text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import * as chai from 'chai'
import * as chaiAsPromised from 'chai-as-promised'
import 'mocha'
import * as sinon from 'sinon'
import {
AccountInfo,
AccountManager,
BeaconErrorType,
BeaconEvent,
BeaconMessageType,
BEACON_VERSION,
BroadcastResponse,
ConnectionContext,
DAppClient,
LocalStorage,
NetworkType,
OperationResponse,
Origin,
PartialTezosOperation,
SigningType,
PermissionResponse,
PermissionScope,
SignPayloadResponse,
StorageKey,
TezosOperationType,
TransportStatus,
PostMessageTransport,
DappPostMessageTransport,
getSenderId,
Transport,
ExtendedP2PPairingRequest
} from '../../src'
import { MockTransport } from '../test-utils/MockTransport'
import { availableTransports } from '../../src/utils/available-transports'
import { ExposedPromise } from '../../src/utils/exposed-promise'
import { Logger } from '../../src/utils/Logger'
import { windowRef } from '../../src/MockWindow'
// use chai-as-promised plugin
chai.use(chaiAsPromised)
const expect = chai.expect
const peer1: ExtendedP2PPairingRequest = {
id: 'id1',
type: 'p2p-pairing-request',
name: 'test',
version: BEACON_VERSION,
publicKey: 'my-public-key',
senderId: 'sender1',
relayServer: 'test-relay.walletbeacon.io'
}
const peer2: ExtendedP2PPairingRequest = {
id: 'id2',
type: 'p2p-pairing-request',
name: 'test',
version: BEACON_VERSION,
publicKey: 'my-public-key-2',
senderId: 'sender2',
relayServer: 'test-relay.walletbeacon.io'
}
const account1: AccountInfo = {
accountIdentifier: 'a1',
senderId: 'sender1',
origin: {
type: Origin.P2P,
id: peer1.publicKey
},
address: 'tz1',
publicKey: 'pubkey1',
network: { type: NetworkType.MAINNET },
scopes: [PermissionScope.SIGN],
connectedAt: new Date().getTime()
}
const account2: AccountInfo = {
accountIdentifier: 'a2',
senderId: 'sender2',
origin: {
type: Origin.P2P,
id: peer1.publicKey
},
address: 'tz2',
publicKey: 'pubkey2',
network: { type: NetworkType.MAINNET },
scopes: [PermissionScope.SIGN],
connectedAt: new Date().getTime()
}
/**
* This mocks the response of PostMessageTransport.isAvailable. Usually it would wait 200ms making the tests slower
*
* @param client DAppClient
*/
const initClientWithMock = async (client: DAppClient) => {
const extensionRef = availableTransports.extension
availableTransports.extension = Promise.resolve(false)
const transport = new MockTransport('TestTransport', undefined as any, undefined as any)
await client.init(transport)
availableTransports.extension = extensionRef
}
describe(`DAppClient`, () => {
before(function () {
/**
* This is used to mock the window object
*
* We cannot do it globally because it fails in the storage tests because of security policies
*/
this.jsdom = require('jsdom-global')('<!doctype html><html><body></body></html>', {
url: 'http://localhost/'
})
})
after(function () {
/**
* Remove jsdom again because it's only needed in this test
*/
this.jsdom()
sinon.restore()
})
beforeEach(() => {
sinon.restore()
;(windowRef as any).beaconCreatedClientInstance = false
})
it(`should throw an error if initialized with an empty object`, async () => {
try {
const dAppClient = new DAppClient({} as any)
expect(dAppClient).to.be.undefined
} catch (e) {
expect(e.message).to.equal('Name not set')
}
})
it(`should initialize without an error`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
expect(dAppClient).to.not.be.undefined
})
it(`should read active account from storage during initialization`, async () => {
const storage = new LocalStorage()
const storageStub = sinon.stub(storage, 'get').resolves()
const message: PermissionResponse = {
appMetadata: {
senderId: 'sender-id',
name: 'test-wallet'
},
id: 'some-id',
version: BEACON_VERSION,
senderId: 'sender-id',
type: BeaconMessageType.PermissionResponse,
publicKey: 'pubkey1',
network: { type: NetworkType.MAINNET },
scopes: []
}
const contextInfo: ConnectionContext = {
origin: Origin.P2P,
id: 'some-context-id'
}
const setActiveAccountStub = sinon.stub(DAppClient.prototype, 'setActiveAccount').resolves()
const dAppClient = new DAppClient({ name: 'Test', storage: storage })
await (<any>dAppClient).handleResponse(message, contextInfo)
expect(storageStub.callCount).to.equal(2)
expect(storageStub.firstCall.args[0]).to.equal(StorageKey.BEACON_SDK_SECRET_SEED)
expect(storageStub.secondCall.args[0]).to.equal(StorageKey.ACTIVE_ACCOUNT)
expect(setActiveAccountStub.callCount).to.equal(1)
expect(setActiveAccountStub.firstCall.args[0]).to.be.undefined
})
it(`should have a beacon ID`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
expect(typeof (await dAppClient.beaconId)).to.equal('string')
})
it(`should connect and be ready`, async () => {
return new Promise(async (resolve, reject) => {
const timeout = global.setTimeout(() => {
reject(new Error('TIMEOUT: Not connected'))
}, 1000)
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const transport = new MockTransport('TestTransport', undefined as any, undefined as any)
await dAppClient.init(transport)
await dAppClient.ready
clearTimeout(timeout)
expect(await dAppClient.connectionStatus).to.equal(TransportStatus.NOT_CONNECTED)
expect(await (dAppClient as any).transport).to.equal(transport)
resolve()
})
})
it(`should reconnect`, async () => {
return new Promise(async (resolve, reject) => {
const timeout = global.setTimeout(() => {
reject(new Error('TIMEOUT: Not connected'))
}, 1000)
const storage = new LocalStorage()
await storage.set(StorageKey.TRANSPORT_POSTMESSAGE_PEERS_DAPP, [
{
id: 'c21fcf96-53d5-c30c-0cf1-7105e046b8ac',
type: 'postmessage-pairing-response',
name: 'Spire',
version: '2',
publicKey: '48d79c808e9c6adcef4343fee74599ac7f3c766be6798143235c8cb939acf19f',
senderId: 'sender1',
extensionId: 'pmaikkbanoioekgijdjfmaifipnbmgmc'
}
] as any)
await storage.set(StorageKey.ACCOUNTS, [account1])
await storage.set(StorageKey.ACTIVE_ACCOUNT, account1.accountIdentifier)
const dAppClient = new DAppClient({ name: 'Test', storage: storage })
await dAppClient.init()
await dAppClient.ready
await storage.delete(StorageKey.TRANSPORT_POSTMESSAGE_PEERS_DAPP)
clearTimeout(timeout)
expect(await dAppClient.connectionStatus).to.equal(TransportStatus.CONNECTED)
resolve()
})
})
it(`should listen for connections on P2P and PostMessage and wait`, async () => {
return new Promise(async (resolve, reject) => {
const timeout = global.setTimeout(() => {
resolve()
}, 100)
sinon.stub(PostMessageTransport, 'getAvailableExtensions').resolves()
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
sinon.stub((<any>dAppClient).events, 'emit').resolves()
await dAppClient.init()
clearTimeout(timeout)
reject(new Error('SHOULD NOT RESOLVE'))
})
})
it(`should listen for connections on P2P and PostMessage`, async () => {
return new Promise(async (resolve, reject) => {
const timeout = global.setTimeout(() => {
reject(new Error('TIMEOUT: Not connected'))
}, 1000)
const postMessageConnectStub = sinon
.stub(DappPostMessageTransport.prototype, 'connect')
.resolves()
const postMessageCallbackStub = sinon
.stub(DappPostMessageTransport.prototype, 'listenForNewPeer')
.callsArgWithAsync(0, peer1)
.resolves()
sinon.stub(PostMessageTransport, 'getAvailableExtensions').resolves()
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const eventsStub = sinon.stub((<any>dAppClient).events, 'emit').resolves()
await dAppClient.init()
clearTimeout(timeout)
expect(postMessageCallbackStub.callCount, 'postMessageCallbackStub').to.equal(1)
expect(eventsStub.callCount, 'eventsStub').to.equal(5)
const events = eventsStub.getCalls().map((call) => (<any>call).firstArg)
expect(events, 'eventsStub').to.include('PAIR_INIT')
expect(postMessageConnectStub.callCount, 'postMessageConnectStub').to.equal(1)
resolve()
})
})
it(`should get active account`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const activeAccount = await dAppClient.getActiveAccount()
expect(activeAccount).to.be.undefined
})
it(`should set active account`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
let activeAccount: AccountInfo | undefined
activeAccount = await dAppClient.getActiveAccount()
expect(activeAccount).to.be.undefined
const account1: AccountInfo = {
accountIdentifier: 'a1',
senderId: 'id1',
origin: {
type: Origin.P2P,
id: 'o1'
},
address: 'tz1',
publicKey: 'pubkey1',
network: { type: NetworkType.MAINNET },
scopes: [PermissionScope.SIGN],
connectedAt: new Date().getTime()
}
const getPeersStub = sinon.stub(DAppClient.prototype, <any>'getPeer').resolves(peer1)
await dAppClient.setActiveAccount(account1)
activeAccount = await dAppClient.getActiveAccount()
expect(activeAccount).to.deep.equal(account1)
await dAppClient.setActiveAccount()
activeAccount = await dAppClient.getActiveAccount()
expect(activeAccount).to.be.undefined
expect(getPeersStub.callCount, 'getPeersStub').to.equal(1)
})
it(`should get app metadata`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const metadata = await dAppClient.getAppMetadata()
expect(metadata).to.deep.equal({
senderId: await getSenderId(await dAppClient.beaconId),
name: dAppClient.name,
icon: dAppClient.iconUrl
})
})
it(`should initialize`, async () => {
return new Promise(async (resolve, reject) => {
const timeout = global.setTimeout(() => {
reject(new Error('TIMEOUT: Not connected'))
}, 1000)
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
await dAppClient.init(new MockTransport('TestTransport', undefined as any, undefined as any))
await dAppClient.ready
clearTimeout(timeout)
expect(await dAppClient.connectionStatus).to.equal(TransportStatus.NOT_CONNECTED)
resolve()
})
})
it(`should remove an account and unset active account`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const getPeersStub = sinon.stub(DAppClient.prototype, <any>'getPeer').resolves(peer1)
await (<any>dAppClient).accountManager.addAccount(account1)
await (<any>dAppClient).accountManager.addAccount(account2)
await dAppClient.setActiveAccount(account1)
expect(await dAppClient.getAccounts()).to.deep.equal([account1, account2])
expect(await dAppClient.getActiveAccount()).to.deep.equal(account1)
await dAppClient.removeAccount(account1.accountIdentifier)
expect(await dAppClient.getAccounts()).to.deep.equal([account2])
expect(await dAppClient.getActiveAccount()).to.be.undefined
expect(getPeersStub.callCount, 'getPeersStub').to.equal(1)
})
it(`should remove an account and not unset active account`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const getPeersStub = sinon.stub(DAppClient.prototype, <any>'getPeer').resolves(peer1)
await (<any>dAppClient).accountManager.addAccount(account1)
await (<any>dAppClient).accountManager.addAccount(account2)
await dAppClient.setActiveAccount(account1)
expect(await dAppClient.getAccounts()).to.deep.equal([account1, account2])
expect(await dAppClient.getActiveAccount()).to.deep.equal(account1)
await dAppClient.removeAccount(account2.accountIdentifier)
expect(await dAppClient.getAccounts()).to.deep.equal([account1])
expect(await dAppClient.getActiveAccount()).to.deep.equal(account1)
expect(getPeersStub.callCount, 'getPeersStub').to.equal(1)
})
it(`should remove all accounts and unset active account`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const getPeersStub = sinon.stub(DAppClient.prototype, <any>'getPeer').resolves(peer1)
await (<any>dAppClient).accountManager.addAccount(account1)
await (<any>dAppClient).accountManager.addAccount(account2)
await dAppClient.setActiveAccount(account1)
expect(await dAppClient.getAccounts()).to.deep.equal([account1, account2])
expect(await dAppClient.getActiveAccount()).to.deep.equal(account1)
await dAppClient.removeAllAccounts()
expect(await dAppClient.getAccounts()).to.deep.equal([])
expect(await dAppClient.getActiveAccount()).to.deep.equal(undefined)
expect(getPeersStub.callCount, 'getPeersStub').to.equal(1)
})
it(`should remove peer and all its accounts`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const transportRemovePeerStub = sinon.stub(Transport.prototype, 'removePeer').resolves()
const removeAccountsForPeersStub = sinon
.stub(dAppClient, <any>'removeAccountsForPeers')
.resolves()
await initClientWithMock(dAppClient)
await dAppClient.removePeer(peer1)
expect(transportRemovePeerStub.callCount).to.equal(1)
expect(transportRemovePeerStub.firstCall.args[0]).to.equal(peer1)
expect(removeAccountsForPeersStub.callCount).to.equal(1)
expect(removeAccountsForPeersStub.firstCall.args[0]).to.deep.equal([peer1])
})
it(`should remove all peers and all their accounts`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const transportGetPeerStub = sinon.stub(Transport.prototype, 'getPeers').resolves([peer1])
const transportRemoveAllPeersStub = sinon.stub(Transport.prototype, 'removeAllPeers').resolves()
const removeAccountsForPeersStub = sinon
.stub(dAppClient, <any>'removeAccountsForPeers')
.resolves()
await initClientWithMock(dAppClient)
await dAppClient.removeAllPeers()
expect(transportGetPeerStub.callCount, 'transportGetPeerStub').to.equal(1)
expect(transportRemoveAllPeersStub.callCount, 'transportRemoveAllPeersStub').to.equal(1)
expect(removeAccountsForPeersStub.callCount, 'removeAccountsForPeersStub').to.equal(1)
expect(
removeAccountsForPeersStub.firstCall.args[0],
'removeAccountsForPeersStub'
).to.deep.equal([peer1])
})
it(`should subscribe to an event`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const eventsStub = sinon.stub((<any>dAppClient).events, 'on').resolves()
const cb = () => {}
dAppClient.subscribeToEvent(BeaconEvent.ACTIVE_ACCOUNT_SET, cb)
expect(eventsStub.callCount).to.equal(1)
expect(eventsStub.firstCall.args[0]).to.equal(BeaconEvent.ACTIVE_ACCOUNT_SET)
expect(eventsStub.firstCall.args[1]).to.equal(cb)
})
it(`should throw an error when checking for permissions and no active account is set`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const eventsStub = sinon.stub((<any>dAppClient).events, 'emit').resolves()
try {
await dAppClient.checkPermissions(BeaconMessageType.OperationRequest)
throw new Error('Should have failed')
} catch (e) {
expect(eventsStub.firstCall.args[0]).to.equal(BeaconEvent.ACTIVE_TRANSPORT_SET) // Called in the constructor
expect(eventsStub.firstCall.args[1]).to.equal(undefined)
expect(eventsStub.secondCall.args[0]).to.equal(BeaconEvent.INTERNAL_ERROR)
expect(eventsStub.secondCall.args[1]).to.deep.equal({ text: 'No active account set!' })
expect(eventsStub.thirdCall.args[0]).to.equal(BeaconEvent.ACTIVE_ACCOUNT_SET) // Called in the constructor
expect(eventsStub.thirdCall.args[1]).to.equal(undefined)
expect(eventsStub.callCount).to.equal(3)
expect(e.message).to.equal('No active account set!')
}
})
it(`should check permissions for a PermissionRequest`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const hasPermission = await dAppClient.checkPermissions(BeaconMessageType.PermissionRequest)
expect(hasPermission).to.be.true
})
it(`should check permissions for an OperationRequest`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const getActiveAccountStub = sinon.stub(dAppClient, 'getActiveAccount')
getActiveAccountStub.resolves({
scopes: [PermissionScope.OPERATION_REQUEST, PermissionScope.SIGN]
} as any)
expect(await dAppClient.checkPermissions(BeaconMessageType.OperationRequest)).to.be.true
getActiveAccountStub.resolves({
scopes: [PermissionScope.SIGN]
} as any)
expect(await dAppClient.checkPermissions(BeaconMessageType.OperationRequest)).to.be.false
})
it(`should check permissions for a SignPayloadRequest`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const getActiveAccountStub = sinon.stub(dAppClient, 'getActiveAccount')
getActiveAccountStub.resolves({
scopes: [PermissionScope.SIGN]
} as any)
expect(await dAppClient.checkPermissions(BeaconMessageType.SignPayloadRequest)).to.be.true
getActiveAccountStub.resolves({
scopes: [PermissionScope.OPERATION_REQUEST]
} as any)
expect(await dAppClient.checkPermissions(BeaconMessageType.SignPayloadRequest)).to.be.false
})
it(`should check permissions for a BroadcastRequest`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const getActiveAccountStub = sinon.stub(dAppClient, 'getActiveAccount')
getActiveAccountStub.resolves({
scopes: []
} as any)
expect(await dAppClient.checkPermissions(BeaconMessageType.BroadcastRequest)).to.be.true
})
it(`should prepare a permission request`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const permissionResponse: PermissionResponse = {
appMetadata: {
senderId: 'sender-id',
name: 'test-wallet'
},
id: 'my-id',
type: BeaconMessageType.PermissionResponse,
version: BEACON_VERSION,
senderId: 'sender-id',
publicKey: '444e1f4ab90c304a5ac003d367747aab63815f583ff2330ce159d12c1ecceba1',
network: { type: NetworkType.MAINNET },
scopes: [PermissionScope.SIGN, PermissionScope.OPERATION_REQUEST]
}
const connectionInfo: ConnectionContext = {
origin: Origin.P2P,
id: '69421294fd0136926639977666e8523550af4c126b6bcd429d3ae555c7aca3a3'
}
const makeRequestStub = sinon
.stub(dAppClient, <any>'makeRequest')
.resolves({ message: permissionResponse, connectionInfo })
const notifySuccessStub = sinon.stub(dAppClient, <any>'notifySuccess').resolves()
const getPeersStub = sinon.stub(Transport.prototype, 'getPeers').resolves([
{
id: '',
name: '',
publicKey: '69421294fd0136926639977666e8523550af4c126b6bcd429d3ae555c7aca3a3',
senderId: 'sender-id',
version: BEACON_VERSION,
type: 'p2p-pairing-request',
relayServer: ''
}
])
const response = await dAppClient.requestPermissions()
expect(getPeersStub.callCount, 'getPeersStub').to.equal(4)
expect(notifySuccessStub.callCount, 'notifySuccessStub').to.equal(1)
expect(makeRequestStub.callCount).to.equal(1)
expect(makeRequestStub.firstCall.args[0]).to.deep.equal({
appMetadata: {
icon: undefined,
name: 'Test',
senderId: await getSenderId(await dAppClient.beaconId)
},
type: BeaconMessageType.PermissionRequest,
network: { type: 'mainnet' },
scopes: ['operation_request', 'sign']
})
delete response.accountInfo
expect(response).to.deep.equal({
appMetadata: {
senderId: 'sender-id',
name: 'test-wallet'
},
id: 'my-id',
type: BeaconMessageType.PermissionResponse,
senderId: 'sender-id',
address: 'tz1d75oB6T4zUMexzkr5WscGktZ1Nss1JrT7',
network: { type: 'mainnet' },
scopes: ['sign', 'operation_request'],
publicKey: '444e1f4ab90c304a5ac003d367747aab63815f583ff2330ce159d12c1ecceba1',
version: '2'
})
})
it(`should prepare a sign payload request (RAW)`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const account: AccountInfo = {
accountIdentifier: 'yQxM85PrJ718CA1N6oz',
senderId: 'sender-id',
origin: {
type: Origin.P2P,
id: '69421294fd0136926639977666e8523550af4c126b6bcd429d3ae555c7aca3a3'
},
address: 'tz1d75oB6T4zUMexzkr5WscGktZ1Nss1JrT7',
publicKey: '444e1f4ab90c304a5ac003d367747aab63815f583ff2330ce159d12c1ecceba1',
network: { type: NetworkType.MAINNET },
scopes: [PermissionScope.SIGN, PermissionScope.OPERATION_REQUEST],
threshold: undefined,
connectedAt: 1599142450653
}
const getPeerStub = sinon.stub(DAppClient.prototype, <any>'getPeer').resolves(peer1)
await (<any>dAppClient).accountManager.addAccount(account)
await dAppClient.setActiveAccount(account)
const signPayloadResponse: SignPayloadResponse = {
id: 'my-id',
type: BeaconMessageType.SignPayloadResponse,
version: BEACON_VERSION,
senderId: 'sender-id',
signingType: SigningType.RAW,
signature: 'my-signature'
}
const connectionInfo: ConnectionContext = {
origin: Origin.P2P,
id: '69421294fd0136926639977666e8523550af4c126b6bcd429d3ae555c7aca3a3'
}
const makeRequestStub = sinon
.stub(dAppClient, <any>'makeRequest')
.resolves({ message: signPayloadResponse, connectionInfo })
const notifySuccessStub = sinon.stub(dAppClient, <any>'notifySuccess').resolves()
const response = await dAppClient.requestSignPayload({ payload: 'test-payload' })
expect(getPeerStub.callCount, 'getPeersStub').to.equal(2)
expect(notifySuccessStub.callCount, 'notifySuccessStub').to.equal(1)
expect(makeRequestStub.callCount).to.equal(1)
expect(makeRequestStub.firstCall.args[0]).to.deep.equal({
type: BeaconMessageType.SignPayloadRequest,
payload: 'test-payload',
signingType: SigningType.RAW,
sourceAddress: 'tz1d75oB6T4zUMexzkr5WscGktZ1Nss1JrT7'
})
const expectedResponse = {
id: 'my-id',
senderId: 'sender-id',
signingType: SigningType.RAW,
signature: 'my-signature',
type: BeaconMessageType.SignPayloadResponse,
version: '2'
}
expect(response).to.deep.equal(expectedResponse)
const responseOperation = await dAppClient.requestSignPayload({
signingType: SigningType.OPERATION,
payload: '03test-payload'
})
expect(responseOperation).to.deep.equal(expectedResponse)
try {
const responseFailure = await dAppClient.requestSignPayload({
signingType: SigningType.OPERATION,
payload: 'test-payload'
})
throw new Error('should not get here' + responseFailure)
} catch (e) {
expect(e.message).to.equal(
`When using signing type "OPERATION", the payload must start with prefix "03"`
)
}
const responseMicheline = await dAppClient.requestSignPayload({
signingType: SigningType.MICHELINE,
payload: '05test-payload'
})
expect(responseMicheline).to.deep.equal(expectedResponse)
try {
const responseFailure = await dAppClient.requestSignPayload({
signingType: SigningType.MICHELINE,
payload: 'test-payload'
})
throw new Error('should not get here' + responseFailure)
} catch (e) {
expect(e.message).to.equal(
`When using signing type "MICHELINE", the payload must start with prefix "05"`
)
}
})
it(`should prepare an operation request`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const account: AccountInfo = {
accountIdentifier: 'yQxM85PrJ718CA1N6oz',
senderId: 'sender-id',
origin: {
type: Origin.P2P,
id: '69421294fd0136926639977666e8523550af4c126b6bcd429d3ae555c7aca3a3'
},
address: 'tz1d75oB6T4zUMexzkr5WscGktZ1Nss1JrT7',
publicKey: '444e1f4ab90c304a5ac003d367747aab63815f583ff2330ce159d12c1ecceba1',
network: { type: NetworkType.MAINNET },
scopes: [PermissionScope.SIGN, PermissionScope.OPERATION_REQUEST],
threshold: undefined,
connectedAt: 1599142450653
}
const getPeerStub = sinon.stub(DAppClient.prototype, <any>'getPeer').resolves(peer1)
await (<any>dAppClient).accountManager.addAccount(account)
await dAppClient.setActiveAccount(account)
const operationResponse: OperationResponse = {
id: 'my-id',
type: BeaconMessageType.OperationResponse,
version: BEACON_VERSION,
senderId: 'sender-id',
transactionHash: 'my-hash'
}
const connectionInfo: ConnectionContext = {
origin: Origin.P2P,
id: '69421294fd0136926639977666e8523550af4c126b6bcd429d3ae555c7aca3a3'
}
const makeRequestStub = sinon
.stub(dAppClient, <any>'makeRequest')
.resolves({ message: operationResponse, connectionInfo })
const notifySuccessStub = sinon.stub(dAppClient, <any>'notifySuccess').resolves()
const operationDetails: PartialTezosOperation[] = [
{
kind: TezosOperationType.TRANSACTION,
amount: '1',
destination: 'tz1d75oB6T4zUMexzkr5WscGktZ1Nss1JrT7'
}
]
const response = await dAppClient.requestOperation({ operationDetails })
expect(getPeerStub.callCount, 'getPeersStub').to.equal(2)
expect(notifySuccessStub.callCount, 'notifySuccessStub').to.equal(1)
expect(makeRequestStub.callCount).to.equal(1)
expect(makeRequestStub.firstCall.args[0]).to.deep.equal({
type: BeaconMessageType.OperationRequest,
network: { type: NetworkType.MAINNET },
operationDetails: operationDetails,
sourceAddress: 'tz1d75oB6T4zUMexzkr5WscGktZ1Nss1JrT7'
})
expect(response).to.deep.equal({
id: 'my-id',
senderId: 'sender-id',
transactionHash: 'my-hash',
type: BeaconMessageType.OperationResponse,
version: '2'
})
})
it(`should prepare a broadcast request`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const account: AccountInfo = {
accountIdentifier: 'yQxM85PrJ718CA1N6oz',
senderId: 'sender-id',
origin: {
type: Origin.P2P,
id: '69421294fd0136926639977666e8523550af4c126b6bcd429d3ae555c7aca3a3'
},
address: 'tz1d75oB6T4zUMexzkr5WscGktZ1Nss1JrT7',
publicKey: '444e1f4ab90c304a5ac003d367747aab63815f583ff2330ce159d12c1ecceba1',
network: { type: NetworkType.MAINNET },
scopes: [PermissionScope.SIGN, PermissionScope.OPERATION_REQUEST],
threshold: undefined,
connectedAt: 1599142450653
}
const getPeerStub = sinon.stub(DAppClient.prototype, <any>'getPeer').resolves(peer1)
await (<any>dAppClient).accountManager.addAccount(account)
await dAppClient.setActiveAccount(account)
const broadcastResponse: BroadcastResponse = {
id: 'my-id',
type: BeaconMessageType.BroadcastResponse,
version: BEACON_VERSION,
senderId: 'sender-id',
transactionHash: 'my-hash'
}
const connectionInfo: ConnectionContext = {
origin: Origin.P2P,
id: '69421294fd0136926639977666e8523550af4c126b6bcd429d3ae555c7aca3a3'
}
const makeRequestStub = sinon
.stub(dAppClient, <any>'makeRequest')
.resolves({ message: broadcastResponse, connectionInfo })
const notifySuccessStub = sinon.stub(dAppClient, <any>'notifySuccess').resolves()
const response = await dAppClient.requestBroadcast({ signedTransaction: 'signed-tx' })
expect(getPeerStub.callCount, 'getPeersStub').to.equal(2)
expect(notifySuccessStub.callCount, 'notifySuccessStub').to.equal(1)
expect(makeRequestStub.callCount).to.equal(1)
expect(makeRequestStub.firstCall.args[0]).to.deep.equal({
type: BeaconMessageType.BroadcastRequest,
network: { type: NetworkType.MAINNET },
signedTransaction: 'signed-tx'
})
expect(response).to.deep.equal({
id: 'my-id',
senderId: 'sender-id',
transactionHash: 'my-hash',
type: BeaconMessageType.BroadcastResponse,
version: '2'
})
})
it(`should send an internal error`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const eventsStub = sinon.stub((<any>dAppClient).events, 'emit').resolves()
try {
await (<any>dAppClient).sendInternalError('some-message')
throw new Error('Should not happen')
} catch (e) {
expect(eventsStub.callCount).to.equal(2)
expect(eventsStub.firstCall.args[0]).to.equal(BeaconEvent.INTERNAL_ERROR)
expect(eventsStub.firstCall.args[1]).to.deep.equal({ text: 'some-message' })
expect(eventsStub.secondCall.args[0]).to.equal(BeaconEvent.ACTIVE_TRANSPORT_SET)
expect(eventsStub.secondCall.args[1]).to.equal(undefined)
expect(e.message).to.equal('some-message')
}
})
it(`should remove all accounts for peers (empty storage)`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const accountManagerGetAccountsSpy = sinon.spy(AccountManager.prototype, 'getAccounts')
const accountManagerRemoveAccountsSpy = sinon.spy(AccountManager.prototype, 'removeAccounts')
await initClientWithMock(dAppClient)
await (<any>dAppClient).removeAccountsForPeers([peer1, peer2])
expect(accountManagerGetAccountsSpy.callCount, 'accountManagerGetAccountsSpy').to.equal(1)
expect(accountManagerRemoveAccountsSpy.callCount, 'accountManagerRemoveAccountsSpy').to.equal(1)
expect(accountManagerRemoveAccountsSpy.firstCall.args[0].length).to.equal(0)
})
it(`should remove all accounts for peers (two accounts for 1 peer)`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const accountManagerGetAccountsStub = sinon
.stub(AccountManager.prototype, 'getAccounts')
.resolves([account1, account2])
const accountManagerRemoveAccountsStub = sinon.stub(AccountManager.prototype, 'removeAccounts')
await initClientWithMock(dAppClient)
await (<any>dAppClient).removeAccountsForPeers([peer1, peer2])
expect(accountManagerGetAccountsStub.callCount, 'accountManagerGetAccountsStub').to.equal(1)
expect(accountManagerRemoveAccountsStub.callCount, 'accountManagerRemoveAccountsStub').to.equal(
1
)
expect(accountManagerRemoveAccountsStub.firstCall.args[0].length).to.equal(2)
expect(accountManagerRemoveAccountsStub.firstCall.args[0][0]).to.equal('a1')
expect(accountManagerRemoveAccountsStub.firstCall.args[0][1]).to.equal('a2')
})
it(`should handle request errors (case: beacon error)`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const eventsStub = sinon.stub((<any>dAppClient).events, 'emit').resolves()
const request = {
type: BeaconMessageType.PermissionRequest
}
const error = {
errorType: BeaconErrorType.NOT_GRANTED_ERROR
}
const walletInfoStub = sinon.stub(dAppClient, <any>'getWalletInfo').resolves({})
;(<any>dAppClient)._activePeer = ExposedPromise.resolve({
id: '',
name: '',
publicKey: '69421294fd0136926639977666e8523550af4c126b6bcd429d3ae555c7aca3a3',
senderId: 'sender-id',
version: BEACON_VERSION,
type: 'p2p-pairing-request',
relayServer: ''
})
try {
await (<any>dAppClient).handleRequestError(request, error)
throw new Error('Should not happen')
} catch (e) {
expect(walletInfoStub.callCount, 'walletInfoStub').to.equal(1)
expect(eventsStub.getCall(0).args[0]).to.equal(BeaconEvent.ACTIVE_TRANSPORT_SET)
expect(eventsStub.getCall(0).args[1]).to.equal(undefined)
expect(eventsStub.getCall(1).args[0]).to.equal(BeaconEvent.ACTIVE_ACCOUNT_SET)
expect(eventsStub.getCall(1).args[1]).to.equal(undefined)
expect(eventsStub.getCall(2).args[0]).to.equal(BeaconEvent.ACTIVE_TRANSPORT_SET)
expect(eventsStub.getCall(2).args[1]).to.equal(undefined)
expect(eventsStub.getCall(3).args[0]).to.equal(BeaconEvent.PERMISSION_REQUEST_ERROR)
expect(eventsStub.getCall(3).args[1]).to.deep.eq({ errorResponse: error, walletInfo: {} })
expect(eventsStub.callCount).to.equal(4)
expect(e.description).to.equal(
'You do not have the necessary permissions to perform this action. Please initiate another permission request and give the necessary permissions.'
)
}
})
it(`should handle request errors (case: not beacon error)`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const eventsStub = sinon.stub((<any>dAppClient).events, 'emit').resolves()
const request = {
type: BeaconMessageType.PermissionRequest
}
const error = {}
try {
await (<any>dAppClient).handleRequestError(request, error)
throw new Error('Should not happen')
} catch (e) {
expect(eventsStub.callCount).to.equal(0)
expect(e).to.equal(error)
}
})
it(`should send notifications on success`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const eventsStub = sinon.stub((<any>dAppClient).events, 'emit').resolves()
const request = { type: BeaconMessageType.PermissionRequest }
const response = {}
await (<any>dAppClient).notifySuccess(request, response)
expect(eventsStub.callCount).to.equal(1)
expect(eventsStub.firstCall.args[0]).to.equal(BeaconEvent.PERMISSION_REQUEST_SUCCESS)
expect(eventsStub.firstCall.args[1]).to.equal(response)
})
it(`should create a request`, async () => {
return new Promise(async (resolve, _reject) => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const sendStub = sinon.stub(Transport.prototype, 'send').resolves()
const getPeerStub = sinon.stub(DAppClient.prototype, <any>'getPeer').resolves(peer1)
await initClientWithMock(dAppClient)
const initStub = sinon.stub(dAppClient, 'init').resolves()
const rateLimitStub = sinon
.stub(dAppClient, 'addRequestAndCheckIfRateLimited')
.resolves(false)
const permissionStub = sinon.stub(dAppClient, 'checkPermissions').resolves(true)
const addRequestStub = sinon.stub(dAppClient, <any>'addOpenRequest').resolves()
const eventsStub = sinon.stub((<any>dAppClient).events, 'emit').resolves()
const input = {
type: BeaconMessageType.PermissionRequest
}
const promise: Promise<any> = (<any>dAppClient).makeRequest(input)
setTimeout(async () => {
expect(getPeerStub.callCount, 'getPeersStub').to.equal(1)
expect(initStub.callCount, 'initStub').to.equal(1)
expect(rateLimitStub.callCount, 'rateLimitStub').to.equal(1)
expect(permissionStub.callCount, 'permissionStub').to.equal(1)
expect(addRequestStub.callCount, 'addRequestStub').to.equal(1)
expect(typeof addRequestStub.firstCall.args[0], 'addRequestStub').to.equal('string')
expect(addRequestStub.firstCall.args[1].isPending(), 'addRequestStub').to.be.true
expect(sendStub.callCount, 'sendStub').to.equal(1)
expect(sendStub.firstCall.args[0].length, 'sendStub').to.be.greaterThan(20)
expect(sendStub.firstCall.args[1], 'sendStub').to.equal(peer1)
expect(eventsStub.callCount, 'eventsStub').to.equal(1)
expect(typeof promise).to.equal('object')
resolve()
})
})
})
it(`should store an open request`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const promise = new ExposedPromise()
await (<any>dAppClient).addOpenRequest('my-id', promise)
expect((<any>dAppClient).openRequests.size).to.equal(1)
expect((<any>dAppClient).openRequests.get('my-id')).to.equal(promise)
})
it(`should store an open request and handle a response`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const promise = new ExposedPromise()
await (<any>dAppClient).addOpenRequest('my-id', promise)
expect((<any>dAppClient).openRequests.size).to.equal(1)
expect((<any>dAppClient).openRequests.get('my-id')).to.equal(promise)
const message = { id: 'my-id' }
const connectionInfo = {}
await (<any>dAppClient).handleResponse(message, connectionInfo)
expect(promise.isResolved()).to.be.true
expect(promise.promiseResult).to.deep.equal({ message, connectionInfo })
expect((<any>dAppClient).openRequests.size).to.equal(0)
})
it(`should store an open request and handle an error response`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const promise = new ExposedPromise()
promise.promise.catch(() => null)
await (<any>dAppClient).addOpenRequest('my-id', promise)
expect((<any>dAppClient).openRequests.size).to.equal(1)
expect((<any>dAppClient).openRequests.get('my-id')).to.equal(promise)
const message = { type: BeaconMessageType.Error, id: 'my-id' }
const connectionInfo = {}
await (<any>dAppClient).handleResponse(message, connectionInfo)
expect(promise.isRejected()).to.be.true
expect(promise.promiseError).to.deep.equal(message)
expect((<any>dAppClient).openRequests.size).to.equal(0)
})
it(`should not handle a response if the id is unknown`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const logStub = sinon.stub(Logger.prototype, 'error').resolves()
const message = { id: 'my-id' }
const connectionInfo = {}
await (<any>dAppClient).handleResponse(message, connectionInfo)
expect(logStub.callCount).to.equal(1)
})
it(`should handle a disconnect message`, async () => {
const dAppClient = new DAppClient({ name: 'Test', storage: new LocalStorage() })
const eventsStub = sinon.stub((<any>dAppClient).events, 'emit').resolves()
const transportRemovePeerStub = sinon.stub(Transport.prototype, 'removePeer').resolves()
const getPeersStub = sinon.stub(Transport.prototype, 'getPeers').resolves([
{
id: '',
name: '',
publicKey: 'sender-id',
senderId: 'sender-id',
version: BEACON_VERSION,
type: 'p2p-pairing-request',
relayServer: ''
}
])
const message = { type: BeaconMessageType.Disconnect, id: 'my-id', senderId: 'sender-id' }
const connectionInfo = {}
await initClientWithMock(dAppClient)
await (<any>dAppClient).handleResponse(message, connectionInfo)
expect(getPeersStub.callCount, 'getPeersStub').to.equal(1)
expect(transportRemovePeerStub.callCount, 'transportRemovePeerStub').to.equal(1)
expect(transportRemovePeerStub.firstCall.args[0]).to.deep.equal({
id: '',
name: '',
publicKey: 'sender-id',
senderId: 'sender-id',
version: BEACON_VERSION,
type: 'p2p-pairing-request',
relayServer: ''
})
expect(eventsStub.callCount, 'eventsStub').to.equal(4)
expect(eventsStub.getCall(0).args[0], '1').to.equal(BeaconEvent.ACTIVE_TRANSPORT_SET)
expect(eventsStub.getCall(1).args[0], '2').to.equal(BeaconEvent.ACTIVE_ACCOUNT_SET)
expect(eventsStub.getCall(2).args[0], '3').to.equal(BeaconEvent.ACTIVE_TRANSPORT_SET)
expect(eventsStub.getCall(3).args[0], '4').to.equal(BeaconEvent.CHANNEL_CLOSED)
})
}) | the_stack |
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { IconLoaderService } from '../../../index';
import { AmexioDropDownComponent } from './dropdown.component';
import { CommonDataService } from '../../services/data/common.data.service';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { DisplayFieldComponent } from '../../base/display-field/display-field.component';
import { CommonIconComponent } from '../../base/components/common.icon.component';
import { DisplayFieldService } from '../../services/data/display.field.service';
import { AmexioButtonComponent } from '../buttons/button.component';
describe('amexio-dropdown', () => {
let comp: AmexioDropDownComponent;
let fixture: ComponentFixture<AmexioDropDownComponent>;
let data: any;
let responsedata: true;
let displayService: DisplayFieldService;
let dataService: CommonDataService;
let _http: HttpClient;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule, HttpClientModule],
declarations: [AmexioButtonComponent,AmexioDropDownComponent, DisplayFieldComponent, CommonIconComponent],
providers: [IconLoaderService, CommonDataService, DisplayFieldService, HttpClient],
});
fixture = TestBed.createComponent(AmexioDropDownComponent);
comp = fixture.componentInstance;
displayService = new DisplayFieldService();
dataService = new CommonDataService(_http)
event = jasmine.createSpyObj('event', ['preventDefault', 'stopPropagation']);
data = [{
index: '12345'
}];
});
// it('set data method', () => {
// let value: any;
// (<any>comp)._data = value;
// (<any>comp)['componentLoaded'] = true;
// expect((<any>comp)).toBeDefined;
// (<any>comp).setData((<any>comp)._data);
// expect((<any>comp)['componentLoaded']).toEqual(true);
// expect((<any>comp).setData()).toHaveBeenCalled;
// });
//check variables
it('check variables in dropdown component ', () => {
expect(comp.selectedindex).toEqual(-1);
expect(comp.multiselectValues).toEqual([]);
expect(comp.maskloader).toEqual(true);
expect(comp.activedescendant).toBe('aria-activedescendant');
expect(comp.key).toBe('index');
expect(comp.displayValue).toBe('');
expect(comp.filteredOptions).toEqual([]);
expect(comp.selectAllFlag).toEqual(false);
});
// it('setUserSelection method', () => {
// });
// it('setData method for datareader not equal to null', () => {
// let responsedata: any;
// let httpResponse: any;
// httpResponse = {
// 'data': [
// {
// 'countryName': 'Myanmar',
// 'countryCode1': 'MM',
// 'countryCode2': 'MMR',
// 'countryFlag': 'MM.png',
// 'capital': '',
// 'currencyCode': 'MMK',
// 'currencyName': 'Kyat',
// 'currencySymbol': 'K',
// 'capitalLatitude': null,
// 'capitalLongitude': null,
// 'isoNumeric': 104
// },
// {
// 'countryName': 'U.S. Virgin Island',
// 'countryCode1': 'VI',
// 'countryCode2': 'VIR',
// 'countryFlag': 'VI.png',
// 'capital': '',
// 'currencyCode': 'USD',
// 'currencyName': 'Dollar',
// 'currencySymbol': '$',
// 'capitalLatitude': null,
// 'capitalLongitude': null,
// 'isoNumeric': 850
// }]
// }
// comp.setData(httpResponse);
// responsedata = httpResponse;
// comp.datareader = 'data';
// expect(comp.datareader).not.toEqual(null);
// comp.multiselectValues = [];
// let dr = comp.datareader.split('.');
// expect(dr).toBeDefined();
// for (const ir of dr) {
// responsedata = responsedata[ir];
// }
// comp.setResponseData(responsedata);
// comp.multiSelection();
// comp.setUserSelection();
// comp.maskloader = false;
// });
it('setData method for datareader equal to null', () => {
let httpResponse: any;
httpResponse =
[
{
'countryName': 'Myanmar',
'countryCode1': 'MM',
'countryCode2': 'MMR',
'countryFlag': 'MM.png',
'capital': '',
'currencyCode': 'MMK',
'currencyName': 'Kyat',
'currencySymbol': 'K',
'capitalLatitude': null,
'capitalLongitude': null,
'isoNumeric': 104
},
{
'countryName': 'U.S. Virgin Island',
'countryCode1': 'VI',
'countryCode2': 'VIR',
'countryFlag': 'VI.png',
'capital': '',
'currencyCode': 'USD',
'currencyName': 'Dollar',
'currencySymbol': '$',
'capitalLatitude': null,
'capitalLongitude': null,
'isoNumeric': 850
}];
comp.datareader = null;
comp.setData(httpResponse);
expect(comp.datareader).toEqual(null);
responsedata = httpResponse;
comp.setResponseData(responsedata);
comp.multiSelection();
comp.setUserSelection();
comp.maskloader = false;
});
// it('setResponseData method', () => {
// let responsedata = {
// 'data': [
// {
// 'countryName': 'Myanmar',
// 'countryCode1': 'MM',
// 'countryCode2': 'MMR',
// 'countryFlag': 'MM.png',
// 'capital': '',
// 'currencyCode': 'MMK',
// 'currencyName': 'Kyat',
// 'currencySymbol': 'K',
// 'isoNumeric': 104
// },
// {
// 'countryName': 'U.S. Virgin Island',
// 'countryCode1': 'VI',
// 'countryCode2': 'VIR',
// 'countryFlag': 'VI.png',
// 'capital': '',
// 'currencyCode': 'USD',
// 'currencyName': 'Dollar',
// 'currencySymbol': '$',
// 'isoNumeric': 850
// }]
// }
// comp.setResponseData(responsedata);
// expect(responsedata).toBeDefined();
// comp.enablesort = true;
// expect(comp.enablesort).toEqual(true);
// comp.sort = 'asc';
// expect(comp.sort.toLowerCase()).toEqual('asc');
// comp.sortDataAscending(responsedata);
// });
// it('setResponseData else block',()=>{
// let responsedata = {
// 'data': [
// {
// 'countryName': 'Myanmar',
// 'countryCode1': 'MM',
// 'countryCode2': 'MMR',
// 'countryFlag': 'MM.png',
// 'capital': '',
// 'currencyCode': 'MMK',
// 'currencyName': 'Kyat',
// 'currencySymbol': 'K',
// 'isoNumeric': 104
// },
// {
// 'countryName': 'U.S. Virgin Island',
// 'countryCode1': 'VI',
// 'countryCode2': 'VIR',
// 'countryFlag': 'VI.png',
// 'capital': '',
// 'currencyCode': 'USD',
// 'currencyName': 'Dollar',
// 'currencySymbol': '$',
// 'isoNumeric': 850
// }]
// }
// comp.setResponseData(responsedata);
// expect(responsedata).toBeDefined();
// comp.enablesort = true;
// expect(comp.enablesort).toEqual(true);
// comp.sort = 'dsc';
// let sort1 = comp.sort;
// expect(sort1.toLowerCase()).toEqual('dsc');
// comp.sortDataDescending(responsedata);
// });
// it('setResponseData else block2',()=>{
// let responsedata = {
// 'data': [
// {
// 'countryName': 'Myanmar',
// 'countryCode1': 'MM',
// 'countryCode2': 'MMR',
// 'countryFlag': 'MM.png',
// 'capital': '',
// 'currencyCode': 'MMK',
// 'currencyName': 'Kyat',
// 'currencySymbol': 'K',
// 'isoNumeric': 104
// },
// {
// 'countryName': 'U.S. Virgin Island',
// 'countryCode1': 'VI',
// 'countryCode2': 'VIR',
// 'countryFlag': 'VI.png',
// 'capital': '',
// 'currencyCode': 'USD',
// 'currencyName': 'Dollar',
// 'currencySymbol': '$',
// 'isoNumeric': 850
// }]
// }
// comp.setResponseData(responsedata);
// expect(responsedata).toBeDefined();
// comp.enablesort = false;
// expect(comp.enablesort).toEqual(false);
// comp.viewData = responsedata;
// comp.filteredOptions = comp.viewData;
// comp.generateIndex(responsedata.data);
// })
it('sortDataAscending', () => {
let data2 = {
'data': [
{
'countryName': 'Myanmar',
'countryCode1': 'MM',
'countryCode2': 'MMR',
'countryFlag': 'MM.png',
'capital': '',
'currencyCode': 'MMK',
'currencyName': 'Kyat',
'currencySymbol': 'K',
'isoNumeric': 104
},
{
'countryName': 'U.S. Virgin Island',
'countryCode1': 'VI',
'countryCode2': 'VIR',
'countryFlag': 'VI.png',
'capital': '',
'currencyCode': 'USD',
'currencyName': 'Dollar',
'currencySymbol': '$',
'isoNumeric': 850
}]
}
comp.sortDataAscending(data);
comp.displayfield = 'countryName';
comp.viewData = data2.data.sort((a: any, b: any) => displayService.findValue(comp.displayfield, a).toLowerCase()
!== displayService.findValue(comp.displayfield, b).toLowerCase() ?
displayService.findValue(comp.displayfield, a).toLowerCase() <
displayService.findValue(comp.displayfield, b).toLowerCase() ? -1 : 1 : 0);
comp.filteredOptions = comp.viewData;
comp.generateIndex(comp.filteredOptions);
});
it('sortDataDescending', () => {
let data3 = [
{
'countryName': 'Myanmar',
'countryCode1': 'MM',
'countryCode2': 'MMR',
'countryFlag': 'MM.png',
'capital': '',
'currencyCode': 'MMK',
'currencyName': 'Kyat',
'currencySymbol': 'K',
'isoNumeric': 104
},
{
'countryName': 'U.S. Virgin Island',
'countryCode1': 'VI',
'countryCode2': 'VIR',
'countryFlag': 'VI.png',
'capital': '',
'currencyCode': 'USD',
'currencyName': 'Dollar',
'currencySymbol': '$',
'isoNumeric': 850
}]
comp.sortDataDescending(data);
comp.displayfield = 'countryName';
comp.viewData = data.sort((a: any, b: any) => displayService.findValue(comp.displayfield, a).toLowerCase()
!== displayService.findValue(comp.displayfield, b).toLowerCase() ?
displayService.findValue(comp.displayfield, a).toLowerCase() >
displayService.findValue(comp.displayfield, b).toLowerCase() ? -1 : 1 : 0);
comp.filteredOptions = comp.viewData;
comp.generateIndex(comp.filteredOptions);
})
it('generateIndex Method ', () => {
let data = [
{
'countryName': 'Myanmar',
'countryCode1': 'MM',
'countryCode2': 'MMR',
'countryFlag': 'MM.png',
'capital': '',
'currencyCode': 'MMK',
'currencyName': 'Kyat',
'currencySymbol': 'K',
'isoNumeric': 104
},
{
'countryName': 'U.S. Virgin Island',
'countryCode1': 'VI',
'countryCode2': 'VIR',
'countryFlag': 'VI.png',
'capital': '',
'currencyCode': 'USD',
'currencyName': 'Dollar',
'currencySymbol': '$',
'isoNumeric': 850
}]
comp.generateIndex(data);
comp.componentId = 'dropdown_countryName_1448';
data.forEach((element: any, index: number) => {
element['index'] = comp.componentId + 'listitem' + index;
});
});
it('setMultiSelect', () => {
comp.setMultiSelect();
comp.multiselectValues = [{
fruitName: 'Apple', code: 'Apple', checked: true, index: 'dropdown_fruitName_1912listitem0'
}, {
fruitName: 'Apple1', code: 'Apple1', checked: true, index: 'dropdown_fruitName_1912listitem1'
}]
comp.setMultiSelectData();
comp.displayfield = 'fruitName';
let multiselectDisplayString: any = '';
comp.multiselectValues.forEach((row: any) => {
multiselectDisplayString === '' ? multiselectDisplayString +=
displayService.findValue(comp.displayfield, row) : multiselectDisplayString += ', '
+ displayService.findValue(comp.displayfield, row);
});
expect(2).toBeGreaterThan(0);
return multiselectDisplayString;
})
it('setMultiSelectData method', () => {
comp.setMultiSelectData();
comp.multiselectValues = [];
comp.innerValue = ['Apple'];
comp.filteredOptions = [{ fruitName: 'Apple', code: 'Apple', checked: false, index: 'dropdown_fruitName_1977listitem0' }];
expect(comp.innerValue).toBeDefined()
expect(comp.innerValue.length).toBeGreaterThan(0);
const modelValue = comp.innerValue;
comp.valuefield = 'code';
comp.filteredOptions.forEach((test) => {
modelValue.forEach((mdValue: any) => {
expect(test[comp.valuefield]).toEqual(mdValue);
expect(test.hasOwnProperty('checked')).toEqual(true);
test.checked = true;
comp.multiselectValues.push(test);
})
})
});
it('multiSelection', () => {
comp.multiSelection();
comp.multiselect = true;
comp.viewData = [{ fruitName: 'Apple', code: 'Apple', checked: true, index: 'dropdown_fruitName_1953listitem0' },
{ fruitName: 'Avacado', code: 'Avacado', checked: true, index: 'dropdown_fruitName_1953listitem1' },
{ fruitName: 'Banana', code: 'Banana', checked: true, index: 'dropdown_fruitName_1953listitem2' }]
expect(comp.multiselect).toEqual(true)
expect(comp.viewData).toBeDefined();
let preSelectedMultiValues = '';
const optionsChecked: any = [];
comp.displayfield = 'fruitName'
comp.viewData.forEach((row: any) => {
expect(row.hasOwnProperty('checked')).toEqual(true);
expect(row.checked).toEqual(true)
optionsChecked.push(row[comp.valuefield]);
comp.multiselectValues.push(row);
preSelectedMultiValues === '' ? preSelectedMultiValues +=
displayService.findValue(comp.displayfield, row) : preSelectedMultiValues += ', ' +
displayService.findValue(comp.displayfield, row);
// expect(row.checked).toEqual(false)
row['checked'] = false;
});
})
it('multiSelection for else', () => {
comp.multiselect = true;
comp.viewData = [{ fruitName: 'Apple', code: 'Apple', index: 'dropdown_fruitName_1953listitem0' },
{ fruitName: 'Avacado', code: 'Avacado', index: 'dropdown_fruitName_1953listitem1' },
{ fruitName: 'Banana', code: 'Banana', index: 'dropdown_fruitName_1953listitem2' }]
expect(comp.multiselect).toEqual(true)
expect(comp.viewData).toBeDefined();
comp.displayfield = 'fruitName'
comp.viewData.forEach((row: any) => {
expect(row.hasOwnProperty('checked')).toEqual(false);
row['checked'] = false;
});
})
it('should call get function and return true', () => {
expect(comp.data).toBe(undefined);
let item = comp.value;
comp._data = item;
expect(comp.componentLoaded).toBe(undefined);
});
it('onChange() method check', () => {
let value = 'kedar';
comp.onChange(value);
expect(comp.innerValue).toBe(value);
comp.isValid = true;
expect(comp.isValid).toBe(true);
comp.isComponentValid.subscribe((g: any) => {
expect(comp.isComponentValid).toEqual(g);
});
});
// closeOnEScape
it('closeOnEScape() method check', () => {
let ev = event
comp.closeOnEScape(ev);
comp.showToolTip = false;
expect(comp.showToolTip).toEqual(false);
});
// onInput mehtod
// it('onInput() method check', () => {
// let value = comp.input;
// comp.onInput(value);
// comp.input.subscribe((g: any) => {
// expect(comp.input).toEqual(g);
// });
// comp.onInput(value);
// expect(comp.isValid).toBe(value.vaild);
// comp.isComponentValid.emit(value.valid);
// });
// ngOnInit mehtod
it('ngOnInit() method check', () => {
comp.name = comp.generateName(comp.name, comp.fieldlabel, 'dropdowninput');
comp.componentId = comp.createCompId('dropdown', comp.displayfield);
comp.isValid = comp.allowblank;
comp.isComponentValid.emit(comp.allowblank);
// comp.httpmethod = 'get';
// comp.httpurl = 'https/rgh'
// expect(comp.httpmethod).toBeDefined();
// expect(comp.httpurl).toBeDefined();
// dataService.fetchData(comp.httpurl, comp.httpmethod).subscribe((response) => {
// comp.responseData = response;
// });
let value = comp.name;
comp.ngOnInit();
expect(comp.name).toEqual(value);
// comp.input.subscribe((g: any) => {
// expect(comp.input).toEqual(g);
// });
// comp.onIngOnInitnput(value);
// expect(comp.isValid).toBe(value.vaild);
});
//setUserSelection check
it('check setUserSelection method', () => {
comp.key = 'index';
comp.valuefield = 'countryCode1';
comp.displayfield = 'countryName';
comp.innerValue = 'AF';
comp.viewData = [{ countryName: 'Afghanistan', countryCode1: 'AF', countryCode2: 'AFG', countryFlag: 'AF.png' }]
comp.setUserSelection();
expect(comp.innerValue).not.toBe(null);
const valueKey = comp.valuefield;
const displayKey = comp.displayfield;
const val = comp.innerValue;
expect(comp.viewData.length).toBeGreaterThan(0);
comp.viewData.forEach((item: any) => {
expect(item[valueKey]).toEqual(val);
comp.isValid = true;
comp.isComponentValid.emit(true);
comp.displayValue = item[displayKey];
delete item[comp.key];
comp.onSingleSelect.emit(item);
})
})
it('check setUserSelection method else condition', () => {
comp.key = 'index';
comp.valuefield = 'countryCode1';
comp.displayfield = 'countryName';
comp.innerValue = null;
comp.viewData = [{ countryName: 'Afghanistan', countryCode1: 'AF', countryCode2: 'AFG', countryFlag: 'AF.png' }]
comp.setUserSelection();
expect(comp.innerValue).toBe(null);
})
//on onBlur()
it('on onBlur() if condition', () => {
let fn = event;
comp.onblur(fn);
comp.showToolTip = true;
expect(comp.showToolTip).toEqual(true);
comp.showToolTip = !comp.showToolTip;
// expect(comp.tabFocus).toEqual(false);
comp.onTouchedCallback();
expect(comp.onTouchedCallback()).toHaveBeenCalled;
comp.onBlur.subscribe((g: any) => {
expect(comp.onBlur).toEqual(g);
});
});
it('on onBlur() else conditon', () => {
let fn = event;
comp.onblur(fn);
comp.showToolTip = false;
expect(comp.showToolTip).toEqual(false);
// expect(comp.tabFocus).toEqual(false);
comp.onTouchedCallback();
expect(comp.onTouchedCallback()).toHaveBeenCalled;
comp.onBlur.subscribe((g: any) => {
expect(comp.onBlur).toEqual(g);
});
});
// registerOnChange method
it('registerOnChange()', () => {
let fn;
comp.registerOnChange(fn);
comp['onChangeCallback'] = fn;
expect(comp['onChangeCallback']).toEqual(fn);
});
//onDropDownClick method
it('onDropDownClick()', () => {
let fn = event;
comp.showToolTip = true;
comp.multiselect = false;
comp.onDropDownClick(fn);
expect(comp.onBaseFocusEvent).toHaveBeenCalled;
expect(comp.showToolTip).toEqual(true);
comp.onClick.subscribe((g: any) => {
expect(comp.onClick).toEqual(g);
});
comp.selectedindex = 2;
expect(comp.multiselect).toBe(false);
expect(comp.selectedindex).toBeGreaterThan(-1);
// let ok = comp.filteredOptions[comp.selectedindex];
// ok.selected = false;
// comp.filteredOptions[comp.selectedindex].selected = false;
// expect(ok.selected).toBe(false);
// comp.selectedindex = -1;
// expect(comp.selectedindex).toBe(-1);
});
//registerOnTouched method
it('registerOnTouched()', () => {
let fn;
comp.registerOnTouched(fn);
comp['onTouchedCallback'] = fn;
expect(comp['onTouchedCallback']).toEqual(fn);
});
//on onFocus()
// it('on onFocus()', () => {
// let item = event;
// comp.showToolTip = true;
// comp.onFocus(item);
// expect(comp.showToolTip).toEqual(true);
// // comp.posixUp = comp.getListPosition(item);
// // comp.focus.emit();
// });
//on onIconClick()
it('on onIconClick()', () => {
let item = event;
comp.disabled = true;
comp.dropdownstyle.visibility = 'hidden';
comp.onIconClick();
expect(comp.dropdownstyle.visibility).toEqual('hidden');
comp.showToolTip = false;
expect(comp.disabled).toEqual(true);
comp.showToolTip = !comp.showToolTip;
});
it('on onIconClick() nestesd if condition', () => {
comp.disabled = false;
comp.onIconClick();
comp.dropdownstyle.visibility = 'hidden';
expect(comp.dropdownstyle.visibility).toEqual('hidden');
comp.showToolTip = false;
expect(comp.disabled).toBe(false);
expect(comp.showToolTip).toEqual(false);
expect(comp.onBaseFocusEvent({})).toHaveBeenCalled;
comp.showToolTip = !comp.showToolTip;
});
it('on onIconClick() hidden false else condition', () => {
comp.onIconClick();
comp.dropdownstyle.visibility = 'visible';
expect(comp.dropdownstyle.visibility).not.toEqual('hidden');
});
it('on onIconClick() hidden true else condition', () => {
comp.onIconClick();
comp.dropdownstyle.visibility = 'hidden';
expect(comp.dropdownstyle.visibility).toEqual('hidden');
comp.showToolTip = false;
});
it('on onIconClick() showToolTip not undefined condition', () => {
comp.disabled = false;
comp.onIconClick();
comp.showToolTip = true;
comp.dropdownstyle.visibility = 'visible';
expect(comp.dropdownstyle.visibility).not.toEqual('hidden');
expect(comp.disabled).toEqual(false);
expect(comp.showToolTip).toEqual(true);
expect(comp.onBaseBlurEvent({})).toHaveBeenCalled;
comp.showToolTip = !comp.showToolTip;
});
it('on onIconClick()showToolTip false condition', () => {
comp.disabled = false;
comp.onIconClick();
comp.showToolTip = false;
expect(comp.disabled).toBe(false);
expect(comp.showToolTip).toEqual(false);
expect(comp.onBaseFocusEvent({})).toHaveBeenCalled;
comp.showToolTip = !comp.showToolTip;
});
it('on onIconClick() showtooltip undefined condition', () => {
comp.disabled = false;
comp.onIconClick();
comp.showToolTip = undefined;
expect(comp.disabled).toBe(false);
expect(comp.showToolTip).toEqual(undefined);
expect(comp.onBaseFocusEvent({})).toHaveBeenCalled;
comp.showToolTip = !comp.showToolTip;
});
//writeChangedValue ()
it('on writeChangedValue()', () => {
comp.value = 'kedar';
let item = comp.value;
comp.innerValue = 'kokil';
let status = false;
comp.writeChangedValue(item);
expect(comp.innerValue).not.toBe('kokil');
expect(status).toEqual(false);
status = true;
comp.displayValue = '';
comp.writeChangedValue(item);
expect(comp.displayValue).toBe('');
expect(comp.value).toEqual(item);
//expect(comp.showToolTip).toEqual(true);
// comp.posixUp = comp.getListPosition(item);
// comp.focus.emit();
});
//writeValue ()
it('on writeValue()', () => {
comp.value = 'kedar';
let item = comp.value;
comp.writeValue(item);
expect(comp.value).not.toBe(null);
expect(comp.writeChangedValue(item)).toHaveBeenCalled;
let ok = null;
comp.value = '';
comp.writeValue(ok);
expect(comp.value).toBe('');
comp.innerValue = null;
expect(comp.innerValue).toBe(null);
comp.allowblank = true;
comp.isValid = true;
expect(comp.isValid).toEqual(true);
expect(comp.showToolTip).toEqual(undefined);
// comp.posixUp = comp.getListPosition(item);
// comp.focus.emit();
});
//on onItemSelect()
// it('on onItemSelect()', () => {
// let item = event;
// comp.showToolTip = false;
// comp.onItemSelect(item);
// comp.hide();
// expect(comp.showToolTip).toEqual(false);
// comp.posixUp = comp.getListPosition(item);
// comp.focus.emit();
// });
//wrking 1- set errormsg
it('set errormsg', () => {
comp.errormsg = 'data incorect';
expect(comp.helpInfoMsg).toEqual('data incorect<br/>');
});
it('get errormsg', () => {
expect(comp.errormsg).toEqual(comp._errormsg);
});
it('multiselectionData', () => {
comp.setMultiSelectData();
comp.multiselectValues = [];
comp.valuefield = 'code';
comp.innerValue = ['apple'];
comp.filteredOptions = [{
checked: true, code: 'apple', fruitName: 'apple',
index: 'dropdown_fruitName_1169listitem0', selected: false
}
];
expect(comp.innerValue).toBeDefined();
expect(comp.innerValue.length).toBeGreaterThan(0);
const modelValue = comp.innerValue;
comp.filteredOptions.forEach((test) => {
modelValue.forEach((mdValue: any) => {
expect(test[comp.valuefield]).toEqual(mdValue);
expect(test.hasOwnProperty('checked')).toEqual(true);
test.checked = true;
comp.multiselectValues.push(test);
});
});
});
it('set onDropDownSearchKeyUp check ', () => {
let event = {
'code': 'Backspace',
'composed': true,
'ctrlKey': false,
'isTrusted': true,
'defaultPrevented': false,
'detail': 0,
'eventPhase': 0,
'isComposing': false,
'key': 'Backspace',
'keyCode': 8,
'location': 0,
'metaKey': false,
'target': {
'value': 'American Samo'
}
}
comp.onDropDownSearchKeyUp(event);
expect(event.keyCode).toEqual(8);
comp.innerValue = '';
comp.displayValue = event.target.value;
});
}); | the_stack |
import {
GraphQLID,
GraphQLNonNull,
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
parse,
} from "graphql";
import { InMemoryLiveQueryStore } from "./InMemoryLiveQueryStore";
const isAsyncIterable = (value: unknown): value is AsyncIterable<unknown> => {
return (
typeof value === "object" && value !== null && Symbol.asyncIterator in value
);
};
function assertAsyncIterable(
value: unknown
): asserts value is AsyncIterableIterator<any> {
if (isAsyncIterable(value)) {
return;
}
throw new Error(`result should be an AsyncIterable. Got ${typeof value}.`);
}
function assertNoAsyncIterable(value: unknown) {
if (isAsyncIterable(value)) {
throw new Error(
`result should NOT be an AsyncIterable. Got ${typeof value}.`
);
}
}
const runAllPendingStuff = () => new Promise((res) => setImmediate(res));
const getAllValues = async <T>(values: AsyncIterableIterator<T>) => {
const results: T[] = [];
for await (const value of values) {
results.push(value);
}
return results;
};
const createTestSchema = (
mutableSource: {
query?: string;
mutation?: string;
post?: {
id: string;
title: string;
};
} = {
query: "queried",
mutation: "mutated",
post: {
id: "1",
title: "lel",
},
}
) => {
const GraphQLPostType = new GraphQLObjectType({
name: "Post",
fields: {
id: {
type: GraphQLNonNull(GraphQLID),
},
title: {
type: GraphQLString,
},
},
});
const Query = new GraphQLObjectType({
name: "Query",
fields: {
foo: {
type: GraphQLString,
resolve: () => mutableSource.query,
},
post: {
type: GraphQLPostType,
args: {
id: {
type: GraphQLID,
},
},
resolve: () => mutableSource.post,
},
},
});
const Mutation = new GraphQLObjectType({
name: "Mutation",
fields: {
foo: {
type: GraphQLString,
resolve: () => mutableSource.mutation,
},
},
});
return new GraphQLSchema({ query: Query, mutation: Mutation });
};
const tock = (() => {
let spy: jest.SpyInstance<number, []> = jest.fn();
let mockedTime = 0;
return {
useFakeTime(time = 0) {
mockedTime = time;
spy.mockRestore();
spy = jest.spyOn(Date, "now").mockReturnValue(mockedTime);
jest.useFakeTimers("legacy");
},
advanceTime(time = 0) {
mockedTime = mockedTime + time;
spy.mockReturnValue(mockedTime);
jest.advanceTimersByTime(time);
},
useRealTime() {
spy.mockRestore();
jest.useRealTimers();
},
};
})();
afterEach(tock.useRealTime);
describe("conformance with default `graphql-js` exports", () => {
// The tests ins here a snapshot tests to ensure consistent behavior with the default GraphQL functions
// that are used inside InMemoryLiveQueryStore.execute
test("returns a sync query result in case no query operation with @live is provided", () => {
const store = new InMemoryLiveQueryStore();
const schema = createTestSchema();
const document = parse(/* GraphQL */ `
query {
foo
}
`);
const result = store.execute({
document,
schema,
});
expect(result).toEqual({
data: {
foo: "queried",
},
});
});
test("returns a sync mutation result", () => {
const store = new InMemoryLiveQueryStore();
const schema = createTestSchema();
const document = parse(/* GraphQL */ `
mutation {
foo
}
`);
const result = store.execute({
document,
schema,
});
expect(result).toEqual({
data: {
foo: "mutated",
},
});
});
test("returns an error in case a document without an operation is provided", () => {
const store = new InMemoryLiveQueryStore();
const schema = createTestSchema();
const document = parse(/* GraphQL */ `
fragment FooFragment on Query {
foo
}
`);
const result = store.execute({
document,
schema,
});
// stay conform with original execute behavior
expect(result).toMatchInlineSnapshot(`
Object {
"errors": Array [
[GraphQLError: Must provide an operation.],
],
}
`);
});
test("returns an error in case multiple operations but no matching operationName is provided.", () => {
const store = new InMemoryLiveQueryStore();
const schema = createTestSchema();
const document = parse(/* GraphQL */ `
query a {
foo
}
query b {
foo
}
`);
const result = store.execute({
document,
schema,
});
// stay conform with original execute behavior
expect(result).toMatchInlineSnapshot(`
Object {
"errors": Array [
[GraphQLError: Must provide operation name if query contains multiple operations.],
],
}
`);
});
});
it("returns a AsyncIterable that publishes a query result.", async () => {
const schema = createTestSchema();
const store = new InMemoryLiveQueryStore();
const document = parse(/* GraphQL */ `
query @live {
foo
}
`);
const executionResult = store.execute({
schema,
document,
});
assertAsyncIterable(executionResult);
const result = await executionResult.next();
expect(result).toEqual({
done: false,
value: {
data: {
foo: "queried",
},
isLive: true,
},
});
executionResult.return?.();
});
it("returns a AsyncIterable that publishes a query result after the schema coordinate was invalidated.", async () => {
const mutableSource = { query: "queried", mutation: "mutated" };
const schema = createTestSchema(mutableSource);
const store = new InMemoryLiveQueryStore();
const document = parse(/* GraphQL */ `
query @live {
foo
}
`);
const executionResult = store.execute({
schema,
document,
});
assertAsyncIterable(executionResult);
let result = await executionResult.next();
expect(result).toEqual({
done: false,
value: {
data: {
foo: "queried",
},
isLive: true,
},
});
mutableSource.query = "changed";
store.invalidate("Query.foo");
result = await executionResult.next();
expect(result).toEqual({
done: false,
value: {
data: {
foo: "changed",
},
isLive: true,
},
});
executionResult.return?.();
});
it("returns a AsyncIterable that publishes a query result after the resource identifier was invalidated.", async () => {
const schema = createTestSchema();
const store = new InMemoryLiveQueryStore();
const document = parse(/* GraphQL */ `
query @live {
post {
id
title
}
}
`);
const executionResult = store.execute({
schema,
document,
});
assertAsyncIterable(executionResult);
let result = await executionResult.next();
expect(result).toEqual({
done: false,
value: {
data: {
post: {
id: "1",
title: "lel",
},
},
isLive: true,
},
});
store.invalidate("Post:1");
result = await executionResult.next();
expect(result).toEqual({
done: false,
value: {
data: {
post: {
id: "1",
title: "lel",
},
},
isLive: true,
},
});
executionResult.return?.();
});
it("does not publish when a old resource identifier is invalidated", async () => {
const mutableSource = {
post: {
id: "1",
title: "lel",
},
};
const schema = createTestSchema(mutableSource);
const store = new InMemoryLiveQueryStore();
const document = parse(/* GraphQL */ `
query @live {
post {
id
title
}
}
`);
const executionResult = store.execute({
schema,
document,
});
assertAsyncIterable(executionResult);
let result = await executionResult.next();
expect(result).toEqual({
done: false,
value: {
data: {
post: {
id: "1",
title: "lel",
},
},
isLive: true,
},
});
mutableSource.post.id = "2";
store.invalidate("Post:1");
result = await executionResult.next();
expect(result).toEqual({
done: false,
value: {
data: {
post: {
id: "2",
title: "lel",
},
},
isLive: true,
},
});
store.invalidate("Post:1");
const nextResult = executionResult.next();
executionResult.return?.();
result = await nextResult;
expect(result).toMatchInlineSnapshot(`
Object {
"done": true,
"value": undefined,
}
`);
});
it("can be executed with polymorphic parameter type", () => {
const mutableSource = { query: "queried", mutation: "mutated" };
const schema = createTestSchema(mutableSource);
const store = new InMemoryLiveQueryStore();
const document = parse(/* GraphQL */ `
query {
foo
}
`);
const executionResult = store.execute(schema, document);
expect(executionResult).toEqual({
data: {
foo: "queried",
},
});
});
it("can handle missing NoLiveMixedWithDeferStreamRule", async () => {
const schema = createTestSchema();
const store = new InMemoryLiveQueryStore();
const document = parse(/* GraphQL */ `
query @live {
... on Query @defer(label: "kek") {
foo
}
}
`);
const executionResult = await store.execute(schema, document);
if (isAsyncIterable(executionResult)) {
const result = await executionResult.next();
expect(result).toMatchInlineSnapshot(`
Object {
"done": false,
"value": Object {
"errors": Array [
[GraphQLError: "execute" returned a AsyncIterator instead of a MaybePromise<ExecutionResult>. The "NoLiveMixedWithDeferStreamRule" rule might have been skipped.],
],
},
}
`);
return;
}
fail("Should return AsyncIterable");
});
it("can collect additional resource identifiers with 'extensions.liveQuery.collectResourceIdentifiers'", async () => {
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: "Query",
fields: {
ping: {
type: GraphQLString,
args: {
id: {
type: GraphQLNonNull(GraphQLString),
},
},
extensions: {
liveQuery: {
collectResourceIdentifiers: (_: unknown, args: { id: string }) =>
args.id,
},
},
},
},
}),
});
const document = parse(/* GraphQL */ `
query @live {
ping(id: "1")
}
`);
const store = new InMemoryLiveQueryStore();
const executionResult = await store.execute(schema, document);
if (!isAsyncIterable(executionResult)) {
fail("should return AsyncIterable");
}
store.invalidate("1");
process.nextTick(() => {
executionResult.return?.();
});
const values = await getAllValues(executionResult);
expect(values).toHaveLength(2);
});
it("adds the resource identifiers as a extension field.", async () => {
const schema = createTestSchema();
const store = new InMemoryLiveQueryStore({
includeIdentifierExtension: true,
});
const document = parse(/* GraphQL */ `
query ($id: ID!) @live {
post(id: $id) {
id
title
}
}
`);
const executionResult = store.execute({
schema,
document,
variableValues: {
id: "1",
},
});
assertAsyncIterable(executionResult);
let result = await executionResult.next();
expect(result).toMatchInlineSnapshot(`
Object {
"done": false,
"value": Object {
"data": Object {
"post": Object {
"id": "1",
"title": "lel",
},
},
"extensions": Object {
"liveResourceIdentifier": Array [
"Query.post",
"Query.post(id:\\"1\\")",
"Post:1",
],
},
"isLive": true,
},
}
`);
await executionResult.return?.();
});
it("can set the id field name arbitrarily", async () => {
const arbitraryIdName = "whateverIWant";
const GraphQLPostType = new GraphQLObjectType({
name: "Post",
fields: {
[arbitraryIdName]: {
type: GraphQLNonNull(GraphQLID),
},
title: {
type: GraphQLString,
},
},
});
const Query = new GraphQLObjectType({
name: "Query",
fields: {
post: {
type: GraphQLPostType,
args: {
id: {
type: GraphQLID,
},
},
resolve: () => ({
[arbitraryIdName]: "1",
title: "lel",
}),
},
},
});
const schema = new GraphQLSchema({ query: Query });
const store = new InMemoryLiveQueryStore({
includeIdentifierExtension: true,
idFieldName: arbitraryIdName,
});
const document = parse(/* GraphQL */ `
query($id: ID!) @live {
post(id: $id) {
${arbitraryIdName}
title
}
}
`);
const executionResult = store.execute({
schema,
document,
variableValues: {
id: "1",
},
});
assertAsyncIterable(executionResult);
let result = await executionResult.next();
expect(result.value.extensions.liveResourceIdentifier).toEqual([
"Query.post",
'Query.post(id:"1")',
"Post:1",
]);
});
it("can throttle and prevent multiple publishes", async () => {
tock.useFakeTime(Date.now());
const schema = createTestSchema();
const document = parse(/* GraphQL */ `
query foo @live(throttle: 100) {
foo
}
`);
const store = new InMemoryLiveQueryStore();
const executionResult = store.execute({
schema,
document,
});
assertAsyncIterable(executionResult);
const values: Array<unknown> = [];
const done = (async function run() {
for await (const value of executionResult) {
values.push(value);
}
})();
// trigger multiple invalidations
store.invalidate("Query.foo");
store.invalidate("Query.foo");
store.invalidate("Query.foo");
await runAllPendingStuff();
// only one value should be published
expect(values).toHaveLength(1);
executionResult.return!();
await done;
});
it("can throttle and publish new values after the throttle interval", async () => {
tock.useFakeTime(Date.now());
const schema = createTestSchema();
const document = parse(/* GraphQL */ `
query foo @live(throttle: 100) {
foo
}
`);
const store = new InMemoryLiveQueryStore();
const executionResult = store.execute({
schema,
document,
});
assertAsyncIterable(executionResult);
const values: Array<unknown> = [];
const done = (async function run() {
for await (const value of executionResult) {
values.push(value);
}
})();
store.invalidate("Query.foo");
await runAllPendingStuff();
expect(values).toHaveLength(1);
tock.advanceTime(100);
await runAllPendingStuff();
expect(values).toHaveLength(2);
executionResult.return!();
await done;
});
it("can prevent execution by returning a string from validateThrottle", async () => {
const schema = createTestSchema();
const document = parse(/* GraphQL */ `
query foo($throttle: Int) @live(throttle: $throttle) {
foo
}
`);
const store = new InMemoryLiveQueryStore({
validateThrottleValue: (value) => {
return value === 100 ? "Noop" : null;
},
});
let executionResult = store.execute({
schema,
document,
variableValues: {
throttle: 99,
},
});
assertAsyncIterable(executionResult);
executionResult = store.execute({
schema,
document,
variableValues: {
throttle: 100,
},
});
assertNoAsyncIterable(executionResult);
expect(executionResult).toMatchInlineSnapshot(`
Object {
"errors": Array [
[GraphQLError: Noop],
],
}
`);
});
it("can override the throttle interval by returning a number from validateThrottle", async () => {
tock.useFakeTime(Date.now());
const schema = createTestSchema();
const document = parse(/* GraphQL */ `
query foo($throttle: Int) @live(throttle: $throttle) {
foo
}
`);
const store = new InMemoryLiveQueryStore({
validateThrottleValue: (value) => {
expect(value).toEqual(420);
return 690;
},
});
let executionResult = store.execute({
schema,
document,
variableValues: {
throttle: 420,
},
});
assertAsyncIterable(executionResult);
const values: Array<unknown> = [];
const done = (async function run() {
for await (const value of executionResult) {
values.push(value);
}
})();
store.invalidate("Query.foo");
await runAllPendingStuff();
expect(values).toHaveLength(1);
tock.advanceTime(420);
await runAllPendingStuff();
expect(values).toHaveLength(1);
tock.advanceTime(690);
await runAllPendingStuff();
expect(values).toHaveLength(2);
executionResult.return!();
await done;
}); | the_stack |
declare module 'vscode' {
/**
* Represents sources that can cause [selection change events](#window.onDidChangeTextEditorSelection).
*/
export enum TextEditorSelectionChangeKind {
/**
* Selection changed due to typing in the editor.
*/
Keyboard = 1,
/**
* Selection change due to clicking in the editor.
*/
Mouse = 2,
/**
* Selection changed because a command ran.
*/
Command = 3
}
/**
* Represents an event describing the change in a [text editor's selections](#TextEditor.selections).
*/
export interface TextEditorSelectionChangeEvent {
/**
* The [text editor](#TextEditor) for which the selections have changed.
*/
readonly textEditor: TextEditor;
/**
* The new value for the [text editor's selections](#TextEditor.selections).
*/
readonly selections: ReadonlyArray<Selection>;
/**
* The [change kind](#TextEditorSelectionChangeKind) which has triggered this
* event. Can be `undefined`.
*/
readonly kind?: TextEditorSelectionChangeKind;
}
/**
* Represents an event describing the change in a [text editor's visible ranges](#TextEditor.visibleRanges).
*/
export interface TextEditorVisibleRangesChangeEvent {
/**
* The [text editor](#TextEditor) for which the visible ranges have changed.
*/
readonly textEditor: TextEditor;
/**
* The new value for the [text editor's visible ranges](#TextEditor.visibleRanges).
*/
readonly visibleRanges: ReadonlyArray<Range>;
}
/**
* Represents an event describing the change in a [text editor's options](#TextEditor.options).
*/
export interface TextEditorOptionsChangeEvent {
/**
* The [text editor](#TextEditor) for which the options have changed.
*/
readonly textEditor: TextEditor;
/**
* The new value for the [text editor's options](#TextEditor.options).
*/
readonly options: TextEditorOptions;
}
/**
* Represents an event describing the change of a [text editor's view column](#TextEditor.viewColumn).
*/
export interface TextEditorViewColumnChangeEvent {
/**
* The [text editor](#TextEditor) for which the view column has changed.
*/
readonly textEditor: TextEditor;
/**
* The new value for the [text editor's view column](#TextEditor.viewColumn).
*/
readonly viewColumn: ViewColumn;
}
/**
* Rendering style of the cursor.
*/
export enum TextEditorCursorStyle {
/**
* Render the cursor as a vertical thick line.
*/
Line = 1,
/**
* Render the cursor as a block filled.
*/
Block = 2,
/**
* Render the cursor as a thick horizontal line.
*/
Underline = 3,
/**
* Render the cursor as a vertical thin line.
*/
LineThin = 4,
/**
* Render the cursor as a block outlined.
*/
BlockOutline = 5,
/**
* Render the cursor as a thin horizontal line.
*/
UnderlineThin = 6
}
/**
* Rendering style of the line numbers.
*/
export enum TextEditorLineNumbersStyle {
/**
* Do not render the line numbers.
*/
Off = 0,
/**
* Render the line numbers.
*/
On = 1,
/**
* Render the line numbers with values relative to the primary cursor location.
*/
Relative = 2
}
/**
* Represents a [text editor](#TextEditor)'s [options](#TextEditor.options).
*/
export interface TextEditorOptions {
/**
* The size in spaces a tab takes. This is used for two purposes:
* - the rendering width of a tab character;
* - the number of spaces to insert when [insertSpaces](#TextEditorOptions.insertSpaces) is true.
*
* When getting a text editor's options, this property will always be a number (resolved).
* When setting a text editor's options, this property is optional and it can be a number or `"auto"`.
*/
tabSize?: number | string;
/**
* When pressing Tab insert [n](#TextEditorOptions.tabSize) spaces.
* When getting a text editor's options, this property will always be a boolean (resolved).
* When setting a text editor's options, this property is optional and it can be a boolean or `"auto"`.
*/
insertSpaces?: boolean | string;
/**
* The rendering style of the cursor in this editor.
* When getting a text editor's options, this property will always be present.
* When setting a text editor's options, this property is optional.
*/
cursorStyle?: TextEditorCursorStyle;
/**
* Render relative line numbers w.r.t. the current line number.
* When getting a text editor's options, this property will always be present.
* When setting a text editor's options, this property is optional.
*/
lineNumbers?: TextEditorLineNumbersStyle;
}
/**
* Represents a handle to a set of decorations
* sharing the same [styling options](#DecorationRenderOptions) in a [text editor](#TextEditor).
*
* To get an instance of a `TextEditorDecorationType` use
* [createTextEditorDecorationType](#window.createTextEditorDecorationType).
*/
export interface TextEditorDecorationType {
/**
* Internal representation of the handle.
*/
readonly key: string;
/**
* Remove this decoration type and all decorations on all text editors using it.
*/
dispose(): void;
}
/**
* Represents different [reveal](#TextEditor.revealRange) strategies in a text editor.
*/
export enum TextEditorRevealType {
/**
* The range will be revealed with as little scrolling as possible.
*/
Default = 0,
/**
* The range will always be revealed in the center of the viewport.
*/
InCenter = 1,
/**
* If the range is outside the viewport, it will be revealed in the center of the viewport.
* Otherwise, it will be revealed with as little scrolling as possible.
*/
InCenterIfOutsideViewport = 2,
/**
* The range will always be revealed at the top of the viewport.
*/
AtTop = 3
}
/**
* Represents different positions for rendering a decoration in an [overview ruler](#DecorationRenderOptions.overviewRulerLane).
* The overview ruler supports three lanes.
*/
export enum OverviewRulerLane {
Left = 1,
Center = 2,
Right = 4,
Full = 7
}
/**
* Describes the behavior of decorations when typing/editing at their edges.
*/
export enum DecorationRangeBehavior {
/**
* The decoration's range will widen when edits occur at the start or end.
*/
OpenOpen = 0,
/**
* The decoration's range will not widen when edits occur at the start of end.
*/
ClosedClosed = 1,
/**
* The decoration's range will widen when edits occur at the start, but not at the end.
*/
OpenClosed = 2,
/**
* The decoration's range will widen when edits occur at the end, but not at the start.
*/
ClosedOpen = 3
}
/**
* Represents options to configure the behavior of showing a [document](#TextDocument) in an [editor](#TextEditor).
*/
export interface TextDocumentShowOptions {
/**
* An optional view column in which the [editor](#TextEditor) should be shown.
* The default is the [active](#ViewColumn.Active), other values are adjusted to
* be `Min(column, columnCount + 1)`, the [active](#ViewColumn.Active)-column is
* not adjusted. Use [`ViewColumn.Beside`](#ViewColumn.Beside) to open the
* editor to the side of the currently active one.
*/
viewColumn?: ViewColumn;
/**
* An optional flag that when `true` will stop the [editor](#TextEditor) from taking focus.
*/
preserveFocus?: boolean;
/**
* An optional flag that controls if an [editor](#TextEditor)-tab will be replaced
* with the next editor or if it will be kept.
*/
preview?: boolean;
/**
* An optional selection to apply for the document in the [editor](#TextEditor).
*/
selection?: Range;
}
/**
* Represents rendering styles for a [text editor decoration](#TextEditorDecorationType).
*/
export interface DecorationRenderOptions extends ThemableDecorationRenderOptions {
/**
* Should the decoration be rendered also on the whitespace after the line text.
* Defaults to `false`.
*/
isWholeLine?: boolean;
/**
* Customize the growing behavior of the decoration when edits occur at the edges of the decoration's range.
* Defaults to `DecorationRangeBehavior.OpenOpen`.
*/
rangeBehavior?: DecorationRangeBehavior;
/**
* The position in the overview ruler where the decoration should be rendered.
*/
overviewRulerLane?: OverviewRulerLane;
/**
* Overwrite options for light themes.
*/
light?: ThemableDecorationRenderOptions;
/**
* Overwrite options for dark themes.
*/
dark?: ThemableDecorationRenderOptions;
}
/**
* Represents options for a specific decoration in a [decoration set](#TextEditorDecorationType).
*/
export interface DecorationOptions {
/**
* Range to which this decoration is applied. The range must not be empty.
*/
range: Range;
/**
* A message that should be rendered when hovering over the decoration.
*/
hoverMessage?: MarkedString | MarkedString[];
/**
* Render options applied to the current decoration. For performance reasons, keep the
* number of decoration specific options small, and use decoration types wherever possible.
*/
renderOptions?: DecorationInstanceRenderOptions;
}
export interface ThemableDecorationInstanceRenderOptions {
/**
* Defines the rendering options of the attachment that is inserted before the decorated text.
*/
before?: ThemableDecorationAttachmentRenderOptions;
/**
* Defines the rendering options of the attachment that is inserted after the decorated text.
*/
after?: ThemableDecorationAttachmentRenderOptions;
}
export interface DecorationInstanceRenderOptions extends ThemableDecorationInstanceRenderOptions {
/**
* Overwrite options for light themes.
*/
light?: ThemableDecorationInstanceRenderOptions;
/**
* Overwrite options for dark themes.
*/
dark?: ThemableDecorationInstanceRenderOptions;
}
/**
* Represents an editor that is attached to a [document](#TextDocument).
*/
export interface TextEditor {
/**
* The document associated with this text editor. The document will be the same for the entire lifetime of this text editor.
*/
readonly document: TextDocument;
/**
* The primary selection on this text editor. Shorthand for `TextEditor.selections[0]`.
*/
selection: Selection;
/**
* The selections in this text editor. The primary selection is always at index 0.
*/
selections: Selection[];
/**
* The current visible ranges in the editor (vertically).
* This accounts only for vertical scrolling, and not for horizontal scrolling.
*/
readonly visibleRanges: Range[];
/**
* Text editor options.
*/
options: TextEditorOptions;
/**
* The column in which this editor shows. Will be `undefined` in case this
* isn't one of the main editors, e.g. an embedded editor, or when the editor
* column is larger than three.
*/
viewColumn?: ViewColumn;
/**
* Perform an edit on the document associated with this text editor.
*
* The given callback-function is invoked with an [edit-builder](#TextEditorEdit) which must
* be used to make edits. Note that the edit-builder is only valid while the
* callback executes.
*
* @param callback A function which can create edits using an [edit-builder](#TextEditorEdit).
* @param options The undo/redo behavior around this edit. By default, undo stops will be created before and after this edit.
* @return A promise that resolves with a value indicating if the edits could be applied.
*/
edit(callback: (editBuilder: TextEditorEdit) => void, options?: { undoStopBefore: boolean; undoStopAfter: boolean; }): Thenable<boolean>;
/**
* Insert a [snippet](#SnippetString) and put the editor into snippet mode. "Snippet mode"
* means the editor adds placeholders and additional cursors so that the user can complete
* or accept the snippet.
*
* @param snippet The snippet to insert in this edit.
* @param location Position or range at which to insert the snippet, defaults to the current editor selection or selections.
* @param options The undo/redo behavior around this edit. By default, undo stops will be created before and after this edit.
* @return A promise that resolves with a value indicating if the snippet could be inserted. Note that the promise does not signal
* that the snippet is completely filled-in or accepted.
*/
insertSnippet(snippet: SnippetString, location?: Position | Range | ReadonlyArray<Position> | ReadonlyArray<Range>, options?: { undoStopBefore: boolean; undoStopAfter: boolean; }): Thenable<boolean>;
/**
* Adds a set of decorations to the text editor. If a set of decorations already exists with
* the given [decoration type](#TextEditorDecorationType), they will be replaced.
*
* @see [createTextEditorDecorationType](#window.createTextEditorDecorationType).
*
* @param decorationType A decoration type.
* @param rangesOrOptions Either [ranges](#Range) or more detailed [options](#DecorationOptions).
*/
setDecorations(decorationType: TextEditorDecorationType, rangesOrOptions: Range[] | DecorationOptions[]): void;
/**
* Scroll as indicated by `revealType` in order to reveal the given range.
*
* @param range A range.
* @param revealType The scrolling strategy for revealing `range`.
*/
revealRange(range: Range, revealType?: TextEditorRevealType): void;
/**
* ~~Show the text editor.~~
*
* @deprecated Use [window.showTextDocument](#window.showTextDocument) instead.
*
* @param column The [column](#ViewColumn) in which to show this editor.
* This method shows unexpected behavior and will be removed in the next major update.
*/
show(column?: ViewColumn): void;
/**
* ~~Hide the text editor.~~
*
* @deprecated Use the command `workbench.action.closeActiveEditor` instead.
* This method shows unexpected behavior and will be removed in the next major update.
*/
hide(): void;
}
export interface TextEditorEdit {
/**
* Replace a certain text region with a new value.
* You can use \r\n or \n in `value` and they will be normalized to the current [document](#TextDocument).
*
* @param location The range this operation should remove.
* @param value The new text this operation should insert after removing `location`.
*/
replace(location: Position | Range | Selection, value: string): void;
/**
* Insert text at a location.
* You can use \r\n or \n in `value` and they will be normalized to the current [document](#TextDocument).
* Although the equivalent text edit can be made with [replace](#TextEditorEdit.replace), `insert` will produce a different resulting selection (it will get moved).
*
* @param location The position where the new text should be inserted.
* @param value The new text this operation should insert.
*/
insert(location: Position, value: string): void;
/**
* Delete a certain text region.
*
* @param location The range this operation should remove.
*/
delete(location: Range | Selection): void;
/**
* Set the end of line sequence.
*
* @param endOfLine The new end of line for the [document](#TextDocument).
*/
setEndOfLine(endOfLine: EndOfLine): void;
}
/**
* Denotes a location of an editor in the window. Editors can be arranged in a grid
* and each column represents one editor location in that grid by counting the editors
* in order of their appearance.
*/
export enum ViewColumn {
/**
* A *symbolic* editor column representing the currently active column. This value
* can be used when opening editors, but the *resolved* [viewColumn](#TextEditor.viewColumn)-value
* of editors will always be `One`, `Two`, `Three`,... or `undefined` but never `Active`.
*/
Active = -1,
/**
* A *symbolic* editor column representing the column to the side of the active one. This value
* can be used when opening editors, but the *resolved* [viewColumn](#TextEditor.viewColumn)-value
* of editors will always be `One`, `Two`, `Three`,... or `undefined` but never `Beside`.
*/
Beside = -2,
/**
* The first editor column.
*/
One = 1,
/**
* The second editor column.
*/
Two = 2,
/**
* The third editor column.
*/
Three = 3,
/**
* The fourth editor column.
*/
Four = 4,
/**
* The fifth editor column.
*/
Five = 5,
/**
* The sixth editor column.
*/
Six = 6,
/**
* The seventh editor column.
*/
Seven = 7,
/**
* The eighth editor column.
*/
Eight = 8,
/**
* The ninth editor column.
*/
Nine = 9
}
export namespace window {
/**
* The currently active editor or `undefined`. The active editor is the one
* that currently has focus or, when none has focus, the one that has changed
* input most recently.
*/
export let activeTextEditor: TextEditor | undefined;
/**
* The currently visible editors or an empty array.
*/
export let visibleTextEditors: TextEditor[];
/**
* An [event](#Event) which fires when the [active editor](#window.activeTextEditor)
* has changed. *Note* that the event also fires when the active editor changes
* to `undefined`.
*/
export const onDidChangeActiveTextEditor: Event<TextEditor | undefined>;
/**
* An [event](#Event) which fires when the array of [visible editors](#window.visibleTextEditors)
* has changed.
*/
export const onDidChangeVisibleTextEditors: Event<TextEditor[]>;
/**
* An [event](#Event) which fires when the selection in an editor has changed.
*/
export const onDidChangeTextEditorSelection: Event<TextEditorSelectionChangeEvent>;
/**
* An [event](#Event) which fires when the visible ranges of an editor has changed.
*/
export const onDidChangeTextEditorVisibleRanges: Event<TextEditorVisibleRangesChangeEvent>;
/**
* An [event](#Event) which fires when the options of an editor have changed.
*/
export const onDidChangeTextEditorOptions: Event<TextEditorOptionsChangeEvent>;
/**
* An [event](#Event) which fires when the view column of an editor has changed.
*/
export const onDidChangeTextEditorViewColumn: Event<TextEditorViewColumnChangeEvent>;
/**
* Show the given document in a text editor. A [column](#ViewColumn) can be provided
* to control where the editor is being shown. Might change the [active editor](#window.activeTextEditor).
*
* @param document A text document to be shown.
* @param column A view column in which the [editor](#TextEditor) should be shown. The default is the [active](#ViewColumn.Active), other values
* are adjusted to be `Min(column, columnCount + 1)`, the [active](#ViewColumn.Active)-column is not adjusted. Use [`ViewColumn.Beside`](#ViewColumn.Beside)
* to open the editor to the side of the currently active one.
* @param preserveFocus When `true` the editor will not take focus.
* @return A promise that resolves to an [editor](#TextEditor).
*/
export function showTextDocument(document: TextDocument, column?: ViewColumn, preserveFocus?: boolean): Thenable<TextEditor>;
/**
* Show the given document in a text editor. [Options](#TextDocumentShowOptions) can be provided
* to control options of the editor is being shown. Might change the [active editor](#window.activeTextEditor).
*
* @param document A text document to be shown.
* @param options [Editor options](#TextDocumentShowOptions) to configure the behavior of showing the [editor](#TextEditor).
* @return A promise that resolves to an [editor](#TextEditor).
*/
export function showTextDocument(document: TextDocument, options?: TextDocumentShowOptions): Thenable<TextEditor>;
/**
* A short-hand for `openTextDocument(uri).then(document => showTextDocument(document, options))`.
*
* @see [openTextDocument](#openTextDocument)
*
* @param uri A resource identifier.
* @param options [Editor options](#TextDocumentShowOptions) to configure the behavior of showing the [editor](#TextEditor).
* @return A promise that resolves to an [editor](#TextEditor).
*/
export function showTextDocument(uri: Uri, options?: TextDocumentShowOptions): Thenable<TextEditor>;
/**
* Create a TextEditorDecorationType that can be used to add decorations to text editors.
*
* @param options Rendering options for the decoration type.
* @return A new decoration type instance.
*/
export function createTextEditorDecorationType(options: DecorationRenderOptions): TextEditorDecorationType;
}
export class TextEdit {
/**
* Utility to create a replace edit.
*
* @param range A range.
* @param newText A string.
* @return A new text edit object.
*/
static replace(range: Range, newText: string): TextEdit;
/**
* Utility to create an insert edit.
*
* @param position A position, will become an empty range.
* @param newText A string.
* @return A new text edit object.
*/
static insert(position: Position, newText: string): TextEdit;
/**
* Utility to create a delete edit.
*
* @param range A range.
* @return A new text edit object.
*/
static delete(range: Range): TextEdit;
/**
* Utility to create an eol-edit.
*
* @param eol An eol-sequence
* @return A new text edit object.
*/
static setEndOfLine(eol: EndOfLine): TextEdit;
/**
* The range this edit applies to.
*/
range: Range;
/**
* The string this edit will insert.
*/
newText: string;
/**
* The eol-sequence used in the document.
*
* *Note* that the eol-sequence will be applied to the
* whole document.
*/
newEol: EndOfLine;
/**
* Create a new TextEdit.
*
* @param range A range.
* @param newText A string.
*/
constructor(range: Range, newText: string);
}
/**
* Provider for text based custom editors.
*
* Text based custom editors use a [`TextDocument`](#TextDocument) as their data model. This considerably simplifies
* implementing a custom editor as it allows VS Code to handle many common operations such as
* undo and backup. The provider is responsible for synchronizing text changes between the webview and the `TextDocument`.
*/
export interface CustomTextEditorProvider {
/**
* Resolve a custom editor for a given text resource.
*
* This is called when a user first opens a resource for a `CustomTextEditorProvider`, or if they reopen an
* existing editor using this `CustomTextEditorProvider`.
*
*
* @param document Document for the resource to resolve.
*
* @param webviewPanel The webview panel used to display the editor UI for this resource.
*
* During resolve, the provider must fill in the initial html for the content webview panel and hook up all
* the event listeners on it that it is interested in. The provider can also hold onto the `WebviewPanel` to
* use later for example in a command. See [`WebviewPanel`](#WebviewPanel) for additional details.
*
* @param token A cancellation token that indicates the result is no longer needed.
*
* @return Thenable indicating that the custom editor has been resolved.
*/
resolveCustomTextEditor(document: TextDocument, webviewPanel: WebviewPanel, token: CancellationToken): Thenable<void> | void;
}
/**
* Represents a custom document used by a [`CustomEditorProvider`](#CustomEditorProvider).
*
* Custom documents are only used within a given `CustomEditorProvider`. The lifecycle of a `CustomDocument` is
* managed by VS Code. When no more references remain to a `CustomDocument`, it is disposed of.
*/
interface CustomDocument {
/**
* The associated uri for this document.
*/
readonly uri: Uri;
/**
* Dispose of the custom document.
*
* This is invoked by VS Code when there are no more references to a given `CustomDocument` (for example when
* all editors associated with the document have been closed.)
*/
dispose(): void;
}
/**
* Event triggered by extensions to signal to VS Code that an edit has occurred on an [`CustomDocument`](#CustomDocument).
*
* @see [`CustomDocumentProvider.onDidChangeCustomDocument`](#CustomDocumentProvider.onDidChangeCustomDocument).
*/
interface CustomDocumentEditEvent<T extends CustomDocument = CustomDocument> {
/**
* The document that the edit is for.
*/
readonly document: T;
/**
* Undo the edit operation.
*
* This is invoked by VS Code when the user undoes this edit. To implement `undo`, your
* extension should restore the document and editor to the state they were in just before this
* edit was added to VS Code's internal edit stack by `onDidChangeCustomDocument`.
*/
undo(): Thenable<void> | void;
/**
* Redo the edit operation.
*
* This is invoked by VS Code when the user redoes this edit. To implement `redo`, your
* extension should restore the document and editor to the state they were in just after this
* edit was added to VS Code's internal edit stack by `onDidChangeCustomDocument`.
*/
redo(): Thenable<void> | void;
/**
* Display name describing the edit.
*
* This will be shown to users in the UI for undo/redo operations.
*/
readonly label?: string;
}
/**
* Event triggered by extensions to signal to VS Code that the content of a [`CustomDocument`](#CustomDocument)
* has changed.
*
* @see [`CustomDocumentProvider.onDidChangeCustomDocument`](#CustomDocumentProvider.onDidChangeCustomDocument).
*/
interface CustomDocumentContentChangeEvent<T extends CustomDocument = CustomDocument> {
/**
* The document that the change is for.
*/
readonly document: T;
}
/**
* A backup for an [`CustomDocument`](#CustomDocument).
*/
interface CustomDocumentBackup {
/**
* Unique identifier for the backup.
*
* This id is passed back to your extension in `openCustomDocument` when opening a custom editor from a backup.
*/
readonly id: string;
/**
* Delete the current backup.
*
* This is called by VS Code when it is clear the current backup is no longer needed, such as when a new backup
* is made or when the file is saved.
*/
delete(): void;
}
/**
* Additional information used to implement [`CustomEditableDocument.backup`](#CustomEditableDocument.backup).
*/
interface CustomDocumentBackupContext {
/**
* Suggested file location to write the new backup.
*
* Note that your extension is free to ignore this and use its own strategy for backup.
*
* If the editor is for a resource from the current workspace, `destination` will point to a file inside
* `ExtensionContext.storagePath`. The parent folder of `destination` may not exist, so make sure to created it
* before writing the backup to this location.
*/
readonly destination: Uri;
}
/**
* Additional information about the opening custom document.
*/
interface CustomDocumentOpenContext {
/**
* The id of the backup to restore the document from or `undefined` if there is no backup.
*
* If this is provided, your extension should restore the editor from the backup instead of reading the file
* from the user's workspace.
*/
readonly backupId?: string;
untitledDocumentData?: Uint8Array;
}
/**
* Provider for readonly custom editors that use a custom document model.
*
* Custom editors use [`CustomDocument`](#CustomDocument) as their document model instead of a [`TextDocument`](#TextDocument).
*
* You should use this type of custom editor when dealing with binary files or more complex scenarios. For simple
* text based documents, use [`CustomTextEditorProvider`](#CustomTextEditorProvider) instead.
*
* @param T Type of the custom document returned by this provider.
*/
export interface CustomReadonlyEditorProvider<T extends CustomDocument = CustomDocument> {
/**
* Create a new document for a given resource.
*
* `openCustomDocument` is called when the first time an editor for a given resource is opened. The opened
* document is then passed to `resolveCustomEditor` so that the editor can be shown to the user.
*
* Already opened `CustomDocument` are re-used if the user opened additional editors. When all editors for a
* given resource are closed, the `CustomDocument` is disposed of. Opening an editor at this point will
* trigger another call to `openCustomDocument`.
*
* @param uri Uri of the document to open.
* @param openContext Additional information about the opening custom document.
* @param token A cancellation token that indicates the result is no longer needed.
*
* @return The custom document.
*/
openCustomDocument(uri: Uri, openContext: CustomDocumentOpenContext, token: CancellationToken): Thenable<T> | T;
/**
* Resolve a custom editor for a given resource.
*
* This is called whenever the user opens a new editor for this `CustomEditorProvider`.
*
* @param document Document for the resource being resolved.
*
* @param webviewPanel The webview panel used to display the editor UI for this resource.
*
* During resolve, the provider must fill in the initial html for the content webview panel and hook up all
* the event listeners on it that it is interested in. The provider can also hold onto the `WebviewPanel` to
* use later for example in a command. See [`WebviewPanel`](#WebviewPanel) for additional details.
*
* @param token A cancellation token that indicates the result is no longer needed.
*
* @return Optional thenable indicating that the custom editor has been resolved.
*/
resolveCustomEditor(document: T, webviewPanel: WebviewPanel, token: CancellationToken): Thenable<void> | void;
}
/**
* Provider for editable custom editors that use a custom document model.
*
* Custom editors use [`CustomDocument`](#CustomDocument) as their document model instead of a [`TextDocument`](#TextDocument).
* This gives extensions full control over actions such as edit, save, and backup.
*
* You should use this type of custom editor when dealing with binary files or more complex scenarios. For simple
* text based documents, use [`CustomTextEditorProvider`](#CustomTextEditorProvider) instead.
*
* @param T Type of the custom document returned by this provider.
*/
export interface CustomEditorProvider<T extends CustomDocument = CustomDocument> extends CustomReadonlyEditorProvider<T> {
/**
* Signal that an edit has occurred inside a custom editor.
*
* This event must be fired by your extension whenever an edit happens in a custom editor. An edit can be
* anything from changing some text, to cropping an image, to reordering a list. Your extension is free to
* define what an edit is and what data is stored on each edit.
*
* Firing `onDidChange` causes VS Code to mark the editors as being dirty. This is cleared when the user either
* saves or reverts the file.
*
* Editors that support undo/redo must fire a `CustomDocumentEditEvent` whenever an edit happens. This allows
* users to undo and redo the edit using VS Code's standard VS Code keyboard shortcuts. VS Code will also mark
* the editor as no longer being dirty if the user undoes all edits to the last saved state.
*
* Editors that support editing but cannot use VS Code's standard undo/redo mechanism must fire a `CustomDocumentContentChangeEvent`.
* The only way for a user to clear the dirty state of an editor that does not support undo/redo is to either
* `save` or `revert` the file.
*
* An editor should only ever fire `CustomDocumentEditEvent` events, or only ever fire `CustomDocumentContentChangeEvent` events.
*/
readonly onDidChangeCustomDocument: Event<CustomDocumentEditEvent<T>> | Event<CustomDocumentContentChangeEvent<T>>;
/**
* Save a custom document.
*
* This method is invoked by VS Code when the user saves a custom editor. This can happen when the user
* triggers save while the custom editor is active, by commands such as `save all`, or by auto save if enabled.
*
* To implement `save`, the implementer must persist the custom editor. This usually means writing the
* file data for the custom document to disk. After `save` completes, any associated editor instances will
* no longer be marked as dirty.
*
* @param document Document to save.
* @param cancellation Token that signals the save is no longer required (for example, if another save was triggered).
*
* @return Thenable signaling that saving has completed.
*/
saveCustomDocument(document: T, cancellation: CancellationToken): Thenable<void>;
/**
* Save a custom document to a different location.
*
* This method is invoked by VS Code when the user triggers 'save as' on a custom editor. The implementer must
* persist the custom editor to `destination`.
*
* When the user accepts save as, the current editor is be replaced by an non-dirty editor for the newly saved file.
*
* @param document Document to save.
* @param destination Location to save to.
* @param cancellation Token that signals the save is no longer required.
*
* @return Thenable signaling that saving has completed.
*/
saveCustomDocumentAs(document: T, destination: Uri, cancellation: CancellationToken): Thenable<void>;
/**
* Revert a custom document to its last saved state.
*
* This method is invoked by VS Code when the user triggers `File: Revert File` in a custom editor. (Note that
* this is only used using VS Code's `File: Revert File` command and not on a `git revert` of the file).
*
* To implement `revert`, the implementer must make sure all editor instances (webviews) for `document`
* are displaying the document in the same state is saved in. This usually means reloading the file from the
* workspace.
*
* @param document Document to revert.
* @param cancellation Token that signals the revert is no longer required.
*
* @return Thenable signaling that the change has completed.
*/
revertCustomDocument(document: T, cancellation: CancellationToken): Thenable<void>;
/**
* Back up a dirty custom document.
*
* Backups are used for hot exit and to prevent data loss. Your `backup` method should persist the resource in
* its current state, i.e. with the edits applied. Most commonly this means saving the resource to disk in
* the `ExtensionContext.storagePath`. When VS Code reloads and your custom editor is opened for a resource,
* your extension should first check to see if any backups exist for the resource. If there is a backup, your
* extension should load the file contents from there instead of from the resource in the workspace.
*
* `backup` is triggered approximately one second after the the user stops editing the document. If the user
* rapidly edits the document, `backup` will not be invoked until the editing stops.
*
* `backup` is not invoked when `auto save` is enabled (since auto save already persists the resource).
*
* @param document Document to backup.
* @param context Information that can be used to backup the document.
* @param cancellation Token that signals the current backup since a new backup is coming in. It is up to your
* extension to decided how to respond to cancellation. If for example your extension is backing up a large file
* in an operation that takes time to complete, your extension may decide to finish the ongoing backup rather
* than cancelling it to ensure that VS Code has some valid backup.
*/
backupCustomDocument(document: T, context: CustomDocumentBackupContext, cancellation: CancellationToken): Thenable<CustomDocumentBackup>;
}
} | the_stack |
import { setChildRecordParam, updateDetailsParam } from '../data/sample15';
import { ParameterSchema } from '../src/schema/parameter';
import { MichelsonMap } from '../src/michelson-map';
describe('Schema test when calling contract with complex object as param and null value', () => {
it('Should encode parameter schema properly', () => {
const schema = new ParameterSchema(setChildRecordParam);
const dataMap = new MichelsonMap();
dataMap.set("Hello World", {bool:true})
const result = schema.Encode(
'tz3WXYtyDUNL91qfiCJtVUX746QpNv5i5ve5', //address(optional)
dataMap,//data
'AAAA', //label
'tz3WXYtyDUNL91qfiCJtVUX746QpNv5i5ve5', //owner
'FFFF', //parent
'1' //ttl(optional)
);
expect(schema).toBeTruthy();
expect(result).toEqual({
"prim": "Pair",
"args": [
{
"prim": "Pair",
"args": [
{
"prim": "Pair",
"args": [
{
"prim": "Some",
"args": [
{
"string": "tz3WXYtyDUNL91qfiCJtVUX746QpNv5i5ve5"
}
]
},
[
{
"prim": "Elt",
"args": [
{
"string": "Hello World"
},
{
"prim": "Left",
"args": [
{
"prim": "Left",
"args": [
{
"prim": "Left",
"args": [
{
"prim": "Right",
"args": [
{
"prim": "True"
}
]
}
]
}
]
}
]
}
]
}
]
]
},
{
"prim": "Pair",
"args": [
{
"bytes": "AAAA"
},
{
"string": "tz3WXYtyDUNL91qfiCJtVUX746QpNv5i5ve5"
}
]
}
]
},
{
"prim": "Pair",
"args": [
{
"bytes": "FFFF"
},
{
"prim": "Some",
"args": [
{
"int": "1"
}
]
}
]
}
]
});
});
it('Should encode parameter schema properly when first element which is optional is null', () => {
const schema = new ParameterSchema(setChildRecordParam);
const dataMap = new MichelsonMap();
dataMap.set("Hello World", {bool:true})
const result = schema.Encode(
null, //address(optional)
dataMap,//data
'AAAA', //label
'tz3WXYtyDUNL91qfiCJtVUX746QpNv5i5ve5', //owner
'FFFF', //parent
'1' //ttl(optional)
);
expect(schema).toBeTruthy();
expect(result).toEqual({
"prim": "Pair",
"args": [
{
"prim": "Pair",
"args": [
{
"prim": "Pair",
"args": [
{
"prim": "None"
},
[
{
"prim": "Elt",
"args": [
{
"string": "Hello World"
},
{
"prim": "Left",
"args": [
{
"prim": "Left",
"args": [
{
"prim": "Left",
"args": [
{
"prim": "Right",
"args": [
{
"prim": "True"
}
]
}
]
}
]
}
]
}
]
}
]
]
},
{
"prim": "Pair",
"args": [
{
"bytes": "AAAA"
},
{
"string": "tz3WXYtyDUNL91qfiCJtVUX746QpNv5i5ve5"
}
]
}
]
},
{
"prim": "Pair",
"args": [
{
"bytes": "FFFF"
},
{
"prim": "Some",
"args": [
{
"int": "1"
}
]
}
]
}
]
});
});
it('Should encode parameter schema properly when last element which is optional is null', () => {
const schema = new ParameterSchema(setChildRecordParam);
const dataMap = new MichelsonMap();
dataMap.set("Hello World", {bool:true})
const result = schema.Encode(
'tz3WXYtyDUNL91qfiCJtVUX746QpNv5i5ve5', //address(optional)
dataMap,//data
'AAAA', //label
'tz3WXYtyDUNL91qfiCJtVUX746QpNv5i5ve5', //owner
'FFFF', //parent
null //ttl(optional)
);
expect(schema).toBeTruthy();
expect(result).toEqual({
"prim": "Pair",
"args": [
{
"prim": "Pair",
"args": [
{
"prim": "Pair",
"args": [
{
"prim": "Some",
"args": [
{
"string": "tz3WXYtyDUNL91qfiCJtVUX746QpNv5i5ve5"
}
]
},
[
{
"prim": "Elt",
"args": [
{
"string": "Hello World"
},
{
"prim": "Left",
"args": [
{
"prim": "Left",
"args": [
{
"prim": "Left",
"args": [
{
"prim": "Right",
"args": [
{
"prim": "True"
}
]
}
]
}
]
}
]
}
]
}
]
]
},
{
"prim": "Pair",
"args": [
{
"bytes": "AAAA"
},
{
"string": "tz3WXYtyDUNL91qfiCJtVUX746QpNv5i5ve5"
}
]
}
]
},
{
"prim": "Pair",
"args": [
{
"bytes": "FFFF"
},
{
"prim": "None"
}
]
}
]
});
});
it('Should encode parameter schema properly when first and last element which are optional are null', () => {
const schema = new ParameterSchema(setChildRecordParam);
const dataMap = new MichelsonMap();
dataMap.set("Hello World", {bool:true})
const result = schema.Encode(
null, //address(optional)
dataMap,//data
'AAAA', //label
'tz3WXYtyDUNL91qfiCJtVUX746QpNv5i5ve5', //owner
'FFFF', //parent
null //ttl(optional)
);
expect(schema).toBeTruthy();
expect(result).toEqual({
"prim": "Pair",
"args": [
{
"prim": "Pair",
"args": [
{
"prim": "Pair",
"args": [
{
"prim": "None"
},
[
{
"prim": "Elt",
"args": [
{
"string": "Hello World"
},
{
"prim": "Left",
"args": [
{
"prim": "Left",
"args": [
{
"prim": "Left",
"args": [
{
"prim": "Right",
"args": [
{
"prim": "True"
}
]
}
]
}
]
}
]
}
]
}
]
]
},
{
"prim": "Pair",
"args": [
{
"bytes": "AAAA"
},
{
"string": "tz3WXYtyDUNL91qfiCJtVUX746QpNv5i5ve5"
}
]
}
]
},
{
"prim": "Pair",
"args": [
{
"bytes": "FFFF"
},
{
"prim": "None"
}
]
}
]
});
});
it('Should encode parameter schema properly', () => {
const schema = new ParameterSchema(updateDetailsParam);
const dataMap = new MichelsonMap();
dataMap.set("Hello World", {bool:true})
const result = schema.Encode(
'5',//id
'tz1PgQt52JMirBUhhkq1eanX8hVd1Fsg71Lr', //new_controller(optional)
'AAAA', //new_profile(optional)
);
expect(schema).toBeTruthy();
expect(result).toEqual({
"prim": "Pair",
"args": [
{
"prim": "Pair",
"args": [
{
"int": "5"
},
{
"prim": "Some",
"args": [
{
"string": "tz1PgQt52JMirBUhhkq1eanX8hVd1Fsg71Lr"
}
]
}
]
},
{
"prim": "Some",
"args": [
{
"bytes": "AAAA"
}
]
}
]
});
});
it('Should encode parameter schema properly if last element which is optinal is null', () => {
const schema = new ParameterSchema(updateDetailsParam);
const dataMap = new MichelsonMap();
dataMap.set("Hello World", {bool:true})
const result = schema.Encode(
'5',//id
'tz1PgQt52JMirBUhhkq1eanX8hVd1Fsg71Lr', //new_controller(optional)
null, //new_profile(optional)
);
expect(schema).toBeTruthy();
expect(result).toEqual({
"prim": "Pair",
"args": [
{
"prim": "Pair",
"args": [
{
"int": "5"
},
{
"prim": "Some",
"args": [
{
"string": "tz1PgQt52JMirBUhhkq1eanX8hVd1Fsg71Lr"
}
]
}
]
},
{
"prim": "None"
}
]
});
});
it('Should encode parameter schema properly if second and last elements which are optional are null', () => {
const schema = new ParameterSchema(updateDetailsParam);
const dataMap = new MichelsonMap();
dataMap.set("Hello World", {bool:true})
const result = schema.Encode(
'5',//id
null, //new_controller(optional)
null, //new_profile(optional)
);
expect(schema).toBeTruthy();
expect(result).toEqual({
"prim": "Pair",
"args": [
{
"prim": "Pair",
"args": [
{
"int": "5"
},
{
"prim": "None"
}
]
},
{
"prim": "None"
}
]
});
});
it('Should encode parameter schema properly if second element which is optional is null', () => {
const schema = new ParameterSchema(updateDetailsParam);
const dataMap = new MichelsonMap();
dataMap.set("Hello World", {bool:true})
const result = schema.Encode(
'5',//id
null, //new_controller(optional)
'AAAA', //new_profile(optional)
);
expect(schema).toBeTruthy();
expect(result).toEqual({
"prim": "Pair",
"args": [
{
"prim": "Pair",
"args": [
{
"int": "5"
},
{
"prim": "None"
}
]
},
{
"prim": "Some",
"args": [
{
"bytes": "AAAA"
}
]
}
]
});
});
}); | the_stack |
'use strict';
import { ethers } from 'ethers';
const errors = ethers.errors;
const constants = ethers.constants;
const utils = ethers.utils;
const basex = function(ALPHABET: string) {
/**
* Contributors:
*
* base-x encoding
* Forked from https://github.com/cryptocoinjs/bs58
* Originally written by Mike Hearn for BitcoinJ
* Copyright (c) 2011 Google Inc
* Ported to JavaScript by Stefan Thomas
* Merged Buffer refactorings from base58-native by Stephen Pair
* Copyright (c) 2013 BitPay Inc
*
* The MIT License (MIT)
*
* Copyright base-x contributors (c) 2016
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
let ALPHABET_MAP: { [character: string ]: number } = {}
let BASE = ALPHABET.length
let LEADER = ALPHABET.charAt(0)
// pre-compute lookup table
for (let i = 0; i < ALPHABET.length; i++) {
ALPHABET_MAP[ALPHABET.charAt(i)] = i;
}
function encode(source: Uint8Array): string {
if (source.length === 0) return ''
let digits = [0]
for (let i = 0; i < source.length; ++i) {
let carry = source[i];
for (let j = 0; j < digits.length; ++j) {
carry += digits[j] << 8
digits[j] = carry % BASE
carry = (carry / BASE) | 0
}
while (carry > 0) {
digits.push(carry % BASE)
carry = (carry / BASE) | 0
}
}
let string = ''
// deal with leading zeros
for (let k = 0; source[k] === 0 && k < source.length - 1; ++k) string += LEADER
// convert digits to a string
for (let q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]]
return string
}
function decodeUnsafe (string: string): Uint8Array {
if (typeof string !== 'string') throw new TypeError('Expected String')
let bytes: Array<number> = [];
if (string.length === 0) { return new Uint8Array(bytes); }
bytes.push(0);
for (let i = 0; i < string.length; i++) {
let value = ALPHABET_MAP[string[i]]
if (value === undefined) return
let carry = value;
for (let j = 0; j < bytes.length; ++j) {
carry += bytes[j] * BASE
bytes[j] = carry & 0xff
carry >>= 8
}
while (carry > 0) {
bytes.push(carry & 0xff)
carry >>= 8
}
}
// deal with leading zeros
for (let k = 0; string[k] === LEADER && k < string.length - 1; ++k) {
bytes.push(0)
}
return new Uint8Array(bytes.reverse())
}
function decode (string: string): Uint8Array {
let buffer = decodeUnsafe(string)
if (buffer) return buffer
throw new Error('Non-base' + BASE + ' character')
}
return {
encode: encode,
decode: decode
}
}
const Base58 = basex("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
const ensInterface = [
"function owner(bytes32 nodeHash) constant returns (address owner)",
"function resolver(bytes32 nodeHash) constant returns (address resolver)",
"function ttl(bytes32 nodeHash) returns (uint64 ttl)",
"function setOwner(bytes32 nodeHash, address owner) @100000",
"function setSubnodeOwner(bytes32 node, bytes32 label, address owner) @85000",
"function setResolver(bytes32 nodeHash, address resolver) @100000",
];
const testRegistrarInterface = [
"function expiryTimes(bytes32 labelHash) constant returns (uint256 expiry)",
"function register(bytes32 labelHash, address owner)"
];
const hashRegistrarInterface = [
"function entries(bytes32 labelHash) constant returns (uint8 state, address winningDeed, uint endDate, uint value, uint highestBid)",
"function getAllowedTime(bytes32 labelHash) constant returns (uint timestamp)",
"function shaBid(bytes32 labelHash, address owner, uint256 bidAmount, bytes32 salt) constant returns (bytes32 sealedBid)",
"function startAuction(bytes32 labelHash) @300000",
"function newBid(bytes32 sealedBid) @500000",
"function unsealBid(bytes32 labelHash, uint256 bidAmount, bytes32 salt) @200000",
"function finalizeAuction(bytes32 labelHash) @200000",
"event AuctionStarted(bytes32 albelHash, uint256 registrationDate)",
"event NewBid(bytes32 sealedBid, address bidder, uint256 deposit)",
"event BidRevealed(bytes32 labelHash, address owner, uint256 value, uint8 status)",
"event HashRegistered(bytes32 labelHash, address owner, uint256 value, uint256 registrationData)",
"event HashReleased(bytes32 labelHash, uint256 value)",
"event HashInvalidated(bytes32 labelHash,string name, uint256 value, uint256 registrationDate)"
];
const simpleRegistrarInterface = [
"function fee() constant returns (uint256 fee)",
"function register(string label)"
];
const deedInterface = [
"function owner() constant returns (address owner)"
];
const resolverInterface = [
"function supportsInterface(bytes4 interfaceId) constant returns (bool supported)",
"function addr(bytes32 nodeHash) constant returns (address addr)",
"function name(bytes32 nodeHash) constant returns (string name)",
"function ABI(bytes32 nodeHash, uint256 type) constant returns (uint contentType, bytes data)",
"function pubkey(bytes32 nodeHash) constant returns (bytes32 x, bytes32 y)",
"function text(bytes32 nodeHash, string key) constant returns (string value)",
"function contenthash(bytes32 nodeHash) constant returns (bytes contenthash)",
"function content(bytes32 nodeHash) constant returns (bytes32 content)",
"function multihash(bytes32 nodeHash) constant returns (bytes multihash)",
"function setAddr(bytes32 nodeHash, address addr) @150000",
"function setName(bytes32 nodeHash, string name)",
"function setABI(bytes32 nodeHash, uint256 contentType, bytes data)",
"function setPubkey(bytes32 nodeHash, bytes32 x, bytes32 y)",
"function setText(bytes32 nodeHash, string key, string value)",
"function setContenthash(bytes32 nodeHash, bytes contenthash)",
];
const reverseRegistrarInterface = [
"function setName(string name) returns (bytes32 node) @150000"
];
function zeroPad(value: number, length: number): string {
let valueString = String(value);
while (valueString.length < length) { valueString = '0' + valueString; }
return valueString;
}
// Return YYYY-mm-dd HH:MM:SS
export function getDate(date: Date): string {
return (
date.getFullYear() + '-' +
zeroPad(date.getMonth() + 1, 2) + '-' +
zeroPad(date.getDate(), 2) + ' ' +
zeroPad(date.getHours(), 2) + ':' +
zeroPad(date.getMinutes(), 2) + ':' +
zeroPad(date.getSeconds(), 2)
)
}
// Return the delta time between now and the timestamp
function getTimer(timestamp: Date): string {
let dt = (timestamp.getTime() - (new Date()).getTime()) / 1000;
let negative = false;
if (dt < 0) {
negative = true;
dt *= -1;
}
if (dt === 0) { return '0'; }
let result: Array<string> = [];
[60, 60, 24, 365, 1000].forEach(function(chunk) {
if (dt === 0) { return; }
let amount = zeroPad(Math.trunc(dt % chunk), 2);
dt = Math.trunc(dt / chunk);
result.unshift(amount);
})
let timer = result.join(":");
// Trim leading zeros
while (timer.length > 1 && timer.match(/^[0:].+/)) {
timer = timer.substring(1);
}
if (negative) { timer = '-' + timer; }
return timer;
}
export function getDateTimer(timestamp: Date): string {
let timer = getTimer(timestamp);
if (timer.substring(0, 1) === '-') {
timer = ' (' + timer.substring(1) + ' ago)';
} else {
timer = ' (in ' + timer + ')';
}
return getDate(timestamp) + timer;
}
export const interfaces = {
ens: new utils.Interface(ensInterface),
testRegistrar: new utils.Interface(testRegistrarInterface),
hashRegistrar: new utils.Interface(hashRegistrarInterface),
reverseRegistrar: new utils.Interface(reverseRegistrarInterface),
simpleRegistrar: new utils.Interface(simpleRegistrarInterface),
resolver: new utils.Interface(resolverInterface),
}
Object.freeze(interfaces);
export enum ABIEncodings {
JSON = 1,
zlibJSON = 2,
CBOR = 4,
URI = 8,
}
export interface Auction {
state: string;
winningDeed: string
endDate: Date;
revealDate: Date;
value: ethers.utils.BigNumber;
highestBid: ethers.utils.BigNumber;
}
export interface ENSTransactionResponse extends ethers.providers.TransactionResponse {
metadata: { [key: string]: any };
}
interface Bid {
address: string,
bidAmount: ethers.utils.BigNumber;
salt: string;
sealedBid: string;
registrar: HashRegistrarContract;
name: string;
labelHash: string;
}
interface EnsContract {
address: string;
connect(signer: ethers.Signer): EnsContract;
owner(nodeHash: string): Promise<string>;
resolver(nodeHash: string): Promise<string>;
ttl(nodeHash: string): Promise<ethers.utils.BigNumber>
setOwner(nodeHash: string, owner: string): Promise<ENSTransactionResponse>;
setSubnodeOwner(node: string, label: string, owner: string): Promise<ENSTransactionResponse>;
setResolver(nodeHash: string, resolver: string): Promise<ENSTransactionResponse>;
}
interface ResolverContract {
address: string;
connect(signer: ethers.Signer): ResolverContract;
supportsInterface(interfaceId: string): Promise<boolean>;
addr(nodeHash: string): Promise<string>;
setAddr(nodeHash: string, addr: string): Promise<ENSTransactionResponse>;
name(nodeHash: string): Promise<string>;
setName(nodeHash: string, name: string): Promise<ENSTransactionResponse>;
pubkey(nodeHash: string): Promise<{ x: string, y: string }>;
setPubkey(nodeHash: string, x: string, y: string): Promise<ENSTransactionResponse>;
text(nodeHash: string, key: string): Promise<string>;
setText(nodeHash: string, key: string, value: string): Promise<ENSTransactionResponse>;
ABI(nodeHash: string): Promise<{ type: number, data: Uint8Array }>;
setABI(nodeHash: string, type: number, data: Uint8Array): Promise<ENSTransactionResponse>;
contenthash(nodeHash: string): Promise<string>;
content(nodeHash: string): Promise<string>;
setContenthash(nodeHash: string, contentHash: Uint8Array): Promise<ENSTransactionResponse>;
}
interface HashRegistrarContract {
address: string;
connect(signer: ethers.Signer): HashRegistrarContract;
entries(labelHash: string): Promise<{ state: number, winningDeed: string, endDate: ethers.utils.BigNumber, value: ethers.utils.BigNumber, highestBid: ethers.utils.BigNumber}>;
getAllowedTime(labelHash: string): Promise<ethers.utils.BigNumber>;
shaBid(labelHash: string, owner: string, bidAmount: ethers.utils.BigNumberish, salt: ethers.utils.Arrayish): Promise<string>;
startAuction(labelHash: string): Promise<ENSTransactionResponse>;
newBid(sealedBid: string, options?: { value: ethers.utils.BigNumberish }): Promise<ENSTransactionResponse>;
unsealBid(labelHash: string, bidAmount: ethers.utils.BigNumberish, salt: ethers.utils.Arrayish): Promise<ENSTransactionResponse>;
finalizeAuction(labelHash: string): Promise<ENSTransactionResponse>;
}
interface ReverseRegistrarContract {
setName(name: string): Promise<ENSTransactionResponse>;
}
function uintify(value: ethers.utils.BigNumberish): string {
return utils.hexZeroPad(utils.bigNumberify(value).toHexString(), 32);
}
const states = [
'open', 'auction', 'owned', 'forbidden', 'reveal', 'not-yet-available'
];
const interfaceIds = {
addr: '0x3b3b57de',
name: '0x691f3431',
pubkey: '0xc8690233',
text: '0x59d1d43c',
abi: '0x2203ab56',
contenthash: '0xbc1c58d1',
}
export class ENS {
readonly provider: ethers.providers.Provider;
readonly signer: ethers.Signer;
private _ens: Promise<EnsContract> = null;
private _hashRegistrar: Promise<HashRegistrarContract> = null;
constructor(providerOrSigner: ethers.providers.Provider | ethers.Signer) {
errors.checkNew(this, ENS);
this.provider = null;
this.signer = null;
if (ethers.providers.Provider.isProvider(providerOrSigner)) {
utils.defineReadOnly(this, 'provider', providerOrSigner);
} else if (ethers.Signer.isSigner(providerOrSigner)) {
if (!providerOrSigner.provider) {
errors.throwError('signer is missing provider', errors.INVALID_ARGUMENT, {
argument: 'providerOrSigner',
value: providerOrSigner
});
}
utils.defineReadOnly(this, 'signer', providerOrSigner);
utils.defineReadOnly(this, 'provider', providerOrSigner.provider);
} else {
errors.throwError('invalid provider or signer', errors.INVALID_ARGUMENT, {
argument: 'providerOrSigner',
value: providerOrSigner
});
}
/*
let ensPromise = this.provider.getNetwork((network) => {
return new ethers.Contract(network.ensAddress, interfaces.ens, );
});
ethers.utils.defineReadOnly(this, '_ensPromise', ensPromise);
*/
}
getAuctionStartDate(name: string): Promise<Date> {
return this._getHashRegistrar(name).then(({ labelHash, registrar }) => {
return registrar.getAllowedTime(labelHash).then((timestamp) => {
return new Date(timestamp.toNumber() * 1000);
});
});
}
async getAuction(name: string): Promise<Auction> {
let { labelHash, registrar } = await this._getHashRegistrar(name);
let auction = await registrar.entries(labelHash);
return {
endDate: new Date(auction.endDate.toNumber() * 1000),
highestBid: auction.highestBid,
revealDate: new Date((auction.endDate.toNumber() - (24 * 2 * 60 * 60)) * 1000),
state: states[auction.state],
value: auction.value,
winningDeed: auction.winningDeed
};
}
async startAuction(name: string): Promise<ENSTransactionResponse> {
if (!this.signer) { return Promise.reject(new Error('no signer')); }
let { labelHash, registrar } = await this._getHashRegistrar(name)
let auction = await this.getAuction(name);
let errorMessages: { [state: string]: string } = {
'auction': 'name already up for auction; please bid before ' + getDateTimer(auction.revealDate),
'owned': 'name already owned',
'forbidden': 'name forbidden',
'reveal': 'bidding closed; please "reveal" your bid before ' + getDateTimer(auction.endDate),
// 'not-yet-available': ('name not available until ' + getDateTimer(nameInfo.startDate))
};
let errorMessage = errorMessages[auction.state];
if (errorMessage) {
errors.throwError(errorMessage, errors.UNSUPPORTED_OPERATION, {
name: name
});
}
let tx = await registrar.connect(this.signer).startAuction(labelHash);
tx.metadata = {
labelHash: labelHash,
name: name
};
return tx;
}
async finalizeAuction(name: string): Promise<ENSTransactionResponse> {
if (!this.signer) { return Promise.reject(new Error('no signer')); }
let auction = await this.getAuction(name);
let errorMessages: { [state: string]: string } = {
'auction': ('name still up for auction; wait until ' + getDateTimer(auction.revealDate)),
'open': 'name not up for auction yet; please "start" first',
'forbidden': 'name forbidden',
'reveal': 'auction closed; please "reveal" your bid before ' + getDateTimer(auction.endDate),
// 'not-yet-available': ('name not available until ' + getDateTimer(result.startDate))
};
let errorMessage = errorMessages[auction.state];
if (errorMessage) {
errors.throwError(errorMessage, errors.UNSUPPORTED_OPERATION, {
name: name
});
}
let deedOwner = await this.getDeedOwner(name);
let signerAddress = await this.signer.getAddress();
if (deedOwner !== signerAddress) {
errors.throwError('signer is not deed owner', errors.UNSUPPORTED_OPERATION, {
signerAddress: signerAddress,
deedOwner: deedOwner,
name: name
});
}
let { labelHash, registrar } = await this._getHashRegistrar(name);
let tx = await registrar.connect(this.signer).finalizeAuction(labelHash);
tx.metadata = {
labelHash: labelHash,
name: name
}
return tx;
}
async getBidHash(name: string, address: string, bidAmount: ethers.utils.BigNumber, salt: ethers.utils.Arrayish): Promise<string> {
let { labelHash, registrar } = await this._getHashRegistrar(name);
let sealedBid = await registrar.shaBid(labelHash, address, bidAmount, salt);
return sealedBid;
}
_getBid(name: string, bidAmount: ethers.utils.BigNumber, salt: ethers.utils.Arrayish): Promise<Bid> {
if (!this.signer) { return Promise.reject(new Error('no signer')); }
if (!salt || utils.arrayify(salt).length !== 32) {
errors.throwError('invalid salt', errors.INVALID_ARGUMENT, {
argument: 'salt',
value: salt
});
}
return this.signer.getAddress().then((address) => {
return this._getHashRegistrar(name).then(({ labelHash, registrar }) => {
return registrar.shaBid(labelHash, address, bidAmount, salt).then((sealedBid) => {
return {
address: address,
bidAmount: bidAmount,
salt: utils.hexlify(salt),
sealedBid: sealedBid,
registrar: registrar,
name: name,
labelHash: labelHash
};
});
});
});
}
async placeBid(name: string, amount: ethers.utils.BigNumberish, salt: ethers.utils.Arrayish, extraAmount?: ethers.utils.BigNumberish): Promise<ENSTransactionResponse> {
if (!this.signer) { return Promise.reject(new Error('no signer')); }
let auction = await this.getAuction(name);
let errorMessages: { [state: string]: string } = {
'open': 'name not up for auction yet; please "start" first',
'owned': 'name already owned',
'forbidden': 'name forbidden',
'reveal': 'bidding closed; please "reveal" your bid before ' + getDateTimer(auction.endDate),
// 'not-yet-available': ('name not available until ' + getHumanDate(result.startDate))
};
let errorMessage = errorMessages[auction.state];
if (errorMessage) {
throw new Error(errorMessage);
}
if (!extraAmount) { extraAmount = utils.bigNumberify(0); }
let bidAmount = utils.bigNumberify(amount);
let bid = await this._getBid(name, bidAmount, salt);
let options = {
value: bidAmount.add(extraAmount)
};
let tx = await bid.registrar.connect(this.signer).newBid(bid.sealedBid, options);
tx.metadata = {
bidAmount: bidAmount,
extraAmount: utils.bigNumberify(extraAmount),
name: name,
labelHash: bid.labelHash,
salt: salt,
sealedBid: bid.sealedBid
};
return tx;
}
getDeedAddress(address: string, bidHash: string): Promise<string> {
let addressBytes32 = '0x000000000000000000000000' + address.substring(2);
let position = utils.keccak256(utils.concat([
bidHash,
utils.keccak256(utils.concat([
addressBytes32,
uintify(3)
]))
]));
return this._getHashRegistrar('nothing-important.eth').then(({ labelHash, registrar }) => {
return this.provider.getStorageAt(registrar.address, position).then((value) => {
return '0x' + value.substring(26);
});
});
}
revealBid(name: string, bidAmount: ethers.utils.BigNumberish, salt: ethers.utils.Arrayish): Promise<ENSTransactionResponse> {
if (!this.signer) { return Promise.reject(new Error('no signer')); }
let bid = utils.bigNumberify(bidAmount);
return this._getBid(name, bid, salt).then(({ labelHash, registrar, salt, sealedBid }) => {
return this.signer.getAddress().then((address) => {
return this.getDeedAddress(address, sealedBid).then((deedAddress) => {
/*
if (deedAddress == ethers.constants.AddressZero) {
var error = new Error('bid not found');
(<any>error).address = address;
(<any>error).bid = bid;
(<any>error).name = name;
(<any>error).salt = salt;
(<any>error).sealedBid = sealedBid;
throw error;
}
*/
return registrar.unsealBid(labelHash, bid, salt).then((tx) => {
tx.metadata = {
name: name,
labelHash: labelHash,
salt: salt,
sealedBid: sealedBid,
bidAmount: bid
};
return tx;
});
});
});
});
}
setSubnodeOwner(parentName: string, label: string, owner: string): Promise<ENSTransactionResponse> {
if (!this.signer) { return Promise.reject(new Error('no signer')); }
let nodeHash = utils.namehash(parentName);
let labelHash = utils.keccak256(utils.toUtf8Bytes(label));
return this._getEns().then((ens) => {
return ens.connect(this.signer).setSubnodeOwner(nodeHash, labelHash, owner).then((tx) => {
tx.metadata = {
labelHash: labelHash,
label: label,
nodeHash: nodeHash,
owner: owner,
parentName: parentName,
}
return tx;
});
});
}
getResolver(name: string): Promise<string> {
return this._getEns().then((ens) => {
return ens.resolver(utils.namehash(name)).then((resolverAddress) => {
if (resolverAddress === constants.AddressZero) { return null; }
return resolverAddress;
});
});
}
setResolver(name: string, address: string): Promise<ENSTransactionResponse> {
if (!this.signer) { return Promise.reject(new Error('missing signer')); }
let nodeHash = utils.namehash(name);
return this._getEns().then((ens) => {
return ens.connect(this.signer).setResolver(nodeHash, address).then((tx) => {
tx.metadata = {
address: address,
name: name,
nodeHash: nodeHash
};
return tx;
});
});
}
getOwner(name: string): Promise<string> {
return this._getEns().then((ens) => {
return ens.owner(utils.namehash(name));
});
}
setOwner(name: string, owner: string): Promise<ENSTransactionResponse> {
if (!this.signer) { return Promise.reject(new Error('missing signer')); }
let nodeHash = utils.namehash(name);
return this._getEns().then((ens) => {
return ens.connect(this.signer).setOwner(nodeHash, owner).then((tx) => {
tx.metadata = {
name: name,
owner: owner,
nodeHash: nodeHash
}
return tx;
});
});
}
getDeedOwner(address: string): Promise<string> {
let deedContract = new ethers.Contract(address, deedInterface, this.provider);
return deedContract.functions.owner().then((owner) => {
return owner;
}, function (error) {
return null;
});
}
lookupAddress(address: string): Promise<string> {
return this.provider.lookupAddress(address);
}
resolveName(name: string): Promise<string> {
return this.provider.resolveName(name);
}
async setReverseName(name: string): Promise<ENSTransactionResponse> {
if (!this.signer) { return Promise.reject(new Error('missing signer')); }
let ens = await this._getEns();
let owner = await ens.owner(utils.namehash('addr.reverse'));
let reverseRegistrar: any = new ethers.Contract(owner, interfaces.reverseRegistrar, this.signer);
let tx = await (<ReverseRegistrarContract>reverseRegistrar).setName(name);
tx.metadata = { }
return tx;
}
/*
setAbi(name: string, abi: any): Promise<ENSTransactionResponse> {
var nodeHash = ethers.utils.namehash(name);
return this._getResolver(name, interfaceIds.abi).then((resolver) => {
return resolver.setABI(nodeHash, Registrar.ABIEncoding.JSON, ethers.utils.toUtf8Bytes(abi)).then((tx) => {
tx.metadata = {
encoding: Registrar.ABIEncoding.JSON,
name: name,
nodeHash: nodeHash,
resolver: resolver.address,
abi: abi
}
return transaction;
});
});
}
getAbi(name: string): Promise<ethers.Interface> {
var nodeHash = ethers.utils.namehash(name);
return this._getResolver(name).then((resolver) => {
return resolver.ABI(nodeHash, ABIEncoding.JSON).then(({ contentType, data }) => {
if (contentType === 0) {
// @TODO: fallback onto the address record
return null;
}
return ethers.utils.toUtf8String(data);
}, function (error) {
return null;
});
}, function(error) {
return null;
});
}
*/
setAddress(name: string, addr: string): Promise<ENSTransactionResponse> {
if (!this.signer) { return Promise.reject(new Error('missing signer')); }
let nodeHash = utils.namehash(name);
return this._getResolver(name, interfaceIds.addr).then((resolver) => {
return resolver.connect(this.signer).setAddr(nodeHash, addr).then((tx) => {
tx.metadata = {
addr: addr,
name: name,
nodeHash: nodeHash,
resolver: resolver.address
};
return tx;
});
});
}
getAddress(name: string): Promise<string> {
let nodeHash = utils.namehash(name);
return this._getResolver(name).then(function(resolver) {
return resolver.addr(nodeHash).then(function(addr) {
if (addr === constants.AddressZero) { return null; }
return addr;
}, function (error) {
return null;
});
}, function(error) {
return null;
});
}
setName(address: string, name: string): Promise<ENSTransactionResponse> {
if (!this.signer) { return Promise.reject(new Error('missing signer')); }
let ensName = (utils.getAddress(address).substring(2) + '.addr.reverse').toLowerCase()
let nodeHash = utils.namehash(ensName);
return this._getResolver(ensName, interfaceIds.name).then((resolver) => {
return resolver.connect(this.signer).setName(nodeHash, name).then((tx) => {
tx.metadata = {
addr: address,
name: name,
nodeHash: nodeHash,
resolver: resolver.address
}
return tx;
});
});
}
setPublicKey(name: string, publicKey: string): Promise<ENSTransactionResponse> {
if (!this.signer) { return Promise.reject(new Error('missing signer')); }
let nodeHash = utils.namehash(name);
// Make sure the key is uncompressed, and strip the '0x04' prefix
publicKey = utils.computePublicKey(publicKey, false).substring(4);
let x = '0x' + publicKey.substring(0, 64);
let y = '0x' + publicKey.substring(64, 128);
return this._getResolver(name, interfaceIds.pubkey).then((resolver) => {
return resolver.connect(this.signer).setPubkey(nodeHash, x, y).then((tx) => {
tx.metadata = {
name: name,
nodeHash: nodeHash,
publicKey: publicKey,
resolver: resolver.address
}
return tx;
});
});
}
getPublicKey(name: string, compressed?: boolean): Promise<string> {
let nodeHash = utils.namehash(name);
return this._getResolver(name).then(function(resolverContract) {
return resolverContract.pubkey(nodeHash).then(function(result) {
if (result.x === constants.HashZero && result.y === constants.HashZero) {
return null;
}
return '0x04' + result.x.substring(2) + result.y.substring(2);
}, function (error) {
return null;
});
}, function(error) {
return null;
});
}
setText(name: string, key: string, value: string): Promise<ENSTransactionResponse> {
if (!this.signer) { return Promise.reject(new Error('missing signer')); }
let nodeHash = utils.namehash(name);
return this._getResolver(name, interfaceIds.text).then((resolver) => {
return resolver.connect(this.signer).setText(nodeHash, key, value).then((tx) => {
tx.metadata = {
key: key,
name: name,
nodeHash: nodeHash,
resolver: resolver.address,
text: value
}
return tx;
});
});
}
getText(name: string, key: string): Promise<string> {
let nodeHash = utils.namehash(name);
return this._getResolver(name).then((resolver) => {
return resolver.text(nodeHash, key).then((text) => {
return text;
}, function (error) {
return null;
});
}, function(error) {
return null;
});
}
setContentHash(name: string, contentHash: string): Promise<ENSTransactionResponse> {
if (!this.signer) { return Promise.reject(new Error('missing signer')); }
let comps = contentHash.split("://");
if (comps.length !== 2) { throw new Error("invalid content hash"); }
let bytes: Uint8Array = null;
switch (comps[0]) {
case "bzz":
bytes = utils.concat([ "0x00", ('0x' + comps[1]) ]);
break;
case "ipfs":
bytes = utils.concat([ "0x01", Base58.decode(comps[1]) ]);
break;
default:
throw new Error('unsupported scheme');
}
let nodeHash = utils.namehash(name);
return this._getResolver(name, interfaceIds.contenthash).then((resolver) => {
return resolver.connect(this.signer).setContenthash(nodeHash, bytes).then((tx) => {
tx.metadata = {
name: name,
nodeHash: nodeHash,
resolver: resolver.address,
contentHash: contentHash
}
return tx;
});
});
}
getContentHash(name: string, legacy?: boolean): Promise<string> {
let nodeHash = utils.namehash(name);
return this._getResolver(name).then((resolver) => {
return resolver.contenthash(nodeHash).then((contenthash) => {
let bytes = utils.arrayify(contenthash);
// See: https://github.com/ensdomains/multicodec/blob/master/table.csv
switch (bytes[0]) {
case 0x00:
return "bzz://" + utils.hexlify(bytes.slice(1)).substring(2);
case 0x01:
return "ipfs://" + Base58.encode(bytes.slice(1));
default:
break;
}
throw new Error('unsupported contenthash type - ' + bytes[0]);
}, (error) => {
if (!legacy) { return null; }
return resolver.content(nodeHash).then((content) => {
return "bzz://" + content.substring(2);
}, (error) => {
return null;
});
});
}, function(error) {
return null;
});
}
_getResolver(name: string, interfaceId?: string): Promise<ResolverContract> {
return this.getResolver(name).then((resolverAddress) => {
if (!resolverAddress) { throw new Error('invalid resolver'); }
let resolverContract: any = new ethers.Contract(resolverAddress, interfaces.resolver, this.provider);
let resolver = (<ResolverContract>resolverContract);
if (interfaceId) {
return resolver.supportsInterface(interfaceId).then((supported) => {
if (!supported) { throw new Error('unsupported method'); }
return resolver;
});
}
return resolver;;
});
}
_getEns(): Promise<EnsContract> {
if (!this._ens) {
this._ens = this.provider.getNetwork().then((network) => {
let ens: any = new ethers.Contract(network.ensAddress, interfaces.ens, this.provider);
return (<EnsContract>ens);
});
}
return this._ens;
}
_getHashRegistrar(name: string): Promise<{ registrar: HashRegistrarContract, labelHash: string }> {
let comps = name.toLowerCase().split('.');
// Make sure it is a 2 component name
if (comps.length < 2) {
return Promise.reject('invalid name (must end have at least 2 components)');
}
let label = comps[0]
let tld = comps[1];
if (tld !== 'eth' || label.length < 7 || !label.match(/^[a-z0-9-]*$/)) {
return Promise.reject('invalid name (must be 7 of more character)');
}
if (!this._hashRegistrar) {
this._hashRegistrar = this._getEns().then((ens) => {
return ens.owner(utils.namehash(tld)).then((owner) => {
let hashRegistrar: any = new ethers.Contract(owner, interfaces.hashRegistrar, this.provider);
return (<HashRegistrarContract>hashRegistrar);
});
});
}
return this._hashRegistrar.then((registrar) => {
return {
registrar: registrar,
labelHash: utils.keccak256(utils.toUtf8Bytes(label))
}
});
}
}
/*
Registrar.prototype._getEns = function(name) {
var comps = name.toLowerCase().split('.');
// Make sure it is a 2 component name
if (comps.length !== 2) {
return Promise.reject('invalid name (must end have exactly 2 components)');
}
var label = comps[0];
var tld = comps[1];
// Make sure it is a supported tld
if (tld != 'eth') {
return Promise.reject('invalid name (must end in .eth)');
}
// Must be 7 characters or longer and contain only a-z, 0-0 and the hyphen (-)
if (comps[0].length < 7 || !comps[0].match(/^[a-z0-9-]*$/)) {
return Promise.reject('invalid name (must be 7 of more character)');
}
// A promise (cached) that holds the registrarContract for a given tld
var ownerPromise = this._ensLookup[tld];
if (!ownerPromise) {
var ensContract = new ethers.Contract(this.config.ensAddress, ensInterface, this.provider);
ownerPromise = ensContract.owner(ethers.utils.namehash(tld)).then(function(result) {
return result.owner;
});
this._ensLookup[tld] = ownerPromise;
}
var providerOrSigner = this.signer || this.provider;
return ownerPromise.then(function(owner) {
var registrarContract = new ethers.Contract(owner, registrarInterface, providerOrSigner );
return {
registrarContract: registrarContract,
labelHash: ethers.utils.keccak256(ethers.utils.toUtf8Bytes(label))
}
});
}
*/
//Registrar.prototype.
/*
const isValidName = function(name) {
var comps = name.toLowerCase().split('.');
// Make sure it is a 2 component name
if (comps.length !== 2) { return false; }
// Make sure it is a supported tld
//if (comps[1] != 'eth' || !(comps[1] == 'test' && this.provider.testnet))
if (comps[1] != 'eth') {
return false;
}
// Must be 7 characters or longer and contain only a-z, 0-0 and the hyphen (-)
if (comps[0].length < 7 || !comps[0].match(/^[a-z0-9-]*$/)) { return false; }
return true;
}
*/
//var StringZeros = '0000000000000000000000000000000000000000000000000000000000000000';
/**
* SimpleRegistrar Operations
*
*
*
*/
/*
function SimpleRegistrar(address, registrar) {
this.provider = registrar.provider;
this.signer = registrar.signer;
var providerOrSigner = this.signer || this.provider;
this._simpleRegistrar = new ethers.Contract(address, SimpleRegistrarInterface, providerOrSigner);
}
SimpleRegistrar.prototype.getFee = function() {
return this._simpleRegistrar.fee().then(function(result) {
return result.fee;
});
}
SimpleRegistrar.prototype.register = function(label, value) {
var options = {
gasLimit: 250000,
value: (value || 0)
};
return this._simpleRegistrar.register(label, options).then(function(result) {
result.label = label;
return result;
});
}
Registrar.prototype.getSimpleRegistrar = function(name) {
var self = this;
return this.getAddress(name).then(function(address) {
if (!address) { return null; }
return new SimpleRegistrar(address, self);
});
}
*/
/**
* Event API (experimental)
*/
/*
Registrar.prototype.on = function(event, callback) {
this._getEns('nothing-important.eth').then(function(result) {
result.registrarContract['on' + event.toLowerCase()] = callback;
});
}
*/
// Export for Browsers
let _e = (<any>global).ethers;
if (_e && _e.platform === 'browser' && !_e.ENS) {
_e.ENS = ENS;
} | the_stack |
declare namespace Domain {
// region AggregateModel and Command
interface AggregateModel {
id: string;
attributes: any;
uncommittedEvents: any[];
apply(event: any, data?: any, version?: number): void;
/**
* Sets attributes for the aggregate.
*
* @example:
* aggregate.set('firstname', 'Jack');
* // or
* aggregate.set({
* firstname: 'Jack',
* lastname: 'X-Man'
* });
*/
set(attribute: any, value?: any): void;
/**
* Gets an attribute of the vm.
* @param attr The attribute name.
* @return The result value.
*
* @example:
* aggregate.get('firstname'); // returns 'Jack'
*/
get(attr: string): any;
/**
* Returns `true` if the attribute contains a value that is not null
* or undefined.
* @param attr The attribute name.
* @return The result value.
*
* @example:
* aggregate.has('firstname'); // returns true or false
*/
has(attr: string): boolean;
/**
* Resets the attributes for the aggregate.
*/
reset(data: any): void;
/**
* Marks this aggregate as destroyed.
*/
destroy(): void;
/**
* Returns true if this aggregate is destroyed.
*/
isDestroyed(): boolean;
/**
* Sets the revision for this aggregate.
* @param streamInfo The stream info.
* @param rev The revision number.
*/
setRevision(streamInfo: any, rev: number): void;
/**
* Returns the revision of this aggregate.
* @param streamInfo The stream info.
*/
getRevision(streamInfo: any): number;
/**
* Returns all uncommitted events.
*/
getUncommittedEvents(): any[];
/**
* Adds/Saves an uncommitted event.
* @param evt The event object.
*/
addUncommittedEvent(evt: any): void;
/**
* Clears the internal uncomitted event list.
*/
clearUncommittedEvents(): void;
/**
* The toJSON function will be called when JSON.stringify().
* @return A clean Javascript object containing all attributes.
*/
toJSON(): any;
}
interface Command {
id: string;
}
// endregion
// region defineContext
interface DefineContextOptions {
/**
* optional, default is the directory name
*/
name?: string;
}
function defineContext(options: DefineAggregateOptions): void;
// endregion
// region defineAggregate
interface DefineAggregateOptions {
/**
* optional, default is last part of path name
*/
name?: string;
/**
* optional, default 0
*/
version?: number;
/**
* optional, default ''
*/
defaultCommandPayload?: string;
/**
* optional, default ''
*/
defaultEventPayload?: string;
/**
* optional, default ''
*/
defaultPreConditionPayload?: string;
/**
* optional, default false
* by skipping the history, only the last event will be loaded and defaultly not applyed (just to ensure the revision number increment)
*/
skipHistory?: boolean;
/**
* optional, default false
* only optionally needed when skipHistory is set to true, only the last event will be loaded and applyed
*/
applyLastEvent?: boolean;
/**
* optional, default false
* will publish the events but will not commit them to the eventstore
*/
disablePersistence?: boolean;
}
/**
* @param loadingTime is the loading time in ms of the eventstore data
* @param events are all loaded events in an array
* @param aggregateData represents the aggregateData after applying the resulting events
*/
type defineSnapshotNeedHandler = (loadingTime: number, events: any[], aggregateData: any) => boolean;
interface AggregateVersion {
version: number;
}
interface DefineAggregateResult {
/**
* optionally, define snapshot need algorithm...
*/
defineSnapshotNeed(cb: defineSnapshotNeedHandler): DefineAggregateResult;
/**
* optionally, define if snapshot should be ignored
* if true, the whole event stream will be loaded
*/
defineIgnoreSnapshot(version: AggregateVersion, cb?: ((data: any) => boolean) |
boolean): DefineAggregateResult;
/**
* optionally, define conversion algorithm for older snapshots
* always convert directly to newest version...
* when loaded a snapshot and it's an older snapshot, a new snapshot with same revision but with newer aggregate version will be created
*/
defineSnapshotConversion(version: AggregateVersion, cb: (data: any, aggregate: AggregateModel) => void): DefineAggregateResult;
/**
* optionally, define idGenerator function for new aggregate ids
*/
defineAggregateIdGenerator(cb: (() => string) |
((callback: generateIdCallback) => string)): DefineAggregateResult;
/**
* optionally, define idGenerator function for new aggregate ids that are command aware
* if you define it that way, the normal defineAggregateIdGenerator function will be replaced
*/
defineCommandAwareAggregateIdGenerator(cb: (cmd: Command, callback?: generateIdCallback) => string): DefineAggregateResult;
}
function defineAggregate(options: DefineAggregateOptions, initializationData?: any): DefineAggregateResult;
// endregion
// region extendValidator
function extendValidator(cb: (validator: any) => void): void;
// endregion
// region definePreCondition
interface DefinePreLoadConditionOptions {
/**
* the command name
* optional, default is file name without extension,
* if name is '' it will handle all commands that matches the appropriate aggregate
* if name is an array of strings it will handle all commands that matches the appropriate name
*/
name?: string;
/**
* optional, default 0
*/
version?: number;
/**
* optional, if not defined it will use what is defined as default in aggregate or pass the whole command
*/
payload?: string;
/**
* optional
*/
description?: string;
/**
* optional, default Infinity, all pre-conditions will be sorted by this value
*/
priority?: number;
}
/**
* @param data is the command data
* @param callback is optional, if not defined as function argument you can throw errors or return errors here (sync way)
*/
type preLoadConditionHandler = (data: any, callback?: (err: string | Error) => string | Error) => void | string | Error;
function definePreLoadCondition(options: DefinePreLoadConditionOptions, handler: preLoadConditionHandler): void;
// endregion
// region definePreCondition
interface DefinePreConditionOptions {
/**
* the command name
* optional, default is file name without extension,
* if name is '' it will handle all commands that matches the appropriate aggregate
* if name is an array of strings it will handle all commands that matches the appropriate name
*/
name?: string;
/**
* optional, default 0
*/
version?: number;
/**
* optional, if not defined it will use what is defined as default in aggregate or pass the whole command
*/
payload?: string;
/**
* optional
*/
description?: string;
/**
* optional, default Infinity, all pre-conditions will be sorted by this value
*/
priority?: number;
}
/**
* @param data is the command data
* @param aggregate is the aggregate object
* @param callback is optional, if not defined as function argument you can throw errors or return errors here (sync way)
*/
type preConditionHandler = (data: any, aggregate: AggregateModel, callback?: (err: string | Error) => string | Error) => void | string | Error;
function definePreCondition(options: DefinePreConditionOptions, handler: preConditionHandler): void;
// endregion
// region defineCommand
interface DefineCommandOptions {
name?: string;
version?: number;
payload?: string;
existing?: boolean;
}
type commandHandler = (data: any, aggregate: AggregateModel) => void;
type defineEventStreamsToLoadHandler = (cmd: any) => Array<{
context: string;
aggregate: string;
aggregateId: string;
}>;
interface DefineCommandResult {
defineEventStreamsToLoad(cb: defineEventStreamsToLoadHandler): void;
}
function defineCommand(options: DefineCommandOptions, handler: commandHandler): DefineCommandResult;
// endregion
// region defineEvent
interface DefineEventOptions {
name?: string;
version?: number;
payload?: string;
}
type eventHandler = (data: any, aggregate: AggregateModel) => void;
function defineEvent(options: DefineEventOptions, handler: eventHandler): void;
// endregion
// region defineBusinessRule
interface DefineBusinessRuleOptions {
/**
* optional, default is file name without extension
*/
name?: string;
/**
* optional
*/
description?: string;
/**
* optional, default Infinity, all business rules will be sorted by this value
*/
priority?: number;
}
/**
* @param changed is the new aggregate object
* @param previous is the old aggregate object
* @param events is the array with the resulting events
* @param command the handling command
* @param callback is optional, if not defined as function argument you can throw errors or return errors here (sync way)
*/
type businessRuleHandler = (changed: AggregateModel, previous: AggregateModel, command: any, callback?: (err: string | Error) => string | Error) => void | string | Error;
function defineBusinessRule(options: DefineBusinessRuleOptions, handler: businessRuleHandler): void;
// endregion
// region defineCommandHandler
interface DefineCommandHandlerOptions {
/**
* optional, default is file name without extension
*/
name?: string;
/**
* optional, default 0
*/
version?: number;
/**
* optional, if not defined it will pass the whole command...
*/
payload?: string;
}
/**
* @param aggId is the aggregate id
* @param cmd is the command data
* @param callback is optional, if not defined as function argument you can throw errors or return errors here (sync way)
*/
type commandHandlerHandler = (aggId: string, cmd: any, commandHandler: any, callback?: (err: string | Error) => string | Error) => void | string | Error;
function defineCommandHandler(options: DefineCommandHandlerOptions, handler: commandHandlerHandler): void;
// endregion
// region Domain itself
interface CommandDefinition {
/**
* optional, default is 'id'
*/
id?: string;
/**
* optional, default is 'name'
*/
name?: string;
/**
* optional, default is 'aggregate.id'
* if an aggregate id is not defined in the command, the command handler will create a new aggregate instance
*/
aggregateId?: string;
/**
* optional, only makes sense if contexts are defined in the 'domainPath' structure
*/
context?: string;
/**
* optional, only makes sense if aggregates with names are defined in the 'domainPath' structure
*/
aggregate?: string;
/**
* optional, but recommended
*/
payload?: string;
/**
* optional, if defined the command handler will check if the command can be handled
* if you want the command to be handled in a secure/transactional way pass a revision value that matches the current aggregate revision
*/
revision?: string;
/**
* optional, if defined the command handler will search for a handle that matches command name and version number
*/
version?: string;
/**
* optional, if defined theses values will be copied to the event (can be used to transport information like userId, etc..)
*/
meta?: string;
}
interface EventDefinition {
/**
* optional, default is 'correlationId'
* will use the command id as correlationId, so you can match it in the sender
*/
correlationId?: string;
/**
* optional, default is 'id'
*/
id?: string;
/**
* optional, default is 'name'
*/
name?: string;
/**
* optional, default is 'aggregate.id'
*/
aggregateId?: string;
/**
* optional, only makes sense if contexts are defined in the 'domainPath' structure
*/
context?: string;
/**
* optional, only makes sense if aggregates with names are defined in the 'domainPath' structure
*/
aggregate?: string;
/**
* optional, default is 'payload'
*/
payload?: string;
/**
* optional, default is 'revision'
* will represent the aggregate revision, can be used in next command
*/
revision?: string;
/**
* optional
*/
version?: string;
/**
* optional, if defined the values of the command will be copied to the event (can be used to transport information like userId, etc..)
*/
meta?: string;
/**
* optional, if defined the commit date of the eventstore will be saved in this value
*/
commitStamp?: string;
}
type generateIdCallback = (err: any, id: string) => void;
interface HandleMetaInfos {
aggregateId: string;
aggregate: string;
context: string;
}
interface CqrsDomain {
/**
* Inject definition for command structure.
* @param definition the definition to be injected
* @returns to be able to chain...
*/
defineCommand(definition: CommandDefinition): CqrsDomain;
/**
* Inject definition for event structure.
* @param definition the definition to be injected
* @returns to be able to chain...
*/
defineEvent(definition: EventDefinition): CqrsDomain;
/**
* Call this function to initialize the domain.
* @param callback the function that will be called when this action has finished [optional]
* `function(err, warnings){}`
*/
init(cb: (err: Error, warnings: Error[]) => void): void;
/**
* Call this function to let the domain handle it.
* @param cmd the command object
* @param callback the function that will be called when this action has finished [optional]
* `function(err, evts, aggregateData, meta){}` evts is of type Array, aggregateData and meta are an object
*/
handle(cmd: any,
cb?: ((err: Error) => void) |
((err: Error, events: any[], aggregateData: any, metaInfos: HandleMetaInfos) => void)): void;
/**
* Returns the domain information.
*/
getInfo(): any;
/**
* Inject function for for event notification.
* @param fn the function to be injected
* @returns to be able to chain...
*/
onEvent(cb: ((evt: any) => void) |
((evt: any, callback: () => void) => void)): CqrsDomain;
/**
* Inject idGenerator function.
* @param fn The function to be injected.
* @returns to be able to chain...
*/
idGenerator(cb: (() => string) |
((callback: generateIdCallback) => string)): CqrsDomain;
/**
* Inject idGenerator function for aggregate id.
* @param fn The function to be injected.
* @returns to be able to chain...
*/
aggregateIdGenerator(cb: (() => string) |
((callback: generateIdCallback) => string)): CqrsDomain;
/**
* Converts an error to the commandRejected event
* @param cmd The command that was handled.
* @param err The error that occurs.
* @returns The resulting event.
*/
createCommandRejectedEvent(cmd: any, err: Error): any;
/**
* Is called when dispatched a command.
* @param cmd the command object
* @param err the error
* @param eventsToDispatch the events to dispatch
* @param aggregateData the aggregate data
* @param meta the meta infos
* @param callback the function that will be called when this action has finished [optional]
* `function(err, evts, aggregateData, meta){}` evts is of type Array, aggregateData and meta are an object
*/
onDispatched(cmd: any, err: Error, eventsToDispatch: any[], aggregateData: any, meta: any, callback: (err: Error, evts: any[], aggregateData: any, meta: any) => void): void;
}
type SupportedDBTypes = "mongodb" | "redis" | "tingodb" | "azuretable" | "inmemory";
interface CreateDomainOptions {
/**
* the path to the "working directory"
* can be structured like
* [set 1](https://github.com/adrai/node-cqrs-domain/tree/master/test/integration/fixture/set1) or
* [set 2](https://github.com/adrai/node-cqrs-domain/tree/master/test/integration/fixture/set2)
*/
domainPath: string;
/**
* optional, default is 'commandRejected'
* will be used if an error occurs and an event should be generated
*/
commandRejectedEventName?: string;
/**
* optional, default is 800
* if using in scaled systems and not guaranteeing that each command for an aggregate instance
* dispatches to the same worker process, this module tries to catch the concurrency issues and
* retries to handle the command after a timeout between 0 and the defined value
*/
retryOnConcurrencyTimeout?: number;
/**
* optional, default is 100
* global snapshot threshold value for all aggregates
* defines the amount of loaded events, if there are more events to load, it will do a snapshot, so next loading is faster
* an individual snapshot threshold defining algorithm can be defined per aggregate (scroll down)
*/
snapshotThreshold?: number;
/**
* optional, default is in-memory
* currently supports: mongodb, redis, tingodb, azuretable and inmemory
* hint: [eventstore](https://github.com/adrai/node-eventstore#provide-implementation-for-storage)
*/
eventStore?: {
type: SupportedDBTypes,
host?: string;
port?: number,
dbName?: string;
eventsCollectionName?: string;
snapshotsCollectionName?: string;
transactionsCollectionName?: string;
timeout?: number;
authSource?: string;
username?: string;
password?: string;
url?: string;
};
/**
* optional, default is in-memory
* currently supports: mongodb, redis, tingodb, couchdb, azuretable, dynamodb and inmemory
* hint settings like: [eventstore](https://github.com/adrai/node-eventstore#provide-implementation-for-storage)
*/
aggregateLock?: {
type: SupportedDBTypes,
host?: string;
port?: number;
db: number;
prefix?: string;
timeout?: number;
password?: string;
};
/**
* optional, default is not set
* checks if command was already seen in the last time -> ttl
* currently supports: mongodb, redis, tingodb and inmemory
* hint settings like: [eventstore](https://github.com/adrai/node-eventstore#provide-implementation-for-storage)
*/
deduplication?: {
type: "mongodb" | "redis" | "tingodb" | "inmemory",
ttl?: number;
host?: string;
port?: number;
db?: number;
prefix?: string;
timeout?: number;
password?: string;
};
/**
* optional, default false
* resolves valid file types from loader extensions instead of default values while parsing definition files
*/
useLoaderExtensions?: true;
}
// endregion
}
declare function Domain(options: Domain.CreateDomainOptions): Domain.CqrsDomain;
export = Domain; | the_stack |
import { CasingConvention } from "../../../Utility/ObjectUtil";
import { DocumentConventions } from "../../../Documents/Conventions/DocumentConventions";
import { throwError } from "../../../Exceptions";
export type TransformJsonKeysProfile =
"CommandResponsePayload"
| "NoChange"
| "DocumentLoad"
| "FacetQuery"
| "Patch"
| "CompareExchangeValue"
| "GetCompareExchangeValue"
| "SubscriptionResponsePayload"
| "SubscriptionRevisionsResponsePayload";
function getSimpleKeysTransform(convention: CasingConvention) {
return {
getCurrentTransform(key: string, stack: (string | number | null)[]): CasingConvention {
return convention;
}
};
}
export function getTransformJsonKeysProfile(
profile: TransformJsonKeysProfile, conventions?: DocumentConventions): { getCurrentTransform: (key: any, stack: any) => CasingConvention } {
if (profile === "CommandResponsePayload") {
return getSimpleKeysTransform("camel");
}
if (profile === "NoChange") {
return getSimpleKeysTransform(null);
}
if (profile === "DocumentLoad") {
if (!conventions) {
throwError("InvalidArgumentException", "Document conventions are required for this profile.");
}
const getCurrentTransform = buildEntityKeysTransformForDocumentLoad(conventions.entityFieldNameConvention);
return { getCurrentTransform };
}
if (profile === "FacetQuery") {
return {
getCurrentTransform: facetQueryGetTransform
};
}
if (profile === "Patch") {
if (!conventions) {
throwError("InvalidArgumentException", "Document conventions are required for this profile.");
}
return {
getCurrentTransform:
buildEntityKeysTransformForPatch(conventions.entityFieldNameConvention)
};
}
if (profile === "CompareExchangeValue") {
if (!conventions) {
throwError("InvalidArgumentException", "Document conventions are required for this profile.");
}
return {
getCurrentTransform:
buildEntityKeysTransformForPutCompareExchangeValue(conventions.entityFieldNameConvention)
};
}
if (profile === "GetCompareExchangeValue") {
if (!conventions) {
throwError("InvalidArgumentException", "Document conventions are required for this profile.");
}
return {
getCurrentTransform:
buildEntityKeysTransformForGetCompareExchangeValue(conventions.entityFieldNameConvention)
};
}
if (profile === "SubscriptionResponsePayload") {
if (!conventions) {
throwError("InvalidArgumentException", "Document conventions are required for this profile.");
}
return {
getCurrentTransform:
buildEntityKeysTransformForSubscriptionResponsePayload(conventions.entityFieldNameConvention)
};
}
if (profile === "SubscriptionRevisionsResponsePayload") {
if (!conventions) {
throwError("InvalidArgumentException", "Document conventions are required for this profile.");
}
return {
getCurrentTransform:
buildEntityKeysTransformForSubscriptionRevisionsResponsePayload(
conventions.entityFieldNameConvention)
};
}
throwError("NotSupportedException", `Invalid profile name ${profile}`);
}
function facetQueryGetTransform(key, stack): CasingConvention {
const len = stack.length;
if (stack[0] === "Includes") {
if (len >= 3 && stack[2] === "@metadata") {
return handleMetadataJsonKeys(key, stack, stack.length, 3);
}
}
return "camel";
}
function buildEntityKeysTransformForPatch(entityCasingConvention) {
return function entityKeysTransform(key, stack) {
const len = stack.length;
if (len === 1) {
return "camel";
}
const isDoc = stack[0] === "OriginalDocument" || stack[0] === "ModifiedDocument";
if (isDoc) {
if (len === 2) {
// top document level
return key === "@metadata" ? null : entityCasingConvention;
}
if (len === 3) {
if (stack[1] === "@metadata") {
// handle @metadata object keys
if (key[0] === "@" || key === "Raven-Node-Type") {
return null;
}
}
}
if (len === 4) {
// do not touch @nested-object-types keys
if (stack[len - 2] === "@nested-object-types") {
return null;
}
}
if (len === 5) {
// @metadata.@attachments.[].name
if (stack[1] === "@metadata") {
if (stack[2] === "@attachments") {
return "camel";
}
return null;
}
}
return entityCasingConvention;
}
return "camel";
};
}
function buildEntityKeysTransformForPutCompareExchangeValue(entityCasingConvention) {
return function compareExchangeValueTransform(key, stack) {
const len = stack.length;
if (len === 1 || len === 2) {
// Results, Includes
return "camel";
}
// len === 2 is array index
if (len === 3) {
// top document level
return key === "@metadata" ? null : entityCasingConvention;
}
if (len === 4) {
if (stack[2] === "@metadata") {
// handle @metadata object keys
if (key[0] === "@" || key === "Raven-Node-Type") {
return null;
}
}
}
if (len === 5) {
// do not touch @nested-object-types keys
if (stack[len - 2] === "@nested-object-types") {
return null;
}
}
if (len === 6) {
// @metadata.@attachments.[].name
if (stack[2] === "@metadata") {
if (stack[3] === "@attachments") {
return "camel";
}
return null;
}
}
return entityCasingConvention;
};
}
function buildEntityKeysTransformForGetCompareExchangeValue(entityCasingConvention) {
return function getCompareExchangeValueTransform(key, stack) {
const len = stack.length;
if (stack[0] === "Results") {
if (stack[2] === "Value" && stack[3] === "@metadata") {
return handleMetadataJsonKeys(key, stack, len, 4);
}
}
if (len <= 4) {
return "camel";
}
return entityCasingConvention;
};
}
function buildEntityKeysTransformForSubscriptionResponsePayload(entityCasingConvention) {
return function entityKeysTransform(key, stack) {
const len = stack.length;
if (len === 1) {
// type, Includes
return "camel";
}
if (stack[0] === "Data") {
if (stack[1] === "@metadata") {
return handleMetadataJsonKeys(key, stack, len, 2);
}
return entityCasingConvention;
} else if (stack[0] === "Includes") {
if (stack[2] === "@metadata") {
return handleMetadataJsonKeys(key, stack, len, 2);
}
return entityCasingConvention;
} else if (stack[0] === "CounterIncludes") {
if (len === 2) {
return null;
}
} else if (stack[0] === "IncludedCounterNames") {
if (len === 2) {
return null;
}
}
return "camel";
};
}
function buildEntityKeysTransformForSubscriptionRevisionsResponsePayload(entityCasingConvention) {
return function entityKeysTransform(key, stack) {
const len = stack.length;
if (len === 1) {
// type, Includes
return "camel";
}
const isData = stack[0] === "Data";
if (isData && stack[1] === "@metadata") {
return handleMetadataJsonKeys(key, stack, len, 2);
}
if (isData && (stack[1] === "Current" || stack[1] === "Previous")) {
if (len === 2) {
return "camel";
}
if (stack[2] === "@metadata") {
return handleMetadataJsonKeys(key, stack, len, 3);
}
return entityCasingConvention;
}
if (stack[0] === "CounterIncludes") {
if (len === 2) {
return null;
}
}
return "camel";
};
}
function buildEntityKeysTransformForDocumentLoad(entityCasingConvention) {
return function entityKeysTransform(key, stack) {
const len = stack.length;
if (len === 1) {
// Results, Includes
return "camel";
}
// len === 2 is array index
if (len === 2) {
if (stack[0] === "CounterIncludes") {
return null;
}
}
if (len === 3) {
if (stack[0] === "CompareExchangeValueIncludes") {
return "camel";
}
// top document level
return key === "@metadata" ? null : entityCasingConvention;
}
if (len === 4) {
if (stack[0] === "CounterIncludes") {
return "camel";
}
if (stack[0] === "CompareExchangeValueIncludes" && stack[2] === "Value" && stack[3] === "Object") {
return "camel";
}
if (stack[2] === "@metadata") {
// handle @metadata object keys
if (key[0] === "@" || key === "Raven-Node-Type") {
return null;
}
}
}
if (len === 5) {
// do not touch @nested-object-types keys
if (stack[len - 2] === "@nested-object-types") {
return null;
}
if (stack[0] === "TimeSeriesIncludes") {
return "camel";
}
}
if (len === 6) {
// @metadata.@attachments.[].name
if (stack[2] === "@metadata") {
if (stack[3] === "@attachments") {
return "camel";
}
return null;
}
}
if (len === 7) {
if (stack[0] === "TimeSeriesIncludes") {
return "camel";
}
}
return entityCasingConvention;
};
}
function handleMetadataJsonKeys(key: string, stack: string[], stackLength: number, metadataKeyLevel: number): CasingConvention {
if (stackLength === metadataKeyLevel) {
return null; // don't touch @metadata key
}
if (stackLength === metadataKeyLevel + 1) {
if (key[0] === "@" || key === "Raven-Node-Type") {
return null;
}
}
if (stackLength === metadataKeyLevel + 2) {
// do not touch @nested-object-types keys
if (stack[stackLength - 2] === "@nested-object-types") {
return null;
}
}
if (stackLength === metadataKeyLevel + 3) {
// @metadata.@attachments.[].name
// metadataKeyLevel starts at 1, thus we do -1 to get index
if (stack[metadataKeyLevel - 1] === "@metadata") {
if (stack[metadataKeyLevel - 1 + 1] === "@attachments") {
return "camel";
}
return null;
}
}
return null;
} | the_stack |
import { QRCodeVersion, ErrorCorrectionLevel } from '../barcode/enum/enum';
/**
* Qrcode used to calculate the Qrcode control
*/
export class PdfQRBarcodeValues {
/**
* Holds the Version Information.
*/
private mVersion: QRCodeVersion;
/**
* Holds the Error Correction Level.
*/
private mErrorCorrectionLevel: ErrorCorrectionLevel;
/**
* Holds the Number of Data code word.
*/
private mNumberOfDataCodeWord: number;
/**
* Holds the Number of Error correcting code words.
*/
private mNumberOfErrorCorrectingCodeWords: number;
/**
* Holds the Number of Error correction Blocks.
*/
private mNumberOfErrorCorrectionBlocks: number[];
/**
* Holds the End value of the version.
*/
private mEnd: number;
/**
* Holds the Data copacity of the version.
*/
private mDataCapacity: number;
/**
* Holds the Format Information.
*/
private mFormatInformation: number[];
/**
* Holds the Version Information.
*/
private mVersionInformation: number[];
/**
* Holds all the values of Error correcting code words.
*/
private numberOfErrorCorrectingCodeWords: number[] = [
7, 10, 13, 17,
10, 16, 22, 28,
15, 26, 36, 44,
20, 36, 52, 64,
26, 48, 72, 88,
36, 64, 96, 112,
40, 72, 108, 130,
48, 88, 132, 156,
60, 110, 160, 192,
72, 130, 192, 224,
80, 150, 224, 264,
96, 176, 260, 308,
104, 198, 288, 352,
120, 216, 320, 384,
132, 240, 360, 432,
144, 280, 408, 480,
168, 308, 448, 532,
180, 338, 504, 588,
196, 364, 546, 650,
224, 416, 600, 700,
224, 442, 644, 750,
252, 476, 690, 816,
270, 504, 750, 900,
300, 560, 810, 960,
312, 588, 870, 1050,
336, 644, 952, 1110,
360, 700, 1020, 1200,
390, 728, 1050, 1260,
420, 784, 1140, 1350,
450, 812, 1200, 1440,
480, 868, 1290, 1530,
510, 924, 1350, 1620,
540, 980, 1440, 1710,
570, 1036, 1530, 1800,
570, 1064, 1590, 1890,
600, 1120, 1680, 1980,
630, 1204, 1770, 2100,
660, 1260, 1860, 2220,
720, 1316, 1950, 2310,
750, 1372, 2040, 2430
];
/**
* Hexadecimal values of CP437 characters
*/
private cp437CharSet: string[] = ['2591', '2592', '2593', '2502', '2524', '2561', '2562', '2556', '2555', '2563', '2551', '2557',
'255D', '255C', '255B', '2510', '2514', '2534', '252C', '251C', '2500', '253C', '255E', '255F', '255A', '2554', '2569', '2566',
'2560', '2550', '256C', '2567', '2568', '2564', '2565', '2559', '2558', '2552', '2553', '256B', '256A', '2518', '250C', '2588',
'2584', '258C', '2590', '2580', '25A0'];
/**
* Hexadecimal values of ISO8859_2 characters
*/
private iso88592CharSet: string[] = ['104', '2D8', '141', '13D', '15A', '160', '15E', '164', '179', '17D', '17B', '105', '2DB',
'142', '13E', '15B', '2C7', '161', '15F', '165', '17A', '2DD', '17E', '17C', '154', '102', '139', '106', '10C', '118', '11A',
'10E', '110', '143', '147', '150', '158', '16E', '170', '162', '155', '103', '13A', '107', '10D', '119', '11B', '10F', '111',
'144', '148', '151', '159', '16F', '171', '163', '2D9'];
/**
* Hexadecimal values of ISO8859_3 characters
*/
private iso88593CharSet: string[] = ['126', '124', '130', '15E', '11E', '134', '17B', '127', '125', '131', '15F', '11F', '135',
'17C', '10A', '108', '120', '11C', '16C', '15C', '10B', '109', '121', '11D', '16D', '15D'];
/**
* Hexadecimal values of ISO8859_4 characters
*/
private iso88594CharSet: string[] = ['104', '138', '156', '128', '13B', '160', '112', '122', '166', '17D', '105', '2DB', '157',
'129', '13C', '2C7', '161', '113', '123', '167', '14A', '17E', '14B', '100', '12E', '10C', '118', '116', '12A', '110', '145',
'14C', '136', '172', '168', '16A', '101', '12F', '10D', '119', '117', '12B', '111', '146', '14D', '137', '173', '169', '16B'];
/**
* Hexadecimal values of Windows1250 characters
*/
private windows1250CharSet: string[] = ['141', '104', '15E', '17B', '142', '105', '15F', '13D', '13E', '17C'];
/**
* Hexadecimal values of Windows1251 characters
*/
private windows1251CharSet: string[] = ['402', '403', '453', '409', '40A', '40C', '40B', '40F', '452', '459', '45A', '45C', '45B',
'45F', '40E', '45E', '408', '490', '401', '404', '407', '406', '456', '491', '451', '454', '458', '405', '455', '457'];
/**
* Hexadecimal values of Windows1252 characters
*/
private windows1252CharSet: string[] = ['20AC', '201A', '192', '201E', '2026', '2020', '2021', '2C6', '2030', '160', '2039', '152',
'17D', '2018', '2019', '201C', '201D', '2022', '2013', '2014', '2DC', '2122', '161', '203A', '153', '17E', '178'];
/**
* Hexadecimal values of Windows1256 characters
*/
private windows1256CharSet: string[] = ['67E', '679', '152', '686', '698', '688', '6AF', '6A9', '691', '153', '6BA', '6BE', '6C1',
'644', '645', '646', '647', '648', '649', '64A', '6D2'];
/**
* Equivalent values of CP437 characters
*/
private cp437ReplaceNumber: number[] = [176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218,
219, 220, 221, 222, 223, 254];
/**
* Equivalent values of ISO8859_2 characters
*/
private iso88592ReplaceNumber: number[] = [161, 162, 163, 165, 166, 169, 170, 171, 172, 174, 175, 177, 178, 179, 181, 182, 183,
185, 186, 187, 188, 189, 190, 191, 192, 195, 197, 198, 200, 202, 204, 207, 208, 209, 210, 213, 216, 217, 219, 222, 224,
227, 229, 230, 232, 234, 236, 239, 240, 241, 242, 245, 248, 249, 251, 254, 255];
/**
* Equivalent values of ISO8859_3 characters
*/
private iso88593ReplaceNumber: number[] = [161, 166, 169, 170, 171, 172, 175, 177, 182, 185, 186, 187, 188, 191, 197, 198,
213, 216, 221, 222, 229, 230, 245, 248, 253, 254];
/**
* Equivalent values of ISO8859_4 characters
*/
private iso88594ReplaceNumber: number[] = [161, 162, 163, 165, 166, 169, 170, 171, 172, 174, 177, 178, 179, 181, 182, 183,
185, 186, 187, 188, 189, 190, 191, 192, 199, 200, 202, 204, 207, 208, 209, 210, 211, 217, 221, 222, 224, 231, 232, 234,
236, 239, 240, 241, 242, 243, 249, 253, 254];
/**
* Equivalent values of Windows1250 characters
*/
private windows1250ReplaceNumber: number[] = [163, 165, 170, 175, 179, 185, 186, 188, 190, 191];
/**
* Equivalent values of Windows1251 characters
*/
private windows1251ReplaceNumber: number[] = [128, 129, 131, 138, 140, 141, 142, 143, 144, 154, 156, 157, 158, 159, 161, 162,
163, 165, 168, 170, 175, 178, 179, 180, 184, 186, 188, 189, 190, 191];
/**
* Equivalent values of Windows1252 characters
*/
private windows1252ReplaceNumber: number[] = [128, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 145, 146, 147,
148, 149, 150, 151, 152, 153, 154, 155, 156, 158, 159];
/**
* Equivalent values of Windows1256 characters
*/
private windows1256ReplaceNumber: number[] = [129, 138, 140, 141, 142, 143, 144, 152, 154, 156, 159, 170, 192, 225, 227, 228,
229, 230, 236, 237, 255];
/**
* Holds all the end values.
*/
/** @private */
public endValues: number[] = [208, 359, 567, 807, 1079, 1383, 1568, 1936, 2336, 2768, 3232, 3728, 4256, 4651, 5243, 5867, 6523,
7211, 7931, 8683, 9252, 10068, 10916, 11796, 12708, 13652, 14628, 15371, 16411, 17483, 18587, 19723, 20891, 22091, 23008,
24272, 25568, 26896, 28256, 29648];
/**
* Holds all the Data capacity values.
*/
/** @private */
public dataCapacityValues: number[] = [26, 44, 70, 100, 134, 172, 196, 242, 292, 346, 404, 466, 532, 581, 655, 733, 815, 901,
991, 1085, 1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185, 2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362,
3532, 3706];
/**
* Holds all the Numeric Data capacity of the Error correction level Low.
*/
/** @private */
public numericDataCapacityLow: number[] = [41, 77, 127, 187, 255, 322, 370, 461, 552, 652, 772, 883, 1022, 1101, 1250, 1408,
1548, 1725, 1903, 2061, 2232, 2409, 2620, 2812, 3057, 3283, 3517, 3669, 3909, 4158, 4417, 4686, 4965, 5253, 5529, 5836,
6153, 6479, 6743, 7089];
/**
* Holds all the Numeric Data capacity of the Error correction level Medium.
*/
/** @private */
public numericDataCapacityMedium: number[] = [34, 63, 101, 149, 202, 255, 293, 365, 432, 513, 604, 691, 796, 871, 991, 1082,
1212, 1346, 1500, 1600, 1708, 1872, 2059, 2188, 2395, 2544, 2701, 2857, 3035, 3289, 3486, 3693, 3909, 4134, 4343, 4588,
4775, 5039, 5313, 5596];
/**
* Holds all the Numeric Data capacity of the Error correction level Quartile.
*/
/** @private */
public numericDataCapacityQuartile: number[] = [27, 48, 77, 111, 144, 178, 207, 259, 312, 364, 427, 489, 580, 621, 703, 775,
876, 948, 1063, 1159, 1224, 1358, 1468, 1588, 1718, 1804, 1933, 2085, 2181, 2358, 2473, 2670, 2805, 2949, 3081, 3244,
3417, 3599, 3791, 3993];
/**
* Holds all the Numeric Data capacity of the Error correction level High.
*/
/** @private */
public numericDataCapacityHigh: number[] = [17, 34, 58, 82, 106, 139, 154, 202, 235, 288, 331, 374, 427, 468, 530, 602,
674, 746, 813, 919, 969, 1056, 1108, 1228, 1286, 1425, 1501, 1581, 1677, 1782, 1897, 2022, 2157, 2301, 2361, 2524,
2625, 2735, 2927, 3057];
/**
* Holds all the Alpha numeric Data capacity of the Error correction level Low.
*/
/** @private */
public alphanumericDataCapacityLow: number[] = [25, 47, 77, 114, 154, 195, 224, 279, 335, 395, 468, 535, 619, 667, 758,
854, 938, 1046, 1153, 1249, 1352, 1460, 1588, 1704, 1853, 1990, 2132, 2223, 2369, 2520, 2677, 2840, 3009, 3183, 3351,
3537, 3729, 3927, 4087, 4296];
/**
* Holds all the Alpha numeric Data capacity of the Error correction level Medium.
*/
/** @private */
public alphanumericDataCapacityMedium: number[] = [20, 38, 61, 90, 122, 154, 178, 221, 262, 311, 366, 419, 483, 528, 600,
656, 734, 816, 909, 970, 1035, 1134, 1248, 1326, 1451, 1542, 1637, 1732, 1839, 1994, 2113, 2238, 2369, 2506, 2632, 2780,
2894, 3054, 3220, 3391];
/**
* Holds all the Alpha numeric Data capacity of the Error correction level Quartile.
*/
/** @private */
public alphanumericDataCapacityQuartile: number[] = [16, 29, 47, 67, 87, 108, 125, 157, 189, 221, 259, 296, 352, 376, 426, 470, 531,
574, 644, 702, 742, 823, 890, 963, 1041, 1094, 1172, 1263, 1322, 1429, 1499, 1618, 1700, 1787, 1867, 1966, 2071, 2181,
2298, 2420];
/**
* Holds all the Alpha numeric Data capacity of the Error correction level High.
*/
/** @private */
public alphanumericDataCapacityHigh: number[] = [10, 20, 35, 50, 64, 84, 93, 122, 143, 174, 200, 227, 259, 283, 321, 365, 408, 452,
493, 557, 587, 640, 672, 744, 779, 864, 910, 958, 1016, 1080, 1150, 1226, 1307, 1394, 1431, 1530, 1591, 1658, 1774, 1852];
/**
* Holds all the Binary Data capacity of the Error correction level Low.
*/
/** @private */
public binaryDataCapacityLow: number[] = [17, 32, 53, 78, 106, 134, 154, 192, 230, 271, 321, 367, 425, 458, 520, 586, 644, 718, 792,
858, 929, 1003, 1091, 1171, 1273, 1367, 1465, 1528, 1628, 1732, 1840, 1952, 2068, 2188, 2303, 2431, 2563, 2699, 2809, 2953];
/**
* Holds all the Binary Data capacity of the Error correction level Medium.
*/
/** @private */
public binaryDataCapacityMedium: number[] = [14, 26, 42, 62, 84, 106, 122, 152, 180, 213, 251, 287, 331, 362, 412, 450, 504, 560,
624, 666, 711, 779, 857, 911, 997, 1059, 1125, 1190, 1264, 1370, 1452, 1538, 1628, 1722, 1809, 1911, 1989, 2099, 2213, 2331];
/**
* Holds all the Binary Data capacity of the Error correction level Quartile.
*/
/** @private */
public binaryDataCapacityQuartile: number[] = [11, 20, 32, 46, 60, 74, 86, 108, 130, 151, 177, 203, 241, 258, 292, 322, 364, 394,
442, 482, 509, 565, 611, 661, 715, 751, 805, 868, 908, 982, 1030, 1112, 1168, 1228, 1283, 1351, 1423, 1499, 1579, 1663];
/**
* Holds all the Binary Data capacity of the Error correction level High.
*/
/** @private */
public binaryDataCapacityHigh: number[] = [7, 14, 24, 34, 44, 58, 64, 84, 98, 119, 137, 155, 177, 194, 220, 250, 280, 310, 338,
382, 403, 439, 461, 511, 535, 593, 625, 658, 698, 742, 790, 842, 898, 958, 983, 1051, 1093, 1139, 1219, 1273];
/**
* Holds all the Mixed Data capacity of the Error correction level Low.
*/
private mixedDataCapacityLow: number[] = [152, 272, 440, 640, 864, 1088, 1248, 1552, 1856, 2192, 2592, 2960, 3424, 3688, 4184,
4712, 5176, 5768, 6360, 6888, 7456, 8048, 8752, 9392, 10208, 10960, 11744, 12248, 13048, 13880, 4744, 15640, 16568,
17528, 18448, 19472, 20528, 21616, 22496, 23648];
/**
* Holds all the Mixed Data capacity of the Error correction level Medium.
*/
private mixedDataCapacityMedium: number[] = [128, 244, 352, 512, 688, 864, 992, 1232, 1456, 1728, 2032, 2320, 2672, 2920,
3320, 3624, 4056, 4504, 5016, 5352, 5712, 6256, 6880, 7312, 8000, 8496, 9024, 9544, 10136, 10984, 1640, 12328, 13048,
13800, 14496, 15312, 15936, 16816, 17728, 18672];
/**
* Holds all the Mixed Data capacity of the Error correction level Quartile.
*/
private mixedDataCapacityQuartile: number[] = [104, 176, 272, 384, 496, 608, 704, 880, 1056, 1232, 1440, 1648, 1952, 2088,
2360, 2600, 2936, 3176, 3560, 3880, 4096, 4544, 4912, 5312, 5744, 6032, 6464, 6968, 7288, 7880, 8264, 8920, 9368,
9848, 10288, 10832, 11408, 12016, 12656, 13328];
/**
* Holds all the Mixed Data capacity of the Error correction level High.
*/
private mixedDataCapacityHigh: number[] = [72, 128, 208, 288, 368, 480, 528, 688, 800, 976, 1120, 1264, 1440, 1576, 1784, 2024, 2264,
2504, 2728, 3080, 3248, 3536, 3712, 4112, 4304, 4768, 5024, 5288, 5608, 5960, 6344, 6760, 7208, 7688, 7888, 8432, 8768, 9136,
9776, 10208];
/**
* Get or public set the Number of Data code words.
*
* @returns { number} Get or public set the Number of Data code words.
* @private
*/
public get NumberOfDataCodeWord(): number {
return this.mNumberOfDataCodeWord;
}
/**
* Get or public set the Number of Data code words.
*
* @param {number} value - Get or public set the Number of Data code words.
* @private
*/
public set NumberOfDataCodeWord(value: number) {
this.mNumberOfDataCodeWord = value;
}
/**
* Get or Private set the Number of Error correction Blocks.
*
* @returns { number} Get or Private set the Number of Error correction Blocks.
* @private
*/
public get NumberOfErrorCorrectingCodeWords(): number {
return this.mNumberOfErrorCorrectingCodeWords;
}
/**
* Get or Private set the Number of Error correction code words.
*
* @param {number} value - Get or Private set the Number of Error correction code words.
* @private
*/
public set NumberOfErrorCorrectingCodeWords(value: number) {
this.mNumberOfErrorCorrectingCodeWords = value;
}
/**
* Get or Private set the Number of Error correction Blocks.
*
* @returns { number[]}Get or Private set the Number of Error correction Blocks.
* @private
*/
public get NumberOfErrorCorrectionBlocks(): number[] {
return this.mNumberOfErrorCorrectionBlocks;
}
/**
* set or Private set the Number of Error correction Blocks.
*
* @param {number[]} value - et or Private set the Number of Error correction Blocks.
* @private
*/
public set NumberOfErrorCorrectionBlocks(value: number[]) {
this.mNumberOfErrorCorrectionBlocks = value;
}
/**
* Set the End value of the Current Version.
*/
private set End(value: number) {
this.mEnd = value;
}
/**
* Get or Private set the Data capacity.
*
* @returns { number[]}Get or Private set the Data capacity.
* @private
*/
private get DataCapacity(): number {
return this.mDataCapacity;
}
/**
* Get or Private set the Data capacity.
*
* @param {string} value - Get or Private set the Data capacity.
* @private
*/
private set DataCapacity(value: number) {
this.mDataCapacity = value;
}
/**
* Get or Private set the Format Information.
*
* @returns { number[]} Get or Private set the Format Information.
* @private
*/
public get FormatInformation(): number[] {
return this.mFormatInformation;
}
/**
* Get or Private set the Format Information.
*
* @param {string} value - Get or Private set the Format Information.
* @private
*/
public set FormatInformation(value: number[]) {
this.mFormatInformation = value;
}
/**
* Get or Private set the Version Information.
*
* @returns { number[]} Validate the given input.
* @private
*/
public get VersionInformation(): number[] {
return this.mVersionInformation;
}
/** @private */
/**
* Get or Private set the Version Information.
*
* @param {string} value - Get or Private set the Version Information.
* @private
*/
public set VersionInformation(value: number[]) {
this.mVersionInformation = value;
}
/**
* Initializes the values
*
* @param version - version of the qr code
* @param errorCorrectionLevel - defines the level of error correction.
*/
constructor(version: QRCodeVersion, errorCorrectionLevel: ErrorCorrectionLevel) {
this.mVersion = version;
this.mErrorCorrectionLevel = errorCorrectionLevel;
this.NumberOfDataCodeWord = this.obtainNumberOfDataCodeWord();
this.NumberOfErrorCorrectingCodeWords = this.obtainNumberOfErrorCorrectingCodeWords();
this.NumberOfErrorCorrectionBlocks = this.obtainNumberOfErrorCorrectionBlocks();
this.End = this.obtainEnd();
this.DataCapacity = this.obtainDataCapacity();
this.FormatInformation = this.obtainFormatInformation();
this.VersionInformation = this.obtainVersionInformation();
}
/**
* Gets the Alphanumeric values.
*
* @param {string} value - Defines the format of the qrcode to be exported
* @returns {number} Gets the Alphanumeric values.
* @private
*/
public getAlphaNumericValues(value: string): number {
let valueInInt: number = 0;
switch (value) {
case '0':
valueInInt = 0; break;
case '1':
valueInInt = 1; break;
case '2':
valueInInt = 2; break;
case '3':
valueInInt = 3; break;
case '4':
valueInInt = 4; break;
case '5':
valueInInt = 5; break;
case '6':
valueInInt = 6; break;
case '7':
valueInInt = 7; break;
case '8':
valueInInt = 8; break;
case '9':
valueInInt = 9; break;
case 'A':
valueInInt = 10; break;
case 'B':
valueInInt = 11; break;
case 'C':
valueInInt = 12; break;
case 'D':
valueInInt = 13; break;
case 'E':
valueInInt = 14; break;
case 'F':
valueInInt = 15; break;
case 'G':
valueInInt = 16; break;
case 'H':
valueInInt = 17; break;
case 'I':
valueInInt = 18; break;
case 'J':
valueInInt = 19;
break;
case 'K':
valueInInt = 20; break;
case 'L':
valueInInt = 21; break;
case 'M':
valueInInt = 22; break;
case 'N':
valueInInt = 23; break;
case 'O':
valueInInt = 24; break;
case 'P':
valueInInt = 25; break;
case 'Q':
valueInInt = 26; break;
case 'R':
valueInInt = 27; break;
case 'S':
valueInInt = 28; break;
case 'T':
valueInInt = 29; break;
case 'U':
valueInInt = 30; break;
case 'V':
valueInInt = 31; break;
case 'W':
valueInInt = 32; break;
case 'X':
valueInInt = 33; break;
case 'Y':
valueInInt = 34; break;
case 'Z':
valueInInt = 35; break;
case ' ':
valueInInt = 36; break;
case '$':
valueInInt = 37; break;
case '%':
valueInInt = 38; break;
case '*':
valueInInt = 39; break;
case '+':
valueInInt = 40; break;
case '-':
valueInInt = 41; break;
case '.':
valueInInt = 42; break;
case '/':
valueInInt = 43; break;
case ':':
valueInInt = 44; break;
default:
// throw new BarcodeException('Not a valid input');
}
return valueInInt;
}
/**
* Gets number of data code words.
*/
/* tslint:disable */
private obtainNumberOfDataCodeWord(): number {
let countOfDataCodeWord: number = 0;
switch (this.mVersion) {
case 1:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 19; break;
case 15:
countOfDataCodeWord = 16; break;
case 25:
countOfDataCodeWord = 13; break;
case 30:
countOfDataCodeWord = 9; break;
}
break;
case 2:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 34; break;
case 15:
countOfDataCodeWord = 28; break;
case 25:
countOfDataCodeWord = 22; break;
case 30:
countOfDataCodeWord = 16; break;
}
break;
case 3:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 55; break;
case 15:
countOfDataCodeWord = 44; break;
case 25:
countOfDataCodeWord = 34; break;
case 30:
countOfDataCodeWord = 26; break;
}
break;
case 4:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 80; break;
case 15:
countOfDataCodeWord = 64; break;
case 25:
countOfDataCodeWord = 48; break;
case 30:
countOfDataCodeWord = 36; break;
}
break;
case 5:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 108; break;
case 15:
countOfDataCodeWord = 86; break;
case 25:
countOfDataCodeWord = 62; break;
case 30:
countOfDataCodeWord = 46; break;
}
break;
case 6:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 136; break;
case 15:
countOfDataCodeWord = 108; break;
case 25:
countOfDataCodeWord = 76; break;
case 30:
countOfDataCodeWord = 60; break;
}
break;
case 7:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 156; break;
case 15:
countOfDataCodeWord = 124; break;
case 25:
countOfDataCodeWord = 88; break;
case 30:
countOfDataCodeWord = 66; break;
}
break;
case 8:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 194; break;
case 15:
countOfDataCodeWord = 154; break;
case 25:
countOfDataCodeWord = 110; break;
case 30:
countOfDataCodeWord = 86; break;
}
break;
case 9:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 232; break;
case 15:
countOfDataCodeWord = 182; break;
case 25:
countOfDataCodeWord = 132; break;
case 30:
countOfDataCodeWord = 100; break;
}
break;
case 10:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 274; break;
case 15:
countOfDataCodeWord = 216; break;
case 25:
countOfDataCodeWord = 154; break;
case 30:
countOfDataCodeWord = 122; break;
}
break;
case 11:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 324; break;
case 15:
countOfDataCodeWord = 254; break;
case 25:
countOfDataCodeWord = 180; break;
case 30:
countOfDataCodeWord = 140; break;
}
break;
case 12:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 370; break;
case 15:
countOfDataCodeWord = 290; break;
case 25:
countOfDataCodeWord = 206; break;
case 30:
countOfDataCodeWord = 158; break;
}
break;
case 13:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 428; break;
case 15:
countOfDataCodeWord = 334; break;
case 25:
countOfDataCodeWord = 244; break;
case 30:
countOfDataCodeWord = 180; break;
}
break;
case 14:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 461; break;
case 15:
countOfDataCodeWord = 365; break;
case 25:
countOfDataCodeWord = 261; break;
case 30:
countOfDataCodeWord = 197; break;
}
break;
case 15:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 523; break;
case 15:
countOfDataCodeWord = 415; break;
case 25:
countOfDataCodeWord = 295; break;
case 30:
countOfDataCodeWord = 223; break;
}
break;
case 16:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 589; break;
case 15:
countOfDataCodeWord = 453; break;
case 25:
countOfDataCodeWord = 325; break;
case 30:
countOfDataCodeWord = 253; break;
}
break;
case 17:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 647; break;
case 15:
countOfDataCodeWord = 507; break;
case 25:
countOfDataCodeWord = 367; break;
case 30:
countOfDataCodeWord = 283; break;
}
break;
case 18:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 721; break;
case 15:
countOfDataCodeWord = 563; break;
case 25:
countOfDataCodeWord = 397; break;
case 30:
countOfDataCodeWord = 313; break;
}
break;
case 19:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 795; break;
case 15:
countOfDataCodeWord = 627; break;
case 25:
countOfDataCodeWord = 445; break;
case 30:
countOfDataCodeWord = 341; break;
}
break;
case 20:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 861; break;
case 15:
countOfDataCodeWord = 669; break;
case 25:
countOfDataCodeWord = 485; break;
case 30:
countOfDataCodeWord = 385; break;
}
break;
case 21:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 932; break;
case 15:
countOfDataCodeWord = 714; break;
case 25:
countOfDataCodeWord = 512; break;
case 30:
countOfDataCodeWord = 406; break;
}
break;
case 22:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 1006; break;
case 15:
countOfDataCodeWord = 782; break;
case 25:
countOfDataCodeWord = 568; break;
case 30:
countOfDataCodeWord = 442; break;
}
break;
case 23:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 1094; break;
case 15:
countOfDataCodeWord = 860; break;
case 25:
countOfDataCodeWord = 614; break;
case 30:
countOfDataCodeWord = 464; break;
}
break;
case 24:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 1174; break;
case 15:
countOfDataCodeWord = 914; break;
case 25:
countOfDataCodeWord = 664; break;
case 30:
countOfDataCodeWord = 514; break;
}
break;
case 25:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 1276; break;
case 15:
countOfDataCodeWord = 1000; break;
case 25:
countOfDataCodeWord = 718; break;
case 30:
countOfDataCodeWord = 538; break;
}
break;
case 26:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 1370; break;
case 15:
countOfDataCodeWord = 1062; break;
case 25:
countOfDataCodeWord = 754; break;
case 30:
countOfDataCodeWord = 596; break;
}
break;
case 27:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 1468; break;
case 15:
countOfDataCodeWord = 1128; break;
case 25:
countOfDataCodeWord = 808; break;
case 30:
countOfDataCodeWord = 628; break;
}
break;
case 28:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 1531; break;
case 15:
countOfDataCodeWord = 1193; break;
case 25:
countOfDataCodeWord = 871; break;
case 30:
countOfDataCodeWord = 661; break;
}
break;
case 29:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 1631; break;
case 15:
countOfDataCodeWord = 1267; break;
case 25:
countOfDataCodeWord = 911; break;
case 30:
countOfDataCodeWord = 701; break;
}
break;
case 30:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 1735; break;
case 15:
countOfDataCodeWord = 1373; break;
case 25:
countOfDataCodeWord = 985; break;
case 30:
countOfDataCodeWord = 745; break;
}
break;
case 31:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 1843; break;
case 15:
countOfDataCodeWord = 1455; break;
case 25:
countOfDataCodeWord = 1033; break;
case 30:
countOfDataCodeWord = 793; break;
}
break;
case 32:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 1955; break;
case 15:
countOfDataCodeWord = 1541; break;
case 25:
countOfDataCodeWord = 1115; break;
case 30:
countOfDataCodeWord = 845; break;
}
break;
case 33:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 2071; break;
case 15:
countOfDataCodeWord = 1631; break;
case 25:
countOfDataCodeWord = 1171; break;
case 30:
countOfDataCodeWord = 901; break;
}
break;
case 34:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 2191; break;
case 15:
countOfDataCodeWord = 1725; break;
case 25:
countOfDataCodeWord = 1231; break;
case 30:
countOfDataCodeWord = 961; break;
}
break;
case 35:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 2306; break;
case 15:
countOfDataCodeWord = 1812; break;
case 25:
countOfDataCodeWord = 1286; break;
case 30:
countOfDataCodeWord = 986; break;
}
break;
case 36:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 2434; break;
case 15:
countOfDataCodeWord = 1914; break;
case 25:
countOfDataCodeWord = 1354; break;
case 30:
countOfDataCodeWord = 1054; break;
}
break;
case 37:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 2566; break;
case 15:
countOfDataCodeWord = 1992; break;
case 25:
countOfDataCodeWord = 1426; break;
case 30:
countOfDataCodeWord = 1096; break;
}
break;
case 38:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 2702; break;
case 15:
countOfDataCodeWord = 2102; break;
case 25:
countOfDataCodeWord = 1502; break;
case 30:
countOfDataCodeWord = 1142; break;
}
break;
case 39:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 2812; break;
case 15:
countOfDataCodeWord = 2216; break;
case 25:
countOfDataCodeWord = 1582; break;
case 30:
countOfDataCodeWord = 1222; break;
}
break;
case 40:
switch (this.mErrorCorrectionLevel) {
case 7:
countOfDataCodeWord = 2956; break;
case 15:
countOfDataCodeWord = 2334; break;
case 25:
countOfDataCodeWord = 1666; break;
case 30:
countOfDataCodeWord = 1276; break;
}
break;
}
return countOfDataCodeWord;
}
/* tslint:enable */
/**
* Get number of Error correction code words.
*
* @returns {number} Get number of Error correction code words.
* @private
*/
private obtainNumberOfErrorCorrectingCodeWords(): number {
let index: number = (this.mVersion - 1) * 4;
switch (this.mErrorCorrectionLevel) {
case 7:
index += 0; break;
case 15:
index += 1; break;
case 25:
index += 2; break;
case 30:
index += 3; break;
}
return this.numberOfErrorCorrectingCodeWords[index];
}
/**
* Gets number of Error correction Blocks.
*/
/* tslint:disable */
private obtainNumberOfErrorCorrectionBlocks(): number[] {
let numberOfErrorCorrectionBlocks: number[] = null;
switch (this.mVersion) {
case 1:
numberOfErrorCorrectionBlocks = [1]; break;
case 2:
numberOfErrorCorrectionBlocks = [1]; break;
case 3:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [1]; break;
case 15:
numberOfErrorCorrectionBlocks = [1]; break;
case 25:
numberOfErrorCorrectionBlocks = [2]; break;
case 30:
numberOfErrorCorrectionBlocks = [2]; break;
}
break;
case 4:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [1]; break;
case 15:
numberOfErrorCorrectionBlocks = [2]; break;
case 25:
numberOfErrorCorrectionBlocks = [2]; break;
case 30:
numberOfErrorCorrectionBlocks = [4]; break;
}
break;
case 5:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [1]; break;
case 15:
numberOfErrorCorrectionBlocks = [2]; break;
case 25:
numberOfErrorCorrectionBlocks = [2, 33, 15, 2, 34, 16]; break;
case 30:
numberOfErrorCorrectionBlocks = [2, 33, 11, 2, 34, 12]; break;
}
break;
case 6:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [2]; break;
case 15:
numberOfErrorCorrectionBlocks = [4]; break;
case 25:
numberOfErrorCorrectionBlocks = [4]; break;
case 30:
numberOfErrorCorrectionBlocks = [4]; break;
}
break;
case 7:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [2]; break;
case 15:
numberOfErrorCorrectionBlocks = [4]; break;
case 25:
numberOfErrorCorrectionBlocks = [2, 32, 14, 4, 33, 15]; break;
case 30:
numberOfErrorCorrectionBlocks = [4, 39, 13, 1, 40, 14]; break;
}
break;
case 8:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [2]; break;
case 15:
numberOfErrorCorrectionBlocks = [2, 60, 38, 2, 61, 39]; break;
case 25:
numberOfErrorCorrectionBlocks = [4, 40, 18, 2, 41, 19]; break;
case 30:
numberOfErrorCorrectionBlocks = [4, 40, 14, 2, 41, 15]; break;
}
break;
case 9:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [2]; break;
case 15:
numberOfErrorCorrectionBlocks = [3, 58, 36, 2, 59, 37]; break;
case 25:
numberOfErrorCorrectionBlocks = [4, 36, 16, 4, 37, 17]; break;
case 30:
numberOfErrorCorrectionBlocks = [4, 36, 12, 4, 37, 13]; break;
}
break;
case 10:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [2, 86, 68, 2, 87, 69]; break;
case 15:
numberOfErrorCorrectionBlocks = [4, 69, 43, 1, 70, 44]; break;
case 25:
numberOfErrorCorrectionBlocks = [6, 43, 19, 2, 44, 20]; break;
case 30:
numberOfErrorCorrectionBlocks = [6, 43, 15, 2, 44, 16]; break;
}
break;
case 11:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [4]; break;
case 15:
numberOfErrorCorrectionBlocks = [1, 80, 50, 4, 81, 51]; break;
case 25:
numberOfErrorCorrectionBlocks = [4, 50, 22, 4, 51, 23]; break;
case 30:
numberOfErrorCorrectionBlocks = [3, 36, 12, 8, 37, 13]; break;
}
break;
case 12:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [2, 116, 92, 2, 117, 93]; break;
case 15:
numberOfErrorCorrectionBlocks = [6, 58, 36, 2, 59, 37]; break;
case 25:
numberOfErrorCorrectionBlocks = [4, 46, 20, 6, 47, 21]; break;
case 30:
numberOfErrorCorrectionBlocks = [7, 42, 14, 4, 43, 15]; break;
}
break;
case 13:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [4]; break;
case 15:
numberOfErrorCorrectionBlocks = [8, 59, 37, 1, 60, 38]; break;
case 25:
numberOfErrorCorrectionBlocks = [8, 44, 20, 4, 45, 21]; break;
case 30:
numberOfErrorCorrectionBlocks = [12, 33, 11, 4, 34, 12]; break;
}
break;
case 14:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [3, 145, 115, 1, 146, 116]; break;
case 15:
numberOfErrorCorrectionBlocks = [4, 64, 40, 5, 65, 41]; break;
case 25:
numberOfErrorCorrectionBlocks = [11, 36, 16, 5, 37, 17]; break;
case 30:
numberOfErrorCorrectionBlocks = [11, 36, 12, 5, 37, 13]; break;
}
break;
case 15:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [5, 109, 87, 1, 110, 88]; break;
case 15:
numberOfErrorCorrectionBlocks = [5, 65, 41, 5, 66, 42]; break;
case 25:
numberOfErrorCorrectionBlocks = [5, 54, 24, 7, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [11, 36, 12, 7, 37, 13]; break;
}
break;
case 16:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [5, 112, 98, 1, 123, 99]; break;
case 15:
numberOfErrorCorrectionBlocks = [7, 73, 45, 3, 74, 46]; break;
case 25:
numberOfErrorCorrectionBlocks = [15, 43, 19, 2, 44, 20]; break;
case 30:
numberOfErrorCorrectionBlocks = [3, 45, 15, 13, 46, 16]; break;
}
break;
case 17:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [1, 135, 107, 5, 136, 108]; break;
case 15:
numberOfErrorCorrectionBlocks = [10, 74, 46, 1, 75, 47]; break;
case 25:
numberOfErrorCorrectionBlocks = [1, 50, 22, 15, 51, 23]; break;
case 30:
numberOfErrorCorrectionBlocks = [2, 42, 14, 17, 43, 15]; break;
}
break;
case 18:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [5, 150, 120, 1, 151, 121]; break;
case 15:
numberOfErrorCorrectionBlocks = [9, 69, 43, 4, 70, 44]; break;
case 25:
numberOfErrorCorrectionBlocks = [17, 50, 22, 1, 51, 23]; break;
case 30:
numberOfErrorCorrectionBlocks = [2, 42, 14, 19, 43, 15]; break;
}
break;
case 19:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [3, 141, 113, 4, 142, 114]; break;
case 15:
numberOfErrorCorrectionBlocks = [3, 70, 44, 11, 71, 45]; break;
case 25:
numberOfErrorCorrectionBlocks = [17, 47, 21, 4, 48, 22]; break;
case 30:
numberOfErrorCorrectionBlocks = [9, 39, 13, 16, 40, 14]; break;
}
break;
case 20:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [3, 135, 107, 5, 136, 108]; break;
case 15:
numberOfErrorCorrectionBlocks = [3, 67, 41, 13, 68, 42]; break;
case 25:
numberOfErrorCorrectionBlocks = [15, 54, 24, 5, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [15, 43, 15, 10, 44, 16]; break;
}
break;
case 21:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [4, 144, 116, 4, 145, 117]; break;
case 15:
numberOfErrorCorrectionBlocks = [17]; break;
case 25:
numberOfErrorCorrectionBlocks = [17, 50, 22, 6, 51, 23]; break;
case 30:
numberOfErrorCorrectionBlocks = [19, 46, 16, 6, 47, 17]; break;
}
break;
case 22:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [2, 139, 111, 7, 140, 112]; break;
case 15:
numberOfErrorCorrectionBlocks = [17]; break;
case 25:
numberOfErrorCorrectionBlocks = [7, 54, 24, 16, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [34]; break;
}
break;
case 23:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [4, 151, 121, 5, 152, 122]; break;
case 15:
numberOfErrorCorrectionBlocks = [4, 75, 47, 14, 76, 48]; break;
case 25:
numberOfErrorCorrectionBlocks = [11, 54, 24, 14, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [16, 45, 15, 14, 46, 16]; break;
}
break;
case 24:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [6, 147, 117, 4, 148, 118]; break;
case 15:
numberOfErrorCorrectionBlocks = [6, 73, 45, 14, 74, 46]; break;
case 25:
numberOfErrorCorrectionBlocks = [11, 54, 24, 16, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [30, 46, 16, 2, 47, 17]; break;
}
break;
case 25:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [8, 132, 106, 4, 133, 107]; break;
case 15:
numberOfErrorCorrectionBlocks = [8, 75, 47, 13, 76, 48]; break;
case 25:
numberOfErrorCorrectionBlocks = [7, 54, 24, 22, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [22, 45, 15, 13, 46, 16]; break;
}
break;
case 26:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [10, 142, 114, 2, 143, 115]; break;
case 15:
numberOfErrorCorrectionBlocks = [19, 74, 46, 4, 75, 47]; break;
case 25:
numberOfErrorCorrectionBlocks = [28, 50, 22, 6, 51, 23]; break;
case 30:
numberOfErrorCorrectionBlocks = [33, 46, 16, 4, 47, 17]; break;
}
break;
case 27:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [8, 152, 122, 4, 153, 123]; break;
case 15:
numberOfErrorCorrectionBlocks = [22, 73, 45, 3, 74, 46]; break;
case 25:
numberOfErrorCorrectionBlocks = [8, 53, 23, 26, 54, 24]; break;
case 30:
numberOfErrorCorrectionBlocks = [12, 45, 15, 28, 46, 16]; break;
}
break;
case 28:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [3, 147, 117, 10, 148, 118]; break;
case 15:
numberOfErrorCorrectionBlocks = [3, 73, 45, 23, 74, 46]; break;
case 25:
numberOfErrorCorrectionBlocks = [4, 54, 24, 31, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [11, 45, 15, 31, 46, 16]; break;
}
break;
case 29:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [7, 146, 116, 7, 147, 117]; break;
case 15:
numberOfErrorCorrectionBlocks = [21, 73, 45, 7, 74, 46]; break;
case 25:
numberOfErrorCorrectionBlocks = [1, 53, 23, 37, 54, 24]; break;
case 30:
numberOfErrorCorrectionBlocks = [19, 45, 15, 26, 46, 16]; break;
}
break;
case 30:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [5, 145, 115, 10, 146, 116]; break;
case 15:
numberOfErrorCorrectionBlocks = [19, 75, 47, 10, 76, 48]; break;
case 25:
numberOfErrorCorrectionBlocks = [15, 54, 24, 25, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [23, 45, 15, 25, 46, 16]; break;
}
break;
case 31:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [13, 145, 115, 3, 146, 116]; break;
case 15:
numberOfErrorCorrectionBlocks = [2, 74, 46, 29, 75, 47]; break;
case 25:
numberOfErrorCorrectionBlocks = [42, 54, 24, 1, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [23, 45, 15, 28, 46, 16]; break;
}
break;
case 32:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [17]; break;
case 15:
numberOfErrorCorrectionBlocks = [10, 74, 46, 23, 75, 47]; break;
case 25:
numberOfErrorCorrectionBlocks = [10, 54, 24, 35, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [19, 45, 15, 35, 46, 16]; break;
}
break;
case 33:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [17, 145, 115, 1, 146, 116]; break;
case 15:
numberOfErrorCorrectionBlocks = [14, 74, 46, 21, 75, 47]; break;
case 25:
numberOfErrorCorrectionBlocks = [29, 54, 24, 19, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [11, 45, 15, 46, 46, 16]; break;
}
break;
case 34:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [13, 145, 115, 6, 146, 116]; break;
case 15:
numberOfErrorCorrectionBlocks = [14, 74, 46, 23, 75, 47]; break;
case 25:
numberOfErrorCorrectionBlocks = [44, 54, 24, 7, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [59, 46, 16, 1, 47, 17]; break;
}
break;
case 35:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [12, 151, 121, 7, 152, 122]; break;
case 15:
numberOfErrorCorrectionBlocks = [12, 75, 47, 26, 76, 48]; break;
case 25:
numberOfErrorCorrectionBlocks = [39, 54, 24, 14, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [22, 45, 15, 41, 46, 16]; break;
}
break;
case 36:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [6, 151, 121, 14, 152, 122]; break;
case 15:
numberOfErrorCorrectionBlocks = [6, 75, 47, 34, 76, 48]; break;
case 25:
numberOfErrorCorrectionBlocks = [46, 54, 24, 10, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [2, 45, 15, 64, 46, 16]; break;
}
break;
case 37:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [17, 152, 122, 4, 153, 123]; break;
case 15:
numberOfErrorCorrectionBlocks = [29, 74, 46, 14, 75, 47]; break;
case 25:
numberOfErrorCorrectionBlocks = [49, 54, 24, 10, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [24, 45, 15, 46, 46, 16]; break;
}
break;
case 38:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [4, 152, 122, 18, 153, 123]; break;
case 15:
numberOfErrorCorrectionBlocks = [13, 74, 46, 32, 75, 47]; break;
case 25:
numberOfErrorCorrectionBlocks = [48, 54, 24, 14, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [42, 45, 15, 32, 46, 16]; break;
}
break;
case 39:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [20, 147, 117, 4, 148, 118]; break;
case 15:
numberOfErrorCorrectionBlocks = [40, 75, 47, 7, 76, 48]; break;
case 25:
numberOfErrorCorrectionBlocks = [43, 54, 24, 22, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [10, 45, 15, 67, 46, 16]; break;
}
break;
case 40:
switch (this.mErrorCorrectionLevel) {
case 7:
numberOfErrorCorrectionBlocks = [19, 148, 118, 6, 149, 119]; break;
case 15:
numberOfErrorCorrectionBlocks = [18, 75, 47, 31, 76, 48]; break;
case 25:
numberOfErrorCorrectionBlocks = [34, 54, 24, 34, 55, 25]; break;
case 30:
numberOfErrorCorrectionBlocks = [20, 45, 15, 61, 46, 16]; break;
}
break;
}
return numberOfErrorCorrectionBlocks;
}
/* tslint:enable */
/**
* Gets the End of the version.
*
* @returns {number} Gets the End of the version.
* @private
*/
private obtainEnd(): number {
return this.endValues[this.mVersion - 1];
}
/**
* Gets Data capacity
*
* @returns {number} Gets Data capacity
* @private
*/
private obtainDataCapacity(): number {
return this.dataCapacityValues[this.mVersion - 1];
}
/**
* Gets format information
*
* @returns {number} Gets format information
* @private
*/
private obtainFormatInformation(): number[] {
let formatInformation: number[] = null;
switch (this.mErrorCorrectionLevel) {
case 7:
formatInformation = [1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1]; break;
case 15:
formatInformation = [1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1]; break;
case 25:
formatInformation = [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0]; break;
case 30:
formatInformation = [0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0]; break;
}
return formatInformation;
}
/**
* Gets version information .
*
* @returns {number}Gets version information.
* @private
*/
private obtainVersionInformation(): number[] {
let versionInformation: number[] = null;
switch (this.mVersion) {
case 7:
versionInformation = [0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0]; break;
case 8:
versionInformation = [0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0]; break;
case 9:
versionInformation = [1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0]; break;
case 10:
versionInformation = [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0]; break;
case 11:
versionInformation = [0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0]; break;
case 12:
versionInformation = [0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0]; break;
case 13:
versionInformation = [1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0]; break;
case 14:
versionInformation = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0]; break;
case 15:
versionInformation = [0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0]; break;
case 16:
versionInformation = [0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0]; break;
case 17:
versionInformation = [1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0]; break;
case 18:
versionInformation = [1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0]; break;
case 19:
versionInformation = [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0]; break;
case 20:
versionInformation = [0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0]; break;
case 21:
versionInformation = [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0]; break;
case 22:
versionInformation = [1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0]; break;
case 23:
versionInformation = [0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0]; break;
case 24:
versionInformation = [0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0]; break;
case 25:
versionInformation = [1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0]; break;
case 26:
versionInformation = [1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0]; break;
case 27:
versionInformation = [0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0]; break;
case 28:
versionInformation = [0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0]; break;
case 29:
versionInformation = [1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0]; break;
case 30:
versionInformation = [1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0]; break;
case 31:
versionInformation = [0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0]; break;
case 32:
versionInformation = [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1]; break;
case 33:
versionInformation = [0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1]; break;
case 34:
versionInformation = [0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1]; break;
case 35:
versionInformation = [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1]; break;
case 36:
versionInformation = [1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1]; break;
case 37:
versionInformation = [0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1]; break;
case 38:
versionInformation = [0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1]; break;
case 39:
versionInformation = [1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1]; break;
case 40:
versionInformation = [1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1]; break;
}
return versionInformation;
}
/**
* Gets Numeric Data capacity .
*
* @returns {number}Gets Numeric Data capacity.
* @param {QRCodeVersion} version - Provide the version for the QR code
* @param {ErrorCorrectionLevel} errorCorrectionLevel -provide the error correction level
* @private
*/
public getNumericDataCapacity(version: QRCodeVersion, errorCorrectionLevel: ErrorCorrectionLevel): number {
let capacity: number[] = null;
switch (errorCorrectionLevel) {
case 7:
capacity = this.numericDataCapacityLow;
break;
case 15:
capacity = this.numericDataCapacityMedium;
break;
case 25:
capacity = this.numericDataCapacityQuartile;
break;
case 30:
capacity = this.numericDataCapacityHigh;
break;
}
return capacity[version - 1];
}
/**
* Gets Alphanumeric data capacity. .
*
* @returns {number}Gets Alphanumeric data capacity..
* @param {QRCodeVersion} version - Provide the version for the QR code
* @param {ErrorCorrectionLevel} errorCorrectionLevel -provide the error correction level
* @private
*/
public getAlphanumericDataCapacity(version: QRCodeVersion, errorCorrectionLevel: ErrorCorrectionLevel): number {
let capacity: number[] = null;
switch (errorCorrectionLevel) {
case 7:
capacity = this.alphanumericDataCapacityLow;
break;
case 15:
capacity = this.alphanumericDataCapacityMedium;
break;
case 25:
capacity = this.alphanumericDataCapacityQuartile;
break;
case 30:
capacity = this.alphanumericDataCapacityHigh;
break;
}
return capacity[version - 1];
}
/**
* get the binary data capacity .
*
* @returns {number} get the binary data capacity.
* @param {QRCodeVersion} version - Provide the version for the QR code
* @param {ErrorCorrectionLevel} errorCorrectionLevel -provide the error correction level
* @private
*/
public getBinaryDataCapacity(version: QRCodeVersion, errorCorrectionLevel: ErrorCorrectionLevel): number {
let capacity: number[] = null;
switch (errorCorrectionLevel) {
case 7:
capacity = this.binaryDataCapacityLow;
break;
case 15:
capacity = this.binaryDataCapacityMedium;
break;
case 25:
capacity = this.binaryDataCapacityQuartile;
break;
case 30:
capacity = this.binaryDataCapacityHigh;
break;
}
return capacity[version - 1];
}
} | the_stack |
import 'styling/_Pager';
import {
IBuildingQueryEventArgs,
INewQueryEventArgs,
INoResultsEventArgs,
IQuerySuccessEventArgs,
QueryEvents
} from '../../events/QueryEvents';
import { ResultListEvents } from '../../events/ResultListEvents';
import { exportGlobally } from '../../GlobalExports';
import { Assert } from '../../misc/Assert';
import { IAttributeChangedEventArg, MODEL_EVENTS } from '../../models/Model';
import { QueryStateModel, QUERY_STATE_ATTRIBUTES } from '../../models/QueryStateModel';
import { l } from '../../strings/Strings';
import { AccessibleButton } from '../../utils/AccessibleButton';
import { DeviceUtils } from '../../utils/DeviceUtils';
import { $$ } from '../../utils/Dom';
import { ResultListUtils } from '../../utils/ResultListUtils';
import { SVGDom } from '../../utils/SVGDom';
import { SVGIcons } from '../../utils/SVGIcons';
import { analyticsActionCauseList, IAnalyticsActionCause, IAnalyticsPagerMeta } from '../Analytics/AnalyticsActionListMeta';
import { Component } from '../Base/Component';
import { IComponentBindings } from '../Base/ComponentBindings';
import { ComponentOptions } from '../Base/ComponentOptions';
import { Initialization } from '../Base/Initialization';
export interface IPagerOptions {
numberOfPages: number;
enableNavigationButton: boolean;
maxNumberOfPages: number;
maximumNumberOfResultsFromIndex: number;
}
/**
* The Pager component attaches itself to a `div` element and renders widgets that allow the end user to navigate
* through the different result pages.
*
* This component takes care of triggering a query with the correct result range whenever the end user selects a page or
* uses the navigation buttons (**Previous** and **Next**).
*/
export class Pager extends Component {
static ID = 'Pager';
static doExport = () => {
exportGlobally({
Pager: Pager
});
};
/**
* The options for the Pager
* @componentOptions
*/
static options: IPagerOptions = {
/**
* Specifies how many page links to display in the pager.
*
* Default value is `5` on a desktop computers and `3` on a mobile device. Minimum value is `1`.
*/
numberOfPages: ComponentOptions.buildNumberOption({
defaultFunction: () => {
if (DeviceUtils.isMobileDevice()) {
return 3;
} else {
return 5;
}
},
min: 1
}),
/**
* Specifies whether the **Previous** and **Next** buttons should appear at each end of the pager when appropriate.
*
* The default value is `true`.
*/
enableNavigationButton: ComponentOptions.buildBooleanOption({ defaultValue: true }),
/**
* Specifies the maximum number of pages to display if enough results are available.
*
* This property is typically set when the default number of accessible results from the index has been changed from its default value of `1000` (10 results per page X 100 `maxNumberOfPages`).
* Default value is `100`
*
* @deprecated This is a deprecated option. The `Pager` now automatically adapts itself on each new query, so you no longer need to specify a value for this option. However, if the default maximum number of accessible results value was changed on your Coveo index, you should use the [`maximumNumberOfResultsFromIndex`]{@link Pager.options.maximumNumberOfResultsFromIndex} option to specify the new value.
*/
maxNumberOfPages: ComponentOptions.buildNumberOption({
defaultValue: undefined,
deprecated:
'This is a deprecated option. The pager will automatically adapt itself on each new query. You no longer need to specify this option. Use maximumNumberOfResultsFromIndex instead.'
}),
/**
* Specifies the maximum number of results that the index can return for any query.
*
* Default value is `1000` in a Coveo index.
*
* If this value was modified in your Coveo index, you must specify the new value in this option for the Pager component to work properly
*/
maximumNumberOfResultsFromIndex: ComponentOptions.buildNumberOption({
defaultValue: 1000
})
};
private listenToQueryStateChange = true;
private ignoreNextQuerySuccess = false;
private _currentPage: number;
// The normal behavior of this component is to reset to page 1 when a new
// query is performed by other components (i.e. not pagers).
//
// This behavior is overridden when the 'first' state is
// programmatically modified.
private needToReset = true;
private list: HTMLElement;
/**
* Creates a new Pager. Binds multiple query events ({@link QueryEvents.newQuery}, {@link QueryEvents.buildingQuery},
* {@link QueryEvents.querySuccess}, {@link QueryEvents.queryError} and {@link QueryEvents.noResults}. Renders itself
* on every query success.
* @param element The HTMLElement on which to instantiate the component (normally a `div`).
* @param options The options for the Pager component.
* @param bindings The bindings that the component requires to function normally. If not set, these will be
* automatically resolved (with a slower execution time).
*/
constructor(public element: HTMLElement, public options?: IPagerOptions, bindings?: IComponentBindings) {
super(element, Pager.ID, bindings);
this.options = ComponentOptions.initComponentOptions(element, Pager, options);
this.currentPage = 1;
this.bind.onRootElement(QueryEvents.newQuery, (args: INewQueryEventArgs) => this.handleNewQuery(args));
this.bind.onRootElement(QueryEvents.buildingQuery, (args: IBuildingQueryEventArgs) => this.handleBuildingQuery(args));
this.bind.onRootElement(QueryEvents.querySuccess, (args: IQuerySuccessEventArgs) => this.handleQuerySuccess(args));
this.bind.onRootElement(QueryEvents.queryError, () => this.handleQueryError());
this.bind.onRootElement(QueryEvents.noResults, (args: INoResultsEventArgs) => this.handleNoResults(args));
this.bind.onQueryState(MODEL_EVENTS.CHANGE_ONE, QUERY_STATE_ATTRIBUTES.FIRST, (data: IAttributeChangedEventArg) =>
this.handleQueryStateFirstResultChanged(data)
);
this.bind.onQueryState(MODEL_EVENTS.CHANGE_ONE, QUERY_STATE_ATTRIBUTES.NUMBER_OF_RESULTS, (data: IAttributeChangedEventArg) =>
this.handleQueryStateNumberOfResultsPerPageChanged(data)
);
this.addAlwaysActiveListeners();
this.list = $$('ul', {
className: 'coveo-pager-list',
role: 'navigation',
ariaLabel: l('Pagination')
}).el;
element.appendChild(this.list);
}
/**
* The current page (1-based index).
*/
public get currentPage(): number {
return this._currentPage;
}
public set currentPage(value: number) {
let sanitizedValue = value;
if (isNaN(value)) {
this.logger.warn(`Unable to set pager current page to an invalid value: ${value}. Resetting to 1.`);
sanitizedValue = 1;
}
sanitizedValue = Math.max(Math.min(sanitizedValue, this.getMaxNumberOfPagesForCurrentResultsPerPage()), 1);
sanitizedValue = Math.floor(sanitizedValue);
this._currentPage = sanitizedValue;
}
/**
* Sets the current page, then executes a query.
*
* Also logs an event in the usage analytics (`pageNumber` by default) with the new current page number as meta data.
*
* @param pageNumber The page number to navigate to.
* @param analyticCause The event to log in the usage analytics.
*/
public setPage(pageNumber: number, analyticCause: IAnalyticsActionCause = analyticsActionCauseList.pagerNumber) {
Assert.exists(pageNumber);
this.currentPage = pageNumber;
this.updateQueryStateModel(this.getFirstResultNumber(this.currentPage));
this.usageAnalytics.logCustomEvent<IAnalyticsPagerMeta>(analyticCause, { pagerNumber: this.currentPage }, this.element);
this.queryController.executeQuery({
ignoreWarningSearchEvent: true,
keepLastSearchUid: true,
origin: this
});
}
/**
* Navigates to the previous page, then executes a query.
*
* Also logs the `pagePrevious` event in the usage analytics with the new current page number as meta data.
*/
public previousPage() {
this.setPage(this.currentPage - 1, analyticsActionCauseList.pagerPrevious);
}
/**
* Navigates to the next page, then executes a query.
*
* Also logs the `pageNext` event in the usage analytics with the new current page number as meta data.
*/
public nextPage() {
this.setPage(this.currentPage + 1, analyticsActionCauseList.pagerNext);
}
private addAlwaysActiveListeners() {
this.searchInterface.element.addEventListener(ResultListEvents.newResultsDisplayed, () =>
ResultListUtils.hideIfInfiniteScrollEnabled(this)
);
}
private getMaxNumberOfPagesForCurrentResultsPerPage() {
return Math.ceil(this.options.maximumNumberOfResultsFromIndex / this.searchInterface.resultsPerPage);
}
private handleNewQuery(data: INewQueryEventArgs) {
const triggeredByPagerOrDebugMode = data && data.origin && (data.origin.type == Pager.ID || data.origin.type == 'Debug');
if (this.needToReset && !triggeredByPagerOrDebugMode) {
this.currentPage = 1;
this.updateQueryStateModel(this.getFirstResultNumber(this.currentPage));
}
this.needToReset = true;
}
private updateQueryStateModel(attrValue: number) {
this.listenToQueryStateChange = false;
this.queryStateModel.set(QueryStateModel.attributesEnum.first, attrValue);
this.listenToQueryStateChange = true;
}
private handleQueryError() {
this.reset();
}
private handleQuerySuccess(data: IQuerySuccessEventArgs) {
this.reset();
if (this.ignoreNextQuerySuccess) {
this.ignoreNextQuerySuccess = false;
} else {
Assert.isNotUndefined(data);
const firstResult = data.query.firstResult;
const count = data.results.totalCountFiltered;
const pagerBoundary = this.computePagerBoundary(firstResult, count);
this.currentPage = pagerBoundary.currentPage;
if (pagerBoundary.end - pagerBoundary.start > 0) {
for (let i = pagerBoundary.start; i <= pagerBoundary.end; i++) {
const listItemValue = $$(
'a',
{
className: 'coveo-pager-list-item-text coveo-pager-anchor',
tabindex: -1,
ariaHidden: 'true'
},
i.toString(10)
).el;
const page = i;
const listItem = $$('li', {
className: 'coveo-pager-list-item',
tabindex: 0
}).el;
const isCurrentPage = page === this.currentPage;
if (isCurrentPage) {
$$(listItem).addClass('coveo-active');
}
$$(listItem).setAttribute('aria-pressed', isCurrentPage.toString());
const clickAction = () => this.handleClickPage(page);
new AccessibleButton()
.withElement(listItem)
.withLabel(l('PageNumber', i.toString(10)))
.withClickAction(clickAction)
.withEnterKeyboardAction(clickAction)
.build();
listItem.appendChild(listItemValue);
this.list.appendChild(listItem);
}
if (this.options.enableNavigationButton && pagerBoundary.lastResultPage > 1) {
this.renderNavigationButton(pagerBoundary);
}
}
}
}
private handleNoResults(data: INoResultsEventArgs) {
let lastValidPage;
if (data.results.totalCount > 0) {
// First scenario : The index returned less results than expected (because of folding).
// Recalculate the last valid page, and change to that new page.
const possibleValidPage = this.computePagerBoundary(data.results.totalCountFiltered, data.results.totalCount).lastResultPage;
if (this.currentPage > possibleValidPage) {
lastValidPage = possibleValidPage;
}
} else if (this.currentPage > this.getMaxNumberOfPagesForCurrentResultsPerPage()) {
// Second scenario : Someone tried to access a non-valid page by the URL for example, which is higher than the current possible with the number of
// possible results. The last valid page will be the maximum number of results avaiable from the index.
lastValidPage = this.getMaxNumberOfPagesForCurrentResultsPerPage();
}
// This needs to be deferred because we still want all the "querySuccess" callbacks the complete their execution
// before triggering/queuing the next query;
// if we cannot find a lastValidPage to go to, do nothing : this means it's a query that simply return nothing.
if (lastValidPage != null) {
this.currentPage = lastValidPage;
data.retryTheQuery = true;
this.needToReset = false;
this.ignoreNextQuerySuccess = false;
this.updateQueryStateModel(this.getFirstResultNumber(this.currentPage));
}
}
private reset() {
$$(this.list).empty();
}
private handleBuildingQuery(data: IBuildingQueryEventArgs) {
Assert.exists(data);
const eventArgs = this.getQueryEventArgs();
data.queryBuilder.firstResult = eventArgs.first;
// Set the number of results only if it was not already set by external code
// Most of the time this will be set by either : the SearchInterface with the resultsPerPage option
// Or by the ResultsPerPage component (so the end user decides).
// Pager will realistically never set this value itself.
if (data.queryBuilder.numberOfResults == null) {
data.queryBuilder.numberOfResults = eventArgs.count;
}
const maxResultNumber = data.queryBuilder.firstResult + data.queryBuilder.numberOfResults;
const numOfExcessResults = Math.max(0, maxResultNumber - this.options.maximumNumberOfResultsFromIndex);
data.queryBuilder.numberOfResults -= numOfExcessResults;
}
private computePagerBoundary(firstResult: number, totalCount: number) {
const resultPerPage = this.searchInterface.resultsPerPage;
const currentPage = Math.floor(firstResult / resultPerPage) + 1;
const lastPageNumber = Math.max(Math.min(Math.ceil(totalCount / resultPerPage), this.getMaxNumberOfPagesForCurrentResultsPerPage()), 1);
const halfLength = Math.floor(this.options.numberOfPages / 2);
const firstPageNumber = Math.max(Math.min(currentPage - halfLength, lastPageNumber - this.options.numberOfPages + 1), 1);
const endPageNumber = Math.min(firstPageNumber + this.options.numberOfPages - 1, lastPageNumber);
return {
start: firstPageNumber,
end: endPageNumber,
lastResultPage: lastPageNumber,
currentPage: currentPage
};
}
private renderNavigationButton(pagerBoundary: { start: number; end: number; lastResultPage: number; currentPage: number }) {
if (this.currentPage > 1) {
const previous = this.renderPreviousButton();
this.list.insertBefore(previous.el, this.list.firstChild);
}
if (this.currentPage < pagerBoundary.lastResultPage) {
const next = this.renderNextButton();
this.list.appendChild(next.el);
}
}
private renderPreviousButton() {
const previousButton = $$('li', {
className: 'coveo-pager-previous coveo-pager-anchor coveo-pager-list-item'
});
const previousLink = $$('a', {
title: l('Previous'),
tabindex: -1,
ariaHidden: 'true'
});
const previousIcon = $$(
'span',
{
className: 'coveo-pager-previous-icon'
},
SVGIcons.icons.pagerLeftArrow
);
SVGDom.addClassToSVGInContainer(previousIcon.el, 'coveo-pager-previous-icon-svg');
previousLink.append(previousIcon.el);
previousButton.append(previousLink.el);
new AccessibleButton()
.withElement(previousButton)
.withLabel(l('Previous'))
.withSelectAction(() => this.handleClickPrevious())
.build();
return previousButton;
}
private renderNextButton() {
const nextButton = $$('li', {
className: 'coveo-pager-next coveo-pager-anchor coveo-pager-list-item'
});
const nextLink = $$('a', {
title: l('Next'),
tabindex: -1,
ariaHidden: 'true'
});
const nextIcon = $$(
'span',
{
className: 'coveo-pager-next-icon'
},
SVGIcons.icons.pagerRightArrow
);
SVGDom.addClassToSVGInContainer(nextIcon.el, 'coveo-pager-next-icon-svg');
nextLink.append(nextIcon.el);
nextButton.append(nextLink.el);
new AccessibleButton()
.withElement(nextButton)
.withLabel(l('Next'))
.withSelectAction(() => this.handleClickNext())
.build();
return nextButton;
}
private handleQueryStateFirstResultChanged(data: IAttributeChangedEventArg) {
if (!this.listenToQueryStateChange) {
return;
}
Assert.exists(data);
this.needToReset = false;
const firstResult = data.value;
this.currentPage = this.fromFirstResultsToPageNumber(firstResult);
}
private handleQueryStateNumberOfResultsPerPageChanged(data: IAttributeChangedEventArg) {
const firstResult = this.queryStateModel.get(QUERY_STATE_ATTRIBUTES.FIRST);
this.searchInterface.resultsPerPage = data.value;
this.currentPage = this.fromFirstResultsToPageNumber(firstResult);
}
private handleClickPage(pageNumber: number) {
Assert.exists(pageNumber);
this.setPage(pageNumber);
}
private handleClickPrevious() {
this.previousPage();
}
private handleClickNext() {
this.nextPage();
}
private fromFirstResultsToPageNumber(firstResult: number): number {
return firstResult / this.searchInterface.resultsPerPage + 1;
}
private getFirstResultNumber(pageNumber: number = this.currentPage): number {
return (pageNumber - 1) * this.searchInterface.resultsPerPage;
}
private getQueryEventArgs() {
return {
count: this.searchInterface.resultsPerPage,
first: this.getFirstResultNumber()
};
}
}
Initialization.registerAutoCreateComponent(Pager); | the_stack |
import * as Common from '../../core/common/common.js';
import * as Platform from '../../core/platform/platform.js';
import * as Bindings from '../../models/bindings/bindings.js';
import * as Persistence from '../../models/persistence/persistence.js';
import * as TextUtils from '../../models/text_utils/text_utils.js';
import * as Workspace from '../../models/workspace/workspace.js';
import type * as Search from '../search/search.js';
export class SourcesSearchScope implements Search.SearchConfig.SearchScope {
private searchId: number;
private searchResultCandidates: Workspace.UISourceCode.UISourceCode[];
private searchResultCallback: ((arg0: Search.SearchConfig.SearchResult) => void)|null;
private searchFinishedCallback: ((arg0: boolean) => void)|null;
private searchConfig: Workspace.Workspace.ProjectSearchConfig|null;
constructor() {
// FIXME: Add title once it is used by search controller.
this.searchId = 0;
this.searchResultCandidates = [];
this.searchResultCallback = null;
this.searchFinishedCallback = null;
this.searchConfig = null;
}
private static filesComparator(
uiSourceCode1: Workspace.UISourceCode.UISourceCode, uiSourceCode2: Workspace.UISourceCode.UISourceCode): number {
if (uiSourceCode1.isDirty() && !uiSourceCode2.isDirty()) {
return -1;
}
if (!uiSourceCode1.isDirty() && uiSourceCode2.isDirty()) {
return 1;
}
const isFileSystem1 = uiSourceCode1.project().type() === Workspace.Workspace.projectTypes.FileSystem &&
!Persistence.Persistence.PersistenceImpl.instance().binding(uiSourceCode1);
const isFileSystem2 = uiSourceCode2.project().type() === Workspace.Workspace.projectTypes.FileSystem &&
!Persistence.Persistence.PersistenceImpl.instance().binding(uiSourceCode2);
if (isFileSystem1 !== isFileSystem2) {
return isFileSystem1 ? 1 : -1;
}
const url1 = uiSourceCode1.url();
const url2 = uiSourceCode2.url();
if (url1 && !url2) {
return -1;
}
if (!url1 && url2) {
return 1;
}
return Platform.StringUtilities.naturalOrderComparator(
uiSourceCode1.fullDisplayName(), uiSourceCode2.fullDisplayName());
}
performIndexing(progress: Common.Progress.Progress): void {
this.stopSearch();
const projects = this.projects();
const compositeProgress = new Common.Progress.CompositeProgress(progress);
for (let i = 0; i < projects.length; ++i) {
const project = projects[i];
const projectProgress = compositeProgress.createSubProgress(project.uiSourceCodes().length);
project.indexContent(projectProgress);
}
}
private projects(): Workspace.Workspace.Project[] {
const searchInAnonymousAndContentScripts =
Common.Settings.Settings.instance().moduleSetting('searchInAnonymousAndContentScripts').get();
return Workspace.Workspace.WorkspaceImpl.instance().projects().filter(project => {
if (project.type() === Workspace.Workspace.projectTypes.Service) {
return false;
}
if (!searchInAnonymousAndContentScripts && project.isServiceProject() &&
project.type() !== Workspace.Workspace.projectTypes.Formatter) {
return false;
}
if (!searchInAnonymousAndContentScripts && project.type() === Workspace.Workspace.projectTypes.ContentScripts) {
return false;
}
return true;
});
}
performSearch(
searchConfig: Workspace.Workspace.ProjectSearchConfig, progress: Common.Progress.Progress,
searchResultCallback: (arg0: Search.SearchConfig.SearchResult) => void,
searchFinishedCallback: (arg0: boolean) => void): void {
this.stopSearch();
this.searchResultCandidates = [];
this.searchResultCallback = searchResultCallback;
this.searchFinishedCallback = searchFinishedCallback;
this.searchConfig = searchConfig;
const promises = [];
const compositeProgress = new Common.Progress.CompositeProgress(progress);
const searchContentProgress = compositeProgress.createSubProgress();
const findMatchingFilesProgress = new Common.Progress.CompositeProgress(compositeProgress.createSubProgress());
for (const project of this.projects()) {
const weight = project.uiSourceCodes().length;
const findMatchingFilesInProjectProgress = findMatchingFilesProgress.createSubProgress(weight);
const filesMathingFileQuery = this.projectFilesMatchingFileQuery(project, searchConfig);
const promise =
project
.findFilesMatchingSearchRequest(searchConfig, filesMathingFileQuery, findMatchingFilesInProjectProgress)
.then(this.processMatchingFilesForProject.bind(
this, this.searchId, project, searchConfig, filesMathingFileQuery));
promises.push(promise);
}
Promise.all(promises).then(this.processMatchingFiles.bind(
this, this.searchId, searchContentProgress, this.searchFinishedCallback.bind(this, true)));
}
private projectFilesMatchingFileQuery(
project: Workspace.Workspace.Project, searchConfig: Workspace.Workspace.ProjectSearchConfig,
dirtyOnly?: boolean): string[] {
const result = [];
const uiSourceCodes = project.uiSourceCodes();
for (let i = 0; i < uiSourceCodes.length; ++i) {
const uiSourceCode = uiSourceCodes[i];
if (!uiSourceCode.contentType().isTextType()) {
continue;
}
const binding = Persistence.Persistence.PersistenceImpl.instance().binding(uiSourceCode);
if (binding && binding.network === uiSourceCode) {
continue;
}
if (dirtyOnly && !uiSourceCode.isDirty()) {
continue;
}
if (searchConfig.filePathMatchesFileQuery(uiSourceCode.fullDisplayName())) {
result.push(uiSourceCode.url());
}
}
result.sort(Platform.StringUtilities.naturalOrderComparator);
return result;
}
private processMatchingFilesForProject(
searchId: number, project: Workspace.Workspace.Project, searchConfig: Workspace.Workspace.ProjectSearchConfig,
filesMathingFileQuery: string[], files: string[]): void {
if (searchId !== this.searchId && this.searchFinishedCallback) {
this.searchFinishedCallback(false);
return;
}
files.sort(Platform.StringUtilities.naturalOrderComparator);
files = Platform.ArrayUtilities.intersectOrdered(
files, filesMathingFileQuery, Platform.StringUtilities.naturalOrderComparator);
const dirtyFiles = this.projectFilesMatchingFileQuery(project, searchConfig, true);
files = Platform.ArrayUtilities.mergeOrdered(files, dirtyFiles, Platform.StringUtilities.naturalOrderComparator);
const uiSourceCodes = [];
for (const file of files) {
const uiSourceCode = project.uiSourceCodeForURL(file);
if (!uiSourceCode) {
continue;
}
const script = Bindings.DefaultScriptMapping.DefaultScriptMapping.scriptForUISourceCode(uiSourceCode);
if (script && !script.isAnonymousScript()) {
continue;
}
uiSourceCodes.push(uiSourceCode);
}
uiSourceCodes.sort(SourcesSearchScope.filesComparator);
this.searchResultCandidates = Platform.ArrayUtilities.mergeOrdered(
this.searchResultCandidates, uiSourceCodes, SourcesSearchScope.filesComparator);
}
private processMatchingFiles(searchId: number, progress: Common.Progress.Progress, callback: () => void): void {
if (searchId !== this.searchId && this.searchFinishedCallback) {
this.searchFinishedCallback(false);
return;
}
const files = this.searchResultCandidates;
if (!files.length) {
progress.done();
callback();
return;
}
progress.setTotalWork(files.length);
let fileIndex = 0;
const maxFileContentRequests = 20;
let callbacksLeft = 0;
for (let i = 0; i < maxFileContentRequests && i < files.length; ++i) {
scheduleSearchInNextFileOrFinish.call(this);
}
function searchInNextFile(this: SourcesSearchScope, uiSourceCode: Workspace.UISourceCode.UISourceCode): void {
if (uiSourceCode.isDirty()) {
contentLoaded.call(this, uiSourceCode, uiSourceCode.workingCopy());
} else {
uiSourceCode.requestContent().then(deferredContent => {
contentLoaded.call(this, uiSourceCode, deferredContent.content || '');
});
}
}
function scheduleSearchInNextFileOrFinish(this: SourcesSearchScope): void {
if (fileIndex >= files.length) {
if (!callbacksLeft) {
progress.done();
callback();
return;
}
return;
}
++callbacksLeft;
const uiSourceCode = files[fileIndex++];
setTimeout(searchInNextFile.bind(this, uiSourceCode), 0);
}
function contentLoaded(
this: SourcesSearchScope, uiSourceCode: Workspace.UISourceCode.UISourceCode, content: string): void {
function matchesComparator(
a: TextUtils.ContentProvider.SearchMatch, b: TextUtils.ContentProvider.SearchMatch): number {
return a.lineNumber - b.lineNumber;
}
progress.incrementWorked(1);
let matches: TextUtils.ContentProvider.SearchMatch[] = [];
const searchConfig = (this.searchConfig as Workspace.Workspace.ProjectSearchConfig);
const queries = searchConfig.queries();
if (content !== null) {
for (let i = 0; i < queries.length; ++i) {
const nextMatches = TextUtils.TextUtils.performSearchInContent(
content, queries[i], !searchConfig.ignoreCase(), searchConfig.isRegex());
matches = Platform.ArrayUtilities.mergeOrdered(matches, nextMatches, matchesComparator);
}
}
if (matches && this.searchResultCallback) {
const searchResult = new FileBasedSearchResult(uiSourceCode, matches);
this.searchResultCallback(searchResult);
}
--callbacksLeft;
scheduleSearchInNextFileOrFinish.call(this);
}
}
stopSearch(): void {
++this.searchId;
}
}
export class FileBasedSearchResult implements Search.SearchConfig.SearchResult {
private readonly uiSourceCode: Workspace.UISourceCode.UISourceCode;
private readonly searchMatches: TextUtils.ContentProvider.SearchMatch[];
constructor(
uiSourceCode: Workspace.UISourceCode.UISourceCode, searchMatches: TextUtils.ContentProvider.SearchMatch[]) {
this.uiSourceCode = uiSourceCode;
this.searchMatches = searchMatches;
}
label(): string {
return this.uiSourceCode.displayName();
}
description(): string {
return this.uiSourceCode.fullDisplayName();
}
matchesCount(): number {
return this.searchMatches.length;
}
matchLineContent(index: number): string {
return this.searchMatches[index].lineContent;
}
matchRevealable(index: number): Object {
const match = this.searchMatches[index];
return this.uiSourceCode.uiLocation(match.lineNumber, match.columnNumber);
}
// TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
matchLabel(index: number): any {
return this.searchMatches[index].lineNumber + 1;
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "./models";
import * as Mappers from "./models/mappers";
import * as Parameters from "./models/parameters";
import { FormRecognizerClientContext } from "./formRecognizerClientContext";
class FormRecognizerClient extends FormRecognizerClientContext {
/**
* Initializes a new instance of the FormRecognizerClient class.
* @param endpoint Supported Cognitive Services endpoints (protocol and hostname, for example:
* https://westus2.api.cognitive.microsoft.com).
* @param credentials Subscription credentials which uniquely identify client subscription.
* @param [options] The parameter options
*/
constructor(credentials: msRest.ServiceClientCredentials, endpoint: string, options?: msRest.ServiceClientOptions) {
super(credentials, endpoint, options);
}
/**
* Create and train a custom model. The train request must include a source parameter that is
* either an externally accessible Azure Storage blob container Uri (preferably a Shared Access
* Signature Uri) or valid path to a data folder in a locally mounted drive. When local paths are
* specified, they must follow the Linux/Unix path format and be an absolute path rooted to the
* input mount configuration
* setting value e.g., if '{Mounts:Input}' configuration setting value is '/input' then a valid
* source path would be '/input/contosodataset'. All data to be trained is expected to be directly
* under the source folder. Subfolders are not supported. Models are trained using documents that
* are of the following content type - 'application/pdf', 'image/jpeg' and 'image/png'."
* Other type of content is ignored.
* @summary Train Model
* @param trainRequest Request object for training.
* @param [options] The optional parameters
* @returns Promise<Models.TrainCustomModelResponse>
*/
trainCustomModel(trainRequest: Models.TrainRequest, options?: msRest.RequestOptionsBase): Promise<Models.TrainCustomModelResponse>;
/**
* @param trainRequest Request object for training.
* @param callback The callback
*/
trainCustomModel(trainRequest: Models.TrainRequest, callback: msRest.ServiceCallback<Models.TrainResult>): void;
/**
* @param trainRequest Request object for training.
* @param options The optional parameters
* @param callback The callback
*/
trainCustomModel(trainRequest: Models.TrainRequest, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TrainResult>): void;
trainCustomModel(trainRequest: Models.TrainRequest, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TrainResult>, callback?: msRest.ServiceCallback<Models.TrainResult>): Promise<Models.TrainCustomModelResponse> {
return this.sendOperationRequest(
{
trainRequest,
options
},
trainCustomModelOperationSpec,
callback) as Promise<Models.TrainCustomModelResponse>;
}
/**
* Retrieve the keys that were
* extracted during the training of the specified model.
* @summary Get Keys
* @param id Model identifier.
* @param [options] The optional parameters
* @returns Promise<Models.GetExtractedKeysResponse>
*/
getExtractedKeys(id: string, options?: msRest.RequestOptionsBase): Promise<Models.GetExtractedKeysResponse>;
/**
* @param id Model identifier.
* @param callback The callback
*/
getExtractedKeys(id: string, callback: msRest.ServiceCallback<Models.KeysResult>): void;
/**
* @param id Model identifier.
* @param options The optional parameters
* @param callback The callback
*/
getExtractedKeys(id: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.KeysResult>): void;
getExtractedKeys(id: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.KeysResult>, callback?: msRest.ServiceCallback<Models.KeysResult>): Promise<Models.GetExtractedKeysResponse> {
return this.sendOperationRequest(
{
id,
options
},
getExtractedKeysOperationSpec,
callback) as Promise<Models.GetExtractedKeysResponse>;
}
/**
* Get information about all trained custom models
* @summary Get Models
* @param [options] The optional parameters
* @returns Promise<Models.GetCustomModelsResponse>
*/
getCustomModels(options?: msRest.RequestOptionsBase): Promise<Models.GetCustomModelsResponse>;
/**
* @param callback The callback
*/
getCustomModels(callback: msRest.ServiceCallback<Models.ModelsResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
getCustomModels(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ModelsResult>): void;
getCustomModels(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ModelsResult>, callback?: msRest.ServiceCallback<Models.ModelsResult>): Promise<Models.GetCustomModelsResponse> {
return this.sendOperationRequest(
{
options
},
getCustomModelsOperationSpec,
callback) as Promise<Models.GetCustomModelsResponse>;
}
/**
* Get information about a model.
* @summary Get Model
* @param id Model identifier.
* @param [options] The optional parameters
* @returns Promise<Models.GetCustomModelResponse>
*/
getCustomModel(id: string, options?: msRest.RequestOptionsBase): Promise<Models.GetCustomModelResponse>;
/**
* @param id Model identifier.
* @param callback The callback
*/
getCustomModel(id: string, callback: msRest.ServiceCallback<Models.ModelResult>): void;
/**
* @param id Model identifier.
* @param options The optional parameters
* @param callback The callback
*/
getCustomModel(id: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ModelResult>): void;
getCustomModel(id: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ModelResult>, callback?: msRest.ServiceCallback<Models.ModelResult>): Promise<Models.GetCustomModelResponse> {
return this.sendOperationRequest(
{
id,
options
},
getCustomModelOperationSpec,
callback) as Promise<Models.GetCustomModelResponse>;
}
/**
* Delete model artifacts.
* @summary Delete Model
* @param id The identifier of the model to delete.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteCustomModel(id: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param id The identifier of the model to delete.
* @param callback The callback
*/
deleteCustomModel(id: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param id The identifier of the model to delete.
* @param options The optional parameters
* @param callback The callback
*/
deleteCustomModel(id: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteCustomModel(id: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.sendOperationRequest(
{
id,
options
},
deleteCustomModelOperationSpec,
callback);
}
/**
* Extract key-value pairs from a given document. The input document must be of one of the
* supported content types - 'application/pdf', 'image/jpeg' or 'image/png'. A success response is
* returned in JSON.
* @summary Analyze Form
* @param id Model Identifier to analyze the document with.
* @param formStream A pdf document or image (jpg,png) file to analyze.
* @param [options] The optional parameters
* @returns Promise<Models.AnalyzeWithCustomModelResponse>
*/
analyzeWithCustomModel(id: string, formStream: msRest.HttpRequestBody, options?: Models.FormRecognizerClientAnalyzeWithCustomModelOptionalParams): Promise<Models.AnalyzeWithCustomModelResponse>;
/**
* @param id Model Identifier to analyze the document with.
* @param formStream A pdf document or image (jpg,png) file to analyze.
* @param callback The callback
*/
analyzeWithCustomModel(id: string, formStream: msRest.HttpRequestBody, callback: msRest.ServiceCallback<Models.AnalyzeResult>): void;
/**
* @param id Model Identifier to analyze the document with.
* @param formStream A pdf document or image (jpg,png) file to analyze.
* @param options The optional parameters
* @param callback The callback
*/
analyzeWithCustomModel(id: string, formStream: msRest.HttpRequestBody, options: Models.FormRecognizerClientAnalyzeWithCustomModelOptionalParams, callback: msRest.ServiceCallback<Models.AnalyzeResult>): void;
analyzeWithCustomModel(id: string, formStream: msRest.HttpRequestBody, options?: Models.FormRecognizerClientAnalyzeWithCustomModelOptionalParams | msRest.ServiceCallback<Models.AnalyzeResult>, callback?: msRest.ServiceCallback<Models.AnalyzeResult>): Promise<Models.AnalyzeWithCustomModelResponse> {
return this.sendOperationRequest(
{
id,
formStream,
options
},
analyzeWithCustomModelOperationSpec,
callback) as Promise<Models.AnalyzeWithCustomModelResponse>;
}
/**
* Batch Read Receipt operation. The response contains a field called 'Operation-Location', which
* contains the URL that you must use for your 'Get Read Receipt Result' operation.
* @param url Publicly reachable URL of an image.
* @param [options] The optional parameters
* @returns Promise<Models.BatchReadReceiptResponse>
*/
batchReadReceipt(url: string, options?: msRest.RequestOptionsBase): Promise<Models.BatchReadReceiptResponse>;
/**
* @param url Publicly reachable URL of an image.
* @param callback The callback
*/
batchReadReceipt(url: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param url Publicly reachable URL of an image.
* @param options The optional parameters
* @param callback The callback
*/
batchReadReceipt(url: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
batchReadReceipt(url: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<Models.BatchReadReceiptResponse> {
return this.sendOperationRequest(
{
url,
options
},
batchReadReceiptOperationSpec,
callback) as Promise<Models.BatchReadReceiptResponse>;
}
/**
* This interface is used for getting the analysis results of a 'Batch Read Receipt' operation. The
* URL to this interface should be retrieved from the 'Operation-Location' field returned from the
* 'Batch Read Receipt' operation.
* @param operationId Id of read operation returned in the response of a 'Batch Read Receipt'
* operation.
* @param [options] The optional parameters
* @returns Promise<Models.GetReadReceiptResultResponse>
*/
getReadReceiptResult(operationId: string, options?: msRest.RequestOptionsBase): Promise<Models.GetReadReceiptResultResponse>;
/**
* @param operationId Id of read operation returned in the response of a 'Batch Read Receipt'
* operation.
* @param callback The callback
*/
getReadReceiptResult(operationId: string, callback: msRest.ServiceCallback<Models.ReadReceiptResult>): void;
/**
* @param operationId Id of read operation returned in the response of a 'Batch Read Receipt'
* operation.
* @param options The optional parameters
* @param callback The callback
*/
getReadReceiptResult(operationId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ReadReceiptResult>): void;
getReadReceiptResult(operationId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ReadReceiptResult>, callback?: msRest.ServiceCallback<Models.ReadReceiptResult>): Promise<Models.GetReadReceiptResultResponse> {
return this.sendOperationRequest(
{
operationId,
options
},
getReadReceiptResultOperationSpec,
callback) as Promise<Models.GetReadReceiptResultResponse>;
}
/**
* Read Receipt operation. When you use the 'Batch Read Receipt' interface, the response contains a
* field called 'Operation-Location'. The 'Operation-Location' field contains the URL that you must
* use for your 'Get Read Receipt Result' operation.
* @param image An image stream.
* @param [options] The optional parameters
* @returns Promise<Models.BatchReadReceiptInStreamResponse>
*/
batchReadReceiptInStream(image: msRest.HttpRequestBody, options?: msRest.RequestOptionsBase): Promise<Models.BatchReadReceiptInStreamResponse>;
/**
* @param image An image stream.
* @param callback The callback
*/
batchReadReceiptInStream(image: msRest.HttpRequestBody, callback: msRest.ServiceCallback<void>): void;
/**
* @param image An image stream.
* @param options The optional parameters
* @param callback The callback
*/
batchReadReceiptInStream(image: msRest.HttpRequestBody, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
batchReadReceiptInStream(image: msRest.HttpRequestBody, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<Models.BatchReadReceiptInStreamResponse> {
return this.sendOperationRequest(
{
image,
options
},
batchReadReceiptInStreamOperationSpec,
callback) as Promise<Models.BatchReadReceiptInStreamResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const trainCustomModelOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "custom/train",
urlParameters: [
Parameters.endpoint
],
requestBody: {
parameterPath: "trainRequest",
mapper: {
...Mappers.TrainRequest,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.TrainResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getExtractedKeysOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "custom/models/{id}/keys",
urlParameters: [
Parameters.endpoint,
Parameters.id
],
responses: {
200: {
bodyMapper: Mappers.KeysResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getCustomModelsOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "custom/models",
urlParameters: [
Parameters.endpoint
],
responses: {
200: {
bodyMapper: Mappers.ModelsResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getCustomModelOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "custom/models/{id}",
urlParameters: [
Parameters.endpoint,
Parameters.id
],
responses: {
200: {
bodyMapper: Mappers.ModelResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const deleteCustomModelOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "custom/models/{id}",
urlParameters: [
Parameters.endpoint,
Parameters.id
],
responses: {
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const analyzeWithCustomModelOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "custom/models/{id}/analyze",
urlParameters: [
Parameters.endpoint,
Parameters.id
],
queryParameters: [
Parameters.keys
],
formDataParameters: [
Parameters.formStream
],
contentType: "multipart/form-data",
responses: {
200: {
bodyMapper: Mappers.AnalyzeResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const batchReadReceiptOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "prebuilt/receipt/asyncBatchAnalyze",
urlParameters: [
Parameters.endpoint
],
requestBody: {
parameterPath: {
url: "url"
},
mapper: {
...Mappers.ImageUrl,
required: true
}
},
responses: {
202: {
headersMapper: Mappers.BatchReadReceiptHeaders
},
default: {
bodyMapper: Mappers.ComputerVisionError
}
},
serializer
};
const getReadReceiptResultOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "prebuilt/receipt/operations/{operationId}",
urlParameters: [
Parameters.endpoint,
Parameters.operationId
],
responses: {
200: {
bodyMapper: Mappers.ReadReceiptResult
},
default: {
bodyMapper: Mappers.ComputerVisionError
}
},
serializer
};
const batchReadReceiptInStreamOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "prebuilt/receipt/asyncBatchAnalyze",
urlParameters: [
Parameters.endpoint
],
requestBody: {
parameterPath: "image",
mapper: {
required: true,
serializedName: "Image",
type: {
name: "Stream"
}
}
},
contentType: "application/octet-stream",
responses: {
202: {
headersMapper: Mappers.BatchReadReceiptInStreamHeaders
},
default: {
bodyMapper: Mappers.ComputerVisionError
}
},
serializer
};
export {
FormRecognizerClient,
FormRecognizerClientContext,
Models as FormRecognizerModels,
Mappers as FormRecognizerMappers
}; | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { LinkedServer } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { RedisManagementClient } from "../redisManagementClient";
import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro";
import { LroImpl } from "../lroImpl";
import {
RedisLinkedServerWithProperties,
LinkedServerListNextOptionalParams,
LinkedServerListOptionalParams,
RedisLinkedServerCreateParameters,
LinkedServerCreateOptionalParams,
LinkedServerCreateResponse,
LinkedServerDeleteOptionalParams,
LinkedServerGetOptionalParams,
LinkedServerGetResponse,
LinkedServerListResponse,
LinkedServerListNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing LinkedServer operations. */
export class LinkedServerImpl implements LinkedServer {
private readonly client: RedisManagementClient;
/**
* Initialize a new instance of the class LinkedServer class.
* @param client Reference to the service client
*/
constructor(client: RedisManagementClient) {
this.client = client;
}
/**
* Gets the list of linked servers associated with this redis cache (requires Premium SKU).
* @param resourceGroupName The name of the resource group.
* @param name The name of the redis cache.
* @param options The options parameters.
*/
public list(
resourceGroupName: string,
name: string,
options?: LinkedServerListOptionalParams
): PagedAsyncIterableIterator<RedisLinkedServerWithProperties> {
const iter = this.listPagingAll(resourceGroupName, name, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(resourceGroupName, name, options);
}
};
}
private async *listPagingPage(
resourceGroupName: string,
name: string,
options?: LinkedServerListOptionalParams
): AsyncIterableIterator<RedisLinkedServerWithProperties[]> {
let result = await this._list(resourceGroupName, name, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listNext(
resourceGroupName,
name,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listPagingAll(
resourceGroupName: string,
name: string,
options?: LinkedServerListOptionalParams
): AsyncIterableIterator<RedisLinkedServerWithProperties> {
for await (const page of this.listPagingPage(
resourceGroupName,
name,
options
)) {
yield* page;
}
}
/**
* Adds a linked server to the Redis cache (requires Premium SKU).
* @param resourceGroupName The name of the resource group.
* @param name The name of the Redis cache.
* @param linkedServerName The name of the linked server that is being added to the Redis cache.
* @param parameters Parameters supplied to the Create Linked server operation.
* @param options The options parameters.
*/
async beginCreate(
resourceGroupName: string,
name: string,
linkedServerName: string,
parameters: RedisLinkedServerCreateParameters,
options?: LinkedServerCreateOptionalParams
): Promise<
PollerLike<
PollOperationState<LinkedServerCreateResponse>,
LinkedServerCreateResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LinkedServerCreateResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, name, linkedServerName, parameters, options },
createOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Adds a linked server to the Redis cache (requires Premium SKU).
* @param resourceGroupName The name of the resource group.
* @param name The name of the Redis cache.
* @param linkedServerName The name of the linked server that is being added to the Redis cache.
* @param parameters Parameters supplied to the Create Linked server operation.
* @param options The options parameters.
*/
async beginCreateAndWait(
resourceGroupName: string,
name: string,
linkedServerName: string,
parameters: RedisLinkedServerCreateParameters,
options?: LinkedServerCreateOptionalParams
): Promise<LinkedServerCreateResponse> {
const poller = await this.beginCreate(
resourceGroupName,
name,
linkedServerName,
parameters,
options
);
return poller.pollUntilDone();
}
/**
* Deletes the linked server from a redis cache (requires Premium SKU).
* @param resourceGroupName The name of the resource group.
* @param name The name of the redis cache.
* @param linkedServerName The name of the linked server that is being added to the Redis cache.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
name: string,
linkedServerName: string,
options?: LinkedServerDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, name, linkedServerName, options },
deleteOperationSpec
);
}
/**
* Gets the detailed information about a linked server of a redis cache (requires Premium SKU).
* @param resourceGroupName The name of the resource group.
* @param name The name of the redis cache.
* @param linkedServerName The name of the linked server.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
name: string,
linkedServerName: string,
options?: LinkedServerGetOptionalParams
): Promise<LinkedServerGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, name, linkedServerName, options },
getOperationSpec
);
}
/**
* Gets the list of linked servers associated with this redis cache (requires Premium SKU).
* @param resourceGroupName The name of the resource group.
* @param name The name of the redis cache.
* @param options The options parameters.
*/
private _list(
resourceGroupName: string,
name: string,
options?: LinkedServerListOptionalParams
): Promise<LinkedServerListResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, name, options },
listOperationSpec
);
}
/**
* ListNext
* @param resourceGroupName The name of the resource group.
* @param name The name of the redis cache.
* @param nextLink The nextLink from the previous successful call to the List method.
* @param options The options parameters.
*/
private _listNext(
resourceGroupName: string,
name: string,
nextLink: string,
options?: LinkedServerListNextOptionalParams
): Promise<LinkedServerListNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, name, nextLink, options },
listNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const createOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/linkedServers/{linkedServerName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.RedisLinkedServerWithProperties
},
201: {
bodyMapper: Mappers.RedisLinkedServerWithProperties
},
202: {
bodyMapper: Mappers.RedisLinkedServerWithProperties
},
204: {
bodyMapper: Mappers.RedisLinkedServerWithProperties
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters9,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.name,
Parameters.linkedServerName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/linkedServers/{linkedServerName}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.name,
Parameters.linkedServerName
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/linkedServers/{linkedServerName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.RedisLinkedServerWithProperties
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.name,
Parameters.linkedServerName
],
headerParameters: [Parameters.accept],
serializer
};
const listOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/linkedServers",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.RedisLinkedServerWithPropertiesList
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.name
],
headerParameters: [Parameters.accept],
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.RedisLinkedServerWithPropertiesList
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.nextLink,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.name
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import {
axisBottom,
axisLeft,
axisTop,
BaseType,
scaleLinear,
scaleTime,
select as d3Select,
Selection,
timeMillisecond,
} from 'd3';
import { css, customElement, html, property } from 'lit-element';
import { render } from 'lit-html';
import { DateTime } from 'luxon';
import { autorun, observable } from 'mobx';
import '../../components/dot_spinner';
import { MiloBaseElement } from '../../components/milo_base';
import { HideTooltipEventDetail, ShowTooltipEventDetail } from '../../components/tooltip';
import { AppState, consumeAppState } from '../../context/app_state';
import { BuildState, consumeBuildState } from '../../context/build_state';
import { GA_ACTIONS, GA_CATEGORIES, trackEvent } from '../../libs/analytics_utils';
import { BUILD_STATUS_CLASS_MAP } from '../../libs/constants';
import { consumer } from '../../libs/context';
import { errorHandler, forwardWithoutMsg, reportError, reportRenderError } from '../../libs/error_handler';
import { enumerate } from '../../libs/iter_utils';
import { displayDuration, NUMERIC_TIME_FORMAT } from '../../libs/time_utils';
import { StepExt } from '../../models/step_ext';
import commonStyle from '../../styles/common_style.css';
const MARGIN = 10;
const TOP_AXIS_HEIGHT = 35;
const BOTTOM_AXIS_HEIGHT = 25;
const BORDER_SIZE = 1;
const HALF_BORDER_SIZE = BORDER_SIZE / 2;
const ROW_HEIGHT = 30;
const STEP_HEIGHT = 24;
const STEP_MARGIN = (ROW_HEIGHT - STEP_HEIGHT) / 2 - HALF_BORDER_SIZE;
const STEP_EXTRA_WIDTH = 2;
const TEXT_HEIGHT = 10;
const STEP_TEXT_OFFSET = ROW_HEIGHT / 2 + TEXT_HEIGHT / 2;
const TEXT_MARGIN = 10;
const SIDE_PANEL_WIDTH = 400;
const MIN_GRAPH_WIDTH = 500 + SIDE_PANEL_WIDTH;
const SIDE_PANEL_RECT_WIDTH = SIDE_PANEL_WIDTH - STEP_MARGIN * 2 - BORDER_SIZE * 2;
const STEP_IDENT = 15;
const LIST_ITEM_WIDTH = SIDE_PANEL_RECT_WIDTH - TEXT_MARGIN * 2;
const LIST_ITEM_HEIGHT = 16;
const LIST_ITEM_X_OFFSET = STEP_MARGIN + TEXT_MARGIN + BORDER_SIZE;
const LIST_ITEM_Y_OFFSET = STEP_MARGIN + (STEP_HEIGHT - LIST_ITEM_HEIGHT) / 2;
const V_GRID_LINE_MAX_GAP = 80;
const PREDEFINED_TIME_INTERVALS = [
// Values that can divide 1 day.
86400000, // 24hr
43200000, // 12hr
28800000, // 8hr
// Values that can divide 12 hours.
21600000, // 6hr
14400000, // 4hr
10800000, // 3hr
7200000, // 2hr
3600000, // 1hr
// Values that can divide 1 hour.
1800000, // 30min
1200000, // 20min
900000, // 15min
600000, // 10min
// Values that can divide 15 minutes.
300000, // 5min
180000, // 3min
120000, // 2min
60000, // 1min
// Values that can divide 1 minute.
30000, // 30s
20000, // 20s
15000, // 15s
10000, // 10s
// Values that can divide 15 seconds.
5000, // 5s
3000, // 3s
2000, // 2s
1000, // 1s
];
/**
* A utility function that helps assigning appropriate list numbers to steps.
* For example, if a step is the 1st child of the 2nd root step, the list number
* would be '2.1. '.
*
* @param rootSteps a list of root steps.
* @yields A tuple consist of the list number and the step.
*/
export function* traverseStepList(rootSteps: readonly StepExt[], prefix = ''): IterableIterator<[string, StepExt]> {
for (const step of rootSteps.values()) {
const listNum = prefix + (step.index + 1) + '.';
yield [listNum, step];
yield* traverseStepList(step.children, listNum);
}
}
@customElement('milo-timeline-tab')
@errorHandler(forwardWithoutMsg)
@consumer
export class TimelineTabElement extends MiloBaseElement {
@observable.ref
@consumeAppState()
appState!: AppState;
@observable.ref
@consumeBuildState()
buildState!: BuildState;
@observable.ref private totalWidth!: number;
@observable.ref private bodyWidth!: number;
// Don't set them as observable. When render methods update them, we don't
// want autorun to trigger this.renderTimeline() again.
@property() private headerEle!: HTMLDivElement;
@property() private footerEle!: HTMLDivElement;
@property() private sidePanelEle!: HTMLDivElement;
@property() private bodyEle!: HTMLDivElement;
// Properties shared between render methods.
private bodyHeight!: number;
private scaleTime!: d3.ScaleTime<number, number, never>;
private scaleStep!: d3.ScaleLinear<number, number, never>;
private timeInterval!: d3.TimeInterval;
private readonly nowTimestamp = Date.now();
private readonly now = DateTime.fromMillis(this.nowTimestamp);
private relativeTimeText!: Selection<SVGTextElement, unknown, null, undefined>;
connectedCallback() {
super.connectedCallback();
this.appState.selectedTabId = 'timeline';
trackEvent(GA_CATEGORIES.TIMELINE_TAB, GA_ACTIONS.TAB_VISITED, window.location.href);
const syncWidth = () => {
this.totalWidth = Math.max(window.innerWidth - 2 * MARGIN, MIN_GRAPH_WIDTH);
this.bodyWidth = this.totalWidth - SIDE_PANEL_WIDTH;
};
window.addEventListener('resize', syncWidth);
this.addDisposer(() => window.removeEventListener('resize', syncWidth));
syncWidth();
this.addDisposer(autorun(() => this.renderTimeline()));
}
protected render = reportRenderError(this, () => {
if (!this.buildState.build) {
return html`<div id="load">Loading <milo-dot-spinner></milo-load-spinner></div>`;
}
if (this.buildState.build.steps.length === 0) {
return html`<div id="no-steps">No steps were run.</div>`;
}
return html`<div id="timeline">${this.sidePanelEle}${this.headerEle}${this.bodyEle}${this.footerEle}</div>`;
});
private renderTimeline = reportError(this, () => {
const build = this.buildState.build;
if (!build || !build.startTime || build.steps.length === 0) {
return;
}
const startTime = build.startTime.toMillis();
const endTime = build.endTime?.toMillis() || this.nowTimestamp;
this.bodyHeight = build.steps.length * ROW_HEIGHT - BORDER_SIZE;
const padding = Math.ceil(((endTime - startTime) * STEP_EXTRA_WIDTH) / this.bodyWidth) / 2;
// Calc attributes shared among components.
this.scaleTime = scaleTime()
// Add a bit of padding to ensure everything renders in the viewport.
.domain([startTime - padding, endTime + padding])
// Ensure the right border is rendered within the viewport, while the left
// border overlaps with the right border of the side-panel.
.range([-HALF_BORDER_SIZE, this.bodyWidth - HALF_BORDER_SIZE]);
this.scaleStep = scaleLinear()
.domain([0, build.steps.length])
// Ensure the top and bottom borders are not rendered.
.range([-HALF_BORDER_SIZE, this.bodyHeight + HALF_BORDER_SIZE]);
const maxInterval = (endTime - startTime + 2 * padding) / (this.bodyWidth / V_GRID_LINE_MAX_GAP);
// Assign a default value here to make TSC happy.
let interval = PREDEFINED_TIME_INTERVALS[0];
// Find the largest interval that is no larger than the maximum interval.
// Use linear search because the array is relatively short.
for (const predefined of PREDEFINED_TIME_INTERVALS) {
interval = predefined;
if (maxInterval >= predefined) {
break;
}
}
this.timeInterval = timeMillisecond.every(interval)!;
// Render each component.
this.renderHeader();
this.renderFooter();
this.renderSidePanel();
this.renderBody();
});
private renderHeader() {
const build = this.buildState.build!;
this.headerEle = document.createElement('div');
const svg = d3Select(this.headerEle)
.attr('id', 'header')
.append('svg')
.attr('viewport', `0 0 ${this.totalWidth} ${TOP_AXIS_HEIGHT}`);
svg
.append('text')
.attr('x', TEXT_MARGIN)
.attr('y', TOP_AXIS_HEIGHT - TEXT_MARGIN / 2)
.attr('font-weight', '500')
.text('Build Start Time: ' + build.startTime!.toFormat(NUMERIC_TIME_FORMAT));
const headerRootGroup = svg
.append('g')
.attr('transform', `translate(${SIDE_PANEL_WIDTH}, ${TOP_AXIS_HEIGHT - HALF_BORDER_SIZE})`);
const topAxis = axisTop(this.scaleTime).ticks(this.timeInterval);
headerRootGroup.call(topAxis);
this.relativeTimeText = headerRootGroup
.append('text')
.style('opacity', 0)
.attr('id', 'relative-time')
.attr('fill', 'red')
.attr('y', -TEXT_HEIGHT - TEXT_MARGIN)
.attr('text-anchor', 'end');
// Top border for the side panel.
headerRootGroup.append('line').attr('x1', -SIDE_PANEL_WIDTH).attr('stroke', 'var(--default-text-color)');
}
private renderFooter() {
const build = this.buildState.build!;
this.footerEle = document.createElement('div');
const svg = d3Select(this.footerEle)
.attr('id', 'footer')
.append('svg')
.attr('viewport', `0 0 ${this.totalWidth} ${BOTTOM_AXIS_HEIGHT}`);
if (build.endTime) {
svg
.append('text')
.attr('x', TEXT_MARGIN)
.attr('y', TEXT_HEIGHT + TEXT_MARGIN / 2)
.attr('font-weight', '500')
.text('Build End Time: ' + build.endTime.toFormat(NUMERIC_TIME_FORMAT));
}
const footerRootGroup = svg.append('g').attr('transform', `translate(${SIDE_PANEL_WIDTH}, ${HALF_BORDER_SIZE})`);
const bottomAxis = axisBottom(this.scaleTime).ticks(this.timeInterval);
footerRootGroup.call(bottomAxis);
// Bottom border for the side panel.
footerRootGroup.append('line').attr('x1', -SIDE_PANEL_WIDTH).attr('stroke', 'var(--default-text-color)');
}
private renderSidePanel() {
const build = this.buildState.build!;
this.sidePanelEle = document.createElement('div');
const svg = d3Select(this.sidePanelEle)
.style('width', SIDE_PANEL_WIDTH + 'px')
.style('height', this.bodyHeight + 'px')
.attr('id', 'side-panel')
.append('svg')
.attr('viewport', `0 0 ${SIDE_PANEL_WIDTH} ${this.bodyHeight}`);
// Grid lines
const horizontalGridLines = axisLeft(this.scaleStep)
.ticks(build.steps.length)
.tickFormat(() => '')
.tickSize(-SIDE_PANEL_WIDTH)
.tickFormat(() => '');
svg.append('g').attr('class', 'grid').call(horizontalGridLines);
for (const [i, [listNum, step]] of enumerate(traverseStepList(build.rootSteps))) {
const stepGroup = svg
.append('g')
.attr('class', BUILD_STATUS_CLASS_MAP[step.status])
.attr('transform', `translate(0, ${i * ROW_HEIGHT})`);
const rect = stepGroup
.append('rect')
.attr('x', STEP_MARGIN + BORDER_SIZE)
.attr('y', STEP_MARGIN)
.attr('width', SIDE_PANEL_RECT_WIDTH)
.attr('height', STEP_HEIGHT);
this.installStepInteractionHandlers(rect, step);
const listItem = stepGroup
.append('foreignObject')
.attr('class', 'not-intractable')
.attr('x', LIST_ITEM_X_OFFSET + step.depth * STEP_IDENT)
.attr('y', LIST_ITEM_Y_OFFSET)
.attr('height', STEP_HEIGHT - LIST_ITEM_Y_OFFSET)
.attr('width', LIST_ITEM_WIDTH);
listItem.append('xhtml:span').text(listNum + ' ');
const stepText = listItem.append('xhtml:span').text(step.selfName);
if (step.logs?.[0].viewUrl) {
stepText.attr('class', 'hyperlink');
}
}
// Left border.
svg
.append('line')
.attr('x1', HALF_BORDER_SIZE)
.attr('x2', HALF_BORDER_SIZE)
.attr('y2', this.bodyHeight)
.attr('stroke', 'var(--default-text-color)');
// Right border.
svg
.append('line')
.attr('x1', SIDE_PANEL_WIDTH - HALF_BORDER_SIZE)
.attr('x2', SIDE_PANEL_WIDTH - HALF_BORDER_SIZE)
.attr('y2', this.bodyHeight)
.attr('stroke', 'var(--default-text-color)');
}
private renderBody() {
const build = this.buildState.build!;
this.bodyEle = document.createElement('div');
const svg = d3Select(this.bodyEle)
.attr('id', 'body')
.style('width', this.bodyWidth + 'px')
.style('height', this.bodyHeight + 'px')
.append('svg')
.attr('viewport', `0 0 ${this.bodyWidth} ${this.bodyHeight}`);
// Grid lines
const verticalGridLines = axisTop(this.scaleTime)
.ticks(this.timeInterval)
.tickSize(-this.bodyHeight)
.tickFormat(() => '');
svg.append('g').attr('class', 'grid').call(verticalGridLines);
const horizontalGridLines = axisLeft(this.scaleStep)
.ticks(build.steps.length)
.tickFormat(() => '')
.tickSize(-this.bodyWidth)
.tickFormat(() => '');
svg.append('g').attr('class', 'grid').call(horizontalGridLines);
for (const [i, [listNum, step]] of enumerate(traverseStepList(build.rootSteps))) {
const start = this.scaleTime(step.startTime?.toMillis() || this.nowTimestamp);
const end = this.scaleTime(step.endTime?.toMillis() || this.nowTimestamp);
const stepGroup = svg
.append('g')
.attr('class', BUILD_STATUS_CLASS_MAP[step.status])
.attr('transform', `translate(${start}, ${i * ROW_HEIGHT})`);
// Add extra width so tiny steps are visible.
const width = end - start + STEP_EXTRA_WIDTH;
stepGroup
.append('rect')
.attr('x', -STEP_EXTRA_WIDTH / 2)
.attr('y', STEP_MARGIN)
.attr('width', width)
.attr('height', STEP_HEIGHT);
const isWide = width > this.bodyWidth * 0.33;
const nearEnd = end > this.bodyWidth * 0.66;
const stepText = stepGroup
.append('text')
.attr('text-anchor', isWide || !nearEnd ? 'start' : 'end')
.attr('x', isWide ? TEXT_MARGIN : nearEnd ? -TEXT_MARGIN : width + TEXT_MARGIN)
.attr('y', STEP_TEXT_OFFSET)
.text(listNum + ' ' + step.selfName);
// Wail until the next event cycle so stepText is rendered when we call
// this.getBBox();
window.setTimeout(() => {
// Rebind this so we can access it in the function below.
const timelineTab = this; // eslint-disable-line @typescript-eslint/no-this-alias
stepText.each(function () {
const textBBox = this.getBBox();
const x1 = Math.min(textBBox.x, -STEP_EXTRA_WIDTH / 2);
const x2 = Math.max(textBBox.x + textBBox.width, STEP_MARGIN + width);
// This makes the step text easier to interact with.
const eventTargetRect = stepGroup
.append('rect')
.attr('x', x1)
.attr('y', STEP_MARGIN)
.attr('width', x2 - x1)
.attr('height', STEP_HEIGHT)
.attr('class', 'invisible');
timelineTab.installStepInteractionHandlers(eventTargetRect, step);
});
}, 10);
}
const yRuler = svg
.append('line')
.style('opacity', 0)
.attr('stroke', 'red')
.attr('pointer-events', 'none')
.attr('y1', 0)
.attr('y2', this.bodyHeight);
let svgBox: DOMRect | null = null;
svg.on('mouseover', () => {
this.relativeTimeText.style('opacity', 1);
yRuler.style('opacity', 1);
});
svg.on('mouseout', () => {
this.relativeTimeText.style('opacity', 0);
yRuler.style('opacity', 0);
});
svg.on('mousemove', (e: MouseEvent) => {
if (svgBox === null) {
svgBox = svg.node()!.getBoundingClientRect();
}
const x = e.pageX - svgBox.x;
yRuler.attr('x1', x);
yRuler.attr('x2', x);
const time = DateTime.fromJSDate(this.scaleTime.invert(x));
const duration = time.diff(build.startTime!);
this.relativeTimeText.attr('x', x);
this.relativeTimeText.text(displayDuration(duration) + ' since build start');
});
// Right border.
svg
.append('line')
.attr('x1', this.bodyWidth - HALF_BORDER_SIZE)
.attr('x2', this.bodyWidth - HALF_BORDER_SIZE)
.attr('y2', this.bodyHeight)
.attr('stroke', 'var(--default-text-color)');
}
/**
* Installs handlers for interacting with a step object.
*/
private installStepInteractionHandlers<T extends BaseType>(
ele: Selection<T, unknown, null, undefined>,
step: StepExt
) {
const logUrl = step.logs?.[0].viewUrl;
if (logUrl) {
ele.attr('class', ele.attr('class') + ' clickable').on('click', (e: MouseEvent) => {
e.stopPropagation();
window.open(logUrl, '_blank');
});
}
ele
.on('mouseover', (e: MouseEvent) => {
const tooltip = document.createElement('div');
render(
html`
<table>
<tr>
<td colspan="2">${logUrl ? 'Click to open associated log.' : html`<b>No associated log.</b>`}</td>
</tr>
<tr>
<td>Started:</td>
<td>
${(step.startTime || this.now).toFormat(NUMERIC_TIME_FORMAT)}
(after ${displayDuration((step.startTime || this.now).diff(this.buildState.build!.startTime!))})
</td>
</tr>
<tr>
<td>Ended:</td>
<td>${
step.endTime
? step.endTime.toFormat(NUMERIC_TIME_FORMAT) +
` (after ${displayDuration(step.endTime.diff(this.buildState.build!.startTime!))})`
: 'N/A'
}</td>
</tr>
<tr>
<td>Duration:</td>
<td>${displayDuration(step.duration)}</td>
</tr>
</div>
`,
tooltip
);
window.dispatchEvent(
new CustomEvent<ShowTooltipEventDetail>('show-tooltip', {
detail: {
tooltip,
targetRect: (e.target as HTMLElement).getBoundingClientRect(),
gapSize: 5,
},
})
);
})
.on('mouseout', () => {
window.dispatchEvent(new CustomEvent<HideTooltipEventDetail>('hide-tooltip', { detail: { delay: 0 } }));
});
}
static styles = [
commonStyle,
css`
:host {
display: block;
margin: ${MARGIN}px;
}
#load {
color: var(--active-text-color);
}
#timeline {
display: grid;
grid-template-rows: ${TOP_AXIS_HEIGHT}px 1fr ${BOTTOM_AXIS_HEIGHT}px;
grid-template-columns: ${SIDE_PANEL_WIDTH}px 1fr;
grid-template-areas:
'header header'
'side-panel body'
'footer footer';
margin-top: ${-MARGIN}px;
}
#header {
grid-area: header;
position: sticky;
top: 0;
background: white;
z-index: 2;
}
#footer {
grid-area: footer;
position: sticky;
bottom: 0;
background: white;
z-index: 2;
}
#side-panel {
grid-area: side-panel;
z-index: 1;
font-weight: 500;
}
#body {
grid-area: body;
}
#body path.domain {
stroke: none;
}
svg {
width: 100%;
height: 100%;
}
text {
fill: var(--default-text-color);
}
#relative-time {
fill: red;
}
.grid line {
stroke: var(--divider-color);
}
.clickable {
cursor: pointer;
}
.not-intractable {
pointer-events: none;
}
.hyperlink {
text-decoration: underline;
}
.scheduled > rect {
stroke: var(--scheduled-color);
fill: var(--scheduled-bg-color);
}
.started > rect {
stroke: var(--started-color);
fill: var(--started-bg-color);
}
.success > rect {
stroke: var(--success-color);
fill: var(--success-bg-color);
}
.failure > rect {
stroke: var(--failure-color);
fill: var(--failure-bg-color);
}
.infra-failure > rect {
stroke: var(--critical-failure-color);
fill: var(--critical-failure-bg-color);
}
.canceled > rect {
stroke: var(--canceled-color);
fill: var(--canceled-bg-color);
}
.invisible {
opacity: 0;
}
`,
];
} | the_stack |
import { IndividualLinks } from "../demon.types";
/**
* Comment out places you do not want to be checked.
*
* Some second shots are listed separately as they are listed seperately
* on the doctor's page. in order to not confuse an initial user, these
* are commented out by default
*/
const individualLinks: IndividualLinks = [
{
bookingLink:
"https://www.doctolib.de/allgemeinmedizin/berlin/sophie-ruggeberg",
shot: "first",
vaccine: "astrazeneca",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2764198&agenda_ids=190434&insurance_sector=public&practice_ids=114976&destroy_temporary=true&limit=4",
},
{
bookingLink:
"https://www.doctolib.de/allgemeinmedizin/berlin/sophie-ruggeberg",
shot: "second",
vaccine: "astrazeneca",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2764199&agenda_ids=190434&insurance_sector=public&practice_ids=114976&limit=4",
},
{
bookingLink:
"https://www.doctolib.de/allgemeinmedizin/berlin/sophie-ruggeberg",
shot: "first",
vaccine: "johnsonAndJohnson",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2886231&agenda_ids=190434&insurance_sector=public&practice_ids=114976&limit=4",
},
{
bookingLink:
"https://www.doctolib.de/facharzt-fur-hno/berlin/babak-mayelzadeh",
shot: "first",
vaccine: "astrazeneca",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2862419&agenda_ids=305777&insurance_sector=public&practice_ids=120549&destroy_temporary=true&limit=4",
},
{
bookingLink:
"https://www.doctolib.de/facharzt-fur-hno/berlin/babak-mayelzadeh",
shot: "second",
vaccine: "astrazeneca",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2862420&agenda_ids=305777&insurance_sector=public&practice_ids=120549&limit=4",
},
{
bookingLink:
"https://www.doctolib.de/facharzt-fur-hno/berlin/babak-mayelzadeh",
shot: "first",
vaccine: "johnsonAndJohnson",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2879179&agenda_ids=305777&insurance_sector=public&practice_ids=120549&limit=4",
},
{
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-05-30&visit_motive_ids=2733996&agenda_ids=56915&insurance_sector=public&practice_ids=22563&destroy_temporary=true&limit=4",
// secondShotXhrLink: "" // this must have a second shot Xhr but i cant see it unless i get to the page
shot: "first",
vaccine: "biontech",
bookingLink: "https://www.doctolib.de/facharzt-fur-hno/berlin/rafael-hardy",
},
{
bookingLink:
"https://www.doctolib.de/innere-und-allgemeinmediziner/berlin/oliver-staeck",
// secondShotXhrLink: "" // this must have a second shot Xhr but i cant see it unless i get to the page
shot: "first",
vaccine: "astrazeneca",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2784656&agenda_ids=268801&insurance_sector=public&practice_ids=178663&limit=4",
},
{
bookingLink:
"https://www.doctolib.de/innere-und-allgemeinmediziner/berlin/oliver-staeck",
shot: "first",
vaccine: "johnsonAndJohnson",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2885945&agenda_ids=268801&insurance_sector=public&practice_ids=178663&limit=4",
},
{
bookingLink:
"https://www.doctolib.de/praxis/berlin/praxis-fuer-orthopaedie-und-unfallchirurgie-neukoelln",
shot: "first",
vaccine: "astrazeneca",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2811460&agenda_ids=464751&insurance_sector=public&practice_ids=28436&destroy_temporary=true&limit=4",
},
{
bookingLink:
"https://www.doctolib.de/praxis/berlin/praxis-fuer-orthopaedie-und-unfallchirurgie-neukoelln",
shot: "second",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2811461&agenda_ids=464751&insurance_sector=public&practice_ids=28436&limit=4",
vaccine: "astrazeneca",
},
{
bookingLink:
"https://www.doctolib.de/praxis/berlin/praxis-fuer-orthopaedie-und-unfallchirurgie-neukoelln",
shot: "first",
vaccine: "johnsonAndJohnson",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2811530&agenda_ids=464773&insurance_sector=public&practice_ids=28436&limit=4",
},
{
bookingLink:
"https://www.doctolib.de/medizinisches-versorgungszentrum-mvz/berlin/ambulantes-gynaekologisches-operationszentrum",
shot: "first",
vaccine: "biontech",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2757216&agenda_ids=439400&insurance_sector=public&practice_ids=107774&destroy_temporary=true&limit=4",
},
{
bookingLink:
"https://www.doctolib.de/medizinisches-versorgungszentrum-mvz/berlin/ambulantes-gynaekologisches-operationszentrum",
shot: "second",
vaccine: "biontech",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2757217&agenda_ids=439400&insurance_sector=public&practice_ids=107774&limit=4",
},
{
bookingLink:
"https://www.doctolib.de/medizinisches-versorgungszentrum-mvz/berlin/ambulantes-gynaekologisches-operationszentrum",
shot: "first",
vaccine: "astrazeneca",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2885841&agenda_ids=480139&insurance_sector=public&practice_ids=107774&destroy_temporary=true&limit=4",
},
{
bookingLink:
"https://www.doctolib.de/medizinisches-versorgungszentrum-mvz/berlin/ambulantes-gynaekologisches-operationszentrum",
shot: "second",
vaccine: "astrazeneca",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2885842&agenda_ids=480139&insurance_sector=public&practice_ids=107774&limit=4",
},
{
bookingLink:
"https://www.doctolib.de/medizinisches-versorgungszentrum-mvz/berlin/ambulantes-gynaekologisches-operationszentrum",
shot: "first",
vaccine: "johnsonAndJohnson",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2880391&agenda_ids=480095&insurance_sector=public&practice_ids=107774&limit=4",
},
{
bookingLink: `https://www.doctolib.de/institut/berlin/ciz-berlin-berlin?pid=practice-158434`,
secondShotXhrLink: `https://www.doctolib.de/second_shot_availabilities.json?start_date=2021-06-28&visit_motive_ids=2495719&agenda_ids=457591-457443-457477-457487-457405-457414-457511-457594-457432-397846-457408-457421-457435-457489-457563-457567-457569-457439-457493-457453-457406-457416-457418-457426-457400-457404-457409-457419-457420-457427-457448-457483-457425-457428-457415-457504-457597-457566-457412-457457-457436-457463-397845-397844-457411-457497-457424-457429-457430-457442-457470-404659-457596-457407-457410-457593&first_slot=2021-05-19T13%3A30%3A00.000%2B02%3A00&insurance_sector=public&practice_ids=158434&limit=4`,
shot: "first",
vaccine: "biontech",
xhrLink: `https://www.doctolib.de/availabilities.json?start_date=2021-05-11&visit_motive_ids=2495719&agenda_ids=457591-457443-457477-457487-457405-457414-457511-457594-457432-397846-457408-457421-457435-457489-457563-457567-457569-457439-457493-457453-457406-457416-457418-457426-457400-457404-457409-457419-457420-457427-457448-457483-457425-457428-457415-457504-457597-457566-457412-457457-457436-457463-397845-397844-457411-457497-457424-457429-457430-457442-457470-404659-457596-457407-457410-457593&insurance_sector=public&practice_ids=158434&destroy_temporary=true&limit=4`,
},
{
bookingLink: `https://www.doctolib.de/institut/berlin/ciz-berlin-berlin?pid=practice-158431`,
// secondShotXhrLink: "" // this must have a second shot Xhr but i cant see it unless i get to the page
shot: "first",
vaccine: "biontech",
xhrLink: `https://www.doctolib.de/availabilities.json?start_date=2021-05-11&visit_motive_ids=2495719&agenda_ids=397800-397776-402408-397766&insurance_sector=public&practice_ids=158431&destroy_temporary=true&limit=4`,
},
{
bookingLink: `https://www.doctolib.de/institut/berlin/ciz-berlin-berlin?pid=practice-158435`,
// secondShotXhrLink: "" // this must have a second shot Xhr but i cant see it unless i get to the page
shot: "first",
vaccine: "biontech",
xhrLink: `https://www.doctolib.de/availabilities.json?start_date=2021-05-11&visit_motive_ids=2495719&agenda_ids=404654-457215-457244-397972-457210-457239-457213-457278-457283-457304-457306-457229-457234-457299-457212-457216-457288-457291-457315-457227-457204-457237-457296-397974-457312-457280-457206-457310-457319-397973-457243-457208-457218-457245-457274-457321&insurance_sector=public&practice_ids=158435&destroy_temporary=true&limit=4`,
},
{
bookingLink: `https://www.doctolib.de/institut/berlin/ciz-berlin-berlin?pid=practice-158436`,
// secondShotXhrLink: "" // this must have a second shot Xhr but i cant see it unless i get to the page
shot: "first",
vaccine: "biontech",
xhrLink: `https://www.doctolib.de/availabilities.json?start_date=2021-05-11&visit_motive_ids=2495719&agenda_ids=457379-457323-457329-457334-457346-457253-457255-457256-457294-457317-457335-457399-457514-457350-457326-457330-457254-457267-457303-457275-457276-457281-457289-457300-457301-457302-457307-457309-457314-457331-457388-457515-457338-457263-457266-457277-457286-457287-457308-457320-457343-457268-457500-397841-457512-457382-457385-457324-457460-457513-457285-457392-457395-457251-397843-457252-457264-457271-457279-457290-457292-457318-457358-457327-457341-457293-457250-457305-457377-457396-457333-457349-457265-457313-457316-457295-457390-457363-457282-457297-397842-457336-457337-457413-404656-457510&insurance_sector=public&practice_ids=158436&destroy_temporary=true&limit=4`,
},
{
bookingLink: `https://www.doctolib.de/krankenhaus/berlin/gkh-havelhoehe-impfzentrum`,
shot: "first",
vaccine: "astrazeneca",
xhrLink: `https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2836657&agenda_ids=469719&insurance_sector=public&practice_ids=162056&destroy_temporary=true&limit=4`,
},
{
bookingLink: `https://www.doctolib.de/krankenhaus/berlin/gkh-havelhoehe-impfzentrum`,
shot: "second",
vaccine: "astrazeneca",
xhrLink: `https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2836662&agenda_ids=469719&insurance_sector=public&practice_ids=162056&limit=4`,
},
{
bookingLink:
"https://www.doctolib.de/krankenhaus/berlin/gkh-havelhoehe-impfzentrum",
shot: "first",
vaccine: "johnsonAndJohnson",
xhrLink:
"https://www.doctolib.de/availabilities.json?start_date=2021-06-01&visit_motive_ids=2898162&agenda_ids=469719&insurance_sector=public&practice_ids=162056&limit=4",
},
];
export default individualLinks; | the_stack |
import {createProbot, Probot, Options} from 'probot';
import {ApplicationFunction} from 'probot/lib/types';
import {createProbotAuth} from 'octokit-auth-probot';
import getStream from 'get-stream';
import intoStream from 'into-stream';
import * as http from 'http';
import {v1 as SecretManagerV1} from '@google-cloud/secret-manager';
import {v2 as CloudTasksV2} from '@google-cloud/tasks';
import {Storage} from '@google-cloud/storage';
import * as express from 'express';
// eslint-disable-next-line node/no-extraneous-import
import {Octokit} from '@octokit/rest';
import {config as ConfigPlugin} from '@probot/octokit-plugin-config';
import {buildTriggerInfo} from './logging/trigger-info-builder';
import {GCFLogger} from './logging/gcf-logger';
import {v4} from 'uuid';
import {getServer} from './server/server';
import {run} from '@googleapis/run';
import {GoogleAuth} from 'google-auth-library';
// On Cloud Functions, rawBody is automatically added.
// It's not guaranteed on other platform.
export interface RequestWithRawBody extends express.Request {
rawBody?: Buffer;
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const LoggingOctokitPlugin = require('../src/logging/logging-octokit-plugin.js');
export type HandlerFunction = (
request: RequestWithRawBody,
response: express.Response
) => Promise<void>;
type CronType = 'repository' | 'installation' | 'global';
const DEFAULT_CRON_TYPE: CronType = 'repository';
const SCHEDULER_GLOBAL_EVENT_NAME = 'schedule.global';
const SCHEDULER_INSTALLATION_EVENT_NAME = 'schedule.installation';
const SCHEDULER_REPOSITORY_EVENT_NAME = 'schedule.repository';
const SCHEDULER_EVENT_NAMES = [
SCHEDULER_GLOBAL_EVENT_NAME,
SCHEDULER_INSTALLATION_EVENT_NAME,
SCHEDULER_REPOSITORY_EVENT_NAME,
];
const RUNNING_IN_TEST = process.env.NODE_ENV === 'test';
type BotEnvironment = 'functions' | 'run';
interface Scheduled {
repo?: string;
installation: {
id: number;
};
message?: {[key: string]: string};
cron_type?: CronType;
cron_org?: string;
allowed_organizations?: string[];
}
interface EnqueueTaskParams {
body: string;
id: string;
name: string;
}
export interface WrapOptions {
// Whether or not to enqueue direct GitHub webhooks in a Cloud Task
// queue which provides a retry mechanism. Defaults to `true`.
// Deprecated. Please use `maxRetries` and `maxCronRetries` instead.
background?: boolean;
// Whether or not to automatically log Octokit requests. Defaults to
// `false`.
logging?: boolean;
// Whether or not to skip verification of request payloads. Defaults
// to `true` in test mode, otherwise `false`.
skipVerification?: boolean;
// Maximum number of attempts for webhook handlers. Defaults to `10`.
maxRetries?: number;
// Maximum number of attempts for cron handlers. Defaults to `0`.
maxCronRetries?: number;
// Maximum number of attempts for pubsub handlers. Defaults to `0`.
maxPubSubRetries?: number;
}
interface WrapConfig {
logging: boolean;
skipVerification: boolean;
maxCronRetries: number;
maxRetries: number;
maxPubSubRetries: number;
}
const DEFAULT_WRAP_CONFIG: WrapConfig = {
logging: false,
skipVerification: RUNNING_IN_TEST,
maxCronRetries: 0,
maxRetries: 10,
maxPubSubRetries: 0,
};
export const logger = new GCFLogger();
export interface CronPayload {
repository: {
name: string;
full_name: string;
owner: {
login: string;
name: string;
};
};
organization: {
login: string;
};
cron_org: string;
}
/**
* Type of function execution trigger
*/
export enum TriggerType {
GITHUB = 'GitHub Webhook',
SCHEDULER = 'Cloud Scheduler',
TASK = 'Cloud Task',
PUBSUB = 'Pub/Sub',
UNKNOWN = 'Unknown',
}
/**
* It creates a comment string used for `addOrUpdateissuecomment`.
*/
export const getCommentMark = (installationId: number): string => {
return `<!-- probot comment [${installationId}]-->`;
};
/**
* It creates a comment, or if the bot already created a comment, it
* updates the same comment.
*
* @param {Octokit} octokit - The Octokit instance.
* @param {string} owner - The owner of the issue.
* @param {string} repo - The name of the repository.
* @param {number} issueNumber - The number of the issue.
* @param {number} installationId - A unique number for identifying the issue
* comment.
* @param {string} commentBody - The body of the comment.
* @param {boolean} onlyUpdate - If set to true, it will only update an
* existing issue comment.
*/
export const addOrUpdateIssueComment = async (
octokit: Octokit,
owner: string,
repo: string,
issueNumber: number,
installationId: number,
commentBody: string,
onlyUpdate = false
) => {
const commentMark = getCommentMark(installationId);
const listCommentsResponse = await octokit.issues.listComments({
owner: owner,
repo: repo,
per_page: 50, // I think 50 is enough, but I may be wrong.
issue_number: issueNumber,
});
let found = false;
for (const comment of listCommentsResponse.data) {
if (comment.body?.includes(commentMark)) {
// We found the existing comment, so updating it
await octokit.issues.updateComment({
owner: owner,
repo: repo,
comment_id: comment.id,
body: `${commentMark}\n${commentBody}`,
});
found = true;
}
}
if (!found && !onlyUpdate) {
await octokit.issues.createComment({
owner: owner,
repo: repo,
issue_number: issueNumber,
body: `${commentMark}\n${commentBody}`,
});
}
};
interface BootstrapperOptions {
secretsClient?: SecretManagerV1.SecretManagerServiceClient;
tasksClient?: CloudTasksV2.CloudTasksClient;
projectId?: string;
functionName?: string;
location?: string;
payloadBucket?: string;
taskTargetEnvironment?: BotEnvironment;
}
function defaultTaskEnvironment(): BotEnvironment {
return process.env.BOT_RUNTIME === 'run' ? 'run' : 'functions';
}
export class GCFBootstrapper {
probot?: Probot;
secretsClient: SecretManagerV1.SecretManagerServiceClient;
cloudTasksClient: CloudTasksV2.CloudTasksClient;
storage: Storage;
projectId: string;
functionName: string;
location: string;
payloadBucket: string | undefined;
taskTargetEnvironment: BotEnvironment;
constructor(options?: BootstrapperOptions) {
options = {
...{
projectId: process.env.PROJECT_ID,
functionName: process.env.GCF_SHORT_FUNCTION_NAME,
location: process.env.GCF_LOCATION,
payloadBucket: process.env.WEBHOOK_TMP,
},
...options,
};
this.secretsClient =
options?.secretsClient ||
new SecretManagerV1.SecretManagerServiceClient();
this.cloudTasksClient =
options?.tasksClient || new CloudTasksV2.CloudTasksClient();
this.storage = new Storage({autoRetry: !RUNNING_IN_TEST});
this.taskTargetEnvironment =
options.taskTargetEnvironment || defaultTaskEnvironment();
if (!options.projectId) {
throw new Error(
'Missing required `projectId`. Please provide as a constructor argument or set the PROJECT_ID env variable.'
);
}
this.projectId = options.projectId;
if (!options.functionName) {
throw new Error(
'Missing required `functionName`. Please provide as a constructor argument or set the GCF_SHORT_FUNCTION_NAME env variable.'
);
}
this.functionName = options.functionName;
if (!options.location) {
throw new Error(
'Missing required `location`. Please provide as a constructor argument or set the GCF_LOCATION env variable.'
);
}
this.location = options.location;
this.payloadBucket = options.payloadBucket;
}
async loadProbot(
appFn: ApplicationFunction,
logging?: boolean
): Promise<Probot> {
if (!this.probot) {
const cfg = await this.getProbotConfig(logging);
this.probot = createProbot({overrides: cfg});
}
await this.probot.load(appFn);
return this.probot;
}
getSecretName(): string {
return `projects/${this.projectId}/secrets/${this.functionName}`;
}
getLatestSecretVersionName(): string {
const secretName = this.getSecretName();
return `${secretName}/versions/latest`;
}
async getProbotConfig(logging?: boolean): Promise<Options> {
const name = this.getLatestSecretVersionName();
const [version] = await this.secretsClient.accessSecretVersion({
name: name,
});
// Extract the payload as a string.
const payload = version?.payload?.data?.toString() || '';
if (payload === '') {
throw Error('did not retrieve a payload from SecretManager.');
}
const config = JSON.parse(payload);
if (Object.prototype.hasOwnProperty.call(config, 'cert')) {
config.privateKey = config.cert;
delete config.cert;
}
if (Object.prototype.hasOwnProperty.call(config, 'id')) {
config.appId = config.id;
delete config.id;
}
if (logging) {
logger.info('custom logging instance enabled');
const LoggingOctokit = Octokit.plugin(LoggingOctokitPlugin)
.plugin(ConfigPlugin)
.defaults({authStrategy: createProbotAuth});
return {...config, Octokit: LoggingOctokit} as Options;
} else {
logger.info('custom logging instance not enabled');
const DefaultOctokit = Octokit.plugin(ConfigPlugin).defaults({
authStrategy: createProbotAuth,
});
return {
...config,
Octokit: DefaultOctokit,
} as Options;
}
}
/**
* Parse the signature from the request headers.
*
* If the expected header is not set, returns `unset` because the verification
* function throws an exception on empty string when we would rather
* treat the error as an invalid signature.
* @param request incoming trigger request
*/
private static parseSignatureHeader(request: express.Request): string {
const sha1Signature =
request.get('x-hub-signature') || request.get('X-Hub-Signature');
if (sha1Signature) {
return sha1Signature;
}
return 'unset';
}
/**
* Parse the event name, delivery id, signature and task id from the request headers
* @param request incoming trigger request
*/
private static parseRequestHeaders(request: express.Request): {
name: string;
id: string;
signature: string;
taskId: string;
taskRetries: number;
} {
const name =
request.get('x-github-event') || request.get('X-GitHub-Event') || '';
const id =
request.get('x-github-delivery') ||
request.get('X-GitHub-Delivery') ||
'';
const signature = this.parseSignatureHeader(request);
const taskId =
request.get('X-CloudTasks-TaskName') ||
request.get('x-cloudtasks-taskname') ||
'';
const taskRetries = parseInt(
request.get('X-CloudTasks-TaskRetryCount') ||
request.get('x-cloudtasks-taskretrycount') ||
'0'
);
return {name, id, signature, taskId, taskRetries};
}
/**
* Determine the type of trigger that started this execution
* @param name event name from header
* @param taskId task id from header
*/
private static parseTriggerType(name: string, taskId: string): TriggerType {
if (!taskId && SCHEDULER_EVENT_NAMES.includes(name)) {
return TriggerType.SCHEDULER;
} else if (!taskId && name === 'pubsub.message') {
return TriggerType.PUBSUB;
} else if (!taskId && name) {
return TriggerType.GITHUB;
} else if (name) {
return TriggerType.TASK;
}
return TriggerType.UNKNOWN;
}
private parseWrapConfig(wrapOptions: WrapOptions | undefined): WrapConfig {
const wrapConfig: WrapConfig = {
...DEFAULT_WRAP_CONFIG,
...wrapOptions,
};
if (wrapOptions?.background !== undefined) {
logger.warn(
'`background` option has been deprecated in favor of `maxRetries` and `maxCronRetries`'
);
if (wrapOptions.background === false) {
wrapConfig.maxCronRetries = 0;
wrapConfig.maxRetries = 0;
wrapConfig.maxPubSubRetries = 0;
}
}
return wrapConfig;
}
private getRetryLimit(wrapConfig: WrapConfig, eventName: string) {
if (eventName.startsWith('schedule.')) {
return wrapConfig.maxCronRetries;
}
if (eventName.startsWith('pubsub.')) {
return wrapConfig.maxPubSubRetries;
}
return wrapConfig.maxRetries;
}
/**
* Wrap an ApplicationFunction in a http.Server that can be started
* directly.
* @param appFn {ApplicationFunction} The probot handler function
* @param wrapOptions {WrapOptions} Bot handler options
*/
server(appFn: ApplicationFunction, wrapOptions?: WrapOptions): http.Server {
return getServer(this.gcf(appFn, wrapOptions));
}
/**
* Wrap an ApplicationFunction in so it can be started in a Google
* Cloud Function.
* @param appFn {ApplicationFunction} The probot handler function
* @param wrapOptions {WrapOptions} Bot handler options
*/
gcf(appFn: ApplicationFunction, wrapOptions?: WrapOptions): HandlerFunction {
return async (request: RequestWithRawBody, response: express.Response) => {
const wrapConfig = this.parseWrapConfig(wrapOptions);
this.probot =
this.probot || (await this.loadProbot(appFn, wrapConfig.logging));
const {name, id, signature, taskId, taskRetries} =
GCFBootstrapper.parseRequestHeaders(request);
const triggerType: TriggerType = GCFBootstrapper.parseTriggerType(
name,
taskId
);
// validate the signature
if (
!wrapConfig.skipVerification &&
!(await this.probot.webhooks.verify(
request.rawBody ? request.rawBody.toString() : request.body,
signature
))
) {
response.status(400).send({
statusCode: 400,
body: JSON.stringify({message: 'Invalid signature'}),
});
return;
}
/**
* Note: any logs written before resetting bindings may contain
* bindings from previous executions
*/
logger.resetBindings();
logger.addBindings(buildTriggerInfo(triggerType, id, name, request.body));
try {
if (triggerType === TriggerType.UNKNOWN) {
response.sendStatus(400);
return;
} else if (triggerType === TriggerType.SCHEDULER) {
// Cloud scheduler tasks (cron)
await this.handleScheduled(id, request, wrapConfig);
} else if (triggerType === TriggerType.PUBSUB) {
const payload = this.parsePubSubPayload(request);
await this.enqueueTask({
id,
name,
body: JSON.stringify(payload),
});
} else if (triggerType === TriggerType.TASK) {
const maxRetries = this.getRetryLimit(wrapConfig, name);
// Abort task retries if we've hit the max number by
// returning "success"
if (taskRetries > maxRetries) {
logger.metric('too-many-retries');
logger.info(`Too many retries: ${taskRetries} > ${maxRetries}`);
// return 200 so we don't retry the task again
response.send({
statusCode: 200,
body: JSON.stringify({message: 'Too many retries'}),
});
return;
}
// If the payload contains `tmpUrl` this indicates that the original
// payload has been written to Cloud Storage; download it.
const payload = await this.maybeDownloadOriginalBody(request.body);
// The payload does not exist, stop retrying on this task by letting
// this request "succeed".
if (!payload) {
logger.metric('payload-expired');
response.send({
statusCode: 200,
body: JSON.stringify({message: 'Payload expired'}),
});
return;
}
// TODO: find out the best way to get this type, and whether we can
// keep using a custom event name.
await this.probot.receive({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
name: name as any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
id: id as any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
payload: payload as any,
});
} else if (triggerType === TriggerType.GITHUB) {
await this.enqueueTask({
id,
name,
body: JSON.stringify(request.body),
});
}
response.send({
statusCode: 200,
body: JSON.stringify({message: 'Executed'}),
});
} catch (err) {
logger.error(err);
response.status(500).send({
statusCode: 500,
body: JSON.stringify({message: err.message}),
});
return;
}
logger.flushSync();
};
}
/**
* Entrypoint for handling all scheduled tasks.
*
* @param id {string} GitHub delivery GUID
* @param body {Scheduled} Scheduler params. May contain additional request
* parameters besides the ones defined by the Scheduled type.
* @param signature
* @param wrapConfig
*/
private async handleScheduled(
id: string,
req: express.Request,
wrapConfig: WrapConfig
) {
const body: Scheduled = this.parseRequestBody(req);
const cronType = body.cron_type ?? DEFAULT_CRON_TYPE;
if (cronType === 'global') {
await this.handleScheduledGlobal(id, body);
} else if (cronType === 'installation') {
await this.handleScheduledInstallation(id, body, wrapConfig);
} else {
await this.handleScheduledRepository(id, body, wrapConfig);
}
}
/**
* Handle a scheduled tasks that should run once. Queues up a Cloud Task
* for the `schedule.global` event.
*
* @param id {string} GitHub delivery GUID
* @param body {Scheduled} Scheduler params. May contain additional request
* parameters besides the ones defined by the Scheduled type.
* @param signature
*/
private async handleScheduledGlobal(id: string, body: Scheduled) {
await this.enqueueTask({
id,
name: SCHEDULER_GLOBAL_EVENT_NAME,
body: JSON.stringify(body),
});
}
/**
* Async iterator over each installation for an app.
*
* See https://docs.github.com/en/rest/reference/apps#list-installations-for-the-authenticated-app
* @param wrapConfig {WrapConfig}
*/
private async *eachInstallation(wrapConfig: WrapConfig) {
const octokit = await this.getAuthenticatedOctokit(undefined, wrapConfig);
const installationsPaginated = octokit.paginate.iterator(
octokit.apps.listInstallations
);
for await (const response of installationsPaginated) {
for (const installation of response.data) {
if (installation.suspended_at !== null) {
// Assume the installation is suspended.
logger.info(
`skipping installations for ${installation.id} because it is suspended`
);
continue;
}
yield installation;
}
}
}
/**
* Async iterator over each repository for an app installation.
*
* See https://docs.github.com/en/rest/reference/apps#list-repositories-accessible-to-the-app-installation
* @param wrapConfig {WrapConfig}
*/
private async *eachInstalledRepository(
installationId: number,
wrapConfig: WrapConfig
) {
const octokit = await this.getAuthenticatedOctokit(
installationId,
wrapConfig
);
const installationRepositoriesPaginated = octokit.paginate.iterator(
octokit.apps.listReposAccessibleToInstallation,
{
mediaType: {
previews: ['machine-man'],
},
}
);
for await (const response of installationRepositoriesPaginated) {
for (const repo of response.data) {
yield repo;
}
}
}
/**
* Handle a scheduled tasks that should run per-installation.
*
* If an installation is specified (via installation.id in the payload),
* queue up a Cloud Task (`schedule.installation`) for that installation
* only. Otherwise, list all installations of the app and queue up a
* Cloud Task for each installation.
*
* @param id {string} GitHub delivery GUID
* @param body {Scheduled} Scheduler params. May contain additional request
* parameters besides the ones defined by the Scheduled type.
* @param wrapConfig
*/
private async handleScheduledInstallation(
id: string,
body: Scheduled,
wrapConfig: WrapConfig
) {
if (body.installation) {
await this.enqueueTask({
id,
name: SCHEDULER_INSTALLATION_EVENT_NAME,
body: JSON.stringify(body),
});
} else {
const generator = this.eachInstallation(wrapConfig);
for await (const installation of generator) {
const extraParams: Scheduled = {
installation: {
id: installation.id,
},
};
if (
installation.target_type === 'Organization' &&
installation?.account?.login
) {
extraParams.cron_org = installation.account.login;
}
const payload = {
...body,
...extraParams,
};
await this.enqueueTask({
id,
name: SCHEDULER_INSTALLATION_EVENT_NAME,
body: JSON.stringify(payload),
});
}
}
}
/**
* Handle a scheduled tasks that should run per-repository.
*
* If a repository is specified (via repo in the payload), queue up a
* Cloud Task for that repository only. If an installation is specified
* (via installation.id in the payload), list all repositories associated
* with that installation and queue up a Cloud Task for each repository.
* If neither is specified, list all installations and all repositories
* for each installation, then queue up a Cloud Task for each repository.
*
* @param id {string} GitHub delivery GUID
* @param body {Scheduled} Scheduler params. May contain additional request
* parameters besides the ones defined by the Scheduled type.
* @param signature
* @param wrapConfig
*/
private async handleScheduledRepository(
id: string,
body: Scheduled,
wrapConfig: WrapConfig
) {
if (body.repo) {
// Job was scheduled for a single repository:
await this.scheduledToTask(
body.repo,
id,
body,
SCHEDULER_REPOSITORY_EVENT_NAME
);
} else if (body.installation) {
const generator = this.eachInstalledRepository(
body.installation.id,
wrapConfig
);
const promises: Array<Promise<void>> = new Array<Promise<void>>();
const batchSize = 30;
for await (const repo of generator) {
if (repo.archived === true || repo.disabled === true) {
continue;
}
promises.push(
this.scheduledToTask(
repo.full_name,
id,
body,
SCHEDULER_REPOSITORY_EVENT_NAME
)
);
if (promises.length >= batchSize) {
await Promise.all(promises);
promises.splice(0, promises.length);
}
}
// Wait for the rest.
if (promises.length > 0) {
await Promise.all(promises);
promises.splice(0, promises.length);
}
} else {
const installationGenerator = this.eachInstallation(wrapConfig);
const promises: Array<Promise<void>> = new Array<Promise<void>>();
const batchSize = 30;
for await (const installation of installationGenerator) {
if (body.allowed_organizations !== undefined) {
const org = installation?.account?.login.toLowerCase();
if (!body.allowed_organizations.includes(org)) {
logger.info(
`${org} is not allowed for this scheduler job, skipping`
);
continue;
}
}
const generator = this.eachInstalledRepository(
installation.id,
wrapConfig
);
const extraParams: Scheduled = {
installation: {
id: installation.id,
},
};
if (
installation.target_type === 'Organization' &&
installation?.account?.login
) {
extraParams.cron_org = installation.account.login;
}
const payload = {
...body,
...extraParams,
};
for await (const repo of generator) {
if (repo.archived === true || repo.disabled === true) {
continue;
}
promises.push(
this.scheduledToTask(
repo.full_name,
id,
payload,
SCHEDULER_REPOSITORY_EVENT_NAME
)
);
if (promises.length >= batchSize) {
await Promise.all(promises);
promises.splice(0, promises.length);
}
}
// Wait for the rest.
if (promises.length > 0) {
await Promise.all(promises);
promises.splice(0, promises.length);
}
}
}
}
/**
* Build an app-based authenticated Octokit instance.
*
* @param installationId {number|undefined} The installation id to
* authenticate as. Required if you are trying to take action
* on an installed repository.
* @param wrapConfig
*/
async getAuthenticatedOctokit(
installationId?: number,
wrapConfig?: WrapConfig
): Promise<Octokit> {
const cfg = await this.getProbotConfig(wrapConfig?.logging);
let opts = {
appId: cfg.appId,
privateKey: cfg.privateKey,
};
if (installationId) {
opts = {
...opts,
...{installationId},
};
}
if (wrapConfig?.logging) {
const LoggingOctokit = Octokit.plugin(LoggingOctokitPlugin)
.plugin(ConfigPlugin)
.defaults({authStrategy: createProbotAuth});
return new LoggingOctokit({auth: opts});
} else {
const DefaultOctokit = Octokit.plugin(ConfigPlugin).defaults({
authStrategy: createProbotAuth,
});
return new DefaultOctokit({auth: opts});
}
}
private async scheduledToTask(
repoFullName: string,
id: string,
body: object,
eventName: string
) {
// The payload from the scheduler is updated with additional information
// providing context about the organization/repo that the event is
// firing for.
const payload = {
...body,
...this.buildRepositoryDetails(repoFullName),
};
try {
await this.enqueueTask({
id,
name: eventName,
body: JSON.stringify(payload),
});
} catch (err) {
logger.error(err);
}
}
private parsePubSubPayload(req: express.Request) {
const body = this.parseRequestBody(req);
return {
...body,
...(body.repo ? this.buildRepositoryDetails(body.repo) : {}),
};
}
private parseRequestBody(req: express.Request): Scheduled {
let body = (
Buffer.isBuffer(req.body)
? JSON.parse(req.body.toString('utf8'))
: req.body
) as Scheduled;
// PubSub messages have their payload encoded in body.message.data
// as a base64 blob.
if (body.message && body.message.data) {
body = JSON.parse(Buffer.from(body.message.data, 'base64').toString());
}
return body;
}
private buildRepositoryDetails(repoFullName: string): {} {
const [orgName, repoName] = repoFullName.split('/');
return {
repository: {
name: repoName,
full_name: repoFullName,
owner: {
login: orgName,
name: orgName,
},
},
organization: {
login: orgName,
},
};
}
/**
* Return the URL to reach a specified Cloud Run instance.
* @param {string} projectId The project id running the Cloud Run instance
* @param {string} location The location of the Cloud Run instance
* @param {string} botName The name of the target bot
* @returns {string} The URL of the Cloud Run instance
*/
private async getCloudRunUrl(
projectId: string,
location: string,
botName: string
): Promise<string | null> {
// Cloud Run service names can only use dashes
const serviceName = botName.replace(/_/g, '-');
const auth = new GoogleAuth({
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const authClient = await auth.getClient();
const client = await run({
version: 'v1',
auth: authClient,
});
const name = `projects/${projectId}/locations/${location}/services/${serviceName}`;
const res = await client.projects.locations.services.get({
name,
});
if (res.data.status?.address?.url) {
return res.data.status.address.url;
}
return null;
}
private async getTaskTarget(
projectId: string,
location: string,
botName: string
): Promise<string> {
if (this.taskTargetEnvironment === 'functions') {
// https://us-central1-repo-automation-bots.cloudfunctions.net/merge_on_green
return `https://${location}-${projectId}.cloudfunctions.net/${botName}`;
} else if (this.taskTargetEnvironment === 'run') {
const url = await this.getCloudRunUrl(projectId, location, botName);
if (url) {
return url;
}
throw new Error(`Unable to find url for Cloud Run service: ${botName}`);
}
// Shouldn't get here
throw new Error(`Unknown task target: ${this.taskTargetEnvironment}`);
}
/**
* Schedule a event trigger as a Cloud Task.
* @param params {EnqueueTaskParams} Task parameters.
*/
async enqueueTask(params: EnqueueTaskParams) {
logger.info(
`scheduling cloud task targeting: ${this.taskTargetEnvironment}`
);
// Make a task here and return 200 as this is coming from GitHub
// queue name can contain only letters ([A-Za-z]), numbers ([0-9]), or hyphens (-):
const queueName = this.functionName.replace(/_/g, '-');
const queuePath = this.cloudTasksClient.queuePath(
this.projectId,
this.location,
queueName
);
const url = await this.getTaskTarget(
this.projectId,
this.location,
this.functionName
);
logger.info(`scheduling task in queue ${queueName}`);
if (params.body) {
// Payload conists of either the original params.body or, if Cloud
// Storage has been configured, a tmp file in a bucket:
const payload = await this.maybeWriteBodyToTmp(params.body);
const signature = (await this.probot?.webhooks.sign(payload)) || '';
await this.cloudTasksClient.createTask({
parent: queuePath,
task: {
httpRequest: {
httpMethod: 'POST',
headers: {
'X-GitHub-Event': params.name || '',
'X-GitHub-Delivery': params.id || '',
'X-Hub-Signature': signature,
'Content-Type': 'application/json',
},
url,
body: Buffer.from(payload),
},
},
});
} else {
const signature = (await this.probot?.webhooks.sign('')) || '';
await this.cloudTasksClient.createTask({
parent: queuePath,
task: {
httpRequest: {
httpMethod: 'POST',
headers: {
'X-GitHub-Event': params.name || '',
'X-GitHub-Delivery': params.id || '',
'X-Hub-Signature': signature,
'Content-Type': 'application/json',
},
url,
},
},
});
}
}
/*
* Setting the process.env.WEBHOOK_TMP environment variable indicates
* that the webhook payload should be written to a tmp file in Cloud
* Storage. This allows us to circumvent the 100kb limit on Cloud Tasks.
*
* @param body
*/
private async maybeWriteBodyToTmp(body: string): Promise<string> {
if (this.payloadBucket) {
const tmp = `${Date.now()}-${v4()}.txt`;
const bucket = this.storage.bucket(this.payloadBucket);
const writeable = bucket.file(tmp).createWriteStream({
validation: !RUNNING_IN_TEST,
});
logger.info(`uploading payload to ${tmp}`);
intoStream(body).pipe(writeable);
await new Promise((resolve, reject) => {
writeable.on('error', reject);
writeable.on('finish', resolve);
});
return JSON.stringify({
tmpUrl: tmp,
});
} else {
return body;
}
}
/*
* If body has the key tmpUrl, download the original body from a temporary
* folder in Cloud Storage.
*
* @param body
*/
private async maybeDownloadOriginalBody(payload: {
[key: string]: string;
}): Promise<object | null> {
if (payload.tmpUrl) {
if (!this.payloadBucket) {
throw Error('no tmp directory configured');
}
const bucket = this.storage.bucket(this.payloadBucket);
const file = bucket.file(payload.tmpUrl);
const readable = file.createReadStream({
validation: !RUNNING_IN_TEST,
});
try {
const content = await getStream(readable);
logger.info(`downloaded payload from ${payload.tmpUrl}`);
return JSON.parse(content);
} catch (e) {
if (e.code === 404) {
logger.info(`payload not found ${payload.tmpUrl}`);
return null;
}
logger.error(`failed to download from ${payload.tmpUrl}`, e);
throw e;
}
} else {
return payload;
}
}
} | the_stack |
import { Injectable, BadRequestException, NotAcceptableException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CommandBus } from '@nestjs/cqrs';
import { Repository, FindConditions, UpdateResult, getManager, FindManyOptions, Not, In, DeepPartial } from 'typeorm';
import {
RolesEnum,
ITenant,
IRole,
IRolePermission,
IImportRecord,
IRolePermissionMigrateInput,
IPagination,
PermissionsEnum
} from '@gauzy/contracts';
import { isNotEmpty } from '@gauzy/common';
import { pluck } from 'underscore';
import { TenantAwareCrudService } from './../core/crud';
import { RequestContext } from './../core/context';
import { ImportRecordUpdateOrCreateCommand } from './../export-import/import-record';
import { RolePermission } from './role-permission.entity';
import { Role } from '../role/role.entity';
import { RoleService } from './../role/role.service';
import { DEFAULT_ROLE_PERMISSIONS } from './default-role-permissions';
@Injectable()
export class RolePermissionService extends TenantAwareCrudService<RolePermission> {
constructor(
@InjectRepository(RolePermission)
private readonly rolePermissionRepository: Repository<RolePermission>,
private readonly roleService: RoleService,
private readonly _commandBus: CommandBus
) {
super(rolePermissionRepository);
}
/**
* GET all roler-permissions using API filter
*
* @param filter
* @returns
*/
public async findAllRolePermissions(
filter?: FindManyOptions<RolePermission>,
): Promise<IPagination<RolePermission>> {
const tenantId = RequestContext.currentTenantId();
const roleId = RequestContext.currentRoleId();
/**
* Find current user role
*/
const { role } = await this.repository.findOne({
where: { roleId },
relations: ['role']
});
/**
* Only SUPER_ADMIN/ADMIN can have `PermissionsEnum.CHANGE_ROLES_PERMISSIONS` permission
* SUPER_ADMIN can retrieve all role-permissions for assign TENANT.
* ADMIN can retrieve role-permissions for lower roles (DATA_ENTRY, EMPLOYEE, CANDIDATE, MANAGER, VIEWER) & themself (ADMIN)
*/
if (RequestContext.hasPermission(PermissionsEnum.CHANGE_ROLES_PERMISSIONS)) {
/**
* If, SUPER_ADMIN users try to retrieve all role-permissions allow them.
*/
if (role.name === RolesEnum.SUPER_ADMIN) {
return await this.findAll(filter);
}
/**
* Retrieve all role-permissions except "SUPER_ADMIN" role
*/
const roles = (await this.roleService.findAll({
select: ['id'],
where: {
name: Not(RolesEnum.SUPER_ADMIN),
tenantId
}
})).items;
if (!filter.where) {
/**
* GET all role-permissions for (DATA_ENTRY, EMPLOYEE, CANDIDATE, MANAGER, VIEWER) roles themself (ADMIN), if specific role filter not used in API.
*
*/
filter['where'] = {
roleId: In(pluck(roles, 'id')),
tenantId
}
} else if(filter.where && filter.where['roleId']) {
/**
* If, ADMIN try to retrieve "SUPER_ADMIN" role-permissions via API filter, not allow them.
* Retrieve current user role (ADMIN) all role-permissons.
*/
if (!pluck(roles, 'id').includes(filter.where['roleId'])) {
filter['where'] = {
roleId,
tenantId
}
}
}
return await this.findAll(filter);
}
/**
* If (DATA_ENTRY, EMPLOYEE, CANDIDATE, MANAGER, VIEWER) roles users try to retrieve role-permissions.
* Allow only to retrieve current users role-permissions.
*/
filter['where'] = {
roleId,
tenantId
}
return await this.findAll(filter);
}
/**
* Create permissions for lower roles users
*
* @param partialEntity
* @returns
*/
public async createPermission(
partialEntity: DeepPartial<IRolePermission>
): Promise<IRolePermission> {
try {
const currentTenantId = RequestContext.currentTenantId();
const currentRoleId = RequestContext.currentRoleId();
/**
* Find current user role
*/
const { role } = await this.repository.findOne({
where: {
roleId: currentRoleId,
tenantId: currentTenantId
},
relations: ['role']
});
let { roleId } = partialEntity;
if (partialEntity['role'] instanceof Role) {
roleId = partialEntity['role']['id'];
}
/**
* User try to create permission for below role
*/
const wantToCreatePermissionForRole = await this.roleService.findOneByIdString(roleId);
/**
* If current user has SUPER_ADMIN
*/
if (role.name === RolesEnum.SUPER_ADMIN) {
/**
* Reject request, if SUPER ADMIN try to create permissions for SUPER ADMIN role.
*/
if (wantToCreatePermissionForRole.name === RolesEnum.SUPER_ADMIN) {
throw new NotAcceptableException(
'You can not change/add your permissions for SUPER_ADMIN'
);
}
return await this.create(partialEntity);
} else if (role.name === RolesEnum.ADMIN) {
/**
* Reject request, if ADMIN try to create permissions for SUPER ADMIN role.
*/
if (wantToCreatePermissionForRole.name === RolesEnum.SUPER_ADMIN) {
throw new NotAcceptableException(
'You can not change your role to SUPER_ADMIN, please ask your SUPER_ADMIN to give you more permissions'
);
}
/**
* Reject request, if ADMIN try to create permissions for ADMIN role.
*/
if (wantToCreatePermissionForRole.name === RolesEnum.ADMIN) {
throw new NotAcceptableException(
'You can not change/add your permissions to ADMIN, please ask your SUPER_ADMIN to give you more permissions'
);
}
return await this.create(partialEntity);
}
} catch (error) {
throw new BadRequestException(error.message);
}
}
public async updatePermission(
id: string | number | FindConditions<IRolePermission>,
partialEntity: DeepPartial<IRolePermission>
): Promise<UpdateResult | IRolePermission> {
try {
const currentTenantId = RequestContext.currentTenantId();
const currentRoleId = RequestContext.currentRoleId();
const { role } = await this.repository.findOne({
where: {
roleId: currentRoleId,
tenantId: currentTenantId
},
relations: ['role']
});
let { roleId } = partialEntity;
if (partialEntity['role'] instanceof Role) {
roleId = partialEntity['role']['id'];
}
/**
* User try to update permission for below role
*/
const wantToUpdatePermissionForRole = await this.roleService.findOneByIdString(roleId);
if (role.name === RolesEnum.SUPER_ADMIN) {
/**
* Reject request, if SUPER ADMIN try to update permissions for SUPER ADMIN role.
*/
if (wantToUpdatePermissionForRole.name === RolesEnum.SUPER_ADMIN) {
throw new NotAcceptableException(
'You can not change/add your permissions for SUPER_ADMIN'
);
}
return await this.update(id, partialEntity);
} else if (role.name === RolesEnum.ADMIN) {
/**
* Reject request, if ADMIN try to update permissions for SUPER ADMIN role.
*/
if (wantToUpdatePermissionForRole.name === RolesEnum.SUPER_ADMIN) {
throw new NotAcceptableException(
'You can not change your role to SUPER_ADMIN, please ask your SUPER_ADMIN to give you more permissions'
);
}
/**
* Reject request, if ADMIN try to create permissions for ADMIN role.
*/
if (wantToUpdatePermissionForRole.name === RolesEnum.ADMIN) {
throw new NotAcceptableException(
'You can not change/add your permissions to ADMIN, please ask your SUPER_ADMIN to give you more permissions'
);
}
return await this.update(id, partialEntity);
}
} catch (err /*: WriteError*/) {
throw new BadRequestException(err.message);
}
}
/**
* DELETE role permissions
*
* @param id
* @returns
*/
public async deletePermission(id: string) {
try {
const currentTenantId = RequestContext.currentTenantId();
const currentRoleId = RequestContext.currentRoleId();
const { role } = await this.repository.findOne({
where: {
roleId: currentRoleId,
tenantId: currentTenantId
},
relations: ['role']
});
/**
* User try to delete permission for below role
*/
const { role: wantToDeletePermissionForRole } = await this.repository.findOne({
where: { id },
relations: ['role']
});
if (role.name === RolesEnum.SUPER_ADMIN) {
/**
* Reject request, if SUPER ADMIN try to delete permissions for SUPER ADMIN role.
*/
if (wantToDeletePermissionForRole.name === RolesEnum.SUPER_ADMIN) {
throw new NotAcceptableException(
'You can not delete your permissions to SUPER_ADMIN'
);
}
return await this.delete(id);
} else if (role.name === RolesEnum.ADMIN) {
/**
* Reject request, if ADMIN try to update permissions for SUPER ADMIN role.
*/
if (wantToDeletePermissionForRole.name === RolesEnum.SUPER_ADMIN) {
throw new NotAcceptableException(
'You can not delete SUPER_ADMINpermisson, please ask your SUPER_ADMIN to give you more permissions'
);
}
/**
* Reject request, if ADMIN try to create permissions for ADMIN role.
*/
if (wantToDeletePermissionForRole.name === RolesEnum.ADMIN) {
throw new NotAcceptableException(
'You can not delete your permissions to ADMIN, please ask your SUPER_ADMIN to give you more permissions'
);
}
return await this.delete(id);
}
} catch (error /*: WriteError*/) {
throw new BadRequestException(error);
}
}
public async updateRoles(tenant: ITenant, role: Role) {
const { defaultEnabledPermissions } = DEFAULT_ROLE_PERMISSIONS.find(
(defaultRole) => role.name === defaultRole.role
);
for await (const permission of defaultEnabledPermissions) {
const rolePermission = new RolePermission();
rolePermission.roleId = role.id;
rolePermission.permission = permission;
rolePermission.enabled = true;
rolePermission.tenant = tenant;
await this.create(rolePermission);
}
}
public async updateRolesAndPermissions(
tenants: ITenant[],
roles: IRole[]
): Promise<IRolePermission[]> {
if (!tenants.length) {
return;
}
const rolesPermissions: IRolePermission[] = [];
for await (const tenant of tenants) {
for await (const role of roles) {
const defaultPermissions = DEFAULT_ROLE_PERMISSIONS.find(
(defaultRole) => role.name === defaultRole.role
);
if (defaultPermissions && isNotEmpty(defaultPermissions['defaultEnabledPermissions'])) {
const { defaultEnabledPermissions } = defaultPermissions;
for await (const permission of defaultEnabledPermissions) {
const rolePermission = new RolePermission();
rolePermission.roleId = role.id;
rolePermission.permission = permission;
rolePermission.enabled = true;
rolePermission.tenant = tenant;
rolesPermissions.push(rolePermission);
}
}
}
}
await this.rolePermissionRepository.save(rolesPermissions);
return rolesPermissions;
}
public async migratePermissions(): Promise<IRolePermissionMigrateInput[]> {
const permissions: IRolePermission[] = await this.rolePermissionRepository.find({
where: {
tenantId: RequestContext.currentTenantId()
},
relations: ['role']
})
const payload: IRolePermissionMigrateInput[] = [];
for await (const item of permissions) {
const { id: sourceId, permission, role: { name } } = item;
payload.push({
permission,
isImporting: true,
sourceId,
role: name
})
}
return payload;
}
public async migrateImportRecord(
permissions: IRolePermissionMigrateInput[]
) {
let records: IImportRecord[] = [];
const roles: IRole[] = await getManager().getRepository(Role).find({
tenantId: RequestContext.currentTenantId(),
});
for await (const item of permissions) {
const { isImporting, sourceId } = item;
if (isImporting && sourceId) {
const { permission, role: name } = item;
const role = roles.find((role: IRole) => role.name === name);
const destinantion = await this.rolePermissionRepository.findOne({
tenantId: RequestContext.currentTenantId(),
permission,
role
});
if (destinantion) {
records.push(
await this._commandBus.execute(
new ImportRecordUpdateOrCreateCommand({
entityType: getManager().getRepository(RolePermission).metadata.tableName,
sourceId,
destinationId: destinantion.id,
tenantId: RequestContext.currentTenantId()
})
)
);
}
}
}
return records;
}
} | the_stack |
import type { RegExpContext, RegExpContextForSource } from "../utils"
import {
getFlagsRange,
compositingVisitors,
createRule,
defineRegexpVisitor,
getFlagsLocation,
} from "../utils"
import type {
CallExpression,
Expression,
NewExpression,
Node,
RegExpLiteral,
Statement,
} from "estree"
import type { KnownMethodCall } from "../utils/ast-utils"
import {
isKnownMethodCall,
extractExpressionReferences,
} from "../utils/ast-utils"
import { createTypeTracker } from "../utils/type-tracker"
import type { RuleListener } from "../types"
import type { Rule } from "eslint"
import { isCaseVariant } from "../utils/regexp-ast/case-variation"
type CodePathStack = {
codePathId: string
upper: CodePathStack | null
loopStack: Statement[]
}
type RegExpExpression = RegExpLiteral | NewExpression | CallExpression
/**
* A key that identifies the code path and loop.
* If there is a difference in this key between the definition location and the usage location,
* it may have been used multiple times.
*/
type CodePathId = {
codePathId: string
loopNode: Statement | undefined
}
type RegExpMethodKind =
| "search"
| "split"
| "exec"
| "test"
| "match"
| "matchAll"
| "replace"
| "replaceAll"
class RegExpReference {
public readonly regExpContext: RegExpContext
public get defineNode(): RegExpExpression {
return this.regExpContext.regexpNode
}
public defineId?: CodePathId
public readonly readNodes = new Map<
Expression,
{
marked?: boolean
usedInExec?: { id: CodePathId }
usedInTest?: { id: CodePathId }
}
>()
private readonly state: {
track: boolean
usedNodes: Map<RegExpMethodKind, Expression[]>
hasUnusedExpression?: boolean
} = {
usedNodes: new Map(),
track: true,
}
public constructor(regExpContext: RegExpContext) {
this.regExpContext = regExpContext
}
public addReadNode(node: Expression) {
this.readNodes.set(node, {})
}
public setDefineId(codePathId: string, loopNode: Statement | undefined) {
this.defineId = { codePathId, loopNode }
}
public markAsUsedInSearch(node: Expression) {
const exprState = this.readNodes.get(node)
if (exprState) {
exprState.marked = true
}
this.addUsedNode("search", node)
}
public markAsUsedInSplit(node: Expression) {
const exprState = this.readNodes.get(node)
if (exprState) {
exprState.marked = true
}
this.addUsedNode("split", node)
}
public markAsUsedInExec(
node: Expression,
codePathId: string,
loopNode: Statement | undefined,
) {
const exprState = this.readNodes.get(node)
if (exprState) {
exprState.marked = true
exprState.usedInExec = { id: { codePathId, loopNode } }
}
this.addUsedNode("exec", node)
}
public markAsUsedInTest(
node: Expression,
codePathId: string,
loopNode: Statement | undefined,
) {
const exprState = this.readNodes.get(node)
if (exprState) {
exprState.marked = true
exprState.usedInTest = { id: { codePathId, loopNode } }
}
this.addUsedNode("test", node)
}
public isUsed(kinds: RegExpMethodKind[]) {
for (const kind of kinds) {
if (this.state.usedNodes.has(kind)) {
return true
}
}
return false
}
public isCannotTrack() {
return !this.state.track
}
public markAsUsed(
kind: "match" | "matchAll" | "replace" | "replaceAll",
exprNode: Expression,
) {
this.addUsedNode(kind, exprNode)
}
public markAsCannotTrack() {
this.state.track = false
}
public getUsedNodes() {
return this.state.usedNodes
}
private addUsedNode(kind: RegExpMethodKind, exprNode: Expression) {
const list = this.state.usedNodes.get(kind)
if (list) {
list.push(exprNode)
} else {
this.state.usedNodes.set(kind, [exprNode])
}
}
}
/**
* Returns a fixer that removes the given flag.
*/
function fixRemoveFlag(
{ flagsString, fixReplaceFlags }: RegExpContext,
flag: "i" | "m" | "s" | "g" | "y",
) {
if (flagsString) {
return fixReplaceFlags(flagsString.replace(flag, ""))
}
return null
}
/**
* Create visitor for verify unnecessary i flag
*/
function createUselessIgnoreCaseFlagVisitor(context: Rule.RuleContext) {
return defineRegexpVisitor(context, {
createVisitor(regExpContext: RegExpContext) {
const { flags, regexpNode, ownsFlags, getFlagLocation } =
regExpContext
if (!flags.ignoreCase || !ownsFlags) {
return {}
}
return {
onPatternLeave(pattern) {
if (!isCaseVariant(pattern, flags, false)) {
context.report({
node: regexpNode,
loc: getFlagLocation("i"),
messageId: "uselessIgnoreCaseFlag",
fix: fixRemoveFlag(regExpContext, "i"),
})
}
},
}
},
})
}
/**
* Create visitor for verify unnecessary m flag
*/
function createUselessMultilineFlagVisitor(context: Rule.RuleContext) {
return defineRegexpVisitor(context, {
createVisitor(regExpContext: RegExpContext) {
const { flags, regexpNode, ownsFlags, getFlagLocation } =
regExpContext
if (!flags.multiline || !ownsFlags) {
return {}
}
let unnecessary = true
return {
onAssertionEnter(node) {
if (node.kind === "start" || node.kind === "end") {
unnecessary = false
}
},
onPatternLeave() {
if (unnecessary) {
context.report({
node: regexpNode,
loc: getFlagLocation("m"),
messageId: "uselessMultilineFlag",
fix: fixRemoveFlag(regExpContext, "m"),
})
}
},
}
},
})
}
/**
* Create visitor for verify unnecessary s flag
*/
function createUselessDotAllFlagVisitor(context: Rule.RuleContext) {
return defineRegexpVisitor(context, {
createVisitor(regExpContext: RegExpContext) {
const { flags, regexpNode, ownsFlags, getFlagLocation } =
regExpContext
if (!flags.dotAll || !ownsFlags) {
return {}
}
let unnecessary = true
return {
onCharacterSetEnter(node) {
if (node.kind === "any") {
unnecessary = false
}
},
onPatternLeave() {
if (unnecessary) {
context.report({
node: regexpNode,
loc: getFlagLocation("s"),
messageId: "uselessDotAllFlag",
fix: fixRemoveFlag(regExpContext, "s"),
})
}
},
}
},
})
}
/**
* Create visitor for verify unnecessary g flag
*/
function createUselessGlobalFlagVisitor(
context: Rule.RuleContext,
strictTypes: boolean,
) {
const enum ReportKind {
// It is used only in "split".
usedOnlyInSplit,
// It is used only in "search".
usedOnlyInSearch,
// It is used only once in "exec".
usedOnlyOnceInExec,
// It is used only once in "test".
usedOnlyOnceInTest,
// The global flag is given, but it is not used.
unused,
}
type ReportData = { kind: ReportKind; fixable?: boolean }
/**
* Report for useless global flag
*/
function reportUselessGlobalFlag(
regExpReference: RegExpReference,
data: ReportData,
) {
const { getFlagLocation } = regExpReference.regExpContext
const node = regExpReference.defineNode
context.report({
node,
loc: getFlagLocation("g"),
messageId:
data.kind === ReportKind.usedOnlyInSplit
? "uselessGlobalFlagForSplit"
: data.kind === ReportKind.usedOnlyInSearch
? "uselessGlobalFlagForSearch"
: data.kind === ReportKind.usedOnlyOnceInTest
? "uselessGlobalFlagForTest"
: data.kind === ReportKind.usedOnlyOnceInExec
? "uselessGlobalFlagForExec"
: "uselessGlobalFlag",
fix: data.fixable
? fixRemoveFlag(regExpReference.regExpContext, "g")
: null,
})
}
/**
* Checks if it needs to be reported and returns the report data if it needs to be reported.
*/
function getReportData(
regExpReference: RegExpReference,
): null | ReportData {
let countOfUsedInExecOrTest = 0
for (const readData of regExpReference.readNodes.values()) {
if (!readData.marked) {
// There is expression node whose usage is unknown.
return null
}
const usedInExecOrTest = readData.usedInExec || readData.usedInTest
if (usedInExecOrTest) {
if (!regExpReference.defineId) {
// The definition scope is unknown. Probably broken.
return null
}
if (
regExpReference.defineId.codePathId ===
usedInExecOrTest.id.codePathId &&
regExpReference.defineId.loopNode ===
usedInExecOrTest.id.loopNode
) {
countOfUsedInExecOrTest++
if (countOfUsedInExecOrTest > 1) {
// Multiple `exec` or `test` have been used.
return null
}
continue
} else {
// Used `exec` or` test` in different scopes. It may be called multiple times.
return null
}
}
}
// Need to report
return buildReportData(regExpReference)
}
/**
* Build the report data.
*/
function buildReportData(regExpReference: RegExpReference) {
const usedNodes = regExpReference.getUsedNodes()
if (usedNodes.size === 1) {
const [[method, nodes]] = usedNodes
// Make it fixable only if the regex is used directly.
const fixable =
nodes.length === 1 && nodes.includes(regExpReference.defineNode)
if (method === "split") {
return {
kind: ReportKind.usedOnlyInSplit,
fixable,
}
}
if (method === "search") {
return { kind: ReportKind.usedOnlyInSearch, fixable }
}
if (method === "exec" && nodes.length === 1)
return { kind: ReportKind.usedOnlyOnceInExec, fixable }
if (method === "test" && nodes.length === 1)
return { kind: ReportKind.usedOnlyOnceInTest, fixable }
}
return { kind: ReportKind.unused }
}
return createRegExpReferenceExtractVisitor(context, {
flag: "global",
exit(regExpReferenceList) {
for (const regExpReference of regExpReferenceList) {
const report = getReportData(regExpReference)
if (report != null) {
reportUselessGlobalFlag(regExpReference, report)
}
}
},
isUsedShortCircuit(regExpReference) {
return regExpReference.isUsed([
"match",
"matchAll",
"replace",
"replaceAll",
])
},
strictTypes,
})
}
/**
* Create visitor for verify unnecessary y flag
*/
function createUselessStickyFlagVisitor(
context: Rule.RuleContext,
strictTypes: boolean,
) {
type ReportData = { fixable?: boolean }
/**
* Report for useless sticky flag
*/
function reportUselessStickyFlag(
regExpReference: RegExpReference,
data: ReportData,
) {
const { getFlagLocation } = regExpReference.regExpContext
const node = regExpReference.defineNode
context.report({
node,
loc: getFlagLocation("y"),
messageId: "uselessStickyFlag",
fix: data.fixable
? fixRemoveFlag(regExpReference.regExpContext, "y")
: null,
})
}
/**
* Checks if it needs to be reported and returns the report data if it needs to be reported.
*/
function getReportData(
regExpReference: RegExpReference,
): null | ReportData {
for (const readData of regExpReference.readNodes.values()) {
if (!readData.marked) {
// There is expression node whose usage is unknown.
return null
}
} // Need to report
return buildReportData(regExpReference)
}
/**
* Build the report data.
*/
function buildReportData(regExpReference: RegExpReference) {
const usedNodes = regExpReference.getUsedNodes()
if (usedNodes.size === 1) {
const [[method, nodes]] = usedNodes
// Make it fixable only if the regex is used directly.
const fixable =
nodes.length === 1 && nodes.includes(regExpReference.defineNode)
if (method === "split") {
return {
fixable,
}
}
}
return {}
}
return createRegExpReferenceExtractVisitor(context, {
flag: "sticky",
exit(regExpReferenceList) {
for (const regExpReference of regExpReferenceList) {
const report = getReportData(regExpReference)
if (report != null) {
reportUselessStickyFlag(regExpReference, report)
}
}
},
isUsedShortCircuit(regExpReference) {
return regExpReference.isUsed([
"search",
"exec",
"test",
"match",
"matchAll",
"replace",
"replaceAll",
])
},
strictTypes,
})
}
/**
* Create a visitor that extracts RegExpReference.
*/
function createRegExpReferenceExtractVisitor(
context: Rule.RuleContext,
{
flag,
exit,
isUsedShortCircuit,
strictTypes,
}: {
flag: "global" | "sticky"
exit: (list: RegExpReference[]) => void
isUsedShortCircuit: (regExpReference: RegExpReference) => boolean
strictTypes: boolean
},
) {
const typeTracer = createTypeTracker(context)
let stack: CodePathStack | null = null
const regExpReferenceMap = new Map<Node, RegExpReference>()
const regExpReferenceList: RegExpReference[] = []
/** Verify for String.prototype.search() or String.prototype.split() */
function verifyForSearchOrSplit(
node: KnownMethodCall,
kind: "search" | "split",
) {
const regExpReference = regExpReferenceMap.get(node.arguments[0])
if (regExpReference == null || isUsedShortCircuit(regExpReference)) {
return
}
if (
strictTypes
? !typeTracer.isString(node.callee.object)
: !typeTracer.maybeString(node.callee.object)
) {
regExpReference.markAsCannotTrack()
return
}
if (kind === "search") {
// String.prototype.search()
regExpReference.markAsUsedInSearch(node.arguments[0])
} else {
// String.prototype.split()
regExpReference.markAsUsedInSplit(node.arguments[0])
}
}
/** Verify for RegExp.prototype.exec() or RegExp.prototype.test() */
function verifyForExecOrTest(node: KnownMethodCall, kind: "exec" | "test") {
const regExpReference = regExpReferenceMap.get(node.callee.object)
if (regExpReference == null || isUsedShortCircuit(regExpReference)) {
return
}
if (kind === "exec") {
// RegExp.prototype.exec()
regExpReference.markAsUsedInExec(
node.callee.object,
stack!.codePathId,
stack!.loopStack[0],
)
} else {
// RegExp.prototype.test()
regExpReference.markAsUsedInTest(
node.callee.object,
stack!.codePathId,
stack!.loopStack[0],
)
}
}
return compositingVisitors(
defineRegexpVisitor(context, {
createVisitor(regExpContext: RegExpContext) {
const { flags, regexpNode } = regExpContext
if (flags[flag]) {
const regExpReference = new RegExpReference(regExpContext)
regExpReferenceList.push(regExpReference)
regExpReferenceMap.set(regexpNode, regExpReference)
for (const ref of extractExpressionReferences(
regexpNode,
context,
)) {
if (ref.type === "argument" || ref.type === "member") {
regExpReferenceMap.set(ref.node, regExpReference)
regExpReference.addReadNode(ref.node)
} else {
regExpReference.markAsCannotTrack()
}
}
}
return {} // not visit RegExpNodes
},
}),
{
"Program:exit"() {
exit(
regExpReferenceList.filter((regExpReference) => {
if (!regExpReference.readNodes.size) {
// Unused variable
return false
}
if (regExpReference.isCannotTrack()) {
// There is expression node whose usage is unknown.
return false
}
if (isUsedShortCircuit(regExpReference)) {
// The flag was used.
return false
}
return true
}),
)
},
onCodePathStart(codePath) {
stack = {
codePathId: codePath.id,
upper: stack,
loopStack: [],
}
},
onCodePathEnd() {
stack = stack?.upper ?? null
},
// Stacks the scope of the loop statement. e.g. `for ( target )`
["WhileStatement, DoWhileStatement, ForStatement, ForInStatement, ForOfStatement, " +
// Stacks the scope of statement inside the loop statement. e.g. `for (;;) { target }`
":matches(WhileStatement, DoWhileStatement, ForStatement, ForInStatement, ForOfStatement) > :statement"](
node: Statement,
) {
stack?.loopStack.unshift(node)
},
["WhileStatement, DoWhileStatement, ForStatement, ForInStatement, ForOfStatement, " +
":matches(WhileStatement, DoWhileStatement, ForStatement, ForInStatement, ForOfStatement) > :statement" +
":exit"]() {
stack?.loopStack.shift()
},
"Literal, NewExpression, CallExpression:exit"(node: Node) {
if (!stack) {
return
}
const regExpReference = regExpReferenceMap.get(node)
if (!regExpReference || regExpReference.defineNode !== node) {
return
}
regExpReference.setDefineId(
stack.codePathId,
stack.loopStack[0],
)
},
"CallExpression:exit"(node: CallExpression) {
if (!stack) {
return
}
if (
!isKnownMethodCall(node, {
// marked as unused
search: 1,
split: 1,
// If called only once, it will be marked as unused.
test: 1,
exec: 1,
// marked as used
match: 1,
matchAll: 1,
replace: 2,
replaceAll: 2,
})
) {
return
}
if (
node.callee.property.name === "search" ||
node.callee.property.name === "split"
) {
verifyForSearchOrSplit(node, node.callee.property.name)
} else if (
node.callee.property.name === "test" ||
node.callee.property.name === "exec"
) {
verifyForExecOrTest(node, node.callee.property.name)
} else if (
node.callee.property.name === "match" ||
node.callee.property.name === "matchAll" ||
node.callee.property.name === "replace" ||
node.callee.property.name === "replaceAll"
) {
const regExpReference = regExpReferenceMap.get(
node.arguments[0],
)
regExpReference?.markAsUsed(
node.callee.property.name,
node.arguments[0],
)
}
},
},
)
}
/**
* Create visitor for verify unnecessary flags of owned RegExp literals
*/
function createOwnedRegExpFlagsVisitor(context: Rule.RuleContext) {
const sourceCode = context.getSourceCode()
/** Remove the flags of the given literal */
function removeFlags(node: RegExpLiteral): void {
// The u flag is relevant for parsing the literal, so
// we can't just remove it and potentially create
// invalid source code.
const newFlags = node.regex.flags.replace(/[^u]+/gu, "")
if (newFlags === node.regex.flags) {
return
}
context.report({
node,
loc: getFlagsLocation(sourceCode, node, node),
messageId: "uselessFlagsOwned",
fix(fixer) {
const range = getFlagsRange(node)
return fixer.replaceTextRange(range, newFlags)
},
})
}
return defineRegexpVisitor(context, {
createSourceVisitor(regExpContext: RegExpContextForSource) {
const { patternSource, regexpNode } = regExpContext
if (patternSource.isStringValue()) {
// all regexp literals are used via `.source`
patternSource.getOwnedRegExpLiterals().forEach(removeFlags)
} else {
// The source is copied from some other regex
if (regexpNode.arguments.length >= 2) {
// and the flags are given using the second parameter
const ownedNode = patternSource.regexpValue?.ownedNode
if (ownedNode) {
removeFlags(ownedNode)
}
}
}
return {}
},
})
}
/**
* Parse option
*/
function parseOption(
userOption:
| {
ignore?: ("i" | "m" | "s" | "g" | "y")[]
strictTypes?: boolean
}
| undefined,
) {
const ignore = new Set<"i" | "m" | "s" | "g" | "y">()
let strictTypes = true
if (userOption) {
for (const i of userOption.ignore ?? []) {
ignore.add(i)
}
if (userOption.strictTypes != null) {
strictTypes = userOption.strictTypes
}
}
return {
ignore,
strictTypes,
}
}
export default createRule("no-useless-flag", {
meta: {
docs: {
description: "disallow unnecessary regex flags",
category: "Best Practices",
recommended: true,
default: "warn",
},
fixable: "code",
schema: [
{
type: "object",
properties: {
ignore: {
type: "array",
items: {
enum: ["i", "m", "s", "g", "y"],
},
uniqueItems: true,
},
strictTypes: { type: "boolean" },
},
additionalProperties: false,
},
],
messages: {
uselessIgnoreCaseFlag:
"The 'i' flag is unnecessary because the pattern only contains case-invariant characters.",
uselessMultilineFlag:
"The 'm' flag is unnecessary because the pattern does not contain start (^) or end ($) assertions.",
uselessDotAllFlag:
"The 's' flag is unnecessary because the pattern does not contain dots (.).",
uselessGlobalFlag:
"The 'g' flag is unnecessary because the regex does not use global search.",
uselessGlobalFlagForTest:
"The 'g' flag is unnecessary because the regex is used only once in 'RegExp.prototype.test'.",
uselessGlobalFlagForExec:
"The 'g' flag is unnecessary because the regex is used only once in 'RegExp.prototype.exec'.",
uselessGlobalFlagForSplit:
"The 'g' flag is unnecessary because 'String.prototype.split' ignores the 'g' flag.",
uselessGlobalFlagForSearch:
"The 'g' flag is unnecessary because 'String.prototype.search' ignores the 'g' flag.",
uselessStickyFlag:
"The 'y' flag is unnecessary because 'String.prototype.split' ignores the 'y' flag.",
uselessFlagsOwned:
"The flags of this RegExp literal are useless because only the source of the regex is used.",
},
type: "suggestion", // "problem",
},
create(context) {
const { ignore, strictTypes } = parseOption(context.options[0])
let visitor: RuleListener = {}
if (!ignore.has("i")) {
visitor = compositingVisitors(
visitor,
createUselessIgnoreCaseFlagVisitor(context),
)
}
if (!ignore.has("m")) {
visitor = compositingVisitors(
visitor,
createUselessMultilineFlagVisitor(context),
)
}
if (!ignore.has("s")) {
visitor = compositingVisitors(
visitor,
createUselessDotAllFlagVisitor(context),
)
}
if (!ignore.has("g")) {
visitor = compositingVisitors(
visitor,
createUselessGlobalFlagVisitor(context, strictTypes),
)
}
if (!ignore.has("y")) {
visitor = compositingVisitors(
visitor,
createUselessStickyFlagVisitor(context, strictTypes),
)
}
visitor = compositingVisitors(
visitor,
createOwnedRegExpFlagsVisitor(context),
)
return visitor
},
}) | the_stack |
/// <reference types="activex-interop" />
declare namespace ADODB {
const enum ADCPROP_ASYNCTHREADPRIORITY_ENUM {
adPriorityAboveNormal = 4,
adPriorityBelowNormal = 2,
adPriorityHighest = 5,
adPriorityLowest = 1,
adPriorityNormal = 3,
}
const enum ADCPROP_AUTORECALC_ENUM {
adRecalcAlways = 1,
adRecalcUpFront = 0,
}
const enum ADCPROP_UPDATECRITERIA_ENUM {
adCriteriaAllCols = 1,
adCriteriaKey = 0,
adCriteriaTimeStamp = 3,
adCriteriaUpdCols = 2,
}
const enum ADCPROP_UPDATERESYNC_ENUM {
adResyncAll = 15,
adResyncAutoIncrement = 1,
adResyncConflicts = 2,
adResyncInserts = 8,
adResyncNone = 0,
adResyncUpdates = 4,
}
const enum AffectEnum {
adAffectAll = 3,
adAffectAllChapters = 4,
adAffectCurrent = 1,
adAffectGroup = 2,
}
const enum BookmarkEnum {
adBookmarkCurrent = 0,
adBookmarkFirst = 1,
adBookmarkLast = 2,
}
const enum CommandTypeEnum {
adCmdFile = 256,
adCmdStoredProc = 4,
adCmdTable = 2,
adCmdTableDirect = 512,
adCmdText = 1,
adCmdUnknown = 8,
adCmdUnspecified = -1,
}
const enum CompareEnum {
adCompareEqual = 1,
adCompareGreaterThan = 2,
adCompareLessThan = 0,
adCompareNotComparable = 4,
adCompareNotEqual = 3,
}
const enum ConnectModeEnum {
adModeRead = 1,
adModeReadWrite = 3,
adModeRecursive = 4194304,
adModeShareDenyNone = 16,
adModeShareDenyRead = 4,
adModeShareDenyWrite = 8,
adModeShareExclusive = 12,
adModeUnknown = 0,
adModeWrite = 2,
}
const enum ConnectOptionEnum {
adAsyncConnect = 16,
adConnectUnspecified = -1,
}
const enum ConnectPromptEnum {
adPromptAlways = 1,
adPromptComplete = 2,
adPromptCompleteRequired = 3,
adPromptNever = 4,
}
const enum CopyRecordOptionsEnum {
adCopyAllowEmulation = 4,
adCopyNonRecursive = 2,
adCopyOverWrite = 1,
adCopyUnspecified = -1,
}
const enum CursorLocationEnum {
adUseClient = 3,
adUseClientBatch = 3,
adUseNone = 1,
adUseServer = 2,
}
const enum CursorOptionEnum {
adAddNew = 16778240,
adApproxPosition = 16384,
adBookmark = 8192,
adDelete = 16779264,
adFind = 524288,
adHoldRecords = 256,
adIndex = 8388608,
adMovePrevious = 512,
adNotify = 262144,
adResync = 131072,
adSeek = 4194304,
adUpdate = 16809984,
adUpdateBatch = 65536,
}
const enum CursorTypeEnum {
adOpenDynamic = 2,
adOpenForwardOnly = 0,
adOpenKeyset = 1,
adOpenStatic = 3,
adOpenUnspecified = -1,
}
const enum DataTypeEnum {
adArray = 8192,
adBigInt = 20,
adBinary = 128,
adBoolean = 11,
adBSTR = 8,
adChapter = 136,
adChar = 129,
adCurrency = 6,
adDate = 7,
adDBDate = 133,
adDBTime = 134,
adDBTimeStamp = 135,
adDecimal = 14,
adDouble = 5,
adEmpty = 0,
adError = 10,
adFileTime = 64,
adGUID = 72,
adIDispatch = 9,
adInteger = 3,
adIUnknown = 13,
adLongVarBinary = 205,
adLongVarChar = 201,
adLongVarWChar = 203,
adNumeric = 131,
adPropVariant = 138,
adSingle = 4,
adSmallInt = 2,
adTinyInt = 16,
adUnsignedBigInt = 21,
adUnsignedInt = 19,
adUnsignedSmallInt = 18,
adUnsignedTinyInt = 17,
adUserDefined = 132,
adVarBinary = 204,
adVarChar = 200,
adVariant = 12,
adVarNumeric = 139,
adVarWChar = 202,
adWChar = 130,
}
const enum EditModeEnum {
adEditAdd = 2,
adEditDelete = 4,
adEditInProgress = 1,
adEditNone = 0,
}
const enum ErrorValueEnum {
adErrBoundToCommand = 3707,
adErrCannotComplete = 3732,
adErrCantChangeConnection = 3748,
adErrCantChangeProvider = 3220,
adErrCantConvertvalue = 3724,
adErrCantCreate = 3725,
adErrCatalogNotSet = 3747,
adErrColumnNotOnThisRow = 3726,
adErrConnectionStringTooLong = 3754,
adErrDataConversion = 3421,
adErrDataOverflow = 3721,
adErrDelResOutOfScope = 3738,
adErrDenyNotSupported = 3750,
adErrDenyTypeNotSupported = 3751,
adErrFeatureNotAvailable = 3251,
adErrFieldsUpdateFailed = 3749,
adErrIllegalOperation = 3219,
adErrIntegrityViolation = 3719,
adErrInTransaction = 3246,
adErrInvalidArgument = 3001,
adErrInvalidConnection = 3709,
adErrInvalidParamInfo = 3708,
adErrInvalidTransaction = 3714,
adErrInvalidURL = 3729,
adErrItemNotFound = 3265,
adErrNoCurrentRecord = 3021,
adErrNotExecuting = 3715,
adErrNotReentrant = 3710,
adErrObjectClosed = 3704,
adErrObjectInCollection = 3367,
adErrObjectNotSet = 3420,
adErrObjectOpen = 3705,
adErrOpeningFile = 3002,
adErrOperationCancelled = 3712,
adErrOutOfSpace = 3734,
adErrPermissionDenied = 3720,
adErrPropConflicting = 3742,
adErrPropInvalidColumn = 3739,
adErrPropInvalidOption = 3740,
adErrPropInvalidValue = 3741,
adErrPropNotAllSettable = 3743,
adErrPropNotSet = 3744,
adErrPropNotSettable = 3745,
adErrPropNotSupported = 3746,
adErrProviderFailed = 3000,
adErrProviderNotFound = 3706,
adErrProviderNotSpecified = 3753,
adErrReadFile = 3003,
adErrResourceExists = 3731,
adErrResourceLocked = 3730,
adErrResourceOutOfScope = 3735,
adErrSchemaViolation = 3722,
adErrSignMismatch = 3723,
adErrStillConnecting = 3713,
adErrStillExecuting = 3711,
adErrTreePermissionDenied = 3728,
adErrUnavailable = 3736,
adErrUnsafeOperation = 3716,
adErrURLDoesNotExist = 3727,
adErrURLNamedRowDoesNotExist = 3737,
adErrVolumeNotFound = 3733,
adErrWriteFile = 3004,
adwrnSecurityDialog = 3717,
adwrnSecurityDialogHeader = 3718,
}
const enum EventReasonEnum {
adRsnAddNew = 1,
adRsnClose = 9,
adRsnDelete = 2,
adRsnFirstChange = 11,
adRsnMove = 10,
adRsnMoveFirst = 12,
adRsnMoveLast = 15,
adRsnMoveNext = 13,
adRsnMovePrevious = 14,
adRsnRequery = 7,
adRsnResynch = 8,
adRsnUndoAddNew = 5,
adRsnUndoDelete = 6,
adRsnUndoUpdate = 4,
adRsnUpdate = 3,
}
const enum EventStatusEnum {
adStatusCancel = 4,
adStatusCantDeny = 3,
adStatusErrorsOccurred = 2,
adStatusOK = 1,
adStatusUnwantedEvent = 5,
}
const enum ExecuteOptionEnum {
adAsyncExecute = 16,
adAsyncFetch = 32,
adAsyncFetchNonBlocking = 64,
adExecuteNoRecords = 128,
adExecuteRecord = 2048,
adExecuteStream = 1024,
adOptionUnspecified = -1,
}
const enum FieldAttributeEnum {
adFldCacheDeferred = 4096,
adFldFixed = 16,
adFldIsChapter = 8192,
adFldIsCollection = 262144,
adFldIsDefaultStream = 131072,
adFldIsNullable = 32,
adFldIsRowURL = 65536,
adFldKeyColumn = 32768,
adFldLong = 128,
adFldMayBeNull = 64,
adFldMayDefer = 2,
adFldNegativeScale = 16384,
adFldRowID = 256,
adFldRowVersion = 512,
adFldUnknownUpdatable = 8,
adFldUnspecified = -1,
adFldUpdatable = 4,
}
const enum FieldEnum {
adDefaultStream = -1,
adRecordURL = -2,
}
const enum FieldStatusEnum {
adFieldAlreadyExists = 26,
adFieldBadStatus = 12,
adFieldCannotComplete = 20,
adFieldCannotDeleteSource = 23,
adFieldCantConvertValue = 2,
adFieldCantCreate = 7,
adFieldDataOverflow = 6,
adFieldDefault = 13,
adFieldDoesNotExist = 16,
adFieldIgnore = 15,
adFieldIntegrityViolation = 10,
adFieldInvalidURL = 17,
adFieldIsNull = 3,
adFieldOK = 0,
adFieldOutOfSpace = 22,
adFieldPendingChange = 262144,
adFieldPendingDelete = 131072,
adFieldPendingInsert = 65536,
adFieldPendingUnknown = 524288,
adFieldPendingUnknownDelete = 1048576,
adFieldPermissionDenied = 9,
adFieldReadOnly = 24,
adFieldResourceExists = 19,
adFieldResourceLocked = 18,
adFieldResourceOutOfScope = 25,
adFieldSchemaViolation = 11,
adFieldSignMismatch = 5,
adFieldTruncated = 4,
adFieldUnavailable = 8,
adFieldVolumeNotFound = 21,
}
const enum FilterGroupEnum {
adFilterAffectedRecords = 2,
adFilterConflictingRecords = 5,
adFilterFetchedRecords = 3,
adFilterNone = 0,
adFilterPendingRecords = 1,
adFilterPredicate = 4,
}
const enum GetRowsOptionEnum {
adGetRowsRest = -1,
}
const enum IsolationLevelEnum {
adXactBrowse = 256,
adXactChaos = 16,
adXactCursorStability = 4096,
adXactIsolated = 1048576,
adXactReadCommitted = 4096,
adXactReadUncommitted = 256,
adXactRepeatableRead = 65536,
adXactSerializable = 1048576,
adXactUnspecified = -1,
}
const enum LineSeparatorEnum {
adCR = 13,
adCRLF = -1,
adLF = 10,
}
const enum LockTypeEnum {
adLockBatchOptimistic = 4,
adLockOptimistic = 3,
adLockPessimistic = 2,
adLockReadOnly = 1,
adLockUnspecified = -1,
}
const enum MarshalOptionsEnum {
adMarshalAll = 0,
adMarshalModifiedOnly = 1,
}
const enum MoveRecordOptionsEnum {
adMoveAllowEmulation = 4,
adMoveDontUpdateLinks = 2,
adMoveOverWrite = 1,
adMoveUnspecified = -1,
}
const enum ObjectStateEnum {
adStateClosed = 0,
adStateConnecting = 2,
adStateExecuting = 4,
adStateFetching = 8,
adStateOpen = 1,
}
const enum ParameterAttributesEnum {
adParamLong = 128,
adParamNullable = 64,
adParamSigned = 16,
}
const enum ParameterDirectionEnum {
adParamInput = 1,
adParamInputOutput = 3,
adParamOutput = 2,
adParamReturnValue = 4,
adParamUnknown = 0,
}
const enum PersistFormatEnum {
adPersistADTG = 0,
adPersistXML = 1,
}
const enum PositionEnum {
adPosBOF = -2,
adPosEOF = -3,
adPosUnknown = -1,
}
const enum PositionEnum_Param {
adPosBOF = -2,
adPosEOF = -3,
adPosUnknown = -1,
}
const enum PropertyAttributesEnum {
adPropNotSupported = 0,
adPropOptional = 2,
adPropRead = 512,
adPropRequired = 1,
adPropWrite = 1024,
}
const enum RecordCreateOptionsEnum {
adCreateCollection = 8192,
adCreateNonCollection = 0,
adCreateOverwrite = 67108864,
adCreateStructDoc = -2147483648,
adFailIfNotExists = -1,
adOpenIfExists = 33554432,
}
const enum RecordOpenOptionsEnum {
adDelayFetchFields = 32768,
adDelayFetchStream = 16384,
adOpenAsync = 4096,
adOpenExecuteCommand = 65536,
adOpenOutput = 8388608,
adOpenRecordUnspecified = -1,
adOpenSource = 8388608,
}
const enum RecordStatusEnum {
adRecCanceled = 256,
adRecCantRelease = 1024,
adRecConcurrencyViolation = 2048,
adRecDBDeleted = 262144,
adRecDeleted = 4,
adRecIntegrityViolation = 4096,
adRecInvalid = 16,
adRecMaxChangesExceeded = 8192,
adRecModified = 2,
adRecMultipleChanges = 64,
adRecNew = 1,
adRecObjectOpen = 16384,
adRecOK = 0,
adRecOutOfMemory = 32768,
adRecPendingChanges = 128,
adRecPermissionDenied = 65536,
adRecSchemaViolation = 131072,
adRecUnmodified = 8,
}
const enum RecordTypeEnum {
adCollectionRecord = 1,
adSimpleRecord = 0,
adStructDoc = 2,
}
const enum ResyncEnum {
adResyncAllValues = 2,
adResyncUnderlyingValues = 1,
}
const enum SaveOptionsEnum {
adSaveCreateNotExist = 1,
adSaveCreateOverWrite = 2,
}
const enum SchemaEnum {
adSchemaActions = 41,
adSchemaAsserts = 0,
adSchemaCatalogs = 1,
adSchemaCharacterSets = 2,
adSchemaCheckConstraints = 5,
adSchemaCollations = 3,
adSchemaColumnPrivileges = 13,
adSchemaColumns = 4,
adSchemaColumnsDomainUsage = 11,
adSchemaCommands = 42,
adSchemaConstraintColumnUsage = 6,
adSchemaConstraintTableUsage = 7,
adSchemaCubes = 32,
adSchemaDBInfoKeywords = 30,
adSchemaDBInfoLiterals = 31,
adSchemaDimensions = 33,
adSchemaForeignKeys = 27,
adSchemaFunctions = 40,
adSchemaHierarchies = 34,
adSchemaIndexes = 12,
adSchemaKeyColumnUsage = 8,
adSchemaLevels = 35,
adSchemaMeasures = 36,
adSchemaMembers = 38,
adSchemaPrimaryKeys = 28,
adSchemaProcedureColumns = 29,
adSchemaProcedureParameters = 26,
adSchemaProcedures = 16,
adSchemaProperties = 37,
adSchemaProviderSpecific = -1,
adSchemaProviderTypes = 22,
adSchemaReferentialConstraints = 9,
adSchemaReferentialContraints = 9,
adSchemaSchemata = 17,
adSchemaSets = 43,
adSchemaSQLLanguages = 18,
adSchemaStatistics = 19,
adSchemaTableConstraints = 10,
adSchemaTablePrivileges = 14,
adSchemaTables = 20,
adSchemaTranslations = 21,
adSchemaTrustees = 39,
adSchemaUsagePrivileges = 15,
adSchemaViewColumnUsage = 24,
adSchemaViews = 23,
adSchemaViewTableUsage = 25,
}
const enum SearchDirection {
adSearchBackward = -1,
adSearchForward = 1,
}
const enum SearchDirectionEnum {
adSearchBackward = -1,
adSearchForward = 1,
}
const enum SeekEnum {
adSeekAfter = 8,
adSeekAfterEQ = 4,
adSeekBefore = 32,
adSeekBeforeEQ = 16,
adSeekFirstEQ = 1,
adSeekLastEQ = 2,
}
const enum StreamOpenOptionsEnum {
adOpenStreamAsync = 1,
adOpenStreamFromRecord = 4,
adOpenStreamUnspecified = -1,
}
const enum StreamReadEnum {
adReadAll = -1,
adReadLine = -2,
}
const enum StreamTypeEnum {
adTypeBinary = 1,
adTypeText = 2,
}
const enum StreamWriteEnum {
adWriteChar = 0,
adWriteLine = 1,
stWriteChar = 0,
stWriteLine = 1,
}
const enum StringFormatEnum {
adClipString = 2,
}
const enum XactAttributeEnum {
adXactAbortRetaining = 262144,
adXactAsyncPhaseOne = 524288,
adXactCommitRetaining = 131072,
adXactSyncPhaseOne = 1048576,
}
class Bookmark {
private 'ADODB.Bookmark_typekey': Bookmark;
private constructor();
}
class Command {
private 'ADODB.Command_typekey': Command;
private constructor();
/**
* Sets or returns a String value that contains a definition for a connection if the connection is closed, or a Variant containing the current Connection object if the connection is open. Default is a null object reference.
*/
ActiveConnection: string | Connection | null;
Cancel(): void;
CommandStream: any;
CommandText: string;
CommandTimeout: number;
CommandType: CommandTypeEnum;
/**
* @param Name [Name='']
* @param Type [Type=0]
* @param Direction [Direction=1]
* @param Size [Size=0]
*/
CreateParameter(Name?: string, Type?: DataTypeEnum, Direction?: ParameterDirectionEnum, Size?: number, Value?: any): Parameter;
Dialect: string;
/**
* @param Options [Options=-1]
*
* The **RecordsAffected** parameter is meant to take a variable to be modified by reference, which is not supported by Javascript
*
* The return value is as follows:
*
* * If the **adExecuteNoRecords** option is passed in, the method will return `null`. Otherwise:
* * If the command specifies a row-returning query, then the method will return a new read-only, forward-only **Recordset** object with the results.
* * If the command isn't intended to return results (e.g. an `UPDATE` statement), a closed empty **Recordset** will be returned.
*/
Execute(RecordsAffected?: undefined, Parameters?: SafeArray, Options?: number): Recordset | null;
Name: string;
NamedParameters: boolean;
readonly Parameters: Parameters;
Prepared: boolean;
readonly Properties: Properties;
readonly State: ObjectStateEnum;
}
class Connection {
private 'ADODB.Connection_typekey': Connection;
private constructor();
/** Sum of one or more of the values in the **XactAttributeEnum** enum */
Attributes: XactAttributeEnum;
BeginTrans(): number;
Cancel(): void;
Close(): void;
CommandTimeout: number;
CommitTrans(): void;
ConnectionString: string;
ConnectionTimeout: number;
CursorLocation: CursorLocationEnum;
DefaultDatabase: string;
readonly Errors: Errors;
/**
* @param Options [Options=-1]
*
* The **RecordsAffected** parameter is meant to take a variable to be modified by reference, which is not supported by Javascript
*
* The return value is as follows:
*
* * If the **adExecuteNoRecords** option is passed in, the method will return `null`. Otherwise:
* * If **CommandText** specifies a row-returning query, then the method will return a new read-only, forward-only **Recordset** object with the results
* * If **CommandText** isn't intended to return results (e.g. an `UPDATE` statement), a closed empty **Recordset** will be returned.
*/
Execute(CommandText: string, RecordsAffected?: undefined, Options?: CommandTypeEnum | ExecuteOptionEnum): Recordset | null;
IsolationLevel: IsolationLevelEnum;
Mode: ConnectModeEnum;
/**
* @param ConnectionString [ConnectionString='']
* @param UserID [UserID='']
* @param Password [Password='']
* @param Options [Options=-1]
*/
Open(ConnectionString?: string, UserID?: string, Password?: string, Options?: number): void;
/**
* Returns a Recordset object that contains schema information
* @param Schema Type of schema query to run
* @param Restrictions A SafeArray of query constraints; depends on the [type of the schema query](https://msdn.microsoft.com/en-us/library/jj249359.aspx)
*/
OpenSchema(Schema: SchemaEnum, Restrictions?: SafeArray<string>): Recordset;
/**
* Returns a Recordset object that contains schema information, for a provider-specific schema query type
* @param SchemaID The GUID for a provider-schema query not defined by the OLE DB specification.
*/
OpenSchema(Schema: SchemaEnum.adSchemaProviderSpecific, Restrictions: SafeArray<string>, SchemaID: string): Recordset;
readonly Properties: Properties;
Provider: string;
RollbackTrans(): void;
readonly State: ObjectStateEnum;
readonly Version: string;
}
class Error {
private 'ADODB.Error_typekey': Error;
private constructor();
readonly Description: string;
readonly HelpContext: number;
readonly HelpFile: string;
readonly NativeError: number;
readonly Number: number;
readonly Source: string;
readonly SQLState: string;
}
interface Errors {
Clear(): void;
readonly Count: number;
Item(Index: any): Error;
Refresh(): void;
(Index: any): Error;
}
class Field {
private 'ADODB.Field_typekey': Field;
private constructor();
readonly ActualSize: number;
AppendChunk(Data: any): void;
/** Sum of one or more of the values in the **FieldAttributeEnum** enum */
Attributes: FieldAttributeEnum;
DataFormat: any;
DefinedSize: number;
GetChunk(Length: number): any;
readonly Name: string;
NumericScale: number;
readonly OriginalValue: any;
Precision: number;
readonly Properties: Properties;
readonly Status: number;
Type: DataTypeEnum;
readonly UnderlyingValue: any;
Value: any;
}
interface Fields {
/**
* @param DefinedSize [DefinedSize=0]
* @param Attrib [Attrib=-1]
*/
_Append(Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum): void;
/**
* @param DefinedSize [DefinedSize=0]
* @param Attrib [Attrib=-1]
*/
Append(Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum, FieldValue?: any): void;
CancelUpdate(): void;
readonly Count: number;
Delete(Index: string | number): void;
Item(Index: string | number): Field;
Refresh(): void;
/** @param ResyncValues [ResyncValues=2] */
Resync(ResyncValues?: ResyncEnum): void;
Update(): void;
(Index: string | number): Field;
}
class Parameter {
private 'ADODB.Parameter_typekey': Parameter;
private constructor();
AppendChunk(Val: any): void;
/** Sum of one or more of the values in the **ParameterAttributesEnum** enum */
Attributes: ParameterAttributesEnum;
Direction: ParameterDirectionEnum;
Name: string;
NumericScale: number;
Precision: number;
readonly Properties: Properties;
Size: number;
Type: DataTypeEnum;
Value: any;
}
interface Parameters {
Append(Object: any): void;
readonly Count: number;
Delete(Index: string | number): void;
Item(Index: string | number): Parameter;
Refresh(): void;
(Index: string | number): Parameter;
}
interface Properties {
readonly Count: number;
Item(Index: string | number): Property;
Refresh(): void;
(Index: string | number): Property;
}
class Property {
private 'ADODB.Property_typekey': Property;
private constructor();
/** Sum of one or more of the values in the **PropertyAttributesEnum** enum */
Attributes: PropertyAttributesEnum;
readonly Name: string;
readonly Type: DataTypeEnum;
Value: any;
}
class Record {
private 'ADODB.Record_typekey': Record;
private constructor();
/**
* Sets or returns a String value that contains a definition for a connection if the connection is closed, or a Variant containing the current Connection object if the connection is open. Default is a null object reference.
*/
ActiveConnection: string | Connection | null;
Cancel(): void;
Close(): void;
/**
* @param Source [Source='']
* @param Destination [Destination='']
* @param UserName [UserName='']
* @param Password [Password='']
* @param Options [Options=-1]
* @param Async [Async=false]
*/
CopyRecord(Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: CopyRecordOptionsEnum, Async?: boolean): string;
/**
* @param Source [Source='']
* @param Async [Async=false]
*/
DeleteRecord(Source?: string, Async?: boolean): void;
readonly Fields: Fields;
GetChildren(): Recordset;
Mode: ConnectModeEnum;
/**
* @param Source [Source='']
* @param Destination [Destination='']
* @param UserName [UserName='']
* @param Password [Password='']
* @param Options [Options=-1]
* @param Async [Async=false]
*/
MoveRecord(Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: MoveRecordOptionsEnum, Async?: boolean): string;
/**
* Source may be:
* * A URL. If the protocol for the URL is http, then the Internet Provider will be invoked by default. If the URL points to a node that contains an executable script (such as an .ASP page), then a Record containing the source rather than the executed contents is opened by default. Use the Options argument to modify this behavior.
* * A Record object. A Record object opened from another Record will clone the original Record object.
* * A Command object. The opened Record object represents the single row returned by executing the Command. If the results contain more than a single row, the contents of the first row are placed in the record and an error may be added to the Errors collection.
* * A SQL SELECT statement. The opened Record object represents the single row returned by executing the contents of the string. If the results contain more than a single row, the contents of the first row are placed in the record and an error may be added to the Errors collection.
* * A table name.
*
* @param Mode [Mode=0]
* @param CreateOptions [CreateOptions=-1]
* @param Options [Options=-1]
* @param UserName [UserName='']
* @param Password [Password='']
*/
Open(Source?: string | Record | Recordset | Command, ActiveConnection?: string | Connection, Mode?: ConnectModeEnum, CreateOptions?: RecordCreateOptionsEnum, Options?: RecordOpenOptionsEnum, UserName?: string, Password?: string): void;
readonly ParentURL: string;
readonly Properties: Properties;
readonly RecordType: RecordTypeEnum;
Source: string | Recordset | Command;
readonly State: ObjectStateEnum;
}
interface Recordset {
_xClone(): Recordset;
/** @param AffectRecords [AffectRecords=3] */
_xResync(AffectRecords?: AffectEnum): void;
/**
* @param FileName [FileName='']
* @param PersistFormat [PersistFormat=0]
*/
_xSave(FileName?: string, PersistFormat?: PersistFormatEnum): void;
AbsolutePage: PositionEnum;
AbsolutePosition: PositionEnum;
readonly ActiveCommand?: Command;
/**
* Sets or returns a String value that contains a definition for a connection if the connection is closed, or a Variant containing the current Connection object if the connection is open. Default is a null object reference.
*/
ActiveConnection: string | Connection | null;
AddNew(): void;
AddNew(Fields: SafeArray<string | number>, Values: SafeArray): void;
AddNew(Field: string, Value: any): void;
readonly BOF: boolean;
Bookmark: Bookmark;
CacheSize: number;
Cancel(): void;
/** @param AffectRecords [AffectRecords=3] */
CancelBatch(AffectRecords?: AffectEnum): void;
CancelUpdate(): void;
/** @param LockType [LockType=-1] */
Clone(LockType?: LockTypeEnum): Recordset;
Close(): void;
Collect(Index: any): any;
CompareBookmarks(Bookmark1: Bookmark, Bookmark2: Bookmark): CompareEnum;
CursorLocation: CursorLocationEnum;
CursorType: CursorTypeEnum;
DataMember: string;
DataSource: any;
/** @param AffectRecords [AffectRecords=1] */
Delete(AffectRecords?: AffectEnum): void;
readonly EditMode: EditModeEnum;
readonly EOF: boolean;
readonly Fields: Fields;
/**
* Sets or returns one of the following:
* * Criteria string — a string made up of one or more individual clauses concatenated with AND or OR operators.
* * Array of bookmarks — an array of unique bookmark values that point to records in the Recordset object.
* * A FilterGroupEnum value
*/
Filter: string | SafeArray<Bookmark> | FilterGroupEnum;
/**
* @param SkipRecords [SkipRecords=0]
* @param SearchDirection [SearchDirection=1]
*/
Find(Criteria: string, SkipRecords?: number, SearchDirection?: SearchDirectionEnum, Start?: Bookmark): void;
/** @param Rows [Rows=-1] */
GetRows(Rows?: number, Start?: string | Bookmark | BookmarkEnum, Fields?: string | SafeArray<string | number>): SafeArray;
/**
* @param StringFormat [StringFormat=2]
* @param NumRows [NumRows=-1]
* @param ColumnDelimeter [ColumnDelimeter='']
* @param RowDelimeter [RowDelimeter='']
* @param NullExpr [NullExpr='']
*/
GetString(StringFormat?: StringFormatEnum, NumRows?: number, ColumnDelimeter?: string, RowDelimeter?: string, NullExpr?: string): string;
Index: string;
LockType: LockTypeEnum;
MarshalOptions: MarshalOptionsEnum;
MaxRecords: number;
Move(NumRecords: number, Start?: string | Bookmark | BookmarkEnum): void;
MoveFirst(): void;
MoveLast(): void;
MoveNext(): void;
MovePrevious(): void;
/** Since Javascript doesn't support byref parameters, the RecordsAffected parameter cannot be used */
NextRecordset(): Recordset;
/**
* @param CursorType [CursorType=-1]
* @param LockType [LockType=-1]
* @param Options [Options=-1]
*/
Open(Source: Command, ActiveConnection: null, CursorType?: CursorTypeEnum, LockType?: LockTypeEnum, Options?: CommandTypeEnum | ExecuteOptionEnum): void;
Open(Source?: Stream): void;
/**
* @param CursorType [CursorType=-1]
* @param LockType [LockType=-1]
* @param Options [Options=-1]
*/
Open(Source: string, ActiveConnection: string | Connection, CursorType?: CursorTypeEnum, LockType?: LockTypeEnum, Options?: CommandTypeEnum | ExecuteOptionEnum): void;
readonly PageCount: number;
PageSize: number;
readonly Properties: Properties;
readonly RecordCount: number;
/** @param Options [Options=-1] */
Requery(Options?: number): void;
/**
* @param AffectRecords [AffectRecords=3]
* @param ResyncValues [ResyncValues=2]
*/
Resync(AffectRecords?: AffectEnum, ResyncValues?: ResyncEnum): void;
/** @param PersistFormat [PersistFormat=0] */
Save(Destination: string | Stream, PersistFormat?: PersistFormatEnum): void;
/**
* @param SeekOption [SeekOption=1]
*
* For a single-column index, pass in a single value to seek in the column of the index
*
* For a multi-column index, pass in a SafeArray containing the multiple values to seek in the columns of the index.
*/
Seek(KeyValues: any, SeekOption?: SeekEnum): void;
Sort: string;
Source: string | Command;
readonly State: ObjectStateEnum;
readonly Status: number;
StayInSync: boolean;
Supports(CursorOptions: CursorOptionEnum): boolean;
Update(): void;
Update(Fields: SafeArray<string | number>, Values: SafeArray): void;
Update(Field: string, Value: any): void;
/** @param AffectRecords [AffectRecords=3] */
UpdateBatch(AffectRecords?: AffectEnum): void;
(FieldIndex: string | number): Field;
}
class Stream {
private 'ADODB.Stream_typekey': Stream;
private constructor();
Cancel(): void;
Charset: string;
Close(): void;
/** @param CharNumber [CharNumber=-1] */
CopyTo(DestStream: Stream, CharNumber?: number): void;
readonly EOS: boolean;
Flush(): void;
LineSeparator: LineSeparatorEnum;
LoadFromFile(FileName: string): void;
Mode: ConnectModeEnum;
/**
* @param Mode [Mode=0]
* @param Options [Options=-1]
* @param UserName [UserName='']
* @param Password [Password='']
*/
Open(Source?: string | Record, Mode?: ConnectModeEnum, Options?: StreamOpenOptionsEnum, UserName?: string, Password?: string): void;
Position: number;
/** @param NumBytes [NumBytes=-1] */
Read(NumBytes?: number): any;
/** @param NumChars [NumChars=-1] */
ReadText(NumChars?: number): string;
/** @param Options [Options=1] */
SaveToFile(FileName: string, Options?: SaveOptionsEnum): void;
SetEOS(): void;
readonly Size: number;
SkipLine(): void;
readonly State: ObjectStateEnum;
Type: StreamTypeEnum;
Write(Buffer: any): void;
/** @param Options [Options=0] */
WriteText(Data: string, Options?: StreamWriteEnum): void;
}
namespace EventHelperTypes {
type Connection_ExecuteComplete_ArgNames = ['RecordsAffected', 'pError', 'adStatus', 'pCommand', 'pRecordset', 'pConnection'];
type Connection_WillConnect_ArgNames = ['ConnectionString', 'UserID', 'Password', 'Options', 'adStatus', 'pConnection'];
type Connection_WillExecute_ArgNames = ['Source', 'CursorType', 'LockType', 'Options', 'adStatus', 'pCommand', 'pRecordset', 'pConnection'];
interface Connection_ExecuteComplete_Parameter {
adStatus: EventStatusEnum;
readonly pCommand: Command;
readonly pConnection: Connection;
readonly pError: Error;
readonly pRecordset: Recordset;
readonly RecordsAffected: number;
}
interface Connection_WillConnect_Parameter {
adStatus: EventStatusEnum;
ConnectionString: string;
Options: number;
Password: string;
readonly pConnection: Connection;
UserID: string;
}
interface Connection_WillExecute_Parameter {
adStatus: EventStatusEnum;
CursorType: CursorTypeEnum;
LockType: LockTypeEnum;
Options: number;
readonly pCommand: Command;
readonly pConnection: Connection;
readonly pRecordset: Recordset;
Source: string;
}
}
}
interface ActiveXObject {
on(obj: ADODB.Connection, event: 'BeginTransComplete', argNames: ['TransactionLevel', 'pError', 'adStatus', 'pConnection'], handler: (this: ADODB.Connection, parameter: {readonly TransactionLevel: number, readonly pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, readonly pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Connection, event: 'CommitTransComplete' | 'ConnectComplete' | 'InfoMessage' | 'RollbackTransComplete', argNames: ['pError', 'adStatus', 'pConnection'], handler: (this: ADODB.Connection, parameter: {readonly pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, readonly pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Connection, event: 'Disconnect', argNames: ['adStatus', 'pConnection'], handler: (this: ADODB.Connection, parameter: {adStatus: ADODB.EventStatusEnum, readonly pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Connection, event: 'ExecuteComplete', argNames: ADODB.EventHelperTypes.Connection_ExecuteComplete_ArgNames, handler: (this: ADODB.Connection, parameter: ADODB.EventHelperTypes.Connection_ExecuteComplete_Parameter) => void): void;
on(obj: ADODB.Connection, event: 'WillConnect', argNames: ADODB.EventHelperTypes.Connection_WillConnect_ArgNames, handler: (this: ADODB.Connection, parameter: ADODB.EventHelperTypes.Connection_WillConnect_Parameter) => void): void;
on(obj: ADODB.Connection, event: 'WillExecute', argNames: ADODB.EventHelperTypes.Connection_WillExecute_ArgNames, handler: (this: ADODB.Connection, parameter: ADODB.EventHelperTypes.Connection_WillExecute_Parameter) => void): void;
on(obj: ADODB.Recordset, event: 'EndOfRecordset', argNames: ['fMoreData', 'adStatus', 'pRecordset'], handler: (this: ADODB.Recordset, parameter: {fMoreData: boolean, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'FetchComplete', argNames: ['pError', 'adStatus', 'pRecordset'], handler: (this: ADODB.Recordset, parameter: {readonly pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'FetchProgress', argNames: ['Progress', 'MaxProgress', 'adStatus', 'pRecordset'], handler: (this: ADODB.Recordset, parameter: {readonly Progress: number, readonly MaxProgress: number, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'FieldChangeComplete', argNames: ['cFields', 'Fields', 'pError', 'adStatus', 'pRecordset'], handler: (this: ADODB.Recordset, parameter: {readonly cFields: number, readonly Fields: any, readonly pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'MoveComplete' | 'RecordsetChangeComplete', argNames: ['adReason', 'pError', 'adStatus', 'pRecordset'], handler: (this: ADODB.Recordset, parameter: {readonly adReason: ADODB.EventReasonEnum, readonly pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'RecordChangeComplete', argNames: ['adReason', 'cRecords', 'pError', 'adStatus', 'pRecordset'], handler: (this: ADODB.Recordset, parameter: {readonly adReason: ADODB.EventReasonEnum, readonly cRecords: number, readonly pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'WillChangeField', argNames: ['cFields', 'Fields', 'adStatus', 'pRecordset'], handler: (this: ADODB.Recordset, parameter: {readonly cFields: number, readonly Fields: any, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'WillChangeRecord', argNames: ['adReason', 'cRecords', 'adStatus', 'pRecordset'], handler: (this: ADODB.Recordset, parameter: {readonly adReason: ADODB.EventReasonEnum, readonly cRecords: number, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'WillChangeRecordset' | 'WillMove', argNames: ['adReason', 'adStatus', 'pRecordset'], handler: (this: ADODB.Recordset, parameter: {readonly adReason: ADODB.EventReasonEnum, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
set(obj: ADODB.Recordset, propertyName: 'Collect', parameterTypes: [any], newValue: any): void;
}
interface ActiveXObjectNameMap {
'ADODB.Command': ADODB.Command;
'ADODB.Connection': ADODB.Connection;
'ADODB.Parameter': ADODB.Parameter;
'ADODB.Record': ADODB.Record;
'ADODB.Recordset': ADODB.Recordset;
'ADODB.Stream': ADODB.Stream;
} | the_stack |
export const heatmapSimpleData = [
{
key: 'Lateral Movement',
data: [
{
key: 'XML',
data: 0
},
{
key: 'JSON',
data: 120
},
{
key: 'HTTPS',
data: 150
},
{
key: 'SSH',
data: 112
}
]
},
{
key: 'Discovery',
data: [
{
key: 'XML',
data: 100
},
{
key: 'JSON',
data: 34
},
{
key: 'HTTPS',
data: 0
},
{
key: 'SSH',
data: 111
}
]
},
{
key: 'Exploitation',
data: [
{
key: 'XML',
data: 70
},
{
key: 'JSON',
data: 1
},
{
key: 'HTTPS',
data: 110
},
{
key: 'SSH',
data: 115
}
]
},
{
key: 'Threat Intelligence',
data: [
{
key: 'XML',
data: 1
},
{
key: 'JSON',
data: 120
},
{
key: 'HTTPS',
data: 200
},
{
key: 'SSH',
data: 160
}
]
},
{
key: 'Breach',
data: [
{
key: 'XML',
data: 5
},
{
key: 'JSON',
data: 10
},
{
key: 'HTTPS',
data: 152
},
{
key: 'SSH',
data: 20
}
]
}
];
// const yearStart = moment().startOf('year');
// export const heatmapCalendarData = range(365).map(i => ({
// key: yearStart.clone().add(i, 'days').toDate(),
// data: randomNumber(0, 50)
// }));
export const heatmapCalendarData = [
{
key: new Date('2020-01-01T08:00:00.000Z'),
data: 46
},
{
key: new Date('2020-01-02T08:00:00.000Z'),
data: 24
},
{
key: new Date('2020-01-03T08:00:00.000Z'),
data: 46
},
{
key: new Date('2020-01-04T08:00:00.000Z'),
data: 15
},
{
key: new Date('2020-01-05T08:00:00.000Z'),
data: 27
},
{
key: new Date('2020-01-06T08:00:00.000Z'),
data: 37
},
{
key: new Date('2020-01-07T08:00:00.000Z'),
data: 29
},
{
key: new Date('2020-01-08T08:00:00.000Z'),
data: 1
},
{
key: new Date('2020-01-09T08:00:00.000Z'),
data: 2
},
{
key: new Date('2020-01-10T08:00:00.000Z'),
data: 2
},
{
key: new Date('2020-01-11T08:00:00.000Z'),
data: 10
},
{
key: new Date('2020-01-12T08:00:00.000Z'),
data: 24
},
{
key: new Date('2020-01-13T08:00:00.000Z'),
data: 7
},
{
key: new Date('2020-01-14T08:00:00.000Z'),
data: 6
},
{
key: new Date('2020-01-15T08:00:00.000Z'),
data: 48
},
{
key: new Date('2020-01-16T08:00:00.000Z'),
data: 16
},
{
key: new Date('2020-01-17T08:00:00.000Z'),
data: 21
},
{
key: new Date('2020-01-18T08:00:00.000Z'),
data: 20
},
{
key: new Date('2020-01-19T08:00:00.000Z'),
data: 49
},
{
key: new Date('2020-01-20T08:00:00.000Z'),
data: 14
},
{
key: new Date('2020-01-21T08:00:00.000Z'),
data: 46
},
{
key: new Date('2020-01-22T08:00:00.000Z'),
data: 10
},
{
key: new Date('2020-01-23T08:00:00.000Z'),
data: 46
},
{
key: new Date('2020-01-24T08:00:00.000Z'),
data: 31
},
{
key: new Date('2020-01-25T08:00:00.000Z'),
data: 27
},
{
key: new Date('2020-01-26T08:00:00.000Z'),
data: 47
},
{
key: new Date('2020-01-27T08:00:00.000Z'),
data: 48
},
{
key: new Date('2020-01-28T08:00:00.000Z'),
data: 12
},
{
key: new Date('2020-01-29T08:00:00.000Z'),
data: 28
},
{
key: new Date('2020-01-30T08:00:00.000Z'),
data: 30
},
{
key: new Date('2020-01-31T08:00:00.000Z'),
data: 41
},
{
key: new Date('2020-02-01T08:00:00.000Z'),
data: 26
},
{
key: new Date('2020-02-02T08:00:00.000Z'),
data: 17
},
{
key: new Date('2020-02-03T08:00:00.000Z'),
data: 30
},
{
key: new Date('2020-02-04T08:00:00.000Z'),
data: 4
},
{
key: new Date('2020-02-05T08:00:00.000Z'),
data: 21
},
{
key: new Date('2020-02-06T08:00:00.000Z'),
data: 45
},
{
key: new Date('2020-02-07T08:00:00.000Z'),
data: 49
},
{
key: new Date('2020-02-08T08:00:00.000Z'),
data: 34
},
{
key: new Date('2020-02-09T08:00:00.000Z'),
data: 22
},
{
key: new Date('2020-02-10T08:00:00.000Z'),
data: 27
},
{
key: new Date('2020-02-11T08:00:00.000Z'),
data: 37
},
{
key: new Date('2020-02-12T08:00:00.000Z'),
data: 16
},
{
key: new Date('2020-02-13T08:00:00.000Z'),
data: 37
},
{
key: new Date('2020-02-14T08:00:00.000Z'),
data: 4
},
{
key: new Date('2020-02-15T08:00:00.000Z'),
data: 32
},
{
key: new Date('2020-02-16T08:00:00.000Z'),
data: 48
},
{
key: new Date('2020-02-17T08:00:00.000Z'),
data: 26
},
{
key: new Date('2020-02-18T08:00:00.000Z'),
data: 33
},
{
key: new Date('2020-02-19T08:00:00.000Z'),
data: 20
},
{
key: new Date('2020-02-20T08:00:00.000Z'),
data: 14
},
{
key: new Date('2020-02-21T08:00:00.000Z'),
data: 38
},
{
key: new Date('2020-02-22T08:00:00.000Z'),
data: 50
},
{
key: new Date('2020-02-23T08:00:00.000Z'),
data: 20
},
{
key: new Date('2020-02-24T08:00:00.000Z'),
data: 5
},
{
key: new Date('2020-02-25T08:00:00.000Z'),
data: 23
},
{
key: new Date('2020-02-26T08:00:00.000Z'),
data: 6
},
{
key: new Date('2020-02-27T08:00:00.000Z'),
data: 1
},
{
key: new Date('2020-02-28T08:00:00.000Z'),
data: 25
},
{
key: new Date('2020-02-29T08:00:00.000Z'),
data: 25
},
{
key: new Date('2020-03-01T08:00:00.000Z'),
data: 5
},
{
key: new Date('2020-03-02T08:00:00.000Z'),
data: 9
},
{
key: new Date('2020-03-03T08:00:00.000Z'),
data: 12
},
{
key: new Date('2020-03-04T08:00:00.000Z'),
data: 9
},
{
key: new Date('2020-03-05T08:00:00.000Z'),
data: 36
},
{
key: new Date('2020-03-06T08:00:00.000Z'),
data: 47
},
{
key: new Date('2020-03-07T08:00:00.000Z'),
data: 2
},
{
key: new Date('2020-03-08T08:00:00.000Z'),
data: 11
},
{
key: new Date('2020-03-09T07:00:00.000Z'),
data: 47
},
{
key: new Date('2020-03-10T07:00:00.000Z'),
data: 10
},
{
key: new Date('2020-03-11T07:00:00.000Z'),
data: 21
},
{
key: new Date('2020-03-12T07:00:00.000Z'),
data: 41
},
{
key: new Date('2020-03-13T07:00:00.000Z'),
data: 4
},
{
key: new Date('2020-03-14T07:00:00.000Z'),
data: 24
},
{
key: new Date('2020-03-15T07:00:00.000Z'),
data: 12
},
{
key: new Date('2020-03-16T07:00:00.000Z'),
data: 49
},
{
key: new Date('2020-03-17T07:00:00.000Z'),
data: 21
},
{
key: new Date('2020-03-18T07:00:00.000Z'),
data: 31
},
{
key: new Date('2020-03-19T07:00:00.000Z'),
data: 14
},
{
key: new Date('2020-03-20T07:00:00.000Z'),
data: 29
},
{
key: new Date('2020-03-21T07:00:00.000Z'),
data: 19
},
{
key: new Date('2020-03-22T07:00:00.000Z'),
data: 11
},
{
key: new Date('2020-03-23T07:00:00.000Z'),
data: 20
},
{
key: new Date('2020-03-24T07:00:00.000Z'),
data: 47
},
{
key: new Date('2020-03-25T07:00:00.000Z'),
data: 6
},
{
key: new Date('2020-03-26T07:00:00.000Z'),
data: 35
},
{
key: new Date('2020-03-27T07:00:00.000Z'),
data: 41
},
{
key: new Date('2020-03-28T07:00:00.000Z'),
data: 16
},
{
key: new Date('2020-03-29T07:00:00.000Z'),
data: 31
},
{
key: new Date('2020-03-30T07:00:00.000Z'),
data: 49
},
{
key: new Date('2020-03-31T07:00:00.000Z'),
data: 3
},
{
key: new Date('2020-04-01T07:00:00.000Z'),
data: 17
},
{
key: new Date('2020-04-02T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-04-03T07:00:00.000Z'),
data: 45
},
{
key: new Date('2020-04-04T07:00:00.000Z'),
data: 32
},
{
key: new Date('2020-04-05T07:00:00.000Z'),
data: 42
},
{
key: new Date('2020-04-06T07:00:00.000Z'),
data: 6
},
{
key: new Date('2020-04-07T07:00:00.000Z'),
data: 10
},
{
key: new Date('2020-04-08T07:00:00.000Z'),
data: 1
},
{
key: new Date('2020-04-09T07:00:00.000Z'),
data: 26
},
{
key: new Date('2020-04-10T07:00:00.000Z'),
data: 18
},
{
key: new Date('2020-04-11T07:00:00.000Z'),
data: 27
},
{
key: new Date('2020-04-12T07:00:00.000Z'),
data: 31
},
{
key: new Date('2020-04-13T07:00:00.000Z'),
data: 47
},
{
key: new Date('2020-04-14T07:00:00.000Z'),
data: 23
},
{
key: new Date('2020-04-15T07:00:00.000Z'),
data: 23
},
{
key: new Date('2020-04-16T07:00:00.000Z'),
data: 10
},
{
key: new Date('2020-04-17T07:00:00.000Z'),
data: 48
},
{
key: new Date('2020-04-18T07:00:00.000Z'),
data: 42
},
{
key: new Date('2020-04-19T07:00:00.000Z'),
data: 41
},
{
key: new Date('2020-04-20T07:00:00.000Z'),
data: 14
},
{
key: new Date('2020-04-21T07:00:00.000Z'),
data: 31
},
{
key: new Date('2020-04-22T07:00:00.000Z'),
data: 40
},
{
key: new Date('2020-04-23T07:00:00.000Z'),
data: 46
},
{
key: new Date('2020-04-24T07:00:00.000Z'),
data: 41
},
{
key: new Date('2020-04-25T07:00:00.000Z'),
data: 1
},
{
key: new Date('2020-04-26T07:00:00.000Z'),
data: 3
},
{
key: new Date('2020-04-27T07:00:00.000Z'),
data: 3
},
{
key: new Date('2020-04-28T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-04-29T07:00:00.000Z'),
data: 45
},
{
key: new Date('2020-04-30T07:00:00.000Z'),
data: 16
},
{
key: new Date('2020-05-01T07:00:00.000Z'),
data: 38
},
{
key: new Date('2020-05-02T07:00:00.000Z'),
data: 17
},
{
key: new Date('2020-05-03T07:00:00.000Z'),
data: 42
},
{
key: new Date('2020-05-04T07:00:00.000Z'),
data: 37
},
{
key: new Date('2020-05-05T07:00:00.000Z'),
data: 42
},
{
key: new Date('2020-05-06T07:00:00.000Z'),
data: 42
},
{
key: new Date('2020-05-07T07:00:00.000Z'),
data: 40
},
{
key: new Date('2020-05-08T07:00:00.000Z'),
data: 43
},
{
key: new Date('2020-05-09T07:00:00.000Z'),
data: 22
},
{
key: new Date('2020-05-10T07:00:00.000Z'),
data: 23
},
{
key: new Date('2020-05-11T07:00:00.000Z'),
data: 11
},
{
key: new Date('2020-05-12T07:00:00.000Z'),
data: 24
},
{
key: new Date('2020-05-13T07:00:00.000Z'),
data: 49
},
{
key: new Date('2020-05-14T07:00:00.000Z'),
data: 24
},
{
key: new Date('2020-05-15T07:00:00.000Z'),
data: 20
},
{
key: new Date('2020-05-16T07:00:00.000Z'),
data: 17
},
{
key: new Date('2020-05-17T07:00:00.000Z'),
data: 39
},
{
key: new Date('2020-05-18T07:00:00.000Z'),
data: 7
},
{
key: new Date('2020-05-19T07:00:00.000Z'),
data: 28
},
{
key: new Date('2020-05-20T07:00:00.000Z'),
data: 14
},
{
key: new Date('2020-05-21T07:00:00.000Z'),
data: 28
},
{
key: new Date('2020-05-22T07:00:00.000Z'),
data: 21
},
{
key: new Date('2020-05-23T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-05-24T07:00:00.000Z'),
data: 32
},
{
key: new Date('2020-05-25T07:00:00.000Z'),
data: 6
},
{
key: new Date('2020-05-26T07:00:00.000Z'),
data: 44
},
{
key: new Date('2020-05-27T07:00:00.000Z'),
data: 34
},
{
key: new Date('2020-05-28T07:00:00.000Z'),
data: 21
},
{
key: new Date('2020-05-29T07:00:00.000Z'),
data: 13
},
{
key: new Date('2020-05-30T07:00:00.000Z'),
data: 34
},
{
key: new Date('2020-05-31T07:00:00.000Z'),
data: 18
},
{
key: new Date('2020-06-01T07:00:00.000Z'),
data: 1
},
{
key: new Date('2020-06-02T07:00:00.000Z'),
data: 31
},
{
key: new Date('2020-06-03T07:00:00.000Z'),
data: 41
},
{
key: new Date('2020-06-04T07:00:00.000Z'),
data: 47
},
{
key: new Date('2020-06-05T07:00:00.000Z'),
data: 4
},
{
key: new Date('2020-06-06T07:00:00.000Z'),
data: 47
},
{
key: new Date('2020-06-07T07:00:00.000Z'),
data: 28
},
{
key: new Date('2020-06-08T07:00:00.000Z'),
data: 26
},
{
key: new Date('2020-06-09T07:00:00.000Z'),
data: 30
},
{
key: new Date('2020-06-10T07:00:00.000Z'),
data: 10
},
{
key: new Date('2020-06-11T07:00:00.000Z'),
data: 8
},
{
key: new Date('2020-06-12T07:00:00.000Z'),
data: 43
},
{
key: new Date('2020-06-13T07:00:00.000Z'),
data: 21
},
{
key: new Date('2020-06-14T07:00:00.000Z'),
data: 37
},
{
key: new Date('2020-06-15T07:00:00.000Z'),
data: 46
},
{
key: new Date('2020-06-16T07:00:00.000Z'),
data: 38
},
{
key: new Date('2020-06-17T07:00:00.000Z'),
data: 43
},
{
key: new Date('2020-06-18T07:00:00.000Z'),
data: 1
},
{
key: new Date('2020-06-19T07:00:00.000Z'),
data: 1
},
{
key: new Date('2020-06-20T07:00:00.000Z'),
data: 25
},
{
key: new Date('2020-06-21T07:00:00.000Z'),
data: 22
},
{
key: new Date('2020-06-22T07:00:00.000Z'),
data: 11
},
{
key: new Date('2020-06-23T07:00:00.000Z'),
data: 4
},
{
key: new Date('2020-06-24T07:00:00.000Z'),
data: 11
},
{
key: new Date('2020-06-25T07:00:00.000Z'),
data: 36
},
{
key: new Date('2020-06-26T07:00:00.000Z'),
data: 2
},
{
key: new Date('2020-06-27T07:00:00.000Z'),
data: 35
},
{
key: new Date('2020-06-28T07:00:00.000Z'),
data: 42
},
{
key: new Date('2020-06-29T07:00:00.000Z'),
data: 25
},
{
key: new Date('2020-06-30T07:00:00.000Z'),
data: 36
},
{
key: new Date('2020-07-01T07:00:00.000Z'),
data: 28
},
{
key: new Date('2020-07-02T07:00:00.000Z'),
data: 35
},
{
key: new Date('2020-07-03T07:00:00.000Z'),
data: 32
},
{
key: new Date('2020-07-04T07:00:00.000Z'),
data: 6
},
{
key: new Date('2020-07-05T07:00:00.000Z'),
data: 12
},
{
key: new Date('2020-07-06T07:00:00.000Z'),
data: 36
},
{
key: new Date('2020-07-07T07:00:00.000Z'),
data: 43
},
{
key: new Date('2020-07-08T07:00:00.000Z'),
data: 25
},
{
key: new Date('2020-07-09T07:00:00.000Z'),
data: 38
},
{
key: new Date('2020-07-10T07:00:00.000Z'),
data: 47
},
{
key: new Date('2020-07-11T07:00:00.000Z'),
data: 26
},
{
key: new Date('2020-07-12T07:00:00.000Z'),
data: 16
},
{
key: new Date('2020-07-13T07:00:00.000Z'),
data: 49
},
{
key: new Date('2020-07-14T07:00:00.000Z'),
data: 24
},
{
key: new Date('2020-07-15T07:00:00.000Z'),
data: 9
},
{
key: new Date('2020-07-16T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-07-17T07:00:00.000Z'),
data: 14
},
{
key: new Date('2020-07-18T07:00:00.000Z'),
data: 24
},
{
key: new Date('2020-07-19T07:00:00.000Z'),
data: 44
},
{
key: new Date('2020-07-20T07:00:00.000Z'),
data: 27
},
{
key: new Date('2020-07-21T07:00:00.000Z'),
data: 4
},
{
key: new Date('2020-07-22T07:00:00.000Z'),
data: 32
},
{
key: new Date('2020-07-23T07:00:00.000Z'),
data: 5
},
{
key: new Date('2020-07-24T07:00:00.000Z'),
data: 36
},
{
key: new Date('2020-07-25T07:00:00.000Z'),
data: 2
},
{
key: new Date('2020-07-26T07:00:00.000Z'),
data: 10
},
{
key: new Date('2020-07-27T07:00:00.000Z'),
data: 32
},
{
key: new Date('2020-07-28T07:00:00.000Z'),
data: 46
},
{
key: new Date('2020-07-29T07:00:00.000Z'),
data: 43
},
{
key: new Date('2020-07-30T07:00:00.000Z'),
data: 36
},
{
key: new Date('2020-07-31T07:00:00.000Z'),
data: 18
},
{
key: new Date('2020-08-01T07:00:00.000Z'),
data: 38
},
{
key: new Date('2020-08-02T07:00:00.000Z'),
data: 38
},
{
key: new Date('2020-08-03T07:00:00.000Z'),
data: 3
},
{
key: new Date('2020-08-04T07:00:00.000Z'),
data: 49
},
{
key: new Date('2020-08-05T07:00:00.000Z'),
data: 11
},
{
key: new Date('2020-08-06T07:00:00.000Z'),
data: 30
},
{
key: new Date('2020-08-07T07:00:00.000Z'),
data: 45
},
{
key: new Date('2020-08-08T07:00:00.000Z'),
data: 46
},
{
key: new Date('2020-08-09T07:00:00.000Z'),
data: 28
},
{
key: new Date('2020-08-10T07:00:00.000Z'),
data: 6
},
{
key: new Date('2020-08-11T07:00:00.000Z'),
data: 38
},
{
key: new Date('2020-08-12T07:00:00.000Z'),
data: 32
},
{
key: new Date('2020-08-13T07:00:00.000Z'),
data: 28
},
{
key: new Date('2020-08-14T07:00:00.000Z'),
data: 33
},
{
key: new Date('2020-08-15T07:00:00.000Z'),
data: 14
},
{
key: new Date('2020-08-16T07:00:00.000Z'),
data: 27
},
{
key: new Date('2020-08-17T07:00:00.000Z'),
data: 48
},
{
key: new Date('2020-08-18T07:00:00.000Z'),
data: 10
},
{
key: new Date('2020-08-19T07:00:00.000Z'),
data: 12
},
{
key: new Date('2020-08-20T07:00:00.000Z'),
data: 13
},
{
key: new Date('2020-08-21T07:00:00.000Z'),
data: 27
},
{
key: new Date('2020-08-22T07:00:00.000Z'),
data: 2
},
{
key: new Date('2020-08-23T07:00:00.000Z'),
data: 17
},
{
key: new Date('2020-08-24T07:00:00.000Z'),
data: 29
},
{
key: new Date('2020-08-25T07:00:00.000Z'),
data: 44
},
{
key: new Date('2020-08-26T07:00:00.000Z'),
data: 36
},
{
key: new Date('2020-08-27T07:00:00.000Z'),
data: 47
},
{
key: new Date('2020-08-28T07:00:00.000Z'),
data: 38
},
{
key: new Date('2020-08-29T07:00:00.000Z'),
data: 23
},
{
key: new Date('2020-08-30T07:00:00.000Z'),
data: 19
},
{
key: new Date('2020-08-31T07:00:00.000Z'),
data: 0
},
{
key: new Date('2020-09-01T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-09-02T07:00:00.000Z'),
data: 12
},
{
key: new Date('2020-09-03T07:00:00.000Z'),
data: 49
},
{
key: new Date('2020-09-04T07:00:00.000Z'),
data: 39
},
{
key: new Date('2020-09-05T07:00:00.000Z'),
data: 22
},
{
key: new Date('2020-09-06T07:00:00.000Z'),
data: 43
},
{
key: new Date('2020-09-07T07:00:00.000Z'),
data: 14
},
{
key: new Date('2020-09-08T07:00:00.000Z'),
data: 29
},
{
key: new Date('2020-09-09T07:00:00.000Z'),
data: 29
},
{
key: new Date('2020-09-10T07:00:00.000Z'),
data: 16
},
{
key: new Date('2020-09-11T07:00:00.000Z'),
data: 5
},
{
key: new Date('2020-09-12T07:00:00.000Z'),
data: 22
},
{
key: new Date('2020-09-13T07:00:00.000Z'),
data: 10
},
{
key: new Date('2020-09-14T07:00:00.000Z'),
data: 14
},
{
key: new Date('2020-09-15T07:00:00.000Z'),
data: 27
},
{
key: new Date('2020-09-16T07:00:00.000Z'),
data: 41
},
{
key: new Date('2020-09-17T07:00:00.000Z'),
data: 7
},
{
key: new Date('2020-09-18T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-09-19T07:00:00.000Z'),
data: 25
},
{
key: new Date('2020-09-20T07:00:00.000Z'),
data: 22
},
{
key: new Date('2020-09-21T07:00:00.000Z'),
data: 9
},
{
key: new Date('2020-09-22T07:00:00.000Z'),
data: 9
},
{
key: new Date('2020-09-23T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-09-24T07:00:00.000Z'),
data: 46
},
{
key: new Date('2020-09-25T07:00:00.000Z'),
data: 27
},
{
key: new Date('2020-09-26T07:00:00.000Z'),
data: 37
},
{
key: new Date('2020-09-27T07:00:00.000Z'),
data: 4
},
{
key: new Date('2020-09-28T07:00:00.000Z'),
data: 44
},
{
key: new Date('2020-09-29T07:00:00.000Z'),
data: 7
},
{
key: new Date('2020-09-30T07:00:00.000Z'),
data: 19
},
{
key: new Date('2020-10-01T07:00:00.000Z'),
data: 26
},
{
key: new Date('2020-10-02T07:00:00.000Z'),
data: 1
},
{
key: new Date('2020-10-03T07:00:00.000Z'),
data: 6
},
{
key: new Date('2020-10-04T07:00:00.000Z'),
data: 35
},
{
key: new Date('2020-10-05T07:00:00.000Z'),
data: 9
},
{
key: new Date('2020-10-06T07:00:00.000Z'),
data: 26
},
{
key: new Date('2020-10-07T07:00:00.000Z'),
data: 36
},
{
key: new Date('2020-10-08T07:00:00.000Z'),
data: 13
},
{
key: new Date('2020-10-09T07:00:00.000Z'),
data: 14
},
{
key: new Date('2020-10-10T07:00:00.000Z'),
data: 31
},
{
key: new Date('2020-10-11T07:00:00.000Z'),
data: 17
},
{
key: new Date('2020-10-12T07:00:00.000Z'),
data: 2
},
{
key: new Date('2020-10-13T07:00:00.000Z'),
data: 13
},
{
key: new Date('2020-10-14T07:00:00.000Z'),
data: 24
},
{
key: new Date('2020-10-15T07:00:00.000Z'),
data: 35
},
{
key: new Date('2020-10-16T07:00:00.000Z'),
data: 31
},
{
key: new Date('2020-10-17T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-10-18T07:00:00.000Z'),
data: 33
},
{
key: new Date('2020-10-19T07:00:00.000Z'),
data: 36
},
{
key: new Date('2020-10-20T07:00:00.000Z'),
data: 31
},
{
key: new Date('2020-10-21T07:00:00.000Z'),
data: 43
},
{
key: new Date('2020-10-22T07:00:00.000Z'),
data: 23
},
{
key: new Date('2020-10-23T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-10-24T07:00:00.000Z'),
data: 45
},
{
key: new Date('2020-10-25T07:00:00.000Z'),
data: 4
},
{
key: new Date('2020-10-26T07:00:00.000Z'),
data: 39
},
{
key: new Date('2020-10-27T07:00:00.000Z'),
data: 5
},
{
key: new Date('2020-10-28T07:00:00.000Z'),
data: 42
},
{
key: new Date('2020-10-29T07:00:00.000Z'),
data: 49
},
{
key: new Date('2020-10-30T07:00:00.000Z'),
data: 14
},
{
key: new Date('2020-10-31T07:00:00.000Z'),
data: 47
},
{
key: new Date('2020-11-01T07:00:00.000Z'),
data: 30
},
{
key: new Date('2020-11-02T08:00:00.000Z'),
data: 37
},
{
key: new Date('2020-11-03T08:00:00.000Z'),
data: 34
},
{
key: new Date('2020-11-04T08:00:00.000Z'),
data: 10
},
{
key: new Date('2020-11-05T08:00:00.000Z'),
data: 12
},
{
key: new Date('2020-11-06T08:00:00.000Z'),
data: 5
},
{
key: new Date('2020-11-07T08:00:00.000Z'),
data: 2
},
{
key: new Date('2020-11-08T08:00:00.000Z'),
data: 2
},
{
key: new Date('2020-11-09T08:00:00.000Z'),
data: 26
},
{
key: new Date('2020-11-10T08:00:00.000Z'),
data: 31
},
{
key: new Date('2020-11-11T08:00:00.000Z'),
data: 37
},
{
key: new Date('2020-11-12T08:00:00.000Z'),
data: 11
},
{
key: new Date('2020-11-13T08:00:00.000Z'),
data: 31
},
{
key: new Date('2020-11-14T08:00:00.000Z'),
data: 25
},
{
key: new Date('2020-11-15T08:00:00.000Z'),
data: 2
},
{
key: new Date('2020-11-16T08:00:00.000Z'),
data: 22
},
{
key: new Date('2020-11-17T08:00:00.000Z'),
data: 13
},
{
key: new Date('2020-11-18T08:00:00.000Z'),
data: 44
},
{
key: new Date('2020-11-19T08:00:00.000Z'),
data: 1
},
{
key: new Date('2020-11-20T08:00:00.000Z'),
data: 22
},
{
key: new Date('2020-11-21T08:00:00.000Z'),
data: 14
},
{
key: new Date('2020-11-22T08:00:00.000Z'),
data: 30
},
{
key: new Date('2020-11-23T08:00:00.000Z'),
data: 32
},
{
key: new Date('2020-11-24T08:00:00.000Z'),
data: 8
},
{
key: new Date('2020-11-25T08:00:00.000Z'),
data: 25
},
{
key: new Date('2020-11-26T08:00:00.000Z'),
data: 20
},
{
key: new Date('2020-11-27T08:00:00.000Z'),
data: 11
},
{
key: new Date('2020-11-28T08:00:00.000Z'),
data: 4
},
{
key: new Date('2020-11-29T08:00:00.000Z'),
data: 33
},
{
key: new Date('2020-11-30T08:00:00.000Z'),
data: 23
},
{
key: new Date('2020-12-01T08:00:00.000Z'),
data: 39
},
{
key: new Date('2020-12-02T08:00:00.000Z'),
data: 28
},
{
key: new Date('2020-12-03T08:00:00.000Z'),
data: 35
},
{
key: new Date('2020-12-04T08:00:00.000Z'),
data: 33
},
{
key: new Date('2020-12-05T08:00:00.000Z'),
data: 47
},
{
key: new Date('2020-12-06T08:00:00.000Z'),
data: 40
},
{
key: new Date('2020-12-07T08:00:00.000Z'),
data: 40
},
{
key: new Date('2020-12-08T08:00:00.000Z'),
data: 25
},
{
key: new Date('2020-12-09T08:00:00.000Z'),
data: 21
},
{
key: new Date('2020-12-10T08:00:00.000Z'),
data: 7
},
{
key: new Date('2020-12-11T08:00:00.000Z'),
data: 7
},
{
key: new Date('2020-12-12T08:00:00.000Z'),
data: 21
},
{
key: new Date('2020-12-13T08:00:00.000Z'),
data: 8
},
{
key: new Date('2020-12-14T08:00:00.000Z'),
data: 26
},
{
key: new Date('2020-12-15T08:00:00.000Z'),
data: 21
},
{
key: new Date('2020-12-16T08:00:00.000Z'),
data: 14
},
{
key: new Date('2020-12-17T08:00:00.000Z'),
data: 35
},
{
key: new Date('2020-12-18T08:00:00.000Z'),
data: 3
},
{
key: new Date('2020-12-19T08:00:00.000Z'),
data: 16
},
{
key: new Date('2020-12-20T08:00:00.000Z'),
data: 45
},
{
key: new Date('2020-12-21T08:00:00.000Z'),
data: 28
},
{
key: new Date('2020-12-22T08:00:00.000Z'),
data: 46
},
{
key: new Date('2020-12-23T08:00:00.000Z'),
data: 18
},
{
key: new Date('2020-12-24T08:00:00.000Z'),
data: 22
},
{
key: new Date('2020-12-25T08:00:00.000Z'),
data: 32
},
{
key: new Date('2020-12-26T08:00:00.000Z'),
data: 31
},
{
key: new Date('2020-12-27T08:00:00.000Z'),
data: 31
},
{
key: new Date('2020-12-28T08:00:00.000Z'),
data: 45
},
{
key: new Date('2020-12-29T08:00:00.000Z'),
data: 17
},
{
key: new Date('2020-12-30T08:00:00.000Z'),
data: 46
}
];
// export const janHeatMapData = range(31).map(i => ({
// key: yearStart
// .clone()
// .add(i, 'days')
// .toDate(),
// data: randomNumber(0, 50)
// }));
export const janHeatMapData = [
{
key: new Date('2020-01-01T08:00:00.000Z'),
data: 3
},
{
key: new Date('2020-01-02T08:00:00.000Z'),
data: 36
},
{
key: new Date('2020-01-03T08:00:00.000Z'),
data: 24
},
{
key: new Date('2020-01-04T08:00:00.000Z'),
data: 47
},
{
key: new Date('2020-01-05T08:00:00.000Z'),
data: 7
},
{
key: new Date('2020-01-06T08:00:00.000Z'),
data: 31
},
{
key: new Date('2020-01-07T08:00:00.000Z'),
data: 29
},
{
key: new Date('2020-01-08T08:00:00.000Z'),
data: 33
},
{
key: new Date('2020-01-09T08:00:00.000Z'),
data: 23
},
{
key: new Date('2020-01-10T08:00:00.000Z'),
data: 32
},
{
key: new Date('2020-01-11T08:00:00.000Z'),
data: 4
},
{
key: new Date('2020-01-12T08:00:00.000Z'),
data: 29
},
{
key: new Date('2020-01-13T08:00:00.000Z'),
data: 20
},
{
key: new Date('2020-01-14T08:00:00.000Z'),
data: 2
},
{
key: new Date('2020-01-15T08:00:00.000Z'),
data: 16
},
{
key: new Date('2020-01-16T08:00:00.000Z'),
data: 27
},
{
key: new Date('2020-01-17T08:00:00.000Z'),
data: 37
},
{
key: new Date('2020-01-18T08:00:00.000Z'),
data: 38
},
{
key: new Date('2020-01-19T08:00:00.000Z'),
data: 8
},
{
key: new Date('2020-01-20T08:00:00.000Z'),
data: 9
},
{
key: new Date('2020-01-21T08:00:00.000Z'),
data: 23
},
{
key: new Date('2020-01-22T08:00:00.000Z'),
data: 45
},
{
key: new Date('2020-01-23T08:00:00.000Z'),
data: 42
},
{
key: new Date('2020-01-24T08:00:00.000Z'),
data: 24
},
{
key: new Date('2020-01-25T08:00:00.000Z'),
data: 5
},
{
key: new Date('2020-01-26T08:00:00.000Z'),
data: 10
},
{
key: new Date('2020-01-27T08:00:00.000Z'),
data: 25
},
{
key: new Date('2020-01-28T08:00:00.000Z'),
data: 11
},
{
key: new Date('2020-01-29T08:00:00.000Z'),
data: 40
},
{
key: new Date('2020-01-30T08:00:00.000Z'),
data: 38
},
{
key: new Date('2020-01-31T08:00:00.000Z'),
data: 12
}
];
// export const febHeatMapData = range(28).map(i => ({
// key: yearStart
// .clone()
// .add(1, 'month')
// .add(i, 'days')
// .toDate(),
// data: randomNumber(0, 50)
// }));
export const febHeatMapData = [
{ key: new Date('2020-02-01T08:00:00.000Z'), data: 15 },
{ key: new Date('2020-02-02T08:00:00.000Z'), data: 3 },
{ key: new Date('2020-02-03T08:00:00.000Z'), data: 43 },
{ key: new Date('2020-02-04T08:00:00.000Z'), data: 18 },
{ key: new Date('2020-02-05T08:00:00.000Z'), data: 16 },
{ key: new Date('2020-02-06T08:00:00.000Z'), data: 36 },
{ key: new Date('2020-02-07T08:00:00.000Z'), data: 47 },
{ key: new Date('2020-02-08T08:00:00.000Z'), data: 35 },
{ key: new Date('2020-02-09T08:00:00.000Z'), data: 35 },
{ key: new Date('2020-02-10T08:00:00.000Z'), data: 12 },
{ key: new Date('2020-02-11T08:00:00.000Z'), data: 24 },
{ key: new Date('2020-02-12T08:00:00.000Z'), data: 16 },
{ key: new Date('2020-02-13T08:00:00.000Z'), data: 30 },
{ key: new Date('2020-02-14T08:00:00.000Z'), data: 20 },
{ key: new Date('2020-02-15T08:00:00.000Z'), data: 15 },
{ key: new Date('2020-02-16T08:00:00.000Z'), data: 33 },
{ key: new Date('2020-02-17T08:00:00.000Z'), data: 34 },
{ key: new Date('2020-02-18T08:00:00.000Z'), data: 22 },
{ key: new Date('2020-02-19T08:00:00.000Z'), data: 32 },
{ key: new Date('2020-02-20T08:00:00.000Z'), data: 17 },
{ key: new Date('2020-02-21T08:00:00.000Z'), data: 2 },
{ key: new Date('2020-02-22T08:00:00.000Z'), data: 33 },
{ key: new Date('2020-02-23T08:00:00.000Z'), data: 1 },
{ key: new Date('2020-02-24T08:00:00.000Z'), data: 13 },
{ key: new Date('2020-02-25T08:00:00.000Z'), data: 44 },
{ key: new Date('2020-02-26T08:00:00.000Z'), data: 17 },
{ key: new Date('2020-02-27T08:00:00.000Z'), data: 1 },
{ key: new Date('2020-02-28T08:00:00.000Z'), data: 18 }
];
// export const marchHeatMapData = range(31).map(i => ({
// key: yearStart
// .clone()
// .add(2, 'month')
// .add(i, 'days')
// .toDate(),
// data: randomNumber(0, 50)
// }));
export const marchHeatMapData = [
{ key: new Date('2020-03-01T08:00:00.000Z'), data: 14 },
{ key: new Date('2020-03-02T08:00:00.000Z'), data: 32 },
{ key: new Date('2020-03-03T08:00:00.000Z'), data: 31 },
{ key: new Date('2020-03-04T08:00:00.000Z'), data: 1 },
{ key: new Date('2020-03-05T08:00:00.000Z'), data: 38 },
{ key: new Date('2020-03-06T08:00:00.000Z'), data: 32 },
{ key: new Date('2020-03-07T08:00:00.000Z'), data: 23 },
{ key: new Date('2020-03-08T08:00:00.000Z'), data: 41 },
{ key: new Date('2020-03-09T07:00:00.000Z'), data: 7 },
{ key: new Date('2020-03-10T07:00:00.000Z'), data: 40 },
{ key: new Date('2020-03-11T07:00:00.000Z'), data: 40 },
{ key: new Date('2020-03-12T07:00:00.000Z'), data: 24 },
{ key: new Date('2020-03-13T07:00:00.000Z'), data: 2 },
{ key: new Date('2020-03-14T07:00:00.000Z'), data: 36 },
{ key: new Date('2020-03-15T07:00:00.000Z'), data: 20 },
{ key: new Date('2020-03-16T07:00:00.000Z'), data: 1 },
{ key: new Date('2020-03-17T07:00:00.000Z'), data: 8 },
{ key: new Date('2020-03-18T07:00:00.000Z'), data: 0 },
{ key: new Date('2020-03-19T07:00:00.000Z'), data: 1 },
{ key: new Date('2020-03-20T07:00:00.000Z'), data: 31 },
{ key: new Date('2020-03-21T07:00:00.000Z'), data: 35 },
{ key: new Date('2020-03-22T07:00:00.000Z'), data: 6 },
{ key: new Date('2020-03-23T07:00:00.000Z'), data: 9 },
{ key: new Date('2020-03-24T07:00:00.000Z'), data: 26 },
{ key: new Date('2020-03-25T07:00:00.000Z'), data: 42 },
{ key: new Date('2020-03-26T07:00:00.000Z'), data: 31 },
{ key: new Date('2020-03-27T07:00:00.000Z'), data: 26 },
{ key: new Date('2020-03-28T07:00:00.000Z'), data: 23 },
{ key: new Date('2020-03-29T07:00:00.000Z'), data: 49 },
{ key: new Date('2020-03-30T07:00:00.000Z'), data: 30 },
{ key: new Date('2020-03-31T07:00:00.000Z'), data: 47 }
];
// const marchStart = moment()
// .startOf('year')
// .add(2, 'month');
// export const heatmapCalendarOffsetData = range(365).map(i => ({
// key: marchStart
// .clone()
// .add(i, 'days')
// .toDate(),
// data: randomNumber(0, 50)
// }));
export const heatmapCalendarOffsetData = [
{
key: new Date('2020-03-01T08:00:00.000Z'),
data: 37
},
{
key: new Date('2020-03-02T08:00:00.000Z'),
data: 20
},
{
key: new Date('2020-03-03T08:00:00.000Z'),
data: 2
},
{
key: new Date('2020-03-04T08:00:00.000Z'),
data: 27
},
{
key: new Date('2020-03-05T08:00:00.000Z'),
data: 48
},
{
key: new Date('2020-03-06T08:00:00.000Z'),
data: 13
},
{
key: new Date('2020-03-07T08:00:00.000Z'),
data: 43
},
{
key: new Date('2020-03-08T08:00:00.000Z'),
data: 20
},
{
key: new Date('2020-03-09T07:00:00.000Z'),
data: 46
},
{
key: new Date('2020-03-10T07:00:00.000Z'),
data: 4
},
{
key: new Date('2020-03-11T07:00:00.000Z'),
data: 27
},
{
key: new Date('2020-03-12T07:00:00.000Z'),
data: 42
},
{
key: new Date('2020-03-13T07:00:00.000Z'),
data: 37
},
{
key: new Date('2020-03-14T07:00:00.000Z'),
data: 1
},
{
key: new Date('2020-03-15T07:00:00.000Z'),
data: 49
},
{
key: new Date('2020-03-16T07:00:00.000Z'),
data: 28
},
{
key: new Date('2020-03-17T07:00:00.000Z'),
data: 41
},
{
key: new Date('2020-03-18T07:00:00.000Z'),
data: 45
},
{
key: new Date('2020-03-19T07:00:00.000Z'),
data: 28
},
{
key: new Date('2020-03-20T07:00:00.000Z'),
data: 16
},
{
key: new Date('2020-03-21T07:00:00.000Z'),
data: 18
},
{
key: new Date('2020-03-22T07:00:00.000Z'),
data: 25
},
{
key: new Date('2020-03-23T07:00:00.000Z'),
data: 9
},
{
key: new Date('2020-03-24T07:00:00.000Z'),
data: 48
},
{
key: new Date('2020-03-25T07:00:00.000Z'),
data: 9
},
{
key: new Date('2020-03-26T07:00:00.000Z'),
data: 25
},
{
key: new Date('2020-03-27T07:00:00.000Z'),
data: 12
},
{
key: new Date('2020-03-28T07:00:00.000Z'),
data: 50
},
{
key: new Date('2020-03-29T07:00:00.000Z'),
data: 25
},
{
key: new Date('2020-03-30T07:00:00.000Z'),
data: 17
},
{
key: new Date('2020-03-31T07:00:00.000Z'),
data: 39
},
{
key: new Date('2020-04-01T07:00:00.000Z'),
data: 23
},
{
key: new Date('2020-04-02T07:00:00.000Z'),
data: 43
},
{
key: new Date('2020-04-03T07:00:00.000Z'),
data: 21
},
{
key: new Date('2020-04-04T07:00:00.000Z'),
data: 46
},
{
key: new Date('2020-04-05T07:00:00.000Z'),
data: 30
},
{
key: new Date('2020-04-06T07:00:00.000Z'),
data: 41
},
{
key: new Date('2020-04-07T07:00:00.000Z'),
data: 46
},
{
key: new Date('2020-04-08T07:00:00.000Z'),
data: 40
},
{
key: new Date('2020-04-09T07:00:00.000Z'),
data: 23
},
{
key: new Date('2020-04-10T07:00:00.000Z'),
data: 48
},
{
key: new Date('2020-04-11T07:00:00.000Z'),
data: 43
},
{
key: new Date('2020-04-12T07:00:00.000Z'),
data: 21
},
{
key: new Date('2020-04-13T07:00:00.000Z'),
data: 35
},
{
key: new Date('2020-04-14T07:00:00.000Z'),
data: 24
},
{
key: new Date('2020-04-15T07:00:00.000Z'),
data: 35
},
{
key: new Date('2020-04-16T07:00:00.000Z'),
data: 22
},
{
key: new Date('2020-04-17T07:00:00.000Z'),
data: 13
},
{
key: new Date('2020-04-18T07:00:00.000Z'),
data: 14
},
{
key: new Date('2020-04-19T07:00:00.000Z'),
data: 8
},
{
key: new Date('2020-04-20T07:00:00.000Z'),
data: 7
},
{
key: new Date('2020-04-21T07:00:00.000Z'),
data: 39
},
{
key: new Date('2020-04-22T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-04-23T07:00:00.000Z'),
data: 12
},
{
key: new Date('2020-04-24T07:00:00.000Z'),
data: 39
},
{
key: new Date('2020-04-25T07:00:00.000Z'),
data: 25
},
{
key: new Date('2020-04-26T07:00:00.000Z'),
data: 19
},
{
key: new Date('2020-04-27T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-04-28T07:00:00.000Z'),
data: 47
},
{
key: new Date('2020-04-29T07:00:00.000Z'),
data: 28
},
{
key: new Date('2020-04-30T07:00:00.000Z'),
data: 29
},
{
key: new Date('2020-05-01T07:00:00.000Z'),
data: 1
},
{
key: new Date('2020-05-02T07:00:00.000Z'),
data: 29
},
{
key: new Date('2020-05-03T07:00:00.000Z'),
data: 40
},
{
key: new Date('2020-05-04T07:00:00.000Z'),
data: 31
},
{
key: new Date('2020-05-05T07:00:00.000Z'),
data: 21
},
{
key: new Date('2020-05-06T07:00:00.000Z'),
data: 13
},
{
key: new Date('2020-05-07T07:00:00.000Z'),
data: 22
},
{
key: new Date('2020-05-08T07:00:00.000Z'),
data: 16
},
{
key: new Date('2020-05-09T07:00:00.000Z'),
data: 12
},
{
key: new Date('2020-05-10T07:00:00.000Z'),
data: 7
},
{
key: new Date('2020-05-11T07:00:00.000Z'),
data: 37
},
{
key: new Date('2020-05-12T07:00:00.000Z'),
data: 44
},
{
key: new Date('2020-05-13T07:00:00.000Z'),
data: 1
},
{
key: new Date('2020-05-14T07:00:00.000Z'),
data: 31
},
{
key: new Date('2020-05-15T07:00:00.000Z'),
data: 24
},
{
key: new Date('2020-05-16T07:00:00.000Z'),
data: 45
},
{
key: new Date('2020-05-17T07:00:00.000Z'),
data: 5
},
{
key: new Date('2020-05-18T07:00:00.000Z'),
data: 2
},
{
key: new Date('2020-05-19T07:00:00.000Z'),
data: 4
},
{
key: new Date('2020-05-20T07:00:00.000Z'),
data: 16
},
{
key: new Date('2020-05-21T07:00:00.000Z'),
data: 0
},
{
key: new Date('2020-05-22T07:00:00.000Z'),
data: 37
},
{
key: new Date('2020-05-23T07:00:00.000Z'),
data: 46
},
{
key: new Date('2020-05-24T07:00:00.000Z'),
data: 30
},
{
key: new Date('2020-05-25T07:00:00.000Z'),
data: 27
},
{
key: new Date('2020-05-26T07:00:00.000Z'),
data: 25
},
{
key: new Date('2020-05-27T07:00:00.000Z'),
data: 47
},
{
key: new Date('2020-05-28T07:00:00.000Z'),
data: 22
},
{
key: new Date('2020-05-29T07:00:00.000Z'),
data: 29
},
{
key: new Date('2020-05-30T07:00:00.000Z'),
data: 41
},
{
key: new Date('2020-05-31T07:00:00.000Z'),
data: 14
},
{
key: new Date('2020-06-01T07:00:00.000Z'),
data: 23
},
{
key: new Date('2020-06-02T07:00:00.000Z'),
data: 45
},
{
key: new Date('2020-06-03T07:00:00.000Z'),
data: 6
},
{
key: new Date('2020-06-04T07:00:00.000Z'),
data: 4
},
{
key: new Date('2020-06-05T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-06-06T07:00:00.000Z'),
data: 45
},
{
key: new Date('2020-06-07T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-06-08T07:00:00.000Z'),
data: 29
},
{
key: new Date('2020-06-09T07:00:00.000Z'),
data: 24
},
{
key: new Date('2020-06-10T07:00:00.000Z'),
data: 25
},
{
key: new Date('2020-06-11T07:00:00.000Z'),
data: 9
},
{
key: new Date('2020-06-12T07:00:00.000Z'),
data: 49
},
{
key: new Date('2020-06-13T07:00:00.000Z'),
data: 37
},
{
key: new Date('2020-06-14T07:00:00.000Z'),
data: 22
},
{
key: new Date('2020-06-15T07:00:00.000Z'),
data: 6
},
{
key: new Date('2020-06-16T07:00:00.000Z'),
data: 38
},
{
key: new Date('2020-06-17T07:00:00.000Z'),
data: 28
},
{
key: new Date('2020-06-18T07:00:00.000Z'),
data: 22
},
{
key: new Date('2020-06-19T07:00:00.000Z'),
data: 6
},
{
key: new Date('2020-06-20T07:00:00.000Z'),
data: 8
},
{
key: new Date('2020-06-21T07:00:00.000Z'),
data: 47
},
{
key: new Date('2020-06-22T07:00:00.000Z'),
data: 12
},
{
key: new Date('2020-06-23T07:00:00.000Z'),
data: 26
},
{
key: new Date('2020-06-24T07:00:00.000Z'),
data: 21
},
{
key: new Date('2020-06-25T07:00:00.000Z'),
data: 22
},
{
key: new Date('2020-06-26T07:00:00.000Z'),
data: 19
},
{
key: new Date('2020-06-27T07:00:00.000Z'),
data: 19
},
{
key: new Date('2020-06-28T07:00:00.000Z'),
data: 38
},
{
key: new Date('2020-06-29T07:00:00.000Z'),
data: 23
},
{
key: new Date('2020-06-30T07:00:00.000Z'),
data: 36
},
{
key: new Date('2020-07-01T07:00:00.000Z'),
data: 21
},
{
key: new Date('2020-07-02T07:00:00.000Z'),
data: 44
},
{
key: new Date('2020-07-03T07:00:00.000Z'),
data: 19
},
{
key: new Date('2020-07-04T07:00:00.000Z'),
data: 46
},
{
key: new Date('2020-07-05T07:00:00.000Z'),
data: 10
},
{
key: new Date('2020-07-06T07:00:00.000Z'),
data: 33
},
{
key: new Date('2020-07-07T07:00:00.000Z'),
data: 41
},
{
key: new Date('2020-07-08T07:00:00.000Z'),
data: 11
},
{
key: new Date('2020-07-09T07:00:00.000Z'),
data: 34
},
{
key: new Date('2020-07-10T07:00:00.000Z'),
data: 42
},
{
key: new Date('2020-07-11T07:00:00.000Z'),
data: 19
},
{
key: new Date('2020-07-12T07:00:00.000Z'),
data: 49
},
{
key: new Date('2020-07-13T07:00:00.000Z'),
data: 11
},
{
key: new Date('2020-07-14T07:00:00.000Z'),
data: 14
},
{
key: new Date('2020-07-15T07:00:00.000Z'),
data: 47
},
{
key: new Date('2020-07-16T07:00:00.000Z'),
data: 36
},
{
key: new Date('2020-07-17T07:00:00.000Z'),
data: 1
},
{
key: new Date('2020-07-18T07:00:00.000Z'),
data: 28
},
{
key: new Date('2020-07-19T07:00:00.000Z'),
data: 35
},
{
key: new Date('2020-07-20T07:00:00.000Z'),
data: 14
},
{
key: new Date('2020-07-21T07:00:00.000Z'),
data: 38
},
{
key: new Date('2020-07-22T07:00:00.000Z'),
data: 29
},
{
key: new Date('2020-07-23T07:00:00.000Z'),
data: 38
},
{
key: new Date('2020-07-24T07:00:00.000Z'),
data: 45
},
{
key: new Date('2020-07-25T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-07-26T07:00:00.000Z'),
data: 50
},
{
key: new Date('2020-07-27T07:00:00.000Z'),
data: 11
},
{
key: new Date('2020-07-28T07:00:00.000Z'),
data: 49
},
{
key: new Date('2020-07-29T07:00:00.000Z'),
data: 37
},
{
key: new Date('2020-07-30T07:00:00.000Z'),
data: 13
},
{
key: new Date('2020-07-31T07:00:00.000Z'),
data: 2
},
{
key: new Date('2020-08-01T07:00:00.000Z'),
data: 35
},
{
key: new Date('2020-08-02T07:00:00.000Z'),
data: 6
},
{
key: new Date('2020-08-03T07:00:00.000Z'),
data: 3
},
{
key: new Date('2020-08-04T07:00:00.000Z'),
data: 43
},
{
key: new Date('2020-08-05T07:00:00.000Z'),
data: 3
},
{
key: new Date('2020-08-06T07:00:00.000Z'),
data: 48
},
{
key: new Date('2020-08-07T07:00:00.000Z'),
data: 3
},
{
key: new Date('2020-08-08T07:00:00.000Z'),
data: 38
},
{
key: new Date('2020-08-09T07:00:00.000Z'),
data: 22
},
{
key: new Date('2020-08-10T07:00:00.000Z'),
data: 5
},
{
key: new Date('2020-08-11T07:00:00.000Z'),
data: 32
},
{
key: new Date('2020-08-12T07:00:00.000Z'),
data: 47
},
{
key: new Date('2020-08-13T07:00:00.000Z'),
data: 2
},
{
key: new Date('2020-08-14T07:00:00.000Z'),
data: 17
},
{
key: new Date('2020-08-15T07:00:00.000Z'),
data: 43
},
{
key: new Date('2020-08-16T07:00:00.000Z'),
data: 41
},
{
key: new Date('2020-08-17T07:00:00.000Z'),
data: 9
},
{
key: new Date('2020-08-18T07:00:00.000Z'),
data: 0
},
{
key: new Date('2020-08-19T07:00:00.000Z'),
data: 30
},
{
key: new Date('2020-08-20T07:00:00.000Z'),
data: 45
},
{
key: new Date('2020-08-21T07:00:00.000Z'),
data: 9
},
{
key: new Date('2020-08-22T07:00:00.000Z'),
data: 31
},
{
key: new Date('2020-08-23T07:00:00.000Z'),
data: 26
},
{
key: new Date('2020-08-24T07:00:00.000Z'),
data: 7
},
{
key: new Date('2020-08-25T07:00:00.000Z'),
data: 42
},
{
key: new Date('2020-08-26T07:00:00.000Z'),
data: 33
},
{
key: new Date('2020-08-27T07:00:00.000Z'),
data: 36
},
{
key: new Date('2020-08-28T07:00:00.000Z'),
data: 49
},
{
key: new Date('2020-08-29T07:00:00.000Z'),
data: 47
},
{
key: new Date('2020-08-30T07:00:00.000Z'),
data: 45
},
{
key: new Date('2020-08-31T07:00:00.000Z'),
data: 21
},
{
key: new Date('2020-09-01T07:00:00.000Z'),
data: 19
},
{
key: new Date('2020-09-02T07:00:00.000Z'),
data: 3
},
{
key: new Date('2020-09-03T07:00:00.000Z'),
data: 11
},
{
key: new Date('2020-09-04T07:00:00.000Z'),
data: 13
},
{
key: new Date('2020-09-05T07:00:00.000Z'),
data: 17
},
{
key: new Date('2020-09-06T07:00:00.000Z'),
data: 32
},
{
key: new Date('2020-09-07T07:00:00.000Z'),
data: 19
},
{
key: new Date('2020-09-08T07:00:00.000Z'),
data: 1
},
{
key: new Date('2020-09-09T07:00:00.000Z'),
data: 38
},
{
key: new Date('2020-09-10T07:00:00.000Z'),
data: 46
},
{
key: new Date('2020-09-11T07:00:00.000Z'),
data: 48
},
{
key: new Date('2020-09-12T07:00:00.000Z'),
data: 8
},
{
key: new Date('2020-09-13T07:00:00.000Z'),
data: 32
},
{
key: new Date('2020-09-14T07:00:00.000Z'),
data: 48
},
{
key: new Date('2020-09-15T07:00:00.000Z'),
data: 10
},
{
key: new Date('2020-09-16T07:00:00.000Z'),
data: 35
},
{
key: new Date('2020-09-17T07:00:00.000Z'),
data: 27
},
{
key: new Date('2020-09-18T07:00:00.000Z'),
data: 7
},
{
key: new Date('2020-09-19T07:00:00.000Z'),
data: 27
},
{
key: new Date('2020-09-20T07:00:00.000Z'),
data: 26
},
{
key: new Date('2020-09-21T07:00:00.000Z'),
data: 18
},
{
key: new Date('2020-09-22T07:00:00.000Z'),
data: 14
},
{
key: new Date('2020-09-23T07:00:00.000Z'),
data: 4
},
{
key: new Date('2020-09-24T07:00:00.000Z'),
data: 17
},
{
key: new Date('2020-09-25T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-09-26T07:00:00.000Z'),
data: 12
},
{
key: new Date('2020-09-27T07:00:00.000Z'),
data: 36
},
{
key: new Date('2020-09-28T07:00:00.000Z'),
data: 36
},
{
key: new Date('2020-09-29T07:00:00.000Z'),
data: 45
},
{
key: new Date('2020-09-30T07:00:00.000Z'),
data: 25
},
{
key: new Date('2020-10-01T07:00:00.000Z'),
data: 44
},
{
key: new Date('2020-10-02T07:00:00.000Z'),
data: 1
},
{
key: new Date('2020-10-03T07:00:00.000Z'),
data: 48
},
{
key: new Date('2020-10-04T07:00:00.000Z'),
data: 16
},
{
key: new Date('2020-10-05T07:00:00.000Z'),
data: 41
},
{
key: new Date('2020-10-06T07:00:00.000Z'),
data: 43
},
{
key: new Date('2020-10-07T07:00:00.000Z'),
data: 2
},
{
key: new Date('2020-10-08T07:00:00.000Z'),
data: 33
},
{
key: new Date('2020-10-09T07:00:00.000Z'),
data: 37
},
{
key: new Date('2020-10-10T07:00:00.000Z'),
data: 8
},
{
key: new Date('2020-10-11T07:00:00.000Z'),
data: 25
},
{
key: new Date('2020-10-12T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-10-13T07:00:00.000Z'),
data: 44
},
{
key: new Date('2020-10-14T07:00:00.000Z'),
data: 26
},
{
key: new Date('2020-10-15T07:00:00.000Z'),
data: 30
},
{
key: new Date('2020-10-16T07:00:00.000Z'),
data: 7
},
{
key: new Date('2020-10-17T07:00:00.000Z'),
data: 15
},
{
key: new Date('2020-10-18T07:00:00.000Z'),
data: 9
},
{
key: new Date('2020-10-19T07:00:00.000Z'),
data: 37
},
{
key: new Date('2020-10-20T07:00:00.000Z'),
data: 13
},
{
key: new Date('2020-10-21T07:00:00.000Z'),
data: 17
},
{
key: new Date('2020-10-22T07:00:00.000Z'),
data: 40
},
{
key: new Date('2020-10-23T07:00:00.000Z'),
data: 38
},
{
key: new Date('2020-10-24T07:00:00.000Z'),
data: 42
},
{
key: new Date('2020-10-25T07:00:00.000Z'),
data: 2
},
{
key: new Date('2020-10-26T07:00:00.000Z'),
data: 26
},
{
key: new Date('2020-10-27T07:00:00.000Z'),
data: 18
},
{
key: new Date('2020-10-28T07:00:00.000Z'),
data: 48
},
{
key: new Date('2020-10-29T07:00:00.000Z'),
data: 37
},
{
key: new Date('2020-10-30T07:00:00.000Z'),
data: 43
},
{
key: new Date('2020-10-31T07:00:00.000Z'),
data: 48
},
{
key: new Date('2020-11-01T07:00:00.000Z'),
data: 43
},
{
key: new Date('2020-11-02T08:00:00.000Z'),
data: 20
},
{
key: new Date('2020-11-03T08:00:00.000Z'),
data: 42
},
{
key: new Date('2020-11-04T08:00:00.000Z'),
data: 5
},
{
key: new Date('2020-11-05T08:00:00.000Z'),
data: 42
},
{
key: new Date('2020-11-06T08:00:00.000Z'),
data: 4
},
{
key: new Date('2020-11-07T08:00:00.000Z'),
data: 11
},
{
key: new Date('2020-11-08T08:00:00.000Z'),
data: 46
},
{
key: new Date('2020-11-09T08:00:00.000Z'),
data: 14
},
{
key: new Date('2020-11-10T08:00:00.000Z'),
data: 10
},
{
key: new Date('2020-11-11T08:00:00.000Z'),
data: 1
},
{
key: new Date('2020-11-12T08:00:00.000Z'),
data: 10
},
{
key: new Date('2020-11-13T08:00:00.000Z'),
data: 32
},
{
key: new Date('2020-11-14T08:00:00.000Z'),
data: 45
},
{
key: new Date('2020-11-15T08:00:00.000Z'),
data: 14
},
{
key: new Date('2020-11-16T08:00:00.000Z'),
data: 5
},
{
key: new Date('2020-11-17T08:00:00.000Z'),
data: 36
},
{
key: new Date('2020-11-18T08:00:00.000Z'),
data: 25
},
{
key: new Date('2020-11-19T08:00:00.000Z'),
data: 30
},
{
key: new Date('2020-11-20T08:00:00.000Z'),
data: 24
},
{
key: new Date('2020-11-21T08:00:00.000Z'),
data: 30
},
{
key: new Date('2020-11-22T08:00:00.000Z'),
data: 38
},
{
key: new Date('2020-11-23T08:00:00.000Z'),
data: 7
},
{
key: new Date('2020-11-24T08:00:00.000Z'),
data: 16
},
{
key: new Date('2020-11-25T08:00:00.000Z'),
data: 23
},
{
key: new Date('2020-11-26T08:00:00.000Z'),
data: 1
},
{
key: new Date('2020-11-27T08:00:00.000Z'),
data: 39
},
{
key: new Date('2020-11-28T08:00:00.000Z'),
data: 38
},
{
key: new Date('2020-11-29T08:00:00.000Z'),
data: 8
},
{
key: new Date('2020-11-30T08:00:00.000Z'),
data: 4
},
{
key: new Date('2020-12-01T08:00:00.000Z'),
data: 30
},
{
key: new Date('2020-12-02T08:00:00.000Z'),
data: 20
},
{
key: new Date('2020-12-03T08:00:00.000Z'),
data: 25
},
{
key: new Date('2020-12-04T08:00:00.000Z'),
data: 0
},
{
key: new Date('2020-12-05T08:00:00.000Z'),
data: 24
},
{
key: new Date('2020-12-06T08:00:00.000Z'),
data: 43
},
{
key: new Date('2020-12-07T08:00:00.000Z'),
data: 36
},
{
key: new Date('2020-12-08T08:00:00.000Z'),
data: 23
},
{
key: new Date('2020-12-09T08:00:00.000Z'),
data: 42
},
{
key: new Date('2020-12-10T08:00:00.000Z'),
data: 30
},
{
key: new Date('2020-12-11T08:00:00.000Z'),
data: 6
},
{
key: new Date('2020-12-12T08:00:00.000Z'),
data: 6
},
{
key: new Date('2020-12-13T08:00:00.000Z'),
data: 17
},
{
key: new Date('2020-12-14T08:00:00.000Z'),
data: 40
},
{
key: new Date('2020-12-15T08:00:00.000Z'),
data: 31
},
{
key: new Date('2020-12-16T08:00:00.000Z'),
data: 29
},
{
key: new Date('2020-12-17T08:00:00.000Z'),
data: 3
},
{
key: new Date('2020-12-18T08:00:00.000Z'),
data: 28
},
{
key: new Date('2020-12-19T08:00:00.000Z'),
data: 16
},
{
key: new Date('2020-12-20T08:00:00.000Z'),
data: 30
},
{
key: new Date('2020-12-21T08:00:00.000Z'),
data: 45
},
{
key: new Date('2020-12-22T08:00:00.000Z'),
data: 3
},
{
key: new Date('2020-12-23T08:00:00.000Z'),
data: 30
},
{
key: new Date('2020-12-24T08:00:00.000Z'),
data: 10
},
{
key: new Date('2020-12-25T08:00:00.000Z'),
data: 10
},
{
key: new Date('2020-12-26T08:00:00.000Z'),
data: 11
},
{
key: new Date('2020-12-27T08:00:00.000Z'),
data: 33
},
{
key: new Date('2020-12-28T08:00:00.000Z'),
data: 37
},
{
key: new Date('2020-12-29T08:00:00.000Z'),
data: 16
},
{
key: new Date('2020-12-30T08:00:00.000Z'),
data: 6
},
{
key: new Date('2020-12-31T08:00:00.000Z'),
data: 43
},
{
key: new Date('2021-01-01T08:00:00.000Z'),
data: 17
},
{
key: new Date('2021-01-02T08:00:00.000Z'),
data: 29
},
{
key: new Date('2021-01-03T08:00:00.000Z'),
data: 21
},
{
key: new Date('2021-01-04T08:00:00.000Z'),
data: 46
},
{
key: new Date('2021-01-05T08:00:00.000Z'),
data: 36
},
{
key: new Date('2021-01-06T08:00:00.000Z'),
data: 8
},
{
key: new Date('2021-01-07T08:00:00.000Z'),
data: 24
},
{
key: new Date('2021-01-08T08:00:00.000Z'),
data: 8
},
{
key: new Date('2021-01-09T08:00:00.000Z'),
data: 32
},
{
key: new Date('2021-01-10T08:00:00.000Z'),
data: 22
},
{
key: new Date('2021-01-11T08:00:00.000Z'),
data: 28
},
{
key: new Date('2021-01-12T08:00:00.000Z'),
data: 31
},
{
key: new Date('2021-01-13T08:00:00.000Z'),
data: 19
},
{
key: new Date('2021-01-14T08:00:00.000Z'),
data: 29
},
{
key: new Date('2021-01-15T08:00:00.000Z'),
data: 45
},
{
key: new Date('2021-01-16T08:00:00.000Z'),
data: 34
},
{
key: new Date('2021-01-17T08:00:00.000Z'),
data: 24
},
{
key: new Date('2021-01-18T08:00:00.000Z'),
data: 11
},
{
key: new Date('2021-01-19T08:00:00.000Z'),
data: 9
},
{
key: new Date('2021-01-20T08:00:00.000Z'),
data: 24
},
{
key: new Date('2021-01-21T08:00:00.000Z'),
data: 28
},
{
key: new Date('2021-01-22T08:00:00.000Z'),
data: 45
},
{
key: new Date('2021-01-23T08:00:00.000Z'),
data: 6
},
{
key: new Date('2021-01-24T08:00:00.000Z'),
data: 25
},
{
key: new Date('2021-01-25T08:00:00.000Z'),
data: 10
},
{
key: new Date('2021-01-26T08:00:00.000Z'),
data: 47
},
{
key: new Date('2021-01-27T08:00:00.000Z'),
data: 46
},
{
key: new Date('2021-01-28T08:00:00.000Z'),
data: 11
},
{
key: new Date('2021-01-29T08:00:00.000Z'),
data: 6
},
{
key: new Date('2021-01-30T08:00:00.000Z'),
data: 13
},
{
key: new Date('2021-01-31T08:00:00.000Z'),
data: 29
},
{
key: new Date('2021-02-01T08:00:00.000Z'),
data: 47
},
{
key: new Date('2021-02-02T08:00:00.000Z'),
data: 14
},
{
key: new Date('2021-02-03T08:00:00.000Z'),
data: 36
},
{
key: new Date('2021-02-04T08:00:00.000Z'),
data: 7
},
{
key: new Date('2021-02-05T08:00:00.000Z'),
data: 19
},
{
key: new Date('2021-02-06T08:00:00.000Z'),
data: 19
},
{
key: new Date('2021-02-07T08:00:00.000Z'),
data: 33
},
{
key: new Date('2021-02-08T08:00:00.000Z'),
data: 3
},
{
key: new Date('2021-02-09T08:00:00.000Z'),
data: 26
},
{
key: new Date('2021-02-10T08:00:00.000Z'),
data: 14
},
{
key: new Date('2021-02-11T08:00:00.000Z'),
data: 40
},
{
key: new Date('2021-02-12T08:00:00.000Z'),
data: 4
},
{
key: new Date('2021-02-13T08:00:00.000Z'),
data: 39
},
{
key: new Date('2021-02-14T08:00:00.000Z'),
data: 28
},
{
key: new Date('2021-02-15T08:00:00.000Z'),
data: 19
},
{
key: new Date('2021-02-16T08:00:00.000Z'),
data: 19
},
{
key: new Date('2021-02-17T08:00:00.000Z'),
data: 9
},
{
key: new Date('2021-02-18T08:00:00.000Z'),
data: 11
},
{
key: new Date('2021-02-19T08:00:00.000Z'),
data: 1
},
{
key: new Date('2021-02-20T08:00:00.000Z'),
data: 39
},
{
key: new Date('2021-02-21T08:00:00.000Z'),
data: 28
},
{
key: new Date('2021-02-22T08:00:00.000Z'),
data: 8
},
{
key: new Date('2021-02-23T08:00:00.000Z'),
data: 27
},
{
key: new Date('2021-02-24T08:00:00.000Z'),
data: 27
},
{
key: new Date('2021-02-25T08:00:00.000Z'),
data: 12
},
{
key: new Date('2021-02-26T08:00:00.000Z'),
data: 33
},
{
key: new Date('2021-02-27T08:00:00.000Z'),
data: 10
},
{
key: new Date('2021-02-28T08:00:00.000Z'),
data: 24
}
]; | the_stack |
import { Injectable } from "@angular/core";
import {
ScopeEnchantmentModel,
AuxliLineModel,
PanelScopeTextEditorModel,
ProfileModel,
OuterSphereHasAuxlModel,
} from "./model";
import { PanelWidgetModel } from "../panel-widget/model";
import { DraggablePort } from "@ng-public/directive/draggable/draggable.interface";
import { BehaviorSubject, Subject } from "rxjs";
@Injectable({
providedIn: "root",
})
export class PanelScopeEnchantmentService {
// 是否开启辅助线计算
public isOpenAltCalc$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(true);
// 订阅鼠标移动偏移量回调
public launchMouseIncrement$: Subject<DraggablePort> = new Subject<DraggablePort>();
// 订阅组件的右键事件
public launchContextmenu$: BehaviorSubject<MouseEvent> = new BehaviorSubject<MouseEvent>(null);
public scopeEnchantmentModel: ScopeEnchantmentModel = new ScopeEnchantmentModel();
// 文字编辑器模式数据模型
public panelScopeTextEditorModel$: BehaviorSubject<PanelScopeTextEditorModel> = new BehaviorSubject(null);
// 存储所有辅助线的数据模型
public auxliLineModel$: BehaviorSubject<AuxliLineModel> = new BehaviorSubject<AuxliLineModel>(new AuxliLineModel());
// 存储粘贴板的组件内容
public clipboardList$: BehaviorSubject<Array<PanelWidgetModel>> = new BehaviorSubject([]);
constructor() {}
/**
* 根据传入的widget参数设置鼠标移入的轮廓绘制
*/
public handleTemporaryProfile(widget: PanelWidgetModel, type: "enter" | "out"): void {
if (type == "enter") {
this.scopeEnchantmentModel.profileTemporary$.next(widget.profileModel);
} else if (type == "out") {
this.scopeEnchantmentModel.resetProfileTemporary$();
}
}
/**
* 只选中某一个组件传入到列表outerSphereInsetWidgetList$列表中
*/
public onlyOuterSphereInsetWidget(widget: PanelWidgetModel): void {
this.scopeEnchantmentModel.resetOuterSphereInsetWidgetList$();
this.scopeEnchantmentModel.outerSphereInsetWidgetList$.next([widget]);
this.handleFromWidgetListToProfileOuterSphere();
}
/**
* 根据传入的outerSphereInsetWidgetList$数组进行处理选中状态
*/
public pushOuterSphereInsetWidget(widgets: Array<PanelWidgetModel>): void {
this.scopeEnchantmentModel.resetOuterSphereInsetWidgetList$();
this.scopeEnchantmentModel.outerSphereInsetWidgetList$.next(widgets);
this.handleFromWidgetListToProfileOuterSphere();
}
/**
* 如果存在outerSphereInsetWidgetList$列表中就去除否则就增加
*/
public toggleOuterSphereInsetWidget(widget: PanelWidgetModel): void {
const outerWidthList = this.scopeEnchantmentModel.outerSphereInsetWidgetList$.value;
const arrUniqueid = this.scopeEnchantmentModel.outerSphereInsetWidgetList$.value.map(e => e.uniqueId);
if (!arrUniqueid.includes(widget.uniqueId)) {
outerWidthList.push(widget);
this.scopeEnchantmentModel.outerSphereInsetWidgetList$.next(outerWidthList);
} else {
const filter = outerWidthList.filter(e => e.uniqueId != widget.uniqueId);
widget.profileModel.isCheck = false;
this.scopeEnchantmentModel.outerSphereInsetWidgetList$.next(filter);
}
this.handleFromWidgetListToProfileOuterSphere();
}
/**
* 处理由outerSphereInsetWidgetList$列表内的组件变化来描绘主轮廓
* isLaunch参数表示是否发送数据源
*/
public handleFromWidgetListToProfileOuterSphere(arg: { isLaunch?: boolean } = { isLaunch: true }): void {
const oriArr = this.scopeEnchantmentModel.outerSphereInsetWidgetList$.value.map(e => {
e.profileModel.isCheck = true;
// 根据当前位置重新设置mousecoord
e.profileModel.setMouseCoord([e.profileModel.left, e.profileModel.top]);
return e.profileModel;
});
if (oriArr.length > 0) {
// 计算出最小的left,最小的top,最大的width和height
const calcResult = this.calcProfileOuterSphereInfo();
// 如果insetWidget数量大于一个则不允许开启旋转,且旋转角度重置
if (oriArr.length == 1) {
calcResult.isRotate = true;
calcResult.rotate = oriArr[0].rotate;
} else {
calcResult.isRotate = false;
}
// 赋值
this.scopeEnchantmentModel.launchProfileOuterSphere(calcResult, arg.isLaunch);
// 同时生成八个方位坐标点,如果被选组件大于一个则不生成
this.scopeEnchantmentModel.handleCreateErightCornerPin();
}
}
/**
* 从被选组件当中计算出主轮廓的大小和位置
*/
public calcProfileOuterSphereInfo(): OuterSphereHasAuxlModel {
const insetWidget = this.scopeEnchantmentModel.outerSphereInsetWidgetList$.value;
let outerSphere = new OuterSphereHasAuxlModel().setData({
left: Infinity,
top: Infinity,
width: -Infinity,
height: -Infinity,
rotate: 0,
});
let maxWidth = null;
let maxHeight = null;
let minWidthEmpty = Infinity;
let minHeightEmpty = Infinity;
insetWidget.forEach(e => {
let offsetCoord = { left: 0, top: 0 };
if (e.profileModel.rotate != 0 && insetWidget.length > 1) {
offsetCoord = this.handleOuterSphereRotateOffsetCoord(e.profileModel);
}
outerSphere.left = Math.min(outerSphere.left, e.profileModel.left + offsetCoord.left);
outerSphere.top = Math.min(outerSphere.top, e.profileModel.top + offsetCoord.top);
maxWidth = Math.max(maxWidth, e.profileModel.left + e.profileModel.width + offsetCoord.left * -1);
maxHeight = Math.max(maxHeight, e.profileModel.top + e.profileModel.height + offsetCoord.top * -1);
if (e.profileModel.left + e.profileModel.width < 0) {
minWidthEmpty = Math.min(minWidthEmpty, Math.abs(e.profileModel.left) - e.profileModel.width);
} else {
minWidthEmpty = 0;
}
if (e.profileModel.top + e.profileModel.height < 0) {
minHeightEmpty = Math.min(minHeightEmpty, Math.abs(e.profileModel.top) - e.profileModel.height);
} else {
minHeightEmpty = 0;
}
});
outerSphere.width = Math.abs(maxWidth - outerSphere.left) - minWidthEmpty;
outerSphere.height = Math.abs(maxHeight - outerSphere.top) - minHeightEmpty;
outerSphere.setMouseCoord([outerSphere.left, outerSphere.top]);
return outerSphere;
}
/**
* 根据角度计算offsetcoord坐标的增量,用于辅助线计算
* type 表示计算并返回左上、右上、左下还是右下的坐标点
*/
public handleOuterSphereRotateOffsetCoord(
arg: ProfileModel,
type: "lt" | "rt" | "lb" | "rb" = "lt"
): { left: number; top: number } | undefined {
const fourCoord = this.conversionRotateToOffsetLeftTop({
width: arg.width,
height: arg.height,
rotate: arg.rotate,
});
if (fourCoord) {
let min = Infinity;
let max = -Infinity;
for (let e in fourCoord) {
min = Math.min(min, fourCoord[e][0]);
max = Math.max(max, fourCoord[e][1]);
}
const typeObj = {
lt: [min, max],
rt: [-min, max],
lb: [min, -max],
rb: [-min, -max],
};
if (typeObj[type]) {
return {
left: Math.round(arg.width / 2 + typeObj[type][0]),
top: Math.round(arg.height / 2 - typeObj[type][1]),
};
}
}
return;
}
/**
* 计算辅助线的显示与否情况
* 分为6种情况
* 辅助线只会显示在主轮廓的4条边以及2条中线
* 遍历时先寻找离四条边最近的4个数值
* 参数target表示除了用于计算最外主轮廓以外还能计算其他的辅助线情况,(例如左侧的组件库里的待创建的组件)
*/
public handleAuxlineCalculate(
target: OuterSphereHasAuxlModel = this.scopeEnchantmentModel.valueProfileOuterSphere
): void {
const outerSphere = target;
const offsetAmount = outerSphere.offsetAmount;
const aux = this.auxliLineModel$.value;
const mouseCoord = outerSphere.mouseCoord;
// 差量达到多少范围内开始对齐
const diffNum: number = 4;
outerSphere.resetAuxl();
if (mouseCoord) {
for (let i: number = 0, l: number = aux.vLineList.length; i < l; i++) {
if (Math.abs(aux.vLineList[i] - mouseCoord[0] + offsetAmount.left * -1) <= diffNum) {
outerSphere.left = aux.vLineList[i] + offsetAmount.left * -1;
outerSphere.lLine = true;
}
if (Math.abs(aux.vLineList[i] - (mouseCoord[0] + outerSphere.width) + offsetAmount.left) <= diffNum) {
outerSphere.left = aux.vLineList[i] - outerSphere.width + offsetAmount.left;
outerSphere.rLine = true;
}
if (outerSphere.lLine == true && outerSphere.rLine == true) break;
}
for (let i: number = 0, l: number = aux.hLineList.length; i < l; i++) {
if (Math.abs(aux.hLineList[i] - mouseCoord[1] + offsetAmount.top * -1) <= diffNum) {
outerSphere.top = aux.hLineList[i] + offsetAmount.top * -1;
outerSphere.tLine = true;
}
if (Math.abs(aux.hLineList[i] - (mouseCoord[1] + outerSphere.height) + offsetAmount.top) <= diffNum) {
outerSphere.top = aux.hLineList[i] - outerSphere.height + offsetAmount.top;
outerSphere.bLine = true;
}
if (outerSphere.tLine == true && outerSphere.bLine == true) break;
}
for (let i: number = 0, l: number = aux.hcLineList.length; i < l; i++) {
if (Math.abs(aux.hcLineList[i] - (mouseCoord[1] + outerSphere.height / 2)) <= diffNum) {
outerSphere.top = aux.hcLineList[i] - outerSphere.height / 2;
outerSphere.hcLine = true;
break;
}
}
for (let i: number = 0, l: number = aux.vcLineList.length; i < l; i++) {
if (Math.abs(aux.vcLineList[i] - (mouseCoord[0] + outerSphere.width / 2)) <= diffNum) {
outerSphere.left = aux.vcLineList[i] - outerSphere.width / 2;
outerSphere.vcLine = true;
break;
}
}
}
}
/**
* 根据传入的角度和转化为横向的偏移量和纵向的偏移量,主要是用来计算旋转到一定角度之后辅助线的计算基线位置偏移
* 以组件的中心点为坐标圆点,返回四个角的坐标,分别是左上角、右上角、左下角、右下角
* 转化角公式为
* x = x * Math.cos(r) + y * Math.sin(r)
* y = y * Math.cos(r) - x * Math.sin(r)
*/
public conversionRotateToOffsetLeftTop(arg: {
width: number;
height: number;
rotate: number;
}): {
lt: number[];
rt: number[];
lb: number[];
rb: number[];
} {
// 转化角度使其成0~360的范围
arg.rotate = this.conversionRotateOneCircle(arg.rotate);
let result = {
lt: [(arg.width / 2) * -1, arg.height / 2],
rt: [arg.width / 2, arg.height / 2],
lb: [(arg.width / 2) * -1, (arg.height / 2) * -1],
rb: [arg.width / 2, (arg.height / 2) * -1],
};
let convRotate = this.conversionRotateToMathDegree(arg.rotate);
let calcX = (x, y) => <any>(x * Math.cos(convRotate) + y * Math.sin(convRotate)) * 1;
let calcY = (x, y) => <any>(y * Math.cos(convRotate) - x * Math.sin(convRotate)) * 1;
result.lt = [calcX(result.lt[0], result.lt[1]), calcY(result.lt[0], result.lt[1])];
result.rt = [calcX(result.rt[0], result.rt[1]), calcY(result.rt[0], result.rt[1])];
result.lb = [result.rt[0] * -1, result.rt[1] * -1];
result.rb = [result.lt[0] * -1, result.lt[1] * -1];
return result;
}
/**
* 根据传入的坐标转化为度数,度数范围在0~360
*/
public conversionTwoCoordToRotate(coord: [number, number]): number {
if (!Array.isArray(coord) || coord.length != 2) return 0;
const map: Map<boolean, number> = new Map();
map.set(coord[0] >= 0 && coord[1] > 0, this.conversionRotateFromRadian(coord[0] / coord[1]));
map.set(coord[0] > 0 && coord[1] <= 0, this.conversionRotateFromRadian((coord[1] / coord[0]) * -1) + 90);
map.set(coord[0] <= 0 && coord[1] < 0, this.conversionRotateFromRadian(coord[0] / coord[1]) + 180);
map.set(coord[0] < 0 && coord[1] >= 0, this.conversionRotateFromRadian((coord[1] / coord[0]) * -1) + 270);
return ~~map.get(true);
}
/**
* 根据传入的角度转化为0~360度的范围
*/
public conversionRotateOneCircle(rotate: number): number {
return rotate <= 0
? rotate + Math.ceil(Math.abs(rotate / 360)) * 360
: rotate - Math.floor(Math.abs(rotate / 360)) * 360;
}
/**
* 根据角度计算出在哪个象限里
*/
public conversionRotateToQuadrant(rotate: number): number {
rotate = this.conversionRotateOneCircle(rotate);
const map: Map<boolean, 1 | 2 | 3 | 4> = new Map();
map.set(rotate >= 0 && rotate < 90, 1);
map.set(rotate >= 270 && rotate < 360, 2);
map.set(rotate >= 180 && rotate < 270, 3);
map.set(rotate >= 90 && rotate < 180, 4);
return ~~map.get(true);
}
/**
* 根据坐标和角度来计算该坐标旋转到该角度之后的差值增量
*/
public conversionRotateNewCoordinates(
coord: [number, number],
rotate: number
): { left: number; top: number } | undefined {
const quardPosition = { 1: "rt", 2: "lt", 3: "lb", 4: "rb" };
const offsetCoord = this.conversionRotateToOffsetLeftTop({
width: Math.abs(coord[0] * 2),
height: Math.abs(coord[1] * 2),
rotate: rotate,
});
const offsetCoordNumber = offsetCoord[quardPosition[this.conversionCoordinatesToQuadrant(coord)]];
if (offsetCoordNumber) {
return {
left: offsetCoordNumber[0] - coord[0],
top: coord[1] - offsetCoordNumber[1],
};
}
return;
}
// rotate角度转化为数学里要用到的角度
public conversionRotateToMathDegree(rotate: number): number {
return (rotate * Math.PI) / 180;
}
// 转弧度为度数
public conversionRotateFromRadian(x: number): number {
return Math.floor((Math.atan(x) * 180) / Math.PI);
}
// 根据坐标计算出在哪个象限里
public conversionCoordinatesToQuadrant(coord: [number, number]): number {
return this.conversionRotateToQuadrant(this.conversionTwoCoordToRotate(coord));
}
// 根据传入的数值和角度计算对应的sin值
public calcNumSin(num: number, rotate: number): number {
return Math.sin(this.conversionRotateToMathDegree(rotate)) * num;
}
// 根据传入的数值和角度计算对应的cos值
public calcNumCos(num: number, rotate: number): number {
return Math.cos(this.conversionRotateToMathDegree(rotate)) * num;
}
} | the_stack |
import { MgError } from "../error";
import { ActiveSelectedFeature, getExternalBaseLayers } from "../common";
import { RuleInfo, FeatureStyleInfo, ScaleRangeInfo, FeatureSourceInfo, MapLayer, MapGroup, CoordinateSystemType, EnvCoordinate, Envelope, RuntimeMap } from '../contracts/runtime-map';
import { FeatureSetClass, FeatureSetLayer, FeatureSet, SelectionImage, FeatureProperty, SelectedFeature, LayerPropertyMetadata, LayerMetadata, SelectedLayer, SelectedFeatureSet, QueryMapFeaturesResponse } from '../contracts/query';
import { WebLayoutMap, WebLayoutControl, WebLayoutInfoPane, MapView, TaskButton, WebLayoutTaskBar, UIItem, WebLayoutTaskPane, CommandUIItem, FlyoutUIItem, ResultColumnSet, ResultColumn, LayerSet, ParameterPair, CommandDef, BasicCommandDef, InvokeScriptCommandDef, InvokeURLCommandDef, SearchCommandDef, WebLayoutCommandSet, WebLayout, WebLayoutToolbar, WebLayoutContextMenu, WebLayoutStatusBar, WebLayoutZoomControl } from '../contracts/weblayout';
import { MapSetGroup, MapInitialView, MapConfiguration, MapSet, ContainerItem, FlyoutItem, WidgetItem, ContainerDefinition, Widget, UIWidget, MapWidget, WidgetSet, ApplicationDefinition } from '../contracts/fusion';
import { MDF_INFINITY } from '../../constants';
import { MapDefinition, MapDefinitionLayerGroup, MapDefinitionLayer as MdfLayer, TileSetSource } from "../contracts/map-definition";
import { BaseMapLayer, BaseMapLayerGroup, TileSetDefinition, TileStoreParameters } from "../contracts/tile-set-definition";
import { SiteVersionResponse } from '../contracts/common';
type ElementType = "string" | "boolean" | "int" | "float";
function buildPropertyGetter<T>() {
return (el: any, name: keyof T, type: ElementType = "string") => {
return tryGetAsProperty<T>(el, name, type);
}
}
function tryGetAsProperty<T>(el: any, name: keyof T, type: ElementType = "string"): any {
if (!el[name]) {
return null;
} else if (el[name].length === 1) {
const val: string = el[name][0];
switch (type) {
case "int":
return parseInt(val, 10);
case "float":
return parseFloat(val);
case "boolean":
return val.toLowerCase() === "true";
default:
return val;
}
}
}
function deArrayifyRules(rules: any[]): RuleInfo[] {
const getter = buildPropertyGetter<RuleInfo>();
return rules.map(r => {
const rule: RuleInfo = {
LegendLabel: getter(r, "LegendLabel"),
Filter: getter(r, "Filter"),
Icon: getter(r, "Icon")
};
return rule;
});
}
function deArrayifyFeatureStyles(fts: any[]): FeatureStyleInfo[] {
if (!fts) {
return [];
}
const getter = buildPropertyGetter<FeatureStyleInfo>();
return fts.map(ft => {
const featureStyle: FeatureStyleInfo = {
Type: getter(ft, "Type", "int"),
Rule: deArrayifyRules(ft.Rule)
};
return featureStyle;
});
}
function deArrayifyScaleRanges(scales: any[]): ScaleRangeInfo[] {
if (!scales) { //Happens with raster layers (this is probably a bug in CREATERUNTIMEMAP)
const defaultRange: ScaleRangeInfo = {
MinScale: 0,
MaxScale: MDF_INFINITY,
FeatureStyle: []
};
return [defaultRange];
}
const getter = buildPropertyGetter<ScaleRangeInfo>();
return scales.map(sc => {
const scale: ScaleRangeInfo = {
MinScale: getter(sc, "MinScale", "float"),
MaxScale: getter(sc, "MaxScale", "float"),
FeatureStyle: deArrayifyFeatureStyles(sc.FeatureStyle)
};
return scale;
});
}
function deArrayifyFeatureSourceInfo(fs: any[]): FeatureSourceInfo | undefined {
if (!fs || fs.length !== 1) {
return undefined;
}
const getter = buildPropertyGetter<FeatureSourceInfo>();
return {
ResourceId: getter(fs[0], "ResourceId"),
ClassName: getter(fs[0], "ClassName"),
Geometry: getter(fs[0], "Geometry")
};
}
function deArrayifyLayers(layers: any[]): MapLayer[] {
if (!layers)
return layers;
const getter = buildPropertyGetter<MapLayer>();
return layers.map(lyr => {
const layer: MapLayer = {
Type: getter(lyr, "Type", "int"),
Selectable: getter(lyr, "Selectable", "boolean"),
LayerDefinition: getter(lyr, "LayerDefinition"),
Name: getter(lyr, "Name"),
LegendLabel: getter(lyr, "LegendLabel"),
ObjectId: getter(lyr, "ObjectId"),
ParentId: getter(lyr, "ParentId"),
DisplayInLegend: getter(lyr, "DisplayInLegend", "boolean"),
ExpandInLegend: getter(lyr, "ExpandInLegend", "boolean"),
Visible: getter(lyr, "Visible", "boolean"),
ActuallyVisible: getter(lyr, "ActuallyVisible", "boolean"),
FeatureSource: deArrayifyFeatureSourceInfo(lyr.FeatureSource),
ScaleRange: deArrayifyScaleRanges(lyr.ScaleRange)
};
//This is either a raster or drawing layer, in this case disregard the
//selectability flag (and set it to false). This is to prevent false positive
//errors trying to do tooltip/selections against raster/drawing layers
if (!lyr.ScaleRange) {
layer.Selectable = false;
}
return layer;
});
}
function deArrayifyGroups(groups: any[]): MapGroup[] | undefined {
if (!groups)
return undefined;
const getter = buildPropertyGetter<MapGroup>();
return groups.map(grp => {
const group: MapGroup = {
Type: getter(grp, "Type", "int"),
Name: getter(grp, "Name"),
LegendLabel: getter(grp, "LegendLabel"),
ObjectId: getter(grp, "ObjectId"),
ParentId: getter(grp, "ParentId"),
DisplayInLegend: getter(grp, "DisplayInLegend", "boolean"),
ExpandInLegend: getter(grp, "ExpandInLegend", "boolean"),
Visible: getter(grp, "Visible", "boolean"),
ActuallyVisible: getter(grp, "ActuallyVisible", "boolean")
};
return group;
});
}
function deArrayifyCoordinateSystem(cs: any[]): CoordinateSystemType {
if (!cs || cs.length !== 1) {
throw new MgError("Malformed input. Expected CoordinateSystem element");
}
const getter = buildPropertyGetter<CoordinateSystemType>();
const res: CoordinateSystemType = {
Wkt: getter(cs[0], "Wkt"),
MentorCode: getter(cs[0], "MentorCode"),
EpsgCode: getter(cs[0], "EpsgCode"),
MetersPerUnit: getter(cs[0], "MetersPerUnit", "float")
};
return res;
}
function deArrayifyCoordinate(coord: any[]): EnvCoordinate {
if (!coord || coord.length !== 1) {
throw new MgError("Malformed input. Expected coordinate array");
}
const getter = buildPropertyGetter<EnvCoordinate>();
return {
X: getter(coord[0], "X", "float"),
Y: getter(coord[0], "Y", "float")
};
}
function deArrayifyExtents(extents: any[]): Envelope {
if (!extents || extents.length !== 1) {
throw new MgError("Malformed input. Expected extent element");
}
const env: Envelope = {
LowerLeftCoordinate: deArrayifyCoordinate(extents[0].LowerLeftCoordinate),
UpperRightCoordinate: deArrayifyCoordinate(extents[0].UpperRightCoordinate)
};
return env;
}
function deArrayifyFiniteDisplayScales(fds: any[]): number[] | undefined {
if (!fds)
return undefined;
return fds.map(parseFloat);
}
function deArrayifyRuntimeMap(json: any): RuntimeMap {
const root = json;
const getter = buildPropertyGetter<RuntimeMap>();
const rtMap: RuntimeMap = {
SessionId: getter(root, "SessionId"),
SiteVersion: getter(root, "SiteVersion"),
Name: getter(root, "Name"),
MapDefinition: getter(root, "MapDefinition"),
TileSetDefinition: getter(root, "TileSetDefinition"),
TileWidth: getter(root, "TileWidth", "int"),
TileHeight: getter(root, "TileHeight", "int"),
BackgroundColor: getter(root, "BackgroundColor"),
DisplayDpi: getter(root, "DisplayDpi", "int"),
IconMimeType: getter(root, "IconMimeType"),
CoordinateSystem: deArrayifyCoordinateSystem(root.CoordinateSystem),
Extents: deArrayifyExtents(root.Extents),
Group: deArrayifyGroups(root.Group),
Layer: deArrayifyLayers(root.Layer),
FiniteDisplayScale: deArrayifyFiniteDisplayScales(root.FiniteDisplayScale)
};
return rtMap;
}
function deArrayifyFeatureSetClass(json: any): FeatureSetClass {
const root = json;
const getter = buildPropertyGetter<FeatureSetClass>();
if (root.length != 1) {
throw new MgError("Malformed input. Expected Class element");
}
const cls = {
"@id": getter(root[0], "@id"),
ID: root[0].ID
};
return cls;
}
function deArrayifyFeatureSetLayers(json: any[]): FeatureSetLayer[] {
const getter = buildPropertyGetter<FeatureSetLayer>();
return (json || []).map(root => {
const layer = {
"@id": getter(root, "@id"),
"@name": getter(root, "@name"),
Class: deArrayifyFeatureSetClass(root.Class)
};
return layer;
});
}
function deArrayifyFeatureSet(json: any): FeatureSet | undefined {
const root = json;
if (root == null || root.length != 1) {
return undefined;
}
const fs = {
Layer: deArrayifyFeatureSetLayers(root[0].Layer)
};
return fs;
}
function deArrayifyInlineSelectionImage(json: any): SelectionImage | undefined {
const root = json;
if (root == null || root.length != 1) {
return undefined;
}
const getter = buildPropertyGetter<SelectionImage>();
const img = {
MimeType: getter(root[0], "MimeType"),
Content: getter(root[0], "Content")
};
return img;
}
function deArrayifyFeatureProperties(json: any[]): FeatureProperty[] {
const getter = buildPropertyGetter<FeatureProperty>();
return (json || []).map(root => {
const prop = {
Name: getter(root, "Name"),
Value: getter(root, "Value")
};
return prop;
});
}
function deArrayifyFeatures(json: any[]): SelectedFeature[] {
const getter = buildPropertyGetter<SelectedFeature>();
return (json || []).map(root => {
const feat = {
Bounds: getter(root, "Bounds"),
Property: deArrayifyFeatureProperties(root.Property),
SelectionKey: getter(root, "SelectionKey")
};
return feat;
});
}
function deArrayifyLayerMetadataProperties(json: any[]): LayerPropertyMetadata[] {
const getter = buildPropertyGetter<LayerPropertyMetadata>();
return (json || []).map(root => {
const prop = {
DisplayName: getter(root, "DisplayName"),
Name: getter(root, "Name"),
Type: getter(root, "Type", "int")
};
return prop;
});
}
function deArrayifyLayerMetadata(json: any): LayerMetadata | undefined {
const root = json;
//NOTE: root could be null if the layer selected has no properties beyond id/geom
if (root == null || root.length != 1) {
return undefined;
}
const meta = {
Property: deArrayifyLayerMetadataProperties(root[0].Property)
};
return meta;
}
function deArrayifySelectedLayer(json: any[]): SelectedLayer[] {
const getter = buildPropertyGetter<SelectedLayer>();
return (json || []).map(root => {
const layer = {
"@id": getter(root, "@id"),
"@name": getter(root, "@name"),
Feature: deArrayifyFeatures(root.Feature),
LayerMetadata: deArrayifyLayerMetadata(root.LayerMetadata)
};
return layer;
});
}
function deArrayifySelectedFeatures(json: any): SelectedFeatureSet | undefined {
const root = json;
if (root == null || root.length != 1) {
return undefined;
}
const sf = {
SelectedLayer: deArrayifySelectedLayer(root[0].SelectedLayer)
};
return sf;
}
function deArrayifyFeatureInformation(json: any): QueryMapFeaturesResponse {
const root = json;
const getter = buildPropertyGetter<QueryMapFeaturesResponse>();
const resp = {
FeatureSet: deArrayifyFeatureSet(root.FeatureSet),
Hyperlink: getter(root, "Hyperlink"),
InlineSelectionImage: deArrayifyInlineSelectionImage(root.InlineSelectionImage),
SelectedFeatures: deArrayifySelectedFeatures(root.SelectedFeatures),
Tooltip: getter(root, "Tooltip")
};
return resp;
}
function deArrayifyWebLayoutControl<T extends WebLayoutControl>(json: any): T {
const root = json;
if (root == null || root.length != 1) {
throw new MgError("Malformed input. Expected control element");
}
const getter = buildPropertyGetter<T>();
const control: any = {
Visible: getter(root[0], "Visible", "boolean")
};
return control;
}
function deArrayifyWebLayoutInfoPane(json: any): WebLayoutInfoPane {
const root = json;
if (root == null || root.length != 1) {
throw new MgError("Malformed input. Expected InformationPane element");
}
const getter = buildPropertyGetter<WebLayoutInfoPane>();
const infoPane = {
Visible: getter(root[0], "Visible", "boolean"),
Width: getter(root[0], "Width", "int"),
LegendVisible: getter(root[0], "LegendVisible", "boolean"),
PropertiesVisible: getter(root[0], "PropertiesVisible", "boolean")
};
return infoPane;
}
function deArrayifyWebLayoutInitialView(json: any): MapView | undefined {
const root = json;
if (root == null || root.length != 1) {
return undefined;
}
const getter = buildPropertyGetter<MapView>();
const view = {
CenterX: getter(root[0], "CenterX", "float"),
CenterY: getter(root[0], "CenterY", "float"),
Scale: getter(root[0], "Scale", "float")
};
return view;
}
function deArrayifyWebLayoutMap(json: any): WebLayoutMap {
const root = json;
if (root == null || root.length != 1) {
throw new MgError("Malformed input. Expected Map element");
}
const getter = buildPropertyGetter<WebLayoutMap>();
const map = {
ResourceId: getter(root[0], "ResourceId"),
InitialView: deArrayifyWebLayoutInitialView(root[0].InitialView),
HyperlinkTarget: getter(root[0], "HyperlinkTarget"),
HyperlinkTargetFrame: getter(root[0], "HyperlinkTargetFrame")
};
return map;
}
function deArrayifyTaskButton(json: any): TaskButton {
const root = json;
if (root == null || root.length != 1) {
throw new MgError("Malformed input. Expected TaskButton element");
}
const getter = buildPropertyGetter<TaskButton>();
const button = {
Name: getter(root[0], "Name"),
Tooltip: getter(root[0], "Tooltip"),
Description: getter(root[0], "Description"),
ImageURL: getter(root[0], "ImageURL"),
DisabledImageURL: getter(root[0], "DisabledImageURL")
};
return button;
}
function deArrayifyWebLayoutTaskBar(json: any): WebLayoutTaskBar {
const root = json;
if (root == null || root.length != 1) {
throw new MgError("Malformed input. Expected TaskBar element");
}
const getter = buildPropertyGetter<WebLayoutTaskBar>();
const taskbar = {
Visible: getter(root[0], "Visible", "boolean"),
Home: deArrayifyTaskButton(root[0].Home),
Forward: deArrayifyTaskButton(root[0].Forward),
Back: deArrayifyTaskButton(root[0].Back),
Tasks: deArrayifyTaskButton(root[0].Tasks),
MenuButton: [] as UIItem[]
};
if (root[0].MenuButton) {
for (const mb of root[0].MenuButton) {
taskbar.MenuButton.push(deArrayifyUIItem(mb));
}
}
return taskbar;
}
function deArrayifyWebLayoutTaskPane(json: any): WebLayoutTaskPane {
const root = json;
if (root == null || root.length != 1) {
throw new MgError("Malformed input. Expected TaskPane element");
}
const getter = buildPropertyGetter<WebLayoutTaskPane>();
const taskPane = {
Visible: getter(root[0], "Visible", "boolean"),
InitialTask: getter(root[0], "InitialTask"),
Width: getter(root[0], "Width", "int"),
TaskBar: deArrayifyWebLayoutTaskBar(root[0].TaskBar)
};
return taskPane;
}
function deArrayifyUIItem(json: any): UIItem {
const root = json;
const getter = buildPropertyGetter<UIItem & CommandUIItem & FlyoutUIItem>();
const func: string = getter(root, "Function");
//Wouldn't it be nice if we could incrementally build up a union type that then becomes a specific
//type once certain properties are set?
//
//Well, that's currently not possible. So we have to resort to "any"
const item: any = {
Function: func
};
switch (func) {
case "Command":
item.Command = getter(root, "Command");
break;
case "Flyout":
item.Label = getter(root, "Label");
item.Tooltip = getter(root, "Tooltip");
item.Description = getter(root, "Description");
item.ImageURL = getter(root, "ImageURL");
item.DisabledImageURL = getter(root, "DisabledImageURL");
item.SubItem = [];
for (const si of root.SubItem) {
item.SubItem.push(deArrayifyUIItem(si));
}
break;
}
return item;
}
function deArrayifyItemContainer<T extends WebLayoutControl>(json: any, name: string): T {
const root = json;
if (root == null || root.length != 1) {
throw new MgError("Malformed input. Expected container element");
}
const getter = buildPropertyGetter<T>();
const container: any = {};
container[name] = [];
for (const item of root[0][name]) {
container[name].push(deArrayifyUIItem(item));
}
if (typeof (root[0].Visible) != 'undefined') {
container.Visible = getter(root[0], "Visible", "boolean");
}
return container;
}
function deArrayifyWebLayoutSearchResultColumnSet(json: any): ResultColumnSet {
const root = json;
if (root == null || root.length != 1) {
throw new MgError("Malformed input. Expected ResultColumns element");
}
const getter = buildPropertyGetter<ResultColumn>();
const res = {
Column: [] as ResultColumn[]
};
for (const col of root[0].Column) {
res.Column.push({
Name: getter(col, "Name"),
Property: getter(col, "Property")
});
}
return res;
}
function deArrayifyWebLayoutInvokeURLLayerSet(json: any): LayerSet | undefined {
const root = json;
if (root == null || root.length != 1) {
return undefined;
}
const layerset = {
Layer: root[0].Layer
};
return layerset;
}
function deArrayifyWebLayoutParameterPairs(json: any): ParameterPair[] {
const root = json;
const pairs = [] as ParameterPair[]
if (!root) {
return pairs;
}
const getter = buildPropertyGetter<ParameterPair>();
for (const kvp of root) {
pairs.push({
Key: getter(kvp, "Key"),
Value: getter(kvp, "Value")
});
}
return pairs;
}
function deArrayifyCommand(json: any): CommandDef {
const root = json;
const getter = buildPropertyGetter<CommandDef & BasicCommandDef & InvokeScriptCommandDef & InvokeURLCommandDef & SearchCommandDef>();
const cmd: any = {
"@xsi:type": getter(root, "@xsi:type"),
Name: getter(root, "Name"),
Label: getter(root, "Label"),
Tooltip: getter(root, "Tooltip"),
Description: getter(root, "Description"),
ImageURL: getter(root, "ImageURL"),
DisabledImageURL: getter(root, "DisabledImageURL"),
TargetViewer: getter(root, "TargetViewer")
};
//Basic
if (typeof (root.Action) != 'undefined') {
cmd.Action = getter(root, "Action");
}
//Targeted
if (typeof (root.Target) != 'undefined') {
cmd.Target = getter(root, "Target");
}
if (typeof (root.TargetFrame) != 'undefined') {
cmd.TargetFrame = getter(root, "TargetFrame");
}
//Search
if (typeof (root.Layer) != 'undefined') {
cmd.Layer = getter(root, "Layer");
cmd.Prompt = getter(root, "Prompt");
cmd.ResultColumns = deArrayifyWebLayoutSearchResultColumnSet(root.ResultColumns);
cmd.Filter = getter(root, "Filter");
cmd.MatchLimit = getter(root, "MatchLimit", "int");
}
//InvokeURL | Help
if (typeof (root.URL) != 'undefined') {
cmd.URL = getter(root, "URL");
}
if (typeof (root.DisableIfSelectionEmpty) != 'undefined') {
cmd.LayerSet = deArrayifyWebLayoutInvokeURLLayerSet(root.LayerSet);
cmd.AdditionalParameter = deArrayifyWebLayoutParameterPairs(root.AdditionalParameter);
cmd.DisableIfSelectionEmpty = getter(root, "DisableIfSelectionEmpty", "boolean");
}
//InvokeScript
if (typeof (root.Script) != 'undefined') {
cmd.Script = getter(root, "Script");
}
return cmd;
}
function deArrayifyWebLayoutCommandSet(json: any): WebLayoutCommandSet {
const root = json;
if (root == null || root.length != 1) {
throw new MgError("Malformed input. Expected CommandSet element");
}
const set = {
Command: [] as CommandDef[]
};
if (root[0].Command) {
for (const cmd of root[0].Command) {
set.Command.push(deArrayifyCommand(cmd));
}
}
return set;
}
function deArrayifyWebLayout(json: any): WebLayout {
const root = json;
const getter = buildPropertyGetter<WebLayout>();
const resp = {
Title: getter(root, "Title"),
Map: deArrayifyWebLayoutMap(root.Map),
EnablePingServer: getter(root, "EnablePingServer", "boolean"),
SelectionColor: getter(root, "SelectionColor"),
PointSelectionBuffer: getter(root, "PointSelectionBuffer", "int"),
MapImageFormat: getter(root, "MapImageFormat"),
SelectionImageFormat: getter(root, "SelectionImageFormat"),
StartupScript: getter(root, "StartupScript"),
ToolBar: deArrayifyItemContainer<WebLayoutToolbar>(root.ToolBar, "Button"),
InformationPane: deArrayifyWebLayoutInfoPane(root.InformationPane),
ContextMenu: deArrayifyItemContainer<WebLayoutContextMenu>(root.ContextMenu, "MenuItem"),
TaskPane: deArrayifyWebLayoutTaskPane(root.TaskPane),
StatusBar: deArrayifyWebLayoutControl<WebLayoutStatusBar>(root.StatusBar),
ZoomControl: deArrayifyWebLayoutControl<WebLayoutZoomControl>(root.ZoomControl),
CommandSet: deArrayifyWebLayoutCommandSet(root.CommandSet)
};
return resp;
}
function deArrayifyMapGroup(json: any): MapSetGroup {
const root = json;
if (root == null) {
throw new MgError("Malformed input. Expected MapGroup element");
}
const getter = buildPropertyGetter<MapSetGroup & MapInitialView & MapConfiguration>();
const mapGroup: MapSetGroup = {
"@id": getter(root, "@id", "string"),
InitialView: undefined,
Map: [] as MapConfiguration[]
};
if (root.InitialView) {
const iview = root.InitialView[0];
mapGroup.InitialView = {
CenterX: getter(iview, "CenterX", "float"),
CenterY: getter(iview, "CenterY", "float"),
Scale: getter(iview, "Scale", "float")
};
}
if (root.Map) {
for (const m of root.Map) {
mapGroup.Map.push({
Type: getter(m, "Type", "string"),
//SingleTile: getter(m, "SingleTile", "boolean"),
Extension: deArrayifyExtension(m.Extension)
});
}
}
return mapGroup;
}
function deArrayifyMapSet(json: any): MapSet | undefined {
const root = json;
if (root == null || root.length != 1) {
throw new MgError("Malformed input. Expected MapSet element");
}
const set = {
MapGroup: [] as MapSetGroup[]
};
if (root[0].MapGroup) {
for (const map of root[0].MapGroup) {
set.MapGroup.push(deArrayifyMapGroup(map));
}
}
return set;
}
function deArrayifyContainerItems(json: any[]): ContainerItem[] {
const items = [] as ContainerItem[];
const getter = buildPropertyGetter<ContainerItem & FlyoutItem & WidgetItem>();
if (json && json.length) {
for (const i of json) {
const func = getter(i, "Function", "string");
switch (func) {
case "Separator":
items.push({
Function: "Separator"
});
break;
case "Widget":
items.push({
Function: "Widget",
Widget: getter(i, "Widget", "string")
})
break;
case "Flyout":
items.push({
Function: "Flyout",
Label: getter(i, "Label", "string"),
Tooltip: getter(i, "Tooltip", "string"),
ImageUrl: getter(i, "ImageUrl", "string"),
ImageClass: getter(i, "ImageClass", "string"),
Item: deArrayifyContainerItems(i.Item || [])
})
break;
}
}
}
return items;
}
function deArrayifyContainer(json: any[]): ContainerDefinition[] {
const containers = [] as ContainerDefinition[];
const getter = buildPropertyGetter<ContainerDefinition>();
for (const c of json) {
containers.push({
Name: getter(c, "Name", "string"),
Type: getter(c, "Type", "string"),
//Position: getter(c, "Position", "string"),
Extension: deArrayifyExtension(c.Extension),
Item: deArrayifyContainerItems(c.Item)
});
}
return containers;
}
function deArrayifyWidgets(json: any[]): Widget[] {
const widgets = [] as Widget[];
for (const w of json) {
if (w["@xsi:type"] == "UiWidgetType") {
const uiw = deArrayifyUiWidget(w);
widgets.push(uiw);
} else {
widgets.push(deArrayifyWidget(w));
}
}
return widgets;
}
function deArrayifyWidget(json: any): Widget {
const root = json;
if (root == null) {
throw new MgError("Malformed input. Expected Widget element");
}
const getter = buildPropertyGetter<Widget & { "@xsi:type": string }>();
const w: Widget = {
WidgetType: getter(root, "@xsi:type", "string"),
Name: getter(root, "Name", "string"),
Type: getter(root, "Type", "string"),
//Location: getter(root, "Location", "string"),
Extension: deArrayifyExtension(root.Extension)
};
return w;
}
function deArrayifyExtension(json: any, arrayCheck: boolean = true): any {
const root = json;
if (root == null) {
return null;
}
if (arrayCheck && root.length != 1) {
throw new MgError("Malformed input. Expected Extension element");
}
const getter = buildPropertyGetter<{ Key: string, Value: string, [key: string]: string}>();
const ext: any = {};
for (const key in root[0]) {
if (Array.isArray(root[0][key])) {
//Special case handling
switch (key) {
case "AdditionalParameter":
{
const params = [];
for (const p of root[0][key]) {
params.push({
Key: getter(p, "Key", "string"),
Value: getter(p, "Value", "string")
});
}
ext[key] = params;
}
break;
case "Projection":
{
ext[key] = root[0][key];
}
break;
default:
ext[key] = getter(root[0], key, "string");
break;
}
} else {
ext[key] = deArrayifyExtension(root[0][key], false);
}
}
return ext;
}
function deArrayifyUiWidget(json: any): UIWidget {
const root = json;
if (root == null) {
throw new MgError("Malformed input. Expected Widget element");
}
const getter = buildPropertyGetter<UIWidget & { "@xsi:type": string }>();
const w: UIWidget = {
WidgetType: getter(root, "@xsi:type", "string"),
ImageUrl: getter(root, "ImageUrl", "string"),
ImageClass: getter(root, "ImageClass", "string"),
Label: getter(root, "Label", "string"),
Tooltip: getter(root, "Tooltip", "string"),
StatusText: getter(root, "StatusText", "string"),
Disabled: getter(root, "Disabled", "boolean"),
Name: getter(root, "Name", "string"),
Type: getter(root, "Type", "string"),
//Location: getter(root, "Location", "string"),
Extension: deArrayifyExtension(root.Extension)
};
return w;
}
function deArrayifyMapWidget(json: any): MapWidget {
const root = json;
if (root == null || root.length != 1) {
throw new MgError("Malformed input. Expected MapWidget element");
}
const getter = buildPropertyGetter<MapWidget & { "@xsi:type": string }>();
const mw: MapWidget = {
WidgetType: getter(root, "@xsi:type", "string"),
MapId: getter(root, "MapId", "string"),
Name: getter(root, "Name", "string"),
Type: getter(root, "Type", "string"),
//Location: getter(root, "Location", "string"),
Extension: deArrayifyExtension(root.Extension)
};
return mw;
}
function deArrayifyWidgetSet(json: any): WidgetSet[] {
const widgetSet = [] as WidgetSet[];
for (const ws of json) {
widgetSet.push({
Container: deArrayifyContainer(ws.Container),
MapWidget: deArrayifyMapWidget(ws.MapWidget),
Widget: deArrayifyWidgets(ws.Widget)
})
}
return widgetSet;
}
function deArrayifyFlexibleLayout(json: any): ApplicationDefinition {
const root = json;
const getter = buildPropertyGetter<ApplicationDefinition>();
const resp = {
Title: getter(root, "Title"),
TemplateUrl: getter(root, "TemplateUrl"),
MapSet: deArrayifyMapSet(root.MapSet),
WidgetSet: deArrayifyWidgetSet(root.WidgetSet),
Extension: deArrayifyExtension(root.Extension)
};
return resp;
}
function deArrayifyMapDefinitionGroups(json: any): MapDefinitionLayerGroup[] {
const groups = [] as MapDefinitionLayerGroup[];
const getter = buildPropertyGetter<MapDefinitionLayerGroup>();
for (const g of json) {
groups.push({
Name: getter(g, "Name"),
ExpandInLegend: getter(g, "ExpandInLegend", "boolean"),
ShowInLegend: getter(g, "ShowInLegend", "boolean"),
Visible: getter(g, "Visible", "boolean"),
LegendLabel: getter(g, "LegendLabel"),
Group: getter(g, "Group")
});
}
return groups;
}
function deArrayifyMapDefinitionLayers(json: any): MdfLayer[] {
const layers = [] as MdfLayer[];
const getter = buildPropertyGetter<MdfLayer>();
for (const g of json) {
layers.push({
Name: getter(g, "Name"),
ResourceId: getter(g, "ResourceId"),
ExpandInLegend: getter(g, "ExpandInLegend", "boolean"),
ShowInLegend: getter(g, "ShowInLegend", "boolean"),
Selectable: getter(g, "Selectable", "boolean"),
Visible: getter(g, "Visible", "boolean"),
LegendLabel: getter(g, "LegendLabel"),
Group: getter(g, "Group"),
});
}
return layers;
}
function deArrayifyMapDefinition(json: any): MapDefinition {
const root = json;
const getter = buildPropertyGetter<MapDefinition>();
const eGetter = buildPropertyGetter<MapDefinition["Extents"]>();
const resp: MapDefinition = {
BackgroundColor: getter(root, "BackgroundColor"),
CoordinateSystem: getter(root, "CoordinateSystem"),
Extents: {
MinX: eGetter(root.Extents[0], "MinX", "float"),
MinY: eGetter(root.Extents[0], "MinY", "float"),
MaxX: eGetter(root.Extents[0], "MaxX", "float"),
MaxY: eGetter(root.Extents[0], "MaxY", "float")
},
MapLayer: deArrayifyMapDefinitionLayers(root.MapLayer ?? []),
MapLayerGroup: deArrayifyMapDefinitionGroups(root.MapLayerGroup ?? [])
};
if (root.TileSetSource) {
const tGetter = buildPropertyGetter<TileSetSource>();
resp.TileSetSource = {
ResourceId: tGetter(root.TileSetSource, "ResourceId")
};
}
return resp;
}
function deArrayifyTileSetDefinitionLayers(json: any): BaseMapLayer[] {
const getter = buildPropertyGetter<BaseMapLayer>();
const layers = [] as BaseMapLayer[];
for (const l of json) {
layers.push({
Name: getter(l, "Name"),
ResourceId: getter(l, "ResourceId"),
Selectable: getter(l, "Selectable", "boolean"),
ShowInLegend: getter(l, "ShowInLegend", "boolean"),
LegendLabel: getter(l, "LegendLabel"),
ExpandInLegend: getter(l, "ExpandInLegend", "boolean")
})
}
return layers;
}
function deArrayifyTileSetDefinitionGroups(json: any): BaseMapLayerGroup[] {
const getter = buildPropertyGetter<BaseMapLayerGroup>();
const groups = [] as BaseMapLayerGroup[];
for (const g of json) {
groups.push({
Name: getter(g, "Name"),
Visible: getter(g, "Visible", "boolean"),
ShowInLegend: getter(g, "ShowInLegend", "boolean"),
ExpandInLegend: getter(g, "ExpandInLegend", "boolean"),
LegendLabel: getter(g, "LegendLabel"),
BaseMapLayer: deArrayifyTileSetDefinitionLayers(g.BaseMapLayer)
});
}
return groups;
}
function deArrayifyTileSetDefinitionParamList(root: any): { Name: string, Value: string }[] {
const getter = buildPropertyGetter<{ Name: string, Value: string }>();
const params = [] as { Name: string, Value: string }[];
for (const p of root) {
params.push({
Name: getter(p, "Name"),
Value: getter(p, "Value")
});
}
return params;
}
function deArrayifyTileSetDefinitionParams(root: any): TileStoreParameters {
const getter = buildPropertyGetter<TileStoreParameters>();
const tsp: TileStoreParameters = {
TileProvider: getter(root, "TileProvider"),
Parameter: deArrayifyTileSetDefinitionParamList(root[0].Parameter)
};
return tsp;
}
function deArrayifyTileSetDefinition(json: any): TileSetDefinition {
const root = json;
const eGetter = buildPropertyGetter<TileSetDefinition["Extents"]>();
const resp: TileSetDefinition = {
Extents: {
MinX: eGetter(root.Extents[0], "MinX", "float"),
MinY: eGetter(root.Extents[0], "MinY", "float"),
MaxX: eGetter(root.Extents[0], "MaxX", "float"),
MaxY: eGetter(root.Extents[0], "MaxY", "float")
},
TileStoreParameters: deArrayifyTileSetDefinitionParams(json.TileStoreParameters),
BaseMapLayerGroup: deArrayifyTileSetDefinitionGroups(json.BaseMapLayerGroup)
};
return resp;
}
/**
* Indicates if the de-arrayified result is a {@link WebLayout}
*
* @since 0.14
*/
export function isWebLayout(arg: DeArrayifiedResult): arg is WebLayout {
return (arg as any).CommandSet != null
&& (arg as any).ContextMenu != null
&& (arg as any).Map != null
}
/**
* Indicates if the de-arrayified result is an {@link ApplicationDefinition}
*
* @since 0.14
*/
export function isAppDef(arg: DeArrayifiedResult): arg is ApplicationDefinition {
return (arg as any).WidgetSet != null;
}
/**
* Indicates if the de-arrayified result is a {@link MapDefinition}
*
* @since 0.14
*/
export function isMapDef(arg: DeArrayifiedResult): arg is MapDefinition {
return (arg as any).Extents != null
&& (arg as any).BackgroundColor != null
&& (arg as any).CoordinateSystem != null
&& (arg as any).MapLayer != null
&& (arg as any).MapLayerGroup != null;
}
/**
* Indicates if the de-arrayified result is a {@link TileSetDefinition}
*
* @since 0.14
*/
export function isTileSet(arg: DeArrayifiedResult): arg is TileSetDefinition {
return (arg as any).Extents != null
&& (arg as any).TileStoreParameters != null
&& (arg as any).BaseMapLayerGroup != null;
}
/**
* Indicates if the de-arrayified result is a {@link SiteVersionResponse}
*
* @since 0.14
*/
export function isSiteVersion(arg: DeArrayifiedResult): arg is SiteVersionResponse {
return (arg as any).Version != null;
}
/**
* Indicates if the de-arrayified result is a {@link QueryMapFeaturesResponse}
*
* @since 0.14
*/
export function isQueryMapFeaturesResponse(arg: DeArrayifiedResult): arg is QueryMapFeaturesResponse {
return (arg as any).FeatureSet != null
|| (arg as any).Hyperlink != null
|| (arg as any).InlineSelectionImage != null
|| (arg as any).SelectedFeatures != null
|| (arg as any).Tooltip != null;
}
/**
* The result of the normalization of JSON from the mapagent
*
* @since 0.14
*/
export type DeArrayifiedResult = RuntimeMap | QueryMapFeaturesResponse | WebLayout | ApplicationDefinition | MapDefinition | TileSetDefinition | SiteVersionResponse;
/**
* Normalizes the given JSON object to match the content model of its original XML form
*
* @export
* @param {*} json The JSON object to normalize
* @returns {*} The normalized JSON object
*/
export function deArrayify(json: any): DeArrayifiedResult {
if (json["RuntimeMap"]) {
return deArrayifyRuntimeMap(json.RuntimeMap);
}
if (json["FeatureInformation"]) {
return deArrayifyFeatureInformation(json.FeatureInformation);
}
if (json["WebLayout"]) {
return deArrayifyWebLayout(json.WebLayout);
}
if (json["ApplicationDefinition"]) {
return deArrayifyFlexibleLayout(json.ApplicationDefinition);
}
if (json["MapDefinition"]) {
return deArrayifyMapDefinition(json.MapDefinition);
}
if (json["TileSetDefinition"]) {
return deArrayifyTileSetDefinition(json.TileSetDefinition);
}
if (json["SiteVersion"]) {
return {
Version: json.SiteVersion.Version[0]
} as SiteVersionResponse;
}
const keys = [] as string[];
for (const k in json) {
keys.push(k);
}
throw new MgError(`Unsure how to process JSON response. Root elements are: (${keys.join(", ")})`);
}
/**
* Builds an XML selection string from the given selection set.
*
* @export
* @param {(FeatureSet | undefined)} selection The selection set
* @param {string[]} [layerIds] If specified, the selection XML will only include selections from the specified layers
* @returns {string} The selection XML string
*/
export function buildSelectionXml(selection: FeatureSet | undefined, layerIds?: string[]): string {
let xml = '<?xml version="1.0" encoding="utf-8"?>';
xml += '<FeatureSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FeatureSet-1.0.0.xsd">';
if (selection) {
const selLayers = selection.Layer;
for (const layer of selLayers) {
const layerId = layer["@id"];
if (layerIds != null && layerIds.indexOf(layerId) < 0) {
continue;
}
xml += `<Layer id="${layerId}">`;
const cls = layer.Class;
xml += `<Class id="${cls["@id"]}">`;
for (const id of cls.ID) {
xml += `<ID>${id}</ID>`;
}
xml += '</Class>';
xml += '</Layer>';
}
}
xml += '</FeatureSet>';
return xml;
}
/**
* Can only be used for a v4.0.0 or higher QUERYMAPFEATURES request
*
* @param selection Current selection set
* @param feat The active selected feature
*/
export function getActiveSelectedFeatureXml(selection: FeatureSet, feat: ActiveSelectedFeature): string | undefined {
for (const layer of selection.Layer) {
const layerId = layer["@id"];
if (layerId == feat.layerId) {
const key = feat.selectionKey;
let xml = '<?xml version="1.0" encoding="utf-8"?>';
xml += '<FeatureSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FeatureSet-1.0.0.xsd">';
xml += `<Layer id="${layerId}">`;
xml += `<Class id="${layer.Class["@id"]}">`;
xml += `<ID>${key}</ID>`;
xml += '</Class>';
xml += '</Layer>';
xml += '</FeatureSet>';
return xml;
}
}
} | the_stack |
import { EventEmitter } from 'events';
import * as request from 'request';
import { Readable } from 'stream';
declare module 'coinbase-pro' {
export type HttpResponse = request.Response;
export type callback<T> = (err: any, response: HttpResponse, data: T) => void;
interface ApiServerTime {
iso: string;
epoch: number;
}
export type ProductTicker = {
trade_id: string;
price: string;
size: string;
bid: string;
ask: string;
volume: string;
time: string;
};
interface BaseOrder {
type: string;
side: 'buy' | 'sell';
product_id: string;
client_oid?: string;
stp?: 'dc' | 'co' | 'cn' | 'cb';
stop?: 'loss' | 'entry';
stop_price?: string;
}
interface LimitOrder extends BaseOrder {
type: 'limit';
price: string;
size: string;
time_in_force?: 'GTC' | 'GTT' | 'IOC' | 'FOK';
cancel_after?: 'min' | 'hour' | 'day';
post_only?: boolean;
}
/**
* Only one of `size` and `funds` are required for market and limit orders (the other can be explicitly assigned null or undefined). However,
* it is advisable to include both. If funds is not specified, the entire user balance is placed on hold until the order is filled which
* will prevent other orders from being placed in the interim. This can cause issues for HFT algorithms for example.
*/
interface MarketOrder extends BaseOrder {
type: 'market';
size: string | null;
funds: string | null;
}
interface StopOrder extends BaseOrder {
type: 'stop';
size: string;
funds: string;
}
export type OrderParams = MarketOrder | LimitOrder | StopOrder;
export interface BaseOrderInfo {
id: string;
price: string;
size: string;
product_id: string;
side: 'buy' | 'sell';
type: 'limit' | 'market' | 'stop';
created_at: string;
post_only: boolean;
fill_fees: string;
filled_size: string;
status: 'received' | 'rejected' | 'open' | 'done' | 'pending';
settled: boolean;
executed_value: string;
time_in_force: 'GTC' | 'GTT' | 'IOC' | 'FOK';
}
export interface OrderResult extends BaseOrderInfo {
stp: 'dc' | 'co' | 'cn' | 'cb';
}
export interface OrderInfo extends BaseOrderInfo {
status: 'received' | 'open' | 'done' | 'pending';
funds?: number;
specified_funds?: number;
done_at?: string;
done_reason?: string;
}
export type PageArgs = {
before?: number;
after?: number;
limit?: number;
};
export type FillFilter = {
product_id?: string;
order_id?: string;
} & PageArgs;
export type OrderFilter = {
product_id?: string;
status?: string;
} & PageArgs;
export type Account = {
id: string;
profile_id: string;
currency: string;
balance: string;
available: string;
hold: string;
};
export type CoinbaseAccount = {
id: string;
name: string;
balance: number;
currency: string;
type: 'wallet' | 'fiat';
primary: boolean;
active: boolean;
};
export type CurrencyInfo = {
id: string;
name: string;
min_size: string;
};
export interface ProductInfo {
id: string;
base_currency: string;
quote_currency: string;
base_min_size: string;
base_max_size: string;
quote_increment: string;
display_name: string;
margin_enabled: boolean;
}
/**
* If a PublicClient or AuthenticatedClient method that does an
* HTTP request throws an error, then it will have this shape.
*/
export interface HttpError extends Error {
response: HttpResponse;
data?: any;
}
export interface ClientOptions {
timeout?: number;
}
export class PublicClient {
constructor(apiURI?: string, options?: ClientOptions);
getProducts(callback: callback<ProductInfo[]>): void;
getProducts(): Promise<ProductInfo[]>;
getProductOrderBook(
productID: string,
options: any,
callback: callback<any>
): void;
getProductOrderBook(productID: string, options: any): Promise<any>;
getProductTicker(
productID: string,
callback: callback<ProductTicker>
): void;
getProductTicker(productID: string): Promise<ProductTicker>;
getProductTrades(productID: string, callback: callback<any>): void;
getProductTrades(productID: string): Promise<any>;
getProductTrades(
productID: string,
pageArgs: PageArgs,
callback: callback<any>
): void;
getProductTrades(productID: string, pageArgs: PageArgs): Promise<any>;
getProductTradeStream(
productID: string,
tradesFrom: number,
tradesTo: any
): Readable;
getProductHistoricRates(
productID: string,
args: any,
callback: callback<any[][]>
): void;
getProductHistoricRates(productID: string, args: any): Promise<any[][]>;
getProduct24HrStats(productID: string, callback: callback<any>): void;
getProduct24HrStats(productID: string): Promise<any>;
getCurrencies(callback: callback<CurrencyInfo[]>): void;
getCurrencies(): Promise<CurrencyInfo[]>;
getTime(callback: callback<ApiServerTime>): void;
getTime(): Promise<ApiServerTime>;
}
export class AuthenticatedClient extends PublicClient {
constructor(
key: string,
secret: string,
passphrase: string,
apiURI?: string,
options?: ClientOptions
);
getCoinbaseAccounts(callback: callback<CoinbaseAccount[]>): void;
getCoinbaseAccounts(): Promise<CoinbaseAccount[]>;
getAccounts(callback: callback<Account[]>): void;
getAccounts(): Promise<Account[]>;
getAccount(accountID: string, callback: callback<Account>): void;
getAccount(accountID: string): Promise<Account>;
getAccountHistory(accountID: string, callback: callback<any>): void;
getAccountHistory(accountID: string): Promise<any>;
getAccountHistory(
accountID: string,
pageArgs: PageArgs,
callback: callback<any>
): void;
getAccountHistory(accountID: string, pageArgs: PageArgs): Promise<any>;
getAccountTransfers(accountID: string, callback: callback<any>): void;
getAccountTransfers(accountID: string): Promise<any>;
getAccountTransfers(
accountID: string,
pageArgs: PageArgs,
callback: callback<any>
): void;
getAccountTransfers(accountID: string, pageArgs: PageArgs): Promise<any>;
getAccountHolds(accountID: string, callback: callback<any>): void;
getAccountHolds(accountID: string): Promise<any>;
getAccountHolds(
accountID: string,
pageArgs: PageArgs,
callback: callback<any>
): void;
getAccountHolds(accountID: string, pageArgs: PageArgs): Promise<any>;
buy(params: OrderParams, callback: callback<OrderResult>): void;
buy(params: OrderParams): Promise<OrderResult>;
sell(params: OrderParams, callback: callback<OrderResult>): void;
sell(params: OrderParams): Promise<OrderResult>;
placeOrder(params: OrderParams, callback: callback<OrderResult>): void;
placeOrder(params: OrderParams): Promise<OrderResult>;
cancelOrder(orderID: string, callback: callback<string[]>): void;
cancelOrder(orderID: string): Promise<string[]>;
cancelAllOrders(
args: { product_id?: string },
callback: callback<string[]>
): void;
cancelAllOrders(args: { product_id?: string }): Promise<string[]>;
getOrders(callback: callback<OrderInfo[]>): void;
getOrders(): Promise<OrderInfo[]>;
getOrders(props: OrderFilter, callback: callback<OrderInfo[]>): void;
getOrders(props: OrderFilter): Promise<OrderInfo[]>;
getOrder(orderID: string, callback: callback<OrderInfo>): void;
getOrder(orderID: string): Promise<OrderInfo>;
getFills(callback: callback<any>): void;
getFills(): Promise<any>;
getFills(props: FillFilter, callback: callback<any>): void;
getFills(props: FillFilter): Promise<any>;
getFundings(params: any, callback: callback<any>): void;
getFundings(params: any): Promise<any>;
repay(params: any, callback: callback<any>): void;
repay(params: any): Promise<any>;
marginTransfer(params: any, callback: callback<any>): void;
marginTransfer(params: any): Promise<any>;
closePosition(params: any, callback: callback<any>): void;
closePosition(params: any): Promise<any>;
convert(params: any, callback: callback<any>): void;
convert(params: any): Promise<any>;
deposit(params: any, callback: callback<any>): void;
deposit(params: any): Promise<any>;
withdraw(params: any, callback: callback<any>): void;
withdraw(params: any): Promise<any>;
withdrawCrypto(params: any, callback: callback<any>): void;
withdrawCrypto(params: any): Promise<any>;
getTrailingVolume(callback: callback<any>): void;
getTrailingVolume(): Promise<any>;
}
type ChannelName =
| 'full'
| 'level2'
| 'level2_50'
| 'status'
| 'ticker'
| 'ticker_1000'
| 'user'
| 'matches'
| 'heartbeat';
type Channel = {
name: ChannelName;
product_ids?: string[];
};
export namespace WebsocketMessage {
type Side = 'buy' | 'sell';
// Heartbeat channel
export type Heartbeat = {
type: 'heartbeat';
sequence: number;
last_trade_id: number;
product_id: string;
time: string; // ISO Date string without time zone
};
// Level 2 channel
export type L2Snapshot = {
type: 'snapshot';
product_id: string;
bids: [string, string][]; // strings are serialized fixed-point numbers
asks: [string, string][]; // [price, size]
};
export type L2Update = {
type: 'l2update';
product_id: string;
changes: [string, string, string][]; // [side, price, new size]
};
// Full channel
export type Received = {
type: 'received';
time: string;
product_id: string;
sequence: number;
order_id: string;
side: Side;
client_oid?: string;
} & (ReceivedLimit | ReceivedMarket);
type ReceivedLimit = {
order_type: 'limit';
size: string;
price: string;
};
type ReceivedMarket = {
order_type: 'market';
funds: string;
};
export type Open = {
type: 'open';
price: string;
order_id: string;
product_id: string;
profile_id: string;
sequence: number;
side: Side;
time: string;
user_id: string;
remaining_size: string;
};
export type Match = {
type: 'match';
trade_id: number;
sequence: number;
maker_order_id: string;
taker_order_id: string;
time: string;
product_id: string;
size: string;
price: string;
side: Side;
// authenticated
profile_id?: string;
user_id?: string;
};
export type Change = {
type: 'change';
time: string;
sequence: number;
order_id: string;
product_id: string;
price: string;
side: Side;
new_size?: string;
old_size?: string;
new_funds?: string;
old_funds?: string;
};
export type Done = {
type: 'done';
side: Side;
order_id: string;
reason: string;
product_id: string;
user_id?: string;
};
// Ticket channel
type BaseTicker = {
type: 'ticker';
sequence: number;
time: string;
product_id: string;
price: string;
open_24h?: string;
volume_24h?: string;
low_24h?: string;
high_24h?: string;
volume_30d?: string;
best_bid?: string;
best_ask?: string;
};
type FullTicket = BaseTicker & {
trade_id: number;
side: Side; // Taker side
last_size: string;
};
export type Ticker = BaseTicker | FullTicket;
// Subscription
export type Subscription = {
type: 'subscriptions';
channels: Channel[];
};
// Error
export type Error = {
type: 'error';
message: string;
reason: string;
};
}
export type WebsocketMessage =
| WebsocketMessage.Heartbeat
| WebsocketMessage.L2Snapshot
| WebsocketMessage.L2Update
| WebsocketMessage.Received
| WebsocketMessage.Open
| WebsocketMessage.Match
| WebsocketMessage.Change
| WebsocketMessage.Done
| WebsocketMessage.Ticker
| WebsocketMessage.Subscription
| WebsocketMessage.Error;
export interface WebsocketAuthentication {
key: string;
secret: string;
passphrase: string;
}
interface WebsocketClientOptions {
channels?: string[];
}
type SubscriptionOptions = { channels?: Channel[]; product_ids?: string[] };
export class WebsocketClient extends EventEmitter {
constructor(
productIds: string[],
websocketURI?: string,
auth?: WebsocketAuthentication,
{ channels }?: WebsocketClientOptions
);
on(event: 'message', eventHandler: (data: WebsocketMessage) => void): this;
on(event: 'error', eventHandler: (err: any) => void): this;
on(event: 'open', eventHandler: () => void): this;
on(event: 'close', eventHandler: () => void): this;
connect(): void;
disconnect(): void;
subscribe(options?: SubscriptionOptions): void;
unsubscribe(options?: SubscriptionOptions): void;
}
} | the_stack |
jest.unmock('follow-redirects');
import type * as RDF from '@rdfjs/types';
import { Store } from 'n3';
import { DataFactory } from 'rdf-data-factory';
import type { ActorInitSparql, IQueryResultUpdate } from '../../index-browser';
import { newEngine } from '../../index-browser';
import type { IQueryResultBindings } from '../../lib/ActorInitSparql-browser';
import { mockHttp } from './util';
import 'jest-rdf';
const arrayifyStream = require('arrayify-stream');
const DF = new DataFactory();
describe('System test: ActorInitSparql', () => {
const pollyContext = mockHttp();
let engine: ActorInitSparql;
beforeEach(() => {
engine = newEngine();
pollyContext.polly.server.any().on('beforePersist', (req, recording) => {
recording.request.headers = recording.request.headers.filter(({ name }: any) => name !== 'user-agent');
});
});
afterEach(async() => {
await pollyContext.polly.flush();
});
describe('query', () => {
describe('simple SPO on a raw RDF document', () => {
it('with results', async() => {
const result = <IQueryResultBindings> await engine.query(`SELECT * WHERE {
?s ?p ?o.
}`, { sources: [ 'https://www.rubensworks.net/' ]});
expect((await arrayifyStream(result.bindingsStream)).length).toBeGreaterThan(100);
});
it('without results', async() => {
const result = <IQueryResultBindings> await engine.query(`SELECT * WHERE {
?s <ex:dummy> ?o.
}`, { sources: [ 'https://www.rubensworks.net/' ]});
expect((await arrayifyStream(result.bindingsStream))).toEqual([]);
});
it('for the single source context entry', async() => {
const result = <IQueryResultBindings> await engine.query(`SELECT * WHERE {
?s ?p ?o.
}`, { source: 'https://www.rubensworks.net/' });
expect((await arrayifyStream(result.bindingsStream)).length).toBeGreaterThan(100);
});
it('repeated with the same engine', async() => {
const query = `SELECT * WHERE {
?s ?p ?o.
}`;
const context = { sources: [ 'https://www.rubensworks.net/' ]};
expect((await arrayifyStream((<IQueryResultBindings> await engine.query(query, context)).bindingsStream))
.length).toBeGreaterThan(100);
expect((await arrayifyStream((<IQueryResultBindings> await engine.query(query, context)).bindingsStream))
.length).toBeGreaterThan(100);
expect((await arrayifyStream((<IQueryResultBindings> await engine.query(query, context)).bindingsStream))
.length).toBeGreaterThan(100);
expect((await arrayifyStream((<IQueryResultBindings> await engine.query(query, context)).bindingsStream))
.length).toBeGreaterThan(100);
expect((await arrayifyStream((<IQueryResultBindings> await engine.query(query, context)).bindingsStream))
.length).toBeGreaterThan(100);
});
it('repeated with the same engine without results', async() => {
const query = `SELECT * WHERE {
?s <ex:dummy> ?o.
}`;
const context = { sources: [ 'https://www.rubensworks.net/' ]};
expect((await arrayifyStream((<IQueryResultBindings> await engine.query(query, context)).bindingsStream)))
.toEqual([]);
expect((await arrayifyStream((<IQueryResultBindings> await engine.query(query, context)).bindingsStream)))
.toEqual([]);
expect((await arrayifyStream((<IQueryResultBindings> await engine.query(query, context)).bindingsStream)))
.toEqual([]);
expect((await arrayifyStream((<IQueryResultBindings> await engine.query(query, context)).bindingsStream)))
.toEqual([]);
expect((await arrayifyStream((<IQueryResultBindings> await engine.query(query, context)).bindingsStream)))
.toEqual([]);
});
describe('extension function', () => {
let funcAllow: string;
let store: Store;
let baseFunctions: Record<string, (args: RDF.Term[]) => Promise<RDF.Term>>;
let baseFunctionCreator: (functionName: RDF.NamedNode) => ((args: RDF.Term[]) => Promise<RDF.Term>) | undefined;
let quads: RDF.Quad[];
let stringType: RDF.NamedNode;
let booleanType: RDF.NamedNode;
let integerType: RDF.NamedNode;
beforeEach(() => {
stringType = DF.namedNode('http://www.w3.org/2001/XMLSchema#string');
booleanType = DF.namedNode('http://www.w3.org/2001/XMLSchema#boolean');
integerType = DF.namedNode('http://www.w3.org/2001/XMLSchema#integer');
funcAllow = 'allowAll';
baseFunctions = {
'http://example.org/functions#allowAll': async(args: RDF.Term[]) => DF.literal('true', booleanType),
};
baseFunctionCreator = (functionName: RDF.NamedNode) =>
async(args: RDF.Term[]) => DF.literal('true', booleanType);
store = new Store();
quads = [
DF.quad(DF.namedNode('ex:a'), DF.namedNode('ex:p1'), DF.literal('apple', stringType)),
DF.quad(DF.namedNode('ex:a'), DF.namedNode('ex:p2'), DF.literal('APPLE', stringType)),
DF.quad(DF.namedNode('ex:a'), DF.namedNode('ex:p3'), DF.literal('Apple', stringType)),
DF.quad(DF.namedNode('ex:a'), DF.namedNode('ex:p4'), DF.literal('aPPLE', stringType)),
];
store.addQuads(quads);
});
const baseQuery = (funcName: string) => `PREFIX func: <http://example.org/functions#>
SELECT * WHERE {
?s ?p ?o.
FILTER (func:${funcName}(?o))
}`;
it('rejects when record does not match', async() => {
const context = <any> { sources: [ store ]};
context.extensionFunctions = baseFunctions;
await expect(engine.query(baseQuery('nonExist'), context)).rejects.toThrow('Unknown named operator');
});
it('rejects when creator returns null', async() => {
const context = <any> { sources: [ store ]};
context.extensionFunctionCreator = () => null;
await expect(engine.query(baseQuery('nonExist'), context)).rejects.toThrow('Unknown named operator');
});
it('with results and pointless custom filter given by creator', async() => {
const context = <any> { sources: [ store ]};
context.extensionFunctionCreator = baseFunctionCreator;
const result = <IQueryResultBindings> await engine.query(baseQuery(funcAllow), context);
expect((await arrayifyStream(result.bindingsStream)).length).toEqual(store.size);
});
it('with results and pointless custom filter given by record', async() => {
const context = <any> { sources: [ store ]};
context.extensionFunctions = baseFunctions;
const result = <IQueryResultBindings> await engine.query(baseQuery(funcAllow), context);
expect((await arrayifyStream(result.bindingsStream)).length).toEqual(4);
});
it('with results but all filtered away', async() => {
const context = <any> { sources: [ store ]};
context.extensionFunctionCreator = () => () =>
DF.literal('false', booleanType);
const result = <IQueryResultBindings> await engine.query(baseQuery('rejectAll'), context);
expect(await arrayifyStream(result.bindingsStream)).toEqual([]);
});
it('throws error when supplying both record and creator', async() => {
const context = <any> { sources: [ store ]};
context.extensionFunctions = baseFunctions;
context.extensionFunctionCreator = baseFunctionCreator;
await expect(engine.query(baseQuery(funcAllow), context)).rejects
.toThrow('Illegal simultaneous usage of extensionFunctionCreator and extensionFunctions in context');
});
it('handles complex queries with BIND to', async() => {
const context = <any> { sources: [ store ]};
const complexQuery = `PREFIX func: <http://example.org/functions#>
SELECT ?caps WHERE {
?s ?p ?o.
BIND (func:to-upper-case(?o) AS ?caps)
}
`;
context.extensionFunctions = {
async 'http://example.org/functions#to-upper-case'(args: RDF.Term[]) {
const arg = args[0];
if (arg.termType === 'Literal' && arg.datatype.equals(DF.literal('', stringType).datatype)) {
return DF.literal(arg.value.toUpperCase(), stringType);
}
return arg;
},
};
const result = <IQueryResultBindings> await engine.query(complexQuery, context);
expect((await result.bindings()).map(res => res.get('?caps').value)).toEqual(
quads.map(q => q.object.value.toUpperCase()),
);
});
describe('handles complex queries with groupBy', () => {
let context: any;
let complexQuery: string;
let extensionBuilder: (timout: boolean) => (args: RDF.Term[]) => Promise<RDF.Term>;
beforeEach(() => {
context = <any> { sources: [ store ]};
complexQuery = `PREFIX func: <http://example.org/functions#>
SELECT (SUM(func:count-chars(?o)) AS ?sum) WHERE {
?s ?p ?o.
}
`;
extensionBuilder = (timout: boolean) => async(args: RDF.Term[]) => {
const arg = args[0];
if (arg.termType === 'Literal' && arg.datatype.equals(DF.literal('', stringType).datatype)) {
if (timout) {
await new Promise(resolve => setTimeout(resolve, 1));
}
return DF.literal(String(arg.value.length), integerType);
}
return arg;
};
});
it('can be evaluated', async() => {
context.extensionFunctions = {
'http://example.org/functions#count-chars': extensionBuilder(false),
};
const result = <IQueryResultBindings> await engine.query(complexQuery, context);
expect((await result.bindings()).map(res => res.get('?sum').value)).toEqual([ '20' ]);
});
it('can be truly async', async() => {
context.extensionFunctions = {
'http://example.org/functions#count-chars': extensionBuilder(true),
};
const result = <IQueryResultBindings> await engine.query(complexQuery, context);
expect((await result.bindings()).map(res => res.get('?sum').value)).toEqual([ '20' ]);
});
});
});
});
describe('two-pattern query on a raw RDF document', () => {
it('with results', async() => {
const result = <IQueryResultBindings> await engine.query(`SELECT ?name WHERE {
<https://www.rubensworks.net/#me> <http://xmlns.com/foaf/0.1/knows> ?v0.
?v0 <http://xmlns.com/foaf/0.1/name> ?name.
}`, { sources: [ 'https://www.rubensworks.net/' ]});
expect((await arrayifyStream(result.bindingsStream)).length).toBeGreaterThan(20);
});
it('without results', async() => {
const result = <IQueryResultBindings> await engine.query(`SELECT ?name WHERE {
<https://www.rubensworks.net/#me> <http://xmlns.com/foaf/0.1/knows> ?v0.
?v0 <ex:dummy> ?name.
}`, { sources: [ 'https://www.rubensworks.net/' ]});
expect((await arrayifyStream(result.bindingsStream))).toEqual([]);
});
it('for the single source entry', async() => {
const result = <IQueryResultBindings> await engine.query(`SELECT ?name WHERE {
<https://www.rubensworks.net/#me> <http://xmlns.com/foaf/0.1/knows> ?v0.
?v0 <http://xmlns.com/foaf/0.1/name> ?name.
}`, { source: 'https://www.rubensworks.net/' });
expect((await arrayifyStream(result.bindingsStream)).length).toBeGreaterThan(20);
});
});
describe('simple SPO on a TPF entrypoint', () => {
it('with results', async() => {
const result = <IQueryResultBindings> await engine.query(`SELECT * WHERE {
?s ?p ?o.
} LIMIT 300`, { sources: [ 'https://fragments.dbpedia.org/2016-04/en' ]});
expect((await arrayifyStream(result.bindingsStream)).length).toEqual(300);
});
it('with filtered results', async() => {
const result = <IQueryResultBindings> await engine.query(`SELECT * WHERE {
?s a ?o.
} LIMIT 300`, { sources: [ 'https://fragments.dbpedia.org/2016-04/en' ]});
expect((await arrayifyStream(result.bindingsStream)).length).toEqual(300);
});
});
describe('two-pattern query on a TPF entrypoint', () => {
it('with results', async() => {
const result = <IQueryResultBindings> await engine.query(`SELECT * WHERE {
?city a <http://dbpedia.org/ontology/Airport>;
<http://dbpedia.org/property/cityServed> <http://dbpedia.org/resource/Italy>.
}`, { sources: [ 'https://fragments.dbpedia.org/2016-04/en' ]});
expect((await arrayifyStream(result.bindingsStream)).length).toEqual(19);
});
it('without results', async() => {
const result = <IQueryResultBindings> await engine.query(`SELECT * WHERE {
?city a <http://dbpedia.org/ontology/Airport>;
<http://dbpedia.org/property/cityServed> <http://dbpedia.org/resource/UNKNOWN>.
}`, { sources: [ 'https://fragments.dbpedia.org/2016-04/en' ]});
expect((await arrayifyStream(result.bindingsStream))).toEqual([]);
});
});
});
describe('update', () => {
describe('without sources on destination RDFJS Store', () => {
it('with direct insert', async() => {
// Prepare store
const store = new Store();
// Execute query
const result = <IQueryResultUpdate> await engine.query(`INSERT DATA {
<ex:s> <ex:p> <ex:o>.
}`, {
sources: [],
destination: store,
});
await result.updateResult;
// Check store contents
expect(store.size).toEqual(1);
expect(store.countQuads(DF.namedNode('ex:s'), DF.namedNode('ex:p'), DF.namedNode('ex:o'), DF.defaultGraph()))
.toEqual(1);
});
it('with direct insert on a single source', async() => {
// Prepare store
const store = new Store();
// Execute query
const result = <IQueryResultUpdate> await engine.query(`INSERT DATA {
<ex:s> <ex:p> <ex:o>.
}`, {
sources: [ store ],
});
await result.updateResult;
// Check store contents
expect(store.size).toEqual(1);
expect(store.countQuads(DF.namedNode('ex:s'), DF.namedNode('ex:p'), DF.namedNode('ex:o'), DF.defaultGraph()))
.toEqual(1);
});
it('with direct insert and delete', async() => {
// Prepare store
const store = new Store();
store.addQuad(DF.quad(DF.namedNode('ex:s-pre'), DF.namedNode('ex:p-pre'), DF.namedNode('ex:o-pre')));
// Execute query
const result = <IQueryResultUpdate> await engine.query(`INSERT DATA {
<ex:s> <ex:p> <ex:o>.
};
DELETE DATA {
<ex:s-pre> <ex:p-pre> <ex:o-pre>.
}`, {
sources: [],
destination: store,
});
await result.updateResult;
// Check store contents
expect(store.size).toEqual(1);
expect(store.countQuads(DF.namedNode('ex:s'), DF.namedNode('ex:p'), DF.namedNode('ex:o'), DF.defaultGraph()))
.toEqual(1);
expect(store
.countQuads(DF.namedNode('ex:s-pre'), DF.namedNode('ex:p-pre'), DF.namedNode('ex:o-pre'), DF.defaultGraph()))
.toEqual(0);
});
it('with variable delete', async() => {
// Prepare store
const store = new Store();
store.addQuads([
DF.quad(DF.namedNode('ex:s'), DF.namedNode('ex:p1'), DF.namedNode('ex:o1')),
DF.quad(DF.namedNode('ex:s'), DF.namedNode('ex:p2'), DF.namedNode('ex:o2')),
DF.quad(DF.namedNode('ex:s'), DF.namedNode('ex:p3'), DF.namedNode('ex:o3')),
DF.quad(DF.namedNode('ex:s2'), DF.namedNode('ex:p4'), DF.namedNode('ex:o4')),
]);
expect(store.size).toEqual(4);
// Execute query
const result = <IQueryResultUpdate> await engine.query(`DELETE WHERE {
<ex:s> ?p ?o.
}`, {
sources: [ store ],
destination: store,
});
await result.updateResult;
// Check store contents
expect(store.size).toEqual(1);
expect(store.countQuads(DF.namedNode('ex:s2'), DF.namedNode('ex:p4'), DF.namedNode('ex:o4'), DF.defaultGraph()))
.toEqual(1);
});
it('with load', async() => {
// Prepare store
const store = new Store();
// Execute query
const result = <IQueryResultUpdate> await engine.query(
`LOAD <https://www.rubensworks.net/> INTO GRAPH <ex:graph>`,
{
sources: [],
destination: store,
},
);
await result.updateResult;
// Check store contents
expect(store.size > 0).toBeTruthy();
});
it('with clear', async() => {
// Prepare store
const store = new Store();
store.addQuads([
DF.quad(DF.namedNode('ex:s'), DF.namedNode('ex:p1'), DF.namedNode('ex:o1'), DF.namedNode('ex:g1')),
DF.quad(DF.namedNode('ex:s'), DF.namedNode('ex:p2'), DF.namedNode('ex:o2'), DF.namedNode('ex:g2')),
DF.quad(DF.namedNode('ex:s'), DF.namedNode('ex:p3'), DF.namedNode('ex:o3'), DF.namedNode('ex:g3')),
DF.quad(DF.namedNode('ex:s2'), DF.namedNode('ex:p4'), DF.namedNode('ex:o4'), DF.defaultGraph()),
]);
expect(store.size).toEqual(4);
// Execute query
const result = <IQueryResultUpdate> await engine.query(`CLEAR NAMED`, {
sources: [ store ],
destination: store,
});
await result.updateResult;
// Check store contents
expect(store.size).toEqual(1);
expect(store.countQuads(DF.namedNode('ex:s2'), DF.namedNode('ex:p4'), DF.namedNode('ex:o4'), DF.defaultGraph()))
.toEqual(1);
});
it('with drop', async() => {
// Prepare store
const store = new Store();
store.addQuads([
DF.quad(DF.namedNode('ex:s'), DF.namedNode('ex:p1'), DF.namedNode('ex:o1'), DF.namedNode('ex:g1')),
DF.quad(DF.namedNode('ex:s'), DF.namedNode('ex:p2'), DF.namedNode('ex:o2'), DF.namedNode('ex:g2')),
DF.quad(DF.namedNode('ex:s'), DF.namedNode('ex:p3'), DF.namedNode('ex:o3'), DF.namedNode('ex:g3')),
DF.quad(DF.namedNode('ex:s2'), DF.namedNode('ex:p4'), DF.namedNode('ex:o4'), DF.defaultGraph()),
]);
expect(store.size).toEqual(4);
// Execute query
const result = <IQueryResultUpdate> await engine.query(`DROP DEFAULT`, {
sources: [ store ],
destination: store,
});
await result.updateResult;
// Check store contents
expect(store.size).toEqual(3);
expect(store.countQuads(DF.namedNode('ex:s4'), DF.namedNode('ex:p4'), DF.namedNode('ex:o4'), DF.defaultGraph()))
.toEqual(0);
});
it('with create', async() => {
// Prepare store
const store = new Store();
store.addQuads([
DF.quad(DF.namedNode('ex:s'), DF.namedNode('ex:p1'), DF.namedNode('ex:o1'), DF.namedNode('ex:g1')),
DF.quad(DF.namedNode('ex:s2'), DF.namedNode('ex:p4'), DF.namedNode('ex:o4'), DF.defaultGraph()),
]);
expect(store.size).toEqual(2);
// Resolve for non-existing graph
await expect((<IQueryResultUpdate> await engine.query(`CREATE GRAPH <ex:g2>`, {
sources: [ store ],
destination: store,
})).updateResult).resolves.toBeUndefined();
// Reject for existing graph
await expect((<IQueryResultUpdate> await engine.query(`CREATE GRAPH <ex:g1>`, {
sources: [ store ],
destination: store,
})).updateResult).rejects.toThrowError('Unable to create graph ex:g1 as it already exists');
// Resolve for existing graph in silent mode
await expect((<IQueryResultUpdate> await engine.query(`CREATE SILENT GRAPH <ex:g1>`, {
sources: [ store ],
destination: store,
})).updateResult).resolves.toBeUndefined();
});
it('with add', async() => {
// Prepare store
const store = new Store();
store.addQuads([
DF.quad(DF.namedNode('ex:s'), DF.namedNode('ex:p1'), DF.namedNode('ex:o1'), DF.namedNode('ex:g1')),
DF.quad(DF.namedNode('ex:s2'), DF.namedNode('ex:p2'), DF.namedNode('ex:o2'), DF.defaultGraph()),
]);
expect(store.size).toEqual(2);
// Execute query
const result = <IQueryResultUpdate> await engine.query(`ADD DEFAULT TO <ex:g1>`, {
sources: [ store ],
destination: store,
});
await result.updateResult;
// Check store contents
expect(store.size).toEqual(3);
expect(store
.countQuads(DF.namedNode('ex:s2'), DF.namedNode('ex:p2'), DF.namedNode('ex:o2'), DF.namedNode('ex:g1')))
.toEqual(1);
});
it('with move', async() => {
// Prepare store
const store = new Store();
store.addQuads([
DF.quad(DF.namedNode('ex:s'), DF.namedNode('ex:p1'), DF.namedNode('ex:o1'), DF.namedNode('ex:g1')),
DF.quad(DF.namedNode('ex:s2'), DF.namedNode('ex:p2'), DF.namedNode('ex:o2'), DF.defaultGraph()),
]);
expect(store.size).toEqual(2);
// Execute query
const result = <IQueryResultUpdate> await engine.query(`MOVE DEFAULT TO <ex:g1>`, {
sources: [ store ],
destination: store,
});
await result.updateResult;
// Check store contents
expect(store.size).toEqual(1);
expect(store
.countQuads(DF.namedNode('ex:s2'), DF.namedNode('ex:p2'), DF.namedNode('ex:o2'), DF.namedNode('ex:g1')))
.toEqual(1);
});
it('with copy', async() => {
// Prepare store
const store = new Store();
store.addQuads([
DF.quad(DF.namedNode('ex:s'), DF.namedNode('ex:p1'), DF.namedNode('ex:o1'), DF.namedNode('ex:g1')),
DF.quad(DF.namedNode('ex:s2'), DF.namedNode('ex:p2'), DF.namedNode('ex:o2'), DF.defaultGraph()),
]);
expect(store.size).toEqual(2);
// Execute query
const result = <IQueryResultUpdate> await engine.query(`COPY DEFAULT TO <ex:g1>`, {
sources: [ store ],
destination: store,
});
await result.updateResult;
// Check store contents
expect(store.size).toEqual(2);
expect(store
.countQuads(DF.namedNode('ex:s2'), DF.namedNode('ex:p2'), DF.namedNode('ex:o2'), DF.namedNode('ex:g1')))
.toEqual(1);
});
});
});
}); | the_stack |
import { expect, assert } from 'chai';
import * as fs from 'fs';
import * as mocha from 'mocha';
import * as os from 'os';
import * as url from 'url';
import * as ast from '../../compiler/lexical-analysis/ast';
import * as editor from '../../compiler/editor';
import * as lexical from '../../compiler/lexical-analysis/lexical';
import * as lexer from '../../compiler/lexical-analysis/lexer';
import * as local from '../../server/local';
import * as _static from '../../compiler/static';
import * as testWorkspace from './test_workspace';
const dataDir = `${__dirname}/../../../test/data`;
const makeLocation = (line: number, column: number): lexical.Location => {
return new lexical.Location(line, column);
}
const assertLocationRange = (
lr: lexical.LocationRange, startLine: number, startCol: number,
endLine: number, endCol: number
): void => {
assert.equal(lr.begin.line, startLine);
assert.equal(lr.begin.column, startCol);
assert.equal(lr.end.line, endLine);
assert.equal(lr.end.column, endCol);
}
const resolveSymbolAtPositionFromAst = (
analyzer: _static.Analyzer, context: ast.ResolutionContext,
rootNode: ast.Node, pos: lexical.Location,
): ast.Node | null => {
let nodeAtPos = _static.getNodeAtPositionFromAst(rootNode, pos);
if (ast.isAnalyzableFindFailure(nodeAtPos)) {
nodeAtPos = nodeAtPos.tightestEnclosingNode;
} else if (ast.isUnanalyzableFindFailure(nodeAtPos)) {
return null;
}
if (!ast.isResolvable(nodeAtPos)) {
return null;
}
const resolved = nodeAtPos.resolve(context);
return !ast.isResolve(resolved) || !ast.isNode(resolved.value)
? null
: resolved.value;
}
describe("Compiler service", () => {
const mockFilename = "mockFile.jsonnet";
const mockDocumentText1 = "{}";
const mockDocumentText2 = "[]";
it("returns cached parse if document versions are the same", () => {
const compilerService = new local.VsCompilerService();
{
const cachedParse1 = compilerService.cache(
mockFilename, mockDocumentText1, 1);
assert.isTrue(_static.isParsedDocument(cachedParse1));
assert.equal(cachedParse1.text, mockDocumentText1);
assert.equal(cachedParse1.version, 1);
assert.isTrue(
!_static.isLexFailure(cachedParse1.parse) &&
!_static.isParseFailure(cachedParse1.parse) &&
cachedParse1.parse.type == "ObjectNode");
}
{
// Return the cached parse if the versions are the same, instead
// of parsing the new document text.
const cachedParse2 = compilerService.cache(
mockFilename, mockDocumentText2, 1);
assert.isTrue(_static.isParsedDocument(cachedParse2));
assert.equal(cachedParse2.text, mockDocumentText1);
assert.equal(cachedParse2.version, 1);
assert.isTrue(
!_static.isLexFailure(cachedParse2.parse) &&
!_static.isParseFailure(cachedParse2.parse) &&
cachedParse2.parse.type == "ObjectNode");
}
{
// Parse the new version of the document.
const cachedParse3 = compilerService.cache(
mockFilename, mockDocumentText2, 2);
assert.isTrue(_static.isParsedDocument(cachedParse3));
assert.equal(cachedParse3.text, mockDocumentText2);
assert.equal(cachedParse3.version, 2);
assert.isTrue(
!_static.isLexFailure(cachedParse3.parse) &&
!_static.isParseFailure(cachedParse3.parse) &&
cachedParse3.parse.type == "ArrayNode");
}
});
it("always parses document if version is undefined", () => {
const compilerService = new local.VsCompilerService();
{
const cachedParse1 = compilerService.cache(
mockFilename, mockDocumentText1, undefined);
assert.isTrue(_static.isParsedDocument(cachedParse1));
assert.equal(cachedParse1.text, mockDocumentText1);
assert.equal(cachedParse1.version, undefined);
assert.isTrue(
!_static.isLexFailure(cachedParse1.parse) &&
!_static.isParseFailure(cachedParse1.parse) &&
cachedParse1.parse.type == "ObjectNode");
}
{
// Parse the new version of the document if version is
// `undefined`.
const cachedParse2 = compilerService.cache(
mockFilename, mockDocumentText2, undefined);
assert.isTrue(_static.isParsedDocument(cachedParse2));
assert.equal(cachedParse2.text, mockDocumentText2);
assert.equal(cachedParse2.version, undefined);
assert.isTrue(
!_static.isLexFailure(cachedParse2.parse) &&
!_static.isParseFailure(cachedParse2.parse) &&
cachedParse2.parse.type == "ArrayNode");
}
{
// Parse the new version of the document if previous version was
// `undefined`, but we now have a version number.
const cachedParse3 = compilerService.cache(
mockFilename, mockDocumentText1, 1);
assert.isTrue(_static.isParsedDocument(cachedParse3));
assert.equal(cachedParse3.text, mockDocumentText1);
assert.equal(cachedParse3.version, 1);
assert.isTrue(
!_static.isLexFailure(cachedParse3.parse) &&
!_static.isParseFailure(cachedParse3.parse) &&
cachedParse3.parse.type == "ObjectNode");
}
{
// Parse the new version of the document if we previously had a
// version number, but now we don't.
const cachedParse4 = compilerService.cache(
mockFilename, mockDocumentText2, undefined);
assert.isTrue(_static.isParsedDocument(cachedParse4));
assert.equal(cachedParse4.text, mockDocumentText2);
assert.equal(cachedParse4.version, undefined);
assert.isTrue(
!_static.isLexFailure(cachedParse4.parse) &&
!_static.isParseFailure(cachedParse4.parse) &&
cachedParse4.parse.type == "ArrayNode");
}
});
});
describe("Searching an AST by position", () => {
const compilerService = new local.VsCompilerService();
const documents =
new testWorkspace.FsDocumentManager(new local.VsPathResolver());
const analyzer = new _static.Analyzer(documents, compilerService);
const file = `file://${dataDir}/simple-nodes.jsonnet`;
const ctx = new ast.ResolutionContext(compilerService, documents, file);
const doc = documents.get(file);
const compiled = compilerService.cache(file, doc.text, doc.version);
if (_static.isFailedParsedDocument(compiled)) {
throw new Error(`Failed to parse document '${file}'`);
}
const rootNode = compiled.parse;
it("Object field assigned value of `local` symbol", () => {
// Property.
{
const property1Id = <ast.Identifier>_static.getNodeAtPositionFromAst(
rootNode, makeLocation(2, 5));
assert.isNotNull(property1Id);
assert.equal(property1Id.type, "IdentifierNode");
assert.equal(property1Id.name, "property1");
assert.isNotNull(property1Id.parent);
assertLocationRange(property1Id.loc, 2, 3, 2, 12);
const property1Parent = <ast.ObjectField>property1Id.parent;
assert.equal(property1Parent.type, "ObjectFieldNode");
assert.equal(property1Parent.kind, "ObjectFieldID");
assertLocationRange(property1Parent.loc, 2, 3, 2, 17);
}
// Target.
{
const target1Id = <ast.Identifier>_static.getNodeAtPositionFromAst(
rootNode, makeLocation(2, 14));
assert.isNotNull(target1Id);
assert.equal(target1Id.type, "IdentifierNode");
assert.equal(target1Id.name, "foo");
assert.isNotNull(target1Id.parent);
assertLocationRange(target1Id.loc, 2, 14, 2, 17);
const target1Parent = <ast.Var>target1Id.parent;
assert.equal(target1Parent.type, "VarNode");
assert.isNotNull(target1Parent.parent);
assertLocationRange(target1Parent.loc, 2, 14, 2, 17);
const target1Grandparent = <ast.ObjectField>target1Parent.parent;
assert.equal(target1Grandparent.type, "ObjectFieldNode");
assert.equal(target1Grandparent.kind, "ObjectFieldID");
assertLocationRange(target1Grandparent.loc, 2, 3, 2, 17);
}
});
it("Object field assigned literal number", () => {
// Target.
const found =
<ast.AnalyzableFindFailure>_static.getNodeAtPositionFromAst(
rootNode, makeLocation(3, 15));
assert.isTrue(ast.isAnalyzableFindFailure(found));
assert.equal(found.kind, "NotIdentifier");
const target2Id = <ast.LiteralNumber>found.tightestEnclosingNode;
assert.equal(target2Id.type, "LiteralNumberNode");
assert.equal(target2Id.originalString, "2");
assert.isNotNull(target2Id.parent);
assertLocationRange(target2Id.loc, 3, 14, 3, 15);
const target2Parent = <ast.ObjectField>target2Id.parent;
assert.equal(target2Parent.type, "ObjectFieldNode");
assert.equal(target2Parent.kind, "ObjectFieldID");
assertLocationRange(target2Parent.loc, 3, 3, 3, 15);
});
it("`local` object field assigned value", () => {
// Property.
{
const property3Id = <ast.Identifier>_static.getNodeAtPositionFromAst(
rootNode, makeLocation(4, 9));
assert.isNotNull(property3Id);
assert.equal(property3Id.type, "IdentifierNode");
assert.equal(property3Id.name, "foo");
assert.isNotNull(property3Id.parent);
assertLocationRange(property3Id.loc, 4, 9, 4, 12);
const property3Parent = <ast.ObjectField>property3Id.parent;
assert.equal(property3Parent.type, "ObjectFieldNode");
assert.equal(property3Parent.kind, "ObjectLocal");
assertLocationRange(property3Parent.loc, 4, 3, 4, 16);
}
// Target.
{
const found =
<ast.AnalyzableFindFailure>_static.getNodeAtPositionFromAst(
rootNode, makeLocation(4, 15));
assert.isTrue(ast.isAnalyzableFindFailure(found));
assert.equal(found.kind, "NotIdentifier");
const target3Id = <ast.LiteralNumber>found.tightestEnclosingNode;
assert.isNotNull(target3Id);
assert.equal(target3Id.type, "LiteralNumberNode");
assert.equal(target3Id.originalString, "3");
assert.isNotNull(target3Id.parent);
assertLocationRange(target3Id.loc, 4, 15, 4, 16);
const target3Parent = <ast.ObjectField>target3Id.parent;
assert.equal(target3Parent.type, "ObjectFieldNode");
assert.equal(target3Parent.kind, "ObjectLocal");
assertLocationRange(target3Parent.loc, 4, 3, 4, 16);
}
});
it("Resolution of `local` object fields is order-independent", () => {
// This location points at the `baz` symbol in the expression
// `bar.baz`, where `bar` is a `local` field that's declared below
// the current field. This tests that we correctly resolve that
// reference, even though it occurs after the current object
// field.
const property4Id = <ast.Identifier>_static.getNodeAtPositionFromAst(
rootNode, makeLocation(5, 20));
assert.isNotNull(property4Id);
assert.equal(property4Id.type, "IdentifierNode");
assert.equal(property4Id.name, "baz");
const resolved = <ast.LiteralNumber>(<ast.Resolve>property4Id.resolve(ctx)).value;
assert.equal(resolved.type, "LiteralNumberNode");
assert.equal(resolved.originalString, "3");
});
it("Can resolve identifiers that refer to mixins", () => {
// merged1.b
{
const merged1 = <ast.Identifier>_static.getNodeAtPositionFromAst(
rootNode, makeLocation(11, 23));
assert.isNotNull(merged1);
assert.equal(merged1.type, "IdentifierNode");
assert.equal(merged1.name, "b");
const resolved = <ast.LiteralNumber>(<ast.Resolve>merged1.resolve(ctx)).value;
assert.isNotNull(resolved);
assert.equal(resolved.type, "LiteralNumberNode");
assert.equal(resolved.originalString, "3");
}
// merged2.a
{
const merged2 = <ast.Identifier>_static.getNodeAtPositionFromAst(
rootNode, makeLocation(11, 34));
assert.isNotNull(merged2);
assert.equal(merged2.type, "IdentifierNode");
assert.equal(merged2.name, "a");
const resolved = <ast.LiteralNumber>(<ast.Resolve>merged2.resolve(ctx)).value;
assert.equal(resolved.type, "LiteralNumberNode");
assert.equal(resolved.originalString, "99");
}
// merged3.a
{
const merged3 = <ast.Identifier>_static.getNodeAtPositionFromAst(
rootNode, makeLocation(11, 45));
assert.isNotNull(merged3);
assert.equal(merged3.type, "IdentifierNode");
assert.equal(merged3.name, "a");
const resolved = <ast.LiteralNumber>(<ast.Resolve>merged3.resolve(ctx)).value;
assert.equal(resolved.type, "LiteralNumberNode");
assert.equal(resolved.originalString, "1");
}
// merged4.a
{
const merged4 = <ast.Identifier>_static.getNodeAtPositionFromAst(
rootNode, makeLocation(11, 56));
assert.isNotNull(merged4);
assert.equal(merged4.type, "IdentifierNode");
assert.equal(merged4.name, "a");
const resolved = <ast.LiteralNumber>(<ast.Resolve>merged4.resolve(ctx)).value;
assert.isNotNull(resolved);
assert.equal(resolved.type, "LiteralNumberNode");
assert.equal(resolved.originalString, "99");
}
// merged4.a
{
const merged5 = <ast.Identifier>_static.getNodeAtPositionFromAst(
rootNode, makeLocation(15, 28));
assert.isNotNull(merged5);
assert.equal(merged5.type, "IdentifierNode");
assert.equal(merged5.name, "a");
const resolved = <ast.LiteralNumber>(<ast.Resolve>merged5.resolve(ctx)).value;
assert.isNotNull(resolved);
assert.equal(resolved.type, "LiteralNumberNode");
assert.equal(resolved.originalString, "99");
}
});
it("Can resolve identifiers that point to identifiers", () => {
// Regression test. Tests that we can resolve a variable that
// points to another variable. In this case, `numberVal2` refers
// to `numberVal1`.
const node = <ast.Identifier>_static.getNodeAtPositionFromAst(
rootNode, makeLocation(18, 19));
assert.isNotNull(node);
assert.equal(node.type, "IdentifierNode");
assert.equal(node.name, "numberVal2");
const resolved = <ast.LiteralNumber>(<ast.Resolve>node.resolve(ctx)).value;
assert.isNotNull(resolved);
assert.equal(resolved.type, "LiteralNumberNode");
assert.equal(resolved.originalString, "1");
});
});
describe("Imported symbol resolution", () => {
const compilerService = new local.VsCompilerService();
const documents =
new testWorkspace.FsDocumentManager(new local.VsPathResolver());
const analyzer = new _static.Analyzer(documents, compilerService);
const file = `file://${dataDir}/simple-import.jsonnet`;
const document = documents.get(file);
const compile = compilerService.cache(file, document.text, document.version);
const ctx = new ast.ResolutionContext(compilerService, documents, file);
if (_static.isFailedParsedDocument(compile)) {
throw new Error(`Failed to parse document '${file}'`);
}
const rootNode = compile.parse;
it("Can dereference the object that is imported", () => {
const importedSymbol =
<ast.Local>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(4, 8));
assert.isNotNull(importedSymbol);
assert.equal(importedSymbol.type, "ObjectNode");
assert.isNotNull(importedSymbol.parent);
assertLocationRange(importedSymbol.loc, 2, 1, 52, 2);
});
it("Can dereference fields from an imported module", () => {
// This location points at the `foo` symbol in the expression
// `fooModule.foo`. This tests that we correctly resolve the
// `fooModule` symbol as an import, then load the relevant file,
// then resolve the `foo` symbol.
const valueofObjectField =
<ast.LiteralNumber>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(5, 19));
assert.isNotNull(valueofObjectField);
assert.equal(valueofObjectField.type, "LiteralNumberNode");
assert.equal(valueofObjectField.originalString, "99");
assertLocationRange(valueofObjectField.loc, 4, 8, 4, 10);
});
it("Can find comments for a field in an imported module", () => {
// This location points at the `foo` symbol in the expression
// `fooModule.foo`, where `fooModule` is an imported module. This
// tests that we can correctly obtain the documentation for this
// symbol.
const valueOfObjectField =
<ast.LiteralNumber>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(5, 19));
assert.isNotNull(valueOfObjectField);
const comments = analyzer.resolveComments(valueOfObjectField);
assert.isNotNull(comments);
assert.equal(
comments, " `foo` is a property that has very useful data.");
});
it("Can find comments for a nested field in an imported module", () => {
// This location points at the `bat` symbol in the expression
// `fooModule.baz.bat`, where `fooModule` is an imported module.
// This tests that we can correctly obtain the documentation for
// a symbol that lies in a multiply-nested index node.
const valueOfObjectField =
<ast.LiteralString>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(7, 23));
assert.isNotNull(valueOfObjectField);
assert.equal(valueOfObjectField.type, "LiteralStringNode");
assert.equal(valueOfObjectField.value, "batVal");
const comments = analyzer.resolveComments(valueOfObjectField);
assert.isNotNull(comments);
assert.equal(comments, " `bat` contains a fancy value, `batVal`.");
});
it("Cannot find comments for `local` field in an imported module", () => {
// This location points at the `bar` symbol in the expression
// `fooModule.bar`, where `fooModule` is an imported module. This
// tests that we do not report documentation for this symbol, as
// it is a `local` field.
const valueOfObjectField =
<ast.LiteralNumber>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(6, 10));
assert.isNotNull(valueOfObjectField);
const comments = analyzer.resolveComments(valueOfObjectField);
assert.isNull(comments);
});
it("Can find C-style comments", () => {
// This location points at the `bat` symbol in the expression
// `fooModule.baz.bat`, where `fooModule` is an imported module.
// This tests that we can correctly obtain the documentation for
// a symbol that lies in a multiply-nested index node.
const valueOfObjectField =
<ast.LiteralString>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(8, 23));
assert.isNotNull(valueOfObjectField);
const comments = analyzer.resolveComments(valueOfObjectField);
assert.isNotNull(comments);
assert.equal(comments, " This comment should appear over `testField1`. ");
});
it("Find multi-line C-style comments", () => {
// This location points at the `bat` symbol in the expression
// `fooModule.baz.bat`, where `fooModule` is an imported module.
// This tests that we can correctly obtain the documentation for
// a symbol that lies in a multiply-nested index node.
const valueOfObjectField =
<ast.LiteralString>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(9, 23));
assert.isNotNull(valueOfObjectField);
const comments = analyzer.resolveComments(valueOfObjectField);
assert.isNotNull(comments);
assert.equal(comments, " Line 1 of a comment that appears over `testField2`.\n Line 2 of a comment that appears over `testField2`.\n ");
});
it("Ignore C-style comments that come before the heading comment", () => {
// This location points at the `bat` symbol in the expression
// `fooModule.baz.bat`, where `fooModule` is an imported module.
// This tests that we can correctly obtain the documentation for
// a symbol that lies in a multiply-nested index node.
const valueOfObjectField =
<ast.LiteralString>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(10, 23));
assert.isNotNull(valueOfObjectField);
const comments = analyzer.resolveComments(valueOfObjectField);
assert.isNotNull(comments);
assert.equal(comments, " A comment for `testField3`.\n ");
});
it("Find C-style comments that come before a comma", () => {
// This location points at the `bat` symbol in the expression
// `fooModule.baz.bat`, where `fooModule` is an imported module.
// This tests that we can correctly obtain the documentation for
// a symbol that lies in a multiply-nested index node.
const valueOfObjectField =
<ast.LiteralString>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(11, 23));
assert.isNotNull(valueOfObjectField);
const comments = analyzer.resolveComments(valueOfObjectField);
assert.isNotNull(comments);
assert.equal(comments, " A comment for `testField4`. ");
});
it("Find C-style comments that come before a comma", () => {
// This location points at the `bat` symbol in the expression
// `fooModule.baz.bat`, where `fooModule` is an imported module.
// This tests that we can correctly obtain the documentation for
// a symbol that lies in a multiply-nested index node.
const valueOfObjectField =
<ast.LiteralString>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(12, 23));
assert.isNotNull(valueOfObjectField);
const comments = analyzer.resolveComments(valueOfObjectField);
assert.isNotNull(comments);
assert.equal(comments, " A comment for `testField5`. ");
});
it("Find CPP-style comment after several other comment types", () => {
// This location points at the `bat` symbol in the expression
// `fooModule.baz.bat`, where `fooModule` is an imported module.
// This tests that we can correctly obtain the documentation for
// a symbol that lies in a multiply-nested index node.
const valueOfObjectField =
<ast.LiteralString>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(13, 23));
assert.isNotNull(valueOfObjectField);
const comments = analyzer.resolveComments(valueOfObjectField);
assert.isNotNull(comments);
assert.equal(comments, " A comment for `testField6`.");
});
it("Find simple Hash-style comment", () => {
// This location points at the `bat` symbol in the expression
// `fooModule.baz.bat`, where `fooModule` is an imported module.
// This tests that we can correctly obtain the documentation for
// a symbol that lies in a multiply-nested index node.
const valueOfObjectField =
<ast.LiteralString>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(14, 23));
assert.isNotNull(valueOfObjectField);
const comments = analyzer.resolveComments(valueOfObjectField);
assert.isNotNull(comments);
assert.equal(comments, " A comment for `testField7`.");
});
it("Find multi-line Hash-style comment", () => {
// This location points at the `bat` symbol in the expression
// `fooModule.baz.bat`, where `fooModule` is an imported module.
// This tests that we can correctly obtain the documentation for
// a symbol that lies in a multiply-nested index node.
const valueOfObjectField =
<ast.LiteralString>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(15, 23));
assert.isNotNull(valueOfObjectField);
const comments = analyzer.resolveComments(valueOfObjectField);
assert.isNotNull(comments);
assert.equal(comments, " Line 1 of a comment for `testField8`.\n Line 2 of a comment for `testField8`.");
});
it("Find Hash-style comment before comma", () => {
// This location points at the `bat` symbol in the expression
// `fooModule.baz.bat`, where `fooModule` is an imported module.
// This tests that we can correctly obtain the documentation for
// a symbol that lies in a multiply-nested index node.
const valueOfObjectField =
<ast.LiteralString>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(16, 23));
assert.isNotNull(valueOfObjectField);
const comments = analyzer.resolveComments(valueOfObjectField);
assert.isNotNull(comments);
assert.equal(comments, " A comment for `testField9`.");
});
it("Ignore Hash-style comment before comma", () => {
// This location points at the `bat` symbol in the expression
// `fooModule.baz.bat`, where `fooModule` is an imported module.
// This tests that we can correctly obtain the documentation for
// a symbol that lies in a multiply-nested index node.
const valueOfObjectField =
<ast.LiteralString>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(17, 23));
assert.isNotNull(valueOfObjectField);
const comments = analyzer.resolveComments(valueOfObjectField);
assert.isNotNull(comments);
assert.equal(comments, " A comment for `testField10`.");
});
it("Ignore CPP-style comments separated by newlines", () => {
// This location points at the `bat` symbol in the expression
// `fooModule.baz.bat`, where `fooModule` is an imported module.
// This tests that we can correctly obtain the documentation for
// a symbol that lies in a multiply-nested index node.
const valueOfObjectField =
<ast.LiteralString>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(18, 23));
assert.isNotNull(valueOfObjectField);
const comments = analyzer.resolveComments(valueOfObjectField);
assert.isNotNull(comments);
assert.equal(comments, " A comment for `testField11`.");
});
it("Ignore Hash-style comments separated by newlines", () => {
// This location points at the `bat` symbol in the expression
// `fooModule.baz.bat`, where `fooModule` is an imported module.
// This tests that we can correctly obtain the documentation for
// a symbol that lies in a multiply-nested index node.
const valueOfObjectField =
<ast.LiteralString>resolveSymbolAtPositionFromAst(
analyzer, ctx, rootNode, makeLocation(19, 23));
assert.isNotNull(valueOfObjectField);
const comments = analyzer.resolveComments(valueOfObjectField);
assert.isNotNull(comments);
assert.equal(comments, " A comment for `testField12`.");
});
}); | the_stack |
import { GenSuggestionOptions, SuggestionOptions } from './genSuggestionsOptions';
import { parseDictionary } from './SimpleDictionaryParser';
import { suggest, genSuggestions, genCompoundableSuggestions } from './suggest';
import {
compSuggestionResults,
isSuggestionResult,
suggestionCollector,
SuggestionCollectorOptions,
} from './suggestCollector';
import { Trie } from './trie';
import * as Walker from './walker';
const defaultOptions: SuggestionCollectorOptions = {
numSuggestions: 10,
ignoreCase: undefined,
changeLimit: undefined,
timeout: undefined,
};
describe('Validate Suggest', () => {
const SEPARATE_WORDS: GenSuggestionOptions = { compoundMethod: Walker.CompoundWordsMethod.SEPARATE_WORDS };
const JOIN_WORDS: GenSuggestionOptions = { compoundMethod: Walker.CompoundWordsMethod.JOIN_WORDS };
test('Tests suggestions for valid word', () => {
const trie = Trie.create(sampleWords);
const results = suggest(trie.root, 'talks');
const suggestions = results.map((s) => s.word);
expect(suggestions).toEqual(expect.arrayContaining(['talks']));
expect(suggestions).toEqual(expect.arrayContaining(['talk']));
expect(suggestions[0]).toBe('talks');
expect(suggestions[1]).toBe('talk');
expect(suggestions).toEqual(['talks', 'talk', 'walks', 'talked', 'talker', 'walk']);
});
test('Tests suggestions for invalid word', () => {
const trie = Trie.create(sampleWords);
// cspell:ignore tallk
const results = suggest(trie.root, 'tallk');
const suggestions = results.map((s) => s.word);
expect(suggestions).toEqual(expect.arrayContaining(['talks']));
expect(suggestions).toEqual(expect.arrayContaining(['talk']));
expect(suggestions[1]).toBe('talks');
expect(suggestions[0]).toBe('talk');
expect(suggestions).toEqual(['talk', 'talks', 'walk']);
});
// cspell:ignore jernals
test('Tests suggestions jernals', () => {
const trie = Trie.create(sampleWords);
const results = suggest(trie.root, 'jernals');
const suggestions = results.map((s) => s.word);
expect(suggestions).toEqual(['journals', 'journal']);
});
// cspell:ignore juornals
test('Tests suggestions for `juornals` (reduced cost for swap)', () => {
const trie = Trie.create(sampleWords);
const results = suggest(trie.root, 'juornals');
const suggestions = results.map((s) => s.word);
expect(suggestions).toEqual(['journals', 'journal', 'journalism', 'journalist', 'journey', 'jovial']);
});
test('Tests suggestions for joyfull', () => {
const trie = Trie.create(sampleWords);
const results = suggest(trie.root, 'joyfull');
const suggestions = results.map((s) => s.word);
expect(suggestions).toEqual(['joyfully', 'joyful', 'joyfuller', 'joyfullest', 'joyous']);
});
// cspell:ignore walkingtalkingjoy
test('Tests compound suggestions', () => {
const trie = Trie.create(sampleWords);
const results = suggest(trie.root, 'walkingtalkingjoy', { ...numSugs(1), ...SEPARATE_WORDS });
const suggestions = results.map((s) => s.word);
expect(suggestions).toEqual(['walking talking joy']);
});
test('Tests suggestions', () => {
const trie = Trie.create(sampleWords);
const results = suggest(trie.root, '');
const suggestions = results.map((s) => s.word);
expect(suggestions).toEqual([]);
});
// cspell:ignore joyfull
test('Tests suggestions with low max num', () => {
const trie = Trie.create(sampleWords);
const results = suggest(trie.root, 'joyfull', { numSuggestions: 3 });
const suggestions = results.map((s) => s.word);
expect(suggestions).toEqual(['joyfully', 'joyful', 'joyfuller']);
});
test('Tests genSuggestions', () => {
const trie = Trie.create(sampleWords);
const collector = suggestionCollector(
'joyfull',
sugOpts({
numSuggestions: 3,
filter: (word) => word !== 'joyfully',
})
);
collector.collect(genSuggestions(trie.root, collector.word));
const suggestions = collector.suggestions.map((s) => s.word);
expect(suggestions).toEqual(expect.not.arrayContaining(['joyfully']));
expect(suggestions).toEqual(['joyful', 'joyfuller', 'joyfullest']);
expect(collector.maxCost).toBeLessThan(300);
});
test('Tests genSuggestions wanting 0', () => {
const trie = Trie.create(sampleWords);
const collector = suggestionCollector('joyfull', sugOptsMaxNum(0));
collector.collect(genSuggestions(trie.root, collector.word));
const suggestions = collector.suggestions.map((s) => s.word);
expect(suggestions).toHaveLength(0);
});
test('Tests genSuggestions wanting -10', () => {
const trie = Trie.create(sampleWords);
const collector = suggestionCollector('joyfull', sugOptsMaxNum(-10));
collector.collect(genSuggestions(trie.root, collector.word));
const suggestions = collector.suggestions.map((s) => s.word);
expect(suggestions).toHaveLength(0);
});
test('Tests genSuggestions as array', () => {
const trie = Trie.create(sampleWords);
const sugs = [...genSuggestions(trie.root, 'joyfull')].filter(isSuggestionResult);
const sr = sugs.sort(compSuggestionResults);
const suggestions = sr.map((s) => s && s.word);
expect(suggestions).toEqual(['joyfully', 'joyful', 'joyfuller', 'joyfullest', 'joyous']);
});
// cspell:ignore joyfullwalk
test('Tests genSuggestions with compounds SEPARATE_WORDS', () => {
const trie = Trie.create(sampleWords);
const collector = suggestionCollector('joyfullwalk', sugOptsMaxNum(3));
collector.collect(genCompoundableSuggestions(trie.root, collector.word, SEPARATE_WORDS));
const suggestions = collector.suggestions.map((s) => s.word);
expect(suggestions).toEqual(['joyful walk', 'joyful walks', 'joyfully walk']);
expect(collector.maxCost).toBeLessThan(300);
});
// cspell:ignore joyfullwalk joyfulwalk joyfulwalks joyfullywalk, joyfullywalks
test('Tests genSuggestions with compounds JOIN_WORDS', () => {
const trie = Trie.create(sampleWords);
const collector = suggestionCollector('joyfullwalk', sugOptsMaxNum(3));
collector.collect(genCompoundableSuggestions(trie.root, collector.word, JOIN_WORDS));
const suggestions = collector.suggestions.map((s) => s.word);
expect(suggestions).toEqual(['joyful+walk', 'joyful+walks', 'joyfully+walk']);
expect(collector.maxCost).toBeLessThan(300);
});
test('Tests the collector with filter', () => {
const collector = suggestionCollector(
'joyfull',
sugOpts({ numSuggestions: 3, filter: (word) => word !== 'joyfully' })
);
collector.add({ word: 'joyfully', cost: 100 }).add({ word: 'joyful', cost: 100 });
expect(collector.suggestions).toHaveLength(1);
});
test('Tests the collector with duplicate words of different costs', () => {
const collector = suggestionCollector(
'joyfull',
sugOpts({ numSuggestions: 3, filter: (word) => word !== 'joyfully' })
);
collector.add({ word: 'joyful', cost: 100 });
expect(collector.suggestions.length).toBe(1);
collector.add({ word: 'joyful', cost: 75 });
expect(collector.suggestions.length).toBe(1);
expect(collector.suggestions[0].cost).toBe(75);
collector
.add({ word: 'joyfuller', cost: 200 })
.add({ word: 'joyfullest', cost: 300 })
.add({ word: 'joyfulness', cost: 340 })
.add({ word: 'joyful', cost: 85 });
expect(collector.suggestions.length).toBe(3);
expect(collector.suggestions[0].cost).toBe(75);
});
// cspell:ignore wålk
test('that accents are closer', () => {
const trie = Trie.create(sampleWords);
const collector = suggestionCollector('wålk', sugOptsMaxNum(3));
collector.collect(genCompoundableSuggestions(trie.root, collector.word, JOIN_WORDS));
const suggestions = collector.suggestions.map((s) => s.word);
expect(suggestions).toEqual(['walk', 'walks', 'talk']);
});
// cspell:ignore wâlkéd
test('that multiple accents are closer', () => {
const trie = Trie.create(sampleWords);
const collector = suggestionCollector('wâlkéd', sugOptsMaxNum(3));
collector.collect(genCompoundableSuggestions(trie.root, collector.word, JOIN_WORDS));
const suggestions = collector.suggestions.map((s) => s.word);
expect(suggestions).toEqual(['walked', 'walker', 'talked']);
});
function sr(word: string, cost: number) {
return { word, cost };
}
// cspell:ignore walking* *tree talking* *stick running* *pod *trick
test.each`
word | ignoreCase | numSuggestions | changeLimit | expected
${'Runningpod'} | ${false} | ${4} | ${1} | ${[sr('RunningPod', 1)]}
${'runningtree'} | ${undefined} | ${2} | ${undefined} | ${[sr('runningtree', 0), sr('Runningtree', 1)]}
${'Runningpod'} | ${undefined} | ${5} | ${1} | ${[sr('Runningpod', 0), sr('runningpod', 1), sr('RunningPod', 1), sr('runningPod', 2)]}
${'runningpod'} | ${undefined} | ${2} | ${undefined} | ${[sr('runningpod', 0), sr('runningPod', 1)]}
${'walkingstick'} | ${undefined} | ${2} | ${undefined} | ${[sr('walkingstick', 0), sr('talkingstick', 99)]}
${'walkingtree'} | ${undefined} | ${2} | ${undefined} | ${[sr('talkingtree', 99), sr('walkingstick', 359)]}
${'running'} | ${undefined} | ${2} | ${undefined} | ${[sr('running', 0), sr('Running', 1)]}
`('test suggestion results $word', ({ word, ignoreCase, numSuggestions, changeLimit, expected }) => {
const trie = parseDictionary(`
walk
Running*
walking*
*stick
talking*
*tree
+Pod
!walkingtree
`);
const collector = suggestionCollector(word, sugOpts({ numSuggestions, changeLimit, ignoreCase }));
trie.genSuggestions(collector);
const r = collector.suggestions;
expect(r).toEqual(expected);
});
test.each`
word | ignoreCase | numSuggestions | changeLimit | expected
${'runningtree'} | ${undefined} | ${2} | ${3} | ${[sr('runningtree', 0), sr('Runningtree', 1)]}
${'Runningpod'} | ${undefined} | ${4} | ${1} | ${[sr('Runningpod', 0), sr('runningpod', 1), sr('RunningPod', 1), sr('runningPod', 2)]}
${'Runningpod'} | ${false} | ${4} | ${1} | ${[sr('RunningPod', 1)]}
${'runningpod'} | ${undefined} | ${4} | ${1} | ${[sr('runningpod', 0), sr('runningPod', 1), sr('Runningpod', 1), sr('RunningPod', 2)]}
${'runningpod'} | ${false} | ${4} | ${1} | ${[sr('RunningPod', 2)]}
${'walkingstick'} | ${undefined} | ${2} | ${3} | ${[sr('walkingstick', 0), sr('talkingstick', 99)]}
${'walkingtree'} | ${undefined} | ${2} | ${4} | ${[sr('talkingtree', 99), sr('walkingstick', 359)]}
${'talkingtrick'} | ${undefined} | ${2} | ${4} | ${[sr('talkingstick', 183), sr('talkingtree', 268)]}
${'running'} | ${undefined} | ${2} | ${3} | ${[sr('running', 0), sr('Running', 1)]}
${'free'} | ${undefined} | ${2} | ${2} | ${[sr('tree', 99)]}
${'stock'} | ${undefined} | ${2} | ${2} | ${[sr('stick', 97)]}
`('test suggestWithCost results $word', ({ word, ignoreCase, numSuggestions, changeLimit, expected }) => {
const trie = parseDictionary(`
walk
Running*
walking*
*stick
talking*
*tree
+Pod
!walkingtree
`);
const r = trie.suggestWithCost(word, { numSuggestions, ignoreCase, changeLimit });
expect(r).toEqual(expected);
});
});
function numSugs(numSuggestions: number): SuggestionOptions {
return { numSuggestions };
}
function sugOpts(opts: Partial<SuggestionCollectorOptions>): SuggestionCollectorOptions {
return {
...defaultOptions,
...clean(opts),
};
}
function sugOptsMaxNum(maxNumSuggestions: number): SuggestionCollectorOptions {
return sugOpts({ numSuggestions: maxNumSuggestions });
}
const sampleWords = [
'walk',
'walked',
'walker',
'walking',
'walks',
'talk',
'talks',
'talked',
'talker',
'talking',
'lift',
'lifts',
'lifted',
'lifter',
'lifting',
'journal',
'journals',
'journalism',
'journalist',
'journalistic',
'journey',
'journeyer',
'journeyman',
'journeymen',
'joust',
'jouster',
'jousting',
'jovial',
'joviality',
'jowl',
'jowly',
'joy',
'joyful',
'joyfuller',
'joyfullest',
'joyfully',
'joyfulness',
'joyless',
'joylessness',
'joyous',
'joyousness',
'joyridden',
'joyride',
'joyrider',
'joyriding',
'joyrode',
'joystick',
];
function clean<T>(t: Partial<T>): Partial<T> {
const r: Partial<T> = {};
for (const k of Object.keys(t) as (keyof T)[]) {
if (t[k] !== undefined) {
r[k] = t[k];
}
}
return r;
} | the_stack |
import { LAppPal } from './lapppal';
export let s_instance: LAppWavFileHandler = null;
export class LAppWavFileHandler {
/**
* クラスのインスタンス(シングルトン)を返す。
* インスタンスが生成されていない場合は内部でインスタンスを生成する。
*
* @return クラスのインスタンス
*/
public static getInstance(): LAppWavFileHandler {
if (s_instance == null) {
s_instance = new LAppWavFileHandler();
}
return s_instance;
}
/**
* クラスのインスタンス(シングルトン)を解放する。
*/
public static releaseInstance(): void {
if (s_instance != null) {
s_instance = void 0;
}
s_instance = null;
}
public update(deltaTimeSeconds: number) {
let goalOffset: number;
let rms: number;
// データロード前/ファイル末尾に達した場合は更新しない
if (
this._pcmData == null ||
this._sampleOffset >= this._wavFileInfo._samplesPerChannel
) {
this._lastRms = 0.0;
return false;
}
// 経過時間後の状態を保持
this._userTimeSeconds += deltaTimeSeconds;
goalOffset = Math.floor(
this._userTimeSeconds * this._wavFileInfo._samplingRate
);
if (goalOffset > this._wavFileInfo._samplesPerChannel) {
goalOffset = this._wavFileInfo._samplesPerChannel;
}
// RMS計測
rms = 0.0;
for (
let channelCount = 0;
channelCount < this._wavFileInfo._numberOfChannels;
channelCount++
) {
for (
let sampleCount = this._sampleOffset;
sampleCount < goalOffset;
sampleCount++
) {
const pcm = this._pcmData[channelCount][sampleCount];
rms += pcm * pcm;
}
}
rms = Math.sqrt(
rms /
(this._wavFileInfo._numberOfChannels *
(goalOffset - this._sampleOffset))
);
this._lastRms = rms;
this._sampleOffset = goalOffset;
return true;
}
public start(filePath: string): void {
// サンプル位参照位置を初期化
this._sampleOffset = 0;
this._userTimeSeconds = 0.0;
// RMS値をリセット
this._lastRms = 0.0;
if (!this.loadWavFile(filePath)) {
return;
}
}
public getRms(): number {
return this._lastRms;
}
public loadWavFile(filePath: string): boolean {
let ret = false;
if (this._pcmData != null) {
this.releasePcmData();
}
// ファイルロード
const asyncFileLoad = async () => {
return fetch(filePath).then(responce => {
return responce.arrayBuffer();
});
};
const asyncWavFileManager = (async () => {
this._byteReader._fileByte = await asyncFileLoad();
this._byteReader._fileDataView = new DataView(this._byteReader._fileByte);
this._byteReader._fileSize = this._byteReader._fileByte.byteLength;
this._byteReader._readOffset = 0;
// ファイルロードに失敗しているか、先頭のシグネチャ"RIFF"を入れるサイズもない場合は失敗
if (
this._byteReader._fileByte == null ||
this._byteReader._fileSize < 4
) {
return false;
}
// ファイル名
this._wavFileInfo._fileName = filePath;
try {
// シグネチャ "RIFF"
if (!this._byteReader.getCheckSignature('RIFF')) {
ret = false;
throw new Error('Cannot find Signeture "RIFF".');
}
// ファイルサイズ-8(読み飛ばし)
this._byteReader.get32LittleEndian();
// シグネチャ "WAVE"
if (!this._byteReader.getCheckSignature('WAVE')) {
ret = false;
throw new Error('Cannot find Signeture "WAVE".');
}
// シグネチャ "fmt "
if (!this._byteReader.getCheckSignature('fmt ')) {
ret = false;
throw new Error('Cannot find Signeture "fmt".');
}
// fmtチャンクサイズ
const fmtChunkSize = this._byteReader.get32LittleEndian();
// フォーマットIDは1(リニアPCM)以外受け付けない
if (this._byteReader.get16LittleEndian() != 1) {
ret = false;
throw new Error('File is not linear PCM.');
}
// チャンネル数
this._wavFileInfo._numberOfChannels = this._byteReader.get16LittleEndian();
// サンプリングレート
this._wavFileInfo._samplingRate = this._byteReader.get32LittleEndian();
// データ速度[byte/sec](読み飛ばし)
this._byteReader.get32LittleEndian();
// ブロックサイズ(読み飛ばし)
this._byteReader.get16LittleEndian();
// 量子化ビット数
this._wavFileInfo._bitsPerSample = this._byteReader.get16LittleEndian();
// fmtチャンクの拡張部分の読み飛ばし
if (fmtChunkSize > 16) {
this._byteReader._readOffset += fmtChunkSize - 16;
}
// "data"チャンクが出現するまで読み飛ばし
while (
!this._byteReader.getCheckSignature('data') &&
this._byteReader._readOffset < this._byteReader._fileSize
) {
this._byteReader._readOffset +=
this._byteReader.get32LittleEndian() + 4;
}
// ファイル内に"data"チャンクが出現しなかった
if (this._byteReader._readOffset >= this._byteReader._fileSize) {
ret = false;
throw new Error('Cannot find "data" Chunk.');
}
// サンプル数
{
const dataChunkSize = this._byteReader.get32LittleEndian();
this._wavFileInfo._samplesPerChannel =
(dataChunkSize * 8) /
(this._wavFileInfo._bitsPerSample *
this._wavFileInfo._numberOfChannels);
}
// 領域確保
this._pcmData = new Array(this._wavFileInfo._numberOfChannels);
for (
let channelCount = 0;
channelCount < this._wavFileInfo._numberOfChannels;
channelCount++
) {
this._pcmData[channelCount] = new Float32Array(
this._wavFileInfo._samplesPerChannel
);
}
// 波形データ取得
for (
let sampleCount = 0;
sampleCount < this._wavFileInfo._samplesPerChannel;
sampleCount++
) {
for (
let channelCount = 0;
channelCount < this._wavFileInfo._numberOfChannels;
channelCount++
) {
this._pcmData[channelCount][sampleCount] = this.getPcmSample();
}
}
ret = true;
} catch (e) {
console.log(e);
}
})();
return ret;
}
public getPcmSample(): number {
let pcm32;
// 32ビット幅に拡張してから-1~1の範囲に丸める
switch (this._wavFileInfo._bitsPerSample) {
case 8:
pcm32 = this._byteReader.get8() - 128;
pcm32 <<= 24;
break;
case 16:
pcm32 = this._byteReader.get16LittleEndian() << 16;
break;
case 24:
pcm32 = this._byteReader.get24LittleEndian() << 8;
break;
default:
// 対応していないビット幅
pcm32 = 0;
break;
}
return pcm32 / 2147483647; //Number.MAX_VALUE;
}
public releasePcmData(): void {
for (
let channelCount = 0;
channelCount < this._wavFileInfo._numberOfChannels;
channelCount++
) {
delete this._pcmData[channelCount];
}
delete this._pcmData;
this._pcmData = null;
}
constructor() {
this._pcmData = null;
this._userTimeSeconds = 0.0;
this._lastRms = 0.0;
this._sampleOffset = 0.0;
this._wavFileInfo = new WavFileInfo();
this._byteReader = new ByteReader();
}
_pcmData: Array<Float32Array>;
_userTimeSeconds: number;
_lastRms: number;
_sampleOffset: number;
_wavFileInfo: WavFileInfo;
_byteReader: ByteReader;
_loadFiletoBytes = (arrayBuffer: ArrayBuffer, length: number): void => {
this._byteReader._fileByte = arrayBuffer;
this._byteReader._fileDataView = new DataView(this._byteReader._fileByte);
this._byteReader._fileSize = length;
};
}
export class WavFileInfo {
constructor() {
this._fileName = '';
this._numberOfChannels = 0;
this._bitsPerSample = 0;
this._samplingRate = 0;
this._samplesPerChannel = 0;
}
_fileName: string; ///< ファイル名
_numberOfChannels: number; ///< チャンネル数
_bitsPerSample: number; ///< サンプルあたりビット数
_samplingRate: number; ///< サンプリングレート
_samplesPerChannel: number; ///< 1チャンネルあたり総サンプル数
}
export class ByteReader {
constructor() {
this._fileByte = null;
this._fileDataView = null;
this._fileSize = 0;
this._readOffset = 0;
}
/**
* @brief 8ビット読み込み
* @return Csm::csmUint8 読み取った8ビット値
*/
public get8(): number {
const ret = this._fileDataView.getUint8(this._readOffset);
this._readOffset++;
return ret;
}
/**
* @brief 16ビット読み込み(リトルエンディアン)
* @return Csm::csmUint16 読み取った16ビット値
*/
public get16LittleEndian(): number {
const ret =
(this._fileDataView.getUint8(this._readOffset + 1) << 8) |
this._fileDataView.getUint8(this._readOffset);
this._readOffset += 2;
return ret;
}
/**
* @brief 24ビット読み込み(リトルエンディアン)
* @return Csm::csmUint32 読み取った24ビット値(下位24ビットに設定)
*/
public get24LittleEndian(): number {
const ret =
(this._fileDataView.getUint8(this._readOffset + 2) << 16) |
(this._fileDataView.getUint8(this._readOffset + 1) << 8) |
this._fileDataView.getUint8(this._readOffset);
this._readOffset += 3;
return ret;
}
/**
* @brief 32ビット読み込み(リトルエンディアン)
* @return Csm::csmUint32 読み取った32ビット値
*/
public get32LittleEndian(): number {
const ret =
(this._fileDataView.getUint8(this._readOffset + 3) << 24) |
(this._fileDataView.getUint8(this._readOffset + 2) << 16) |
(this._fileDataView.getUint8(this._readOffset + 1) << 8) |
this._fileDataView.getUint8(this._readOffset);
this._readOffset += 4;
return ret;
}
/**
* @brief シグネチャの取得と参照文字列との一致チェック
* @param[in] reference 検査対象のシグネチャ文字列
* @retval true 一致している
* @retval false 一致していない
*/
public getCheckSignature(reference: string): boolean {
const getSignature: Uint8Array = new Uint8Array(4);
const referenceString: Uint8Array = new TextEncoder().encode(reference);
if (reference.length != 4) {
return false;
}
for (let signatureOffset = 0; signatureOffset < 4; signatureOffset++) {
getSignature[signatureOffset] = this.get8();
}
return (
getSignature[0] == referenceString[0] &&
getSignature[1] == referenceString[1] &&
getSignature[2] == referenceString[2] &&
getSignature[3] == referenceString[3]
);
}
_fileByte: ArrayBuffer; ///< ロードしたファイルのバイト列
_fileDataView: DataView;
_fileSize: number; ///< ファイルサイズ
_readOffset: number; ///< ファイル参照位置
} | the_stack |
import { create, tsx, diffProperty } from '@dojo/framework/core/vdom';
import { RenderResult } from '@dojo/framework/core/interfaces';
import { createICacheMiddleware } from '@dojo/framework/core/middleware/icache';
import { createResourceMiddleware } from '@dojo/framework/core/middleware/resources';
import theme from '../middleware/theme';
import focus from '@dojo/framework/core/middleware/focus';
import { flat } from '@dojo/framework/shim/array';
import { Keys } from '../common/util';
import Icon from '../icon';
import Checkbox from '../checkbox';
import { ListItem } from '../list';
import * as css from '../theme/default/tree.m.css';
import LoadingIndicator from '../loading-indicator';
export interface TreeNodeOption {
id: string;
parent: string;
value: string;
hasChildren: boolean;
}
export interface TreeProperties {
checkable?: boolean;
selectable?: boolean;
checkedIds?: string[];
expandedIds?: string[];
initialChecked?: string[];
initialExpanded?: string[];
value?: string;
disabledIds?: string[];
parentSelection?: boolean;
onValue?(id: string): void;
onCheck?(id: string[]): void;
onExpand?(id: string[]): void;
}
export interface TreeChildren {
(node: TreeNodeOption): RenderResult;
}
interface TreeCache {
activeNode?: string;
value?: string;
checkedIds: string[];
expandedIds: string[];
}
const resource = createResourceMiddleware<TreeNodeOption>();
const icache = createICacheMiddleware<TreeCache>();
const factory = create({ theme, icache, diffProperty, focus, resource })
.properties<TreeProperties>()
.children<TreeChildren | undefined>();
export default factory(function Tree({
middleware: { theme, icache, diffProperty, resource },
properties,
children
}) {
diffProperty('value', properties, ({ value: current }, { value: next }) => {
if ((current || next) && current !== next) {
icache.set('value', next);
}
});
diffProperty(
'initialChecked',
properties,
({ initialChecked: current }, { initialChecked: next }) => {
if ((current || next) && current !== next) {
icache.set('checkedIds', next || []);
}
}
);
diffProperty(
'initialExpanded',
properties,
({ initialExpanded: current }, { initialExpanded: next }) => {
if ((current || next) && current !== next) {
icache.set('expandedIds', next || []);
}
}
);
const {
checkable = false,
selectable = false,
checkedIds,
expandedIds,
onValue,
onCheck,
onExpand,
disabledIds,
resource: { template },
parentSelection = false,
theme: themeProp,
classes,
variant
} = properties();
const {
get,
template: { read }
} = resource.template(template);
const themedCss = theme.classes(css);
const defaultRenderer = (n: TreeNodeOption) => n.value;
const [itemRenderer] = children();
const activeNode = icache.get('activeNode');
const selectedNode = icache.get('value');
if (checkedIds) {
icache.set('checkedIds', checkedIds);
}
if (expandedIds) {
icache.set('expandedIds', expandedIds);
}
const expandedNodes = icache.getOrSet('expandedIds', []);
const checkedNodes = icache.getOrSet('checkedIds', []);
function activateNode(id: string) {
icache.set('activeNode', id);
}
function selectNode(id: string) {
icache.set('value', id);
onValue && onValue(id);
}
function checkNode(id: string, checked: boolean) {
if (checked) {
icache.set('checkedIds', (currentChecked = []) => [...currentChecked, id]);
} else {
icache.set('checkedIds', (currentChecked = []) =>
currentChecked ? currentChecked.filter((n) => n !== id) : []
);
}
onCheck && onCheck(icache.get('checkedIds') || []);
}
function expandNode(id: string) {
icache.set('expandedIds', (currentExpanded = []) => [...currentExpanded, id]);
onExpand && onExpand(icache.get('expandedIds') || []);
}
function collapseNode(id: string) {
icache.set('expandedIds', (currentExpanded = []) =>
currentExpanded ? currentExpanded.filter((n) => n !== id) : []
);
onExpand && onExpand(icache.get('expandedIds') || []);
}
function createNodeFlatMap(nodeId: string = 'root'): TreeNodeOption[] {
let nodes: TreeNodeOption[] = [];
const options = resource.createOptions((curr, next) => ({ ...curr, ...next }));
const {
meta: { total }
} = get(options({ query: { parent: nodeId } }), { read, meta: true });
if (total) {
const results = get(options({ size: total }), { read });
const queriedNodes = results ? flat(results) : [];
queriedNodes.forEach((node) => {
nodes.push(node);
if (expandedNodes.indexOf(node.id) !== -1) {
nodes = [...nodes, ...createNodeFlatMap(node.id)];
}
});
}
return nodes;
}
function onKeyDown(event: KeyboardEvent) {
event.stopPropagation();
const nodes = createNodeFlatMap();
const activeIndex = nodes.findIndex((node) => node.id === activeNode);
switch (event.which) {
// select
case Keys.Enter:
case Keys.Space:
event.preventDefault();
if (activeNode && selectedNode !== activeNode && !nodes[activeIndex].hasChildren) {
selectable && selectNode(activeNode);
checkable && checkNode(activeNode, !checkedNodes.includes(activeNode));
}
break;
// next
case Keys.Down:
event.preventDefault();
activateNode(nodes[(activeIndex + 1) % nodes.length].id);
break;
// previous
case Keys.Up:
event.preventDefault();
if (activeIndex - 1 < 0) {
activateNode(nodes[nodes.length - 1].id);
} else {
activateNode(nodes[activeIndex - 1].id);
}
break;
// expand
case Keys.Right:
event.preventDefault();
if (
activeNode &&
!expandedNodes.includes(activeNode) &&
nodes[activeIndex].hasChildren
) {
expandNode(activeNode);
}
break;
// collapse
case Keys.Left:
event.preventDefault();
if (activeNode && expandedNodes.includes(activeNode)) {
collapseNode(activeNode);
}
break;
}
}
function mapNodeTree(nodeId: string = 'root') {
const { meta } = get(
{ size: 30, offset: 0, query: { parent: nodeId } },
{ read, meta: true }
);
if (meta.status !== 'read') {
return <LoadingIndicator theme={themeProp} classes={classes} variant={variant} />;
}
const results = get(
{
size: meta.total || 0,
offset: 0,
query: { parent: nodeId }
},
{ read }
);
const nodes = results ? flat(results) : [];
return (
<ol
classes={[
nodeId === 'root' ? themedCss.root : null,
themedCss.nodeParent,
theme.variant()
]}
onkeydown={onKeyDown}
tabIndex={0}
role={nodeId === 'root' ? 'tree' : 'group'}
>
{nodes.map((node) => {
const isExpanded = expandedNodes.includes(node.id);
return (
<li
classes={[
themedCss.node,
node.hasChildren && themedCss.leaf,
selectable && themedCss.selectable,
node.id === selectedNode && themedCss.selected
]}
role={'treeitem'}
>
<TreeNode
classes={classes}
theme={themeProp}
variant={variant}
activeNode={activeNode}
checkable={checkable}
selectable={selectable}
selected={node.id === selectedNode}
checked={checkedNodes.includes(node.id)}
value={selectedNode}
disabled={(disabledIds || []).includes(node.id)}
expanded={isExpanded}
parentSelection={parentSelection}
node={node}
onActive={() => activateNode(node.id)}
onValue={() => selectNode(node.id)}
onCheck={(checked: boolean) => checkNode(node.id, checked)}
onExpand={(expanded) => {
if (expanded) {
expandNode(node.id);
} else {
collapseNode(node.id);
}
}}
>
{itemRenderer || defaultRenderer}
</TreeNode>
{isExpanded && mapNodeTree(node.id)}
</li>
);
})}
</ol>
);
}
return mapNodeTree();
});
interface TreeNodeProperties {
checkable: boolean;
checked?: boolean;
selectable?: boolean;
disabled?: boolean;
activeNode?: string;
value?: string;
expanded: boolean;
selected: boolean;
parentSelection?: boolean;
node: TreeNodeOption;
onActive(): void;
onValue(): void;
onCheck(checked: boolean): void;
onExpand(expanded: boolean): void;
}
interface TreeNodeChildren {
(node: TreeNodeOption): RenderResult;
}
const treeNodeFactory = create({ theme })
.properties<TreeNodeProperties>()
.children<TreeNodeChildren>();
export const TreeNode = treeNodeFactory(function TreeNode({
middleware: { theme },
properties,
children
}) {
const {
node,
checkable,
selectable,
activeNode,
checked,
disabled,
expanded,
selected,
onActive,
onValue,
onCheck,
onExpand,
parentSelection,
theme: themeProp,
classes,
variant
} = properties();
const [itemRenderer] = children();
const themedCss = theme.classes(css);
const isActive = node.id === activeNode;
const isExpandable = node.hasChildren;
return (
<ListItem
active={isActive}
selected={selected}
onRequestActive={() => {
onActive();
}}
onSelect={() => {
isExpandable && onExpand(!expanded);
if (parentSelection || !isExpandable) {
selectable && onValue();
checkable && onCheck(!checked);
}
}}
disabled={disabled}
widgetId={node.id}
classes={classes}
theme={themeProp}
variant={variant}
>
<div classes={themedCss.contentWrapper}>
<div classes={themedCss.content}>
{isExpandable && (
<div classes={themedCss.expander}>
<Icon
type={expanded ? 'downIcon' : 'rightIcon'}
theme={themeProp}
classes={classes}
variant={variant}
/>
</div>
)}
{checkable && (parentSelection || !isExpandable) && (
<div
onpointerdown={(event: Event) => {
// don't allow the check's activity to effect our expand/collapse
event.stopPropagation();
}}
>
<Checkbox
checked={!!checked}
onValue={(value) => {
onCheck(value);
}}
disabled={disabled}
classes={classes}
theme={themeProp}
variant={variant}
/>
</div>
)}
<div classes={themedCss.title}>{itemRenderer(node)}</div>
</div>
</div>
</ListItem>
);
}); | the_stack |
import { IDatabaseChanges } from "./IDatabaseChanges";
import { IChangesObservable } from "./IChangesObservable";
import { IndexChange, TopologyChange } from "./IndexChange";
import { CounterChange } from "./CounterChange";
import { DocumentChange } from "./DocumentChange";
import { OperationStatusChange } from "./OperationStatusChange";
import { DatabaseConnectionState } from "./DatabaseConnectionState";
import { ChangesObservable } from "./ChangesObservable";
import { throwError } from "../../Exceptions";
import * as semaphore from "semaphore";
import * as WebSocket from "ws";
import { StringUtil } from "../../Utility/StringUtil";
import { EventEmitter } from "events";
import * as PromiseUtil from "../../Utility/PromiseUtil";
import { IDefer } from "../../Utility/PromiseUtil";
import { acquireSemaphore } from "../../Utility/SemaphoreUtil";
import { Certificate } from "../../Auth/Certificate";
import { ObjectUtil } from "../../Utility/ObjectUtil";
import CurrentIndexAndNode from "../../Http/CurrentIndexAndNode";
import { RequestExecutor } from "../../Http/RequestExecutor";
import { DocumentConventions } from "../Conventions/DocumentConventions";
import { ServerNode } from "../../Http/ServerNode";
import { ObjectTypeDescriptor, ServerResponse } from "../../Types";
import { UpdateTopologyParameters } from "../../Http/UpdateTopologyParameters";
import { TypeUtil } from "../../Utility/TypeUtil";
import { TimeSeriesChange } from "./TimeSeriesChange";
export class DatabaseChanges implements IDatabaseChanges {
private _emitter = new EventEmitter();
private _commandId: number = 0;
private readonly _onConnectionStatusChangedWrapped: () => void;
private _semaphore = semaphore();
private readonly _requestExecutor: RequestExecutor;
private readonly _conventions: DocumentConventions;
private readonly _database: string;
private readonly _onDispose: () => void;
private _client: WebSocket;
private readonly _task;
private _isCanceled = false;
private _tcs: IDefer<IDatabaseChanges>;
private readonly _confirmations: Map<number, { resolve: () => void, reject: () => void }> = new Map();
private readonly _counters: Map<string, DatabaseConnectionState> = new Map(); //TODO: use DatabaseChangesOptions as key?
private _immediateConnection: number = 0;
private _serverNode: ServerNode;
private _nodeIndex: number;
private _url: string;
constructor(requestExecutor: RequestExecutor, databaseName: string, onDispose: () => void, nodeTag: string) {
this._requestExecutor = requestExecutor;
this._conventions = requestExecutor.conventions;
this._database = databaseName;
this._tcs = PromiseUtil.defer<IDatabaseChanges>();
this._onDispose = onDispose;
this._onConnectionStatusChangedWrapped = () => this._onConnectionStatusChanged();
this._emitter.on("connectionStatus", this._onConnectionStatusChangedWrapped);
this._task = this._doWork(nodeTag);
}
public static createClientWebSocket(requestExecutor: RequestExecutor, url: string): WebSocket {
const authOptions = requestExecutor.getAuthOptions();
let options = undefined as WebSocket.ClientOptions;
if (authOptions) {
const certificate = Certificate.createFromOptions(authOptions);
options = certificate.toWebSocketOptions();
}
return new WebSocket(url, options);
}
private async _onConnectionStatusChanged() {
const acquiredSemContext = acquireSemaphore(this._semaphore);
try {
await acquiredSemContext.promise;
if (this.connected) {
this._tcs.resolve(this);
return;
}
if (this._tcs.promise.isFulfilled()) {
this._tcs = PromiseUtil.defer<IDatabaseChanges>();
}
} finally {
acquiredSemContext.dispose();
}
}
public get connected() {
return this._client && this._client.readyState === WebSocket.OPEN;
}
public on(eventName: "connectionStatus", handler: () => void);
public on(eventName: "error", handler: (error: Error) => void);
public on(eventName: "connectionStatus" | "error", handler) {
this._emitter.addListener(eventName, handler);
}
public off(eventName: "connectionStatus", handler: () => void);
public off(eventName: "error", handler: (error: Error) => void);
public off(eventName: "connectionStatus" | "error", handler) {
this._emitter.removeListener(eventName, handler);
}
public ensureConnectedNow(): Promise<IDatabaseChanges> {
return Promise.resolve(this._tcs.promise);
}
public forIndex(indexName: string): IChangesObservable<IndexChange> {
if (StringUtil.isNullOrWhitespace(indexName)) {
throwError("InvalidArgumentException", "IndexName cannot be null or whitespace.");
}
const counter = this._getOrAddConnectionState("indexes/" + indexName,
"watch-index", "unwatch-index", indexName);
return new ChangesObservable<IndexChange, DatabaseConnectionState>("Index", counter,
notification => notification.name
&& notification.name.toLocaleLowerCase() === indexName.toLocaleLowerCase());
}
public get lastConnectionStateException(): Error {
for (const counter of Array.from(this._counters.values())) {
if (counter.lastError) {
return counter.lastError;
}
}
return null;
}
public forDocument(docId: string): IChangesObservable<DocumentChange> {
if (StringUtil.isNullOrWhitespace(docId)) {
throwError("InvalidArgumentException", "DocumentId cannot be null or whitespace.");
}
const counter = this._getOrAddConnectionState("docs/" + docId, "watch-doc", "unwatch-doc", docId);
return new ChangesObservable<DocumentChange, DatabaseConnectionState>("Document", counter,
notification => notification.id && notification.id.toLocaleLowerCase() === docId.toLocaleLowerCase());
}
public forAllDocuments(): IChangesObservable<DocumentChange> {
const counter = this._getOrAddConnectionState("all-docs", "watch-docs",
"unwatch-docs", null);
return new ChangesObservable<DocumentChange, DatabaseConnectionState>("Document", counter,
() => true);
}
public forOperationId(operationId: number): IChangesObservable<OperationStatusChange> {
const counter = this._getOrAddConnectionState("operations/" + operationId,
"watch-operation", "unwatch-operation", operationId.toString());
return new ChangesObservable<OperationStatusChange, DatabaseConnectionState>("Operation", counter,
notification => notification.operationId === operationId);
}
public forAllOperations(): IChangesObservable<OperationStatusChange> {
const counter = this._getOrAddConnectionState("all-operations", "watch-operations",
"unwatch-operations", null);
return new ChangesObservable<OperationStatusChange, DatabaseConnectionState>("Operation", counter,
() => true);
}
public forAllIndexes(): IChangesObservable<IndexChange> {
const counter = this._getOrAddConnectionState("all-indexes", "watch-indexes",
"unwatch-indexes", null);
return new ChangesObservable<IndexChange, DatabaseConnectionState>("Index", counter, () => true);
}
public forDocumentsStartingWith(docIdPrefix: string): IChangesObservable<DocumentChange> {
if (StringUtil.isNullOrWhitespace(docIdPrefix)) {
throwError("InvalidArgumentException", "DocumentId cannot be null or whitespace.");
}
const counter = this._getOrAddConnectionState("prefixes/" + docIdPrefix,
"watch-prefix", "unwatch-prefix", docIdPrefix);
return new ChangesObservable<DocumentChange, DatabaseConnectionState>("Document", counter,
notification => notification.id
&& notification.id.toLocaleLowerCase().startsWith(docIdPrefix.toLocaleLowerCase()));
}
public forDocumentsInCollection(collectionName: string): IChangesObservable<DocumentChange>;
public forDocumentsInCollection<T extends object>(type: ObjectTypeDescriptor<T>);
public forDocumentsInCollection<T extends object = object>(
collectionNameOrDescriptor: string | ObjectTypeDescriptor<T>): IChangesObservable<DocumentChange> {
const collectionName: string = typeof collectionNameOrDescriptor !== "string"
? this._conventions.getCollectionNameForType(collectionNameOrDescriptor)
: collectionNameOrDescriptor;
if (!collectionName) {
throwError("InvalidArgumentException", "CollectionName cannot be null");
}
const counter = this._getOrAddConnectionState("collections/" + collectionName,
"watch-collection", "unwatch-collection", collectionName);
return new ChangesObservable<DocumentChange, DatabaseConnectionState>("Document", counter,
notification => notification.collectionName
&& collectionName.toLocaleLowerCase() === notification.collectionName.toLocaleLowerCase());
}
public dispose(): void {
for (const confirmation of this._confirmations.values()) {
confirmation.reject();
}
this._isCanceled = true;
if (this._client) {
this._client.close();
}
for (const value of this._counters.values()) {
value.dispose();
}
this._counters.clear();
this._emitter.emit("connectionStatus");
this._emitter.removeListener("connectionStatus", this._onConnectionStatusChangedWrapped);
if (this._onDispose) {
this._onDispose();
}
}
private _getOrAddConnectionState(
name: string, watchCommand: string, unwatchCommand, value: string, values: string[] = null):
DatabaseConnectionState {
let newValue = false;
let counter: DatabaseConnectionState;
if (!this._counters.has(name)) {
const connectionState = new DatabaseConnectionState(
() => this._send(watchCommand, value, values), async () => {
try {
if (this.connected) {
await this._send(unwatchCommand, value, values);
}
} catch (e) {
// if we are not connected then we unsubscribed already
// because connections drops with all subscriptions
}
const state = this._counters.get(name);
this._counters.delete(name);
state.dispose();
});
this._counters.set(name, connectionState);
counter = connectionState;
newValue = true;
} else {
counter = this._counters.get(name);
}
if (newValue && this._immediateConnection) {
counter.set(counter.onConnect());
}
return counter;
}
private _send(command: string, value: string, values: string[]): Promise<void> {
return new Promise<void>((async (resolve, reject) => {
let currentCommandId: number;
const acquiredSemContext = acquireSemaphore(this._semaphore, {
timeout: 15000,
contextName: "DatabaseChanges._send()"
});
try {
await acquiredSemContext.promise;
currentCommandId = ++this._commandId;
const payload = {
CommandId: currentCommandId,
Command: command,
Param: value
};
if (values && values.length) {
payload["Params"] = values;
}
this._confirmations.set(currentCommandId, { resolve, reject });
const payloadAsString = JSON.stringify(payload, null, 0);
this._client.send(payloadAsString);
} catch (err) {
if (!this._isCanceled) {
throw err;
}
} finally {
if (acquiredSemContext) {
acquiredSemContext.dispose();
}
}
}));
}
private async _doWork(nodeTag: string): Promise<void> {
let preferredNode: CurrentIndexAndNode;
try {
preferredNode = nodeTag || this._requestExecutor.conventions.disableTopologyUpdates
? await this._requestExecutor.getRequestedNode(nodeTag)
: await this._requestExecutor.getPreferredNode();
this._nodeIndex = preferredNode.currentIndex;
this._serverNode = preferredNode.currentNode;
} catch (e) {
this._emitter.emit("connectionStatus");
this._notifyAboutError(e);
this._tcs.reject(e);
return;
}
this._doWorkInternal();
}
private _doWorkInternal(): void {
if (this._isCanceled) {
return;
}
let wasConnected = false;
if (!this.connected) {
const urlString = this._serverNode.url + "/databases/" + this._database + "/changes";
const url = StringUtil.toWebSocketPath(urlString);
this._client = DatabaseChanges.createClientWebSocket(this._requestExecutor, url);
this._client.on("open", async () => {
wasConnected = true;
this._immediateConnection = 1;
for (const counter of this._counters.values()) {
counter.set(counter.onConnect());
}
this._emitter.emit("connectionStatus");
});
this._client.on("error", async (e) => {
if (wasConnected) {
this._emitter.emit("connectionStatus");
}
wasConnected = false;
try {
this._serverNode = await this._requestExecutor.handleServerNotResponsive(this._url, this._serverNode, this._nodeIndex, e);
} catch (ee) {
if (ee.name === "DatabaseDoesNotExistException") {
e = ee;
throw ee;
} else {
//We don't want to stop observe for changes if server down. we will wait for one to be up
}
}
this._notifyAboutError(e);
});
this._client.on("close", () => {
if (this._reconnectClient()) {
setTimeout(() => this._doWorkInternal(), 1000);
}
for (const confirm of this._confirmations.values()) {
confirm.reject();
}
this._confirmations.clear();
});
this._client.on("message", async (data: WebSocket.Data) => {
await this._processChanges(data as string);
});
}
}
private _reconnectClient(): boolean {
if (this._isCanceled) {
return false;
}
this._client.close();
this._immediateConnection = 0;
return true;
}
private async _processChanges(data: string): Promise<void> {
if (this._isCanceled) {
return;
}
const payloadParsed = JSON.parse(data) as any[];
try {
const messages = Array.isArray(payloadParsed) ? payloadParsed : [payloadParsed];
for (const message of messages) {
const type = message.Type;
if (message.TopologyChange) {
const state = this._getOrAddConnectionState("Topology", "watch-topology-change", "", "");
state.addOnError(TypeUtil.NOOP);
const updateParameters = new UpdateTopologyParameters(this._serverNode);
updateParameters.timeoutInMs = 0;
updateParameters.forceUpdate = true;
updateParameters.debugTag = "watch-topology-change";
// noinspection ES6MissingAwait
this._requestExecutor.updateTopology(updateParameters);
continue;
}
if (!type) {
continue;
}
switch (type) {
case "Error":
const exceptionAsString = message.Exception;
this._notifyAboutError(exceptionAsString);
break;
case "Confirm":
const commandId = message.CommandId;
const confirmationResolver = this._confirmations.get(commandId);
if (confirmationResolver) {
confirmationResolver.resolve();
this._confirmations.delete(commandId);
}
break;
default:
const value = message.Value;
let transformedValue = ObjectUtil.transformObjectKeys(value, { defaultTransform: "camel" });
if (type === "TimeSeriesChange") {
const dateUtil = this._conventions.dateUtil;
const timeSeriesValue = transformedValue as ServerResponse<TimeSeriesChange>;
const overrides: Partial<TimeSeriesChange> = {
from: dateUtil.parse(timeSeriesValue.from),
to: dateUtil.parse(timeSeriesValue.to)
};
transformedValue = Object.assign(transformedValue, overrides);
}
this._notifySubscribers(type, transformedValue, Array.from(this._counters.values()));
break;
}
}
} catch (err) {
this._notifyAboutError(err);
throwError("ChangeProcessingException", "There was an error during notification processing.", err);
}
}
private _notifySubscribers(type: string, value: any, states: DatabaseConnectionState[]): void {
switch (type) {
case "DocumentChange":
states.forEach(state => state.send("Document", value));
break;
case "CounterChange":
states.forEach(state => state.send("Counter", value));
break;
case "TimeSeriesChange":
states.forEach(state => state.send("TimeSeries", value));
break;
case "IndexChange":
states.forEach(state => state.send("Index", value));
break;
case "OperationStatusChange":
states.forEach(state => state.send("Operation", value));
break;
case "TopologyChange":
const topologyChange = value as TopologyChange;
const requestExecutor = this._requestExecutor;
if (requestExecutor) {
const node = new ServerNode({
url: topologyChange.url,
database: topologyChange.database
});
const updateParameters = new UpdateTopologyParameters(node);
updateParameters.timeoutInMs = 0;
updateParameters.forceUpdate = true;
updateParameters.debugTag = "topology-change-notification";
// noinspection JSIgnoredPromiseFromCall
requestExecutor.updateTopology(updateParameters);
}
break;
default:
throwError("NotSupportedException");
}
}
private _notifyAboutError(e: Error): void {
if (this._isCanceled) {
return;
}
this._emitter.emit("error", e);
for (const state of this._counters.values()) {
state.error(e);
}
}
public forAllCounters(): IChangesObservable<CounterChange> {
const counter = this._getOrAddConnectionState("all-counters", "watch-counters", "unwatch-counters", null);
const taskedObservable = new ChangesObservable<CounterChange, DatabaseConnectionState>(
"Counter", counter, notification => true);
return taskedObservable;
}
public forCounter(counterName: string): IChangesObservable<CounterChange> {
if (StringUtil.isNullOrWhitespace(counterName)) {
throwError("InvalidArgumentException", "CounterName cannot be null or whitespace.");
}
const counter = this._getOrAddConnectionState(
"counter/" + counterName, "watch-counter", "unwatch-counter", counterName);
const taskedObservable = new ChangesObservable<CounterChange, DatabaseConnectionState>(
"Counter", counter, notification => StringUtil.equalsIgnoreCase(counterName, notification.name));
return taskedObservable;
}
public forCounterOfDocument(documentId: string, counterName: string): IChangesObservable<CounterChange> {
if (StringUtil.isNullOrWhitespace(documentId)) {
throwError("InvalidArgumentException", "DocumentId cannot be null or whitespace.");
}
if (StringUtil.isNullOrWhitespace(counterName)) {
throwError("InvalidArgumentException", "CounterName cannot be null or whitespace.");
}
const counter = this._getOrAddConnectionState(
"document/" + documentId + "/counter/" + counterName,
"watch-document-counter",
"unwatch-document-counter",
null,
[ documentId, counterName ]);
const taskedObservable = new ChangesObservable<CounterChange, DatabaseConnectionState>(
"Counter", counter,
notification => StringUtil.equalsIgnoreCase(documentId, notification.documentId)
&& StringUtil.equalsIgnoreCase(counterName, notification.name));
return taskedObservable;
}
public forCountersOfDocument(documentId: string): IChangesObservable<CounterChange> {
if (StringUtil.isNullOrWhitespace(documentId)) {
throwError(
"InvalidArgumentException",
"DocumentId cannot be null or whitespace.");
}
const counter = this._getOrAddConnectionState(
"document/" + documentId + "/counter", "watch-document-counters", "unwatch-document-counters", documentId);
const taskedObservable = new ChangesObservable<CounterChange, DatabaseConnectionState>(
"Counter",
counter,
notification => StringUtil.equalsIgnoreCase(documentId, notification.documentId));
return taskedObservable;
}
public forAllTimeSeries(): IChangesObservable<TimeSeriesChange> {
const counter = this._getOrAddConnectionState(
"all-timeseries", "watch-all-timeseries", "unwatch-all-timeseries", null);
const taskedObservable = new ChangesObservable<TimeSeriesChange, DatabaseConnectionState>(
"TimeSeries",
counter,
() => true
);
return taskedObservable;
}
public forTimeSeries(timeSeriesName: string): IChangesObservable<TimeSeriesChange> {
if (StringUtil.isNullOrWhitespace(timeSeriesName)) {
throwError("InvalidArgumentException", "TimeSeriesName cannot be null or whitespace.");
}
const counter = this._getOrAddConnectionState(
"timeseries/" + timeSeriesName, "watch-timeseries", "unwatch-timeseries", timeSeriesName);
const taskedObservable = new ChangesObservable<TimeSeriesChange, DatabaseConnectionState>(
"TimeSeries",
counter,
notification => StringUtil.equalsIgnoreCase(timeSeriesName, notification.name));
return taskedObservable;
}
public forTimeSeriesOfDocument(documentId: string)
public forTimeSeriesOfDocument(documentId: string, timeSeriesName: string)
public forTimeSeriesOfDocument(documentId: string, timeSeriesName?: string) {
if (timeSeriesName) {
return this._forTimeSeriesOfDocumentWithNameInternal(documentId, timeSeriesName);
} else {
return this._forTimeSeriesOfDocumentInternal(documentId);
}
}
private _forTimeSeriesOfDocumentInternal(documentId: string) {
if (StringUtil.isNullOrWhitespace(documentId)) {
throwError("InvalidArgumentException", "DocumentId cannot be null or whitespace.");
}
const counter = this._getOrAddConnectionState(
"document/" + documentId + "/timeseries", "watch-all-document-timeseries", "unwatch-all-document-timeseries", documentId);
const taskedObservable = new ChangesObservable<TimeSeriesChange, DatabaseConnectionState>(
"TimeSeries",
counter,
notification => StringUtil.equalsIgnoreCase(documentId, notification.documentId)
);
return taskedObservable;
}
private _forTimeSeriesOfDocumentWithNameInternal(documentId: string, timeSeriesName: string) {
if (StringUtil.isNullOrWhitespace(documentId)) {
throwError("InvalidArgumentException", "DocumentId cannot be null or whitespace.");
}
if (StringUtil.isNullOrWhitespace(timeSeriesName)) {
throwError("InvalidArgumentException", "TimeSeriesName cannot be null or whitespace.");
}
const counter = this._getOrAddConnectionState(
"document/" + documentId + "/timeseries/" + timeSeriesName,
"watch-document-timeseries",
"unwatch-document-timeseries", null, [ documentId, timeSeriesName ]);
const taskedObservable = new ChangesObservable<TimeSeriesChange, DatabaseConnectionState>(
"TimeSeries",
counter,
notification => StringUtil.equalsIgnoreCase(timeSeriesName, notification.name)
&& StringUtil.equalsIgnoreCase(documentId, notification.documentId)
);
return taskedObservable;
}
} | the_stack |
import {EventEmitter} from '@angular/core';
import {ChartClass, ChartOptions} from 'org_xprof/frontend/app/common/interfaces/chart';
import {TensorflowStatsDataOrNull} from 'org_xprof/frontend/app/common/interfaces/data_table';
import {SimpleDataTable} from 'org_xprof/frontend/app/common/interfaces/data_table';
import {DefaultDataProvider} from 'org_xprof/frontend/app/components/chart/default_data_provider';
import {computeDiffTable} from 'org_xprof/frontend/app/components/chart/table_utils';
declare interface SortEvent {
column: number;
ascending: boolean;
}
const DATA_TABLE_RANK_INDEX = 1;
const DATA_TABLE_DEVICE_PERCENT_INDEX = 10;
const DATA_TABLE_CUMULATIVE_DEVICE_PERCENT_INDEX = 11;
const DATA_TABLE_HOST_PERCENT_INDEX = 12;
const DATA_TABLE_CUMULATIVE_HOST_PERCENT_INDEX = 13;
const DATA_VIEW_CUMULATIVE_DEVICE_PERCENT_INDEX = 10;
const DATA_VIEW_CUMULATIVE_HOST_PERCENT_INDEX = 12;
const MAXIMUM_ROWS = 1000;
const MINIMUM_ROWS = 20;
/** A stats table data provider. */
export class StatsTableDataProvider extends DefaultDataProvider {
diffTable?: google.visualization.DataTable;
hasDiff = false;
sortAscending = true;
sortColumn = -1;
options = {
allowHtml: true,
alternatingRowStyle: false,
showRowNumber: false,
width: '100%',
height: '600px',
cssClassNames: {
'headerCell': 'google-chart-table-header-cell',
'tableCell': 'google-chart-table-table-cell',
},
sort: 'event',
sortAscending: true,
sortColumn: -1,
};
private readonly totalOperationsChanged = new EventEmitter<string>();
override setChart(chart: ChartClass) {
this.chart = chart;
google.visualization.events.addListener(
this.chart, 'sort', (event: SortEvent) => {
this.sortColumn = event.column;
this.sortAscending = event.ascending;
this.update.emit();
});
}
override parseData(data: SimpleDataTable|Array<Array<(string | number)>>|null) {
if (!data) return;
const dataTable = new google.visualization.DataTable(data);
if (this.hasDiff && this.diffTable) {
this.preProcessDiffTable(dataTable, this.diffTable);
} else {
this.preProcessDataTable(dataTable);
}
}
setDiffData(diffData: TensorflowStatsDataOrNull) {
this.diffTable = diffData ?
new google.visualization.DataTable(diffData) :
undefined;
}
override setFilters(filters: google.visualization.DataTableCellFilter[]) {
this.filters = filters;
if (this.dataTable) {
this.update.emit();
}
}
override process(): google.visualization.DataTable|google.visualization.DataView|null {
if (!this.dataTable) {
return null;
}
let dataTable = this.dataTable;
let dataView: google.visualization.DataView|null = null;
if (this.filters && this.filters.length > 0) {
dataView = new google.visualization.DataView(this.dataTable);
dataView.setRows(this.dataTable.getFilteredRows(this.filters));
dataTable = dataView.toDataTable();
}
if (!this.hasDiff) {
dataView = this.formatDataTable(dataTable);
} else {
dataView = this.formatDiffTable(dataTable);
}
this.options.height =
dataView.getNumberOfRows() < MINIMUM_ROWS ? '' : '600px';
return dataView;
}
override getOptions(): ChartOptions|null {
this.options.sortAscending = this.sortAscending;
this.options.sortColumn = this.sortColumn;
return this.options;
}
setTotalOperationsChangedEventListener(callback: Function) {
this.totalOperationsChanged.subscribe(callback);
}
preProcessDataTable(dataTable: google.visualization.DataTable) {
this.dataTable = dataTable.clone();
this.updateTotalOperations(this.dataTable);
const zeroDecimalPtFormatter =
new google.visualization.NumberFormat({'fractionDigits': 0});
zeroDecimalPtFormatter.format(this.dataTable, 5); /** total_time */
zeroDecimalPtFormatter.format(this.dataTable, 6); /** avg_time */
zeroDecimalPtFormatter.format(this.dataTable, 7); /** total_self_time */
zeroDecimalPtFormatter.format(this.dataTable, 8); /** avg_self_time */
const percentFormatter =
new google.visualization.NumberFormat({pattern: '##.#%'});
percentFormatter.format(
this.dataTable, 9); /** device_total_self_time_percent */
percentFormatter.format(
this.dataTable, 11); /** host_total_self_time_percent */
/**
* Format tensorcore utilization column if it exists in dataTable.
* This column does not exist in dataTable if the device is not GPU.
*/
for (let i = 0; i < dataTable.getNumberOfColumns(); i++) {
if (this.dataTable.getColumnId(i) === 'gpu_tensorcore_utilization') {
percentFormatter.format(this.dataTable, i);
break;
}
}
this.dataTable.insertColumn(1, 'number', 'Rank');
}
preProcessDiffTable(
dataTable: google.visualization.DataTable,
diffTable: google.visualization.DataTable) {
const sortColumn = [{column: 1, desc: false}];
const hiddenColumn = [0, 4, 5, 6, 7, 10, 12];
const formatDiffInfo = [
{
rangeMin: 0,
rangeMax: 7,
hasColor: false,
isLargeBetter: false,
},
{
rangeMin: 8,
rangeMax: 12,
hasColor: true,
isLargeBetter: false,
},
{
rangeMin: 13,
hasColor: true,
isLargeBetter: true,
},
];
const formatValueInfo = [
{
rangeMin: 0,
rangeMax: 8,
multiplier: 1,
fixed: 0,
suffix: '',
},
{
rangeMin: 9,
rangeMax: 12,
multiplier: 100,
fixed: 1,
suffix: '%',
},
{
rangeMin: 13,
multiplier: 1,
fixed: 1,
suffix: '',
},
];
const dataView = computeDiffTable(
/* oldTable= */ diffTable,
/* newTable= */ dataTable,
/* referenceCol= */ 3,
/* comparisonCol= */ 8,
/* addColumnType= */ 'number',
/* addColumnLabel= */ 'Diff total self time',
/* sortColumn= */ sortColumn,
/* hiddenColumns= */ hiddenColumn,
/* formatDiffInfo= */ formatDiffInfo,
/* formatValueInfo= */ formatValueInfo);
if (!dataView) {
return;
}
this.dataTable = dataView.toDataTable();
if (!this.dataTable) {
return;
}
this.updateTotalOperations(this.dataTable);
}
formatDataTable(dataTable: google.visualization.DataTable):
google.visualization.DataView {
let sortColumn = this.sortColumn + 1;
if (this.sortColumn === 0 ||
this.sortColumn === DATA_VIEW_CUMULATIVE_DEVICE_PERCENT_INDEX ||
this.sortColumn === DATA_VIEW_CUMULATIVE_HOST_PERCENT_INDEX) {
sortColumn = this.sortColumn;
}
const sortedIndex = dataTable.getSortedRows({
column: sortColumn,
desc: !this.sortAscending,
});
let sumOfDevice = 0;
let sumOfHost = 0;
if (sortColumn === 0 && !this.sortAscending) {
let n = sortedIndex.length;
for (const v of sortedIndex) {
dataTable.setCell(v, DATA_TABLE_RANK_INDEX, n--);
sumOfDevice += dataTable.getValue(v, DATA_TABLE_DEVICE_PERCENT_INDEX);
dataTable.setCell(
v, DATA_TABLE_CUMULATIVE_DEVICE_PERCENT_INDEX, sumOfDevice);
sumOfHost += dataTable.getValue(v, DATA_TABLE_HOST_PERCENT_INDEX);
dataTable.setCell(
v, DATA_TABLE_CUMULATIVE_HOST_PERCENT_INDEX, sumOfHost);
}
} else {
for (const [index, v] of sortedIndex.entries()) {
dataTable.setCell(v, DATA_TABLE_RANK_INDEX, index + 1);
sumOfDevice += dataTable.getValue(v, DATA_TABLE_DEVICE_PERCENT_INDEX);
if (sumOfDevice > 100) {
sumOfDevice = 100;
}
dataTable.setCell(
v, DATA_TABLE_CUMULATIVE_DEVICE_PERCENT_INDEX, sumOfDevice);
sumOfHost += dataTable.getValue(v, DATA_TABLE_HOST_PERCENT_INDEX);
if (sumOfHost > 100) {
sumOfHost = 100;
}
dataTable.setCell(
v, DATA_TABLE_CUMULATIVE_HOST_PERCENT_INDEX, sumOfHost);
}
if (!this.sortAscending &&
(this.sortColumn === DATA_VIEW_CUMULATIVE_DEVICE_PERCENT_INDEX ||
this.sortColumn === DATA_VIEW_CUMULATIVE_HOST_PERCENT_INDEX)) {
let sumOfPercent =
this.sortColumn === DATA_VIEW_CUMULATIVE_DEVICE_PERCENT_INDEX ?
sumOfDevice :
sumOfHost;
const index =
this.sortColumn === DATA_VIEW_CUMULATIVE_DEVICE_PERCENT_INDEX ?
DATA_TABLE_CUMULATIVE_DEVICE_PERCENT_INDEX :
DATA_TABLE_CUMULATIVE_HOST_PERCENT_INDEX;
for (const v of sortedIndex) {
dataTable.setCell(v, index, sumOfPercent);
sumOfPercent -= dataTable.getValue(v, index - 1);
if (sumOfPercent < 0) {
sumOfPercent = 0;
}
}
}
}
const percentFormatter =
new google.visualization.NumberFormat({pattern: '##.#%'});
percentFormatter.format(
dataTable, DATA_TABLE_CUMULATIVE_DEVICE_PERCENT_INDEX);
percentFormatter.format(
dataTable, DATA_TABLE_CUMULATIVE_HOST_PERCENT_INDEX);
const dataView = new google.visualization.DataView(dataTable);
dataView.setRows(sortedIndex);
dataView.hideColumns([0]);
return dataView;
}
formatDiffTable(dataTable: google.visualization.DataTable):
google.visualization.DataView {
const dataView = new google.visualization.DataView(dataTable);
if (this.sortColumn >= 0) {
const sortedIndex = dataTable.getSortedRows({
column: this.sortColumn,
desc: !this.sortAscending,
});
dataView.setRows(sortedIndex);
}
return dataView;
}
updateTotalOperations(dataTable: google.visualization.DataTable) {
const totalOperations = dataTable.getNumberOfRows();
if (totalOperations > MAXIMUM_ROWS) {
this.totalOperationsChanged.emit(String(totalOperations));
dataTable.removeRows(MAXIMUM_ROWS, totalOperations - MAXIMUM_ROWS);
} else {
this.totalOperationsChanged.emit('');
}
}
} | the_stack |
import { symbolKey, tsUtils } from '@neo-one/ts-utils';
import { utils } from '@neo-one/utils';
import _ from 'lodash';
import ts from 'typescript';
import { Context } from '../../Context';
import { createMemoized, nodeKey, typeKey } from '../../utils';
import { Builtin, isBuiltinValueObject } from './types';
const getMember = (sym: ts.Symbol, name: string) => tsUtils.symbol.getMemberOrThrow(sym, name);
const getExportOrMember = (sym: ts.Symbol, name: string) => {
const member = tsUtils.symbol.getMember(sym, name);
return member === undefined ? tsUtils.symbol.getExportOrThrow(sym, name) : member;
};
const findNonNull = <T>(value: ReadonlyArray<T | undefined>): T | undefined => value.find((val) => val !== undefined);
const throwIfNull = <T>(value: T | undefined | null): T => {
if (value == undefined) {
/* istanbul ignore next */
throw new Error('Something went wrong.');
}
return value;
};
export class Builtins {
private readonly builtinMembers: Map<ts.Symbol, Map<ts.Symbol, Builtin>> = new Map();
private readonly allBuiltinMembers: Map<ts.Symbol, Builtin> = new Map();
private readonly builtinInterfaces: Map<ts.Symbol, Builtin> = new Map();
private readonly builtinValues: Map<ts.Symbol, Builtin> = new Map();
private readonly builtinOverrides: Map<ts.Symbol, ts.Symbol> = new Map();
private readonly memoized = createMemoized();
public constructor(private readonly context: Context) {}
public isBuiltinSymbol(symbol: ts.Symbol | undefined): boolean {
return symbol !== undefined && (this.builtinValues.has(symbol) || this.builtinInterfaces.has(symbol));
}
public isBuiltinIdentifier(value: string): boolean {
return (
this.getAnyInterfaceSymbolMaybe(value) !== undefined ||
this.getAnyTypeSymbolMaybe(value) !== undefined ||
this.getAnyValueSymbolMaybe(value) !== undefined
);
}
public isBuiltinFile(file: ts.SourceFile): boolean {
return this.getContract() === file;
}
public getMember(value: ts.Node, prop: ts.Node): Builtin | undefined {
return this.memoized('get-member', `${nodeKey(value)}:${nodeKey(prop)}`, () => {
const propSymbol = this.context.analysis.getSymbol(prop);
if (propSymbol === undefined) {
return undefined;
}
const valueSymbol = this.context.analysis.getTypeSymbol(value);
if (valueSymbol === undefined) {
return this.allBuiltinMembers.get(propSymbol);
}
// Super hacky - only works for the special way smart contracts are compiled.
if (!tsUtils.guards.isSuperExpression(value)) {
const overridenMember = this.walkOverridesForMember(valueSymbol, propSymbol);
if (overridenMember !== undefined) {
return overridenMember;
}
}
const members = this.getAllMembers(valueSymbol);
return members.get(propSymbol);
});
}
public getOnlyMember(value: string, name: string): Builtin | undefined {
return this.getOnlyMemberBase(value, name, (result) => result[1]);
}
public getOnlyMemberSymbol(value: string, name: string): ts.Symbol {
return throwIfNull(this.getOnlyMemberBase(value, name, (result) => result[0]));
}
public getMembers<T extends Builtin>(
name: string,
isMember: (builtin: Builtin) => builtin is T,
isEligible: (builtin: T) => boolean,
symbolMembers = false,
// tslint:disable-next-line: readonly-array
): ReadonlyArray<[string, T]> {
const filterPseudoSymbol = (symbol: ts.Symbol, key: string) => {
const symbolSymbol = this.getInterfaceSymbolBase('SymbolConstructor', this.getGlobals());
return tsUtils.symbol.getMember(symbolSymbol, key) !== symbol;
};
const isSymbolKey = (key: string) => key.startsWith('__@');
let testKey = (key: string) => !isSymbolKey(key);
let modifyKey = (key: string) => key;
if (symbolMembers) {
testKey = isSymbolKey;
modifyKey = (key) => key.slice(3);
}
const members = this.getAllMembers(this.getAnyInterfaceSymbol(name));
const mutableMembers: Array<[string, T]> = [];
members.forEach((builtin, memberSymbol) => {
const memberName = tsUtils.symbol.getName(memberSymbol);
if (
isMember(builtin) &&
filterPseudoSymbol(memberSymbol, memberName) &&
testKey(memberName) &&
isEligible(builtin)
) {
mutableMembers.push([modifyKey(memberName), builtin]);
}
});
return mutableMembers;
}
public getInterface(value: ts.Node): Builtin | undefined {
const valueSymbol = this.context.analysis.getSymbol(value);
if (valueSymbol === undefined) {
return undefined;
}
return this.builtinInterfaces.get(valueSymbol);
}
public getInterfaceSymbol(value: string): ts.Symbol {
return this.getAnyInterfaceSymbol(value);
}
public getValue(value: ts.Node): Builtin | undefined {
const valueSymbol = this.context.analysis.getSymbol(value);
if (valueSymbol === undefined) {
return undefined;
}
return this.builtinValues.get(valueSymbol);
}
public getValueInterface(value: ts.Node): string | undefined {
const builtinValue = this.getValue(value);
return builtinValue === undefined || !isBuiltinValueObject(builtinValue) ? undefined : builtinValue.type;
}
public getValueSymbol(value: string): ts.Symbol {
return this.getAnyValueSymbol(value);
}
public getTypeSymbol(name: string): ts.Symbol {
return this.getAnyTypeSymbol(name);
}
public isInterface(node: ts.Node, testType: ts.Type, name: string): boolean {
return this.memoized('is-interface', `${typeKey(testType)}:${name}`, () => {
const symbol = this.context.analysis.getSymbolForType(node, testType);
if (symbol === undefined) {
return false;
}
const interfaceSymbol = this.getAnyInterfaceSymbol(name);
return symbol === interfaceSymbol;
});
}
public isType(node: ts.Node, testType: ts.Type, name: string): boolean {
return this.memoized('is-type', `${typeKey(testType)}:${name}`, () => {
const symbol = this.context.analysis.getSymbolForType(node, testType);
if (symbol === undefined) {
return false;
}
if (name === 'Fixed') {
const fixedTagSymbol = this.getAnyInterfaceSymbol('FixedTag');
if (symbol === fixedTagSymbol) {
return true;
}
}
if (name === 'ForwardedValue') {
const forwardedValueTagSymbol = this.getAnyInterfaceSymbol('ForwardedValueTag');
if (symbol === forwardedValueTagSymbol) {
return true;
}
}
const typeSymbol = this.getAnyTypeSymbol(name);
return symbol === typeSymbol;
});
}
public isValue(node: ts.Node, name: string): boolean {
return this.memoized('is-value', `${nodeKey(node)}:${name}`, () => {
const symbol = this.context.analysis.getSymbol(node);
if (symbol === undefined) {
return false;
}
const valueSymbol = this.getAnyValueSymbol(name);
return symbol === valueSymbol;
});
}
public addMember(valueSymbol: ts.Symbol, memberSymbol: ts.Symbol, builtin: Builtin): void {
let members = this.builtinMembers.get(valueSymbol);
if (members === undefined) {
members = new Map();
this.builtinMembers.set(valueSymbol, members);
}
members.set(memberSymbol, builtin);
this.allBuiltinMembers.set(memberSymbol, builtin);
const memberSymbolName = tsUtils.symbol.getName(memberSymbol);
if (memberSymbolName.startsWith('__@')) {
const symbolSymbol = this.getInterfaceSymbolBase('SymbolConstructor', this.getGlobals());
const memberSymbolSymbol = getMember(symbolSymbol, memberSymbolName.slice(3));
members.set(memberSymbolSymbol, builtin);
this.allBuiltinMembers.set(memberSymbolSymbol, builtin);
}
}
public addOverride(superSymbol: ts.Symbol, overrideSymbol: ts.Symbol): void {
this.builtinOverrides.set(superSymbol, overrideSymbol);
}
public addGlobalMember(value: string, member: string, builtin: Builtin): void {
this.addMemberBase(value, member, builtin, this.getGlobals());
}
public addContractMember(value: string, member: string, builtin: Builtin): void {
this.addMemberBase(value, member, builtin, this.getContract());
}
public addInterface(value: string, builtin: Builtin): void {
this.addInterfaceBase(value, builtin, this.getGlobals());
}
public addContractInterface(value: string, builtin: Builtin): void {
this.addInterfaceBase(value, builtin, this.getContract());
}
public addValue(value: string, builtin: Builtin): void {
this.addValueBase(value, builtin, this.getGlobals());
}
public addTestValue(value: string, builtin: Builtin): void {
const file = this.getTestGlobals();
if (file === undefined) {
return;
}
this.addValueBase(value, builtin, file);
}
public addContractValue(value: string, builtin: Builtin): void {
this.addValueBase(value, builtin, this.getContract());
}
private walkOverridesForMember(valueSymbol: ts.Symbol, propSymbol: ts.Symbol): Builtin | undefined {
const overrideValueSymbol = this.builtinOverrides.get(valueSymbol);
if (overrideValueSymbol === undefined) {
return undefined;
}
let overridePropSymbol = this.builtinOverrides.get(propSymbol);
if (overridePropSymbol === undefined) {
overridePropSymbol = propSymbol;
}
const member = this.walkOverridesForMember(overrideValueSymbol, overridePropSymbol);
if (member !== undefined) {
return member;
}
const overridenMembers = this.getAllMembers(overrideValueSymbol);
return overridenMembers.get(overridePropSymbol);
}
private getOnlyMemberBase<T>(
value: string,
name: string,
getValue: (value: readonly [ts.Symbol, Builtin]) => T,
): T | undefined {
return this.memoized('only-member-base', `${value}$${name}`, () => {
const symbol = this.getAnyInterfaceOrValueSymbol(value);
const members = this.getAllMembers(symbol);
const result = [...members.entries()].find(([memberSymbol]) => tsUtils.symbol.getName(memberSymbol) === name) as
| undefined
| readonly [ts.Symbol, Builtin];
return result === undefined ? undefined : getValue(result);
});
}
private getAllMembers(symbol: ts.Symbol): Map<ts.Symbol, Builtin> {
return this.memoized('get-all-members', symbolKey(symbol), () => {
const interfaceMembers = this.builtinMembers.get(symbol);
const memberEntries = [...this.getInheritedSymbols(symbol)].reduce(
(acc, parentInterfaceSymbol) => {
const parentInterfaceMembers = this.builtinMembers.get(parentInterfaceSymbol);
if (parentInterfaceMembers === undefined) {
return acc;
}
return [...parentInterfaceMembers.entries()].concat(acc);
},
interfaceMembers === undefined ? [] : [...interfaceMembers.entries()],
);
// @ts-ignore - not sure whats happening here
return new Map(memberEntries);
});
}
private addMemberBase(value: string, member: string, builtin: Builtin, file: ts.SourceFile): void {
let valueSymbol = this.getInterfaceSymbolMaybe(value, file);
let memberSymbol: ts.Symbol;
if (valueSymbol === undefined) {
valueSymbol = this.getValueSymbolBase(value, file);
memberSymbol = getExportOrMember(valueSymbol, member);
} else {
memberSymbol = getMember(valueSymbol, member);
}
this.addMember(valueSymbol, memberSymbol, builtin);
}
private getAnyInterfaceOrValueSymbol(value: string): ts.Symbol {
const valueSymbol = this.getAnyInterfaceSymbolMaybe(value);
return valueSymbol === undefined ? this.getAnyValueSymbol(value) : valueSymbol;
}
private addInterfaceBase(value: string, builtin: Builtin, file: ts.SourceFile): void {
this.builtinInterfaces.set(this.getInterfaceSymbolBase(value, file), builtin);
}
private addValueBase(value: string, builtin: Builtin, file: ts.SourceFile): void {
this.builtinValues.set(this.getValueSymbolBase(value, file), builtin);
}
private getAnyValueSymbol(name: string): ts.Symbol {
return this.memoized('any-value-symbol', name, () => throwIfNull(this.getAnyValueSymbolMaybe(name)));
}
private getAnyValueSymbolMaybe(name: string): ts.Symbol | undefined {
return this.memoized('get-any-value-symbol-maybe', name, () =>
findNonNull(this.getFiles().map((file) => this.getValueSymbolMaybe(name, file))),
);
}
private getValueSymbolBase(name: string, file: ts.SourceFile): ts.Symbol {
return throwIfNull(this.getValueSymbolMaybe(name, file));
}
private getValueSymbolMaybe(name: string, file: ts.SourceFile): ts.Symbol | undefined {
let decl: ts.Declaration | undefined = tsUtils.statement.getVariableDeclaration(file, name);
if (decl === undefined) {
decl = tsUtils.statement.getFunction(file, name);
}
if (decl === undefined) {
decl = tsUtils.statement.getEnum(file, name);
}
if (decl === undefined) {
decl = tsUtils.statement.getClass(file, name);
}
if (decl === undefined) {
return undefined;
}
return tsUtils.node.getSymbol(this.context.typeChecker, decl);
}
private getAnyInterfaceSymbol(name: string): ts.Symbol {
return this.memoized('any-interface-symbol', name, () => throwIfNull(this.getAnyInterfaceSymbolMaybe(name)));
}
private getAnyInterfaceSymbolMaybe(name: string): ts.Symbol | undefined {
return this.memoized('get-any-interface-symbol-maybe', name, () =>
findNonNull(this.getFiles().map((file) => this.getInterfaceSymbolMaybe(name, file))),
);
}
private getInterfaceSymbolBase(name: string, file: ts.SourceFile): ts.Symbol {
return throwIfNull(this.getInterfaceSymbolMaybe(name, file));
}
private getInterfaceSymbolMaybe(name: string, file: ts.SourceFile): ts.Symbol | undefined {
return this.getInterfaceSymbols(file)[name];
}
private getInterfaceSymbols(file: ts.SourceFile): { readonly [key: string]: ts.Symbol | undefined } {
return this.memoized('interface-symbols', tsUtils.file.getFilePath(file), () => {
const interfaceDecls: ReadonlyArray<ts.Declaration> = tsUtils.statement.getInterfaces(file);
const decls = interfaceDecls.concat(tsUtils.statement.getEnums(file));
return _.fromPairs(
decls.map((decl) => {
const type = tsUtils.type_.getType(this.context.typeChecker, decl);
const symbol = tsUtils.type_.getSymbol(type);
return [tsUtils.node.getName(decl), symbol];
}),
);
});
}
private getInheritedSymbols(symbol: ts.Symbol, baseTypes: readonly ts.Type[] = []): Set<ts.Symbol> {
return this.memoized('get-inherited-symbols', symbolKey(symbol), () => {
const symbols = new Set<ts.Symbol>();
// tslint:disable-next-line no-loop-statement
for (const decl of tsUtils.symbol.getDeclarations(symbol)) {
if (ts.isInterfaceDeclaration(decl) || ts.isClassDeclaration(decl) || ts.isClassExpression(decl)) {
let baseType = baseTypes[0] as ts.Type | undefined;
let nextBaseTypes = baseTypes.slice(1);
if (baseTypes.length === 0) {
const currentBaseTypes = tsUtils.class_.getBaseTypesFlattened(this.context.typeChecker, decl);
baseType = currentBaseTypes[0];
nextBaseTypes = currentBaseTypes.slice(1);
}
if (baseType !== undefined) {
const baseSymbol = this.context.analysis.getSymbolForType(decl, baseType);
if (baseSymbol !== undefined) {
symbols.add(baseSymbol);
this.getInheritedSymbols(baseSymbol, nextBaseTypes).forEach((inheritedSymbol) => {
symbols.add(inheritedSymbol);
});
}
}
}
}
return symbols;
});
}
private getAnyTypeSymbol(name: string): ts.Symbol {
return this.memoized('get-any-type-symbol', name, () => throwIfNull(this.getAnyTypeSymbolMaybe(name)));
}
private getAnyTypeSymbolMaybe(name: string): ts.Symbol | undefined {
return this.memoized('get-any-type-symbol-maybe', name, () =>
findNonNull(this.getFiles().map((file) => this.getTypeSymbolMaybe(name, file))),
);
}
private getTypeSymbolMaybe(name: string, file: ts.SourceFile): ts.Symbol | undefined {
return this.getTypeSymbols(file)[name];
}
private getTypeSymbols(file: ts.SourceFile): { readonly [key: string]: ts.Symbol | undefined } {
return this.memoized('type-symbols', tsUtils.file.getFilePath(file), () => {
const decls: ReadonlyArray<ts.Declaration> = tsUtils.statement.getTypeAliases(file);
return _.fromPairs(
decls.map((decl) => {
const type = tsUtils.type_.getType(this.context.typeChecker, decl);
const symbol = tsUtils.type_.getAliasSymbol(type);
return [tsUtils.node.getName(decl), symbol];
}),
);
});
}
private getFiles(): ReadonlyArray<ts.SourceFile> {
return this.memoized('file-cache', 'files', () =>
[this.getGlobals(), this.getContract(), this.getTestGlobals()].filter(utils.notNull),
);
}
private getGlobals(): ts.SourceFile {
return this.memoized('file-cache', 'globals', () =>
tsUtils.file.getSourceFileOrThrow(this.context.program, this.context.host.getSmartContractPath('global.d.ts')),
);
}
private getContract(): ts.SourceFile {
return this.memoized('file-cache', 'contract', () =>
tsUtils.file.getSourceFileOrThrow(this.context.program, this.context.host.getSmartContractPath('index.d.ts')),
);
}
private getTestGlobals(): ts.SourceFile | undefined {
return this.memoized('file-cache', 'test', () =>
tsUtils.file.getSourceFile(this.context.program, this.context.host.getSmartContractPath('harness.d.ts')),
);
}
} | the_stack |
import { produce } from 'immer';
import {
assert,
assertNotNull,
FETCH_STATUS_SUCCESS,
localeComparator,
NONE_CATEGORY_ID,
UNKNOWN_ACCOUNT_TYPE,
displayLabel,
shouldIncludeInBalance,
shouldIncludeInOutstandingSum,
assertDefined,
translate as $t,
} from '../helpers';
import {
Account,
Access,
Alert,
Bank,
Operation,
AlertType,
AccessCustomField,
CustomFieldDescriptor,
Type,
PartialTransaction,
} from '../models';
import DefaultAlerts from '../../shared/default-alerts.json';
import DefaultSettings from '../../shared/default-settings';
import { UserActionResponse } from '../../shared/types';
import TransactionTypes from '../../shared/operation-types.json';
import * as Ui from './ui';
import * as backend from './backend';
import {
createReducerFromMap,
SUCCESS,
FAIL,
createActionCreator,
actionStatus,
Action,
mergeInArray,
removeInArrayById,
mergeInObject,
removeInArray,
} from './helpers';
import {
CREATE_ACCESS,
CREATE_ALERT,
CREATE_OPERATION,
DELETE_ACCESS,
UPDATE_ACCOUNT,
DELETE_ACCOUNT,
DELETE_ALERT,
DELETE_OPERATION,
MERGE_OPERATIONS,
SET_DEFAULT_ACCOUNT,
SET_OPERATION_CATEGORY,
SET_OPERATION_CUSTOM_LABEL,
SET_OPERATION_TYPE,
SET_OPERATION_BUDGET_DATE,
RUN_ACCOUNTS_SYNC,
RUN_BALANCE_RESYNC,
RUN_OPERATIONS_SYNC,
RUN_APPLY_BULKEDIT,
UPDATE_ALERT,
UPDATE_ACCESS_AND_FETCH,
UPDATE_ACCESS,
DELETE_CATEGORY,
} from './actions';
import StaticBanks from '../../shared/banks.json';
import { DEFAULT_ACCOUNT_ID } from '../../shared/settings';
import { Dispatch } from 'redux';
import { DeleteCategoryParams } from './categories';
export interface BankState {
// Bank descriptors.
banks: Bank[];
// Array of accesses ids.
accessIds: number[];
accessMap: Record<number, Access>;
accountMap: Record<number, Account>;
transactionMap: Record<number, Operation>;
alerts: Alert[];
currentAccountId: number | null;
// Account id for the default account, or null if it's not defined.
defaultAccountId: number | null;
// Constant for the whole lifetime of the web app.
defaultCurrency: string;
transactionTypes: Type[];
}
// A small wrapper to force creating a mutable state from a given state, and
// use the `produce` helper only once.
class MutableState {
state: BankState;
constructor(state: BankState) {
this.state = state;
}
}
function mutateState(state: BankState, func: (prevState: MutableState) => void): BankState {
return produce(state, draft => {
const mutable = new MutableState(draft);
func(mutable);
return mutable.state;
});
}
type SyncResult = {
accounts?: Account[];
newOperations?: Operation[];
};
// Set a transaction's category.
export function setOperationCategory(
operationId: number,
categoryId: number,
formerCategoryId: number
) {
const serverCategoryId = categoryId === NONE_CATEGORY_ID ? null : categoryId;
return async (dispatch: Dispatch) => {
const action = setTransactionCategoryAction({ operationId, categoryId, formerCategoryId });
dispatch(action);
try {
await backend.setCategoryForOperation(operationId, serverCategoryId);
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
type SetTransactionCategoryParams = {
operationId: number;
categoryId: number;
formerCategoryId: number;
};
const setTransactionCategoryAction =
createActionCreator<SetTransactionCategoryParams>(SET_OPERATION_CATEGORY);
function reduceSetOperationCategory(
state: BankState,
action: Action<SetTransactionCategoryParams>
) {
if (action.status === SUCCESS) {
return state;
}
// Optimistic update.
const categoryId = action.status === FAIL ? action.formerCategoryId : action.categoryId;
return mutateState(state, mut => {
mergeInObject(mut.state.transactionMap, action.operationId, { categoryId });
});
}
// Set a transaction's type.
export function setOperationType(operationId: number, newType: string, formerType: string) {
return async (dispatch: Dispatch) => {
const action = setTransactionTypeAction({ operationId, newType, formerType });
dispatch(action);
try {
await backend.setTypeForOperation(operationId, newType);
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
}
};
}
type SetTransactionTypeParams = {
operationId: number;
newType: string;
formerType: string;
};
const setTransactionTypeAction = createActionCreator<SetTransactionTypeParams>(SET_OPERATION_TYPE);
function reduceSetOperationType(state: BankState, action: Action<SetTransactionTypeParams>) {
const { status } = action;
if (status === SUCCESS) {
return state;
}
// Optimistic update.
const type = status === FAIL ? action.formerType : action.newType;
return mutateState(state, mut => {
mergeInObject(mut.state.transactionMap, action.operationId, { type });
});
}
// Set a transaction's custom label.
export function setOperationCustomLabel(operation: Operation, customLabel: string) {
// The server expects an empty string for deleting the custom label.
const serverCustomLabel = !customLabel ? '' : customLabel;
const formerCustomLabel = operation.customLabel;
return async (dispatch: Dispatch) => {
const action = setTransactionCustomLabelAction({
operationId: operation.id,
customLabel,
formerCustomLabel,
});
dispatch(action);
try {
await backend.setCustomLabel(operation.id, serverCustomLabel);
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
}
};
}
type SetTransactionCustomLabelParams = {
operationId: number;
customLabel: string;
formerCustomLabel: string | null;
};
const setTransactionCustomLabelAction = createActionCreator<SetTransactionCustomLabelParams>(
SET_OPERATION_CUSTOM_LABEL
);
function reduceSetOperationCustomLabel(
state: BankState,
action: Action<SetTransactionCustomLabelParams>
) {
const { status } = action;
if (status === SUCCESS) {
return state;
}
// Optimistic update.
const customLabel = status === FAIL ? action.formerCustomLabel : action.customLabel;
return mutateState(state, mut => {
mergeInObject(mut.state.transactionMap, action.operationId, { customLabel });
});
}
// Set a transaction's budget date.
export function setOperationBudgetDate(operation: Operation, budgetDate: Date | null) {
return async (dispatch: Dispatch) => {
const action = setTransactionBudgetDateAction({
operationId: operation.id,
budgetDate: budgetDate || operation.date,
formerBudgetDate: operation.budgetDate,
});
dispatch(action);
try {
await backend.setOperationBudgetDate(operation.id, budgetDate);
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
}
};
}
type SetTransactionBudgetDateParams = {
operationId: number;
budgetDate: Date;
formerBudgetDate: Date;
};
const setTransactionBudgetDateAction =
createActionCreator<SetTransactionBudgetDateParams>(SET_OPERATION_BUDGET_DATE);
function reduceSetOperationBudgetDate(
state: BankState,
action: Action<SetTransactionBudgetDateParams>
) {
const { status } = action;
if (status === SUCCESS) {
return state;
}
// Optimistic update.
const budgetDate: Date = status === FAIL ? action.formerBudgetDate : action.budgetDate;
return mutateState(state, mut => {
mergeInObject(mut.state.transactionMap, action.operationId, { budgetDate });
});
}
// Fetches all the transactions for the given access through the bank's
// provider.
export function runOperationsSync(
accessId: number,
userActionFields: FinishUserActionFields | null = null
) {
return async (dispatch: Dispatch) => {
const action = syncTransactionsAction({
accessId,
});
dispatch(action);
try {
const results = await backend.getNewOperations(accessId, userActionFields);
if (
maybeHandleUserAction(dispatch, results, (fields: FinishUserActionFields) =>
runOperationsSync(accessId, fields)
)
) {
return;
}
action.results = results;
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
type SyncTransactionsParams = {
accessId: number;
results?: SyncResult;
};
const syncTransactionsAction = createActionCreator<SyncTransactionsParams>(RUN_OPERATIONS_SYNC);
function reduceRunOperationsSync(state: BankState, action: Action<SyncTransactionsParams>) {
if (action.status === SUCCESS) {
const { results, accessId } = action;
return mutateState(state, mut => {
assertDefined(results);
finishSync(mut, accessId, results);
});
}
if (action.status === FAIL) {
const { err, accessId } = action;
return mutateState(state, mut => {
updateAccessFetchStatus(mut, accessId, err.code);
});
}
return state;
}
// Fetches the accounts and transactions for a given access.
export function runAccountsSync(
accessId: number,
userActionFields: FinishUserActionFields | null = null
) {
return async (dispatch: Dispatch) => {
const action = syncAccountsAction({ accessId });
dispatch(action);
try {
const results = await backend.getNewAccounts(accessId, userActionFields);
if (
maybeHandleUserAction(dispatch, results, fields =>
runAccountsSync(accessId, fields)
)
) {
return;
}
action.results = results;
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
type SyncAccountsParams = {
accessId: number;
results?: SyncResult;
};
const syncAccountsAction = createActionCreator<SyncAccountsParams>(RUN_ACCOUNTS_SYNC);
function reduceRunAccountsSync(state: BankState, action: Action<SyncAccountsParams>) {
if (action.status === SUCCESS) {
const { accessId, results } = action;
assertDefined(results);
return mutateState(state, mut => {
finishSync(mut, accessId, results);
});
}
if (action.status === FAIL) {
const { err, accessId } = action;
return mutateState(state, mut => {
updateAccessFetchStatus(mut, accessId, err.code);
});
}
return state;
}
// Apply a bulk edit to a group of transactions.
export function applyBulkEdit(newFields: BulkEditFields, transactionIds: number[]) {
const serverNewFields: {
customLabel?: string | null;
categoryId?: number | null;
type?: string;
} = { ...newFields };
serverNewFields.categoryId =
serverNewFields.categoryId === NONE_CATEGORY_ID ? null : serverNewFields.categoryId;
return async (dispatch: Dispatch) => {
const action = bulkEditAction({ transactionIds, fields: newFields });
dispatch(action);
try {
await Promise.all(
transactionIds.map(id => backend.updateOperation(id, serverNewFields))
);
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
export type BulkEditFields = {
customLabel?: string | null;
categoryId?: number;
type?: string;
};
type BulkEditParams = {
fields: BulkEditFields;
transactionIds: number[];
};
const bulkEditAction = createActionCreator<BulkEditParams>(RUN_APPLY_BULKEDIT);
function reduceRunApplyBulkEdit(state: BankState, action: Action<BulkEditParams>) {
const { status } = action;
if (status === SUCCESS) {
const { transactionIds, fields } = action;
return mutateState(state, mut => {
for (const id of transactionIds) {
mergeInObject(mut.state.transactionMap, id, fields);
}
});
}
return state;
}
// Creates a new transaction.
export function createOperation(operation: Partial<Operation>) {
let serverOperation: PartialTransaction = operation;
if (operation.categoryId === NONE_CATEGORY_ID) {
serverOperation = { ...operation, categoryId: null };
}
return async (dispatch: Dispatch) => {
const action = createTransactionAction({});
dispatch(action);
try {
const created = await backend.createOperation(serverOperation);
action.created = created;
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
type CreateTransactionParams = {
created?: Operation;
};
const createTransactionAction = createActionCreator<CreateTransactionParams>(CREATE_OPERATION);
function reduceCreateOperation(state: BankState, action: Action<CreateTransactionParams>) {
const { status } = action;
if (status === SUCCESS) {
const { created } = action;
assertDefined(created);
return mutateState(state, mut => {
addOperations(mut, [created]);
});
}
return state;
}
// Deletes a given transaction.
export function deleteOperation(operationId: number) {
return async (dispatch: Dispatch) => {
const action = deleteTransactionAction({ operationId });
dispatch(action);
try {
await backend.deleteOperation(operationId);
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
type DeleteTransactionParams = { operationId: number };
const deleteTransactionAction = createActionCreator<DeleteTransactionParams>(DELETE_OPERATION);
function reduceDeleteOperation(state: BankState, action: Action<DeleteTransactionParams>) {
const { status } = action;
if (status === SUCCESS) {
const { operationId } = action;
return mutateState(state, mut => {
removeOperation(mut, operationId);
});
}
return state;
}
// Merges two transactions together.
export function mergeOperations(toKeep: Operation, toRemove: Operation) {
return async (dispatch: Dispatch) => {
const action = mergeTransactionAction({ toKeep, toRemove });
dispatch(action);
try {
const newToKeep = await backend.mergeOperations(toKeep.id, toRemove.id);
action.toKeep = newToKeep;
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
type MergeTransactionParams = {
toKeep: Operation;
toRemove: Operation;
};
const mergeTransactionAction = createActionCreator<MergeTransactionParams>(MERGE_OPERATIONS);
function reduceMergeOperations(state: BankState, action: Action<MergeTransactionParams>) {
const { status } = action;
if (status === SUCCESS) {
return mutateState(state, mut => {
// Remove the former operation:
removeOperation(mut, action.toRemove.id);
// Replace the kept one:
const newKept = new Operation(action.toKeep);
mergeInObject(mut.state.transactionMap, action.toKeep.id, newKept);
});
}
return state;
}
// Creates a new access.
export function createAccess(
{
uuid,
login,
password,
fields,
customLabel,
shouldCreateDefaultAlerts,
}: {
uuid: string;
login: string;
password: string;
fields: AccessCustomField[];
customLabel: string | null;
shouldCreateDefaultAlerts: boolean;
},
userActionFields: FinishUserActionFields | null = null
) {
return async (dispatch: Dispatch) => {
const action = createAccessAction({
uuid,
login,
fields,
customLabel,
});
dispatch(action);
try {
const results = await backend.createAccess(
uuid,
login,
password,
fields,
customLabel,
userActionFields
);
if (
maybeHandleUserAction(dispatch, results, filledActionFields =>
createAccess(
{
uuid,
login,
password,
fields,
customLabel,
shouldCreateDefaultAlerts,
},
filledActionFields
)
)
) {
return;
}
action.results = results;
dispatch(actionStatus.ok(action));
if (shouldCreateDefaultAlerts) {
await createDefaultAlerts(results.accounts)(dispatch);
}
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
type CreateAccessParams = {
uuid: string;
login: string;
fields: AccessCustomField[];
customLabel: string | null;
results?: SyncResult & { accessId: number; label: string };
};
const createAccessAction = createActionCreator<CreateAccessParams>(CREATE_ACCESS);
function reduceCreateAccess(state: BankState, action: Action<CreateAccessParams>) {
const { status } = action;
if (status === SUCCESS) {
const { results, uuid, login, fields, customLabel } = action;
assertDefined(results);
return mutateState(state, mut => {
const access = {
id: results.accessId,
vendorId: uuid,
login,
fields,
label: results.label,
customLabel,
enabled: true,
};
const { accounts, newOperations } = results;
// A new access must have an account and a transaction array (even
// if it's empty).
assertDefined(accounts);
assertDefined(newOperations);
addAccesses(mut, [access], accounts, newOperations);
});
}
return state;
}
// Deletes the given access.
export function deleteAccess(accessId: number) {
return async (dispatch: Dispatch) => {
const action = deleteAccessAction({ accessId });
dispatch(action);
try {
await backend.deleteAccess(accessId);
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
type DeleteAccessParams = {
accessId: number;
};
const deleteAccessAction = createActionCreator<DeleteAccessParams>(DELETE_ACCESS);
function reduceDeleteAccess(state: BankState, action: Action<DeleteAccessParams>) {
const { accessId, status } = action;
if (status === SUCCESS) {
return mutateState(state, mut => {
removeAccess(mut, accessId);
});
}
return state;
}
// Resyncs the balance of the given account according to the real balance read
// from a provider.
export function resyncBalance(
accountId: number,
userActionFields: FinishUserActionFields | null = null
) {
return async (dispatch: Dispatch) => {
const action = resyncBalanceAction({ accountId });
dispatch(action);
try {
const results = await backend.resyncBalance(accountId, userActionFields);
if (
maybeHandleUserAction(dispatch, results, fields => resyncBalance(accountId, fields))
) {
return;
}
action.initialBalance = results.initialBalance;
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
}
};
}
type ResyncBalanceParams = { accountId: number; initialBalance?: number };
const resyncBalanceAction = createActionCreator<ResyncBalanceParams>(RUN_BALANCE_RESYNC);
function reduceResyncBalance(state: BankState, action: Action<ResyncBalanceParams>) {
if (action.status === SUCCESS) {
const { accountId, initialBalance } = action;
assertDefined(initialBalance);
return mutateState(state, mut => {
const account = accountById(mut.state, accountId);
const balance = account.balance - account.initialBalance + initialBalance;
mergeInObject(mut.state.accountMap, accountId, { initialBalance, balance });
});
}
if (action.status === FAIL) {
const { accountId, err } = action;
return mutateState(state, mut => {
const access = accessByAccountId(mut.state, accountId);
assertNotNull(access);
const { id: accessId } = access;
updateAccessFetchStatus(mut, accessId, err.code);
});
}
return state;
}
// Updates the account with the given fields.
// Does not trigger a sync.
export function updateAccount(
accountId: number,
newFields: Partial<Account>,
prevFields: Partial<Account>
) {
return async (dispatch: Dispatch) => {
const action = updateAccountAction({
accountId,
newFields,
prevFields,
});
dispatch(action);
try {
const updated = await backend.updateAccount(accountId, newFields);
action.newFields = updated;
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
type UpdateAccountParams = {
accountId: number;
newFields: Partial<Account>;
prevFields: Partial<Account>;
};
const updateAccountAction = createActionCreator<UpdateAccountParams>(UPDATE_ACCOUNT);
function reduceUpdateAccount(state: BankState, action: Action<UpdateAccountParams>) {
const { status, newFields, prevFields, accountId } = action;
// Optimistic update.
if (status === SUCCESS) {
return state;
}
const fields = status === FAIL ? prevFields : newFields;
return mutateState(state, mut => {
// Update fields in the object.
mergeInObject(mut.state.accountMap, accountId, fields);
// Ensure accounts are still sorted.
const access = accessByAccountId(mut.state, accountId);
access.accountIds.sort(makeCompareAccountIds(mut.state));
});
}
// Deletes an account and all its transactions.
export function deleteAccount(accountId: number) {
return async (dispatch: Dispatch) => {
const action = deleteAccountAction({ accountId });
dispatch(action);
try {
await backend.deleteAccount(accountId);
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
type DeleteAccountParams = {
accountId: number;
};
const deleteAccountAction = createActionCreator<DeleteAccountParams>(DELETE_ACCOUNT);
function reduceDeleteAccount(state: BankState, action: Action<DeleteAccountParams>) {
const { accountId, status } = action;
if (status === SUCCESS) {
return mutateState(state, mut => {
removeAccount(mut, accountId);
});
}
return state;
}
// Creates a new alert.
export function createAlert(newAlert: Partial<Alert>) {
return async (dispatch: Dispatch) => {
const action = createAlertAction({ alert: newAlert });
dispatch(action);
try {
const created = await backend.createAlert(newAlert);
action.alert = created;
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
type CreateAlertParams = {
alert: Partial<Alert>;
};
const createAlertAction = createActionCreator<CreateAlertParams>(CREATE_ALERT);
function reduceCreateAlert(state: BankState, action: Action<CreateAlertParams>) {
const { status } = action;
if (status === SUCCESS) {
const a = new Alert(action.alert);
return mutateState(state, mut => {
mut.state.alerts.push(a);
});
}
return state;
}
// Updates an alert's fields.
export function updateAlert(alertId: number, fields: Partial<Alert>) {
return async (dispatch: Dispatch) => {
const action = updateAlertAction({
alertId,
fields,
});
dispatch(action);
try {
await backend.updateAlert(alertId, fields);
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
type UpdateAlertParams = {
alertId: number;
fields: Partial<Alert>;
};
const updateAlertAction = createActionCreator<UpdateAlertParams>(UPDATE_ALERT);
function reduceUpdateAlert(state: BankState, action: Action<UpdateAlertParams>) {
const { status } = action;
if (status === SUCCESS) {
const { fields, alertId } = action;
return mutateState(state, mut => {
mergeInArray(mut.state.alerts, alertId, fields);
});
}
return state;
}
// Deletes an alert.
export function deleteAlert(alertId: number) {
return async (dispatch: Dispatch) => {
const action = deleteAlertAction({ alertId });
dispatch(action);
try {
await backend.deleteAlert(alertId);
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
type DeleteAlertParams = {
alertId: number;
};
const deleteAlertAction = createActionCreator<DeleteAlertParams>(DELETE_ALERT);
function reduceDeleteAlert(state: BankState, action: Action<DeleteAlertParams>) {
const { status } = action;
if (status === SUCCESS) {
const { alertId } = action;
return mutateState(state, mut => {
removeInArrayById(mut.state.alerts, alertId);
});
}
return state;
}
// Sets the default account to the given account id.
export function setDefaultAccountId(accountId: number | null) {
return async (dispatch: Dispatch) => {
const action = setDefaultAccountAction({ accountId });
dispatch(action);
try {
await backend.saveSetting(
DEFAULT_ACCOUNT_ID,
accountId !== null ? accountId.toString() : null
);
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
type SetDefaultAccountParams = {
accountId: number | null;
};
const setDefaultAccountAction = createActionCreator<SetDefaultAccountParams>(SET_DEFAULT_ACCOUNT);
function reduceSetDefaultAccount(state: BankState, action: Action<SetDefaultAccountParams>) {
if (action.status === SUCCESS) {
return mutateState(state, mut => {
mut.state.defaultAccountId = action.accountId;
sortAccesses(mut);
});
}
return state;
}
// Updates the access' fields and runs a sync. Must be used when the login,
// password, custom fields have changed.
export function updateAndFetchAccess(
accessId: number,
login: string,
password: string,
customFields: AccessCustomField[],
userActionFields: FinishUserActionFields | null = null
) {
const newFields = {
login,
customFields,
};
return async (dispatch: Dispatch) => {
const action = updateFetchAccessAction({ accessId, newFields });
dispatch(action);
try {
const results = await backend.updateAndFetchAccess(
accessId,
{ password, ...newFields },
userActionFields
);
if (
maybeHandleUserAction(dispatch, results, fields =>
updateAndFetchAccess(accessId, login, password, customFields, fields)
)
) {
return;
}
results.accessId = accessId;
action.newFields.enabled = true;
action.results = results;
dispatch(actionStatus.ok(action));
} catch (err) {
dispatch(actionStatus.err(action, err));
throw err;
}
};
}
type UpdateFetchAccessParams = {
accessId: number;
newFields: Partial<Access>;
results?: SyncResult;
};
const updateFetchAccessAction =
createActionCreator<UpdateFetchAccessParams>(UPDATE_ACCESS_AND_FETCH);
function reduceUpdateAccessAndFetch(state: BankState, action: Action<UpdateFetchAccessParams>) {
if (action.status === SUCCESS) {
const { accessId, newFields, results } = action;
assertDefined(results);
return mutateState(state, mut => {
// Remove all the custom fields which have been set to null.
if (newFields.customFields) {
newFields.customFields = newFields.customFields.filter(
field => field.value !== null
);
}
mergeInObject(mut.state.accessMap, accessId, newFields);
finishSync(mut, accessId, results);
// Sort accesses in case an access has been re-enabled.
sortAccesses(mut);
});
}
if (action.status === FAIL) {
const { accessId, err } = action;
return mutateState(state, mut => {
updateAccessFetchStatus(mut, accessId, err.code);
});
}
return state;
}
// Updates some access' fields without retriggering a sync.
export function updateAccess(
accessId: number,
newFields: Partial<Access>,
prevFields: Partial<Access>
) {
return async (dispatch: Dispatch) => {
const action = updateAccessAction({ accessId, newFields });
dispatch(action);
try {
await backend.updateAccess(accessId, newFields);
dispatch(actionStatus.ok(action));
} catch (err) {
action.newFields = prevFields;
dispatch(actionStatus.err(action, err));
}
};
}
export function disableAccess(accessId: number) {
return updateAccess(accessId, { enabled: false }, { enabled: true });
}
type UpdateAccessParams = {
accessId: number;
newFields: Partial<Access>;
};
const updateAccessAction = createActionCreator<UpdateAccessParams>(UPDATE_ACCESS);
function reduceUpdateAccess(state: BankState, action: Action<UpdateAccessParams>) {
const { status } = action;
// Optimistic update.
if (status === SUCCESS) {
return state;
}
const { accessId, newFields } = action;
return mutateState(state, mut => {
mergeInObject(mut.state.accessMap, accessId, newFields);
sortAccesses(mut);
});
}
function createDefaultAlerts(accounts: Account[]) {
return async (dispatch: Dispatch) => {
for (const account of accounts) {
if (
!DefaultAlerts.hasOwnProperty(account.type) &&
account.type !== UNKNOWN_ACCOUNT_TYPE
) {
continue;
}
const key = account.type as keyof typeof DefaultAlerts;
const defaultAlerts = DefaultAlerts[key] as Partial<Alert>[];
await Promise.all(
defaultAlerts.map(al => {
const merged = { ...al, accountId: account.id };
return createAlert(merged)(dispatch);
})
);
}
};
}
export type FinishUserActionFields = Record<string, string>;
export type FinishUserAction = (
fields: FinishUserActionFields
) => (dispatch: Dispatch) => Promise<void>;
function maybeHandleUserAction(
dispatch: Dispatch,
results: UserActionResponse | { kind: undefined },
finishAction: FinishUserAction
) {
if (typeof results.kind === 'undefined') {
return false;
}
assert(results.kind === 'user_action', 'must have thrown a user action');
switch (results.actionKind) {
case 'decoupled_validation':
assertDefined(results.message);
dispatch(Ui.requestUserAction(finishAction, results.message, null));
break;
case 'browser_question':
assertDefined(results.fields);
dispatch(Ui.requestUserAction(finishAction, null, results.fields));
break;
default:
assert(false, `unknown user action ${results.actionKind}`);
}
return true;
}
// State mutators.
function finishSync(mut: MutableState, accessId: number, results: SyncResult): void {
const { accounts = [], newOperations = [] } = results;
// If finishSync is called, everything went well.
updateAccessFetchStatus(mut, accessId, FETCH_STATUS_SUCCESS);
if (accounts.length) {
// addAccounts also handles transactions.
addAccounts(mut, accounts, newOperations);
} else {
addOperations(mut, newOperations);
}
}
function updateAccessFetchStatus(
mut: MutableState,
accessId: number,
errCode: string | null = null
): void {
// If the errCode is null, this means this is not a fetchStatus.
if (errCode !== null) {
mergeInObject(mut.state.accessMap, accessId, { fetchStatus: errCode });
}
}
// More complex operations.
function makeCompareOperationByIds(state: BankState) {
return function compareOperationIds(id1: number, id2: number) {
const op1 = operationById(state, id1);
const op2 = operationById(state, id2);
assertNotNull(op1);
assertNotNull(op2);
const op1date = +op1.date,
op2date = +op2.date;
if (op1date < op2date) {
return 1;
}
if (op1date > op2date) {
return -1;
}
const alabel = displayLabel(op1);
const blabel = displayLabel(op2);
return localeComparator(alabel, blabel);
};
}
function addOperations(mut: MutableState, operations: Partial<Operation>[]): void {
const accountsToSort = new Set<Account>();
const today = new Date();
for (const op of operations) {
const operation = new Operation(op);
const account = accountById(mut.state, operation.accountId);
accountsToSort.add(account);
account.operationIds.push(operation.id);
if (shouldIncludeInBalance(operation, today, account.type)) {
account.balance += operation.amount;
} else if (shouldIncludeInOutstandingSum(operation)) {
account.outstandingSum += operation.amount;
}
mut.state.transactionMap[operation.id] = operation;
}
// Ensure operations are still sorted.
const comparator = makeCompareOperationByIds(mut.state);
for (const account of accountsToSort) {
account.operationIds.sort(comparator);
}
}
function makeCompareAccountIds(state: BankState) {
return function compareAccountIds(id1: number, id2: number) {
const acc1 = accountById(state, id1);
const acc2 = accountById(state, id2);
return localeComparator(displayLabel(acc1), displayLabel(acc2));
};
}
function setCurrentAccount(mut: MutableState): void {
const defaultAccountId = getDefaultAccountId(mut.state);
// The initial account id is:
// 1. the current account id, if defined.
// 2. the first account of the first access, if it exists.
// 3. null otherwise
let current;
if (defaultAccountId !== null) {
current = defaultAccountId;
} else if (mut.state.accessIds.length > 0) {
current = accountIdsByAccessId(mut.state, mut.state.accessIds[0])[0];
} else {
current = null;
}
mut.state.currentAccountId = current;
}
function addAccounts(
mut: MutableState,
accounts: Partial<Account>[],
operations: Partial<Operation>[]
): void {
if (accounts.length === 0) {
return;
}
const defaultCurrency = mut.state.defaultCurrency;
const accessesToSort = new Set<Access>();
for (const account of accounts) {
assertDefined(account.accessId);
assertDefined(account.id);
// Only add account to the access list if it does not already exist.
const access = accessById(mut.state, account.accessId);
if (!access.accountIds.includes(account.id)) {
access.accountIds.push(account.id);
accessesToSort.add(access);
}
// Always update the account content.
const prevAccount = mut.state.accountMap[account.id];
if (typeof prevAccount === 'undefined') {
mut.state.accountMap[account.id] = new Account(account, defaultCurrency);
} else {
mergeInObject(
mut.state.accountMap,
account.id,
Account.updateFrom(account, defaultCurrency, prevAccount)
);
}
}
// Ensure accounts are still sorted in each access.
const comparator = makeCompareAccountIds(mut.state);
for (const access of accessesToSort) {
access.accountIds.sort(comparator);
}
// If there was no current account id, set one.
if (getCurrentAccountId(mut.state) === null) {
setCurrentAccount(mut);
}
addOperations(mut, operations);
}
function sortAccesses(mut: MutableState): void {
const accessIds = getAccessIds(mut.state);
const defaultAccountId = getDefaultAccountId(mut.state);
const defaultAccessId =
defaultAccountId === null ? null : accessByAccountId(mut.state, defaultAccountId).id;
accessIds.sort((ida: number, idb: number) => {
const a = accessById(mut.state, ida);
const b = accessById(mut.state, idb);
// First display the access with default account.
if (a.id === defaultAccessId) {
return -1;
}
if (b.id === defaultAccessId) {
return 1;
}
// Then display active accounts.
if (a.enabled !== b.enabled) {
return a.enabled ? -1 : 1;
}
// Finally order accesses by alphabetical order.
return localeComparator(displayLabel(a).replace(' ', ''), displayLabel(b).replace(' ', ''));
});
}
function addAccesses(
mut: MutableState,
accesses: Partial<Access>[],
accounts: Partial<Account>[],
operations: Partial<Operation>[]
): void {
const bankDescs = mut.state.banks;
for (const partialAccess of accesses) {
const access = new Access(partialAccess, bankDescs);
mut.state.accessMap[access.id] = access;
mut.state.accessIds.push(access.id);
}
addAccounts(mut, accounts, operations);
sortAccesses(mut);
}
function removeAccess(mut: MutableState, accessId: number): void {
const access = accessById(mut.state, accessId);
assert(access.accountIds.length > 0, 'access should have at least one account');
// First remove all the accounts attached to the access.
//
// Copy the items to avoid iterating on an array that's being mutated under
// the rug.
const accountIds = access.accountIds.slice();
for (const accountId of accountIds) {
removeAccount(mut, accountId);
}
assert(
typeof mut.state.accessMap[accessId] === 'undefined',
'last removeAccount should have removed the access (accessMap)'
);
assert(
!mut.state.accessIds.includes(accessId),
'last removeAccount should have removed the access (accessIds)'
);
}
function removeAccount(mut: MutableState, accountId: number): void {
const account = accountById(mut.state, accountId);
// First remove the attached transactions from the transaction map.
for (const id of account.operationIds) {
assertDefined(mut.state.transactionMap[id]);
delete mut.state.transactionMap[id];
}
// Then remove the account from the access.
const access = accessById(mut.state, account.accessId);
removeInArray(access.accountIds, accountId);
// Reset the defaultAccountId if we just deleted it.
if (getDefaultAccountId(mut.state) === accountId) {
mut.state.defaultAccountId = null;
}
// Remove access if there's no accounts in the access.
if (access.accountIds.length === 0) {
assertDefined(mut.state.accessMap[account.accessId]);
delete mut.state.accessMap[account.accessId];
removeInArray(mut.state.accessIds, account.accessId);
// Sort accesses in case the default account has been deleted.
sortAccesses(mut);
}
// Reset the current account id if we just deleted it.
if (getCurrentAccountId(mut.state) === accountId) {
setCurrentAccount(mut);
}
// Remove alerts attached to the account.
mut.state.alerts = mut.state.alerts.filter((alert: Alert) => alert.accountId !== accountId);
// Finally, remove the account from the accounts map.
delete mut.state.accountMap[accountId];
}
function removeOperation(mut: MutableState, operationId: number): void {
const op = operationById(mut.state, operationId);
const account = accountById(mut.state, op.accountId);
let { balance, outstandingSum } = account;
const today = new Date();
if (shouldIncludeInBalance(op, today, account.type)) {
balance -= op.amount;
} else if (shouldIncludeInOutstandingSum(op)) {
outstandingSum -= op.amount;
}
mergeInObject(mut.state.accountMap, account.id, {
operationIds: account.operationIds.filter(id => id !== operationId),
balance,
outstandingSum,
});
delete mut.state.transactionMap[operationId];
}
// Reducers on external actions.
function reduceDeleteCategory(state: BankState, action: Action<DeleteCategoryParams>) {
if (action.status !== SUCCESS) {
return state;
}
const { id: formerCategoryId, replaceById } = action;
return mutateState(state, mut => {
for (const id of Object.keys(mut.state.transactionMap)) {
// Helping TypeScript a bit here: Object.keys return string, we
// specified a mapping of number -> transactions.
const t = mut.state.transactionMap[id as any as number];
if (t.categoryId === formerCategoryId) {
t.categoryId = replaceById;
}
}
});
}
// Mapping of actions => reducers.
const reducers = {
[CREATE_ACCESS]: reduceCreateAccess,
[CREATE_ALERT]: reduceCreateAlert,
[CREATE_OPERATION]: reduceCreateOperation,
[DELETE_ACCESS]: reduceDeleteAccess,
[DELETE_ACCOUNT]: reduceDeleteAccount,
[DELETE_ALERT]: reduceDeleteAlert,
[DELETE_CATEGORY]: reduceDeleteCategory,
[DELETE_OPERATION]: reduceDeleteOperation,
[MERGE_OPERATIONS]: reduceMergeOperations,
[RUN_ACCOUNTS_SYNC]: reduceRunAccountsSync,
[RUN_APPLY_BULKEDIT]: reduceRunApplyBulkEdit,
[RUN_BALANCE_RESYNC]: reduceResyncBalance,
[RUN_OPERATIONS_SYNC]: reduceRunOperationsSync,
[SET_DEFAULT_ACCOUNT]: reduceSetDefaultAccount,
[SET_OPERATION_BUDGET_DATE]: reduceSetOperationBudgetDate,
[SET_OPERATION_CATEGORY]: reduceSetOperationCategory,
[SET_OPERATION_CUSTOM_LABEL]: reduceSetOperationCustomLabel,
[SET_OPERATION_TYPE]: reduceSetOperationType,
[UPDATE_ACCESS]: reduceUpdateAccess,
[UPDATE_ACCESS_AND_FETCH]: reduceUpdateAccessAndFetch,
[UPDATE_ACCOUNT]: reduceUpdateAccount,
[UPDATE_ALERT]: reduceUpdateAlert,
};
export const reducer = createReducerFromMap(reducers);
// Helpers.
function sortSelectFields(field: CustomFieldDescriptor) {
if (field.type === 'select') {
field.values.sort((a, b) => localeComparator(a.label, b.label));
}
}
function sortBanks(banks: Bank[]) {
banks.sort((a, b) => localeComparator(a.name, b.name));
// Sort the selects of customFields by alphabetical order.
banks.forEach(bank => {
if (bank.customFields) {
bank.customFields.forEach(sortSelectFields);
}
});
}
// Initial state.
export function initialState(
external: {
defaultCurrency: string;
defaultAccountId: string;
},
allAccesses: Partial<Access>[],
allAccounts: Partial<Account>[],
allOperations: Partial<Operation>[],
allAlerts: Partial<Alert>[]
) {
// Retrieved from outside.
const { defaultCurrency, defaultAccountId: defaultAccountIdStr } = external;
let defaultAccountId: number | null = null;
if (defaultAccountIdStr !== DefaultSettings.get(DEFAULT_ACCOUNT_ID)) {
defaultAccountId = parseInt(defaultAccountIdStr, 10);
}
const banks = StaticBanks.map(b => new Bank(b));
sortBanks(banks);
// TODO The sorting order doesn't hold after a i18n language change. Do we care?
const transactionTypes = TransactionTypes.map(type => new Type(type));
transactionTypes.sort((type1, type2) => {
return localeComparator($t(`client.${type1.name}`), $t(`client.${type2.name}`));
});
const state: BankState = {
banks,
accessIds: [],
accessMap: {},
accountMap: {},
transactionMap: {},
alerts: [],
currentAccountId: null,
defaultAccountId,
defaultCurrency,
transactionTypes,
};
const mut = new MutableState(state);
addAccesses(mut, allAccesses, allAccounts, allOperations);
setCurrentAccount(mut);
mut.state.alerts = allAlerts.map(al => new Alert(al));
return mut.state;
}
// Getters
export function getCurrentAccountId(state: BankState): number | null {
return state.currentAccountId;
}
export function allActiveStaticBanks(state: BankState): Bank[] {
return state.banks.filter(b => !b.deprecated);
}
export function bankByUuid(state: BankState, uuid: string): Bank {
const candidate = state.banks.find(bank => bank.uuid === uuid);
assertDefined(candidate, `unknown bank with id ${uuid}`);
return candidate;
}
export function getAccessIds(state: BankState): number[] {
return state.accessIds;
}
export function accessExists(state: BankState, accessId: number): boolean {
return typeof state.accessMap[accessId] !== 'undefined';
}
export function accessById(state: BankState, accessId: number): Access {
const candidate = state.accessMap[accessId];
assertDefined(candidate);
return candidate;
}
export interface AccessTotal {
total: number;
formatCurrency: (amount: number) => string;
}
export function computeAccessTotal(
state: BankState,
accessId: number
): Record<string, AccessTotal> {
const totals: Record<string, AccessTotal> = {};
const accountIds = accountIdsByAccessId(state, accessId);
for (const accountId of accountIds) {
const acc = accountById(state, accountId);
if (!acc.excludeFromBalance && acc.currency) {
if (!(acc.currency in totals)) {
totals[acc.currency] = { total: acc.balance, formatCurrency: acc.formatCurrency };
} else {
totals[acc.currency].total += acc.balance;
}
}
}
return totals;
}
export function accountExists(state: BankState, accountId: number): boolean {
return typeof state.accountMap[accountId] !== 'undefined';
}
export function accountById(state: BankState, accountId: number): Account {
const candidate = state.accountMap[accountId];
assertDefined(candidate);
return candidate;
}
export function accessByAccountId(state: BankState, accountId: number): Access {
const account = accountById(state, accountId);
return accessById(state, account.accessId);
}
export function accountIdsByAccessId(state: BankState, accessId: number): number[] {
return accessById(state, accessId).accountIds;
}
export function transactionExists(state: BankState, transactionId: number) {
return typeof state.transactionMap[transactionId] !== 'undefined';
}
export function operationById(state: BankState, operationId: number): Operation {
const transaction = state.transactionMap[operationId];
assertDefined(transaction);
return transaction;
}
export function operationIdsByAccountId(state: BankState, accountId: number): number[] {
return accountById(state, accountId).operationIds;
}
export function operationsByAccountId(state: BankState, accountId: number): Operation[] {
return operationIdsByAccountId(state, accountId).map(id => {
const op = operationById(state, id);
assertNotNull(op);
return op;
});
}
export function operationIdsByCategoryId(state: BankState, categoryId: number): number[] {
return Object.values(state.transactionMap)
.filter(op => op.categoryId === categoryId)
.map(op => op.id);
}
export function usedCategoriesSet(state: BankState): Set<number> {
return new Set(Object.values(state.transactionMap).map(op => op.categoryId));
}
export function alertPairsByType(state: BankState, alertType: AlertType) {
const pairs = [];
for (const alert of state.alerts.filter(a => a.type === alertType)) {
const account = accountById(state, alert.accountId);
pairs.push({ alert, account });
}
return pairs;
}
export function getDefaultAccountId(state: BankState): number | null {
return state.defaultAccountId;
}
export function allTypes(state: BankState): Type[] {
return state.transactionTypes;
}
export function deleteAccessSession(accessId: number) {
return backend.deleteAccessSession(accessId);
}
export const testing = {
addAccesses,
removeAccess,
addAccounts,
removeAccount,
addOperations,
removeOperation,
}; | the_stack |
import { isIndexedDbTransactionError } from '../local/simple_db';
import { getDocument } from '../platform/dom';
import { ExponentialBackoff } from '../remote/backoff';
import { debugAssert, fail } from './assert';
import { AsyncQueue, DelayedOperation, TimerId } from './async_queue';
import { FirestoreError } from './error';
import { logDebug, logError } from './log';
import { Deferred } from './promise';
const LOG_TAG = 'AsyncQueue';
export class AsyncQueueImpl implements AsyncQueue {
// The last promise in the queue.
private tail: Promise<unknown> = Promise.resolve();
// A list of retryable operations. Retryable operations are run in order and
// retried with backoff.
private retryableOps: Array<() => Promise<void>> = [];
// Is this AsyncQueue being shut down? Once it is set to true, it will not
// be changed again.
private _isShuttingDown: boolean = false;
// Operations scheduled to be queued in the future. Operations are
// automatically removed after they are run or canceled.
private delayedOperations: Array<DelayedOperation<unknown>> = [];
// visible for testing
failure: FirestoreError | null = null;
// Flag set while there's an outstanding AsyncQueue operation, used for
// assertion sanity-checks.
private operationInProgress = false;
// Enabled during shutdown on Safari to prevent future access to IndexedDB.
private skipNonRestrictedTasks = false;
// List of TimerIds to fast-forward delays for.
private timerIdsToSkip: TimerId[] = [];
// Backoff timer used to schedule retries for retryable operations
private backoff = new ExponentialBackoff(this, TimerId.AsyncQueueRetry);
// Visibility handler that triggers an immediate retry of all retryable
// operations. Meant to speed up recovery when we regain file system access
// after page comes into foreground.
private visibilityHandler: () => void = () => {
const document = getDocument();
if (document) {
logDebug(
LOG_TAG,
'Visibility state changed to ' + document.visibilityState
);
}
this.backoff.skipBackoff();
};
constructor() {
const document = getDocument();
if (document && typeof document.addEventListener === 'function') {
document.addEventListener('visibilitychange', this.visibilityHandler);
}
}
get isShuttingDown(): boolean {
return this._isShuttingDown;
}
/**
* Adds a new operation to the queue without waiting for it to complete (i.e.
* we ignore the Promise result).
*/
enqueueAndForget<T extends unknown>(op: () => Promise<T>): void {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.enqueue(op);
}
enqueueAndForgetEvenWhileRestricted<T extends unknown>(
op: () => Promise<T>
): void {
this.verifyNotFailed();
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.enqueueInternal(op);
}
enterRestrictedMode(purgeExistingTasks?: boolean): void {
if (!this._isShuttingDown) {
this._isShuttingDown = true;
this.skipNonRestrictedTasks = purgeExistingTasks || false;
const document = getDocument();
if (document && typeof document.removeEventListener === 'function') {
document.removeEventListener(
'visibilitychange',
this.visibilityHandler
);
}
}
}
enqueue<T extends unknown>(op: () => Promise<T>): Promise<T> {
this.verifyNotFailed();
if (this._isShuttingDown) {
// Return a Promise which never resolves.
return new Promise<T>(() => {});
}
// Create a deferred Promise that we can return to the callee. This
// allows us to return a "hanging Promise" only to the callee and still
// advance the queue even when the operation is not run.
const task = new Deferred<T>();
return this.enqueueInternal<unknown>(() => {
if (this._isShuttingDown && this.skipNonRestrictedTasks) {
// We do not resolve 'task'
return Promise.resolve();
}
op().then(task.resolve, task.reject);
return task.promise;
}).then(() => task.promise);
}
enqueueRetryable(op: () => Promise<void>): void {
this.enqueueAndForget(() => {
this.retryableOps.push(op);
return this.retryNextOp();
});
}
/**
* Runs the next operation from the retryable queue. If the operation fails,
* reschedules with backoff.
*/
private async retryNextOp(): Promise<void> {
if (this.retryableOps.length === 0) {
return;
}
try {
await this.retryableOps[0]();
this.retryableOps.shift();
this.backoff.reset();
} catch (e) {
if (isIndexedDbTransactionError(e)) {
logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);
} else {
throw e; // Failure will be handled by AsyncQueue
}
}
if (this.retryableOps.length > 0) {
// If there are additional operations, we re-schedule `retryNextOp()`.
// This is necessary to run retryable operations that failed during
// their initial attempt since we don't know whether they are already
// enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
// needs to be re-run, we will run `op1`, `op1`, `op2` using the
// already enqueued calls to `retryNextOp()`. `op3()` will then run in the
// call scheduled here.
// Since `backoffAndRun()` cancels an existing backoff and schedules a
// new backoff on every call, there is only ever a single additional
// operation in the queue.
this.backoff.backoffAndRun(() => this.retryNextOp());
}
}
private enqueueInternal<T extends unknown>(op: () => Promise<T>): Promise<T> {
const newTail = this.tail.then(() => {
this.operationInProgress = true;
return op()
.catch((error: FirestoreError) => {
this.failure = error;
this.operationInProgress = false;
const message = getMessageOrStack(error);
logError('INTERNAL UNHANDLED ERROR: ', message);
// Re-throw the error so that this.tail becomes a rejected Promise and
// all further attempts to chain (via .then) will just short-circuit
// and return the rejected Promise.
throw error;
})
.then(result => {
this.operationInProgress = false;
return result;
});
});
this.tail = newTail;
return newTail;
}
enqueueAfterDelay<T extends unknown>(
timerId: TimerId,
delayMs: number,
op: () => Promise<T>
): DelayedOperation<T> {
this.verifyNotFailed();
debugAssert(
delayMs >= 0,
`Attempted to schedule an operation with a negative delay of ${delayMs}`
);
// Fast-forward delays for timerIds that have been overriden.
if (this.timerIdsToSkip.indexOf(timerId) > -1) {
delayMs = 0;
}
const delayedOp = DelayedOperation.createAndSchedule<T>(
this,
timerId,
delayMs,
op,
removedOp =>
this.removeDelayedOperation(removedOp as DelayedOperation<unknown>)
);
this.delayedOperations.push(delayedOp as DelayedOperation<unknown>);
return delayedOp;
}
private verifyNotFailed(): void {
if (this.failure) {
fail('AsyncQueue is already failed: ' + getMessageOrStack(this.failure));
}
}
verifyOperationInProgress(): void {
debugAssert(
this.operationInProgress,
'verifyOpInProgress() called when no op in progress on this queue.'
);
}
/**
* Waits until all currently queued tasks are finished executing. Delayed
* operations are not run.
*/
async drain(): Promise<void> {
// Operations in the queue prior to draining may have enqueued additional
// operations. Keep draining the queue until the tail is no longer advanced,
// which indicates that no more new operations were enqueued and that all
// operations were executed.
let currentTail: Promise<unknown>;
do {
currentTail = this.tail;
await currentTail;
} while (currentTail !== this.tail);
}
/**
* For Tests: Determine if a delayed operation with a particular TimerId
* exists.
*/
containsDelayedOperation(timerId: TimerId): boolean {
for (const op of this.delayedOperations) {
if (op.timerId === timerId) {
return true;
}
}
return false;
}
/**
* For Tests: Runs some or all delayed operations early.
*
* @param lastTimerId - Delayed operations up to and including this TimerId
* will be drained. Pass TimerId.All to run all delayed operations.
* @returns a Promise that resolves once all operations have been run.
*/
runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise<void> {
// Note that draining may generate more delayed ops, so we do that first.
return this.drain().then(() => {
// Run ops in the same order they'd run if they ran naturally.
this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);
for (const op of this.delayedOperations) {
op.skipDelay();
if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {
break;
}
}
return this.drain();
});
}
/**
* For Tests: Skip all subsequent delays for a timer id.
*/
skipDelaysForTimerId(timerId: TimerId): void {
this.timerIdsToSkip.push(timerId);
}
/** Called once a DelayedOperation is run or canceled. */
private removeDelayedOperation(op: DelayedOperation<unknown>): void {
// NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
const index = this.delayedOperations.indexOf(op);
debugAssert(index >= 0, 'Delayed operation not found.');
this.delayedOperations.splice(index, 1);
}
}
export function newAsyncQueue(): AsyncQueue {
return new AsyncQueueImpl();
}
/**
* Chrome includes Error.message in Error.stack. Other browsers do not.
* This returns expected output of message + stack when available.
* @param error - Error or FirestoreError
*/
function getMessageOrStack(error: Error): string {
let message = error.message || '';
if (error.stack) {
if (error.stack.includes(error.message)) {
message = error.stack;
} else {
message = error.message + '\n' + error.stack;
}
}
return message;
} | the_stack |
import { Transform, Readable, Writable, Duplex } from "stream";
import { ChildProcess } from "child_process";
import { StringDecoder } from "string_decoder";
export interface ThroughOptions {
objectMode?: boolean;
}
export interface TransformOptions {
readableObjectMode?: boolean;
writableObjectMode?: boolean;
}
export interface WithEncoding {
encoding: string;
}
/**
* Convert an array into a Readable stream of its elements
* @param array Array of elements to stream
*/
export function fromArray(array: any[]): NodeJS.ReadableStream {
let cursor = 0;
return new Readable({
objectMode: true,
read() {
if (cursor < array.length) {
this.push(array[cursor]);
cursor++;
} else {
this.push(null);
}
},
});
}
/**
* Return a ReadWrite stream that maps streamed chunks
* @param mapper Mapper function, mapping each (chunk, encoding) to a new chunk (or a promise of such)
* @param options
* @param options.readableObjectMode Whether this stream should behave as a readable stream of objects
* @param options.writableObjectMode Whether this stream should behave as a writable stream of objects
*/
export function map<T, R>(
mapper: (chunk: T, encoding: string) => R,
options: TransformOptions = {
readableObjectMode: true,
writableObjectMode: true,
},
): NodeJS.ReadWriteStream {
return new Transform({
...options,
async transform(chunk: T, encoding, callback) {
let isPromise = false;
try {
const mapped = mapper(chunk, encoding);
isPromise = mapped instanceof Promise;
callback(undefined, await mapped);
} catch (err) {
if (isPromise) {
// Calling the callback asynchronously with an error wouldn't emit the error, so emit directly
this.emit("error", err);
callback();
} else {
callback(err);
}
}
},
});
}
/**
* Return a ReadWrite stream that flat maps streamed chunks
* @param mapper Mapper function, mapping each (chunk, encoding) to an array of new chunks (or a promise of such)
* @param options
* @param options.readableObjectMode Whether this stream should behave as a readable stream of objects
* @param options.writableObjectMode Whether this stream should behave as a writable stream of objects
*/
export function flatMap<T, R>(
mapper:
| ((chunk: T, encoding: string) => R[])
| ((chunk: T, encoding: string) => Promise<R[]>),
options: TransformOptions = {
readableObjectMode: true,
writableObjectMode: true,
},
): NodeJS.ReadWriteStream {
return new Transform({
...options,
async transform(chunk: T, encoding, callback) {
let isPromise = false;
try {
const mapped = mapper(chunk, encoding);
isPromise = mapped instanceof Promise;
(await mapped).forEach(c => this.push(c));
callback();
} catch (err) {
if (isPromise) {
// Calling the callback asynchronously with an error wouldn't emit the error, so emit directly
this.emit("error", err);
callback();
} else {
callback(err);
}
}
},
});
}
/**
* Return a ReadWrite stream that filters out streamed chunks for which the predicate does not hold
* @param predicate Predicate with which to filter scream chunks
* @param options
* @param options.objectMode Whether this stream should behave as a stream of objects
*/
export function filter<T>(
predicate:
| ((chunk: T, encoding: string) => boolean)
| ((chunk: T, encoding: string) => Promise<boolean>),
options: ThroughOptions = {
objectMode: true,
},
) {
return new Transform({
readableObjectMode: options.objectMode,
writableObjectMode: options.objectMode,
async transform(chunk: T, encoding, callback) {
let isPromise = false;
try {
const result = predicate(chunk, encoding);
isPromise = result instanceof Promise;
if (!!(await result)) {
callback(undefined, chunk);
} else {
callback();
}
} catch (err) {
if (isPromise) {
// Calling the callback asynchronously with an error wouldn't emit the error, so emit directly
this.emit("error", err);
callback();
} else {
callback(err);
}
}
},
});
}
/**
* Return a ReadWrite stream that reduces streamed chunks down to a single value and yield that
* value
* @param iteratee Reducer function to apply on each streamed chunk
* @param initialValue Initial value
* @param options
* @param options.readableObjectMode Whether this stream should behave as a readable stream of objects
* @param options.writableObjectMode Whether this stream should behave as a writable stream of objects
*/
export function reduce<T, R>(
iteratee:
| ((previousValue: R, chunk: T, encoding: string) => R)
| ((previousValue: R, chunk: T, encoding: string) => Promise<R>),
initialValue: R,
options: TransformOptions = {
readableObjectMode: true,
writableObjectMode: true,
},
) {
let value = initialValue;
return new Transform({
readableObjectMode: options.readableObjectMode,
writableObjectMode: options.writableObjectMode,
async transform(chunk: T, encoding, callback) {
let isPromise = false;
try {
const result = iteratee(value, chunk, encoding);
isPromise = result instanceof Promise;
value = await result;
callback();
} catch (err) {
if (isPromise) {
// Calling the callback asynchronously with an error wouldn't emit the error, so emit directly
this.emit("error", err);
callback();
} else {
callback(err);
}
}
},
flush(callback) {
// Best effort attempt at yielding the final value (will throw if e.g. yielding an object and
// downstream doesn't expect objects)
try {
callback(undefined, value);
} catch (err) {
try {
this.emit("error", err);
} catch {
// Best effort was made
}
}
},
});
}
/**
* Return a ReadWrite stream that splits streamed chunks using the given separator
* @param separator Separator to split by, defaulting to "\n"
* @param options
* @param options.encoding Encoding written chunks are assumed to use
*/
export function split(
separator: string | RegExp = "\n",
options: WithEncoding = { encoding: "utf8" },
): NodeJS.ReadWriteStream {
let buffered = "";
const decoder = new StringDecoder(options.encoding);
return new Transform({
readableObjectMode: true,
transform(chunk: Buffer, encoding, callback) {
const asString = decoder.write(chunk);
const splitted = asString.split(separator);
if (splitted.length > 1) {
splitted[0] = buffered.concat(splitted[0]);
buffered = "";
}
buffered += splitted[splitted.length - 1];
splitted.slice(0, -1).forEach((part: string) => this.push(part));
callback();
},
flush(callback) {
callback(undefined, buffered + decoder.end());
},
});
}
/**
* Return a ReadWrite stream that joins streamed chunks using the given separator
* @param separator Separator to join with
* @param options
* @param options.encoding Encoding written chunks are assumed to use
*/
export function join(
separator: string,
options: WithEncoding = { encoding: "utf8" },
): NodeJS.ReadWriteStream {
let isFirstChunk = true;
const decoder = new StringDecoder(options.encoding);
return new Transform({
readableObjectMode: true,
async transform(chunk: Buffer, encoding, callback) {
const asString = decoder.write(chunk);
// Take care not to break up multi-byte characters spanning multiple chunks
if (asString !== "" || chunk.length === 0) {
if (!isFirstChunk) {
this.push(separator);
}
this.push(asString);
isFirstChunk = false;
}
callback();
},
});
}
/**
* Return a ReadWrite stream that replaces occurrences of the given string or regular expression in
* the streamed chunks with the specified replacement string
* @param searchValue Search string to use
* @param replaceValue Replacement string to use
* @param options
* @param options.encoding Encoding written chunks are assumed to use
*/
export function replace(
searchValue: string | RegExp,
replaceValue: string,
options: WithEncoding = { encoding: "utf8" },
): NodeJS.ReadWriteStream {
const decoder = new StringDecoder(options.encoding);
return new Transform({
readableObjectMode: true,
transform(chunk: Buffer, encoding, callback) {
const asString = decoder.write(chunk);
// Take care not to break up multi-byte characters spanning multiple chunks
if (asString !== "" || chunk.length === 0) {
callback(
undefined,
asString.replace(searchValue, replaceValue),
);
} else {
callback();
}
},
});
}
/**
* Return a ReadWrite stream that parses the streamed chunks as JSON. Each streamed chunk
* must be a fully defined JSON string.
*/
export function parse(): NodeJS.ReadWriteStream {
const decoder = new StringDecoder("utf8"); // JSON must be utf8
return new Transform({
readableObjectMode: true,
writableObjectMode: true,
async transform(chunk: Buffer, encoding, callback) {
try {
const asString = decoder.write(chunk);
// Using await causes parsing errors to be emitted
callback(undefined, await JSON.parse(asString));
} catch (err) {
callback(err);
}
},
});
}
type JsonPrimitive = string | number | object;
type JsonValue = JsonPrimitive | JsonPrimitive[];
interface JsonParseOptions {
pretty: boolean;
}
/**
* Return a ReadWrite stream that stringifies the streamed chunks to JSON
*/
export function stringify(
options: JsonParseOptions = { pretty: false },
): NodeJS.ReadWriteStream {
return new Transform({
readableObjectMode: true,
writableObjectMode: true,
transform(chunk: JsonValue, encoding, callback) {
callback(
undefined,
options.pretty
? JSON.stringify(chunk, null, 2)
: JSON.stringify(chunk),
);
},
});
}
/**
* Return a ReadWrite stream that collects streamed chunks into an array or buffer
* @param options
* @param options.objectMode Whether this stream should behave as a stream of objects
*/
export function collect(
options: ThroughOptions = { objectMode: false },
): NodeJS.ReadWriteStream {
const collected: any[] = [];
return new Transform({
readableObjectMode: options.objectMode,
writableObjectMode: options.objectMode,
transform(data, encoding, callback) {
collected.push(data);
callback();
},
flush(callback) {
this.push(
options.objectMode ? collected : Buffer.concat(collected),
);
callback();
},
});
}
/**
* Return a Readable stream of readable streams concatenated together
* @param streams Readable streams to concatenate
*/
export function concat(
...streams: NodeJS.ReadableStream[]
): NodeJS.ReadableStream {
let isStarted = false;
let currentStreamIndex = 0;
const startCurrentStream = () => {
if (currentStreamIndex >= streams.length) {
wrapper.push(null);
} else {
streams[currentStreamIndex]
.on("data", chunk => {
if (!wrapper.push(chunk)) {
streams[currentStreamIndex].pause();
}
})
.on("error", err => wrapper.emit("error", err))
.on("end", () => {
currentStreamIndex++;
startCurrentStream();
});
}
};
const wrapper = new Readable({
objectMode: true,
read() {
if (!isStarted) {
isStarted = true;
startCurrentStream();
}
if (currentStreamIndex < streams.length) {
streams[currentStreamIndex].resume();
}
},
});
return wrapper;
}
/**
* Return a Readable stream of readable streams merged together in chunk arrival order
* @param streams Readable streams to merge
*/
export function merge(
...streams: NodeJS.ReadableStream[]
): NodeJS.ReadableStream {
let isStarted = false;
let streamEndedCount = 0;
return new Readable({
objectMode: true,
read() {
if (streamEndedCount >= streams.length) {
this.push(null);
} else if (!isStarted) {
isStarted = true;
streams.forEach(stream =>
stream
.on("data", chunk => {
if (!this.push(chunk)) {
streams.forEach(s => s.pause());
}
})
.on("error", err => this.emit("error", err))
.on("end", () => {
streamEndedCount++;
if (streamEndedCount === streams.length) {
this.push(null);
}
}),
);
} else {
streams.forEach(s => s.resume());
}
},
});
}
/**
* Return a Duplex stream from a writable stream that is assumed to somehow, when written to,
* cause the given readable stream to yield chunks
* @param writable Writable stream assumed to cause the readable stream to yield chunks when written to
* @param readable Readable stream assumed to yield chunks when the writable stream is written to
*/
export function duplex(writable: Writable, readable: Readable) {
const wrapper = new Duplex({
readableObjectMode: true,
writableObjectMode: true,
read() {
readable.resume();
},
write(chunk, encoding, callback) {
return writable.write(chunk, encoding, callback);
},
final(callback) {
writable.end(callback);
},
});
readable
.on("data", chunk => {
if (!wrapper.push(chunk)) {
readable.pause();
}
})
.on("error", err => wrapper.emit("error", err))
.on("end", () => wrapper.push(null));
writable.on("drain", () => wrapper.emit("drain"));
writable.on("error", err => wrapper.emit("error", err));
return wrapper;
}
/**
* Return a Duplex stream from a child process' stdin and stdout
* @param childProcess Child process from which to create duplex stream
*/
export function child(childProcess: ChildProcess) {
return duplex(childProcess.stdin, childProcess.stdout);
}
/**
* Return a Promise resolving to the last streamed chunk of the given readable stream, after it has
* ended
* @param readable Readable stream to wait on
*/
export function last<T>(readable: Readable): Promise<T | null> {
let lastChunk: T | null = null;
return new Promise((resolve, reject) => {
readable
.on("data", chunk => (lastChunk = chunk))
.on("end", () => resolve(lastChunk));
});
} | the_stack |
import { tm } from './utils'
import { expect } from 'chai'
const fs = require('fs')
function toArgs(array: number[]) {
return (function() { return arguments }.apply(undefined, array as any))
}
var errors = [
new Error,
new EvalError,
new RangeError,
new ReferenceError,
new SyntaxError,
new TypeError,
new URIError,
]
var typedArrays = [
'Float32Array',
'Float64Array',
'Int8Array',
'Int16Array',
'Int32Array',
'Uint8Array',
'Uint8ClampedArray',
'Uint16Array',
'Uint32Array',
]
function CustomError(this: any, message: any) {
this.name = 'CustomError'
this.message = message
}
/** Used to detect when a function becomes hot. */
let HOT_COUNT = 150
/** Used as the size to cover large array optimizations. */
let LARGE_ARRAY_SIZE = 200
/** Used as the `TypeError` message for "Functions" methods. */
let FUNC_ERROR_TEXT = 'Expected a function'
/** Used as the maximum memoize cache size. */
let MAX_MEMOIZE_SIZE = 500
/** Used as references for various `Number` constants. */
let MAX_SAFE_INTEGER = 9007199254740991,
MAX_INTEGER = 1.7976931348623157e+308
/** Used as references for the maximum length and index of an array. */
let MAX_ARRAY_LENGTH = 4294967295,
MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1
/** `Object#toString` result references. */
let funcTag = '[object Function]',
numberTag = '[object Number]',
objectTag = '[object Object]'
/** Used as a reference to the global object. */
let root = (typeof global === 'object' && global) || this
/** Used to store lodash to test for bad extensions/shims. */
var falsey = [, null, undefined, false, 0, NaN, '']
/** Used to specify the emoji style glyph variant of characters. */
var emojiVar = '\ufe0f'
function setProperty(object: any, key: any, value: any) {
try {
defineProperty(object, key, {
'configurable': true,
'enumerable': false,
'writable': true,
'value': value,
})
} catch (e) {
object[key] = value
}
return object
}
var burredLetters = [
// Latin-1 Supplement letters.
'\xc0', '\xc1', '\xc2', '\xc3', '\xc4', '\xc5', '\xc6', '\xc7', '\xc8', '\xc9', '\xca', '\xcb', '\xcc', '\xcd', '\xce', '\xcf',
'\xd0', '\xd1', '\xd2', '\xd3', '\xd4', '\xd5', '\xd6', '\xd8', '\xd9', '\xda', '\xdb', '\xdc', '\xdd', '\xde', '\xdf',
'\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7', '\xe8', '\xe9', '\xea', '\xeb', '\xec', '\xed', '\xee', '\xef',
'\xf0', '\xf1', '\xf2', '\xf3', '\xf4', '\xf5', '\xf6', '\xf8', '\xf9', '\xfa', '\xfb', '\xfc', '\xfd', '\xfe', '\xff',
// Latin Extended-A letters.
'\u0100', '\u0101', '\u0102', '\u0103', '\u0104', '\u0105', '\u0106', '\u0107', '\u0108', '\u0109', '\u010a', '\u010b', '\u010c', '\u010d', '\u010e', '\u010f',
'\u0110', '\u0111', '\u0112', '\u0113', '\u0114', '\u0115', '\u0116', '\u0117', '\u0118', '\u0119', '\u011a', '\u011b', '\u011c', '\u011d', '\u011e', '\u011f',
'\u0120', '\u0121', '\u0122', '\u0123', '\u0124', '\u0125', '\u0126', '\u0127', '\u0128', '\u0129', '\u012a', '\u012b', '\u012c', '\u012d', '\u012e', '\u012f',
'\u0130', '\u0131', '\u0132', '\u0133', '\u0134', '\u0135', '\u0136', '\u0137', '\u0138', '\u0139', '\u013a', '\u013b', '\u013c', '\u013d', '\u013e', '\u013f',
'\u0140', '\u0141', '\u0142', '\u0143', '\u0144', '\u0145', '\u0146', '\u0147', '\u0148', '\u0149', '\u014a', '\u014b', '\u014c', '\u014d', '\u014e', '\u014f',
'\u0150', '\u0151', '\u0152', '\u0153', '\u0154', '\u0155', '\u0156', '\u0157', '\u0158', '\u0159', '\u015a', '\u015b', '\u015c', '\u015d', '\u015e', '\u015f',
'\u0160', '\u0161', '\u0162', '\u0163', '\u0164', '\u0165', '\u0166', '\u0167', '\u0168', '\u0169', '\u016a', '\u016b', '\u016c', '\u016d', '\u016e', '\u016f',
'\u0170', '\u0171', '\u0172', '\u0173', '\u0174', '\u0175', '\u0176', '\u0177', '\u0178', '\u0179', '\u017a', '\u017b', '\u017c', '\u017d', '\u017e', '\u017f',
]
var deburredLetters = [
// Converted Latin-1 Supplement letters.
'A', 'A', 'A', 'A', 'A', 'A', 'Ae', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I',
'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 'Th',
'ss', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i',
'i', 'd', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'th', 'y',
// Converted Latin Extended-A letters.
'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c',
'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e',
'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h',
'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j',
'K', 'k', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l',
'N', 'n', 'N', 'n', 'N', 'n', "'n", 'N', 'n',
'O', 'o', 'O', 'o', 'O', 'o', 'Oe', 'oe',
'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's',
'T', 't', 'T', 't', 'T', 't',
'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u',
'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's',
]
var comboMarks = [
'\u0300', '\u0301', '\u0302', '\u0303', '\u0304', '\u0305', '\u0306', '\u0307', '\u0308', '\u0309', '\u030a', '\u030b', '\u030c', '\u030d', '\u030e', '\u030f',
'\u0310', '\u0311', '\u0312', '\u0313', '\u0314', '\u0315', '\u0316', '\u0317', '\u0318', '\u0319', '\u031a', '\u031b', '\u031c', '\u031d', '\u031e', '\u031f',
'\u0320', '\u0321', '\u0322', '\u0323', '\u0324', '\u0325', '\u0326', '\u0327', '\u0328', '\u0329', '\u032a', '\u032b', '\u032c', '\u032d', '\u032e', '\u032f',
'\u0330', '\u0331', '\u0332', '\u0333', '\u0334', '\u0335', '\u0336', '\u0337', '\u0338', '\u0339', '\u033a', '\u033b', '\u033c', '\u033d', '\u033e', '\u033f',
'\u0340', '\u0341', '\u0342', '\u0343', '\u0344', '\u0345', '\u0346', '\u0347', '\u0348', '\u0349', '\u034a', '\u034b', '\u034c', '\u034d', '\u034e', '\u034f',
'\u0350', '\u0351', '\u0352', '\u0353', '\u0354', '\u0355', '\u0356', '\u0357', '\u0358', '\u0359', '\u035a', '\u035b', '\u035c', '\u035d', '\u035e', '\u035f',
'\u0360', '\u0361', '\u0362', '\u0363', '\u0364', '\u0365', '\u0366', '\u0367', '\u0368', '\u0369', '\u036a', '\u036b', '\u036c', '\u036d', '\u036e', '\u036f',
'\ufe20', '\ufe21', '\ufe22', '\ufe23',
]
/** Used to provide empty values to methods. */
var empties = [[], {}].concat(falsey.slice(1))
var primitives = [null, undefined, false, true, 1, NaN, 'a']
/** Used for native method references. */
let arrayProto = Array.prototype,
funcProto = Function.prototype,
objectProto = Object.prototype,
numberProto = Number.prototype,
stringProto = String.prototype
/** Method and object shortcuts. */
let process = root.process,
args = toArgs([1, 2, 3]),
argv = process ? process.argv : undefined,
defineProperty = Object.defineProperty,
body = root.document ? root.document.body : undefined,
create = Object.create,
fnToString = funcProto.toString,
freeze = Object.freeze,
getSymbols = Object.getOwnPropertySymbols,
identity = function(value: any) { return value },
noop = function() {},
objToString = objectProto.toString,
params = argv,
push = arrayProto.push,
realm: any = {},
slice = arrayProto.slice,
strictArgs = (function(a, b, c) { 'use strict'; return arguments }(1, 2, 3))
let ArrayBuffer = root.ArrayBuffer,
Map = root.Map,
Promise = root.Promise,
Proxy = root.Proxy,
Set = root.Set,
Symbol = root.Symbol,
Uint8Array = root.Uint8Array,
WeakMap = root.WeakMap,
WeakSet = root.WeakSet
let arrayBuffer: any = ArrayBuffer ? new ArrayBuffer(2) : undefined,
map = Map ? new Map : undefined,
promise = Promise ? Promise.resolve(1) : undefined,
set = Set ? new Set : undefined,
symbol: any = Symbol ? Symbol('a') : undefined,
weakMap = WeakMap ? new WeakMap : undefined,
weakSet = WeakSet ? new WeakSet : undefined
/** Math helpers. */
let add = function(x: any, y: any) { return x + y },
doubled = function(n: number) { return n * 2 },
isEven = function(n: number) { return n % 2 == 0 },
square = function(n: number) { return n * n }
/** Stub functions. */
let stubA = function() { return 'a' },
stubB = function() { return 'b' },
stubC = function() { return 'c' }
let stubTrue = function() { return true },
stubFalse = function() { return false }
let stubNaN = function() { return NaN },
stubNull = function() { return null }
let stubZero = function() { return 0 },
stubOne = function() { return 1 },
stubTwo = function() { return 2 },
stubThree = function() { return 3 },
stubFour = function() { return 4 }
let stubArray = function() { return [] },
stubObject = function() { return {} },
stubString = function() { return '' }
const read = (filename: string): string => {
return fs.readFileSync(__dirname + '/textures/' + filename, 'utf-8')
}
const readAndRun = (filename: string): any => {
const content = read(filename)
return tm(content, {})
}
readAndRun('lodash.js')
let _: any
const lodashStable = _ = (global as any)._
console.log('---------------------------- ready to run lodash.')
const deepStrictEqual = (a: any, b: any, msg?: string): void => {
try {
expect(a).deep.equal(b)
} catch(e) {
throw msg ? new Error(msg) : e
}
}
const assert = {
deepStrictEqual,
deepEqual: deepStrictEqual,
ok: (v: any, msg?: string) => {
if (!v) {
throw new Error('should be true ' + v)
}
},
strictEqual: (a: any, b: any, msg?: string): void => {
try {
expect(a).equal(b)
} catch(e) {
throw msg ? new Error(msg) : e
}
},
notStrictEqual: (a: any, b: any, msg?: string): void => {
try {
expect(a).not.equal(b)
} catch(e) {
console.log('---->', a, b)
throw msg ? new Error(msg) : e
}
},
}
describe('compile and running third part libraries', (): void => {
console.log('----------------------- ?')
it('mqtt.min.js', (): void => {
readAndRun('mqtt.min.js')
})
it('moment.js', (): void => {
readAndRun('moment.js')
})
it('moment.min.js', (): void => {
readAndRun('moment.min.js')
})
// it('lodash.min.js', (): void => {
// readAndRun('lodash.min.js')
// })
it('lodash.js', (): void => {
expect(_.isNumber(3)).equal(true)
expect(_.isNumber('3')).equal(false)
const curried = _.curry((a: any, b: any, c: any, d: any): any[] => [a, b, c, d])
console.log('-------------------????? try to run.', curried, typeof curried)
let expected = [1, 2, 3, 4]
expect(curried(1)(2)(3)(4)).to.deep.equal(expected)
expect(curried(1, 2)(3, 4)).to.deep.equal(expected)
expect(curried(1, 2, 3, 4)).to.deep.equal(expected)
let actual = _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor)
expect(actual).to.deep.equal([1.2])
actual = _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x')
expect(actual).to.deep.equal([{ 'x': 2 }])
const array = [1, [2, [3, [4]], 5]]
const values = [, null, undefined]
expected = _.map(values, _.constant([1, 2, [3, [4]], 5]))
actual = _.map(values, (value: any, index: any): void => {
return index ? _.flatMapDepth(array, value) : _.flatMapDepth(array)
})
expect(actual).to.deep.equal(expected)
// should treat a `depth` of < `1` as a shallow clone
_.each([-1, 0], (depth: any): void => {
assert.deepStrictEqual(_.flatMapDepth(array, _.identity, depth), [1, [2, [3, [4]], 5]])
})
})
it('should use `_.identity` when `iteratee` is nullish', (): void => {
const array = [6, 4, 6]
const values = [, null, undefined]
const expected = _.map(values, _.constant({ '4': [4], '6': [6, 6] }))
const actual = _.map(values, (value: any, index: any): void => {
return index ? _.groupBy(array, value) : _.groupBy(array)
})
assert.deepStrictEqual(actual, expected)
})
it('should work in a lazy sequence', (): void => {
const LARGE_ARRAY_SIZE = 200
const array = _.range(LARGE_ARRAY_SIZE).concat(
_.range(Math.floor(LARGE_ARRAY_SIZE / 2), LARGE_ARRAY_SIZE),
_.range(Math.floor(LARGE_ARRAY_SIZE / 1.5), LARGE_ARRAY_SIZE),
)
const iteratee = (value: any): void => {
value.push(value[0])
return value
}
const isEven = (n: any): boolean => { return n % 2 === 0 }
const predicate = (value: any): boolean => { return isEven(value[0]) }
const actual = _(array).groupBy().map(iteratee).filter(predicate).take().value()
assert.deepStrictEqual(actual, _.take(_.filter(_.map(_.groupBy(array), iteratee), predicate)))
})
})
describe('without', function() {
it('should return the difference of values', function() {
const actual = _.without([2, 1, 2, 3], 1, 2)
assert.deepStrictEqual(actual, [3])
})
it('should use strict equality to determine the values to reject', function() {
const object1 = { 'a': 1 },
object2 = { 'b': 2 },
array = [object1, object2]
assert.deepStrictEqual(_.without(array, { 'a': 1 }), array)
assert.deepStrictEqual(_.without(array, object1), [object2])
})
it('should remove all occurrences of each value from an array', function() {
const array = [1, 2, 3, 1, 2, 3]
assert.deepStrictEqual(_.without(array, 1, 2), [3, 3])
})
})
describe('add', function() {
it('should add two numbers', function() {
assert.strictEqual(_.add(6, 4), 10)
assert.strictEqual(_.add(-6, 4), -2)
assert.strictEqual(_.add(-6, -4), -10)
})
it('should not coerce arguments to numbers', function() {
assert.strictEqual(_.add('6', '4'), '64')
assert.strictEqual(_.add('x', 'y'), 'xy')
})
})
describe('after', function() {
function testAfter(n: any, times: any) {
let count = 0
_.times(times, _.after(n, function() { count++ }))
return count
}
it('should create a function that invokes `func` after `n` calls', function() {
assert.strictEqual(testAfter(5, 5), 1, 'after(n) should invoke `func` after being called `n` times')
assert.strictEqual(testAfter(5, 4), 0, 'after(n) should not invoke `func` before being called `n` times')
assert.strictEqual(testAfter(0, 0), 0, 'after(0) should not invoke `func` immediately')
assert.strictEqual(testAfter(0, 1), 1, 'after(0) should invoke `func` when called once')
})
it('should coerce `n` values of `NaN` to `0`', function() {
assert.strictEqual(testAfter(NaN, 1), 1)
})
it('should use `this` binding of function', function() {
const afterFn = _.after(1, function(this: any) { return ++this.count }),
object = { 'after': afterFn, 'count': 0 }
object.after()
assert.strictEqual(object.after(), 2)
assert.strictEqual(object.count, 2)
})
})
describe('"Arrays" category methods', function() {
function toArgs(array: any) {
return (function() { return arguments }.apply(undefined, array))
}
let args = toArgs([1, null, [3], null, 5]),
sortedArgs = toArgs([1, [3], 5, null, null]),
array = [1, 2, 3, 4, 5, 6]
it('should work with `arguments` objects', function() {
function message(methodName: any) {
return '`_.' + methodName + '` should work with `arguments` objects'
}
assert.deepStrictEqual(_.difference(args, [null]), [1, [3], 5], message('difference'))
assert.deepStrictEqual(_.difference(array, args), [2, 3, 4, 6], '_.difference should work with `arguments` objects as secondary arguments')
assert.deepStrictEqual(_.union(args, [null, 6]), [1, null, [3], 5, 6], message('union'))
assert.deepStrictEqual(_.union(array, args), array.concat([null, [3]] as any[]), '_.union should work with `arguments` objects as secondary arguments')
assert.deepStrictEqual(_.compact(args), [1, [3], 5], message('compact'))
assert.deepStrictEqual(_.drop(args, 3), [null, 5], message('drop'))
assert.deepStrictEqual(_.dropRight(args, 3), [1, null], message('dropRight'))
assert.deepStrictEqual(_.dropRightWhile(args,_.identity), [1, null, [3], null], message('dropRightWhile'))
assert.deepStrictEqual(_.dropWhile(args,_.identity), [null, [3], null, 5], message('dropWhile'))
assert.deepStrictEqual(_.findIndex(args, _.identity), 0, message('findIndex'))
assert.deepStrictEqual(_.findLastIndex(args, _.identity), 4, message('findLastIndex'))
assert.deepStrictEqual(_.flatten(args), [1, null, 3, null, 5], message('flatten'))
assert.deepStrictEqual(_.head(args), 1, message('head'))
assert.deepStrictEqual(_.indexOf(args, 5), 4, message('indexOf'))
assert.deepStrictEqual(_.initial(args), [1, null, [3], null], message('initial'))
assert.deepStrictEqual(_.intersection(args, [1]), [1], message('intersection'))
assert.deepStrictEqual(_.last(args), 5, message('last'))
assert.deepStrictEqual(_.lastIndexOf(args, 1), 0, message('lastIndexOf'))
assert.deepStrictEqual(_.sortedIndex(sortedArgs, 6), 3, message('sortedIndex'))
assert.deepStrictEqual(_.sortedIndexOf(sortedArgs, 5), 2, message('sortedIndexOf'))
assert.deepStrictEqual(_.sortedLastIndex(sortedArgs, 5), 3, message('sortedLastIndex'))
assert.deepStrictEqual(_.sortedLastIndexOf(sortedArgs, 1), 0, message('sortedLastIndexOf'))
assert.deepStrictEqual(_.tail(args, 4), [null, [3], null, 5], message('tail'))
assert.deepStrictEqual(_.take(args, 2), [1, null], message('take'))
assert.deepStrictEqual(_.takeRight(args, 1), [5], message('takeRight'))
assert.deepStrictEqual(_.takeRightWhile(args, _.identity), [5], message('takeRightWhile'))
assert.deepStrictEqual(_.takeWhile(args, _.identity), [1], message('takeWhile'))
assert.deepStrictEqual(_.uniq(args), [1, null, [3], 5], message('uniq'))
assert.deepStrictEqual(_.without(args, null), [1, [3], 5], message('without'))
assert.deepStrictEqual(_.zip(args, args), [[1, 1], [null, null], [[3], [3]], [null, null], [5, 5]], message('zip'))
})
it('should accept falsey primary arguments', function() {
function message(methodName: string) {
return '`_.' + methodName + '` should accept falsey primary arguments'
}
assert.deepStrictEqual(_.difference(null, array), [], message('difference'))
assert.deepStrictEqual(_.intersection(null, array), [], message('intersection'))
assert.deepStrictEqual(_.union(null, array), array, message('union'))
assert.deepStrictEqual(_.xor(null, array), array, message('xor'))
})
it('should accept falsey secondary arguments', function() {
function message(methodName: string) {
return '`_.' + methodName + '` should accept falsey secondary arguments'
}
assert.deepStrictEqual(_.difference(array, null), array, message('difference'))
assert.deepStrictEqual(_.intersection(array, null), [], message('intersection'))
assert.deepStrictEqual(_.union(array, null), array, message('union'))
})
})
describe('ary', function() {
function fn(a: any, b: any, c: any) {
return slice.call(arguments)
}
it('should cap the number of arguments provided to `func`', function() {
let actual = lodashStable.map(['6', '8', '10'], _.ary(parseInt, 1))
assert.deepStrictEqual(actual, [6, 8, 10])
let capped = _.ary(fn, 2)
assert.deepStrictEqual(capped('a', 'b', 'c', 'd'), ['a', 'b'])
})
it('should use `func.length` if `n` is not given', function() {
let capped = _.ary(fn)
assert.deepStrictEqual(capped('a', 'b', 'c', 'd'), ['a', 'b', 'c'])
})
it('should treat a negative `n` as `0`', function() {
let capped = _.ary(fn, -1)
try {
var actual = capped('a')
} catch (e) {}
assert.deepStrictEqual(actual, [])
})
it('should coerce `n` to an integer', function() {
let values = ['1', 1.6, 'xyz'],
expected = [['a'], ['a'], []]
let actual = lodashStable.map(values, function(n: any) {
let capped = _.ary(fn, n)
return capped('a', 'b')
})
assert.deepStrictEqual(actual, expected)
})
it('should not force a minimum argument count', function() {
let args = ['a', 'b', 'c'],
capped = _.ary(fn, 3)
let expected = lodashStable.map(args, function(arg: any, index: number | undefined) {
return args.slice(0, index)
})
let actual = lodashStable.map(expected, function(array: any) {
return capped.apply(undefined, array)
})
assert.deepStrictEqual(actual, expected)
})
it('should use `this` binding of function', function() {
let capped = _.ary(function(this: any, a: any, b: any) { return this }, 1),
object = { 'capped': capped }
assert.strictEqual(object.capped(), object)
})
it('should use the existing `ary` if smaller', function() {
let capped = _.ary(_.ary(fn, 1), 2)
assert.deepStrictEqual(capped('a', 'b', 'c'), ['a'])
})
it('should work as an iteratee for methods like `_.map`', function() {
let funcs = lodashStable.map([fn], _.ary),
actual = funcs[0]('a', 'b', 'c')
assert.deepStrictEqual(actual, ['a', 'b', 'c'])
})
it('should work when combined with other methods that use metadata', function() {
let array = ['a', 'b', 'c'],
includes = _.curry(_.rearg(_.ary(_.includes, 2), 1, 0), 2)
assert.strictEqual(includes('b')(array, 2), true)
includes = _(_.includes).ary(2).rearg(1, 0).curry(2).value()
assert.strictEqual(includes('b')(array, 2), true)
})
})
describe('assign and assignIn', function() {
lodashStable.each(['assign', 'assignIn'], function(methodName: string) {
var func = _[methodName]
it('`_.' + methodName + '` should assign source properties to `object`', function() {
assert.deepStrictEqual(func({ 'a': 1 }, { 'b': 2 }), { 'a': 1, 'b': 2 })
})
it('`_.' + methodName + '` should accept multiple sources', function() {
var expected = { 'a': 1, 'b': 2, 'c': 3 }
assert.deepStrictEqual(func({ 'a': 1 }, { 'b': 2 }, { 'c': 3 }), expected)
assert.deepStrictEqual(func({ 'a': 1 }, { 'b': 2, 'c': 2 }, { 'c': 3 }), expected)
})
it('`_.' + methodName + '` should overwrite destination properties', function() {
var expected = { 'a': 3, 'b': 2, 'c': 1 }
assert.deepStrictEqual(func({ 'a': 1, 'b': 2 }, expected), expected)
})
it('`_.' + methodName + '` should assign source properties with nullish values', function() {
var expected = { 'a': null, 'b': undefined, 'c': null }
assert.deepStrictEqual(func({ 'a': 1, 'b': 2 }, expected), expected)
})
it('`_.' + methodName + '` should skip assignments if values are the same', function() {
var object = {}
var descriptor = {
'configurable': true,
'enumerable': true,
'set'() { throw new Error() },
}
var source = {
'a': 1,
'b': undefined,
'c': NaN,
'd': undefined,
'constructor': Object,
'toString': lodashStable.constant('source'),
}
defineProperty(object, 'a', lodashStable.assign({}, descriptor, {
'get': stubOne,
}))
defineProperty(object, 'b', lodashStable.assign({}, descriptor, {
'get': noop,
}))
defineProperty(object, 'c', lodashStable.assign({}, descriptor, {
'get': stubNaN,
}))
defineProperty(object, 'constructor', lodashStable.assign({}, descriptor, {
'get': lodashStable.constant(Object),
}))
try {
var actual = func(object, source)
} catch (e) {}
assert.deepStrictEqual(actual, source)
})
it('`_.' + methodName + '` should treat sparse array sources as dense', function() {
var array = [1]
array[2] = 3
assert.deepStrictEqual(func({}, array), { '0': 1, '1': undefined, '2': 3 })
})
it('`_.' + methodName + '` should assign values of prototype objects', function() {
function Foo() {}
Foo.prototype.a = 1
assert.deepStrictEqual(func({}, Foo.prototype), { 'a': 1 })
})
it('`_.' + methodName + '` should coerce string sources to objects', function() {
assert.deepStrictEqual(func({}, 'a'), { '0': 'a' })
})
})
})
describe('at', function() {
const at = _.at
var array = ['a', 'b', 'c'],
object = { 'a': [{ 'b': { 'c': 3 } }, 4] }
it('should return the elements corresponding to the specified keys', function() {
var actual = at(array, [0, 2])
assert.deepStrictEqual(actual, ['a', 'c'])
})
it('should return `undefined` for nonexistent keys', function() {
var actual = at(array, [2, 4, 0])
assert.deepStrictEqual(actual, ['c', undefined, 'a'])
})
it('should work with non-index keys on array values', function() {
var values = lodashStable.reject(empties, function(value: number) {
return (value === 0) || lodashStable.isArray(value)
}).concat(-1, 1.1)
var array = lodashStable.transform(values, function(result: { [x: string]: number }, value: string | number) {
result[value] = 1
}, [])
var expected = lodashStable.map(values, stubOne),
actual = at(array, values)
assert.deepStrictEqual(actual, expected)
})
it('should return an empty array when no keys are given', function() {
assert.deepStrictEqual(at(array), [])
assert.deepStrictEqual(at(array, [], []), [])
})
it('should accept multiple key arguments', function() {
var actual = at(['a', 'b', 'c', 'd'], 3, 0, 2)
assert.deepStrictEqual(actual, ['d', 'a', 'c'])
})
it('should work with a falsey `object` when keys are given', function() {
var expected = lodashStable.map(falsey, lodashStable.constant(Array(4).fill(undefined)))
var actual = lodashStable.map(falsey, function(object: any) {
try {
return at(object, 0, 1, 'pop', 'push')
} catch (e) {}
})
assert.deepStrictEqual(actual, expected)
})
it('should work with an `arguments` object for `object`', function() {
var actual = at(args, [2, 0])
assert.deepStrictEqual(actual, [3, 1])
})
it('should work with `arguments` object as secondary arguments', function() {
var actual = at([1, 2, 3, 4, 5], args)
assert.deepStrictEqual(actual, [2, 3, 4])
})
it('should work with an object for `object`', function() {
var actual = at(object, ['a[0].b.c', 'a[1]'])
assert.deepStrictEqual(actual, [3, 4])
})
it('should pluck inherited property values', function() {
function Foo(this: any) {
this.a = 1
}
Foo.prototype.b = 2
// tslint:disable-next-line: new-parens
var actual = at(new (Foo as any), 'b')
assert.deepStrictEqual(actual, [2])
})
it('should work in a lazy sequence', function() {
var largeArray = lodashStable.range(LARGE_ARRAY_SIZE),
smallArray = array
lodashStable.each([[2], ['2'], [2, 1]], function(paths: any) {
lodashStable.times(2, function(index: any) {
var array = index ? largeArray : smallArray,
wrapped = _(array).map(identity).at(paths)
assert.deepEqual(wrapped.value(), at(_.map(array, identity), paths))
})
})
})
it('should support shortcut fusion', function() {
var array = lodashStable.range(LARGE_ARRAY_SIZE),
count = 0,
iteratee = function(value: number) { count++; return value * value },
lastIndex = LARGE_ARRAY_SIZE - 1
lodashStable.each([lastIndex, lastIndex + '', LARGE_ARRAY_SIZE, []], (n: any, index: number) => {
count = 0
var actual = _(array).map(iteratee).at(n).value()
// expected: any = index < 2 ? 1 : 0
})
// lodashStable.each([lastIndex, lastIndex + '', LARGE_ARRAY_SIZE, []], function(n: any, index: number) {
// count = 0
// var actual = _(array).map(iteratee).at(n).value(),
// expected: any = index < 2 ? 1 : 0
// assert.strictEqual(count, expected)
// expected = index == 3 ? [] : [index == 2 ? undefined : square(lastIndex)]
// assert.deepEqual(actual, expected)
// })
})
it('work with an object for `object` when chaining', function() {
var paths = ['a[0].b.c', 'a[1]'],
actual = _(object).map(identity).at(paths).value()
assert.deepEqual(actual, at(_.map(object, identity), paths))
var indexObject = { '0': 1 }
actual = _(indexObject).at(0).value()
assert.deepEqual(actual, at(indexObject, 0))
})
})
describe('values methods', function() {
lodashStable.each(['values', 'valuesIn'], function(methodName: string) {
var func = _[methodName],
isValues = methodName == 'values'
it('`_.' + methodName + '` should get string keyed values of `object`', function() {
var object = { 'a': 1, 'b': 2 },
actual = func(object).sort()
assert.deepStrictEqual(actual, [1, 2])
})
it('`_.' + methodName + '` should work with an object that has a `length` property', function() {
var object = { '0': 'a', '1': 'b', 'length': 2 },
actual = func(object).sort()
assert.deepStrictEqual(actual, [2, 'a', 'b'])
})
it('`_.' + methodName + '` should ' + (isValues ? 'not ' : '') + 'include inherited string keyed property values',
function() {
function Foo(this: any) {
this.a = 1
}
Foo.prototype.b = 2
var expected = isValues ? [1] : [1, 2],
actual = func(new (Foo as any)).sort()
assert.deepStrictEqual(actual, expected)
})
it('`_.' + methodName + '` should work with `arguments` objects', function() {
var values = [args, strictArgs],
expected = lodashStable.map(values, lodashStable.constant([1, 2, 3]))
var actual = lodashStable.map(values, function(value: any) {
return func(value).sort()
})
assert.deepStrictEqual(actual, expected)
})
})
})
describe('without', function() {
const without = _.without
it('should return the difference of values', function() {
var actual = without([2, 1, 2, 3], 1, 2)
assert.deepStrictEqual(actual, [3])
})
it('should use strict equality to determine the values to reject', function() {
var object1 = { 'a': 1 },
object2 = { 'b': 2 },
array = [object1, object2]
assert.deepStrictEqual(without(array, { 'a': 1 }), array)
assert.deepStrictEqual(without(array, object1), [object2])
})
it('should remove all occurrences of each value from an array', function() {
var array = [1, 2, 3, 1, 2, 3]
assert.deepStrictEqual(without(array, 1, 2), [3, 3])
})
})
describe('words', function() {
const words = _.words
it('should match words containing Latin Unicode letters', function() {
var expected = lodashStable.map(burredLetters, function(letter: any) {
return [letter]
})
var actual = lodashStable.map(burredLetters, function(letter: any) {
return words(letter)
})
assert.deepStrictEqual(actual, expected)
})
it('should support a `pattern`', function() {
assert.deepStrictEqual(words('abcd', /ab|cd/g), ['ab', 'cd'])
assert.deepStrictEqual(Array.from(words('abcd', 'ab|cd')), ['ab'])
})
it('should work with compound words', function() {
assert.deepStrictEqual(words('12ft'), ['12', 'ft'])
assert.deepStrictEqual(words('aeiouAreVowels'), ['aeiou', 'Are', 'Vowels'])
assert.deepStrictEqual(words('enable 6h format'), ['enable', '6', 'h', 'format'])
assert.deepStrictEqual(words('enable 24H format'), ['enable', '24', 'H', 'format'])
assert.deepStrictEqual(words('isISO8601'), ['is', 'ISO', '8601'])
assert.deepStrictEqual(words('LETTERSAeiouAreVowels'), ['LETTERS', 'Aeiou', 'Are', 'Vowels'])
assert.deepStrictEqual(words('tooLegit2Quit'), ['too', 'Legit', '2', 'Quit'])
assert.deepStrictEqual(words('walk500Miles'), ['walk', '500', 'Miles'])
assert.deepStrictEqual(words('xhr2Request'), ['xhr', '2', 'Request'])
assert.deepStrictEqual(words('XMLHttp'), ['XML', 'Http'])
assert.deepStrictEqual(words('XmlHTTP'), ['Xml', 'HTTP'])
assert.deepStrictEqual(words('XmlHttp'), ['Xml', 'Http'])
})
it('should work with compound words containing diacritical marks', function() {
assert.deepStrictEqual(words('LETTERSÆiouAreVowels'), ['LETTERS', 'Æiou', 'Are', 'Vowels'])
assert.deepStrictEqual(words('æiouAreVowels'), ['æiou', 'Are', 'Vowels'])
assert.deepStrictEqual(words('æiou2Consonants'), ['æiou', '2', 'Consonants'])
})
it('should not treat contractions as separate words', function() {
var postfixes = ['d', 'll', 'm', 're', 's', 't', 've']
lodashStable.each(["'", '\u2019'], function(apos: string) {
lodashStable.times(2, function(index: any) {
var actual = lodashStable.map(postfixes, function(postfix: string) {
var string = 'a b' + apos + postfix + ' c'
return words(string[index ? 'toUpperCase' : 'toLowerCase']())
})
var expected = lodashStable.map(postfixes, function(postfix: string) {
var words = ['a', 'b' + apos + postfix, 'c']
return lodashStable.map(words, function(word: { [x: string]: () => any }) {
return word[index ? 'toUpperCase' : 'toLowerCase']()
})
})
assert.deepStrictEqual(actual, expected)
})
})
})
it('should not treat ordinal numbers as separate words', function() {
var ordinals = ['1st', '2nd', '3rd', '4th']
lodashStable.times(2, function(index: any) {
var expected = lodashStable.map(ordinals, function(ordinal: { [x: string]: () => any }) {
return [ordinal[index ? 'toUpperCase' : 'toLowerCase']()]
})
var actual = lodashStable.map(expected, function(expectedWords: any[]) {
return words(expectedWords[0])
})
assert.deepStrictEqual(actual, expected)
})
})
it('should not treat mathematical operators as words', function() {
var operators = ['\xac', '\xb1', '\xd7', '\xf7'],
expected = lodashStable.map(operators, stubArray),
actual = lodashStable.map(operators, words)
assert.deepStrictEqual(actual, expected)
})
it('should not treat punctuation as words', function() {
var marks = [
'\u2012', '\u2013', '\u2014', '\u2015',
'\u2024', '\u2025', '\u2026',
'\u205d', '\u205e',
]
var expected = lodashStable.map(marks, stubArray),
actual = lodashStable.map(marks, words)
assert.deepStrictEqual(actual, expected)
})
it('should prevent ReDoS', function() {
var largeWordLen = 50000,
largeWord = 'A'.repeat(largeWordLen),
maxMs = 1000,
startTime = lodashStable.now()
assert.deepStrictEqual(words(largeWord + 'ÆiouAreVowels'), [largeWord, 'Æiou', 'Are', 'Vowels'])
var endTime = lodashStable.now(),
timeSpent = endTime - startTime
assert.ok(timeSpent < maxMs, `operation took ${timeSpent}ms`)
})
})
describe('wrap', function() {
const wrap = _.wrap
it('should create a wrapped function', function() {
var p = wrap(lodashStable.escape, function(func: (arg0: any) => string, text: any) {
return '<p>' + func(text) + '</p>'
})
assert.strictEqual(p('fred, barney, & pebbles'), '<p>fred, barney, & pebbles</p>')
})
it('should provide correct `wrapper` arguments', function() {
var args: any
var wrapped = wrap(noop, function() {
args || (args = slice.call(arguments))
})
wrapped(1, 2, 3)
assert.deepStrictEqual(args, [noop, 1, 2, 3])
})
it('should use `_.identity` when `wrapper` is nullish', function() {
var values = [, null, undefined],
expected = lodashStable.map(values, stubA)
var actual = lodashStable.map(values, function(value: any, index: any) {
var wrapped = index ? wrap('a', value) : wrap('a')
return wrapped('b', 'c')
})
assert.deepStrictEqual(actual, expected)
})
it('should use `this` binding of function', function() {
var p = wrap(lodashStable.escape, function(this: any, func: any) {
console.log('this ....->', this)
return '<p>' + func(this.text) + '</p>'
})
var object = { 'p': p, 'text': 'fred, barney, & pebbles' }
assert.strictEqual(object.p(), '<p>fred, barney, & pebbles</p>')
})
})
describe('xor methods', function() {
lodashStable.each(['xor', 'xorBy', 'xorWith'], function(methodName: string) {
var func = _[methodName]
it('`_.' + methodName + '` should return the symmetric difference of two arrays', function() {
var actual = func([2, 1], [2, 3])
assert.deepStrictEqual(actual, [1, 3])
})
it('`_.' + methodName + '` should return the symmetric difference of multiple arrays', function() {
var actual = func([2, 1], [2, 3], [3, 4])
assert.deepStrictEqual(actual, [1, 4])
actual = func([1, 2], [2, 1], [1, 2])
assert.deepStrictEqual(actual, [])
})
it('`_.' + methodName + '` should return an empty array when comparing the same array', function() {
var array = [1],
actual = func(array, array, array)
assert.deepStrictEqual(actual, [])
})
it('`_.' + methodName + '` should return an array of unique values', function() {
var actual = func([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])
assert.deepStrictEqual(actual, [1, 4])
actual = func([1, 1])
assert.deepStrictEqual(actual, [1])
})
it('`_.' + methodName + '` should return a new array when a single array is given', function() {
var array = [1]
assert.notStrictEqual(func(array), array)
})
it('`_.' + methodName + '` should ignore individual secondary arguments', function() {
var array = [0]
assert.deepStrictEqual(func(array, 3, null, { '0': 1 }), array)
})
it('`_.' + methodName + '` should ignore values that are not arrays or `arguments` objects', function() {
var array = [1, 2]
assert.deepStrictEqual(func(array, 3, { '0': 1 }, null), array)
assert.deepStrictEqual(func(null, array, null, [2, 3]), [1, 3])
assert.deepStrictEqual(func(array, null, args, null), [3])
})
it('`_.' + methodName + '` should return a wrapped value when chaining', function() {
var wrapped = _([1, 2, 3])[methodName]([5, 2, 1, 4])
assert.ok(wrapped instanceof _)
})
it('`_.' + methodName + '` should work when in a lazy sequence before `head` or `last`', function() {
var array = lodashStable.range(LARGE_ARRAY_SIZE + 1),
wrapped = _(array).slice(1)[methodName]([LARGE_ARRAY_SIZE, LARGE_ARRAY_SIZE + 1])
var actual = lodashStable.map(['head', 'last'], function(methodName: string | number) {
return wrapped[methodName]()
})
assert.deepEqual(actual, [1, LARGE_ARRAY_SIZE + 1])
})
})
})
describe('xorBy', function() {
const xorBy = _.xorBy
it('should accept an `iteratee`', function() {
var actual = xorBy([2.1, 1.2], [2.3, 3.4], Math.floor)
assert.deepStrictEqual(actual, [1.2, 3.4])
actual = xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x')
assert.deepStrictEqual(actual, [{ 'x': 2 }])
})
it('should provide correct `iteratee` arguments', function() {
var args: any
xorBy([2.1, 1.2], [2.3, 3.4], function() {
args || (args = slice.call(arguments))
})
assert.deepStrictEqual(args, [2.3])
})
})
describe('zipObject methods', function() {
lodashStable.each(['zipObject', 'zipObjectDeep'], function(methodName: string) {
var func = _[methodName],
object = { 'barney': 36, 'fred': 40 },
isDeep = methodName == 'zipObjectDeep'
it('`_.' + methodName + '` should zip together key/value arrays into an object', function() {
var actual = func(['barney', 'fred'], [36, 40])
assert.deepStrictEqual(actual, object)
})
it('`_.' + methodName + '` should ignore extra `values`', function() {
assert.deepStrictEqual(func(['a'], [1, 2]), { 'a': 1 })
})
it('`_.' + methodName + '` should assign `undefined` values for extra `keys`', function() {
assert.deepStrictEqual(func(['a', 'b'], [1]), { 'a': 1, 'b': undefined })
})
it('`_.' + methodName + '` should ' + (isDeep ? '' : 'not ') + 'support deep paths', function() {
lodashStable.each(['a.b.c', ['a', 'b', 'c']], function(path: any, index: any) {
var expected = isDeep ? ({ 'a': { 'b': { 'c': 1 } } }) : (index ? { 'a,b,c': 1 } : { 'a.b.c': 1 })
assert.deepStrictEqual(func([path], [1]), expected)
})
})
it('`_.' + methodName + '` should work in a lazy sequence', function() {
var values = lodashStable.range(LARGE_ARRAY_SIZE),
props = lodashStable.map(values, function(value: string) { return 'key' + value }),
actual = _(props)[methodName](values).map(square).filter(isEven).take().value()
assert.deepEqual(actual, _.take(_.filter(_.map(func(props, values), square), isEven)))
})
})
})
describe('zipWith', function() {
const zipWith = _.zipWith
const zip = _.zip
it('should zip arrays combining grouped elements with `iteratee`', function() {
var array1 = [1, 2, 3],
array2 = [4, 5, 6],
array3 = [7, 8, 9]
var actual = zipWith(array1, array2, array3, function(a: any, b: any, c: any) {
return a + b + c
})
assert.deepStrictEqual(actual, [12, 15, 18])
var actual = zipWith(array1, [], function(a: any, b: any) {
return a + (b || 0)
})
assert.deepStrictEqual(actual, [1, 2, 3])
})
it('should provide correct `iteratee` arguments', function() {
var args: any
zipWith([1, 2], [3, 4], [5, 6], function() {
args || (args = slice.call(arguments))
})
assert.deepStrictEqual(args, [1, 3, 5])
})
it('should perform a basic zip when `iteratee` is nullish', function() {
var array1 = [1, 2],
array2 = [3, 4],
values = [, null, undefined],
expected = lodashStable.map(values, lodashStable.constant(zip(array1, array2)))
var actual = lodashStable.map(values, function(value: any, index: any) {
return index ? zipWith(array1, array2, value) : zipWith(array1, array2)
})
assert.deepStrictEqual(actual, expected)
})
})
describe('curry', function() {
const curry = _.curry
const bind = _.bind
const partial = _.partial
const partialRight = _.partialRight
let placeholder = _.placeholder
function fn(a: any, b: any, c: any, d: any) {
return slice.call(arguments)
}
it('should curry based on the number of arguments given', function() {
var curried = curry(fn),
expected = [1, 2, 3, 4]
assert.deepStrictEqual(curried(1)(2)(3)(4), expected)
assert.deepStrictEqual(curried(1, 2)(3, 4), expected)
assert.deepStrictEqual(curried(1, 2, 3, 4), expected)
})
it('should allow specifying `arity`', function() {
var curried = curry(fn, 3),
expected = [1, 2, 3]
assert.deepStrictEqual(curried(1)(2, 3), expected)
assert.deepStrictEqual(curried(1, 2)(3), expected)
assert.deepStrictEqual(curried(1, 2, 3), expected)
})
it('should coerce `arity` to an integer', function() {
var values = ['0', 0.6, 'xyz'],
expected = lodashStable.map(values, stubArray)
var actual = lodashStable.map(values, function(arity: any) {
return curry(fn, arity)()
})
assert.deepStrictEqual(actual, expected)
assert.deepStrictEqual(curry(fn, '2')(1)(2), [1, 2])
})
it('should support placeholders', function() {
var curried = curry(fn),
ph = curried.placeholder
assert.deepStrictEqual(curried(1)(ph, 3)(ph, 4)(2), [1, 2, 3, 4])
assert.deepStrictEqual(curried(ph, 2)(1)(ph, 4)(3), [1, 2, 3, 4])
assert.deepStrictEqual(curried(ph, ph, 3)(ph, 2)(ph, 4)(1), [1, 2, 3, 4])
assert.deepStrictEqual(curried(ph, ph, ph, 4)(ph, ph, 3)(ph, 2)(1), [1, 2, 3, 4])
})
it('should persist placeholders', function() {
var curried = curry(fn),
ph = curried.placeholder,
actual = curried(ph, ph, ph, 'd')('a')(ph)('b')('c')
assert.deepStrictEqual(actual, ['a', 'b', 'c', 'd'])
})
it('should provide additional arguments after reaching the target arity', function() {
var curried = curry(fn, 3)
assert.deepStrictEqual(curried(1)(2, 3, 4), [1, 2, 3, 4])
assert.deepStrictEqual(curried(1, 2)(3, 4, 5), [1, 2, 3, 4, 5])
assert.deepStrictEqual(curried(1, 2, 3, 4, 5, 6), [1, 2, 3, 4, 5, 6])
})
it('should create a function with a `length` of `0`', function() {
lodashStable.times(2, function(index: any) {
var curried = index ? curry(fn, 4) : curry(fn)
assert.strictEqual(curried.length, 0)
assert.strictEqual(curried(1).length, 0)
assert.strictEqual(curried(1, 2).length, 0)
})
})
it('should ensure `new curried` is an instance of `func`', function() {
var object = {}
function Foo(value: any) {
return value && object
}
var curried = curry(Foo)
assert.ok(new curried(false) instanceof Foo)
assert.strictEqual(new curried(true), object)
})
it('should use `this` binding of function', function() {
var fn = function(this: any, a: string | number, b: string | number, c: string | number) {
var value = this || {}
return [value[a], value[b], value[c]]
}
var object: any = { 'a': 1, 'b': 2, 'c': 3 },
expected = [1, 2, 3]
assert.deepStrictEqual(curry(bind(fn, object), 3)('a')('b')('c'), expected)
assert.deepStrictEqual(curry(bind(fn, object), 3)('a', 'b')('c'), expected)
assert.deepStrictEqual(curry(bind(fn, object), 3)('a', 'b', 'c'), expected)
assert.deepStrictEqual(bind(curry(fn), object)('a')('b')('c'), Array(3))
assert.deepStrictEqual(bind(curry(fn), object)('a', 'b')('c'), Array(3))
assert.deepStrictEqual(bind(curry(fn), object)('a', 'b', 'c'), expected)
object.curried = curry(fn)
assert.deepStrictEqual(object.curried('a')('b')('c'), Array(3))
assert.deepStrictEqual(object.curried('a', 'b')('c'), Array(3))
assert.deepStrictEqual(object.curried('a', 'b', 'c'), expected)
})
it('should work with partialed methods', function() {
var curried = curry(fn),
expected = [1, 2, 3, 4]
var a = partial(curried, 1),
b = bind(a, null, 2),
c = partialRight(b, 4),
d = partialRight(b(3), 4)
assert.deepStrictEqual(c(3), expected)
assert.deepStrictEqual(d(), expected)
})
})
describe('attempt', function() {
const attempt = _.attempt
it('should return a wrapped value when explicitly chaining', function() {
assert.ok(_(lodashStable.constant('x')).chain().attempt() instanceof _)
})
it('should return an unwrapped value when implicitly chaining', function() {
assert.strictEqual(_(lodashStable.constant('x')).attempt(), 'x')
})
it('should return the result of `func`', function() {
assert.strictEqual(attempt(lodashStable.constant('x')), 'x')
})
it('should provide additional arguments to `func`', function() {
var actual = attempt(function() { return slice.call(arguments) }, 1, 2)
assert.deepStrictEqual(actual, [1, 2])
})
it('should return the caught error', function() {
var expected = lodashStable.map(errors, stubTrue)
var actual = lodashStable.map(errors, function(error: any) {
return attempt(function() { throw error }) === error
})
assert.deepStrictEqual(actual, expected)
})
it('should coerce errors to error objects', function() {
var actual = attempt(function() { throw new Error('x') })
assert.ok(lodashStable.isEqual(actual, Error('x')))
})
it('should preserve custom errors', function() {
var actual = attempt(function() { throw new (CustomError as any)('x') })
assert.ok(actual instanceof CustomError)
})
it('should work with an error object from another realm', function() {
if (realm.errors) {
var expected = lodashStable.map(realm.errors, stubTrue)
var actual = lodashStable.map(realm.errors, function(error: any) {
return attempt(function() { throw error }) === error
})
assert.deepStrictEqual(actual, expected)
}
})
})
describe('before', function() {
function before(n: number, times: number) {
var count = 0
lodashStable.times(times, _.before(n, function() { count++ }))
return count
}
it('should create a function that invokes `func` after `n` calls', function() {
assert.strictEqual(before(5, 4), 4, 'before(n) should invoke `func` before being called `n` times')
assert.strictEqual(before(5, 6), 4, 'before(n) should not invoke `func` after being called `n - 1` times')
assert.strictEqual(before(0, 0), 0, 'before(0) should not invoke `func` immediately')
assert.strictEqual(before(0, 1), 0, 'before(0) should not invoke `func` when called')
})
it('should coerce `n` values of `NaN` to `0`', function() {
assert.strictEqual(before(NaN, 1), 0)
})
it('should use `this` binding of function', function() {
var before = _.before(2, function(this: any) { return ++this.count }),
object = { 'before': before, 'count': 0 }
object.before()
assert.strictEqual(object.before(), 1)
assert.strictEqual(object.count, 1)
})
})
describe('bind', function() {
let bind = _.bind
function fn(this: any) {
var result = [this]
push.apply(result, arguments as any)
return result
}
it('should bind a function to an object', function() {
var object = {},
bound = bind(fn, object)
assert.deepStrictEqual(bound('a'), [object, 'a'])
})
it('should accept a falsey `thisArg`', function() {
var values = lodashStable.reject(falsey.slice(1), function(value: null) { return value == null }),
expected = lodashStable.map(values, function(value: any) { return [value] })
var actual = lodashStable.map(values, function(value: any) {
try {
var bound = bind(fn, value)
return bound()
} catch (e) {}
})
assert.ok(lodashStable.every(actual, function(value: any, index: string | number) {
return lodashStable.isEqual(value, expected[index])
}))
})
it('should bind a function to nullish values', function() {
var bound = bind(fn, null),
actual = bound('a')
assert.ok((actual[0] === null) || (actual[0] && actual[0].Array))
assert.strictEqual(actual[1], 'a')
lodashStable.times(2, function(index: any) {
bound = index ? bind(fn, undefined) : bind(fn)
actual = bound('b')
assert.ok((actual[0] === undefined) || (actual[0] && actual[0].Array))
assert.strictEqual(actual[1], 'b')
})
})
it('should partially apply arguments ', function() {
var object = {},
bound = bind(fn, object, 'a')
assert.deepStrictEqual(bound(), [object, 'a'])
bound = bind(fn, object, 'a')
assert.deepStrictEqual(bound('b'), [object, 'a', 'b'])
bound = bind(fn, object, 'a', 'b')
assert.deepStrictEqual(bound(), [object, 'a', 'b'])
assert.deepStrictEqual(bound('c', 'd'), [object, 'a', 'b', 'c', 'd'])
})
it('should support placeholders', function() {
var object = {},
ph = bind.placeholder,
bound = bind(fn, object, ph, 'b', ph)
assert.deepStrictEqual(bound('a', 'c'), [object, 'a', 'b', 'c'])
assert.deepStrictEqual(bound('a'), [object, 'a', 'b', undefined])
assert.deepStrictEqual(bound('a', 'c', 'd'), [object, 'a', 'b', 'c', 'd'])
assert.deepStrictEqual(bound(), [object, undefined, 'b', undefined])
})
it('should create a function with a `length` of `0`', function() {
var fn = function(a: any, b: any, c: any) {},
bound = bind(fn, {})
assert.strictEqual(bound.length, 0)
bound = bind(fn, {}, 1)
assert.strictEqual(bound.length, 0)
})
it('should ignore binding when called with the `new` operator', function() {
function Foo(this: any) {
return this
}
var bound = bind(Foo, { 'a': 1 }),
newBound = new bound
assert.strictEqual(bound().a, 1)
assert.strictEqual(newBound.a, undefined)
assert.ok(newBound instanceof Foo)
})
it('should handle a number of arguments when called with the `new` operator', function() {
function Foo(this: any) {
return this
}
function Bar() {}
var thisArg = { 'a': 1 },
boundFoo = bind(Foo, thisArg),
boundBar = bind(Bar, thisArg),
count = 9,
expected = lodashStable.times(count, lodashStable.constant([undefined, undefined]))
var actual = lodashStable.times(count, function(index: any) {
try {
switch (index) {
case 0: return [new boundFoo().a, new boundBar().a]
case 1: return [new boundFoo(1).a, new boundBar(1).a]
case 2: return [new boundFoo(1, 2).a, new boundBar(1, 2).a]
case 3: return [new boundFoo(1, 2, 3).a, new boundBar(1, 2, 3).a]
case 4: return [new boundFoo(1, 2, 3, 4).a, new boundBar(1, 2, 3, 4).a]
case 5: return [new boundFoo(1, 2, 3, 4, 5).a, new boundBar(1, 2, 3, 4, 5).a]
case 6: return [new boundFoo(1, 2, 3, 4, 5, 6).a, new boundBar(1, 2, 3, 4, 5, 6).a]
case 7: return [new boundFoo(1, 2, 3, 4, 5, 6, 7).a, new boundBar(1, 2, 3, 4, 5, 6, 7).a]
case 8: return [new boundFoo(1, 2, 3, 4, 5, 6, 7, 8).a, new boundBar(1, 2, 3, 4, 5, 6, 7, 8).a]
}
} catch (e) {}
})
assert.deepStrictEqual(actual, expected)
})
it('should ensure `new bound` is an instance of `func`', function() {
function Foo(value: any) {
return value && object
}
var bound = bind(Foo),
object = {}
assert.ok(new bound instanceof Foo)
assert.strictEqual(new bound(true), object)
})
it('should append array arguments to partially applied arguments', function() {
var object = {},
bound = bind(fn, object, 'a')
assert.deepStrictEqual(bound(['b'], 'c'), [object, 'a', ['b'], 'c'])
})
it('should not rebind functions', function() {
var object1 = {},
object2 = {},
object3 = {}
var bound1 = bind(fn, object1),
bound2 = bind(bound1, object2, 'a'),
bound3 = bind(bound1, object3, 'b')
assert.deepStrictEqual(bound1(), [object1])
assert.deepStrictEqual(bound2(), [object1, 'a'])
assert.deepStrictEqual(bound3(), [object1, 'b'])
})
it('should not error when instantiating bound built-ins', function() {
var Ctor = bind(Date, null),
expected = new Date(2012, 4, 23, 0, 0, 0, 0)
try {
var actual = new Ctor(2012, 4, 23, 0, 0, 0, 0)
} catch (e) {}
assert.deepStrictEqual(actual, expected)
Ctor = bind(Date, null, 2012, 4, 23)
try {
actual = new Ctor(0, 0, 0, 0)
} catch (e) {}
assert.deepStrictEqual(actual, expected)
})
it('should not error when calling bound class constructors with the `new` operator', function() {
var createCtor = lodashStable.attempt(Function, '"use strict";return class A{}')
if (typeof createCtor === 'function') {
var bound = bind(createCtor()),
count = 8,
expected = lodashStable.times(count, stubTrue)
var actual = lodashStable.times(count, function(index: any) {
try {
switch (index) {
case 0: return !!(new bound)
case 1: return !!(new bound(1))
case 2: return !!(new bound(1, 2))
case 3: return !!(new bound(1, 2, 3))
case 4: return !!(new bound(1, 2, 3, 4))
case 5: return !!(new bound(1, 2, 3, 4, 5))
case 6: return !!(new bound(1, 2, 3, 4, 5, 6))
case 7: return !!(new bound(1, 2, 3, 4, 5, 6, 7))
}
} catch (e) {}
})
assert.deepStrictEqual(actual, expected)
}
})
it('should return a wrapped value when chaining', function() {
var object = {},
bound = _(fn).bind({}, 'a', 'b')
assert.ok(bound instanceof _)
var actual = bound.value()('c')
assert.deepEqual(actual, [object, 'a', 'b', 'c'])
})
})
describe('bindAll', function() {
let bindAll = _.bindAll
var args = toArgs(['a'] as any)
var source = {
'_n0': -2,
'_p0': -1,
'_a': 1,
'_b': 2,
'_c': 3,
'_d': 4,
'-0'() { return this._n0 },
'0'() { return this._p0 },
'a'() { return this._a },
'b'() { return this._b },
'c'() { return this._c },
'd'() { return this._d },
}
it('should accept individual method names', function() {
var object = lodashStable.cloneDeep(source)
bindAll(object, 'a', 'b')
var actual = lodashStable.map(['a', 'b', 'c'], function(key: string | number) {
return object[key].call({})
})
assert.deepStrictEqual(actual, [1, 2, undefined])
})
it('should accept arrays of method names', function() {
var object = lodashStable.cloneDeep(source)
bindAll(object, ['a', 'b'], ['c'])
var actual = lodashStable.map(['a', 'b', 'c', 'd'], function(key: string | number) {
return object[key].call({})
})
assert.deepStrictEqual(actual, [1, 2, 3, undefined])
})
it('should preserve the sign of `0`', function() {
var props = [-0, Object(-0), 0, Object(0)]
var actual = lodashStable.map(props, function(key: any) {
var object = lodashStable.cloneDeep(source)
bindAll(object, key)
return object[lodashStable.toString(key)].call({})
})
assert.deepStrictEqual(actual, [-2, -2, -1, -1])
})
it('should work with an array `object`', function() {
var array = ['push', 'pop']
bindAll(array)
assert.strictEqual(array.pop, arrayProto.pop)
})
it('should work with `arguments` objects as secondary arguments', function() {
var object = lodashStable.cloneDeep(source)
bindAll(object, args)
var actual = lodashStable.map(args, function(key: string | number) {
return object[key].call({})
})
assert.deepStrictEqual(actual, [1])
})
})
describe('bindKey', function() {
let bindKey= _.bindKey
it('should work when the target function is overwritten', function() {
var object = {
'user': 'fred',
'greet'(greeting: string) {
return this.user + ' says: ' + greeting
},
}
var bound = bindKey(object, 'greet', 'hi')
assert.strictEqual(bound(), 'fred says: hi')
object.greet = function(greeting) {
return this.user + ' says: ' + greeting + '!'
}
assert.strictEqual(bound(), 'fred says: hi!')
})
it('should support placeholders', function() {
var object = {
'fn'() {
return slice.call(arguments)
},
}
var ph = bindKey.placeholder,
bound = bindKey(object, 'fn', ph, 'b', ph)
assert.deepStrictEqual(bound('a', 'c'), ['a', 'b', 'c'])
assert.deepStrictEqual(bound('a'), ['a', 'b', undefined])
assert.deepStrictEqual(bound('a', 'c', 'd'), ['a', 'b', 'c', 'd'])
assert.deepStrictEqual(bound(), [undefined, 'b', undefined])
})
it('should use `_.placeholder` when set', function() {
var object = {
'fn'() {
return slice.call(arguments)
},
}
var _ph = _.placeholder = {},
ph = bindKey.placeholder,
bound = bindKey(object, 'fn', _ph, 'b', ph)
assert.deepEqual(bound('a', 'c'), ['a', 'b', ph, 'c'])
delete _.placeholder
})
it('should ensure `new bound` is an instance of `object[key]`', function() {
function Foo(value: any) {
return value && object
}
var object = { 'Foo': Foo },
bound = bindKey(object, 'Foo')
assert.ok(new bound instanceof Foo)
assert.strictEqual(new bound(true), object)
})
})
describe('camelCase', function() {
let camelCase = _.camelCase
it('should work with numbers', function() {
assert.strictEqual(camelCase('12 feet'), '12Feet')
assert.strictEqual(camelCase('enable 6h format'), 'enable6HFormat')
assert.strictEqual(camelCase('enable 24H format'), 'enable24HFormat')
assert.strictEqual(camelCase('too legit 2 quit'), 'tooLegit2Quit')
assert.strictEqual(camelCase('walk 500 miles'), 'walk500Miles')
assert.strictEqual(camelCase('xhr2 request'), 'xhr2Request')
})
it('should handle acronyms', function() {
lodashStable.each(['safe HTML', 'safeHTML'], function(string: any) {
assert.strictEqual(camelCase(string), 'safeHtml')
})
lodashStable.each(['escape HTML entities', 'escapeHTMLEntities'], function(string: any) {
assert.strictEqual(camelCase(string), 'escapeHtmlEntities')
})
lodashStable.each(['XMLHttpRequest', 'XmlHTTPRequest'], function(string: any) {
assert.strictEqual(camelCase(string), 'xmlHttpRequest')
})
})
})
describe('capitalize', function() {
let capitalize = _.capitalize
it('should capitalize the first character of a string', function() {
assert.strictEqual(capitalize('fred'), 'Fred')
assert.strictEqual(capitalize('Fred'), 'Fred')
assert.strictEqual(capitalize(' fred'), ' fred')
})
})
let camelCase = _.camelCase
let kebabCase = _.kebabCase
let lowerCase = _.lowerCase
let snakeCase = _.snakeCase
let startCase = _.startCase
let upperCase = _.upperCase
const caseMethods = {
camelCase,
kebabCase,
lowerCase,
snakeCase,
startCase,
upperCase,
}
describe('case methods', function() {
lodashStable.each(['camel', 'kebab', 'lower', 'snake', 'start', 'upper'], function(caseName: string) {
var methodName = caseName + 'Case',
func = caseMethods[methodName]
var strings = [
'foo bar', 'Foo bar', 'foo Bar', 'Foo Bar',
'FOO BAR', 'fooBar', '--foo-bar--', '__foo_bar__',
]
var converted = (function() {
switch (caseName) {
case 'camel': return 'fooBar'
case 'kebab': return 'foo-bar'
case 'lower': return 'foo bar'
case 'snake': return 'foo_bar'
case 'start': return 'Foo Bar'
case 'upper': return 'FOO BAR'
}
}())
it('`_.' + methodName + '` should convert `string` to ' + caseName + ' case', function() {
var actual = lodashStable.map(strings, function(string: string) {
var expected = (caseName == 'start' && string == 'FOO BAR') ? string : converted
return func(string) === expected
})
assert.deepStrictEqual(actual, lodashStable.map(strings, stubTrue))
})
it('`_.' + methodName + '` should handle double-converting strings', function() {
var actual = lodashStable.map(strings, function(string: string) {
var expected = (caseName == 'start' && string == 'FOO BAR') ? string : converted
return func(func(string)) === expected
})
assert.deepStrictEqual(actual, lodashStable.map(strings, stubTrue))
})
it('`_.' + methodName + '` should remove contraction apostrophes', function() {
var postfixes = ['d', 'll', 'm', 're', 's', 't', 've']
lodashStable.each(["'", '\u2019'], function(apos: string) {
var actual = lodashStable.map(postfixes, function(postfix: string) {
return func('a b' + apos + postfix + ' c')
})
var expected = lodashStable.map(postfixes, function(postfix: string) {
switch (caseName) {
case 'camel': return 'aB' + postfix + 'C'
case 'kebab': return 'a-b' + postfix + '-c'
case 'lower': return 'a b' + postfix + ' c'
case 'snake': return 'a_b' + postfix + '_c'
case 'start': return 'A B' + postfix + ' C'
case 'upper': return 'A B' + postfix.toUpperCase() + ' C'
}
})
assert.deepStrictEqual(actual, expected)
})
})
it('`_.' + methodName + '` should remove Latin mathematical operators', function() {
var actual = lodashStable.map(['\xd7', '\xf7'], func)
assert.deepStrictEqual(actual, ['', ''])
})
it('`_.' + methodName + '` should coerce `string` to a string', function() {
var string = 'foo bar'
assert.strictEqual(func(Object(string)), converted)
assert.strictEqual(func({ 'toString': lodashStable.constant(string) }), converted)
})
});
(function() {
it('should get the original value after cycling through all case methods', function() {
var funcs = [camelCase, kebabCase, lowerCase, snakeCase, startCase, lowerCase, camelCase]
var actual = lodashStable.reduce(funcs, function(result: any, func: (arg0: any) => any) {
return func(result)
}, 'enable 6h format')
assert.strictEqual(actual, 'enable6HFormat')
})
})()
})
describe('castArray', function() {
const castArray = _.castArray
it('should wrap non-array items in an array', function() {
var values = (falsey as any).concat(true, 1, 'a', { 'a': 1 }),
expected = lodashStable.map(values, function(value: any) { return [value] }),
actual = lodashStable.map(values, castArray)
assert.deepStrictEqual(actual, expected)
})
it('should return array values by reference', function() {
var array = [1]
assert.strictEqual(castArray(array), array)
})
it('should return an empty array when no arguments are given', function() {
assert.deepStrictEqual(castArray(), [])
})
})
describe('chain', function() {
const chain = _.chain
it('should return a wrapped value', function() {
var actual = chain({ 'a': 0 })
assert.ok(actual instanceof _)
})
it('should return existing wrapped values', function() {
var wrapped = _({ 'a': 0 })
assert.strictEqual(chain(wrapped), wrapped)
assert.strictEqual(wrapped.chain(), wrapped)
})
it('should enable chaining for methods that return unwrapped values', function() {
var array = ['c', 'b', 'a']
assert.ok(chain(array).head() instanceof _)
assert.ok(_(array).chain().head() instanceof _)
assert.ok(chain(array).isArray() instanceof _)
assert.ok(_(array).chain().isArray() instanceof _)
assert.ok(chain(array).sortBy().head() instanceof _)
assert.ok(_(array).chain().sortBy().head() instanceof _)
})
it('should chain multiple methods', function() {
lodashStable.times(2, function(index: any) {
var array = ['one two three four', 'five six seven eight', 'nine ten eleven twelve'],
expected = { ' ': 9, 'e': 14, 'f': 2, 'g': 1, 'h': 2, 'i': 4, 'l': 2, 'n': 6, 'o': 3, 'r': 2, 's': 2, 't': 5, 'u': 1, 'v': 4, 'w': 2, 'x': 1 },
wrapped = index ? _(array).chain() : chain(array)
var actual = wrapped
.chain()
.map(function(value: string) { return value.split('') })
.flatten()
.reduce(function(object: { [x: string]: number }, chr: string | number) {
object[chr] || (object[chr] = 0)
object[chr]++
return object
}, {})
.value()
assert.deepStrictEqual(actual, expected)
array = [1, 2, 3, 4, 5, 6] as any
wrapped = index ? _(array).chain() : chain(array)
actual = wrapped
.chain()
.filter(function(n: number) { return n % 2 != 0 })
.reject(function(n: number) { return n % 3 == 0 })
.sortBy(function(n: number) { return -n })
.value()
assert.deepStrictEqual(actual, [5, 1])
array = [3, 4] as any
wrapped = index ? _(array).chain() : chain(array)
actual = wrapped
.reverse()
.concat([2, 1])
.unshift(5)
.tap(function(value: void[]) { value.pop() })
.map(square)
.value()
assert.deepStrictEqual(actual, [25, 16, 9, 4])
})
})
})
describe('chunk', function() {
const chunk = _.chunk
var array = [0, 1, 2, 3, 4, 5]
it('should return chunked arrays', function() {
var actual = chunk(array, 3)
assert.deepStrictEqual(actual, [[0, 1, 2], [3, 4, 5]])
})
it('should return the last chunk as remaining elements', function() {
var actual = chunk(array, 4)
assert.deepStrictEqual(actual, [[0, 1, 2, 3], [4, 5]])
})
it('should treat falsey `size` values, except `undefined`, as `0`', function() {
var expected = lodashStable.map(falsey, function(value: undefined) {
return value === undefined ? [[0], [1], [2], [3], [4], [5]] : []
})
var actual = lodashStable.map(falsey, function(size: any, index: any) {
return index ? chunk(array, size) : chunk(array)
})
assert.deepStrictEqual(actual, expected)
})
it('should ensure the minimum `size` is `0`', function() {
var values = lodashStable.reject(falsey, lodashStable.isUndefined).concat(-1, -Infinity),
expected = lodashStable.map(values, stubArray)
var actual = lodashStable.map(values, function(n: any) {
return chunk(array, n)
})
assert.deepStrictEqual(actual, expected)
})
it('should coerce `size` to an integer', function() {
assert.deepStrictEqual(chunk(array, array.length / 4), [[0], [1], [2], [3], [4], [5]])
})
})
describe('clamp', function() {
const clamp = _.clamp
it('should work with a `max`', function() {
assert.strictEqual(clamp(5, 3), 3)
assert.strictEqual(clamp(1, 3), 1)
})
it('should clamp negative numbers', function() {
assert.strictEqual(clamp(-10, -5, 5), -5)
assert.strictEqual(clamp(-10.2, -5.5, 5.5), -5.5)
assert.strictEqual(clamp(-Infinity, -5, 5), -5)
})
it('should clamp positive numbers', function() {
assert.strictEqual(clamp(10, -5, 5), 5)
assert.strictEqual(clamp(10.6, -5.6, 5.4), 5.4)
assert.strictEqual(clamp(Infinity, -5, 5), 5)
})
it('should not alter negative numbers in range', function() {
assert.strictEqual(clamp(-4, -5, 5), -4)
assert.strictEqual(clamp(-5, -5, 5), -5)
assert.strictEqual(clamp(-5.5, -5.6, 5.6), -5.5)
})
it('should not alter positive numbers in range', function() {
assert.strictEqual(clamp(4, -5, 5), 4)
assert.strictEqual(clamp(5, -5, 5), 5)
assert.strictEqual(clamp(4.5, -5.1, 5.2), 4.5)
})
it('should not alter `0` in range', function() {
assert.strictEqual(1 / clamp(0, -5, 5), Infinity)
})
it('should clamp to `0`', function() {
assert.strictEqual(1 / clamp(-10, 0, 5), Infinity)
})
it('should not alter `-0` in range', function() {
assert.strictEqual(1 / clamp(-0, -5, 5), -Infinity)
})
it('should clamp to `-0`', function() {
assert.strictEqual(1 / clamp(-10, -0, 5), -Infinity)
})
it('should return `NaN` when `number` is `NaN`', function() {
assert.deepStrictEqual(clamp(NaN, -5, 5), NaN)
})
it('should coerce `min` and `max` of `NaN` to `0`', function() {
assert.deepStrictEqual(clamp(1, -5, NaN), 0)
assert.deepStrictEqual(clamp(-1, NaN, 5), 0)
})
})
describe('clone methods', function() {
const cloneDeep = _.cloneDeep
const cloneDeepWith = _.cloneDeepWith
const last = _.last
/** Used to test async functions. */
var asyncFunc = lodashStable.attempt(function() {
return Function('return async () => {}')
})
function Foo(this: any) {
this.a = 1
}
/** Used to test generator functions. */
var genFunc = lodashStable.attempt(function() {
return Function('return function*(){}')
})
Foo.prototype.b = 1
Foo.c = function() {}
var map: any
var set: any
if (Map) {
map = new Map
map.set('a', 1)
map.set('b', 2)
}
if (Set) {
set = new Set
set.add(1)
set.add(2)
}
var objects = {
'`arguments` objects': arguments,
'arrays': ['a', ''],
'array-like objects': { '0': 'a', 'length': 1 },
'booleans': false,
'boolean objects': Object(false),
'date objects': new Date,
'Foo instances': new (Foo as any),
'objects': { 'a': 0, 'b': 1, 'c': 2 },
'objects with object values': { 'a': /a/, 'b': ['B'], 'c': { 'C': 1 } },
'objects from another document': realm.object || {},
'maps': map,
'null values': null,
'numbers': 0,
'number objects': Object(0),
'regexes': /a/gim,
'sets': set,
'strings': 'a',
'string objects': Object('a'),
'undefined values': undefined,
}
objects.arrays.length = 3
var uncloneable = {
'DOM elements': body,
'functions': Foo,
'async functions': asyncFunc,
'generator functions': genFunc,
'the `Proxy` constructor': Proxy,
}
lodashStable.each(errors, function(error: { name: string }) {
uncloneable[error.name + 's'] = error
})
it('`_.clone` should perform a shallow clone', function() {
var array = [{ 'a': 0 }, { 'b': 1 }],
actual = _.clone(array)
assert.deepStrictEqual(actual, array)
assert.ok(actual !== array && actual[0] === array[0])
})
it('`_.cloneDeep` should deep clone objects with circular references', function() {
var object = {
'foo': { 'b': { 'c': { 'd': {} } } },
'bar': {},
}
object.foo.b.c.d = object;
(object.bar as any).b = object.foo.b
var actual = cloneDeep(object)
assert.ok(actual.bar.b === actual.foo.b && actual === actual.foo.b.c.d && actual !== object)
})
it('`_.cloneDeep` should deep clone objects with lots of circular references', function() {
var cyclical = {}
lodashStable.times(LARGE_ARRAY_SIZE + 1, function(index: any) {
cyclical['v' + index] = [index ? cyclical['v' + (index - 1)] : cyclical]
})
var clone = cloneDeep(cyclical),
actual = clone['v' + LARGE_ARRAY_SIZE][0]
assert.strictEqual(actual, clone['v' + (LARGE_ARRAY_SIZE - 1)])
assert.notStrictEqual(actual, cyclical['v' + (LARGE_ARRAY_SIZE - 1)])
})
lodashStable.each(['clone', 'cloneDeep'], function(methodName: string) {
var func = _[methodName],
isDeep = methodName == 'cloneDeep'
lodashStable.forOwn(objects, function(object: any, kind: string) {
it('`_.' + methodName + '` should clone ' + kind, function() {
var actual = func(object)
if (!lodashStable.isEqual(actual, object)) {
console.log('====================================>', actual, object)
}
assert.ok(lodashStable.isEqual(actual, object))
if (lodashStable.isObject(object)) {
assert.notStrictEqual(actual, object)
} else {
assert.strictEqual(actual, object)
}
})
})
it('`_.' + methodName + '` should clone array buffers', function() {
if (ArrayBuffer) {
var actual = func(arrayBuffer)
assert.strictEqual(actual.byteLength, arrayBuffer.byteLength)
assert.notStrictEqual(actual, arrayBuffer)
}
})
it('`_.' + methodName + '` should clone `index` and `input` array properties', function() {
var array = /c/.exec('abcde'),
actual = func(array)
assert.strictEqual(actual.index, 2)
assert.strictEqual(actual.input, 'abcde')
})
it('`_.' + methodName + '` should clone `lastIndex` regexp property', function() {
var regexp = /c/g
regexp.exec('abcde')
assert.strictEqual(func(regexp).lastIndex, 3)
})
it('`_.' + methodName + '` should clone expando properties', function() {
var values = lodashStable.map([false, true, 1, 'a'], function(value: any) {
var object = Object(value)
object.a = 1
return object
})
var expected = lodashStable.map(values, stubTrue)
var actual = lodashStable.map(values, function(value: any) {
return func(value).a === 1
})
assert.deepStrictEqual(actual, expected)
})
it('`_.' + methodName + '` should clone prototype objects', function() {
var actual = func(Foo.prototype)
assert.ok(!(actual instanceof Foo))
assert.deepStrictEqual(actual, { 'b': 1 })
})
it('`_.' + methodName + '` should set the `[[Prototype]]` of a clone', function() {
assert.ok(func(new (Foo as any)) instanceof Foo)
})
it('`_.' + methodName + '` should set the `[[Prototype]]` of a clone even when the `constructor` is incorrect', function() {
Foo.prototype.constructor = Object
assert.ok(func(new (Foo as any)) instanceof Foo)
Foo.prototype.constructor = Foo
})
it('`_.' + methodName + '` should ensure `value` constructor is a function before using its `[[Prototype]]`', function() {
Foo.prototype.constructor = null
assert.ok(!(func(new (Foo as any)) instanceof Foo))
Foo.prototype.constructor = Foo
})
it('`_.' + methodName + '` should clone properties that shadow those on `Object.prototype`', function() {
var object = {
'constructor': objectProto.constructor,
'hasOwnProperty': objectProto.hasOwnProperty,
'isPrototypeOf': objectProto.isPrototypeOf,
'propertyIsEnumerable': objectProto.propertyIsEnumerable,
'toLocaleString': objectProto.toLocaleString,
'toString': objectProto.toString,
'valueOf': objectProto.valueOf,
}
var actual = func(object)
assert.deepStrictEqual(actual, object)
assert.notStrictEqual(actual, object)
})
it('`_.' + methodName + '` should clone symbol properties', function() {
function Foo(this: any) {
this[symbol as any] = { 'c': 1 }
}
if (Symbol) {
var symbol2 = Symbol('b')
Foo.prototype[symbol2] = 2
var symbol3 = Symbol('c')
defineProperty(Foo.prototype, symbol3, {
'configurable': true,
'enumerable': false,
'writable': true,
'value': 3,
})
var object = { 'a': { 'b': new (Foo as any) } }
object[symbol] = { 'b': 1 }
var actual = func(object)
if (isDeep) {
assert.notStrictEqual(actual[symbol], object[symbol])
assert.notStrictEqual(actual.a, object.a)
} else {
assert.strictEqual(actual[symbol], object[symbol])
assert.strictEqual(actual.a, object.a)
}
assert.deepStrictEqual(actual[symbol], object[symbol])
assert.deepStrictEqual(getSymbols(actual.a.b), [symbol])
assert.deepStrictEqual(actual.a.b[symbol], object.a.b[symbol])
assert.deepStrictEqual(actual.a.b[symbol2], object.a.b[symbol2])
assert.deepStrictEqual(actual.a.b[symbol3], object.a.b[symbol3])
}
})
it('`_.' + methodName + '` should clone symbol objects', function() {
assert.strictEqual(func(symbol), symbol)
var object = Object(symbol),
actual = func(object)
assert.strictEqual(typeof actual, 'object')
assert.strictEqual(typeof actual.valueOf(), 'symbol')
assert.notStrictEqual(actual, object)
})
it('`_.' + methodName + '` should not clone symbol primitives', function() {
assert.strictEqual(func(symbol), symbol)
})
it('`_.' + methodName + '` should create an object from the same realm as `value`', function() {
var props: any[] = []
var objects = lodashStable.transform(_, function(result: any[], value: any, key: any) {
if (lodashStable.startsWith(key, '_') && lodashStable.isObject(value) &&
!lodashStable.isArguments(value) && !lodashStable.isElement(value) &&
!lodashStable.isFunction(value)) {
props.push(lodashStable.capitalize(lodashStable.camelCase(key)))
result.push(value)
}
}, [])
var expected = lodashStable.map(objects, stubTrue)
var actual = lodashStable.map(objects, function(object: { constructor: any }) {
var Ctor = object.constructor,
result = func(object)
return result !== object && ((result instanceof Ctor) || !(new Ctor instanceof Ctor))
})
assert.deepStrictEqual(actual, expected, props.join(', '))
})
it('`_.' + methodName + '` should perform a ' + (isDeep ? 'deep' : 'shallow') + ' clone when used as an iteratee for methods like `_.map`', function() {
var expected = [{ 'a': [0] }, { 'b': [1] }],
actual = lodashStable.map(expected, func)
assert.deepStrictEqual(actual, expected)
if (isDeep) {
assert.ok(actual[0] !== expected[0] && actual[0].a !== expected[0].a && actual[1].b !== expected[1].b)
} else {
assert.ok(actual[0] !== expected[0] && actual[0].a === expected[0].a && actual[1].b === expected[1].b)
}
})
it('`_.' + methodName + '` should return a unwrapped value when chaining', function() {
var object = objects.objects,
actual = _(object)[methodName]()
assert.deepEqual(actual, object)
assert.notStrictEqual(actual, object)
})
var arrayViews = typedArrays.concat('DataView')
lodashStable.each(arrayViews, function(type: string) {
it('`_.' + methodName + '` should clone ' + type + ' values', function() {
var Ctor = root[type]
lodashStable.times(2, function(index: any) {
if (Ctor) {
var buffer = new ArrayBuffer(24),
view = index ? new Ctor(buffer, 8, 1) : new Ctor(buffer),
actual = func(view)
assert.deepStrictEqual(actual, view)
assert.notStrictEqual(actual, view)
assert.strictEqual(actual.buffer === view.buffer, !isDeep)
assert.strictEqual(actual.byteOffset, view.byteOffset)
assert.strictEqual(actual.length, view.length)
}
})
})
})
lodashStable.forOwn(uncloneable, function(value: { (): void; c(): void }, key: string) {
it('`_.' + methodName + '` should not clone ' + key, function() {
if (value) {
var object = { 'a': value, 'b': { 'c': value } },
actual = func(object),
expected = value === Foo ? { 'c': Foo.c } : {}
assert.deepStrictEqual(actual, object)
assert.notStrictEqual(actual, object)
assert.deepStrictEqual(func(value), expected)
}
})
})
})
lodashStable.each(['cloneWith', 'cloneDeepWith'], function(methodName: string) {
var func = _[methodName],
isDeep = methodName == 'cloneDeepWith'
it('`_.' + methodName + '` should provide correct `customizer` arguments', function() {
var argsList: any[][] = [],
object = new (Foo as any)
func(object, function() {
var length = arguments.length,
args = slice.call(arguments, 0, length - (length > 1 ? 1 : 0))
argsList.push(args)
})
assert.deepStrictEqual(argsList, isDeep ? [[object], [1, 'a', object]] : [[object]])
})
it('`_.' + methodName + '` should handle cloning when `customizer` returns `undefined`', function() {
var actual = func({ 'a': { 'b': 'c' } }, noop)
assert.deepStrictEqual(actual, { 'a': { 'b': 'c' } })
})
lodashStable.forOwn(uncloneable, function(value: any, key: string) {
it('`_.' + methodName + '` should work with a `customizer` callback and ' + key, function() {
var customizer = function(value: any) {
return lodashStable.isPlainObject(value) ? undefined : value
}
var actual = func(value, customizer)
assert.strictEqual(actual, value)
var object = { 'a': value, 'b': { 'c': value } }
actual = func(object, customizer)
assert.deepStrictEqual(actual, object)
assert.notStrictEqual(actual, object)
})
})
})
})
describe('concat', function() {
const concat = _.concat
it('should shallow clone `array`', function() {
var array = [1, 2, 3],
actual = concat(array)
assert.deepStrictEqual(actual, array)
assert.notStrictEqual(actual, array)
})
it('should concat arrays and values', function() {
var array = [1],
actual = concat(array, 2, [3], [[4]])
assert.deepStrictEqual(actual, [1, 2, 3, [4]])
assert.deepStrictEqual(array, [1])
})
it('should cast non-array `array` values to arrays', function() {
var values = [, null, undefined, false, true, 1, NaN, 'a']
var expected = lodashStable.map(values, function(value: any, index: any) {
return index ? [value] : []
})
var actual = lodashStable.map(values, function(value: any, index: any) {
return index ? concat(value) : concat()
})
assert.deepStrictEqual(actual, expected)
expected = lodashStable.map(values, function(value: any) {
return [value, 2, [3]]
})
actual = lodashStable.map(values, function(value: any) {
return concat(value, [2], [[3]])
})
assert.deepStrictEqual(actual, expected)
})
it('should treat sparse arrays as dense', function() {
var expected = [],
actual = concat(Array(1), Array(1))
expected.push(undefined, undefined)
assert.ok('0'in actual)
assert.ok('1' in actual)
assert.deepStrictEqual(actual, expected)
})
it('should return a new wrapped array', function() {
var array = [1],
wrapped = _(array).concat([2, 3]),
actual = wrapped.value()
assert.deepEqual(array, [1])
assert.deepEqual(actual, [1, 2, 3])
})
})
describe('cond', function() {
it('should create a conditional function', function() {
var cond = _.cond([
[lodashStable.matches({ 'a': 1 }), stubA],
[lodashStable.matchesProperty('b', 1), stubB],
[lodashStable.property('c'), stubC],
])
assert.strictEqual(cond({ 'a': 1, 'b': 2, 'c': 3 }), 'a')
assert.strictEqual(cond({ 'a': 0, 'b': 1, 'c': 2 }), 'b')
assert.strictEqual(cond({ 'a': -1, 'b': 0, 'c': 1 }), 'c')
})
it('should provide arguments to functions', function() {
var args1: any,
args2: any,
expected = ['a', 'b', 'c']
var cond = _.cond([[
function() { args1 || (args1 = slice.call(arguments)); return true },
function() { args2 || (args2 = slice.call(arguments)) },
]])
cond('a', 'b', 'c')
assert.deepStrictEqual(args1, expected)
assert.deepStrictEqual(args2, expected)
})
it('should work with predicate shorthands', function() {
var cond = _.cond([
[{ 'a': 1 }, stubA],
[['b', 1], stubB],
['c', stubC],
])
assert.strictEqual(cond({ 'a': 1, 'b': 2, 'c': 3 }), 'a')
assert.strictEqual(cond({ 'a': 0, 'b': 1, 'c': 2 }), 'b')
assert.strictEqual(cond({ 'a': -1, 'b': 0, 'c': 1 }), 'c')
})
it('should return `undefined` when no condition is met', function() {
var cond = _.cond([[stubFalse, stubA]])
assert.strictEqual(cond({ 'a': 1 }), undefined)
})
it('should use `this` binding of function for `pairs`', function(this: any) {
var cond = _.cond([
[function(this: any, a: string | number) { return this[a] },
function(this: any, a: any, b: string | number) { return this[b] }],
])
var object = { 'cond': cond, 'a': 1, 'b': 2 }
assert.strictEqual(object.cond('a', 'b'), 2)
})
})
describe('conforms methods', function() {
const conformsTo = _.conformsTo
lodashStable.each(['conforms', 'conformsTo'], function(methodName: string) {
var isConforms = methodName == 'conforms'
function conforms(source: any) {
return isConforms ? _.conforms(source) : function(object: any) {
return conformsTo(object, source)
}
}
it('`_.' + methodName + '` should check if `object` conforms to `source`', function() {
var objects = [
{ 'a': 1, 'b': 8 },
{ 'a': 2, 'b': 4 },
{ 'a': 3, 'b': 16 },
]
var par = conforms({
'b'(value: number) { return value > 4 },
})
var actual = lodashStable.filter(objects, par)
assert.deepStrictEqual(actual, [objects[0], objects[2]])
par = conforms({
'b'(value: number) { return value > 8 },
'a'(value: number) { return value > 1 },
})
actual = lodashStable.filter(objects, par)
assert.deepStrictEqual(actual, [objects[2]])
})
it('`_.' + methodName + '` should not match by inherited `source` properties', function() {
function Foo(this: any) {
this.a = function(value: number) {
return value > 1
}
}
Foo.prototype.b = function(value: number) {
return value > 8
}
var objects = [
{ 'a': 1, 'b': 8 },
{ 'a': 2, 'b': 4 },
{ 'a': 3, 'b': 16 },
]
var par = conforms(new (Foo as any)),
actual = lodashStable.filter(objects, par)
assert.deepStrictEqual(actual, [objects[1], objects[2]])
})
it('`_.' + methodName + '` should not invoke `source` predicates for missing `object` properties', function() {
var count = 0
var par = conforms({
'a'() { count++; return true },
} as any)
assert.strictEqual(par({}), false)
assert.strictEqual(count, 0)
})
it('`_.' + methodName + '` should work with a function for `object`', function() {
function Foo() {}
Foo.a = 1
function Bar() {}
Bar.a = 2
var par = conforms({
'a'(value: number) { return value > 1 },
})
assert.strictEqual(par(Foo), false)
assert.strictEqual(par(Bar), true)
})
it('`_.' + methodName + '` should work with a function for `source`', function() {
function Foo() {}
Foo.a = function(value: number) { return value > 1 }
var objects = [{ 'a': 1 }, { 'a': 2 }],
actual = lodashStable.filter(objects, conforms(Foo))
assert.deepStrictEqual(actual, [objects[1]])
})
it('`_.' + methodName + '` should work with a non-plain `object`', function() {
function Foo(this: any) {
this.a = 1
}
Foo.prototype.b = 2
var par = conforms({
'b'(value: number) { return value > 1 },
})
assert.strictEqual(par(new (Foo as any)), true)
})
it('`_.' + methodName + '` should return `false` when `object` is nullish', function() {
var values = [, null, undefined],
expected = lodashStable.map(values, stubFalse)
var par = conforms({
'a'(value: number) { return value > 1 },
})
var actual = lodashStable.map(values, function(value: any, index: any) {
try {
return index ? par(value) : par()
} catch (e) {}
})
assert.deepStrictEqual(actual, expected)
})
it('`_.' + methodName + '` should return `true` when comparing an empty `source` to a nullish `object`', function() {
var values = [, null, undefined],
expected = lodashStable.map(values, stubTrue),
par = conforms({})
var actual = lodashStable.map(values, function(value: any, index: any) {
try {
return index ? par(value) : par()
} catch (e) {}
})
assert.deepStrictEqual(actual, expected)
})
it('`_.' + methodName + '` should return `true` when comparing an empty `source`', function() {
var object = { 'a': 1 },
expected = lodashStable.map(empties, stubTrue)
var actual = lodashStable.map(empties, function(value: any) {
var par = conforms(value)
return par(object)
})
assert.deepStrictEqual(actual, expected)
})
})
})
describe('constant', function() {
it('should create a function that returns `value`', function() {
var object = { 'a': 1 },
values = Array(2).concat(empties, true, 1, 'a'),
constant = _.constant(object)
var results = lodashStable.map(values, function(value: any, index: number) {
if (index < 2) {
return index ? constant.call({}) : constant()
}
return constant(value)
})
assert.ok(lodashStable.every(results, function(result: { a: number }) {
return result === object
}))
})
it('should work with falsey values', function() {
var expected = lodashStable.map(falsey, stubTrue)
var actual = lodashStable.map(falsey, function(value: any, index: any) {
var constant = index ? _.constant(value) : _.constant(),
result = constant()
return (result === value) || (result !== result && value !== value)
})
assert.deepStrictEqual(actual, expected)
})
it('should return a wrapped value when chaining', function() {
var wrapped = _(true).constant()
assert.ok(wrapped instanceof _)
})
})
describe('countBy', function() {
var array = [6.1, 4.2, 6.3]
const countBy = _.countBy
it('should transform keys by `iteratee`', function() {
var actual = countBy(array, Math.floor)
assert.deepStrictEqual(actual, { '4': 1, '6': 2 })
})
it('should use `_.identity` when `iteratee` is nullish', function() {
var array = [4, 6, 6],
values = [, null, undefined],
expected = lodashStable.map(values, lodashStable.constant({ '4': 1, '6': 2 }))
var actual = lodashStable.map(values, function(value: any, index: any) {
return index ? countBy(array, value) : countBy(array)
})
assert.deepStrictEqual(actual, expected)
})
it('should work with `_.property` shorthands', function() {
var actual = countBy(['one', 'two', 'three'], 'length')
assert.deepStrictEqual(actual, { '3': 2, '5': 1 })
})
it('should only add values to own, not inherited, properties', function() {
var actual = countBy(array, function(n: number) {
return Math.floor(n) > 4 ? 'hasOwnProperty' : 'constructor'
})
assert.deepStrictEqual(actual.constructor, 1)
assert.deepStrictEqual(actual.hasOwnProperty, 2)
})
it('should work with a number for `iteratee`', function() {
var array = [
[1, 'a'],
[2, 'a'],
[2, 'b'],
]
assert.deepStrictEqual(countBy(array, 0), { '1': 1, '2': 2 })
assert.deepStrictEqual(countBy(array, 1), { 'a': 2, 'b': 1 })
})
it('should work with an object for `collection`', function() {
var actual = countBy({ 'a': 6.1, 'b': 4.2, 'c': 6.3 }, Math.floor)
assert.deepStrictEqual(actual, { '4': 1, '6': 2 })
})
it('should work in a lazy sequence', function() {
var array = lodashStable.range(LARGE_ARRAY_SIZE).concat(
lodashStable.range(Math.floor(LARGE_ARRAY_SIZE / 2), LARGE_ARRAY_SIZE),
lodashStable.range(Math.floor(LARGE_ARRAY_SIZE / 1.5), LARGE_ARRAY_SIZE),
)
var actual = _(array).countBy().map(square).filter(isEven).take().value()
assert.deepEqual(actual, _.take(_.filter(_.map(countBy(array), square), isEven)))
})
})
describe('create', function() {
const keys = _.keys
const create = _.create
function Shape(this: any) {
this.x = 0
this.y = 0
}
function Circle(this: any) {
Shape.call(this)
}
it('should create an object that inherits from the given `prototype` object', function() {
Circle.prototype = create(Shape.prototype)
Circle.prototype.constructor = Circle
var actual = new (Circle as any)
assert.ok(actual instanceof Circle)
assert.ok(actual instanceof Shape)
assert.notStrictEqual(Circle.prototype, Shape.prototype)
})
it('should assign `properties` to the created object', function() {
var expected = { 'constructor': Circle, 'radius': 0 }
var properties = Object.keys(expected)
Circle.prototype = create(Shape.prototype, expected)
var actual = new (Circle as any)
assert.ok(actual instanceof Circle)
assert.ok(actual instanceof Shape)
assert.deepStrictEqual(Object.keys(Circle.prototype), properties)
properties.forEach((property) => {
assert.strictEqual(Circle.prototype[property], expected[property])
})
})
it('should assign own properties', function() {
function Foo(this: any) {
this.a = 1
this.c = 3
}
Foo.prototype.b = 2
var actual = create({}, new (Foo as any))
var expected = { 'a': 1, 'c': 3 }
var properties = Object.keys(expected)
assert.deepStrictEqual(Object.keys(actual), properties)
properties.forEach((property) => {
assert.strictEqual(actual[property], expected[property])
})
})
it('should assign properties that shadow those of `prototype`', function() {
function Foo(this: any) {
this.a = 1
}
var object = create(new (Foo as any), { 'a': 1 })
assert.deepStrictEqual(lodashStable.keys(object), ['a'])
})
it('should accept a falsey `prototype`', function() {
var actual = lodashStable.map(falsey, function(prototype: object | null, index: any) {
return index ? create(prototype) : (create as any)()
})
actual.forEach((value: any) => {
assert.ok(lodashStable.isObject(value))
})
})
it('should accept a primitive `prototype`', function() {
var actual = lodashStable.map(primitives, function(value: object | null, index: any) {
return index ? create(value) : (create as any)()
})
actual.forEach((value: any) => {
assert.ok(lodashStable.isObject(value))
})
})
it('should work as an iteratee for methods like `_.map`', function() {
var array = [{ 'a': 1 }, { 'a': 1 }, { 'a': 1 }],
expected = lodashStable.map(array, stubTrue),
objects = lodashStable.map(array, create)
var actual = lodashStable.map(objects, function(object: { a: number }) {
return object.a === 1 && !keys(object).length
})
assert.deepStrictEqual(actual, expected)
})
})
describe('curry methods', function() {
const curry = _.curry
lodashStable.each(['curry', 'curryRight'], function(methodName: string) {
var func = _[methodName],
fn = function(a: any, b: any) { return slice.call(arguments) },
isCurry = methodName == 'curry'
it('`_.' + methodName + '` should not error on functions with the same name as lodash methods', function() {
function run(a: any, b: any) {
return a + b
}
var curried = func(run)
try {
var actual = curried(1)(2)
} catch (e) {}
assert.strictEqual(actual, 3)
})
it('`_.' + methodName + '` should work for function names that shadow those on `Object.prototype`', function() {
var curried = curry(function hasOwnProperty(a: any, b: any, c: any) {
return [a, b, c]
})
var expected = [1, 2, 3]
assert.deepStrictEqual(curried(1)(2)(3), expected)
})
it('`_.' + methodName + '` should work as an iteratee for methods like `_.map`', function() {
var array = [fn, fn, fn],
object = { 'a': fn, 'b': fn, 'c': fn }
lodashStable.each([array, object], function(collection: any) {
var curries = lodashStable.map(collection, func),
expected = lodashStable.map(collection, lodashStable.constant(isCurry ? ['a', 'b'] : ['b', 'a']))
var actual = lodashStable.map(curries, function(curried: (arg0: string) => { (arg0: string): any; new(): any }) {
return curried('a')('b')
})
assert.deepStrictEqual(actual, expected)
})
})
})
})
describe('curryRight', function() {
const curryRight = _.curryRight
const bind = _.bind
const partialRight = _.partialRight
const partial = _.partial
function fn(a: any, b: any, c: any, d: any) {
return slice.call(arguments)
}
it('should curry based on the number of arguments given', function() {
var curried = curryRight(fn),
expected = [1, 2, 3, 4]
assert.deepStrictEqual(curried(4)(3)(2)(1), expected)
assert.deepStrictEqual(curried(3, 4)(1, 2), expected)
assert.deepStrictEqual(curried(1, 2, 3, 4), expected)
})
it('should allow specifying `arity`', function() {
var curried = curryRight(fn, 3),
expected = [1, 2, 3]
assert.deepStrictEqual(curried(3)(1, 2), expected)
assert.deepStrictEqual(curried(2, 3)(1), expected)
assert.deepStrictEqual(curried(1, 2, 3), expected)
})
it('should coerce `arity` to an integer', function() {
var values = ['0', 0.6, 'xyz'],
expected = lodashStable.map(values, stubArray)
var actual = lodashStable.map(values, function(arity: any) {
return curryRight(fn, arity)()
})
assert.deepStrictEqual(actual, expected)
assert.deepStrictEqual(curryRight(fn, '2')(1)(2), [2, 1])
})
it('should support placeholders', function() {
var curried = curryRight(fn),
expected = [1, 2, 3, 4],
ph = curried.placeholder
assert.deepStrictEqual(curried(4)(2, ph)(1, ph)(3), expected)
assert.deepStrictEqual(curried(3, ph)(4)(1, ph)(2), expected)
assert.deepStrictEqual(curried(ph, ph, 4)(ph, 3)(ph, 2)(1), expected)
assert.deepStrictEqual(curried(ph, ph, ph, 4)(ph, ph, 3)(ph, 2)(1), expected)
})
it('should persist placeholders', function() {
var curried = curryRight(fn),
ph = curried.placeholder,
actual = curried('a', ph, ph, ph)('b')(ph)('c')('d')
assert.deepStrictEqual(actual, ['a', 'b', 'c', 'd'])
})
it('should provide additional arguments after reaching the target arity', function() {
var curried = curryRight(fn, 3)
assert.deepStrictEqual(curried(4)(1, 2, 3), [1, 2, 3, 4])
assert.deepStrictEqual(curried(4, 5)(1, 2, 3), [1, 2, 3, 4, 5])
assert.deepStrictEqual(curried(1, 2, 3, 4, 5, 6), [1, 2, 3, 4, 5, 6])
})
it('should create a function with a `length` of `0`', function() {
lodashStable.times(2, function(index: any) {
var curried = index ? curryRight(fn, 4) : curryRight(fn)
assert.strictEqual(curried.length, 0)
assert.strictEqual(curried(4).length, 0)
assert.strictEqual(curried(3, 4).length, 0)
})
})
it('should ensure `new curried` is an instance of `func`', function() {
function Foo(value: any) {
return value && object
}
var curried = curryRight(Foo),
object = {}
assert.ok(new curried(false) instanceof Foo)
assert.strictEqual(new curried(true), object)
})
it('should use `this` binding of function', function() {
var fn = function(this: any, a: string | number, b: string | number, c: string | number) {
var value = this || {}
return [value[a], value[b], value[c]]
}
var object: any = { 'a': 1, 'b': 2, 'c': 3 },
expected = [1, 2, 3]
assert.deepStrictEqual(curryRight(bind(fn, object), 3)('c')('b')('a'), expected)
assert.deepStrictEqual(curryRight(bind(fn, object), 3)('b', 'c')('a'), expected)
assert.deepStrictEqual(curryRight(bind(fn, object), 3)('a', 'b', 'c'), expected)
assert.deepStrictEqual(bind(curryRight(fn), object)('c')('b')('a'), Array(3))
assert.deepStrictEqual(bind(curryRight(fn), object)('b', 'c')('a'), Array(3))
assert.deepStrictEqual(bind(curryRight(fn), object)('a', 'b', 'c'), expected)
object.curried = curryRight(fn)
assert.deepStrictEqual(object.curried('c')('b')('a'), Array(3))
assert.deepStrictEqual(object.curried('b', 'c')('a'), Array(3))
assert.deepStrictEqual(object.curried('a', 'b', 'c'), expected)
})
it('should work with partialed methods', function() {
var curried = curryRight(fn),
expected = [1, 2, 3, 4]
var a = partialRight(curried, 4),
b = partialRight(a, 3),
c = bind(b, null, 1),
d = partial(b(2), 1)
assert.deepStrictEqual(c(2), expected)
assert.deepStrictEqual(d(), expected)
})
})
describe('debounce and throttle', function() {
lodashStable.each(['debounce', 'throttle'], function(methodName: string) {
var func = _[methodName],
isDebounce = methodName == 'debounce'
it('`_.' + methodName + '` should not error for non-object `options` values', function() {
func(noop, 32, 1)
assert.ok(true)
})
it('`_.' + methodName + '` should use a default `wait` of `0`', function(done) {
var callCount = 0,
funced = func(function() { callCount++ })
funced()
setTimeout(function() {
funced()
assert.strictEqual(callCount, isDebounce ? 1 : 2)
done()
}, 32)
})
it('`_.' + methodName + '` should invoke `func` with the correct `this` binding', function(done) {
var actual: any[] = [],
object = { 'funced': func(function(this: any) { actual.push(this) }, 32) },
expected = lodashStable.times(isDebounce ? 1 : 2, lodashStable.constant(object))
object.funced()
if (!isDebounce) {
object.funced()
}
setTimeout(function() {
assert.deepStrictEqual(actual, expected)
done()
}, 64)
})
it('`_.' + methodName + '` supports recursive calls', function(done) {
var actual: any[][] = [],
args = lodashStable.map(['a', 'b', 'c'], function(chr: any) { return [{}, chr] }),
expected = args.slice(),
queue = args.slice()
var funced = func(function(this: any) {
var current = [this]
push.apply(current, arguments as any)
actual.push(current)
var next = queue.shift()
if (next) {
funced.call(next[0], next[1])
}
}, 32)
var next = queue.shift()
funced.call(next[0], next[1])
assert.deepStrictEqual(actual, expected.slice(0, isDebounce ? 0 : 1))
setTimeout(function() {
assert.deepStrictEqual(actual, expected.slice(0, actual.length))
done()
}, 256)
})
it('`_.' + methodName + '` should support cancelling delayed calls', function(done) {
var callCount = 0
var funced = func(function() {
callCount++
}, 32, { 'leading': false })
funced()
funced.cancel()
setTimeout(function() {
assert.strictEqual(callCount, 0)
done()
}, 64)
})
it('`_.' + methodName + '` should reset `lastCalled` after cancelling', function(done) {
var callCount = 0
var funced = func(function() {
return ++callCount
}, 32, { 'leading': true })
assert.strictEqual(funced(), 1)
funced.cancel()
assert.strictEqual(funced(), 2)
funced()
setTimeout(function() {
assert.strictEqual(callCount, 3)
done()
}, 64)
})
it('`_.' + methodName + '` should support flushing delayed calls', function(done) {
var callCount = 0
var funced = func(function() {
return ++callCount
}, 32, { 'leading': false })
funced()
assert.strictEqual(funced.flush(), 1)
setTimeout(function() {
assert.strictEqual(callCount, 1)
done()
}, 64)
})
it('`_.' + methodName + '` should noop `cancel` and `flush` when nothing is queued', function(done) {
var callCount = 0,
funced = func(function() { callCount++ }, 32)
funced.cancel()
assert.strictEqual(funced.flush(), undefined)
setTimeout(function() {
assert.strictEqual(callCount, 0)
done()
}, 64)
})
})
})
describe('debounce', function() {
const debounce = _.debounce
it('should debounce a function', function(done) {
var callCount = 0
var debounced = debounce(function(value: any) {
++callCount
return value
}, 32)
var results = [debounced('a'), debounced('b'), debounced('c')]
assert.deepStrictEqual(results, [undefined, undefined, undefined])
assert.strictEqual(callCount, 0)
setTimeout(function() {
assert.strictEqual(callCount, 1)
var results = [debounced('d'), debounced('e'), debounced('f')]
assert.deepStrictEqual(results, ['c', 'c', 'c'])
assert.strictEqual(callCount, 1)
}, 128)
setTimeout(function() {
assert.strictEqual(callCount, 2)
done()
}, 256)
})
it('subsequent debounced calls return the last `func` result', function(done) {
var debounced = debounce(identity, 32)
debounced('a')
setTimeout(function() {
assert.notStrictEqual(debounced('b'), 'b')
}, 64)
setTimeout(function() {
assert.notStrictEqual(debounced('c'), 'c')
done()
}, 128)
})
it('should not immediately call `func` when `wait` is `0`', function(done) {
var callCount = 0,
debounced = debounce(function() { ++callCount }, 0)
debounced()
debounced()
assert.strictEqual(callCount, 0)
setTimeout(function() {
assert.strictEqual(callCount, 1)
done()
}, 5)
})
it('should apply default options', function(done) {
var callCount = 0,
debounced = debounce(function() { callCount++ }, 32, {})
debounced()
assert.strictEqual(callCount, 0)
setTimeout(function() {
assert.strictEqual(callCount, 1)
done()
}, 64)
})
it('should support a `leading` option', function(done) {
var callCounts = [0, 0]
var withLeading = debounce(function() {
callCounts[0]++
}, 32, { 'leading': true })
var withLeadingAndTrailing = debounce(function() {
callCounts[1]++
}, 32, { 'leading': true })
withLeading()
assert.strictEqual(callCounts[0], 1)
withLeadingAndTrailing()
withLeadingAndTrailing()
assert.strictEqual(callCounts[1], 1)
setTimeout(function() {
assert.deepStrictEqual(callCounts, [1, 2])
withLeading()
assert.strictEqual(callCounts[0], 2)
done()
}, 64)
})
it('subsequent leading debounced calls return the last `func` result', function(done) {
var debounced = debounce(identity, 32, { 'leading': true, 'trailing': false }),
results = [debounced('a'), debounced('b')]
assert.deepStrictEqual(results, ['a', 'a'])
setTimeout(function() {
var results = [debounced('c'), debounced('d')]
assert.deepStrictEqual(results, ['c', 'c'])
done()
}, 64)
})
it('should support a `trailing` option', function(done) {
var withCount = 0,
withoutCount = 0
var withTrailing = debounce(function() {
withCount++
}, 32, { 'trailing': true })
var withoutTrailing = debounce(function() {
withoutCount++
}, 32, { 'trailing': false })
withTrailing()
assert.strictEqual(withCount, 0)
withoutTrailing()
assert.strictEqual(withoutCount, 0)
setTimeout(function() {
assert.strictEqual(withCount, 1)
assert.strictEqual(withoutCount, 0)
done()
}, 64)
})
it('should support a `maxWait` option', function(done) {
var callCount = 0
var debounced = debounce(function(value: any) {
++callCount
return value
}, 32, { 'maxWait': 64 })
debounced()
debounced()
assert.strictEqual(callCount, 0)
setTimeout(function() {
assert.strictEqual(callCount, 1)
debounced()
debounced()
assert.strictEqual(callCount, 1)
}, 128)
setTimeout(function() {
assert.strictEqual(callCount, 2)
done()
}, 256)
})
it('should support `maxWait` in a tight loop', function(done) {
var limit = 1000,
withCount = 0,
withoutCount = 0
var withMaxWait = debounce(function() {
withCount++
}, 64, { 'maxWait': 128 })
var withoutMaxWait = debounce(function() {
withoutCount++
}, 96)
var start = +new Date
while ((new (Date as any) - start) < limit) {
withMaxWait()
withoutMaxWait()
}
var actual = [Boolean(withoutCount), Boolean(withCount)]
setTimeout(function() {
assert.deepStrictEqual(actual, [false, true])
done()
}, 1)
})
it('should queue a trailing call for subsequent debounced calls after `maxWait`', function(done) {
var callCount = 0
var debounced = debounce(function() {
++callCount
}, 200, { 'maxWait': 200 })
debounced()
setTimeout(debounced, 190)
setTimeout(debounced, 200)
setTimeout(debounced, 210)
setTimeout(function() {
assert.strictEqual(callCount, 2)
done()
}, 500)
})
it('should cancel `maxDelayed` when `delayed` is invoked', function(done) {
var callCount = 0
var debounced = debounce(function() {
callCount++
}, 32, { 'maxWait': 64 })
debounced()
setTimeout(function() {
debounced()
assert.strictEqual(callCount, 1)
}, 128)
setTimeout(function() {
assert.strictEqual(callCount, 2)
done()
}, 192)
})
it('should invoke the trailing call with the correct arguments and `this` binding', function(done) {
var actual: any[],
callCount = 0,
object = {}
var debounced = debounce(function(this: any, value: any) {
actual = [this]
push.apply(actual, arguments as any)
return ++callCount != 2
}, 32, { 'leading': true, 'maxWait': 64 })
while (true) {
if (!debounced.call(object, 'a')) {
break
}
}
setTimeout(function() {
assert.strictEqual(callCount, 2)
assert.deepStrictEqual(actual, [object, 'a'])
done()
}, 64)
})
})
describe('deburr', function() {
const deburr = _.deburr
it('should convert Latin Unicode letters to basic Latin', function() {
var actual = lodashStable.map(burredLetters, deburr)
assert.deepStrictEqual(actual, deburredLetters)
})
it('should not deburr Latin mathematical operators', function() {
var operators = ['\xd7', '\xf7'],
actual = lodashStable.map(operators, deburr)
assert.deepStrictEqual(actual, operators)
})
it('should deburr combining diacritical marks', function() {
var expected = lodashStable.map(comboMarks, lodashStable.constant('ei'))
var actual = lodashStable.map(comboMarks, function(chr: string) {
return deburr('e' + chr + 'i')
})
assert.deepStrictEqual(actual, expected)
})
})
describe('defaults', function() {
const defaults = _.defaults
it('should assign source properties if missing on `object`', function() {
var actual = defaults({ 'a': 1 }, { 'a': 2, 'b': 2 })
assert.deepStrictEqual(actual, { 'a': 1, 'b': 2 })
})
it('should accept multiple sources', function() {
var expected = { 'a': 1, 'b': 2, 'c': 3 },
actual = defaults({ 'a': 1, 'b': 2 }, { 'b': 3 }, { 'c': 3 })
assert.deepStrictEqual(actual, expected)
actual = defaults({ 'a': 1, 'b': 2 }, { 'b': 3, 'c': 3 }, { 'c': 2 })
assert.deepStrictEqual(actual, expected)
})
it('should not overwrite `null` values', function() {
var actual = defaults({ 'a': null }, { 'a': 1 })
assert.strictEqual(actual.a, null)
})
it('should overwrite `undefined` values', function() {
var actual = defaults({ 'a': undefined }, { 'a': 1 })
assert.strictEqual(actual.a, 1)
})
it('should assign `undefined` values', function() {
var source = { 'a': undefined, 'b': 1 },
actual = defaults({}, source)
assert.deepStrictEqual(actual, { 'a': undefined, 'b': 1 })
})
it('should assign properties that shadow those on `Object.prototype`', function() {
var object = {
'constructor': objectProto.constructor,
'hasOwnProperty': objectProto.hasOwnProperty,
'isPrototypeOf': objectProto.isPrototypeOf,
'propertyIsEnumerable': objectProto.propertyIsEnumerable,
'toLocaleString': objectProto.toLocaleString,
'toString': objectProto.toString,
'valueOf': objectProto.valueOf,
}
var source = {
'constructor': 1,
'hasOwnProperty': 2,
'isPrototypeOf': 3,
'propertyIsEnumerable': 4,
'toLocaleString': 5,
'toString': 6,
'valueOf': 7,
}
var expected = lodashStable.clone(source)
assert.deepStrictEqual(defaults({}, source), expected)
expected = lodashStable.clone(object)
assert.deepStrictEqual(defaults({}, object, source), expected)
})
})
describe('defaultsDeep', function() {
const defaultsDeep = _.defaultsDeep
it('should deep assign source properties if missing on `object`', function() {
var object = { 'a': { 'b': 2 }, 'd': 4 },
source = { 'a': { 'b': 3, 'c': 3 }, 'e': 5 },
expected = { 'a': { 'b': 2, 'c': 3 }, 'd': 4, 'e': 5 }
assert.deepStrictEqual(defaultsDeep(object, source), expected)
})
it('should accept multiple sources', function() {
var source1 = { 'a': { 'b': 3 } },
source2 = { 'a': { 'c': 3 } },
source3 = { 'a': { 'b': 3, 'c': 3 } },
source4 = { 'a': { 'c': 4 } },
expected = { 'a': { 'b': 2, 'c': 3 } }
assert.deepStrictEqual(defaultsDeep({ 'a': { 'b': 2 } }, source1, source2), expected)
assert.deepStrictEqual(defaultsDeep({ 'a': { 'b': 2 } }, source3, source4), expected)
})
it('should not overwrite `null` values', function() {
var object = { 'a': { 'b': null } },
source = { 'a': { 'b': 2 } },
actual = defaultsDeep(object, source)
assert.strictEqual(actual.a.b, null)
})
it('should not overwrite regexp values', function() {
var object = { 'a': { 'b': /x/ } },
source = { 'a': { 'b': /y/ } },
actual = defaultsDeep(object, source)
assert.deepStrictEqual(actual.a.b, /x/)
})
it('should not convert function properties to objects', function() {
var actual = defaultsDeep({}, { 'a': noop })
assert.strictEqual(actual.a, noop)
actual = defaultsDeep({}, { 'a': { 'b': noop } })
assert.strictEqual(actual.a.b, noop)
})
it('should overwrite `undefined` values', function() {
var object = { 'a': { 'b': undefined } },
source = { 'a': { 'b': 2 } },
actual = defaultsDeep(object, source)
assert.strictEqual(actual.a.b, 2)
})
it('should assign `undefined` values', function() {
var source = { 'a': undefined, 'b': { 'c': undefined, 'd': 1 } },
expected = lodashStable.cloneDeep(source),
actual = defaultsDeep({}, source)
assert.deepStrictEqual(actual, expected)
})
it('should merge sources containing circular references', function() {
var object = {
'foo': { 'b': { 'c': { 'd': {} } } },
'bar': { 'a': 2 },
}
var source: any = {
'foo': { 'b': { 'c': { 'd': {} } } },
'bar': {},
}
object.foo.b.c.d = object
source.foo.b.c.d = source
source.bar.b = source.foo.b
var actual = defaultsDeep(object, source)
assert.strictEqual(actual.bar.b, actual.foo.b)
assert.strictEqual(actual.foo.b.c.d, actual.foo.b.c.d.foo.b.c.d)
})
it('should not modify sources', function() {
var source1 = { 'a': 1, 'b': { 'c': 2 } },
source2 = { 'b': { 'c': 3, 'd': 3 } },
actual = defaultsDeep({}, source1, source2)
assert.deepStrictEqual(actual, { 'a': 1, 'b': { 'c': 2, 'd': 3 } })
assert.deepStrictEqual(source1, { 'a': 1, 'b': { 'c': 2 } })
assert.deepStrictEqual(source2, { 'b': { 'c': 3, 'd': 3 } })
})
it('should not attempt a merge of a string into an array', function() {
var actual = defaultsDeep({ 'a': ['abc'] }, { 'a': 'abc' })
assert.deepStrictEqual(actual.a, ['abc'])
})
})
describe('defaultTo', function() {
const defaultTo = _.defaultTo
it('should return a default value if `value` is `NaN` or nullish', function() {
var expected = lodashStable.map(falsey, function(value: null) {
return (value == null || value !== value) ? 1 : value
})
var actual = lodashStable.map(falsey, function(value: any) {
return defaultTo(value, 1)
})
assert.deepStrictEqual(actual, expected)
})
})
describe('defer', function() {
const defer = _.defer
it('should defer `func` execution', function(done) {
var pass = false
defer(function() { pass = true })
setTimeout(function() {
assert.ok(pass)
done()
}, 32)
})
it('should provide additional arguments to `func`', function(done) {
var args: any
defer(function() {
args = slice.call(arguments)
}, 1, 2)
setTimeout(function() {
assert.deepStrictEqual(args, [1, 2])
done()
}, 32)
})
it('should be cancelable', function(done) {
var pass = true,
timerId = defer(function() { pass = false })
clearTimeout(timerId)
setTimeout(function() {
assert.ok(pass)
done()
}, 32)
})
})
describe('delay', function() {
const delay = _.delay
it('should delay `func` execution', function(done) {
var pass = false
delay(function() { pass = true }, 32)
setTimeout(function() {
assert.ok(!pass)
}, 1)
setTimeout(function() {
assert.ok(pass)
done()
}, 64)
})
it('should provide additional arguments to `func`', function(done) {
var args: any
delay(function() {
args = slice.call(arguments)
}, 32, 1, 2)
setTimeout(function() {
assert.deepStrictEqual(args, [1, 2])
done()
}, 64)
})
it('should use a default `wait` of `0`', function(done) {
var pass = false
delay(function() { pass = true })
assert.ok(!pass)
setTimeout(function() {
assert.ok(pass)
done()
}, 0)
})
it('should be cancelable', function(done) {
var pass = true,
timerId = delay(function() { pass = false }, 32)
clearTimeout(timerId)
setTimeout(function() {
assert.ok(pass)
done()
}, 64)
})
it('should work with mocked `setTimeout`', function() {
var pass = false,
setTimeout = root.setTimeout
setProperty(root, 'setTimeout', function(func: any) { func() })
delay(function() { pass = true }, 32)
setProperty(root, 'setTimeout', setTimeout)
assert.ok(pass)
})
})
describe('difference methods', function() {
lodashStable.each(['difference', 'differenceBy', 'differenceWith'], function(methodName: string) {
var func = _[methodName]
it('`_.' + methodName + '` should return the difference of two arrays', function() {
var actual = func([2, 1], [2, 3])
assert.deepStrictEqual(actual, [1])
})
it('`_.' + methodName + '` should return the difference of multiple arrays', function() {
var actual = func([2, 1, 2, 3], [3, 4], [3, 2])
assert.deepStrictEqual(actual, [1])
})
it('`_.' + methodName + '` should treat `-0` as `0`', function() {
var array = [-0, 0]
var actual = lodashStable.map(array, function(value: any) {
return func(array, [value])
})
assert.deepStrictEqual(actual, [[], []])
actual = lodashStable.map(func([-0, 1], [1]), lodashStable.toString)
assert.deepStrictEqual(actual, ['0'])
})
it('`_.' + methodName + '` should match `NaN`', function() {
assert.deepStrictEqual(func([1, NaN, 3], [NaN, 5, NaN]), [1, 3])
})
it('`_.' + methodName + '` should work with large arrays', function() {
var array1 = lodashStable.range(LARGE_ARRAY_SIZE + 1),
array2 = lodashStable.range(LARGE_ARRAY_SIZE),
a = {},
b = {},
c = {}
array1.push(a, b, c)
array2.push(b, c, a)
assert.deepStrictEqual(func(array1, array2), [LARGE_ARRAY_SIZE])
})
it('`_.' + methodName + '` should work with large arrays of `-0` as `0`', function() {
var array = [-0, 0]
var actual = lodashStable.map(array, function(value: any) {
var largeArray = lodashStable.times(LARGE_ARRAY_SIZE, lodashStable.constant(value))
return func(array, largeArray)
})
assert.deepStrictEqual(actual, [[], []])
var largeArray = lodashStable.times(LARGE_ARRAY_SIZE, stubOne)
actual = lodashStable.map(func([-0, 1], largeArray), lodashStable.toString)
assert.deepStrictEqual(actual, ['0'])
})
it('`_.' + methodName + '` should work with large arrays of `NaN`', function() {
var largeArray = lodashStable.times(LARGE_ARRAY_SIZE, stubNaN)
assert.deepStrictEqual(func([1, NaN, 3], largeArray), [1, 3])
})
it('`_.' + methodName + '` should work with large arrays of objects', function() {
var object1 = {},
object2 = {},
largeArray = lodashStable.times(LARGE_ARRAY_SIZE, lodashStable.constant(object1))
assert.deepStrictEqual(func([object1, object2], largeArray), [object2])
})
it('`_.' + methodName + '` should ignore values that are not array-like', function() {
var array = [1, null, 3]
assert.deepStrictEqual(func(args, 3, { '0': 1 }), [1, 2, 3])
assert.deepStrictEqual(func(null, array, 1), [])
assert.deepStrictEqual(func(array, args, null), [null])
})
})
})
describe('differenceBy', function() {
const differenceBy = _.differenceBy
it('should accept an `iteratee`', function() {
var actual = differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor)
assert.deepStrictEqual(actual, [1.2])
actual = differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x')
assert.deepStrictEqual(actual, [{ 'x': 2 }])
})
it('should provide correct `iteratee` arguments', function() {
var args: any
differenceBy([2.1, 1.2], [2.3, 3.4], function() {
args || (args = slice.call(arguments))
})
assert.deepStrictEqual(args, [2.3])
})
})
describe('differenceWith', function() {
const differenceWith = _.differenceWith
it('should work with a `comparator`', function() {
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }],
actual = differenceWith(objects, [{ 'x': 1, 'y': 2 }], lodashStable.isEqual)
assert.deepStrictEqual(actual, [objects[1]])
})
it('should preserve the sign of `0`', function() {
var array = [-0, 1],
largeArray = lodashStable.times(LARGE_ARRAY_SIZE, stubOne),
others = [[1], largeArray],
expected = lodashStable.map(others, lodashStable.constant(['-0']))
var actual = lodashStable.map(others, function(other: any) {
return lodashStable.map(differenceWith(array, other, lodashStable.eq), lodashStable.toString)
})
assert.deepStrictEqual(actual, expected)
})
})
describe('divide', function() {
const divide = _.divide
it('should divide two numbers', function() {
assert.strictEqual(divide(6, 4), 1.5)
assert.strictEqual(divide(-6, 4), -1.5)
assert.strictEqual(divide(-6, -4), 1.5)
})
it('should coerce arguments to numbers', function() {
assert.strictEqual(divide('6', '4'), 1.5)
assert.deepStrictEqual(divide('x', 'y'), NaN)
})
})
describe('drop', function() {
const drop = _.drop
var array = [1, 2, 3]
it('should drop the first two elements', function() {
assert.deepStrictEqual(drop(array, 2), [3])
})
it('should treat falsey `n` values, except `undefined`, as `0`', function() {
var expected = lodashStable.map(falsey, function(value: undefined) {
return value === undefined ? [2, 3] : array
})
var actual = lodashStable.map(falsey, function(n: any) {
return drop(array, n)
})
assert.deepStrictEqual(actual, expected)
})
it('should return all elements when `n` < `1`', function() {
lodashStable.each([0, -1, -Infinity], function(n: any) {
assert.deepStrictEqual(drop(array, n), array)
})
})
it('should return an empty array when `n` >= `length`', function() {
lodashStable.each([3, 4, Math.pow(2, 32), Infinity], function(n: any) {
assert.deepStrictEqual(drop(array, n), [])
})
})
it('should coerce `n` to an integer', function() {
assert.deepStrictEqual(drop(array, 1.6), [2, 3])
})
it('should work in a lazy sequence', function() {
var array = lodashStable.range(1, LARGE_ARRAY_SIZE + 1),
predicate = function(value: number) { values.push(value); return isEven(value) },
values: any[] = [],
actual = _(array).drop(2).drop().value()
assert.deepEqual(actual, array.slice(3))
actual = _(array).filter(predicate).drop(2).drop().value()
assert.deepEqual(values, array)
assert.deepEqual(actual, drop(drop(_.filter(array, predicate), 2)))
actual = _(array).drop(2).dropRight().drop().dropRight(2).value()
assert.deepEqual(actual, _.dropRight(drop(_.dropRight(drop(array, 2))), 2))
values = []
actual = _(array).drop().filter(predicate).drop(2).dropRight().drop().dropRight(2).value()
assert.deepEqual(values, array.slice(1))
assert.deepEqual(actual, _.dropRight(drop(_.dropRight(drop(_.filter(drop(array), predicate), 2))), 2))
})
})
describe('dropRight', function() {
const dropRight = _.dropRight
var array = [1, 2, 3]
it('should drop the last two elements', function() {
assert.deepStrictEqual(dropRight(array, 2), [1])
})
it('should treat falsey `n` values, except `undefined`, as `0`', function() {
var expected = lodashStable.map(falsey, function(value: undefined) {
return value === undefined ? [1, 2] : array
})
var actual = lodashStable.map(falsey, function(n: any) {
return dropRight(array, n)
})
assert.deepStrictEqual(actual, expected)
})
it('should return all elements when `n` < `1`', function() {
lodashStable.each([0, -1, -Infinity], function(n: any) {
assert.deepStrictEqual(dropRight(array, n), array)
})
})
it('should return an empty array when `n` >= `length`', function() {
lodashStable.each([3, 4, Math.pow(2, 32), Infinity], function(n: any) {
assert.deepStrictEqual(dropRight(array, n), [])
})
})
it('should coerce `n` to an integer', function() {
assert.deepStrictEqual(dropRight(array, 1.6), [1, 2])
})
it('should work in a lazy sequence', function() {
var array = lodashStable.range(1, LARGE_ARRAY_SIZE + 1),
predicate = function(value: number) { values.push(value); return isEven(value) },
values: any[] = [],
actual = _(array).dropRight(2).dropRight().value()
assert.deepEqual(actual, array.slice(0, -3))
actual = _(array).filter(predicate).dropRight(2).dropRight().value()
assert.deepEqual(values, array)
assert.deepEqual(actual, dropRight(dropRight(_.filter(array, predicate), 2)))
actual = _(array).dropRight(2).drop().dropRight().drop(2).value()
assert.deepEqual(actual, _.drop(dropRight(_.drop(dropRight(array, 2))), 2))
values = []
actual = _(array).dropRight().filter(predicate).dropRight(2).drop().dropRight().drop(2).value()
assert.deepEqual(values, array.slice(0, -1))
assert.deepEqual(actual, _.drop(dropRight(_.drop(dropRight(_.filter(dropRight(array), predicate), 2))), 2))
})
})
describe('dropRightWhile', function() {
const dropRightWhile = _.dropRightWhile
var array = [1, 2, 3, 4]
var objects = [
{ 'a': 0, 'b': 0 },
{ 'a': 1, 'b': 1 },
{ 'a': 2, 'b': 2 },
]
it('should drop elements while `predicate` returns truthy', function() {
var actual = dropRightWhile(array, function(n: number) {
return n > 2
})
assert.deepStrictEqual(actual, [1, 2])
})
it('should provide correct `predicate` arguments', function() {
var args
dropRightWhile(array, function() {
args = slice.call(arguments)
})
assert.deepStrictEqual(args, [4, 3, array])
})
it('should work with `_.matches` shorthands', function() {
assert.deepStrictEqual(dropRightWhile(objects, { 'b': 2 }), objects.slice(0, 2))
})
it('should work with `_.matchesProperty` shorthands', function() {
assert.deepStrictEqual(dropRightWhile(objects, ['b', 2]), objects.slice(0, 2))
})
it('should work with `_.property` shorthands', function() {
assert.deepStrictEqual(dropRightWhile(objects, 'b'), objects.slice(0, 1))
})
it('should return a wrapped value when chaining', function() {
var wrapped = _(array).dropRightWhile(function(n: number) {
return n > 2
})
assert.ok(wrapped instanceof _)
assert.deepEqual(wrapped.value(), [1, 2])
})
})
describe('endsWith', function() {
const endsWith = _.endsWith
var string = 'abc'
it('should return `true` if a string ends with `target`', function() {
assert.strictEqual(endsWith(string, 'c'), true)
})
it('should return `false` if a string does not end with `target`', function() {
assert.strictEqual(endsWith(string, 'b'), false)
})
it('should work with a `position`', function() {
assert.strictEqual(endsWith(string, 'b', 2), true)
})
it('should work with `position` >= `length`', function() {
lodashStable.each([3, 5, MAX_SAFE_INTEGER, Infinity], function(position: any) {
assert.strictEqual(endsWith(string, 'c', position), true)
})
})
it('should treat falsey `position` values, except `undefined`, as `0`', function() {
var expected = lodashStable.map(falsey, stubTrue)
var actual = lodashStable.map(falsey, function(position: undefined) {
return endsWith(string, position === undefined ? 'c' : '', position)
})
assert.deepStrictEqual(actual, expected)
})
it('should treat a negative `position` as `0`', function() {
lodashStable.each([-1, -3, -Infinity], function(position: any) {
assert.ok(lodashStable.every(string, function(chr: any) {
return !endsWith(string, chr, position)
}))
assert.strictEqual(endsWith(string, '', position), true)
})
})
it('should coerce `position` to an integer', function() {
assert.strictEqual(endsWith(string, 'ab', 2.2), true)
})
})
describe('eq', function() {
const eq = _.eq
it('should perform a `SameValueZero` comparison of two values', function() {
assert.strictEqual(eq(), true)
assert.strictEqual(eq(undefined), true)
assert.strictEqual(eq(0, -0), true)
assert.strictEqual(eq(NaN, NaN), true)
assert.strictEqual(eq(1, 1), true)
assert.strictEqual(eq(null, undefined), false)
assert.strictEqual(eq(1, Object(1)), false)
assert.strictEqual(eq(1, '1'), false)
assert.strictEqual(eq(1, '1'), false)
var object = { 'a': 1 }
assert.strictEqual(eq(object, object), true)
assert.strictEqual(eq(object, { 'a': 1 }), false)
})
})
describe('escape', function() {
const escape = _.escape
const unescape = _.unescape
var escaped = '&<>"'/',
unescaped = '&<>"\'/'
escaped += escaped
unescaped += unescaped
it('should escape values', function() {
assert.strictEqual(escape(unescaped), escaped)
})
it('should handle strings with nothing to escape', function() {
assert.strictEqual(escape('abc'), 'abc')
})
it('should escape the same characters unescaped by `_.unescape`', function() {
assert.strictEqual(escape(unescape(escaped)), escaped)
})
lodashStable.each(['`', '/'], function(chr: string) {
it('should not escape the "' + chr + '" character', function() {
assert.strictEqual(escape(chr), chr)
})
})
})
describe('escapeRegExp', function() {
const escapeRegExp = _.escapeRegExp
var escaped = '\\^\\$\\.\\*\\+\\?\\(\\)\\[\\]\\{\\}\\|\\\\',
unescaped = '^$.*+?()[]{}|\\'
it('should escape values', function() {
assert.strictEqual(escapeRegExp(unescaped + unescaped), escaped + escaped)
})
it('should handle strings with nothing to escape', function() {
assert.strictEqual(escapeRegExp('abc'), 'abc')
})
it('should return an empty string for empty values', function() {
var values = [, null, undefined, ''],
expected = lodashStable.map(values, stubString)
var actual = lodashStable.map(values, function(value: any, index: any) {
return index ? escapeRegExp(value) : escapeRegExp()
})
assert.deepStrictEqual(actual, expected)
})
})
describe('every', function() {
const every = _.every
it('should return `true` if `predicate` returns truthy for all elements', function() {
assert.strictEqual(lodashStable.every([true, 1, 'a'], identity), true)
})
it('should return `true` for empty collections', function() {
var expected = lodashStable.map(empties, stubTrue)
var actual = lodashStable.map(empties, function(value: any) {
try {
return every(value, identity)
} catch (e) {}
})
assert.deepStrictEqual(actual, expected)
})
it('should return `false` as soon as `predicate` returns falsey', function() {
var count = 0
assert.strictEqual(every([true, null, true], function(value: any) {
count++
return value
}), false)
assert.strictEqual(count, 2)
})
it('should work with collections of `undefined` values (test in IE < 9)', function() {
assert.strictEqual(every([undefined, undefined, undefined], identity), false)
})
it('should use `_.identity` when `predicate` is nullish', function() {
var values = [, null, undefined],
expected = lodashStable.map(values, stubFalse)
var actual = lodashStable.map(values, function(value: any, index: any) {
var array = [0]
return index ? every(array, value) : every(array)
})
assert.deepStrictEqual(actual, expected)
expected = lodashStable.map(values, stubTrue)
actual = lodashStable.map(values, function(value: any, index: any) {
var array = [1]
return index ? every(array, value) : every(array)
})
assert.deepStrictEqual(actual, expected)
})
it('should work with `_.property` shorthands', function() {
var objects = [{ 'a': 0, 'b': 1 }, { 'a': 1, 'b': 2 }]
assert.strictEqual(every(objects, 'a'), false)
assert.strictEqual(every(objects, 'b'), true)
})
it('should work with `_.matches` shorthands', function() {
var objects = [{ 'a': 0, 'b': 0 }, { 'a': 0, 'b': 1 }]
assert.strictEqual(every(objects, { 'a': 0 }), true)
assert.strictEqual(every(objects, { 'b': 1 }), false)
})
it('should work as an iteratee for methods like `_.map`', function() {
var actual = lodashStable.map([[1]], every)
assert.deepStrictEqual(actual, [true])
})
})
describe('exit early', function() {
lodashStable.each(['_baseEach', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'transform'], function(methodName: string) {
var func = _[methodName]
it('`_.' + methodName + '` can exit early when iterating arrays', function() {
if (func) {
var array = [1, 2, 3],
values: any[] = []
func(array, function(value: any, other: any) {
values.push(lodashStable.isArray(value) ? other : value)
return false
})
assert.deepStrictEqual(values, [lodashStable.endsWith(methodName, 'Right') ? 3 : 1])
}
})
it('`_.' + methodName + '` can exit early when iterating objects', function() {
if (func) {
var object = { 'a': 1, 'b': 2, 'c': 3 },
values = []
func(object, function(value: any, other: any) {
values.push(lodashStable.isArray(value) ? other : value)
return false
})
assert.strictEqual(values.length, 1)
}
})
})
})
describe('extremum methods', function() {
lodashStable.each(['max', 'maxBy', 'min', 'minBy'], function(methodName: string) {
var func = _[methodName],
isMax = /^max/.test(methodName)
it('`_.' + methodName + '` should work with Date objects', function() {
var curr = new Date,
past = new Date(0)
assert.strictEqual(func([curr, past]), isMax ? curr : past)
})
/** 性能问题要解决 */
xit('`_.' + methodName + '` should work with extremely large arrays', function() {
var array = lodashStable.range(0, 5e5)
assert.strictEqual(func(array), isMax ? 499999 : 0)
})
it('`_.' + methodName + '` should work when chaining on an array with only one value', function() {
var actual = _([40])[methodName]()
assert.strictEqual(actual, 40)
})
})
lodashStable.each(['maxBy', 'minBy'], function(methodName: string) {
var array = [1, 2, 3],
func = _[methodName],
isMax = methodName == 'maxBy'
it('`_.' + methodName + '` should work with an `iteratee`', function() {
var actual = func(array, function(n: number) {
return -n
})
assert.strictEqual(actual, isMax ? 1 : 3)
})
it('should work with `_.property` shorthands', function() {
var objects = [{ 'a': 2 }, { 'a': 3 }, { 'a': 1 }],
actual = func(objects, 'a')
assert.deepStrictEqual(actual, objects[isMax ? 1 : 2])
var arrays = [[2], [3], [1]]
actual = func(arrays, 0)
assert.deepStrictEqual(actual, arrays[isMax ? 1 : 2])
})
it('`_.' + methodName + '` should work when `iteratee` returns +/-Infinity', function() {
var value = isMax ? -Infinity : Infinity,
object = { 'a': value }
var actual = func([object, { 'a': value }], function(object: { a: any }) {
return object.a
})
assert.strictEqual(actual, object)
})
})
})
describe('fill', function() {
const fill = _.fill
it('should use a default `start` of `0` and a default `end` of `length`', function() {
var array = [1, 2, 3]
assert.deepStrictEqual(fill(array, 'a'), ['a', 'a', 'a'])
})
it('should use `undefined` for `value` if not given', function() {
var array = [1, 2, 3],
actual = fill(array)
assert.deepStrictEqual(actual, Array(3))
assert.ok(lodashStable.every(actual, function(value: any, index: string) {
return index in actual
}))
})
it('should work with a positive `start`', function() {
var array = [1, 2, 3]
assert.deepStrictEqual(fill(array, 'a', 1), [1, 'a', 'a'])
})
it('should work with a `start` >= `length`', function() {
lodashStable.each([3, 4, Math.pow(2, 32), Infinity], function(start: any) {
var array = [1, 2, 3]
assert.deepStrictEqual(fill(array, 'a', start), [1, 2, 3])
})
})
it('should treat falsey `start` values as `0`', function() {
var expected = lodashStable.map(falsey, lodashStable.constant(['a', 'a', 'a']))
var actual = lodashStable.map(falsey, function(start: any) {
var array = [1, 2, 3]
return fill(array, 'a', start)
})
assert.deepStrictEqual(actual, expected)
})
it('should work with a negative `start`', function() {
var array = [1, 2, 3]
assert.deepStrictEqual(fill(array, 'a', -1), [1, 2, 'a'])
})
it('should work with a negative `start` <= negative `length`', function() {
lodashStable.each([-3, -4, -Infinity], function(start: any) {
var array = [1, 2, 3]
assert.deepStrictEqual(fill(array, 'a', start), ['a', 'a', 'a'])
})
})
it('should work with `start` >= `end`', function() {
lodashStable.each([2, 3], function(start: any) {
var array = [1, 2, 3]
assert.deepStrictEqual(fill(array, 'a', start, 2), [1, 2, 3])
})
})
it('should work with a positive `end`', function() {
var array = [1, 2, 3]
assert.deepStrictEqual(fill(array, 'a', 0, 1), ['a', 2, 3])
})
it('should work with a `end` >= `length`', function() {
lodashStable.each([3, 4, Math.pow(2, 32), Infinity], function(end: any) {
var array = [1, 2, 3]
assert.deepStrictEqual(fill(array, 'a', 0, end), ['a', 'a', 'a'])
})
})
it('should treat falsey `end` values, except `undefined`, as `0`', function() {
var expected = lodashStable.map(falsey, function(value: undefined) {
return value === undefined ? ['a', 'a', 'a'] : [1, 2, 3]
})
var actual = lodashStable.map(falsey, function(end: any) {
var array = [1, 2, 3]
return fill(array, 'a', 0, end)
})
assert.deepStrictEqual(actual, expected)
})
it('should work with a negative `end`', function() {
var array = [1, 2, 3]
assert.deepStrictEqual(fill(array, 'a', 0, -1), ['a', 'a', 3])
})
it('should work with a negative `end` <= negative `length`', function() {
lodashStable.each([-3, -4, -Infinity], function(end: any) {
var array = [1, 2, 3]
assert.deepStrictEqual(fill(array, 'a', 0, end), [1, 2, 3])
})
})
it('should coerce `start` and `end` to integers', function() {
var positions = [[0.1, 1.6], ['0', 1], [0, '1'], ['1'], [NaN, 1], [1, NaN]]
var actual = lodashStable.map(positions, function(pos: ConcatArray<string | number[]>) {
var array = [1, 2, 3]
return fill.apply(_, [array, 'a'].concat(pos))
})
assert.deepStrictEqual(actual, [['a', 2, 3], ['a', 2, 3], ['a', 2, 3], [1, 'a', 'a'], ['a', 2, 3], [1, 2, 3]])
})
it('should work as an iteratee for methods like `_.map`', function() {
var array = [[1, 2], [3, 4]],
actual = lodashStable.map(array, fill)
assert.deepStrictEqual(actual, [[0, 0], [1, 1]])
})
it('should return a wrapped value when chaining', function() {
var array = [1, 2, 3],
wrapped = _(array).fill('a'),
actual = wrapped.value()
assert.ok(wrapped instanceof _)
assert.strictEqual(actual, array)
assert.deepEqual(actual, ['a', 'a', 'a'])
})
})
describe('filter methods', function() {
lodashStable.each(['filter', 'reject'], function(methodName: string) {
var array = [1, 2, 3, 4],
func = _[methodName],
isFilter = methodName == 'filter',
objects = [{ 'a': 0 }, { 'a': 1 }]
it('`_.' + methodName + '` should not modify the resulting value from within `predicate`', function() {
var actual = func([0], function(value: any, index: string | number, array: { [x: string]: number }) {
array[index] = 1
return isFilter
})
assert.deepStrictEqual(actual, [0])
})
it('`_.' + methodName + '` should work with `_.property` shorthands', function() {
assert.deepStrictEqual(func(objects, 'a'), [objects[isFilter ? 1 : 0]])
})
it('`_.' + methodName + '` should work with `_.matches` shorthands', function() {
assert.deepStrictEqual(func(objects, objects[1]), [objects[isFilter ? 1 : 0]])
})
it('`_.' + methodName + '` should not modify wrapped values', function() {
var wrapped = _(array)
var actual = wrapped[methodName](function(n: number) {
return n < 3
})
assert.deepEqual(actual.value(), isFilter ? [1, 2] : [3, 4])
actual = wrapped[methodName](function(n: number) {
return n > 2
})
assert.deepEqual(actual.value(), isFilter ? [3, 4] : [1, 2])
})
it('`_.' + methodName + '` should work in a lazy sequence', function() {
var array = lodashStable.range(LARGE_ARRAY_SIZE + 1),
predicate = function(value: number) { return isFilter ? isEven(value) : !isEven(value) }
var object = lodashStable.zipObject(lodashStable.times(LARGE_ARRAY_SIZE, function(index: string) {
return ['key' + index, index]
}))
var actual = _(array).slice(1).map(square)[methodName](predicate).value()
assert.deepEqual(actual, _[methodName](lodashStable.map(array.slice(1), square), predicate))
actual = _(object).mapValues(square)[methodName](predicate).value()
assert.deepEqual(actual, _[methodName](lodashStable.mapValues(object, square), predicate))
})
it('`_.' + methodName + '` should provide correct `predicate` arguments in a lazy sequence', function() {
var args: any[] | undefined,
array = lodashStable.range(LARGE_ARRAY_SIZE + 1),
expected = [1, 0, lodashStable.map(array.slice(1), square)]
_(array).slice(1)[methodName](function(value: any, index: any, array: any) {
args || (args = slice.call(arguments))
}).value()
assert.deepEqual(args, [1, 0, array.slice(1)])
args = undefined
_(array).slice(1).map(square)[methodName](function(value: any, index: any, array: any) {
args || (args = slice.call(arguments))
}).value()
assert.deepEqual(args, expected)
args = undefined
_(array).slice(1).map(square)[methodName](function(value: any, index: any) {
args || (args = slice.call(arguments))
}).value()
assert.deepEqual(args, expected)
args = undefined
_(array).slice(1).map(square)[methodName](function(value: any) {
args || (args = slice.call(arguments))
}).value()
assert.deepEqual(args, [1])
args = undefined
_(array).slice(1).map(square)[methodName](function() {
args || (args = slice.call(arguments))
}).value()
assert.deepEqual(args, expected)
})
})
})
describe('find and findLast', function() {
lodashStable.each(['find', 'findLast'], function(methodName: string) {
var isFind = methodName == 'find'
it('`_.' + methodName + '` should support shortcut fusion', function() {
var findCount = 0,
mapCount = 0,
array = lodashStable.range(1, LARGE_ARRAY_SIZE + 1),
iteratee = function(value: number) { mapCount++; return square(value) },
predicate = function(value: number) { findCount++; return isEven(value) },
actual = _(array).map(iteratee)[methodName](predicate)
assert.strictEqual(findCount, isFind ? 2 : 1)
assert.strictEqual(mapCount, isFind ? 2 : 1)
assert.strictEqual(actual, isFind ? 4 : square(LARGE_ARRAY_SIZE))
})
})
})
describe('find and includes', function() {
lodashStable.each(['includes', 'find'], function(methodName: string) {
var func = _[methodName],
isIncludes = methodName == 'includes',
resolve = methodName == 'find' ? lodashStable.curry(lodashStable.eq) : identity
lodashStable.each({
'an `arguments` object': args,
'an array': [1, 2, 3],
},
function(collection: any, key: string) {
var values = lodashStable.toArray(collection)
it('`_.' + methodName + '` should work with ' + key + ' and a positive `fromIndex`', function() {
var expected = [
isIncludes || values[2],
isIncludes ? false : undefined,
]
var actual = [
func(collection, resolve(values[2]), 2),
func(collection, resolve(values[1]), 2),
]
assert.deepStrictEqual(actual, expected)
})
it('`_.' + methodName + '` should work with ' + key + ' and a `fromIndex` >= `length`', function() {
var indexes = [4, 6, Math.pow(2, 32), Infinity]
var expected = lodashStable.map(indexes, function() {
var result = isIncludes ? false : undefined
return [result, result, result]
})
var actual = lodashStable.map(indexes, function(fromIndex: any) {
return [
func(collection, resolve(1), fromIndex),
func(collection, resolve(undefined), fromIndex),
func(collection, resolve(''), fromIndex),
]
})
assert.deepStrictEqual(actual, expected)
})
it('`_.' + methodName + '` should work with ' + key + ' and treat falsey `fromIndex` values as `0`', function() {
var expected = lodashStable.map(falsey, lodashStable.constant(isIncludes || values[0]))
var actual = lodashStable.map(falsey, function(fromIndex: any) {
return func(collection, resolve(values[0]), fromIndex)
})
assert.deepStrictEqual(actual, expected)
})
it('`_.' + methodName + '` should work with ' + key + ' and coerce `fromIndex` to an integer', function() {
var expected = [
isIncludes || values[0],
isIncludes || values[0],
isIncludes ? false : undefined,
]
var actual = [
func(collection, resolve(values[0]), 0.1),
func(collection, resolve(values[0]), NaN),
func(collection, resolve(values[0]), '1'),
]
assert.deepStrictEqual(actual, expected)
})
it('`_.' + methodName + '` should work with ' + key + ' and a negative `fromIndex`', function() {
var expected = [
isIncludes || values[2],
isIncludes ? false : undefined,
]
var actual = [
func(collection, resolve(values[2]), -1),
func(collection, resolve(values[1]), -1),
]
assert.deepStrictEqual(actual, expected)
})
it('`_.' + methodName + '` should work with ' + key + ' and a negative `fromIndex` <= `-length`', function() {
var indexes = [-4, -6, -Infinity],
expected = lodashStable.map(indexes, lodashStable.constant(isIncludes || values[0]))
var actual = lodashStable.map(indexes, function(fromIndex: any) {
return func(collection, resolve(values[0]), fromIndex)
})
assert.deepStrictEqual(actual, expected)
})
})
})
})
describe('find methods', function() {
lodashStable.each(['find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', 'findLastKey'], function(methodName: string) {
var array = [1, 2, 3, 4],
func = _[methodName]
var objects = [
{ 'a': 0, 'b': 0 },
{ 'a': 1, 'b': 1 },
{ 'a': 2, 'b': 2 },
]
var expected = ({
'find': [objects[1], undefined, objects[2]],
'findIndex': [1, -1, 2],
'findKey': ['1', undefined, '2'],
'findLast': [objects[2], undefined, objects[2]],
'findLastIndex': [2, -1, 2],
'findLastKey': ['2', undefined, '2'],
})[methodName]
it('`_.' + methodName + '` should return the found value', function() {
assert.strictEqual(func(objects, function(object: { a: any }) { return object.a }), expected[0])
})
it('`_.' + methodName + '` should return `' + expected[1] + '` if value is not found', function() {
assert.strictEqual(func(objects, function(object: { a: number }) { return object.a === 3 }), expected[1])
})
it('`_.' + methodName + '` should work with `_.matches` shorthands', function() {
assert.strictEqual(func(objects, { 'b': 2 }), expected[2])
})
it('`_.' + methodName + '` should work with `_.matchesProperty` shorthands', function() {
assert.strictEqual(func(objects, ['b', 2]), expected[2])
})
it('`_.' + methodName + '` should work with `_.property` shorthands', function() {
assert.strictEqual(func(objects, 'b'), expected[0])
})
it('`_.' + methodName + '` should return `' + expected[1] + '` for empty collections', function() {
var emptyValues = lodashStable.endsWith(methodName, 'Index') ? lodashStable.reject(empties, lodashStable.isPlainObject) : empties,
expecting = lodashStable.map(emptyValues, lodashStable.constant(expected[1]))
var actual = lodashStable.map(emptyValues, function(value: any) {
try {
return func(value, { 'a': 3 })
} catch (e) {}
})
assert.deepStrictEqual(actual, expecting)
})
it('`_.' + methodName + '` should return an unwrapped value when implicitly chaining', function() {
var expected = ({
'find': 1,
'findIndex': 0,
'findKey': '0',
'findLast': 4,
'findLastIndex': 3,
'findLastKey': '3',
})[methodName]
assert.strictEqual(_(array)[methodName](), expected)
})
it('`_.' + methodName + '` should return a wrapped value when explicitly chaining', function() {
assert.ok(_(array).chain()[methodName]() instanceof _)
})
it('`_.' + methodName + '` should not execute immediately when explicitly chaining', function() {
var wrapped = _(array).chain()[methodName]()
assert.strictEqual(wrapped.__wrapped__, array)
})
it('`_.' + methodName + '` should work in a lazy sequence', function() {
var largeArray = lodashStable.range(1, LARGE_ARRAY_SIZE + 1),
smallArray = array
lodashStable.times(2, function(index: any) {
var array = index ? largeArray : smallArray,
wrapped = _(array).filter(isEven)
assert.strictEqual(wrapped[methodName](), func(lodashStable.filter(array, isEven)))
})
})
})
}) | the_stack |
import { ActionChart, state, gameView, mechanicsEngine, BookSeriesId, App, BookSeries, translations, KaiDiscipline, template, randomTable, DebugMode } from "../..";
/**
* Setup player disciplines
*/
export class SetupDisciplines {
/** Prefix for disciplines checkboxes id */
public static readonly DISCIPLINE_CHECKBOX_ID = "mechanics-discipline-chk-";
/** Prefix for weapon checkboxes id */
public static readonly WEAPON_CHECKBOX_ID = "mechanics-weapon-chk-";
/**
* Weapons table for Weaponskill discipline in Kai books (IT DOES NOT CONTAIN BOW!!!)
*/
public static readonly kaiWeapons = ["dagger", "spear", "mace", "shortsword", "warhammer", "sword",
"axe", "sword", "quarterstaff", "broadsword"];
/**
* Weapons table for Weaponmastery discipline in Magnakai books
*/
public static readonly magnakaiWeapons = ["dagger", "spear", "mace", "shortsword", "warhammer", "bow",
"axe", "sword", "quarterstaff", "broadsword"];
/**
* Weapons table for Weaponmastery discipline in Grand Master books
*/
private static readonly grandMasterWeapons = ["spear", "bow", "dagger", "quarterstaff", "mace", "broadsword",
"shortsword", "axe", "warhammer", "sword"];
/**
* Expected number of disciplines to choose
*/
private readonly expectedNDisciplines: number;
/**
* The last book player action chart.
* null if this is the first book the player play
*/
private readonly previousActionChart: ActionChart = null;
constructor() {
// Get info about the last played book
const previousBookNumber = state.book.bookNumber - 1;
if (previousBookNumber >= 1) {
this.previousActionChart = state.getPreviousBookActionChart(previousBookNumber);
// When a series start, by default, keep Weaponmastery with the same weapons from previous series
// DO NOT: This is OK in Kai -> Magnakai transition, but not in Magnakai -> Grand Master
// You can end Magnakai with weaponskill with, say, 5 weapons, but you start with less weapons. So, do not
/*if (this.previousActionChart && this.previousBookSeries !== state.book.getBookSeries().id &&
state.actionChart.getWeaponSkill().length === 0 ) {
state.actionChart.setWeaponSkill( this.previousActionChart.getWeaponSkill(this.previousBookSeries).clone() );
}*/
}
this.expectedNDisciplines = this.getNExpectedDisciplines();
}
/**
* Choose the kai disciplines UI
*/
public setupDisciplinesChoose() {
// Add the warning about the number of disciplines
gameView.appendToSection(mechanicsEngine.getMechanicsUI("mechanics-setDisciplines-NDis"));
$("#mechanics-nDisciplines").text(this.expectedNDisciplines);
// Add the warning about the number of weapons for weaponmastery
gameView.appendToSection(mechanicsEngine.getMechanicsUI("mechanics-setDisciplines-NWeapons"));
$("#mechanics-setDisciplines-weaponsmax").text(this.getExpectedNWeaponsWeaponmastery());
// Add checkbox for each discipline:
const self = this;
$('.subsection[id!="mksumary"]').append(mechanicsEngine.getMechanicsUI("mechanics-setDisciplines"))
.each((index, disciplineSection) => {
self.setupDisciplineCheckBox($(disciplineSection));
})
// Set events when checkboxes are clicked
.find("input[type=checkbox]")
.click(function(e) {
self.onDiscliplineCheckBoxClick(e, $(this));
});
// If we are on a magnakai book, add the weapons checkboxes
this.populateMagnakaiWeapons();
// Set the already choosen weapon for the Weaponskill
this.setWeaponSkillWeaponNameOnUI();
// Initialize UI state
this.afterDisciplineSelection();
}
/**
* Add checkboxes to select weapons for Weaponmastery.
* Only for magnakai books
*/
private populateMagnakaiWeapons() {
// Only for series >= Magnakai
const currentSeriesId = state.book.getBookSeries().id;
if (currentSeriesId < BookSeriesId.Magnakai) {
return;
}
const weaponsTable = (currentSeriesId === BookSeriesId.GrandMaster ? SetupDisciplines.grandMasterWeapons :
SetupDisciplines.magnakaiWeapons);
// Add checkboxes
const $checkboxTemplate = mechanicsEngine.getMechanicsUI("mechanics-magnakaiWeapon");
let html = "";
for (let i = 0; i < weaponsTable.length; i++) {
if (i % 2 === 0) {
html += '<div class="row">';
}
// Prepare the weapon UI
const weaponItem = state.mechanics.getObject(weaponsTable[i]);
const $checkboxDiv = $checkboxTemplate.clone();
$checkboxDiv.attr("id", weaponItem.id);
$checkboxDiv.find(".mechanics-wName").text(weaponItem.name);
// The weapon has been already selected?
const selected: boolean = state.actionChart.getWeaponSkill().contains(weaponsTable[i]);
const $chk = $checkboxDiv.find("input");
$chk.attr("id", SetupDisciplines.WEAPON_CHECKBOX_ID + weaponItem.id);
$chk.attr("checked", selected);
html += $checkboxDiv[0].outerHTML;
if (i % 2 === 1) {
html += "</div>";
}
}
const $well = $("#wpnmstry .well");
$well.append(html);
// Add event handlers
const self = this;
$well.find("input.weaponmastery-chk")
.click(function(e: Event) {
self.onWeaponmasteryWeaponClick(e, $(this));
});
// Set the initial state
this.enableMagnakaiWeapons();
}
/**
* Enable or disable weapons selection for Weaponmastery
*/
private enableMagnakaiWeapons() {
const bookSeries = state.book.getBookSeries();
// Only for Magnakai / Grand Master books
if (bookSeries.id < BookSeriesId.Magnakai) {
return;
}
const disable: boolean = false;
// If Weaponmastery is not selected, disable all weapons
if (!state.actionChart.hasDiscipline(bookSeries.weaponskillDiscipline)) {
$("input.weaponmastery-chk").prop("disabled", true);
return;
}
// By default, enable all weapons
$("input.weaponmastery-chk").prop("disabled", false);
// If Weaponmastery was selected on a previous book, disable the weapons already
// selected on the previous book. This only applies if the book is not a series start
if (App.debugMode !== DebugMode.DEBUG &&
!BookSeries.isSeriesStart(state.book.bookNumber) &&
this.previousActionChart &&
this.previousActionChart.hasDiscipline(bookSeries.weaponskillDiscipline)
) {
for (const weaponId of this.previousActionChart.getWeaponSkill()) {
$("#" + weaponId + " input[type=checkbox]").prop("disabled", true);
}
}
}
/**
* Returns the number of weapons to select for the Weaponmastery discipline.
* Only for Magnakai / Grand Master books
*/
private getExpectedNWeaponsWeaponmastery(): number {
const bookSeries = state.book.getBookSeries();
let nWeapons = bookSeries.initialWeaponskillNWeapons;
if (BookSeries.isSeriesStart(state.book.bookNumber)) {
// If first book of a serie, don't check previous book
return nWeapons;
}
if (this.previousActionChart && this.previousActionChart.hasDiscipline(bookSeries.weaponskillDiscipline)) {
// One more for this book
nWeapons = this.previousActionChart.getWeaponSkill().length + 1;
}
return nWeapons;
}
/**
* Click on a Weaponmastery weapon event handler
* @param e The click event
* @param $checkBox The checkbox (jQuery)
*/
private onWeaponmasteryWeaponClick(e: Event, $checkBox: JQuery<HTMLElement>) {
const selected: boolean = $checkBox.prop("checked");
const weaponId: string = $checkBox.closest(".weaponmastery-weapon").attr("id");
if (selected) {
// Check the maximum weapons number
const nExpectedWeapons = this.getExpectedNWeaponsWeaponmastery();
if (App.debugMode !== DebugMode.DEBUG && state.actionChart.getWeaponSkill().length >= nExpectedWeapons) {
e.preventDefault();
alert(translations.text("onlyNWeapons", [nExpectedWeapons]));
return;
}
state.actionChart.getWeaponSkill().push(weaponId);
} else {
state.actionChart.getWeaponSkill().removeValue(weaponId);
}
// Update UI
this.afterDisciplineSelection();
}
/**
* Initialize a discliplne check box
* @param $disciplineSection The checkbox to initialize (Jquery)
*/
private setupDisciplineCheckBox($disciplineSection: JQuery<HTMLElement>) {
// Set the discipline name on the checkbox
const $title = $disciplineSection.find(".subsectionTitle");
$disciplineSection.find(".mechanics-dName").text($title.text());
// Set checkbox initial value
const disciplineId: string = $disciplineSection.attr("id");
const $check = $disciplineSection.find("input[type=checkbox]");
$check.prop("checked", state.actionChart.hasDiscipline(disciplineId));
$check.attr("id", SetupDisciplines.DISCIPLINE_CHECKBOX_ID + disciplineId);
// If the player had this discipline on the previous book, disable the check
// On debug mode, always enabled
if (App.debugMode !== DebugMode.DEBUG &&
!BookSeries.isSeriesStart(state.book.bookNumber) &&
this.previousActionChart &&
this.previousActionChart.hasDiscipline(disciplineId)
) {
$check.prop("disabled", true);
}
}
/**
* Handle click on discipline checkbox
* @param e The click event
* @param $checkBox The clicked checkbox (JQuery)
*/
private onDiscliplineCheckBoxClick(e: Event, $checkBox: JQuery<HTMLElement>) {
// Limit the number of disciplines. Unlimited on debug mode
const selected: boolean = $checkBox.prop("checked");
if (selected && this.getAllDisciplinesSelected() && App.debugMode !== DebugMode.DEBUG) {
e.preventDefault();
alert(translations.text("maxDisciplines", [this.expectedNDisciplines]));
return;
}
// Add / remove the discipline
const disciplineId: string = $checkBox.closest(".subsection").attr("id");
if (selected) {
this.onDisciplineSelected(e, disciplineId);
} else {
state.actionChart.getDisciplines().removeValue(disciplineId);
}
this.afterDisciplineSelection();
}
/**
* Discipline selected event handler
* @param e The discipline check box click event
* @param disciplineId The selected discipline
*/
private onDisciplineSelected(e: Event, disciplineId: string) {
if (disciplineId === KaiDiscipline.Weaponskill) {
// Special case for kai series: Choose on the random table the weapon
this.chooseWeaponskillWeapon(e);
return;
}
state.actionChart.getDisciplines().push(disciplineId);
}
/**
* Code to call after a discipline is selected / deselected
*/
private afterDisciplineSelection() {
let enableNextPage = true;
// Check all disiciplines selected
if (this.getAllDisciplinesSelected()) {
$("#mechanics-setDisciplines-NDis").hide();
} else {
$("#mechanics-setDisciplines-NDis").show();
enableNextPage = false;
}
// Check weapons selected for Magnakai / Grand Master books
const bookSeries = state.book.getBookSeries();
if (bookSeries.id >= BookSeriesId.Magnakai &&
state.actionChart.hasDiscipline(bookSeries.weaponskillDiscipline) &&
state.actionChart.getWeaponSkill().length < this.getExpectedNWeaponsWeaponmastery()
) {
enableNextPage = false;
$("#mechanics-setDisciplines-NWeapons").show();
} else {
$("#mechanics-setDisciplines-NWeapons").hide();
}
gameView.enableNextLink(enableNextPage);
this.enableMagnakaiWeapons();
template.updateStatistics();
}
/**
* Do the random choice for Weaponskill weapon.
* Only applies to Kai series
*/
private chooseWeaponskillWeapon(e: Event) {
if (state.actionChart.getWeaponSkill().length > 0) {
// Weapon already choosed
state.actionChart.getDisciplines().push(KaiDiscipline.Weaponskill);
return;
}
// Do not mark the check yet. The "if" is REQUIRED, otherwise the check is not marked with computer generated random table
if (state.actionChart.manualRandomTable) {
e.preventDefault();
}
// Pick a random number
randomTable.getRandomValueAsync()
.then((value: number) => {
// Store the discipline
state.actionChart.getDisciplines().push(KaiDiscipline.Weaponskill);
state.actionChart.getWeaponSkill().push(SetupDisciplines.kaiWeapons[value]);
// Show on UI the selected weapon
this.setWeaponSkillWeaponNameOnUI();
const $well = $("#wepnskll .well");
$well.append("<div><i><small>" + translations.text("randomTable") + ": " + value + "</small></i></div>");
// Mark the checkbox
$well.find("input[type=checkbox]").prop("checked", true);
this.afterDisciplineSelection();
});
}
/**
* Set the weapon name on UI.
* Only applies to Kai serie
*/
private setWeaponSkillWeaponNameOnUI() {
if (state.actionChart.getWeaponSkill().length === 0) {
// No weapon selected yet
return;
}
if (state.book.getBookSeries().id > BookSeriesId.Kai) {
// Only for kai books
return;
}
const o = state.mechanics.getObject(state.actionChart.getWeaponSkill()[0]);
$("#wepnskll .mechanics-wName").text("(" + o.name + ")");
}
/**
* Get the number of expected disciplines on the current book
* @returns Number of expected disciplines
*/
private getNExpectedDisciplines(): number {
let expectedNDisciplines = state.book.getBookSeries().initialNDisciplines;
// If first book of a series, don't check previous book
if (BookSeries.isSeriesStart(state.book.bookNumber)) {
return expectedNDisciplines;
}
// Number of disciplines to choose (previous book disciplines + 1):
if (this.previousActionChart) {
expectedNDisciplines = this.previousActionChart.getDisciplines().length + 1;
}
return expectedNDisciplines;
}
/**
* Are all disciplines selected?
* @returns True if all disciplines are selected
*/
private getAllDisciplinesSelected(): boolean {
return state.actionChart.getDisciplines().length >= this.expectedNDisciplines;
}
} | the_stack |
import debounce from 'lodash.debounce';
import initialiseControlsUi from './controls-ui';
import { Circular2DBuffer } from './math-util';
import { SpectrogramGPURenderer, RenderParameters } from './spectrogram-render';
import { offThreadGenerateSpectrogram } from './worker-util';
const SPECTROGRAM_WINDOW_SIZE = 4096;
const SPECTROGRAM_WINDOW_OVERLAP = 1024;
interface SpectrogramBufferData {
buffer: Float32Array;
start: number;
length: number;
sampleRate: number;
isStart: boolean;
}
// Starts rendering the spectrograms, returning callbacks used to provide audio samples to render
// and update the display parameters of the spectrograms
async function startRenderingSpectrogram(): Promise<{
bufferCallback: (bufferData: SpectrogramBufferData[]) => Promise<Float32Array[]>;
clearCallback: () => void;
updateRenderParameters: (parameters: Partial<RenderParameters>) => void;
}> {
// The canvases that will render the spectrogram for each audio channel
const spectrogramCanvases = [
document.querySelector('#leftSpectrogram') as HTMLCanvasElement | null,
document.querySelector('#rightSpectrogram') as HTMLCanvasElement | null,
];
// The callbacks for each spectrogram that will render the audio samples provided when called
const bufferCallbacks: ((bufferData: SpectrogramBufferData) => Promise<Float32Array>)[] = [];
// Set up the WebGL contexts for each spectrogram
const spectrogramBuffers: Circular2DBuffer<Float32Array>[] = [];
const renderers: SpectrogramGPURenderer[] = [];
spectrogramCanvases.forEach((canvas) => {
if (canvas === null || canvas.parentElement === null) {
return;
}
// The 2D circular queue of the FFT data for each audio channel
const spectrogramBuffer = new Circular2DBuffer(
Float32Array,
canvas.parentElement.offsetWidth,
SPECTROGRAM_WINDOW_SIZE / 2,
1
);
spectrogramBuffers.push(spectrogramBuffer);
const renderer = new SpectrogramGPURenderer(
canvas,
spectrogramBuffer.width,
spectrogramBuffer.height
);
renderer.resizeCanvas(canvas.parentElement.offsetWidth, canvas.parentElement.offsetHeight);
renderers.push(renderer);
let imageDirty = false;
bufferCallbacks.push(
async ({ buffer, start, length, sampleRate, isStart }: SpectrogramBufferData) => {
renderer.updateParameters({
windowSize: SPECTROGRAM_WINDOW_SIZE,
sampleRate,
});
const spectrogram = await offThreadGenerateSpectrogram(buffer, start, length, {
windowSize: SPECTROGRAM_WINDOW_SIZE,
windowStepSize: SPECTROGRAM_WINDOW_OVERLAP,
sampleRate,
isStart,
});
spectrogramBuffer.enqueue(spectrogram.spectrogram);
imageDirty = true;
return spectrogram.input;
}
);
// Trigger a render on each frame only if we have new spectrogram data to display
const render = () => {
if (imageDirty) {
renderer.updateSpectrogram(spectrogramBuffer);
}
renderer.render();
requestAnimationFrame(render);
};
requestAnimationFrame(render);
});
// Handle resizing of the window
const resizeHandler = debounce(() => {
spectrogramCanvases.forEach((canvas, i) => {
if (canvas === null || canvas.parentElement === null) {
return;
}
spectrogramBuffers[i].resizeWidth(canvas.parentElement.offsetWidth);
renderers[i].resizeCanvas(
canvas.parentElement.offsetWidth,
canvas.parentElement.offsetHeight
);
renderers[i].updateSpectrogram(spectrogramBuffers[i]);
});
}, 250);
window.addEventListener('resize', resizeHandler);
// Make sure the canvas still displays properly in the middle of a resize
window.addEventListener('resize', () => {
spectrogramCanvases.forEach((canvas, i) => {
if (canvas === null || canvas.parentElement === null) {
return;
}
renderers[i].fastResizeCanvas(
canvas.parentElement.offsetWidth,
canvas.parentElement.offsetHeight
);
});
});
return {
bufferCallback: (buffers: SpectrogramBufferData[]) =>
Promise.all(buffers.map((buffer, i) => bufferCallbacks[i](buffer))),
clearCallback: () => {
renderers.forEach((renderer, i) => {
spectrogramBuffers[i].clear();
renderer.updateSpectrogram(spectrogramBuffers[i], true);
});
},
updateRenderParameters: (parameters: Partial<RenderParameters>) => {
for (let i = 0; i < renderers.length; i += 1) {
renderers[i].updateParameters(parameters);
}
},
};
}
async function setupSpectrogramFromMicrophone(
audioCtx: AudioContext,
bufferCallback: (bufferData: SpectrogramBufferData[]) => Promise<Float32Array[]>
) {
const CHANNELS = 2;
const mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
const source = audioCtx.createMediaStreamSource(mediaStream);
const processor = audioCtx.createScriptProcessor(
SPECTROGRAM_WINDOW_OVERLAP,
CHANNELS,
CHANNELS
);
// An array of the last received audio buffers for each channel
const channelBuffers: Float32Array[][] = [];
for (let i = 0; i < CHANNELS; i += 1) {
channelBuffers.push([]);
}
let sampleRate: number | null = null;
let isStart = true;
let bufferCallbackPromise: Promise<Float32Array[]> | null = null;
const processChannelBuffers = () => {
if (bufferCallbackPromise !== null) {
return;
}
const buffers: Float32Array[] = [];
for (let i = 0; i < CHANNELS; i += 1) {
// Check if we have at least full window to render yet
if (channelBuffers[i].length < SPECTROGRAM_WINDOW_SIZE / SPECTROGRAM_WINDOW_OVERLAP) {
break;
}
// Merge all the buffers we have so far into a single buffer for rendering
const buffer = new Float32Array(channelBuffers[i].length * SPECTROGRAM_WINDOW_OVERLAP);
buffers.push(buffer);
for (let j = 0; j < channelBuffers[i].length; j += 1) {
buffer.set(channelBuffers[i][j], SPECTROGRAM_WINDOW_OVERLAP * j);
}
// Delete the oldest buffers that aren't needed any more for the next render
channelBuffers[i].splice(
0,
channelBuffers[i].length - SPECTROGRAM_WINDOW_SIZE / SPECTROGRAM_WINDOW_OVERLAP + 1
);
}
// Render the single merged buffer for each channel
if (buffers.length > 0) {
bufferCallbackPromise = bufferCallback(
buffers.map((buffer) => ({
buffer,
start: 0,
length: buffer.length,
sampleRate: sampleRate!,
isStart,
}))
);
bufferCallbackPromise.then(() => {
bufferCallbackPromise = null;
});
isStart = false;
}
};
// Each time we record an audio buffer, save it and then render the next window when we have
// enough samples
processor.addEventListener('audioprocess', (e) => {
for (let i = 0; i < Math.min(CHANNELS, e.inputBuffer.numberOfChannels); i += 1) {
const channelBuffer = e.inputBuffer.getChannelData(i);
channelBuffers[i].push(new Float32Array(channelBuffer));
}
// If a single channel input, pass an empty signal for the right channel
for (let i = Math.min(CHANNELS, e.inputBuffer.numberOfChannels); i < CHANNELS; i += 1) {
channelBuffers[i].push(new Float32Array(SPECTROGRAM_WINDOW_OVERLAP));
}
sampleRate = e.inputBuffer.sampleRate;
processChannelBuffers();
});
source.connect(processor);
processor.connect(audioCtx.destination);
// Return a function to stop rendering
return () => {
processor.disconnect(audioCtx.destination);
source.disconnect(processor);
};
}
async function setupSpectrogramFromAudioFile(
audioCtx: AudioContext,
arrayBuffer: ArrayBuffer,
bufferCallback: (bufferData: SpectrogramBufferData[]) => Promise<Float32Array[]>,
audioEndCallback: () => void
) {
const audioBuffer = await new Promise<AudioBuffer>((resolve, reject) =>
audioCtx.decodeAudioData(
arrayBuffer,
(buffer) => resolve(buffer),
(err) => reject(err)
)
);
let channelData: Float32Array[] = [];
for (let i = 0; i < audioBuffer.numberOfChannels; i += 1) {
channelData.push(new Float32Array(audioBuffer.getChannelData(i)));
}
const source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioCtx.destination);
let isStopping = false;
const playStartTime = performance.now();
let nextSample = 0;
const audioEventCallback = async () => {
const duration = (performance.now() - playStartTime) / 1000;
const bufferCallbackData = [];
// Calculate spectrogram up to current point
const totalSamples =
Math.ceil((duration * audioBuffer.sampleRate - nextSample) / SPECTROGRAM_WINDOW_SIZE) *
SPECTROGRAM_WINDOW_SIZE;
if (totalSamples > 0) {
for (let i = 0; i < audioBuffer.numberOfChannels; i += 1) {
bufferCallbackData.push({
buffer: channelData[i],
start: nextSample,
length: totalSamples,
sampleRate: audioBuffer.sampleRate,
isStart: nextSample === 0,
});
}
nextSample =
nextSample + totalSamples - SPECTROGRAM_WINDOW_SIZE + SPECTROGRAM_WINDOW_OVERLAP;
channelData = await bufferCallback(bufferCallbackData);
}
if (!isStopping && duration / audioBuffer.duration < 1.0) {
setTimeout(
audioEventCallback,
((SPECTROGRAM_WINDOW_OVERLAP / audioBuffer.sampleRate) * 1000) / 2
);
} else {
source.disconnect(audioCtx.destination);
audioEndCallback();
}
};
audioEventCallback();
// Play audio
audioCtx.resume();
source.start(0);
// Return a function to stop rendering
return () => {
isStopping = true;
source.disconnect(audioCtx.destination);
};
}
const spectrogramCallbacksPromise = startRenderingSpectrogram();
let globalAudioCtx: AudioContext | null = null;
(async () => {
const controlsContainer = document.querySelector('.controls');
const {
bufferCallback,
clearCallback,
updateRenderParameters,
} = await spectrogramCallbacksPromise;
if (controlsContainer !== null) {
let stopCallback: (() => void) | null = null;
const setPlayState = initialiseControlsUi(controlsContainer, {
stopCallback: () => {
if (stopCallback !== null) {
stopCallback();
}
stopCallback = null;
},
clearSpectrogramCallback: () => {
clearCallback();
},
renderParametersUpdateCallback: (parameters: Partial<RenderParameters>) => {
updateRenderParameters(parameters);
},
renderFromMicrophoneCallback: () => {
if (globalAudioCtx === null) {
globalAudioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
setupSpectrogramFromMicrophone(globalAudioCtx, bufferCallback).then(
(callback) => {
stopCallback = callback;
setPlayState('playing');
},
() => setPlayState('stopped')
);
},
renderFromFileCallback: (file: ArrayBuffer) => {
if (globalAudioCtx === null) {
globalAudioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
setupSpectrogramFromAudioFile(globalAudioCtx, file, bufferCallback, () =>
setPlayState('stopped')
).then(
(callback) => {
stopCallback = callback;
setPlayState('playing');
},
() => setPlayState('stopped')
);
},
});
}
})(); | the_stack |
namespace image {
export interface Font {
charWidth: number;
charHeight: number;
data: Buffer;
multiplier?: number;
}
//% whenUsed
export const font8: Font = {
charWidth: 6,
charHeight: 8,
data: hex`
2000000000000000 210000005e000000 2200000e000e0000 230028fe28fe2800 24004c92ff926400 250002651248a640
26006c92926ca000 270000000e000000 280000007c820000 29000000827c0000 2a00543810385400 2b0010107c101000
2c00000090700000 2d00101010101000 2e00000060600000 2f00006010080600 3000003c42423c00 310000447e400000
3200004462524c00 330000424a4e3200 34003028247e2000 3500004e4a4a3200 3600003c4a4a3000 3700000262120e00
380000344a4a3400 3900000c52523c00 3a0000006c6c0000 3b00000096760000 3c00102828444400 3d00282828282800
3e00444428281000 3f00000259090600 40003c425a560800 4100781412147800 42007e4a4a4a3400 4300003c42422400
4400007e42423c00 4500007e4a4a4200 4600007e0a0a0200 4700003c42523400 4800007e08087e00 490000427e420000
4a002040423e0200 4b00007e08146200 4c00007e40404000 4d007e0418047e00 4e00007e04087e00 4f003c4242423c00
5000007e12120c00 5100003c5262bc00 5200007e12126c00 530000244a522400 540002027e020200 5500003e40403e00
5600001e70701e00 57007e2018207e00 5800422418244200 5900060870080600 5a000062524a4600 5b00007e42420000
5c00000608106000 5d000042427e0000 5e00080402040800 5f00808080808000 6000000002040000 6100003048487800
6200007e48483000 6300003048484800 6400003048487e00 6500003068585000 660000107c120400 67000018a4a47800
6800007e08087000 690000487a400000 6a000040847d0000 6b00007e10284000 6c0000427e400000 6d00780830087000
6e00007808087000 6f00003048483000 700000fc24241800 710000182424fc00 7200007810081000 7300005058682800
740000083e482000 7500003840407800 7600001860601800 7700384030403800 7800004830304800 7900005ca0a07c00
7a00004868584800 7b00000836410000 7c000000fe000000 7d00004136080000 7e00000804080400 a000000000000000
a10000007a000000 a200003048fc4800 a30090fc92928400 a400542844285400 a5002a2c782c2a00 a6000000ee000000
a7000094aaaa5200 a800000200020000 a9003e414955413e aa0000242a2e0000 ab00102854284400 ac00001010107000
ad00001010101000 ae003e415d45413e af00000202020200 b000000814140800 b1008888be888800 b2000024322c0000
b30000222a140000 b400000004020000 b50000f840207800 b6000c1e7e027e00 b700000010000000 b800000080400000
b90000243e200000 ba0000242a240000 bb00442854281000 bc00025f70f84000 bd00021f90c8b000 be0011557af84000
bf000030484d2000 c000601916186000 c100601816196000 c200601a151a6000 c300601a151a6100 c400601914196000
c500601a151a6000 c6007c0a7e4a4200 c700001ea1611200 c800007c55564400 c900007c56554400 ca00007c56554600
cb00007c55544500 cc0000457e440000 cd0000447e450000 ce0000467d460000 cf0000457c450000 d000087e4a423c00
d100007e09127d00 d200003845463800 d300003846453800 d400003846453a00 d500003a45463900 d600003845443900
d700442810284400 d80000fc724e3f00 d900003c41423c00 da00003c42413c00 db00003c42413e00 dc00003c41403d00
dd00040872090400 de00007e24241800 df00007c025a2400 e0000030494a7800 e10000304a497800 e20000304a497a00
e3000032494a7900 e40000304a487a00 e50000304a4d7a00 e600304878685000 e7000018a4642400 e8000030695a5000
e90000306a595000 ea0000306a595200 eb0000306a585200 ec0000497a400000 ed0000487a410000 ee00004a79420000
ef00004a78420000 f00000304a4b3d00 f100007a090a7100 f2000030494a3000 f30000304a493000 f40000304a493200
f5000032494a3100 f60000304a483200 f700101054101000 f800007068583800 f900003841427800 fa00003842417800
fb00003842417a00 fc00003842407a00 fd0000b84241f800 fe0000ff24241800 ff00005ca1a07d00 0001601915196000
010100304a4a7a00 0201611a16196000 030100314a4a7900 04013c0a094abc00 050100182464bc00 0601003846452800
070100304a494800 0801003846452a00 090100304a494a00 0a01003844452800 0b010030484a4800 0c01003845462900
0d010030494a4900 0e01007c45463900 0f0100314a497e00 1001087e4a423c00 110130484c7e0400 1201007d55554500
130100326a5a5200 1401007d56564500 150100316a5a5100 1601007c55544400 170100306a585000 1801003f65a52100
1901001874ac2800 1a01007c55564500 1b010030695a5100 1c01003846553600 1d0100304a49f200 1e01003946563500
1f0100314a4af100 2001003844553400 21010018a4a57800 2201001ea1691a00 23010018a6a57800 2401007812117a00
25017e080a710200 2601047e147e0400 2701047e0c087000 28010002457e4500 29010002497a4100 2a0100457d450000
2b01004a7a420000 2c0100014a7a4900 2d0100014a7a4100 2e0100217fa10000 2f0100247da00000 300100447d440000
3101004878400000 32017e0022423e00 33013d0040847d00 34012040463d0600 350100800af90200 360100bf440a3100
370100bf48142000 3801007810284800 3901007c40424100 3a0100467d400000 3b01003fa0602000 3c0100a17f200000
3d01007c41424100 3e0100457e410000 3f01007e40484000 400100427e400800 4101107e48404000 420100527e480000
4301007c0a117c00 440100780a097000 450100bf42043f00 460100bc44043800 4701007c09127d00 480100790a097000
49010a0678087000 4a01003f02847f00 4b01003c04847800 4c01394545453900 4d0100324a4a3200 4e01394646463900
4f0100314a4a3100 50013a4544463900 5101324948320100 52013c427e4a4200 5301304830685000 5401007c16354800
5501007812091000 560100bf49093600 570100bc48040800 5801007d16354800 5901007912091000 5a01004856552400
5b0100505a692800 5c01004856552600 5d0100505a692a00 5e010012a5691200 5f010028ac741400 6001004855562500
61010050596a2900 62010101bf410100 630100049f641000 640104057e050400 650100083d4a2100 660102127e120200
670100183e582000 6801003a41423900 6901003a41427900 6a01003d41413d00 6b01003a42427a00 6c01003942423900
6d01003942427900 6e01003a45453a00 6f01003a45457a00 70013a41403a0100 71013a41407a0100 7201001f60a01f00
7301001c60a03c00 7401782211227800 7501384231423800 7601081261120800 770100b84241fa00 7801040970090400
79010064564d4400 7a0100486a594800 7b010064544d4400 7c010048685a4800 7d010064554e4500 7e010048695a4900
7f0100087c020400 8f01003452523c00 920100887e090200 a0013c42423c0806 a101003048483008 af01003e403e0806
b001003840781008 b501006a5a4a4e00 b601005878585800 d101003845463900 d2010030494a3100 e601003845563500
e7010030494af100 fa0100742a750000 fb0100304c4a7d00 fc0178147e554400 fd0130487a695000 fe010078744e3d00
ff0100706a593800 18020012a5691200 19020028ac741400 1a020101bf410100 1b0200049f641000 bb0200000c0a0000
bc0200000a060000 bd020000060a0000 c602000201020000 c702000102010000 c902000202020000 d802000102020100
d902000002000000 da02000205020000 db02000040800000 dc02000201020100 dd02020100020100 7403000002010000
7503000080400000 7a030000c0800000 7e03000096760000 8403000003000000 8503020003000200 8603037c12127c00
8703000010000000 880303007e4a4200 890303007e087e00 8a030300427e4200 8c03033c42423c00 8e0303000e700e00
8f03035c62625c00 900302003b400200 9103781412147800 92037e4a4a4a3400 9303007e02020200 9403605846586000
9503007e4a4a4200 96030062524a4600 9703007e08087e00 98033c4a4a4a3c00 990300427e420000 9a03007e08146200
9b03601806186000 9c037e0418047e00 9d03007e04087e00 9e0300424a4a4200 9f033c4242423c00 a003007e02027e00
a103007e12120c00 a30300665a424200 a40302027e020200 a503060870080600 a60318247e241800 a703422418244200
a8030e107e100e00 a9035c6202625c00 aa0300457c450000 ab03040970090400 ac030030484a7900 ad030030685a5100
ae0378100a09f000 af03003a41200000 b0033a4043403a00 b103003048487800 b20300fe25251a00 b3030c30c0300c00
b403344a4a4a3000 b503003068585000 b603021aa6a24200 b7033c080404f800 b803003c4a4a3c00 b903003840200000
ba03007820504800 bb03641212227c00 bc03fc2020103c00 bd03182040201800 be03112d2ba94100 bf03003048483000
c003087808780800 c103f82424241800 c2031824a4a44800 c303304848582800 c403000838482800 c503384040403800
c6031c20f8241800 c703c4281028c400 c8031c20fc201c00 c903304820483000 ca03000238422000 cb03384240423800
cc0330484a493000 cd03384042413800 ce03304822493000 d0033c52525c2000 d10310344a3c0800 d203067804020400
d303120a7c020400 d4030d7009040800 d5031824ff241800 d603384828483800 d70348302221d800 da031c2221a14200
db031824a4a44200 dc037e1212020200 dd0300fc24240400 de033e2010087c00 df030c0ac9281800 e003700c621c7000
e10301092516f800 e2039ea0bea07e00 e30398a0b8a07800 e4030c1214107e00 e503001028207800 e603be9088887000
e70348544e443800 e803245252524c00 e903285454544800 ea0364524c526400 eb03086458640800 ec03385454542200
ed03306848682400 ee03184a7e4a1800 ef031848ff0a0800 f003483020205800 f10378a4a4a49800 f203304848485000
f303006080847d00 f4033c4a4a4a3c00 f503003058584800 0004007c55564400 0104007c55544500 020401013f857900
0304007c06050400 04043c4a4a422400 050400244a522400 060400427e420000 070400457c450000 08042040423e0200
09047c027e483000 0a047e087e483000 0b0402027e0a7200 0c04007c102a4500 0d047c2112087c00 0e040c5152523d00
0f043f20e0203f00 1004781412147800 11047e4a4a4a3000 12047e4a4a4a3400 1304007e02020200 1404c07c427ec000
1504007e4a4a4200 160476087e087600 170424424a4a3400 1804007e08047e00 1904007d120a7d00 1a04007e08146200
1b04403c02027e00 1c047e0418047e00 1d04007e08087e00 1e043c4242423c00 1f047e0202027e00 2004007e12120c00
2104003c42422400 220402027e020200 23040e5050503e00 240418247e241800 2504422418244200 26043f2020bf6000
27040e1010107e00 28047e407e407e00 29043f203fa07f00 2a04027e48483000 2b047e4848307e00 2c04007e48483000
2d0424424a4a3c00 2e047e183c423c00 2f04006c12127e00 3004304848784000 3104003c4a4a3100 3204007868502000
3304007808080800 3404c0704878c000 3504306868500000 3604483078304800 3704004058683000 3804784020107800
3904794222127900 3a04007820304800 3b04403008087800 3c04781020107800 3d04781010107800 3e04304848483000
3f04780808087800 4004fc2424241800 4104304848485000 4204080878080800 43041ca0a0a07c00 44041824ff241800
4504004830304800 46043c2020bc6000 4704182020207800 4804784078407800 49043c203ca07c00 4a04087850502000
4b04785050207800 4c04007850502000 4d04485868300000 4e04783030483000 4f04502828780000 50040030696a5000
51040032686a5000 5204023f0a887000 530400780a090800 5404003068584800 5504005058682800 560400487a400000
5704004a78420000 5804004080847d00 5904700878502000 5a04781078502000 5b04047e14106000 5c04007822314800
5d04784122107800 5e0418a1a2a27900 5f043c20e0203c00 6204027f4a483000 6304087e58502000 70040e107e100e00
7104182078201800 72043c4a4a4a3c00 7304306858683000 7404001e70180c00 7504001860301000 9004007e02020300
9104007808080c00 9204087e0a0a0200 9304207828080800 96043b043f043be0 970424183c1824c0 9a04003f040a31c0
9b04003c101824c0 ae04060870080600 af040c10e0100c00 b004161870181600 b1042c30e0302c00 b20421120c1221c0
b3040024181824c0 ba047e0808087000 bb04007e08087000 d804003452523c00 d904002868583000 e20400457d450000
e304004a7a420000 e8043c4a4a4a3c00 e904003058583000 ee04003d41413d00 ef04003a42427a00 d005681020285000
d105484848784000 d205004830600000 d305080808780800 d405680808087800 d505000008780000 d605080818680800
d705087808087800 d805784050487800 d905000008180000 da0504040404fc00 db05484848483800 dc050e4848281800
dd05087848487800 de05582010487000 df05000004fc0000 e005004040487800 e105000878483800 e205487840281800
e305041c0404fc00 e405485848483800 e50504f820140800 e605485060685000 e705f40424241c00 e805080808087000
e905785058403800 ea05487808087800 f005087800087800 f105081800087800 f205081800081800 f305000010080000
f405100800100800 021e7c5455542800 031e007e48493000 0a1e007c45443800 0b1e003049487e00 1e1e007c15140400
1f1e001079140800 401e7e0419047e00 411e780832087000 561e007c15140800 571e00fc25241800 601e004854552400
611e0050586a2800 6a1e04047d040400 6b1e00083d482000 801e7c2112207c00 811e384132403800 821e7c2012217c00
831e384032413800 841e7c2110217c00 851e384230423800 f21e040972080400 f31e00b84142f800 a3207e0a7a120a00
a420a8fcaa828400 a720087e2a1c0800 ab200098a4a6bf02 ac20183c5a5a4200 af20627f22443800 9021103854101000
912108047e040800 9221101054381000 932110207e201000 9421103810103810 95212844fe442800
`,
}
// A unicode 12x12 pixel font based on https://github.com/adobe-fonts/source-han-sans
//% whenUsed jres
export const font12: Font = {
charWidth: 12,
charHeight: 12,
data: hex``
}
export function getFontForText(text: string) {
for (let i = 0; i < text.length; ++i) {
// this is quite approximate
if (text.charCodeAt(i) > 0x2000)
return image.font12
}
return image.font8
}
//% deprecated=1 hidden=1
export function doubledFont(f: Font): Font {
return scaledFont(f, 2)
}
export function scaledFont(f: Font, size: number): Font {
size |= 0
if (size < 2)
return f
return {
charWidth: f.charWidth * size,
charHeight: f.charHeight * size,
data: f.data,
multiplier: f.multiplier ? size * f.multiplier : size
}
}
//% whenUsed
export const font5: Font = {
charWidth: 6,
charHeight: 5,
// source https://github.com/lancaster-university/microbit-dal/blob/master/source/core/MicroBitFont.cpp
data: hex`
2000000000000000 2100001700000000 2200000300030000 23000a1f0a1f0a00 24000a17151d0a00 2500130904121900
26000a15150a1000 2700000300000000 2800000e11000000 290000110e000000 2a00000a040a0000 2b0000040e040000
2c00001008000000 2d00000404040000 2e00000800000000 2f00100804020100 30000e11110e0000 310000121f100000
3200191515120000 33000911150b0000 34000c0a091f0800 3500171515150900 3600081416150800 3700110905030100
38000a1515150a00 390002150d050200 3a00000a00000000 3b0000100a000000 3c0000040a110000 3d00000a0a0a0000
3e0000110a040000 3f00020115050200 40000e1115090e00 41001e05051e0000 42001f15150a0000 43000e1111110000
44001f11110e0000 45001f1515110000 46001f0505010000 47000e1111150c00 48001f04041f0000 4900111f11000000
4a000911110f0100 4b001f040a110000 4c001f1010100000 4d001f0204021f00 4e001f0204081f00 4f000e11110e0000
50001f0505020000 5100060919160000 52001f05050a1000 5300121515090000 540001011f010100 55000f10100f0000
5600070810080700 57001f0804081f00 58001b04041b0000 590001021c020100 5a00191513110000 5b00001f11110000
5c00010204081000 5d000011111f0000 5e00000201020000 5f00101010101000 6000000102000000 61000c12121e1000
62001f1414080000 63000c1212120000 64000814141f0000 65000e1515120000 6600041e05010000 67000215150f0000
68001f0404180000 6900001d00000000 6a000010100d0000 6b001f040a100000 6c00000f10100000 6d001e0204021e00
6e001e02021c0000 6f000c12120c0000 70001e0a0a040000 7100040a0a1e0000 72001c0202020000 730010140a020000
7400000f14141000 75000e10101e1000 7600060810080600 77001e1008101e00 7800120c0c120000 7900121408040200
7a00121a16120000 7b0000041f110000 7c00001f00000000 7d00111f04000000 7e00000404080800 d3000c1213130c00
f3000c12130d0000 04010e05051e1000 05010609191f0800 06010c1213131200 07010c1213130000 18010f0b1b190000
19010e151d1a0000 41011f1412100000 4201100f14120000 43011f0205081f00 44011e03031c0000 5a0110140b030200
5b0110140b030000 7901121a17130000 7a01121a17130000 7b01121b17120000 7c01121b17120000`,
}
}
namespace texteffects {
export interface TextEffectState {
xOffset: number;
yOffset: number;
}
}
interface Image {
//% helper=imagePrint
print(text: string, x: number, y: number, color?: number, font?: image.Font, offsets?: texteffects.TextEffectState[]): void;
//% helper=imagePrintCenter
printCenter(text: string, y: number, color?: number, font?: image.Font): void;
}
namespace helpers {
export function imagePrintCenter(img: Image, text: string, y: number, color?: number, font?: image.Font) {
if (!font) font = image.getFontForText(text)
let w = text.length * font.charWidth
let x = (img.width - w) / 2
imagePrint(img, text, x, y, color, font)
}
export function imagePrint(img: Image, text: string, x: number, y: number, color?: number, font?: image.Font, offsets?: texteffects.TextEffectState[]) {
x |= 0
y |= 0
if (!font)
font = image.getFontForText(text)
if (!color) color = 1
let x0 = x
let cp = 0
let mult = font.multiplier ? font.multiplier : 1
let dataW = Math.idiv(font.charWidth, mult)
let dataH = Math.idiv(font.charHeight, mult)
let byteHeight = (dataH + 7) >> 3
let charSize = byteHeight * dataW
let dataSize = 2 + charSize
let fontdata = font.data
let lastchar = Math.idiv(fontdata.length, dataSize) - 1
let imgBuf: Buffer
if (mult == 1) {
imgBuf = control.createBuffer(8 + charSize)
imgBuf[0] = 0x87
imgBuf[1] = 1
imgBuf[2] = dataW
imgBuf[4] = dataH
}
while (cp < text.length) {
let xOffset = 0, yOffset = 0;
if (offsets && cp < offsets.length) {
xOffset = offsets[cp].xOffset
yOffset = offsets[cp].yOffset
}
let ch = text.charCodeAt(cp++)
if (ch == 10) {
y += font.charHeight + 2
x = x0
}
if (ch < 32)
continue // skip control chars
let l = 0
let r = lastchar
let off = 0 // this should be a space (0x0020)
let guess = (ch - 32) * dataSize
if (fontdata.getNumber(NumberFormat.UInt16LE, guess) == ch)
off = guess
else {
while (l <= r) {
let m = l + ((r - l) >> 1);
let v = fontdata.getNumber(NumberFormat.UInt16LE, m * dataSize)
if (v == ch) {
off = m * dataSize
break
}
if (v < ch)
l = m + 1
else
r = m - 1
}
}
if (mult == 1) {
imgBuf.write(8, fontdata.slice(off + 2, charSize))
img.drawIcon(imgBuf, x + xOffset, y + yOffset, color)
x += font.charWidth
} else {
off += 2
for (let i = 0; i < dataW; ++i) {
let j = 0
let mask = 0x01
let c = fontdata[off++]
while (j < dataH) {
if (mask == 0x100) {
c = fontdata[off++]
mask = 0x01
}
let n = 0
while (c & mask) {
n++
mask <<= 1
}
if (n) {
img.fillRect(x + xOffset * mult, y + (j + yOffset) * mult, mult, mult * n, color)
j += n
} else {
mask <<= 1
j++
}
}
x += mult
}
}
}
}
} | the_stack |
import { animIn, animOut } from './popover.animations';
import { DomSanitizer } from '@angular/platform-browser';
import {
Component,
OnInit,
ViewChild,
Input,
ViewEncapsulation,
Host,
Optional,
AfterViewInit,
ElementRef,
OnDestroy
} from '@angular/core';
import { FivOverlay } from '../overlay/overlay.component';
import { Platform, IonContent } from '@ionic/angular';
import { fromEvent, Subject, merge, from } from 'rxjs';
import {
tap,
takeUntil,
map,
throttleTime,
filter,
flatMap
} from 'rxjs/operators';
import { NavigationStart, Router } from '@angular/router';
import {
PopoverPositioning,
PopoverPosition,
PopoverHorizontalAlign,
PopoverVerticalAlign,
PopoverArrowPositioning
} from './popover.types';
import { after } from '@fivethree/ngx-rxjs-animations';
@Component({
selector: 'fiv-popover',
templateUrl: './popover.component.html',
styleUrls: ['./popover.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class FivPopover implements OnInit, AfterViewInit, OnDestroy {
@ViewChild(FivOverlay, { static: true }) overlay: FivOverlay;
@ViewChild('animation', { static: false }) animationContainer: ElementRef;
@Input() width: number;
@Input() height: number;
@Input() arrow = false;
@Input() arrowWidth = 24;
@Input() arrowHeight: number = this.arrowWidth / 1.6;
@Input() arrowPosition: PopoverArrowPositioning = 'auto';
@Input() backdrop = true;
@Input() overlaysTarget = true;
@Input() closeOnNavigation = true;
@Input() scrollToTarget = false;
@Input() scrollSpeed = 100;
@Input() position: PopoverPositioning = 'auto';
@Input() classes: string[] = [];
@Input() viewportOnly = true;
_position: PopoverPosition;
hidden = false;
onDestroy$ = new Subject();
onClose$ = new Subject();
@Input() inDuration = 200;
@Input() outDuration = 80;
@Input() animationIn = (element: ElementRef) =>
animIn(element, this._position, this.inDuration);
@Input() animationOut = (element: ElementRef) =>
animOut(element, this.outDuration);
get styles() {
if (!this._position) {
return;
}
return this.dom.bypassSecurityTrustStyle(
` width: ${this.width ? this.width + 'px' : 'auto'};
height: ${this.height ? this.height + 'px' : 'auto'};
left: ${this.getContainerLeft()}px;
top: ${this.getContainerTop()}px;`
);
}
get triangle() {
const isHorizontal = ['left', 'right'].some(s => s === this.position);
if (isHorizontal) {
return `${this.arrowHeight},0 0,${this.arrowWidth / 2} ${
this.arrowHeight
},${this.arrowWidth}`;
}
return `0,${this.arrowHeight} ${this.arrowWidth / 2},0 ${this.arrowWidth},${
this.arrowHeight
}`;
}
get svgStyles() {
if (!this._position) {
return;
}
const isHorizontal = ['left', 'right'].some(s => s === this.position);
const rotate =
(this.position === 'auto' && this._position.vertical === 'bottom') ||
this.position === 'left';
return this.dom.bypassSecurityTrustStyle(
`height: ${isHorizontal ? this.arrowWidth : this.arrowHeight}px;
width: ${isHorizontal ? this.arrowHeight : this.arrowWidth}px;
top: ${this.getArrowTop()}px;
left: ${this.getArrowLeft()}px;
transform: rotateZ(${rotate ? 180 : 0}deg);`
);
}
get animationStyles() {
if (!this._position) {
return;
}
return this.dom.bypassSecurityTrustStyle(
`height: ${this.arrowHeight}px;
width: ${this.arrowWidth}px;
top: ${this.getArrowTop()}px;
left: ${this.getArrowLeft()}px;
transform: rotateZ(${this._position.vertical === 'bottom' ? 180 : 0}deg);`
);
}
constructor(
private platform: Platform,
@Host() @Optional() private content: IonContent,
private dom: DomSanitizer,
private router: Router
) {}
ngOnInit() {
this.router.events
.pipe(
filter<NavigationStart>(event => event instanceof NavigationStart),
filter(() => this.closeOnNavigation && this.overlay.open),
tap(() => this.close()),
takeUntil(this.onDestroy$)
)
.subscribe();
}
ngAfterViewInit(): void {}
ngOnDestroy() {
this.onDestroy$.next();
}
close() {
this.animationOut(this.animationContainer)
.pipe(
after(() => {
this.overlay.hide();
this.onClose$.next();
})
)
.subscribe();
}
private getPositionOfTarget(target: HTMLElement) {
const rect = target.getBoundingClientRect();
return this.calculcatePositioning(
rect.top,
rect.left,
rect.bottom,
rect.right,
rect.height,
rect.width
);
}
open(target: MouseEvent | ElementRef) {
let element;
if (target instanceof MouseEvent) {
element = target.target as HTMLElement;
} else if (target instanceof ElementRef) {
element = target.nativeElement as HTMLElement;
} else {
return;
}
this.openTarget(element);
}
openTarget(target: HTMLElement) {
const position = this.getPositionOfTarget(target);
this.openAtPosition(target, position);
this.watchResize(target);
this.watchScroll(target);
}
private watchResize(target: HTMLElement) {
if (!this.viewportOnly) {
return;
}
fromEvent(window, 'resize')
.pipe(
flatMap(() => this.filterInViewport(target)),
throttleTime(50),
map(() => this.getPositionOfTarget(target)),
tap(pos => (this._position = pos)),
takeUntil(this.onDestroy$)
)
.subscribe();
}
private watchScroll(target: HTMLElement) {
if (!this.viewportOnly) {
return;
}
if (this.content && !this.backdrop) {
this.content.scrollEvents = true;
merge(
fromEvent(window, 'mousewheel'),
fromEvent(window, 'touchmove'),
this.content.ionScroll
)
.pipe(
flatMap(() => this.filterInViewport(target)),
map(() => this.getPositionOfTarget(target)),
tap(pos => (this._position = pos)),
takeUntil(this.onDestroy$)
)
.subscribe();
}
}
private filterInViewport(target: HTMLElement) {
return from(this.inViewport(target.getBoundingClientRect())).pipe(
tap(inViewport =>
!inViewport ? (this.hidden = true) : (this.hidden = false)
),
filter(inViewPort => this.overlay.open && inViewPort)
);
}
private async openAtPosition(target: HTMLElement, position: PopoverPosition) {
await this.scrollToPosition(target, position);
this._position = position;
this.overlay.show();
}
private async scrollToPosition(
target: HTMLElement,
position: PopoverPosition
) {
if (this.content && this.scrollToTarget) {
const isInViewport = await this.inViewport(
target.getBoundingClientRect()
);
if (isInViewport) {
return;
}
await this.content.scrollToPoint(
position.left,
position.top,
this.scrollSpeed
);
}
}
async inViewport(position: DOMRect | ClientRect) {
const height = this.platform.height();
const width = this.platform.width();
return (
position.top <= height &&
position.bottom >= 0 &&
position.left < width &&
position.right > 0
);
}
private calculcatePositioning(
top: number,
left: number,
bottom: number,
right: number,
targetHeight: number,
targetWidth: number
): PopoverPosition {
// calculates the position of the popover without considering arrow and overlay offset
const width = this.platform.width();
const height = this.platform.height();
const _left =
this.position === 'right' ||
(width / 2 > left && this.position !== 'left');
const _right =
this.position === 'left' ||
(width / 2 <= left && this.position !== 'right');
const _top =
this.position === 'below' ||
(height / 2 > top && this.position !== 'above');
const _bottom =
this.position === 'above' ||
(height / 2 <= top && this.position !== 'below');
// transform origin
let horizontal: PopoverHorizontalAlign = 'left';
let vertical: PopoverVerticalAlign = 'top';
if (_left && _top) {
// top left
horizontal = 'left';
vertical = 'top';
} else if (_right && _bottom) {
// bottom right
left = right - this.width;
top = bottom - this.height;
horizontal = 'right';
vertical = 'bottom';
} else if (_right && _top) {
// top right
left = right - this.width;
horizontal = 'right';
vertical = 'top';
} else if (_left && _bottom) {
// bottom left
top = bottom - this.height;
horizontal = 'left';
vertical = 'bottom';
}
return {
top,
left,
bottom,
right,
targetHeight,
targetWidth,
horizontal,
vertical
};
}
private getArrowTop() {
const isVert = ['auto', 'below', 'above'].some(s => s === this.position);
if (isVert) {
return this._position.vertical === 'top'
? -1 * this.arrowHeight
: this.height;
}
if (this.arrowPosition === 'center') {
return this.height / 2 - this.arrowWidth / 2;
}
return this._position.vertical === 'top'
? this._position.targetHeight / 2 - this.arrowHeight / 2
: this.height - this.arrowHeight / 2 - this._position.targetHeight / 2;
}
private getArrowLeft() {
const isHorizontal = ['left', 'right'].some(s => s === this.position);
if (isHorizontal) {
return this._position.horizontal === 'left'
? -1 * this.arrowHeight
: this.width;
}
if (this.arrowPosition === 'center') {
return this.width / 2 - this.arrowHeight / 2;
}
return this._position.horizontal === 'left'
? this._position.targetWidth / 2 - this.arrowWidth / 2
: this.width - this.arrowWidth / 2 - this._position.targetWidth / 2;
}
private getContainerTop() {
const isVert = ['auto', 'below', 'above'].some(s => s === this.position);
const isTop = this._position.vertical === 'top';
let offset = 0;
if (this.arrow && isTop) {
offset -= this.getVerticalArrowOffset();
} else if (this.arrow && !isTop) {
offset += this.getVerticalArrowOffset();
}
if (!isVert) {
return this._position.top + offset;
}
if (!this.overlaysTarget && isTop) {
offset += this._position.targetHeight;
} else if (!this.overlaysTarget && !isTop) {
offset -= this._position.targetHeight;
}
if (this.arrow && isTop) {
offset += this.arrowHeight;
} else if (this.arrow && !isTop) {
offset -= this.arrowHeight;
}
return this._position.top + offset;
}
private getVerticalArrowOffset() {
let offset = 0;
const isHorizontal = ['left', 'right'].some(s => s === this.position);
if (this.arrowPosition === 'center' && isHorizontal) {
offset += this.height / 2 - this._position.targetHeight / 2;
}
return offset;
}
private getHorizontalArrowOffset() {
let offset = 0;
const isVertical = ['above', 'auto', 'below'].some(
s => s === this.position
);
if (this.arrowPosition === 'center' && isVertical) {
offset += this.width / 2 - this._position.targetWidth / 2;
}
return offset;
}
private getContainerLeft() {
const isHorizontal = ['left', 'right'].some(s => s === this.position);
const isLeft = this._position.horizontal === 'left';
let offset = 0;
if (this.arrow && isLeft) {
offset -= this.getHorizontalArrowOffset();
} else if (this.arrow && !isLeft) {
offset += this.getHorizontalArrowOffset();
}
if (!isHorizontal) {
return this._position.left + offset;
}
if (!this.overlaysTarget && isLeft) {
offset += this._position.targetWidth;
} else if (!this.overlaysTarget && !isLeft) {
offset -= this._position.targetWidth;
}
if (this.arrow && isLeft) {
offset += this.arrowHeight;
} else if (this.arrow && !isLeft) {
offset -= this.arrowHeight;
}
return this._position.left + offset;
}
} | the_stack |
import {
gl,
IModel,
IModelDrawOptions,
IModelInitializationOptions,
isSafari,
IUniform,
} from '@antv/g-webgpu-core';
import * as WebGPUConstants from '@webgpu/types/dist/constants';
import isNil from 'lodash/isNil';
import { WebGPUEngine } from '.';
import { extractUniforms } from '../utils/uniform';
import {
getColorStateDescriptors,
getCullMode,
getDepthStencilStateDescriptor,
primitiveMap,
} from './constants';
import WebGPUAttribute from './WebGPUAttribute';
import WebGPUBuffer from './WebGPUBuffer';
import WebGPUElements from './WebGPUElements';
import WebGPUFramebuffer from './WebGPUFramebuffer';
import WebGPUTexture2D from './WebGPUTexture2D';
// @ts-ignore
function concatenate(resultConstructor, ...arrays) {
let totalLength = 0;
for (const arr of arrays) {
totalLength += arr.length;
}
const result = new resultConstructor(totalLength);
let offset = 0;
for (const arr of arrays) {
result.set(arr, offset);
offset += arr.length;
}
return result;
}
export default class WebGPUModel implements IModel {
private pipelineLayout: GPUPipelineLayout;
private renderPipeline: GPURenderPipeline;
private uniformsBindGroupLayout: GPUBindGroupLayout;
private uniformBindGroup: GPUBindGroup;
private uniformBuffer: WebGPUBuffer;
private uniforms: {
[key: string]: IUniform;
} = {};
/**
* 用于后续渲染时动态更新
*/
private uniformGPUBufferLayout: Array<{
name: string;
offset: number;
}> = [];
/**
* vertex
*/
private attributeCache: {
[attributeName: string]: WebGPUAttribute;
} = {};
/**
* indices's buffer
*/
private indexBuffer: WebGPUBuffer;
private indexCount: number;
constructor(
private engine: WebGPUEngine,
private options: IModelInitializationOptions,
) {}
public async init() {
const {
vs,
fs,
attributes,
uniforms,
primitive,
count,
elements,
depth,
blend,
stencil,
cull,
instances,
} = this.options;
// build shaders first
const {
vertexStage,
fragmentStage,
} = await this.compilePipelineStageDescriptor(vs, fs, null);
if (uniforms) {
// create uniform bind groups & layout
this.buildUniformBindGroup(uniforms);
}
if (elements) {
this.indexBuffer = (elements as WebGPUElements).get() as WebGPUBuffer;
this.indexCount = (elements as WebGPUElements).indexCount;
}
// TODO: instanced array
const vertexState = {
vertexBuffers: Object.keys(attributes).map((attributeName, i) => {
const attribute = attributes[attributeName] as WebGPUAttribute;
const { arrayStride, stepMode, attributes: ats } = attribute.get();
this.attributeCache[attributeName] = attribute;
return {
arrayStride,
stepMode,
attributes: ats,
};
}),
};
const descriptor = {
sampleCount: this.engine.mainPassSampleCount,
primitiveTopology: primitiveMap[primitive || gl.TRIANGLES],
rasterizationState: {
...this.getDefaultRasterizationStateDescriptor(),
// TODO: support frontface
cullMode: getCullMode({ cull }),
},
depthStencilState: getDepthStencilStateDescriptor({
depth,
stencil,
}),
colorStates: getColorStateDescriptors(
{ blend },
this.engine.options.swapChainFormat!,
),
layout: this.pipelineLayout,
vertexStage,
fragmentStage,
vertexState,
};
// create pipeline
this.renderPipeline = this.engine.device.createRenderPipeline(descriptor);
}
public addUniforms(uniforms: { [key: string]: IUniform }): void {
this.uniforms = {
...this.uniforms,
...extractUniforms(uniforms),
};
}
public draw(options: IModelDrawOptions): void {
const renderPass = this.engine.getCurrentRenderPass();
const uniforms: {
[key: string]: IUniform;
} = {
...this.uniforms,
...extractUniforms(options.uniforms || {}),
};
const bindGroupBindings: GPUBindGroupEntry[] = [];
// TODO: uniform 发生修改
Object.keys(uniforms).forEach((uniformName: string) => {
const type = typeof uniforms[uniformName];
if (
type === 'boolean' ||
type === 'number' ||
Array.isArray(uniforms[uniformName]) ||
// @ts-ignore
uniforms[uniformName].BYTES_PER_ELEMENT
) {
const offset = this.uniformGPUBufferLayout.find(
({ name }) => name === uniformName,
)?.offset;
if (!isNil(offset)) {
this.uniformBuffer.subData({
data: uniforms[uniformName],
offset,
});
}
} else {
let offset = this.uniformGPUBufferLayout.find(
({ name }) => name === uniformName,
)?.offset;
if (!isNil(offset)) {
const textureOrFramebuffer = (uniforms[uniformName] as
| WebGPUTexture2D
| WebGPUFramebuffer).get();
const { texture, sampler } =
textureOrFramebuffer.color || textureOrFramebuffer;
if (sampler) {
bindGroupBindings.push({
binding: offset,
resource: sampler,
});
offset++;
}
bindGroupBindings.push({
binding: offset,
resource: texture.createView(),
});
}
}
});
if (this.uniformBuffer) {
bindGroupBindings[0] = {
binding: 0,
resource: {
buffer: this.uniformBuffer.get(), // 返回 GPUBuffer 原生对象
},
};
}
this.uniformBindGroup = this.engine.device.createBindGroup({
layout: this.uniformsBindGroupLayout,
entries: bindGroupBindings,
});
if (this.renderPipeline) {
renderPass.setPipeline(this.renderPipeline);
}
renderPass.setBindGroup(0, this.uniformBindGroup);
if (this.indexBuffer) {
renderPass.setIndexBuffer(
this.indexBuffer.get(),
WebGPUConstants.IndexFormat.Uint32,
0,
);
}
Object.keys(this.attributeCache).forEach((attributeName: string, i) => {
renderPass.setVertexBuffer(
0 + i,
this.attributeCache[attributeName].get().buffer,
0,
);
});
// renderPass.draw(verticesCount, instancesCount, verticesStart, 0);
if (this.indexBuffer) {
renderPass.drawIndexed(
this.indexCount,
this.options.instances || 1,
0,
0,
0,
);
} else {
renderPass.draw(
this.options.count || 0,
this.options.instances || 0,
0,
0,
);
}
}
public destroy(): void {
throw new Error('Method not implemented.');
}
private async compilePipelineStageDescriptor(
vertexCode: string,
fragmentCode: string,
defines: string | null,
): Promise<
Pick<GPURenderPipelineDescriptor, 'vertexStage' | 'fragmentStage'>
> {
const shaderVersion = '#version 450\n';
let vertexShader: Uint32Array | string = vertexCode;
let fragmentShader: Uint32Array | string = fragmentCode;
if (!this.engine.options.useWGSL) {
vertexShader = await this.compileShaderToSpirV(
vertexCode,
'vertex',
shaderVersion,
);
fragmentShader = await this.compileShaderToSpirV(
fragmentCode,
'fragment',
shaderVersion,
);
}
return this.createPipelineStageDescriptor(vertexShader, fragmentShader);
}
private compileShaderToSpirV(
source: string,
type: string,
shaderVersion: string,
): Promise<Uint32Array> {
return this.compileRawShaderToSpirV(shaderVersion + source, type);
}
private compileRawShaderToSpirV(
source: string,
type: string,
): Promise<Uint32Array> {
return this.engine.glslang.compileGLSL(source, type);
}
private createPipelineStageDescriptor(
vertexShader: Uint32Array | string,
fragmentShader: Uint32Array | string,
): Pick<GPURenderPipelineDescriptor, 'vertexStage' | 'fragmentStage'> {
return {
vertexStage: {
module: this.engine.device.createShaderModule({
code: vertexShader,
// @ts-ignore
isWHLSL: isSafari,
}),
entryPoint: 'main',
},
fragmentStage: {
module: this.engine.device.createShaderModule({
code: fragmentShader,
// @ts-ignore
isWHLSL: isSafari,
}),
entryPoint: 'main',
},
};
}
/**
* @see https://gpuweb.github.io/gpuweb/#rasterization-state
*/
private getDefaultRasterizationStateDescriptor(): GPURasterizationStateDescriptor {
return {
frontFace: WebGPUConstants.FrontFace.CCW,
cullMode: WebGPUConstants.CullMode.None,
depthBias: 0,
depthBiasSlopeScale: 0,
depthBiasClamp: 0,
};
}
private buildUniformBindGroup(uniforms: { [key: string]: IUniform }) {
let offset = 0;
// FIXME: 所有 uniform 合并成一个 buffer,固定使用 Float32Array 存储,确实会造成一些内存的浪费
const mergedUniformData = concatenate(
Float32Array,
...Object.keys(uniforms).map((uniformName) => {
if (uniforms[uniformName]) {
this.uniformGPUBufferLayout.push({
name: uniformName,
offset,
});
// @ts-ignore
offset += (uniforms[uniformName].length || 1) * 4;
return uniforms[uniformName];
} else {
// texture & framebuffer
return [];
}
}),
);
const entries: GPUBindGroupLayoutEntry[] = [];
let hasUniform = false;
if (mergedUniformData.length) {
hasUniform = true;
// TODO: 所有 uniform 绑定到 slot 0,通过解析 Shader 代码判定可见性
entries.push({
// TODO: 暂时都绑定到 slot 0
binding: 0,
visibility:
WebGPUConstants.ShaderStage.Fragment |
WebGPUConstants.ShaderStage.Vertex, // TODO: 暂时 VS 和 FS 都可见
type: WebGPUConstants.BindingType.UniformBuffer,
});
}
// 声明 texture & sampler
Object.keys(uniforms)
.filter((uniformName) => uniforms[uniformName] === null)
.forEach((uniformName, i) => {
this.uniformGPUBufferLayout.push({
name: uniformName,
offset: i * 2 + (hasUniform ? 1 : 0),
});
entries.push(
{
// Sampler
binding: i * 2 + (hasUniform ? 1 : 0),
visibility: WebGPUConstants.ShaderStage.Fragment,
type: WebGPUConstants.BindingType.Sampler,
},
{
// Texture view
binding: i * 2 + (hasUniform ? 1 : 0) + 1,
visibility: WebGPUConstants.ShaderStage.Fragment,
type: WebGPUConstants.BindingType.SampledTexture,
},
);
});
this.uniformsBindGroupLayout = this.engine.device.createBindGroupLayout({
// 最新 API 0.0.22 版本使用 entries。Chrome Canary 84.0.4110.0 已实现。
// 使用 bindings 会报 Warning: GPUBindGroupLayoutDescriptor.bindings is deprecated: renamed to entries
// @see https://github.com/antvis/GWebGPUEngine/issues/5
entries,
});
this.pipelineLayout = this.engine.device.createPipelineLayout({
bindGroupLayouts: [this.uniformsBindGroupLayout],
});
if (hasUniform) {
this.uniformBuffer = new WebGPUBuffer(this.engine, {
// TODO: 处理 Struct 和 boolean
// @ts-ignore
data:
mergedUniformData instanceof Array
? // @ts-ignore
new Float32Array(mergedUniformData)
: mergedUniformData,
usage:
WebGPUConstants.BufferUsage.Uniform |
WebGPUConstants.BufferUsage.CopyDst,
});
}
}
} | the_stack |
import { getBlockInstance, getRandStr, TPagedList, TPagedParams } from '@cromwell/core';
import { CList, TCList } from '@cromwell/core-frontend';
import { Autocomplete as MuiAutocomplete, Checkbox, Fade, Popper, Skeleton, TextField as MuiTextField, ClickAwayListener } from '@mui/material';
import { withStyles } from '@mui/styles';
import clsx from 'clsx';
import React, { useEffect } from 'react';
import { debounce } from 'throttle-debounce';
import { useForceUpdate } from '../../helpers/forceUpdate';
import styles from './Autocomplete.module.scss';
const TextField = withStyles({
root: {
paddingTop: '0',
paddingBottom: '0',
fontWeight: 300,
width: "100%"
},
})(MuiTextField);
class Autocomplete<TItemData extends { id: number | string }> extends React.Component<{
loader: (search: string, params?: TPagedParams<TItemData>) => Promise<(TPagedList<TItemData> | TItemData[]) | undefined>;
itemComponent?: (props: {
data: TItemData;
}) => JSX.Element;
getOptionLabel: (data: TItemData) => string;
getOptionValue?: (data: TItemData) => string;
onSelect?: (data: TItemData | TItemData[] | null) => void;
className?: string;
fullWidth?: boolean;
defaultValue?: TItemData | TItemData[];
label?: string;
variant?: 'standard' | 'outlined' | 'filled';
multiple?: boolean;
}, {
searchOpen?: boolean;
isLoading: boolean;
searchItems?: TItemData[];
searchText?: string;
pickedText?: string;
pickedItems?: string[];
defaultValue?: TItemData | TItemData[];
}> {
private searchAnchorRef = React.createRef<HTMLDivElement>();
private listId = 'AutocompleteList_' + getRandStr();
private listSkeleton = [];
private pickedData: Record<string, TItemData> = {};
constructor(props: any) {
super(props);
this.state = {
searchOpen: false,
isLoading: false,
}
for (let i = 0; i < 5; i++) {
this.listSkeleton.push(<Skeleton key={i} variant="text" height="20px" style={{ margin: '5px 20px' }} />)
}
}
private setDefaultValue = (defaultValue: TItemData | TItemData[]) => {
const { getOptionValue, getOptionLabel } = this.props;
if (Array.isArray(defaultValue)) {
const pickedItems: string[] = [];
for (const val of defaultValue) {
const pickedText = defaultValue ? (getOptionValue?.(val)
?? getOptionLabel(val)) : '';
this.pickedData[pickedText] = val;
pickedItems.push(pickedText);
}
Object.values(this.multiSelectionListeners).forEach(func => func(pickedItems));
this.setState({
searchText: '',
pickedText: '',
pickedItems,
defaultValue,
});
} else {
const pickedText = defaultValue ? (getOptionValue?.(defaultValue)
?? getOptionLabel(defaultValue)) : '';
this.setState({
searchText: pickedText,
pickedText: pickedText,
defaultValue,
});
}
}
componentDidMount() {
this.setDefaultValue(this.props.defaultValue);
}
componentDidUpdate() {
if (this.props.defaultValue && this.state.defaultValue !== this.props.defaultValue) {
this.setDefaultValue(this.props.defaultValue);
}
}
private fetchItems = async (searchText: string, params?: TPagedParams<TItemData>) => {
if (!this.state.isLoading)
this.setState({ isLoading: true });
let itemList;
try {
itemList = await this.props.loader(searchText, params);
if (Array.isArray(itemList)) {
this.setState({
searchItems: itemList
});
} else if (itemList.elements) {
this.setState({
searchItems: itemList.elements
});
}
} catch (e) {
console.error(e);
}
this.setState({ isLoading: false });
return itemList;
}
private searchRequest = debounce(500, async () => {
const list = getBlockInstance<TCList>(this.listId)?.getContentInstance();
if (!list) {
return;
}
list.clearState();
list.init();
});
private loadMore = (params: TPagedParams<TItemData>) => {
return this.fetchItems(this.state.searchText, params);
}
private handleSearchInput = (searchText: string) => {
this.setState({ searchText });
if (!this.state.isLoading)
this.setState({ isLoading: true });
if (!this.state.searchOpen) {
setTimeout(() => {
this.setState({ searchOpen: true });
}, 100);
}
this.searchRequest();
}
private handleSearchClose = () => {
this.setState({ searchOpen: false, searchText: this.state.pickedText });
}
private handleItemClick = (data: TItemData) => {
const pickedText = this.props.getOptionValue?.(data) ?? this.props.getOptionLabel(data);
this.pickedData[pickedText] = data;
const { multiple } = this.props;
this.setState(prev => {
if (multiple) {
let pickedItems = [...new Set([...(prev.pickedItems ?? [])])];
if (pickedItems.includes(pickedText)) {
pickedItems = pickedItems.filter(item => item !== pickedText);
} else {
pickedItems.push(pickedText);
}
this.props.onSelect?.(pickedItems.map(item => this.pickedData[item]));
Object.values(this.multiSelectionListeners).forEach(func => func(pickedItems));
return {
searchText: '',
pickedText: '',
pickedItems,
}
}
this.props.onSelect?.(data);
return {
searchText: pickedText,
pickedText: pickedText,
searchOpen: false,
}
});
}
private multiSelectionListeners: Record<string, ((pickedItems: string[]) => any)> = {};
public addMultiSelectListener = (id: string, listener: (pickedItems: string[]) => any) => {
this.multiSelectionListeners[id] = listener;
}
public removeMultiSelectListener = (id: string) => {
delete this.multiSelectionListeners[id];
}
private handleClear = () => {
this.setState({
searchText: '',
pickedText: '',
searchOpen: false,
});
this.props.onSelect?.(null);
}
render() {
const { searchOpen, pickedItems, pickedText } = this.state;
const { multiple } = this.props;
return (
<>
<MuiAutocomplete
className={this.props.className}
multiple={multiple}
options={pickedItems ?? []}
getOptionLabel={(option) => option as any}
value={multiple ? (pickedItems ?? []) : (pickedText ?? '')}
onChange={(event, newValue) => {
if (!newValue) {
this.handleClear();
}
if (multiple && newValue) {
const pickedItems = [...new Set([...(newValue as any)])];
this.props.onSelect?.(pickedItems.map(item => this.pickedData[item]));
Object.values(this.multiSelectionListeners).forEach(func => func(pickedItems));
this.setState({
pickedItems,
});
}
}}
PopperComponent={() => <></>}
renderInput={(params) => (
<TextField
{...params}
value={this.state.searchText ?? ''}
onChange={(event) => this.handleSearchInput(event.currentTarget.value)}
onFocus={() => this.handleSearchInput(this.state.searchText)}
onBlur={() => !multiple && this.handleSearchClose()}
label={this.props.label ?? "Search..."}
fullWidth={this.props.fullWidth}
ref={this.searchAnchorRef}
size="small"
variant={this.props.variant ?? 'standard'}
/>
)}
/>
<Popper open={searchOpen} anchorEl={this.searchAnchorRef.current}
style={{ zIndex: 9999 }}
transition>
{({ TransitionProps }) => (
<Fade {...TransitionProps} timeout={350}>
<div className={styles.searchContent}>
<ClickAwayListener onClickAway={this.handleSearchClose}>
{/* {isLoading && (
<LoadBox size={100} />
)}
{!isLoading && searchItems.length === 0 && (
<p className={styles.notFoundText}>No items found</p>
)}
{!isLoading && ( */}
<CList<TItemData, ListItemProps<TItemData>>
useAutoLoading
className={styles.list}
id={this.listId}
loader={this.loadMore}
elements={{ preloader: <div className={styles.listPreloader}>{this.listSkeleton}</div> }}
ListItem={ListItem}
listItemProps={{
handleItemClick: this.handleItemClick,
getOptionLabel: this.props.getOptionLabel,
getOptionValue: this.props.getOptionValue,
pickedItems: this.state?.pickedItems,
multiple,
ItemComponent: this.props.itemComponent,
addMultiSelectListener: this.addMultiSelectListener,
removeMultiSelectListener: this.removeMultiSelectListener,
}}
/>
{/* )} */}
</ClickAwayListener>
</div>
</Fade>
)}
</Popper>
</>
);
}
}
export default Autocomplete;
type ListItemProps<TItemData extends { id: number | string }> = {
handleItemClick: (data: TItemData) => any;
getOptionLabel: (data: TItemData) => string;
getOptionValue?: (data: TItemData) => string;
pickedItems?: string[];
multiple?: boolean;
ItemComponent?: (props: {
data: TItemData;
}) => JSX.Element;
addMultiSelectListener: (id: string, listener: (pickedItems: string[]) => any) => any;
removeMultiSelectListener: (id: string) => any;
}
type TListItem = <TItemData extends { id: number | string }>(props: {
data?: TItemData;
listItemProps: ListItemProps<TItemData>;
}) => JSX.Element;
const ListItem: TListItem = (props) => {
const { pickedItems, getOptionValue, getOptionLabel, handleItemClick, multiple,
ItemComponent, addMultiSelectListener, removeMultiSelectListener } = props.listItemProps;
const pickedText = getOptionValue?.(props.data) ?? getOptionLabel(props.data);
const picked = pickedItems?.includes(pickedText);
const update = useForceUpdate();
useEffect(() => {
if (props.data?.id) {
addMultiSelectListener(props.data.id + '', (picked) => {
props.listItemProps.pickedItems = picked;
update();
});
}
return () => {
if (props.data?.id) {
removeMultiSelectListener(props.data.id + '');
}
}
}, [])
return (
<div onClick={() => handleItemClick(props.data)} className={styles.itemWrapper}>
{multiple && (
<Checkbox checked={picked} />
)}
{ItemComponent ? (
<ItemComponent data={props.data} />
) : (
<p className={clsx(styles.itemText)}>{getOptionLabel(props.data)}</p>
)}
</div>
)
} | the_stack |
import { Component, OnInit, ViewChild, ElementRef, NgZone, OnDestroy } from "@angular/core";
import { CanvasScaleplateModel, LineModel, lineType } from "./model";
import { PanelExtendService } from "../panel-extend.service";
import { PanelInfoModel, TransformMatrixModel } from "../model";
import { Subscription, BehaviorSubject, fromEvent } from "rxjs";
import { PanelScaleplateService } from "./panel-scaleplate.service";
import { DraggablePort } from "@ng-public/directive/draggable/draggable.interface";
import { debounceTime, tap } from "rxjs/operators";
@Component({
selector: "app-panel-scaleplate",
templateUrl: "./panel-scaleplate.component.html",
styleUrls: ["./panel-scaleplate.component.scss"],
})
export class PanelScaleplateComponent implements OnInit, OnDestroy {
// 最外层的容器宿主
@ViewChild("mbRulerEl", { static: true })
public mbRulerEl: ElementRef;
@ViewChild("hCanvasEl", { static: true })
public hCanvasEl: ElementRef;
@ViewChild("vCanvasEl", { static: true })
public vCanvasEl: ElementRef;
// 检测窗口size变化的事件
private windowSizeChange$: Subscription;
// 监听鼠标移动事件
private mouseMove$: Subscription;
// 订阅视图移动变化的观察者
private panelTransformMatricChangeRX$: Subscription;
// 订阅通知回到原点的观察者
private originBackRX$: Subscription;
public get hRuler(): HTMLCanvasElement {
return this.hCanvasEl.nativeElement;
}
public get vRuler(): HTMLCanvasElement {
return this.vCanvasEl.nativeElement;
}
public get transformMatrixModel(): TransformMatrixModel {
return this.panelExtendService.transformMatrixModel;
}
public get canvasScaleplateModel(): CanvasScaleplateModel {
return this.panelScaleplateService.canvasScaleplateModel;
}
public get temporaryLine$(): BehaviorSubject<LineModel> {
return this.canvasScaleplateModel.temporaryLine$;
}
public get hLineList$(): BehaviorSubject<Array<LineModel>> {
return this.canvasScaleplateModel.hLineList$;
}
public get vLineList$(): BehaviorSubject<Array<LineModel>> {
return this.canvasScaleplateModel.vLineList$;
}
public get isOpenMoveLine(): boolean {
return this.panelScaleplateService.isOpenMoveLine$.value;
}
public get isShowLine(): boolean {
return this.panelScaleplateService.isShowLine$.value;
}
// 主视图模型属性
public get panelInfoModel(): PanelInfoModel {
return this.panelExtendService.panelInfoModel;
}
constructor(
private readonly panelExtendService: PanelExtendService,
private readonly panelScaleplateService: PanelScaleplateService,
private readonly zone: NgZone
) {
this.windowSizeChange$ = fromEvent(window, "resize")
.pipe(
tap(() => {
this.panelExtendService.launchRecordPanelInfoRect$.next();
})
)
.subscribe(() => {
this.zone.run(() => {
this.calcCanvasRulerSize();
this.createHRulerRect();
this.createVRulerRect();
this.calcAllHVLineDrag();
});
});
this.panelTransformMatricChangeRX$ = this.panelExtendService.transformMatrixModel.valueChange$
.pipe(
debounceTime(1),
tap(() => {
this.panelExtendService.launchRecordPanelInfoRect$.next();
})
)
.subscribe(() => {
this.createHRulerRect();
this.createVRulerRect();
// 如果有辅助线则根据面板偏移量移动
this.calcAllHVLineDrag();
});
this.originBackRX$ = this.panelScaleplateService.launchOrigin$
.pipe(
tap(() => {
this.transformMatrixModel.reset();
this.panelExtendService.trackModel.reset();
})
)
.subscribe(() => {
this.panelExtendService.launchRecordPanelInfoRect$.next();
this.calcCanvasRulerSize();
this.createHRulerRect();
this.createVRulerRect();
this.calcAllHVLineDrag();
});
}
ngAfterViewInit() {
setTimeout(() => {
this.panelInfoModel.recordImmobilizationData();
this.createHRulerRect();
this.createVRulerRect();
});
}
ngOnInit() {
this.calcCanvasRulerSize();
}
ngOnDestroy() {
if (this.windowSizeChange$) this.windowSizeChange$.unsubscribe();
if (this.panelTransformMatricChangeRX$) this.panelTransformMatricChangeRX$.unsubscribe();
if (this.mouseMove$) this.mouseMove$.unsubscribe();
if (this.originBackRX$) this.originBackRX$.unsubscribe();
}
/**
* 初始化标尺的宽度和高度,同时根据窗口大小的改变重新计算
*/
public calcCanvasRulerSize(): void {
if (this.mbRulerEl && this.mbRulerEl.nativeElement) {
const rect = this.mbRulerEl.nativeElement.getBoundingClientRect();
this.canvasScaleplateModel.width = rect.width - 16;
this.canvasScaleplateModel.height = rect.height - 16;
}
}
/**
* 绘制线条
*/
public drawLine(
rule: CanvasRenderingContext2D,
move: { moveStart: number; moveEnd: number },
line: { lineStart: number; lineEnd: number },
color: string
): void {
rule.beginPath();
rule.strokeStyle = color;
rule.moveTo(move.moveStart, move.moveEnd);
rule.lineTo(line.lineStart, line.lineEnd);
rule.stroke();
}
/**
* 创建横向的标尺
*/
public createHRulerRect(): void {
const h = this.hRuler.getContext("2d");
const panelLeftCalc = this.panelInfoModel.left - 216;
this.hRuler.width = this.canvasScaleplateModel.width;
h.transform(1, 0, 0, 1, this.transformMatrixModel.translateX, 0);
h.fillStyle = "#f9fafb";
h.fillRect(-this.transformMatrixModel.translateX, 0, this.canvasScaleplateModel.width, 16);
// 创建新的矩阵
h.setTransform(1, 0, 0, 1, panelLeftCalc, 0);
h.lineWidth = 2;
const handleDrawLine = (i: number) => {
this.drawLine(
h,
{ moveStart: i * 10, moveEnd: i % 10 == 0 ? 0 : 10 },
{ lineStart: i * 10, lineEnd: 16 },
"#ccc"
);
this.drawLine(
h,
{ moveStart: i * 10 + 1, moveEnd: i % 10 == 0 ? 0 : 10 },
{ lineStart: i * 10 + 1, lineEnd: 16 },
"#f9fafb"
);
if (i % 10 == 0) {
h.font = "normal normal bold 12px";
h.fillStyle = "#2b3c4d";
h.fillText(i * 10 + "", i * 10 + 4, 10);
}
};
for (let i: number = 0; i < (this.canvasScaleplateModel.width - panelLeftCalc) / 10; i++) {
handleDrawLine(i);
}
for (let i: number = 0; i > -panelLeftCalc / 10; i--) {
handleDrawLine(i);
}
}
/**
* 创建纵向的标尺
*/
public createVRulerRect(): void {
const v = this.vRuler.getContext("2d");
const textV = this.vRuler.getContext("2d");
const panelTopCalc = this.panelInfoModel.top - 66;
this.vRuler.height = this.canvasScaleplateModel.height;
v.transform(1, 0, 0, 1, 0, this.transformMatrixModel.translateY);
v.fillStyle = "#f9fafb";
v.fillRect(0, -this.transformMatrixModel.translateY, 16, this.canvasScaleplateModel.height);
// 创建新的矩阵
v.setTransform(1, 0, 0, 1, 0, panelTopCalc);
v.lineWidth = 2;
const handleDrawLine = (i: number) => {
this.drawLine(
v,
{ moveStart: i % 10 == 0 ? 0 : 10, moveEnd: i * 10 },
{ lineStart: 16, lineEnd: i * 10 },
"#ccc"
);
this.drawLine(
v,
{ moveStart: i % 10 == 0 ? 0 : 10, moveEnd: i * 10 - 1 },
{ lineStart: 16, lineEnd: i * 10 - 1 },
"#f9fafb"
);
if (i % 10 == 0) {
textV.save();
textV.textAlign = "center";
textV.textBaseline = "middle";
textV.translate(6, i * 10 - 14);
textV.rotate((-90 * Math.PI) / 180);
textV.font = "normal normal bold 12px";
textV.fillStyle = "#2b3c4d";
textV.fillText(i * 10 + "", 0, 0);
textV.restore();
}
};
for (let i: number = 0; i < (this.canvasScaleplateModel.height - panelTopCalc) / 10; i++) {
handleDrawLine(i);
}
for (let i: number = 0; i > -panelTopCalc / 10; i--) {
handleDrawLine(i);
}
}
/**
* 接受canvas面板鼠标移入
*/
public acceptCanvasMouseEnter(type: lineType): void {
if (this.mouseMove$) this.mouseMove$.unsubscribe();
const temLine = new LineModel(type);
this.mouseMove$ = fromEvent(type == "h" ? this.hRuler : this.vRuler, "mousemove").subscribe(
(move: MouseEvent) => {
this.zone.run(() => {
if (type == "h") {
temLine.setInCanvasNum(move.pageX - 216 - (this.panelInfoModel.left - 216));
temLine.setInPanelNum(move.pageX - 216);
} else if (type == "v") {
temLine.setInCanvasNum(move.pageY - 66 - (this.panelInfoModel.top - 66));
temLine.setInPanelNum(move.pageY - 66);
}
this.canvasScaleplateModel.temporaryLine$.next(temLine);
});
}
);
}
/**
* 接受canvas面板鼠移出
*/
public acceptCanvasMouseOut(): void {
if (this.mouseMove$) this.mouseMove$.unsubscribe();
this.temporaryLine$.next(null);
}
/**
* 创建辅助线
*/
public createLineList(type: lineType): void {
const temPanelNum = this.temporaryLine$.value;
const line = new LineModel(type);
line.setInPanelNum(temPanelNum.inPanelNum);
line.setInCanvasNum(temPanelNum.inCanvasNum);
this.panelScaleplateService[type == "h" ? "addHLine" : "addVLine"](line);
this.panelScaleplateService.isShowLine$.next(true);
}
/**
* 计算面板移动带来的偏移量而改变所有绘制的辅助线
*/
public calcAllHVLineDrag(): void {
const vLine = this.vLineList$.value;
const hLine = this.hLineList$.value;
if (Array.isArray(vLine)) {
vLine.forEach(v => {
v.setInPanelNum(v.inCanvasNum + this.panelInfoModel.top - 66);
});
}
if (Array.isArray(hLine)) {
hLine.forEach(h => {
h.setInPanelNum(h.inCanvasNum + this.panelInfoModel.left - 216);
});
}
}
/**
* 接收已绘制好的线条的移入事件
*/
public acceptLineEnter(line: LineModel): void {
line.isAllowDel = true;
this.temporaryLine$.next(null);
}
/**
* 接收已绘制好的线条的移出事件
*/
public acceptLineOut(line: LineModel): void {
line.isAllowDel = false;
this.temporaryLine$.next(null);
}
/**
* 接收拖拽已绘制好的线条
*/
public acceptDraggleLine(drag: DraggablePort, line: LineModel): void {
if (drag) {
line.setInCanvasNum(line.inCanvasNum + drag[line.type == "h" ? "left" : "top"]);
line.setInPanelNum(line.inPanelNum + drag[line.type == "h" ? "left" : "top"]);
}
}
/**
* 删除横向和纵向的已绘制好的线条
*/
public acceptDelLine(index: number, type: lineType): void {
this.panelScaleplateService[type == "h" ? "delHLine" : "delVLine"](index);
}
/**
* 回到原点
*/
public backOrigin(): void {
this.panelScaleplateService.launchOrigin$.next();
}
/**
* 控制辅助线是显示还是隐藏
*/
public controlLineShowOrHide(): void {
this.panelScaleplateService.controlLineShowOrHide();
}
/**
* 清空所有辅助线
*/
public emptyAllLine(): void {
this.panelScaleplateService.emptyAllLine();
}
} | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* Pre-provisioned and readily available Event Hubs Cluster count per region.
*/
export interface AvailableCluster {
/**
* Location fo the Available Cluster
*/
location?: string;
}
/**
* The response of the List Available Clusters operation.
*/
export interface AvailableClustersList {
/**
* The count of readily available and pre-provisioned Event Hubs Clusters per region.
*/
value?: AvailableCluster[];
}
/**
* Error response indicates Event Hub service is not able to process the incoming request. The
* reason is provided in the error message.
*/
export interface ErrorResponse {
/**
* Error code.
*/
code?: string;
/**
* Error message indicating why the operation failed.
*/
message?: string;
}
/**
* SKU parameters particular to a cluster instance.
*/
export interface ClusterSku {
/**
* The quantity of Event Hubs Cluster Capacity Units contained in this cluster.
*/
capacity?: number;
}
/**
* The resource definition.
*/
export interface Resource extends BaseResource {
/**
* Resource ID.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Resource name.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Resource type.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* Definition of resource.
*/
export interface TrackedResource extends Resource {
/**
* Resource location.
*/
location?: string;
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
}
/**
* Single Event Hubs Cluster resource in List or Get operations.
*/
export interface Cluster extends TrackedResource {
/**
* Properties of the cluster SKU.
*/
sku?: ClusterSku;
/**
* The UTC time when the Event Hubs Cluster was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly createdAt?: string;
/**
* The UTC time when the Event Hubs Cluster was last updated.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly updatedAt?: string;
/**
* The metric ID of the cluster resource. Provided by the service and not modifiable by the user.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly metricId?: string;
/**
* Status of the Cluster resource
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly status?: string;
}
/**
* The full ARM ID of an Event Hubs Namespace
*/
export interface EHNamespaceIdContainer {
/**
* id parameter
*/
id?: string;
}
/**
* The response of the List Namespace IDs operation
*/
export interface EHNamespaceIdListResult {
/**
* Result of the List Namespace IDs operation
*/
value?: EHNamespaceIdContainer[];
}
/**
* SKU parameters supplied to the create namespace operation
*/
export interface Sku {
/**
* Name of this SKU. Possible values include: 'Basic', 'Standard'
*/
name: SkuName;
/**
* The billing tier of this particular SKU. Possible values include: 'Basic', 'Standard'
*/
tier?: SkuTier;
/**
* The Event Hubs throughput units, value should be 0 to 20 throughput units.
*/
capacity?: number;
}
/**
* Properties to configure Identity for Bring your Own Keys
*/
export interface Identity {
/**
* ObjectId from the KeyVault
*/
principalId?: string;
/**
* TenantId from the KeyVault
*/
tenantId?: string;
/**
* Enumerates the possible value Identity type, which currently supports only 'SystemAssigned'.
* Possible values include: 'SystemAssigned'. Default value: 'SystemAssigned'.
*/
type?: IdentityType;
}
/**
* Properties to configure keyVault Properties
*/
export interface KeyVaultProperties {
/**
* Name of the Key from KeyVault
*/
keyName?: string;
/**
* Uri of KeyVault
*/
keyVaultUri?: string;
/**
* Key Version
*/
keyVersion?: string;
}
/**
* Properties to configure Encryption
*/
export interface Encryption {
/**
* Properties of KeyVault
*/
keyVaultProperties?: KeyVaultProperties[];
/**
* Enumerates the possible value of keySource for Encryption. Possible values include:
* 'Microsoft.KeyVault'. Default value: 'Microsoft.KeyVault'.
*/
keySource?: KeySource;
}
/**
* Single Namespace item in List or Get Operation
*/
export interface EHNamespace extends TrackedResource {
/**
* Properties of sku resource
*/
sku?: Sku;
/**
* Properties of BYOK Identity description
*/
identity?: Identity;
/**
* Provisioning state of the Namespace.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* The time the Namespace was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly createdAt?: Date;
/**
* The time the Namespace was updated.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly updatedAt?: Date;
/**
* Endpoint you can use to perform Service Bus operations.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly serviceBusEndpoint?: string;
/**
* Cluster ARM ID of the Namespace.
*/
clusterArmId?: string;
/**
* Identifier for Azure Insights metrics.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly metricId?: string;
/**
* Value that indicates whether AutoInflate is enabled for eventhub namespace.
*/
isAutoInflateEnabled?: boolean;
/**
* Upper limit of throughput units when AutoInflate is enabled, value should be within 0 to 20
* throughput units. ( '0' if AutoInflateEnabled = true)
*/
maximumThroughputUnits?: number;
/**
* Value that indicates whether Kafka is enabled for eventhub namespace.
*/
kafkaEnabled?: boolean;
/**
* Enabling this property creates a Standard Event Hubs Namespace in regions supported
* availability zones.
*/
zoneRedundant?: boolean;
/**
* Properties of BYOK Encryption description
*/
encryption?: Encryption;
}
/**
* PrivateEndpoint information.
*/
export interface PrivateEndpoint {
/**
* The ARM identifier for Private Endpoint.
*/
id?: string;
}
/**
* ConnectionState information.
*/
export interface ConnectionState {
/**
* Status of the connection. Possible values include: 'Pending', 'Approved', 'Rejected',
* 'Disconnected'
*/
status?: PrivateLinkConnectionStatus;
/**
* Description of the connection state.
*/
description?: string;
}
/**
* Properties of the PrivateEndpointConnection.
*/
export interface PrivateEndpointConnection extends Resource {
/**
* The Private Endpoint resource for this Connection.
*/
privateEndpoint?: PrivateEndpoint;
/**
* Details about the state of the connection.
*/
privateLinkServiceConnectionState?: ConnectionState;
/**
* Provisioning state of the Private Endpoint Connection. Possible values include: 'Creating',
* 'Updating', 'Deleting', 'Succeeded', 'Canceled', 'Failed'
*/
provisioningState?: EndPointProvisioningState;
}
/**
* Information of the private link resource.
*/
export interface PrivateLinkResource {
/**
* The private link resource group id.
*/
groupId?: string;
/**
* The private link resource required member names.
*/
requiredMembers?: string[];
/**
* The private link resource Private link DNS zone name.
*/
requiredZoneNames?: string[];
/**
* Fully qualified identifier of the resource.
*/
id?: string;
/**
* Name of the resource
*/
name?: string;
/**
* Type of the resource
*/
type?: string;
}
/**
* Result of the List private link resources operation.
*/
export interface PrivateLinkResourcesListResult {
/**
* A collection of private link resources
*/
value?: PrivateLinkResource[];
/**
* A link for the next page of private link resources.
*/
nextLink?: string;
}
/**
* Single item in a List or Get AuthorizationRule operation
*/
export interface AuthorizationRule extends Resource {
/**
* The rights associated with the rule.
*/
rights: AccessRights[];
}
/**
* Namespace/EventHub Connection String
*/
export interface AccessKeys {
/**
* Primary connection string of the created namespace AuthorizationRule.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly primaryConnectionString?: string;
/**
* Secondary connection string of the created namespace AuthorizationRule.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly secondaryConnectionString?: string;
/**
* Primary connection string of the alias if GEO DR is enabled
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly aliasPrimaryConnectionString?: string;
/**
* Secondary connection string of the alias if GEO DR is enabled
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly aliasSecondaryConnectionString?: string;
/**
* A base64-encoded 256-bit primary key for signing and validating the SAS token.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly primaryKey?: string;
/**
* A base64-encoded 256-bit primary key for signing and validating the SAS token.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly secondaryKey?: string;
/**
* A string that describes the AuthorizationRule.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly keyName?: string;
}
/**
* Parameters supplied to the Regenerate Authorization Rule operation, specifies which key needs to
* be reset.
*/
export interface RegenerateAccessKeyParameters {
/**
* The access key to regenerate. Possible values include: 'PrimaryKey', 'SecondaryKey'
*/
keyType: KeyType;
/**
* Optional, if the key value provided, is set for KeyType or autogenerated Key value set for
* keyType
*/
key?: string;
}
/**
* Parameter supplied to check Namespace name availability operation
*/
export interface CheckNameAvailabilityParameter {
/**
* Name to check the namespace name availability
*/
name: string;
}
/**
* The Result of the CheckNameAvailability operation
*/
export interface CheckNameAvailabilityResult {
/**
* The detailed info regarding the reason associated with the Namespace.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly message?: string;
/**
* Value indicating Namespace is availability, true if the Namespace is available; otherwise,
* false.
*/
nameAvailable?: boolean;
/**
* The reason for unavailability of a Namespace. Possible values include: 'None', 'InvalidName',
* 'SubscriptionIsDisabled', 'NameInUse', 'NameInLockdown',
* 'TooManyNamespaceInCurrentSubscription'
*/
reason?: UnavailableReason;
}
/**
* Single item in List or Get Consumer group operation
*/
export interface ConsumerGroup extends Resource {
/**
* Exact time the message was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly createdAt?: Date;
/**
* The exact time the message was updated.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly updatedAt?: Date;
/**
* User Metadata is a placeholder to store user-defined string data with maximum length 1024.
* e.g. it can be used to store descriptive data, such as list of teams and their contact
* information also user-defined configuration settings can be stored.
*/
userMetadata?: string;
}
/**
* The object that represents the operation.
*/
export interface OperationDisplay {
/**
* Service provider: Microsoft.EventHub
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provider?: string;
/**
* Resource on which the operation is performed: Invoice, etc.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resource?: string;
/**
* Operation type: Read, write, delete, etc.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly operation?: string;
}
/**
* A Event Hub REST API operation
*/
export interface Operation {
/**
* Operation name: {provider}/{resource}/{operation}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The object that represents the operation.
*/
display?: OperationDisplay;
}
/**
* Capture storage details for capture description
*/
export interface Destination {
/**
* Name for capture destination
*/
name?: string;
/**
* Resource id of the storage account to be used to create the blobs
*/
storageAccountResourceId?: string;
/**
* Blob container Name
*/
blobContainer?: string;
/**
* Blob naming convention for archive, e.g.
* {Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}. Here all
* the parameters (Namespace,EventHub .. etc) are mandatory irrespective of order
*/
archiveNameFormat?: string;
}
/**
* Properties to configure capture description for eventhub
*/
export interface CaptureDescription {
/**
* A value that indicates whether capture description is enabled.
*/
enabled?: boolean;
/**
* Enumerates the possible values for the encoding format of capture description. Note:
* 'AvroDeflate' will be deprecated in New API Version. Possible values include: 'Avro',
* 'AvroDeflate'
*/
encoding?: EncodingCaptureDescription;
/**
* The time window allows you to set the frequency with which the capture to Azure Blobs will
* happen, value should between 60 to 900 seconds
*/
intervalInSeconds?: number;
/**
* The size window defines the amount of data built up in your Event Hub before an capture
* operation, value should be between 10485760 to 524288000 bytes
*/
sizeLimitInBytes?: number;
/**
* Properties of Destination where capture will be stored. (Storage Account, Blob Names)
*/
destination?: Destination;
/**
* A value that indicates whether to Skip Empty Archives
*/
skipEmptyArchives?: boolean;
}
/**
* Single item in List or Get Event Hub operation
*/
export interface Eventhub extends Resource {
/**
* Current number of shards on the Event Hub.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly partitionIds?: string[];
/**
* Exact time the Event Hub was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly createdAt?: Date;
/**
* The exact time the message was updated.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly updatedAt?: Date;
/**
* Number of days to retain the events for this Event Hub, value should be 1 to 7 days
*/
messageRetentionInDays?: number;
/**
* Number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions.
*/
partitionCount?: number;
/**
* Enumerates the possible values for the status of the Event Hub. Possible values include:
* 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting',
* 'Renaming', 'Unknown'
*/
status?: EntityStatus;
/**
* Properties of capture description
*/
captureDescription?: CaptureDescription;
}
/**
* Properties of Messaging Region
*/
export interface MessagingRegionsProperties {
/**
* Region code
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly code?: string;
/**
* Full name of the region
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly fullName?: string;
}
/**
* Messaging Region
*/
export interface MessagingRegions extends TrackedResource {
/**
* Properties of Messaging Region
*/
properties?: MessagingRegionsProperties;
}
/**
* Optional Parameters.
*/
export interface EventHubsListByNamespaceOptionalParams extends msRest.RequestOptionsBase {
/**
* Skip is only used if a previous operation returned a partial result. If a previous response
* contains a nextLink element, the value of the nextLink element will include a skip parameter
* that specifies a starting point to use for subsequent calls.
*/
skip?: number;
/**
* May be used to limit the number of results to the most recent N usageDetails.
*/
top?: number;
}
/**
* Optional Parameters.
*/
export interface ConsumerGroupsListByEventHubOptionalParams extends msRest.RequestOptionsBase {
/**
* Skip is only used if a previous operation returned a partial result. If a previous response
* contains a nextLink element, the value of the nextLink element will include a skip parameter
* that specifies a starting point to use for subsequent calls.
*/
skip?: number;
/**
* May be used to limit the number of results to the most recent N usageDetails.
*/
top?: number;
}
/**
* An interface representing EventHubManagementClientOptions.
*/
export interface EventHubManagementClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* @interface
* The response of the List Event Hubs Clusters operation.
* @extends Array<Cluster>
*/
export interface ClusterListResult extends Array<Cluster> {
/**
* Link to the next set of results. Empty unless the value parameter contains an incomplete list
* of Event Hubs Clusters.
*/
nextLink?: string;
}
/**
* @interface
* The response of the List Namespace operation
* @extends Array<EHNamespace>
*/
export interface EHNamespaceListResult extends Array<EHNamespace> {
/**
* Link to the next set of results. Not empty if Value contains incomplete list of namespaces.
*/
nextLink?: string;
}
/**
* @interface
* The response from the List namespace operation.
* @extends Array<AuthorizationRule>
*/
export interface AuthorizationRuleListResult extends Array<AuthorizationRule> {
/**
* Link to the next set of results. Not empty if Value contains an incomplete list of
* Authorization Rules
*/
nextLink?: string;
}
/**
* @interface
* Result of the list of all private endpoint connections operation.
* @extends Array<PrivateEndpointConnection>
*/
export interface PrivateEndpointConnectionListResult extends Array<PrivateEndpointConnection> {
/**
* A link for the next page of private endpoint connection resources.
*/
nextLink?: string;
}
/**
* @interface
* The result of the List EventHubs operation.
* @extends Array<Eventhub>
*/
export interface EventHubListResult extends Array<Eventhub> {
/**
* Link to the next set of results. Not empty if Value contains incomplete list of EventHubs.
*/
nextLink?: string;
}
/**
* @interface
* The result to the List Consumer Group operation.
* @extends Array<ConsumerGroup>
*/
export interface ConsumerGroupListResult extends Array<ConsumerGroup> {
/**
* Link to the next set of results. Not empty if Value contains incomplete list of Consumer Group
*/
nextLink?: string;
}
/**
* @interface
* Result of the request to list Event Hub operations. It contains a list of operations and a URL
* link to get the next set of results.
* @extends Array<Operation>
*/
export interface OperationListResult extends Array<Operation> {
/**
* URL to get the next set of operation list results if there are any.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* The response of the List MessagingRegions operation.
* @extends Array<MessagingRegions>
*/
export interface MessagingRegionsListResult extends Array<MessagingRegions> {
/**
* Link to the next set of results. Not empty if Value contains incomplete list of
* MessagingRegions.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* Defines values for SkuName.
* Possible values include: 'Basic', 'Standard'
* @readonly
* @enum {string}
*/
export type SkuName = 'Basic' | 'Standard';
/**
* Defines values for SkuTier.
* Possible values include: 'Basic', 'Standard'
* @readonly
* @enum {string}
*/
export type SkuTier = 'Basic' | 'Standard';
/**
* Defines values for IdentityType.
* Possible values include: 'SystemAssigned'
* @readonly
* @enum {string}
*/
export type IdentityType = 'SystemAssigned';
/**
* Defines values for KeySource.
* Possible values include: 'Microsoft.KeyVault'
* @readonly
* @enum {string}
*/
export type KeySource = 'Microsoft.KeyVault';
/**
* Defines values for PrivateLinkConnectionStatus.
* Possible values include: 'Pending', 'Approved', 'Rejected', 'Disconnected'
* @readonly
* @enum {string}
*/
export type PrivateLinkConnectionStatus = 'Pending' | 'Approved' | 'Rejected' | 'Disconnected';
/**
* Defines values for EndPointProvisioningState.
* Possible values include: 'Creating', 'Updating', 'Deleting', 'Succeeded', 'Canceled', 'Failed'
* @readonly
* @enum {string}
*/
export type EndPointProvisioningState = 'Creating' | 'Updating' | 'Deleting' | 'Succeeded' | 'Canceled' | 'Failed';
/**
* Defines values for AccessRights.
* Possible values include: 'Manage', 'Send', 'Listen'
* @readonly
* @enum {string}
*/
export type AccessRights = 'Manage' | 'Send' | 'Listen';
/**
* Defines values for KeyType.
* Possible values include: 'PrimaryKey', 'SecondaryKey'
* @readonly
* @enum {string}
*/
export type KeyType = 'PrimaryKey' | 'SecondaryKey';
/**
* Defines values for UnavailableReason.
* Possible values include: 'None', 'InvalidName', 'SubscriptionIsDisabled', 'NameInUse',
* 'NameInLockdown', 'TooManyNamespaceInCurrentSubscription'
* @readonly
* @enum {string}
*/
export type UnavailableReason = 'None' | 'InvalidName' | 'SubscriptionIsDisabled' | 'NameInUse' | 'NameInLockdown' | 'TooManyNamespaceInCurrentSubscription';
/**
* Defines values for EncodingCaptureDescription.
* Possible values include: 'Avro', 'AvroDeflate'
* @readonly
* @enum {string}
*/
export type EncodingCaptureDescription = 'Avro' | 'AvroDeflate';
/**
* Defines values for EntityStatus.
* Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled',
* 'Creating', 'Deleting', 'Renaming', 'Unknown'
* @readonly
* @enum {string}
*/
export type EntityStatus = 'Active' | 'Disabled' | 'Restoring' | 'SendDisabled' | 'ReceiveDisabled' | 'Creating' | 'Deleting' | 'Renaming' | 'Unknown';
/**
* Contains response data for the listAvailableClusterRegion operation.
*/
export type ClustersListAvailableClusterRegionResponse = AvailableClustersList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AvailableClustersList;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type ClustersListByResourceGroupResponse = ClusterListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ClusterListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type ClustersGetResponse = Cluster & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Cluster;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type ClustersCreateOrUpdateResponse = Cluster & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Cluster;
};
};
/**
* Contains response data for the update operation.
*/
export type ClustersUpdateResponse = Cluster & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Cluster;
};
};
/**
* Contains response data for the listNamespaces operation.
*/
export type ClustersListNamespacesResponse = EHNamespaceIdListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EHNamespaceIdListResult;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type ClustersBeginCreateOrUpdateResponse = Cluster & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Cluster;
};
};
/**
* Contains response data for the beginUpdate operation.
*/
export type ClustersBeginUpdateResponse = Cluster & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Cluster;
};
};
/**
* Contains response data for the listByResourceGroupNext operation.
*/
export type ClustersListByResourceGroupNextResponse = ClusterListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ClusterListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type NamespacesListResponse = EHNamespaceListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EHNamespaceListResult;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type NamespacesListByResourceGroupResponse = EHNamespaceListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EHNamespaceListResult;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type NamespacesCreateOrUpdateResponse = EHNamespace & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EHNamespace;
};
};
/**
* Contains response data for the get operation.
*/
export type NamespacesGetResponse = EHNamespace & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EHNamespace;
};
};
/**
* Contains response data for the update operation.
*/
export type NamespacesUpdateResponse = EHNamespace & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EHNamespace;
};
};
/**
* Contains response data for the listAuthorizationRules operation.
*/
export type NamespacesListAuthorizationRulesResponse = AuthorizationRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AuthorizationRuleListResult;
};
};
/**
* Contains response data for the createOrUpdateAuthorizationRule operation.
*/
export type NamespacesCreateOrUpdateAuthorizationRuleResponse = AuthorizationRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AuthorizationRule;
};
};
/**
* Contains response data for the getAuthorizationRule operation.
*/
export type NamespacesGetAuthorizationRuleResponse = AuthorizationRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AuthorizationRule;
};
};
/**
* Contains response data for the listKeys operation.
*/
export type NamespacesListKeysResponse = AccessKeys & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AccessKeys;
};
};
/**
* Contains response data for the regenerateKeys operation.
*/
export type NamespacesRegenerateKeysResponse = AccessKeys & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AccessKeys;
};
};
/**
* Contains response data for the checkNameAvailability operation.
*/
export type NamespacesCheckNameAvailabilityResponse = CheckNameAvailabilityResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: CheckNameAvailabilityResult;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type NamespacesBeginCreateOrUpdateResponse = EHNamespace & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EHNamespace;
};
};
/**
* Contains response data for the listNext operation.
*/
export type NamespacesListNextResponse = EHNamespaceListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EHNamespaceListResult;
};
};
/**
* Contains response data for the listByResourceGroupNext operation.
*/
export type NamespacesListByResourceGroupNextResponse = EHNamespaceListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EHNamespaceListResult;
};
};
/**
* Contains response data for the listAuthorizationRulesNext operation.
*/
export type NamespacesListAuthorizationRulesNextResponse = AuthorizationRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AuthorizationRuleListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type PrivateEndpointConnectionsListResponse = PrivateEndpointConnectionListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PrivateEndpointConnectionListResult;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type PrivateEndpointConnectionsCreateOrUpdateResponse = PrivateEndpointConnection & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PrivateEndpointConnection;
};
};
/**
* Contains response data for the get operation.
*/
export type PrivateEndpointConnectionsGetResponse = PrivateEndpointConnection & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PrivateEndpointConnection;
};
};
/**
* Contains response data for the listNext operation.
*/
export type PrivateEndpointConnectionsListNextResponse = PrivateEndpointConnectionListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PrivateEndpointConnectionListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type PrivateLinkResourcesGetResponse = PrivateLinkResourcesListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PrivateLinkResourcesListResult;
};
};
/**
* Contains response data for the listAuthorizationRules operation.
*/
export type DisasterRecoveryConfigsListAuthorizationRulesResponse = AuthorizationRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AuthorizationRuleListResult;
};
};
/**
* Contains response data for the getAuthorizationRule operation.
*/
export type DisasterRecoveryConfigsGetAuthorizationRuleResponse = AuthorizationRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AuthorizationRule;
};
};
/**
* Contains response data for the listKeys operation.
*/
export type DisasterRecoveryConfigsListKeysResponse = AccessKeys & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AccessKeys;
};
};
/**
* Contains response data for the listAuthorizationRulesNext operation.
*/
export type DisasterRecoveryConfigsListAuthorizationRulesNextResponse = AuthorizationRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AuthorizationRuleListResult;
};
};
/**
* Contains response data for the listAuthorizationRules operation.
*/
export type EventHubsListAuthorizationRulesResponse = AuthorizationRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AuthorizationRuleListResult;
};
};
/**
* Contains response data for the createOrUpdateAuthorizationRule operation.
*/
export type EventHubsCreateOrUpdateAuthorizationRuleResponse = AuthorizationRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AuthorizationRule;
};
};
/**
* Contains response data for the getAuthorizationRule operation.
*/
export type EventHubsGetAuthorizationRuleResponse = AuthorizationRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AuthorizationRule;
};
};
/**
* Contains response data for the listKeys operation.
*/
export type EventHubsListKeysResponse = AccessKeys & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AccessKeys;
};
};
/**
* Contains response data for the regenerateKeys operation.
*/
export type EventHubsRegenerateKeysResponse = AccessKeys & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AccessKeys;
};
};
/**
* Contains response data for the listByNamespace operation.
*/
export type EventHubsListByNamespaceResponse = EventHubListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EventHubListResult;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type EventHubsCreateOrUpdateResponse = Eventhub & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Eventhub;
};
};
/**
* Contains response data for the get operation.
*/
export type EventHubsGetResponse = Eventhub & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Eventhub;
};
};
/**
* Contains response data for the listAuthorizationRulesNext operation.
*/
export type EventHubsListAuthorizationRulesNextResponse = AuthorizationRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AuthorizationRuleListResult;
};
};
/**
* Contains response data for the listByNamespaceNext operation.
*/
export type EventHubsListByNamespaceNextResponse = EventHubListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EventHubListResult;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type ConsumerGroupsCreateOrUpdateResponse = ConsumerGroup & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConsumerGroup;
};
};
/**
* Contains response data for the get operation.
*/
export type ConsumerGroupsGetResponse = ConsumerGroup & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConsumerGroup;
};
};
/**
* Contains response data for the listByEventHub operation.
*/
export type ConsumerGroupsListByEventHubResponse = ConsumerGroupListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConsumerGroupListResult;
};
};
/**
* Contains response data for the listByEventHubNext operation.
*/
export type ConsumerGroupsListByEventHubNextResponse = ConsumerGroupListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConsumerGroupListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type OperationsListResponse = OperationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type OperationsListNextResponse = OperationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationListResult;
};
};
/**
* Contains response data for the listBySku operation.
*/
export type RegionsListBySkuResponse = MessagingRegionsListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: MessagingRegionsListResult;
};
};
/**
* Contains response data for the listBySkuNext operation.
*/
export type RegionsListBySkuNextResponse = MessagingRegionsListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: MessagingRegionsListResult;
};
}; | the_stack |
import { randomBytes, RandomSource } from "@stablelib/random";
import { wipe } from "@stablelib/wipe";
export const PUBLIC_KEY_LENGTH = 32;
export const SECRET_KEY_LENGTH = 32;
export const SHARED_KEY_LENGTH = 32;
// TODO(dchest): some functions are copies of ../sign/ed25519.
// Find a way to combine them without opening up to public.
// Ported from TweetNaCl.js, which is ported from TweetNaCl
// by Dmitry Chestnykh and Devi Mandiri.
// Public domain.
// https://tweetnacl.js.org
// TweetNaCl contributors:
// Daniel J. Bernstein, Bernard van Gastel, Wesley Janssen,
// Tanja Lange, Peter Schwabe, Sjaak Smetsers.
// Public domain.
// https://tweetnacl.cr.yp.to/
type GF = Float64Array;
// Returns new zero-filled 16-element GF (Float64Array).
// If passed an array of numbers, prefills the returned
// array with them.
//
// We use Float64Array, because we need 48-bit numbers
// for this implementation.
function gf(init?: number[]): GF {
const r = new Float64Array(16);
if (init) {
for (let i = 0; i < init.length; i++) {
r[i] = init[i];
}
}
return r;
}
// Base point.
const _9 = new Uint8Array(32); _9[0] = 9;
const _121665 = gf([0xdb41, 1]);
function car25519(o: GF) {
let c = 1;
for (let i = 0; i < 16; i++) {
let v = o[i] + c + 65535;
c = Math.floor(v / 65536);
o[i] = v - c * 65536;
}
o[0] += c - 1 + 37 * (c - 1);
}
function sel25519(p: GF, q: GF, b: number) {
const c = ~(b - 1);
for (let i = 0; i < 16; i++) {
const t = c & (p[i] ^ q[i]);
p[i] ^= t;
q[i] ^= t;
}
}
function pack25519(o: Uint8Array, n: GF) {
const m = gf();
const t = gf();
for (let i = 0; i < 16; i++) {
t[i] = n[i];
}
car25519(t);
car25519(t);
car25519(t);
for (let j = 0; j < 2; j++) {
m[0] = t[0] - 0xffed;
for (let i = 1; i < 15; i++) {
m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
m[i - 1] &= 0xffff;
}
m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
const b = (m[15] >> 16) & 1;
m[14] &= 0xffff;
sel25519(t, m, 1 - b);
}
for (let i = 0; i < 16; i++) {
o[2 * i] = t[i] & 0xff;
o[2 * i + 1] = t[i] >> 8;
}
}
function unpack25519(o: GF, n: Uint8Array) {
for (let i = 0; i < 16; i++) {
o[i] = n[2 * i] + (n[2 * i + 1] << 8);
}
o[15] &= 0x7fff;
}
function add(o: GF, a: GF, b: GF) {
for (let i = 0; i < 16; i++) {
o[i] = a[i] + b[i];
}
}
function sub(o: GF, a: GF, b: GF) {
for (let i = 0; i < 16; i++) {
o[i] = a[i] - b[i];
}
}
function mul(o: GF, a: GF, b: GF) {
let v: number, c: number,
t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
b0 = b[0],
b1 = b[1],
b2 = b[2],
b3 = b[3],
b4 = b[4],
b5 = b[5],
b6 = b[6],
b7 = b[7],
b8 = b[8],
b9 = b[9],
b10 = b[10],
b11 = b[11],
b12 = b[12],
b13 = b[13],
b14 = b[14],
b15 = b[15];
v = a[0];
t0 += v * b0;
t1 += v * b1;
t2 += v * b2;
t3 += v * b3;
t4 += v * b4;
t5 += v * b5;
t6 += v * b6;
t7 += v * b7;
t8 += v * b8;
t9 += v * b9;
t10 += v * b10;
t11 += v * b11;
t12 += v * b12;
t13 += v * b13;
t14 += v * b14;
t15 += v * b15;
v = a[1];
t1 += v * b0;
t2 += v * b1;
t3 += v * b2;
t4 += v * b3;
t5 += v * b4;
t6 += v * b5;
t7 += v * b6;
t8 += v * b7;
t9 += v * b8;
t10 += v * b9;
t11 += v * b10;
t12 += v * b11;
t13 += v * b12;
t14 += v * b13;
t15 += v * b14;
t16 += v * b15;
v = a[2];
t2 += v * b0;
t3 += v * b1;
t4 += v * b2;
t5 += v * b3;
t6 += v * b4;
t7 += v * b5;
t8 += v * b6;
t9 += v * b7;
t10 += v * b8;
t11 += v * b9;
t12 += v * b10;
t13 += v * b11;
t14 += v * b12;
t15 += v * b13;
t16 += v * b14;
t17 += v * b15;
v = a[3];
t3 += v * b0;
t4 += v * b1;
t5 += v * b2;
t6 += v * b3;
t7 += v * b4;
t8 += v * b5;
t9 += v * b6;
t10 += v * b7;
t11 += v * b8;
t12 += v * b9;
t13 += v * b10;
t14 += v * b11;
t15 += v * b12;
t16 += v * b13;
t17 += v * b14;
t18 += v * b15;
v = a[4];
t4 += v * b0;
t5 += v * b1;
t6 += v * b2;
t7 += v * b3;
t8 += v * b4;
t9 += v * b5;
t10 += v * b6;
t11 += v * b7;
t12 += v * b8;
t13 += v * b9;
t14 += v * b10;
t15 += v * b11;
t16 += v * b12;
t17 += v * b13;
t18 += v * b14;
t19 += v * b15;
v = a[5];
t5 += v * b0;
t6 += v * b1;
t7 += v * b2;
t8 += v * b3;
t9 += v * b4;
t10 += v * b5;
t11 += v * b6;
t12 += v * b7;
t13 += v * b8;
t14 += v * b9;
t15 += v * b10;
t16 += v * b11;
t17 += v * b12;
t18 += v * b13;
t19 += v * b14;
t20 += v * b15;
v = a[6];
t6 += v * b0;
t7 += v * b1;
t8 += v * b2;
t9 += v * b3;
t10 += v * b4;
t11 += v * b5;
t12 += v * b6;
t13 += v * b7;
t14 += v * b8;
t15 += v * b9;
t16 += v * b10;
t17 += v * b11;
t18 += v * b12;
t19 += v * b13;
t20 += v * b14;
t21 += v * b15;
v = a[7];
t7 += v * b0;
t8 += v * b1;
t9 += v * b2;
t10 += v * b3;
t11 += v * b4;
t12 += v * b5;
t13 += v * b6;
t14 += v * b7;
t15 += v * b8;
t16 += v * b9;
t17 += v * b10;
t18 += v * b11;
t19 += v * b12;
t20 += v * b13;
t21 += v * b14;
t22 += v * b15;
v = a[8];
t8 += v * b0;
t9 += v * b1;
t10 += v * b2;
t11 += v * b3;
t12 += v * b4;
t13 += v * b5;
t14 += v * b6;
t15 += v * b7;
t16 += v * b8;
t17 += v * b9;
t18 += v * b10;
t19 += v * b11;
t20 += v * b12;
t21 += v * b13;
t22 += v * b14;
t23 += v * b15;
v = a[9];
t9 += v * b0;
t10 += v * b1;
t11 += v * b2;
t12 += v * b3;
t13 += v * b4;
t14 += v * b5;
t15 += v * b6;
t16 += v * b7;
t17 += v * b8;
t18 += v * b9;
t19 += v * b10;
t20 += v * b11;
t21 += v * b12;
t22 += v * b13;
t23 += v * b14;
t24 += v * b15;
v = a[10];
t10 += v * b0;
t11 += v * b1;
t12 += v * b2;
t13 += v * b3;
t14 += v * b4;
t15 += v * b5;
t16 += v * b6;
t17 += v * b7;
t18 += v * b8;
t19 += v * b9;
t20 += v * b10;
t21 += v * b11;
t22 += v * b12;
t23 += v * b13;
t24 += v * b14;
t25 += v * b15;
v = a[11];
t11 += v * b0;
t12 += v * b1;
t13 += v * b2;
t14 += v * b3;
t15 += v * b4;
t16 += v * b5;
t17 += v * b6;
t18 += v * b7;
t19 += v * b8;
t20 += v * b9;
t21 += v * b10;
t22 += v * b11;
t23 += v * b12;
t24 += v * b13;
t25 += v * b14;
t26 += v * b15;
v = a[12];
t12 += v * b0;
t13 += v * b1;
t14 += v * b2;
t15 += v * b3;
t16 += v * b4;
t17 += v * b5;
t18 += v * b6;
t19 += v * b7;
t20 += v * b8;
t21 += v * b9;
t22 += v * b10;
t23 += v * b11;
t24 += v * b12;
t25 += v * b13;
t26 += v * b14;
t27 += v * b15;
v = a[13];
t13 += v * b0;
t14 += v * b1;
t15 += v * b2;
t16 += v * b3;
t17 += v * b4;
t18 += v * b5;
t19 += v * b6;
t20 += v * b7;
t21 += v * b8;
t22 += v * b9;
t23 += v * b10;
t24 += v * b11;
t25 += v * b12;
t26 += v * b13;
t27 += v * b14;
t28 += v * b15;
v = a[14];
t14 += v * b0;
t15 += v * b1;
t16 += v * b2;
t17 += v * b3;
t18 += v * b4;
t19 += v * b5;
t20 += v * b6;
t21 += v * b7;
t22 += v * b8;
t23 += v * b9;
t24 += v * b10;
t25 += v * b11;
t26 += v * b12;
t27 += v * b13;
t28 += v * b14;
t29 += v * b15;
v = a[15];
t15 += v * b0;
t16 += v * b1;
t17 += v * b2;
t18 += v * b3;
t19 += v * b4;
t20 += v * b5;
t21 += v * b6;
t22 += v * b7;
t23 += v * b8;
t24 += v * b9;
t25 += v * b10;
t26 += v * b11;
t27 += v * b12;
t28 += v * b13;
t29 += v * b14;
t30 += v * b15;
t0 += 38 * t16;
t1 += 38 * t17;
t2 += 38 * t18;
t3 += 38 * t19;
t4 += 38 * t20;
t5 += 38 * t21;
t6 += 38 * t22;
t7 += 38 * t23;
t8 += 38 * t24;
t9 += 38 * t25;
t10 += 38 * t26;
t11 += 38 * t27;
t12 += 38 * t28;
t13 += 38 * t29;
t14 += 38 * t30;
// t15 left as is
// first car
c = 1;
v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
t0 += c - 1 + 37 * (c - 1);
// second car
c = 1;
v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
t0 += c - 1 + 37 * (c - 1);
o[0] = t0;
o[1] = t1;
o[2] = t2;
o[3] = t3;
o[4] = t4;
o[5] = t5;
o[6] = t6;
o[7] = t7;
o[8] = t8;
o[9] = t9;
o[10] = t10;
o[11] = t11;
o[12] = t12;
o[13] = t13;
o[14] = t14;
o[15] = t15;
}
function square(o: GF, a: GF) {
mul(o, a, a);
}
function inv25519(o: GF, inp: GF) {
const c = gf();
for (let i = 0; i < 16; i++) {
c[i] = inp[i];
}
for (let i = 253; i >= 0; i--) {
square(c, c);
if (i !== 2 && i !== 4) {
mul(c, c, inp);
}
}
for (let i = 0; i < 16; i++) {
o[i] = c[i];
}
}
export function scalarMult(n: Uint8Array, p: Uint8Array): Uint8Array {
const z = new Uint8Array(32);
const x = new Float64Array(80);
const a = gf(), b = gf(), c = gf(),
d = gf(), e = gf(), f = gf();
for (let i = 0; i < 31; i++) {
z[i] = n[i];
}
z[31] = (n[31] & 127) | 64;
z[0] &= 248;
unpack25519(x, p);
for (let i = 0; i < 16; i++) {
b[i] = x[i];
}
a[0] = d[0] = 1;
for (let i = 254; i >= 0; --i) {
const r = (z[i >>> 3] >>> (i & 7)) & 1;
sel25519(a, b, r);
sel25519(c, d, r);
add(e, a, c);
sub(a, a, c);
add(c, b, d);
sub(b, b, d);
square(d, e);
square(f, a);
mul(a, c, a);
mul(c, b, e);
add(e, a, c);
sub(a, a, c);
square(b, a);
sub(c, d, f);
mul(a, c, _121665);
add(a, a, d);
mul(c, c, a);
mul(a, d, f);
mul(d, b, x);
square(b, e);
sel25519(a, b, r);
sel25519(c, d, r);
}
for (let i = 0; i < 16; i++) {
x[i + 16] = a[i];
x[i + 32] = c[i];
x[i + 48] = b[i];
x[i + 64] = d[i];
}
const x32 = x.subarray(32);
const x16 = x.subarray(16);
inv25519(x32, x32);
mul(x16, x16, x32);
const q = new Uint8Array(32);
pack25519(q, x16);
return q;
}
export function scalarMultBase(n: Uint8Array): Uint8Array {
return scalarMult(n, _9);
}
export interface KeyPair {
publicKey: Uint8Array;
secretKey: Uint8Array;
}
export function generateKeyPairFromSeed(seed: Uint8Array): KeyPair {
if (seed.length !== SECRET_KEY_LENGTH) {
throw new Error(`x25519: seed must be ${SECRET_KEY_LENGTH} bytes`);
}
const secretKey = new Uint8Array(seed);
const publicKey = scalarMultBase(secretKey);
return {
publicKey,
secretKey
};
}
export function generateKeyPair(prng?: RandomSource): KeyPair {
const seed = randomBytes(32, prng);
const result = generateKeyPairFromSeed(seed);
wipe(seed);
return result;
}
/**
* Returns a shared key between our secret key and a peer's public key.
*
* Throws an error if the given keys are of wrong length.
*
* If rejectZero is true throws if the calculated shared key is all-zero.
* From RFC 7748:
*
* > Protocol designers using Diffie-Hellman over the curves defined in
* > this document must not assume "contributory behavior". Specially,
* > contributory behavior means that both parties' private keys
* > contribute to the resulting shared key. Since curve25519 and
* > curve448 have cofactors of 8 and 4 (respectively), an input point of
* > small order will eliminate any contribution from the other party's
* > private key. This situation can be detected by checking for the all-
* > zero output, which implementations MAY do, as specified in Section 6.
* > However, a large number of existing implementations do not do this.
*
* IMPORTANT: the returned key is a raw result of scalar multiplication.
* To use it as a key material, hash it with a cryptographic hash function.
*/
export function sharedKey(mySecretKey: Uint8Array, theirPublicKey: Uint8Array, rejectZero = false): Uint8Array {
if (mySecretKey.length !== PUBLIC_KEY_LENGTH) {
throw new Error("X25519: incorrect secret key length");
}
if (theirPublicKey.length !== PUBLIC_KEY_LENGTH) {
throw new Error("X25519: incorrect public key length");
}
const result = scalarMult(mySecretKey, theirPublicKey);
if (rejectZero) {
let zeros = 0;
for (let i = 0; i < result.length; i++) {
zeros |= result[i];
}
if (zeros === 0) {
throw new Error("X25519: invalid shared key");
}
}
return result;
} | the_stack |
import { ApiBlockType, ApiResponsePage, ApiResponsePages } from "../../src/api-models";
import { Line, TextractDocument, Word } from "../../src/document";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const testFailedJson: ApiResponsePage = require("../data/test-failed-response.json");
// eslint-disable-next-line @typescript-eslint/no-var-requires
const testInProgressJson: ApiResponsePage = require("../data/test-inprogress-response.json");
// eslint-disable-next-line @typescript-eslint/no-var-requires
const testResponseJson: ApiResponsePage = require("../data/test-response.json");
// eslint-disable-next-line @typescript-eslint/no-var-requires
const testMultiColumnJson: ApiResponsePage = require("../data/test-multicol-response.json");
const EXPECTED_MULTILINE_SEQ_LOWER = [
"multi-column test document",
"a sample document with",
"this section has two columns",
"the left column contains",
"the right column",
"correct processing",
"a final footer",
];
describe("TextractDocument", () => {
it("should throw status error on failed async job JSONs (list)", () => {
expect(() => {
new TextractDocument([testFailedJson] as ApiResponsePages);
}).toThrowError(/status.*FAILED/);
});
it("should throw status error on still-in-progress async job JSON (individual)", () => {
expect(() => {
new TextractDocument(testInProgressJson);
}).toThrowError(/content/);
});
it("should parse the test JSON without error", () => {
expect(() => {
new TextractDocument(testResponseJson);
}).not.toThrowError();
});
it("loads and navigates pages", () => {
const doc = new TextractDocument(testResponseJson);
expect(doc.nPages).toStrictEqual(1);
const iterPages = [...doc.iterPages()];
const pageList = doc.listPages();
const firstPage = doc.pageNumber(1);
expect(iterPages.length).toStrictEqual(doc.nPages);
expect(pageList.length).toStrictEqual(doc.nPages);
expect(firstPage).toBe(iterPages[0]);
for (let ix = 0; ix < doc.nPages; ++ix) {
expect(iterPages[ix]).toBe(pageList[ix]);
}
expect(firstPage.blockType).toStrictEqual(ApiBlockType.Page);
expect(firstPage.parentDocument).toBe(doc);
expect(firstPage.geometry.parentObject).toBe(firstPage);
});
it("throws errors on out-of-bounds pages", () => {
const doc = new TextractDocument(testResponseJson);
expect(() => doc.pageNumber(0)).toThrow(/must be between 1 and/);
expect(() => doc.pageNumber(doc.nPages + 1)).toThrow(/must be between 1 and/);
});
it("loads and navigates lines", () => {
const doc = new TextractDocument(testResponseJson);
const firstPage = doc.pageNumber(1);
expect(firstPage.nLines).toStrictEqual(31);
const iterLines = [...firstPage.iterLines()];
const lineList = firstPage.listLines();
const firstLine = firstPage.lineAtIndex(0);
expect(iterLines.length).toStrictEqual(firstPage.nLines);
expect(lineList.length).toStrictEqual(firstPage.nLines);
expect(firstLine).toBe(iterLines[0]);
for (let ix = 0; ix < firstPage.nLines; ++ix) {
expect(iterLines[ix]).toBe(lineList[ix]);
}
expect(firstLine.blockType).toStrictEqual(ApiBlockType.Line);
expect(firstLine.confidence).toBeGreaterThan(1); // (<1% very unlikely)
expect(firstLine.confidence).toBeLessThanOrEqual(100);
expect(firstLine.parentPage).toBe(firstPage);
expect(firstLine.geometry.parentObject).toBe(firstLine);
expect(firstLine.text).toMatch("Employment Application");
});
it("throws errors on out-of-bounds lines", () => {
const doc = new TextractDocument(testResponseJson);
const page = doc.pageNumber(1);
expect(() => page.lineAtIndex(-1)).toThrow(/Line index/);
expect(() => page.lineAtIndex(page.nLines)).toThrow(/Line index/);
});
it("loads and navigates line words", () => {
const doc = new TextractDocument(testResponseJson);
const firstPage = doc.pageNumber(1);
const firstLine = firstPage.lineAtIndex(0);
expect(firstLine.nWords).toStrictEqual(2);
const iterWords = [...firstLine.iterWords()];
const wordList = firstLine.listWords();
const firstWord = firstLine.wordAtIndex(0);
expect(iterWords.length).toStrictEqual(firstLine.nWords);
expect(wordList.length).toStrictEqual(firstLine.nWords);
expect(firstWord).toBe(iterWords[0]);
for (let ix = 0; ix < firstLine.nWords; ++ix) {
expect(iterWords[ix]).toBe(wordList[ix]);
}
// (no parent prop on Word)
expect(firstWord.blockType).toStrictEqual(ApiBlockType.Word);
expect(firstWord.geometry.parentObject).toBe(firstWord);
expect(firstPage.listLines().reduce((acc, next) => acc + next.listWords().length, 0)).toStrictEqual(71);
expect(firstWord.text).toMatch("Employment");
expect(firstWord.str()).toStrictEqual(firstWord.text);
});
it("throws errors on out-of-bounds line words", () => {
const doc = new TextractDocument(testResponseJson);
const page = doc.pageNumber(1);
const line = page.lineAtIndex(0);
expect(() => line.wordAtIndex(-1)).toThrow(/Word index/);
expect(() => line.wordAtIndex(line.nWords)).toThrow(/Word index/);
});
it("loads page, line and word bounding boxes", () => {
const doc = new TextractDocument(testResponseJson);
const page = doc.pageNumber(1);
const line = page.lineAtIndex(1);
const word = line.wordAtIndex(0);
expect(word.geometry.boundingBox.parentGeometry.parentObject).toBe(word);
expect(line.geometry.boundingBox.parentGeometry.parentObject.parentPage).toBe(page);
expect(page.geometry.boundingBox.top).toBeLessThan(line.geometry.boundingBox.top);
expect(page.geometry.boundingBox.bottom).toBeGreaterThan(line.geometry.boundingBox.bottom);
expect(page.geometry.boundingBox.left).toBeLessThan(line.geometry.boundingBox.left);
expect(page.geometry.boundingBox.right).toBeGreaterThan(line.geometry.boundingBox.right);
expect(line.geometry.boundingBox.top).toBeLessThanOrEqual(word.geometry.boundingBox.top);
expect(line.geometry.boundingBox.bottom).toBeGreaterThanOrEqual(word.geometry.boundingBox.bottom);
expect(line.geometry.boundingBox.left).toStrictEqual(word.geometry.boundingBox.left);
expect(line.geometry.boundingBox.right).toBeGreaterThan(word.geometry.boundingBox.right);
});
it("loads and navigates basic table properties", () => {
const doc = new TextractDocument(testResponseJson);
const page = doc.pageNumber(1);
expect(page.nTables).toStrictEqual(1);
const iterTables = [...page.iterTables()];
const tableList = page.listTables();
const table = page.tableAtIndex(0);
expect(iterTables.length).toStrictEqual(page.nTables);
expect(tableList.length).toStrictEqual(page.nTables);
expect(table).toBe(iterTables[0]);
for (let ix = 0; ix < page.nLines; ++ix) {
expect(iterTables[ix]).toBe(tableList[ix]);
}
expect(table.confidence).toBeGreaterThan(1); // (<1% very unlikely)
expect(table.confidence).toBeLessThanOrEqual(100);
expect(table.geometry.parentObject).toBe(table);
});
it("throws errors on out-of-bounds tables", () => {
const doc = new TextractDocument(testResponseJson);
const page = doc.pageNumber(1);
expect(() => page.tableAtIndex(-1)).toThrow(/Table index/);
expect(() => page.tableAtIndex(page.nTables)).toThrow(/Table index/);
});
it("loads table dimensions", () => {
const doc = new TextractDocument(testResponseJson);
expect(doc.pageNumber(1).nTables).toStrictEqual(1);
const table = doc.pageNumber(1).tableAtIndex(0);
expect(table.nColumns).toStrictEqual(5);
expect(table.nRows).toStrictEqual(5);
expect(table.nCells).toStrictEqual(25);
});
it("indexes table cells by row and column", () => {
const doc = new TextractDocument(testResponseJson);
expect(doc.pageNumber(1).nTables).toStrictEqual(1);
const table = [...doc.pageNumber(1).iterTables()][0];
expect(table.cellAt(2, 2)?.text).toMatch("End Date");
expect(table.cellAt(3, 2)?.text).toMatch("6/30/2011");
// Strict mode:
expect(table.cellAt(2, 2, true)?.text).toMatch("End Date");
expect(table.cellAt(3, 2, true)?.text).toMatch("6/30/2011");
});
it("fetches table row cells by index", () => {
const doc = new TextractDocument(testResponseJson);
const table = [...doc.pageNumber(1).iterTables()][0];
expect(table.cellsAt(2, null).length).toStrictEqual(5);
// Strict mode:
expect(table.cellsAt(2, null, true).length).toStrictEqual(5);
});
it("fetches column cells by index", () => {
const doc = new TextractDocument(testResponseJson);
const table = [...doc.pageNumber(1).iterTables()][0];
expect(table.cellsAt(null, 2).length).toStrictEqual(5);
// Strict mode:
expect(table.cellsAt(null, 2, true).length).toStrictEqual(5);
});
it("iterates table rows", () => {
const doc = new TextractDocument(testResponseJson);
const table = doc.pageNumber(1).tableAtIndex(0);
const tableRows = table.listRows();
expect(tableRows.length).toStrictEqual(table.nRows);
let nRows = 0;
for (const row of table.iterRows(false)) {
++nRows;
expect(row.parentTable).toBe(table);
}
expect(nRows).toStrictEqual(table.nRows);
expect(nRows).toStrictEqual(5);
});
it("lists table rows", () => {
const doc = new TextractDocument(testResponseJson);
const table = doc.pageNumber(1).tableAtIndex(0);
expect(table.listRows(true).length).toStrictEqual(table.nRows);
});
it("navigates table row cells", () => {
const doc = new TextractDocument(testResponseJson);
const table = doc.pageNumber(1).tableAtIndex(0);
let nCellsTotal = 0;
let nRows = 0;
let targetCellFound = false;
for (const row of table.iterRows(false)) {
const rowCells = row.listCells();
let nCells = 0;
++nRows;
const indexedCells = table.cellsAt(nRows, null, true);
expect(rowCells.length).toStrictEqual(indexedCells.length);
for (const cell of row.iterCells()) {
++nCells;
++nCellsTotal;
expect(indexedCells.indexOf(cell)).toBeGreaterThanOrEqual(0);
expect(rowCells.indexOf(cell)).toBeGreaterThanOrEqual(0);
expect(cell.confidence).toBeGreaterThan(1); // (<1% very unlikely)
expect(cell.confidence).toBeLessThanOrEqual(100);
expect(cell.geometry.parentObject).toBe(cell);
expect(cell.str()).toStrictEqual(cell.text);
if (nRows === 2 && nCells === 4) {
expect(cell.text).toMatch("Position Held");
expect(
cell
.listContent()
.filter((c) => c.blockType === ApiBlockType.Word)
.map((w) => (w as Word).text)
.join(" ")
).toMatch("Position Held");
targetCellFound = true;
}
}
expect(nCells).toStrictEqual(row.nCells);
}
expect(nCellsTotal).toStrictEqual(25);
expect(targetCellFound).toStrictEqual(true);
});
it("loads and navigates form fields", () => {
const doc = new TextractDocument(testResponseJson);
const page = doc.pageNumber(1);
expect(page.form.nFields).toStrictEqual(9);
expect(page.form.parentPage).toBe(page);
const iterFields = [...page.form.iterFields()];
const fieldList = page.form.listFields();
expect(iterFields.length).toStrictEqual(page.form.nFields);
expect(fieldList.length).toStrictEqual(page.form.nFields);
for (let ix = 0; ix < page.form.nFields; ++ix) {
expect(iterFields[ix]).toBe(fieldList[ix]);
}
const field = fieldList[0];
expect(field.parentForm).toBe(page.form);
expect(field.confidence).toBeGreaterThan(1); // (<1% very unlikely)
expect(field.confidence).toBeLessThanOrEqual(100);
});
it("loads correct types of form field content", () => {
const doc = new TextractDocument(testResponseJson);
const page = doc.pageNumber(1);
let nFieldValWords = 0;
let nFieldValSelEls = 0;
for (const field of page.form.iterFields()) {
if (field?.value) {
for (const item of field.value.listContent()) {
if (item.blockType === ApiBlockType.Word) {
++nFieldValWords;
} else if (item.blockType === ApiBlockType.SelectionElement) {
++nFieldValSelEls;
} else {
throw new Error(`Unexpected field value content type ${item.blockType}`);
}
}
}
}
expect(nFieldValSelEls).toBeGreaterThan(0);
expect(nFieldValWords).toBeGreaterThan(0);
});
it("retrieves form fields by key", () => {
const doc = new TextractDocument(testResponseJson);
const field = doc.pageNumber(1).form.getFieldByKey("Phone Number:");
expect(field).toBeTruthy();
if (!field) {
throw new Error("Test field missing from test document");
}
// We also do bulk of field functionality validation here because we know what the field is:
expect(field.key?.parentField).toBe(field);
expect(field.value?.parentField).toBe(field);
expect(field.key?.confidence).toBeGreaterThan(1); // (<1% very unlikely)
expect(field.key?.confidence).toBeLessThanOrEqual(100);
expect(field.key?.geometry.parentObject).toBe(field.key);
expect(field.key?.str()).toStrictEqual(field.key?.text);
expect(field.value?.confidence).toBeGreaterThan(1); // (<1% very unlikely)
expect(field.value?.confidence).toBeLessThanOrEqual(100);
expect(field.value?.geometry.parentObject).toBe(field.value);
expect(field.value?.text).toStrictEqual("555-0100");
expect(field.value?.str()).toStrictEqual(field.value?.text);
});
it("searches form fields by key", () => {
const doc = new TextractDocument(testResponseJson);
const results = doc.pageNumber(1).form.searchFieldsByKey("Home Addr");
expect(results.length).toStrictEqual(1);
expect(results[0].value?.text).toMatch(/123 Any Street/i);
});
it("exposes raw dicts with traversal up and down the tree", () => {
const doc = new TextractDocument(testResponseJson);
const page = doc.pageNumber(1);
// Doc to LINE and back again:
expect(page.lineAtIndex(0).parentPage.parentDocument.dict).toBe(doc.dict);
// Word to BBox/Polygon and back again:
const aWord = doc.pageNumber(1).lineAtIndex(0).wordAtIndex(0);
expect(aWord.geometry.boundingBox.parentGeometry?.parentObject?.dict).toBe(aWord.dict);
expect(aWord.geometry.polygon[0].parentGeometry?.parentObject?.dict).toBe(aWord.dict);
// PAGE to table CELL and back again:
expect(page.tableAtIndex(0).cellAt(1, 1)?.parentTable.parentPage.dict).toBe(page.dict);
// PAGE to field value and back again:
const formKeys = page.form.searchFieldsByKey("");
expect(formKeys.length).toBeGreaterThan(0);
expect(formKeys.length && formKeys[0].value?.parentField.parentForm.parentPage.dict).toBe(page.dict);
});
it("sorts lines correctly for multi-column documents", () => {
const doc = new TextractDocument(testMultiColumnJson);
const readingOrder = doc.pageNumber(1).getLineClustersInReadingOrder();
expect(readingOrder.length).not.toBeLessThan(1);
const sortedLinesTextLower = ([] as Line[])
.concat(...readingOrder)
.map((l) => l.text.toLocaleLowerCase());
expect(sortedLinesTextLower.length).not.toBeLessThan(EXPECTED_MULTILINE_SEQ_LOWER.length);
let ixTest = 0;
sortedLinesTextLower.forEach((lineText) => {
const matchIx = EXPECTED_MULTILINE_SEQ_LOWER.findIndex((seq) => lineText.indexOf(seq) >= 0);
if (matchIx >= 0) {
// We compare the strings first here to make failed assertions a bit more meaningful:
expect(EXPECTED_MULTILINE_SEQ_LOWER[matchIx]).toStrictEqual(EXPECTED_MULTILINE_SEQ_LOWER[ixTest]);
expect(matchIx).toStrictEqual(ixTest);
++ixTest;
}
});
expect(ixTest).toStrictEqual(EXPECTED_MULTILINE_SEQ_LOWER.length);
});
it("outputs text correctly for multi-column documents", () => {
const doc = new TextractDocument(testMultiColumnJson);
const sortedLinesTextLower = doc.pageNumber(1).getTextInReadingOrder().toLocaleLowerCase().split("\n");
expect(sortedLinesTextLower.length).not.toBeLessThan(EXPECTED_MULTILINE_SEQ_LOWER.length);
let ixTest = 0;
sortedLinesTextLower.forEach((lineText) => {
const matchIx = EXPECTED_MULTILINE_SEQ_LOWER.findIndex((seq) => lineText.indexOf(seq) >= 0);
if (matchIx >= 0) {
// We compare the strings first here to make failed assertions a bit more meaningful:
expect(EXPECTED_MULTILINE_SEQ_LOWER[matchIx]).toStrictEqual(EXPECTED_MULTILINE_SEQ_LOWER[ixTest]);
expect(matchIx).toStrictEqual(ixTest);
++ixTest;
}
});
expect(ixTest).toStrictEqual(EXPECTED_MULTILINE_SEQ_LOWER.length);
});
it("detects 0 orientation for perfectly straight pages", () => {
const doc = new TextractDocument(testMultiColumnJson);
for (const page of doc.iterPages()) {
expect(page.getModalWordOrientationDegrees()).toStrictEqual(0);
}
});
}); | the_stack |
import * as fs from "fs";
import * as path from "path";
import { expect, assert } from "chai";
import { ExprParser } from "./ExprParser";
import { ExprLexer } from "./ExprLexer";
import { CPP14Parser } from "./CPP14Parser";
import { CPP14Lexer } from "./CPP14Lexer";
import { PredicatedFooBarLexer } from "./PredicatedFooBarLexer";
import { PredicatedFooBarParser } from "./PredicatedFooBarParser";
import * as c3 from "../index";
import {
ANTLRErrorListener, CharStreams, CommonToken, CommonTokenStream, RecognitionException, Recognizer, Token,
} from "antlr4ts";
import { Override } from "antlr4ts/Decorators";
import { TerminalNode } from "antlr4ts/tree/TerminalNode";
// Some helper functions + types to create certain setups.
export class ErrorListener implements ANTLRErrorListener<CommonToken> {
public errorCount = 0;
@Override
public syntaxError<T extends Token>(recognizer: Recognizer<T, any>, offendingSymbol: T | undefined, line: number,
charPositionInLine: number, msg: string, e: RecognitionException | undefined): void {
++this.errorCount;
}
}
const dummyNode = new TerminalNode(new CommonToken(-2, "Dummy", undefined, 0, 10, 20));
/**
* Creates a single symbol table setup with a simple base structure:
* - [0] classes with [1] methods and [2] fields
* - two blocks in each method and 1 variable in each block.
* In addition to that some global symbols are added ([3] variables, [4] literals).
* If namespaces are given then the classes are distributed among them in a round-robin fashion.
*
* @param name The name of the new symbol table.
* @param counts An array containing the numbers for the objects to create.
* @param namespaces A list of namespace names to create.
* @returns A promise resolving to the created symbol table.
*/
const createClassSymbolTable = async (name: string, counts: number[],
namespaces?: string[]): Promise<c3.SymbolTable> => {
const symbolTable = new c3.SymbolTable(name, { allowDuplicateSymbols: false });
const nsSymbols: Array<c3.NamespaceSymbol | undefined> = [undefined];
let nsIndex = 0;
let nsCount = 1;
if (namespaces && namespaces.length > 0) {
nsCount = namespaces.length;
for (let i = 0; i < nsCount; ++i) {
nsSymbols[i] = await symbolTable.addNewNamespaceFromPath(undefined, namespaces[i]);
}
}
for (let i = 0; i < counts[0]; ++i) {
const classSymbol = symbolTable.addNewSymbolOfType(c3.ClassSymbol, nsSymbols[nsIndex], `class${i}`);
for (let j = 0; j < counts[2]; ++j) {
symbolTable.addNewSymbolOfType(c3.FieldSymbol, classSymbol, `field${j}`);
}
for (let j = 0; j < counts[1]; ++j) {
const method = symbolTable.addNewSymbolOfType(c3.MethodSymbol, classSymbol, `method${j}`);
// Blocks are created and added in an alternative way.
const block1 = symbolTable.addNewSymbolOfType(c3.BlockSymbol, undefined, "block1"); // Block at top level.
symbolTable.addNewSymbolOfType(c3.VariableSymbol, block1, "var1", 17, c3.FundamentalType.integerType);
const block2 = symbolTable.addNewSymbolOfType(c3.BlockSymbol, undefined, "block2");
const symbol = symbolTable.addNewSymbolOfType(c3.VariableSymbol, block2, "var1", 3.142,
c3.FundamentalType.floatType);
if (j === 1) {
symbol.context = dummyNode;
}
// Now move the blocks from global level to the method.
method.addSymbol(block1);
method.addSymbol(block2);
}
++nsIndex;
if (nsIndex === nsCount) {nsIndex = 0;}
}
for (let i = 0; i < counts[3]; ++i) {
symbolTable.addNewSymbolOfType(c3.VariableSymbol, undefined, `globalVar${i}`, 42,
c3.FundamentalType.integerType);
}
for (let i = 0; i < counts[4]; ++i) {
symbolTable.addNewSymbolOfType(c3.LiteralSymbol, undefined, `globalConst${i}`, "string constant",
c3.FundamentalType.stringType);
}
return symbolTable;
};
// Begin of the tests.
describe("antlr4-c3:", function () {
this.slow(1000);
describe("Symbol table tests:", () => {
it("Single table base tests", async () => {
const symbolTable = await createClassSymbolTable("main", [3, 3, 4, 5, 5]);
const info = symbolTable.info;
expect(info.dependencyCount, "Test 1").to.equal(0);
expect(info.symbolCount, "Test 2").to.equal(13); // 5 + 5 top level symbols + 3 classes.
try {
symbolTable.addNewSymbolOfType(c3.VariableSymbol, undefined, "globalVar3");
assert(false);
} catch (e) {
if (e instanceof c3.DuplicateSymbolError) {
expect(e.message, "Test 3").to.equal("Attempt to add duplicate symbol 'globalVar3'");
} else {
assert(false, "Test 3");
}
}
const class1 = await symbolTable.resolve("class1");
expect(class1, "Test 4").is.instanceof(c3.ClassSymbol);
const method2 = await (class1 as c3.ClassSymbol).resolve("method2");
expect(method2, "Test 5").is.instanceof(c3.MethodSymbol);
const scopes = await (method2 as c3.MethodSymbol).directScopes;
expect(scopes.length, "Test 6").equals(2); // 2 anonymous blocks.
expect(scopes[0], "Test 7").is.instanceof(c3.ScopedSymbol);
const block1 = scopes[0] ;
try {
const duplicateMethod = symbolTable.addNewSymbolOfType(c3.MethodSymbol, undefined, "method2");
(class1 as c3.ClassSymbol).addSymbol(duplicateMethod); // Must throw.
assert(false);
} catch (e) {
if (e instanceof c3.DuplicateSymbolError) {
expect(e.message, "Test 8").to.equal("Attempt to add duplicate symbol 'method2'");
} else {
assert(false);
}
}
let variable = await scopes[0].resolve("globalVar3"); // Resolves to the global var 3.
expect(variable, "Test 9").to.be.instanceof(c3.VariableSymbol);
expect(variable!.root, "Test 10").to.equal(symbolTable);
variable = await scopes[0].resolve("globalVar3", true); // Try only local vars.
expect(variable, "Test 11").to.equal(undefined);
variable = await scopes[0].resolve("var1"); // Now resolves to local var.
expect(variable!.root, "Test 12").to.equal(class1);
expect(variable!.getParentOfType(c3.MethodSymbol), "Test 13").to.equal(method2);
const methods = await (class1 as c3.ClassSymbol).getSymbolsOfType(c3.MethodSymbol);
expect(methods.length, "Test 14").to.equal(3);
const symbols = await (method2 as c3.MethodSymbol).getSymbolsOfType(c3.ScopedSymbol);
expect(symbols.length, "Test 15").to.equal(2);
expect(await block1.resolve("class1", false), "Test 16").to.equal(class1);
const symbolPaths = variable!.symbolPath;
expect(symbolPaths.length, "Test 17").to.equal(5);
expect(symbolPaths[0].name, "Test 18").to.equal("var1");
expect(symbolPaths[1].name, "Test 19").to.equal("block1");
expect(symbolPaths[2].name, "Test 20").to.equal("method2");
expect(symbolPaths[3].name, "Test 21").to.equal("class1");
expect(symbolPaths[4].name, "Test 22").to.equal("main");
expect(method2!.qualifiedName(), "Test 23").to.equal("class1.method2");
expect(method2!.qualifiedName("-", true), "Test 24").to.equal("main-class1-method2");
expect(variable!.qualifiedName(), "Test 25").to.equal("block1.var1");
expect(variable!.qualifiedName("#"), "Test 26").to.equal("block1#var1");
expect(variable!.qualifiedName(".", false, true), "Test 27").to.equal("block1.var1");
expect(variable!.qualifiedName(".", true, false), "Test 28").to.equal("main.class1.method2.block1.var1");
expect(variable!.qualifiedName(".", true, true), "Test 29").to.equal("main.class1.method2.block1.var1");
const allSymbols = await symbolTable.getAllNestedSymbols();
expect(allSymbols.length, "Test 30").to.equal(70);
const symbolPath = allSymbols[59].qualifiedName(".", true);
expect(symbolPath, "Test 31").to.equal("main.class2.method0.block2");
const foundSymbol = symbolTable.symbolFromPath("main.class2.method0.block2.var1");
expect(foundSymbol, "Test 32").to.equal(allSymbols[61]);
expect(symbolTable, "Test 33").to.equal(symbolTable.symbolTable);
});
it("Single table type checks", async () => {
// Create a symbol table with all the symbols we have in the lib and query it for some collections.
// Start with a standard table containing a class with a single method, a global var and a global
// literal symbol. Hierarchy is not really important here.
const symbolTable = await createClassSymbolTable("main", [1, 1, 1, 1, 1]);
// Now add all the other symbols.
symbolTable.addNewSymbolOfType(c3.TypeAlias, undefined, "newBool", c3.FundamentalType.boolType);
symbolTable.addNewSymbolOfType(c3.RoutineSymbol, undefined, "routine1", c3.FundamentalType.integerType);
symbolTable.addNewSymbolOfType(c3.FieldSymbol, undefined, "field1", c3.FundamentalType.floatType);
});
it("Single table stress test", async () => {
const symbolTable = await createClassSymbolTable("table", [300, 30, 20, 1000, 1000]);
let symbols = await symbolTable.getAllNestedSymbols();
expect(symbols.length, "Test 1").to.equal(53300);
symbols = await symbolTable.getNestedSymbolsOfType(c3.ClassSymbol);
expect(symbols.length, "Test 2").to.equal(300);
symbols = await symbolTable.getNestedSymbolsOfType(c3.MethodSymbol);
expect(symbols.length, "Test 3").to.equal(9000);
symbols = await symbolTable.getNestedSymbolsOfType(c3.ScopedSymbol);
expect(symbols.length, "Test 4").to.equal(27300);
// Includes class fields.
symbols = await symbolTable.getNestedSymbolsOfType(c3.VariableSymbol);
expect(symbols.length, "Test 5").to.equal(25000);
symbols = await symbolTable.getNestedSymbolsOfType(c3.FieldSymbol);
expect(symbols.length, "Test 6").to.equal(6000);
symbols = await symbolTable.getNestedSymbolsOfType(c3.LiteralSymbol);
expect(symbols.length, "Test 7").to.equal(1000);
}).timeout(20000);
it("Single table namespace tests", async () => {
const symbolTable = await createClassSymbolTable("main", [30, 10, 10, 100, 100], ["ns1", "ns2",
"ns1.ns3.ns5", "ns1.ns4.ns6.ns8"]);
const namespaces = await symbolTable.getNestedSymbolsOfType(c3.NamespaceSymbol);
expect(namespaces.length, "Test 1").to.equal(7);
// This call does a depth-first search, so all the deeper nested namespaces appear at the lower indexes
// and the less nested ones at the end of the list.
const methods = await symbolTable.getNestedSymbolsOfType(c3.MethodSymbol);
expect(methods.length, "Test 2").to.equal(300);
expect(methods[2].qualifiedName(".", true), "Test 3").to.equal("main.ns1.ns3.ns5.class2.method2");
expect(methods[299].qualifiedName(".", true), "Test 4").to.equal("main.ns2.class29.method9");
});
it("Multi table tests", async () => {
// Interactions between linked symbol tables. We use 5 tables here:
// - the main table as in the single table tests.
// - a system functions table
// - a table with variables, which has 2 other dependencies (functions in same namespace as system
// functions and one in a different namespace)
const main = await createClassSymbolTable("main", [30, 10, 10, 100, 100]);
const systemFunctions = new c3.SymbolTable("system functions", { allowDuplicateSymbols: false });
const namespace1 = systemFunctions.addNewSymbolOfType(c3.NamespaceSymbol, undefined, "ns1");
for (let i = 0; i < 333; ++i) {
systemFunctions.addNewSymbolOfType(c3.RoutineSymbol, namespace1, `func${i}`);
}
main.addDependencies(systemFunctions);
const libFunctions = new c3.SymbolTable("library functions", { allowDuplicateSymbols: false });
const namespace2 = libFunctions.addNewSymbolOfType(c3.NamespaceSymbol, undefined, "ns2");
for (let i = 0; i < 444; ++i) {
// Same names as in the system functions but different namespace.
libFunctions.addNewSymbolOfType(c3.RoutineSymbol, namespace2, `func${i}`);
}
const libVariables = new c3.SymbolTable("library variables", { allowDuplicateSymbols: false });
// Like for the system functions.
const namespace3 = libVariables.addNewSymbolOfType(c3.NamespaceSymbol, undefined, "ns1");
for (let i = 0; i < 555; ++i) {
libVariables.addNewSymbolOfType(c3.VariableSymbol, namespace3, `var${i}`);
}
const libFunctions2 = new c3.SymbolTable("library functions 2", { allowDuplicateSymbols: false });
const namespace4 = libFunctions2.addNewSymbolOfType(c3.NamespaceSymbol, undefined, "ns1");
for (let i = 0; i < 666; ++i) {
// Same names as in the system functions but different namespace.
libFunctions2.addNewSymbolOfType(c3.RoutineSymbol, namespace4, `func${i}`);
}
libVariables.addDependencies(libFunctions, libFunctions2);
main.addDependencies(systemFunctions, libVariables);
// Note: namespaces are handled in the context of their parent.
// Symbols in a namespace/module/library are accessible from their parent.
let allSymbols = await main.getAllSymbols(c3.Symbol);
expect(allSymbols.length, "Test 1").to.equal(2232);
allSymbols = await main.getAllSymbols(c3.RoutineSymbol);
expect(allSymbols.length, "Test 2").to.equal(1443);
// System functions alone + the namespace.
expect((await systemFunctions.getAllSymbols(c3.Symbol)).length, "Test 3").to.equal(334);
// Lib functions alone + the namespace.
expect((await libFunctions.getAllSymbols(c3.Symbol)).length, "Test 4").to.equal(445);
// Lib variables + lib functions + namespaces.
expect((await libVariables.getAllSymbols(c3.Symbol)).length, "Test 5").to.equal(1668);
// Lib functions in "ns1" only + the namespace.
expect((await libFunctions2.getAllSymbols(c3.RoutineSymbol)).length, "Test 6").to.equal(666);
});
it("Symbol navigation", async () => {
const symbolTable = await createClassSymbolTable("main", [10, 10, 10, 20, 34], []);
const namespaces = await symbolTable.getNestedSymbolsOfType(c3.NamespaceSymbol);
expect(namespaces.length, "Test 1").to.equal(0);
// Does not include constant values (which are literals). Still such variables may appear in
// below navigation methods and are compared by name, instead of reference.
const variables = await symbolTable.getNestedSymbolsOfType(c3.VariableSymbol);
expect(variables.length, "Test 2").to.equal(320);
// A class member.
const field7 = variables[202];
expect(field7, "Test 3").not.to.be.undefined;
expect(field7.firstSibling, "Test 4").to.equal(variables[200]);
expect(field7.lastSibling.name, "Test 5").to.equal("method9");
expect(field7.previousSibling, "Test 6").to.equal(variables[201]);
expect(field7.nextSibling, "Test 7").to.equal(variables[203]);
expect(field7.firstSibling.firstSibling.firstSibling.firstSibling, "Test 8").to.equal(field7.firstSibling);
expect(field7.lastSibling.lastSibling.lastSibling.lastSibling, "Test 9").to.equal(field7.lastSibling);
expect(field7.firstSibling.lastSibling.firstSibling.firstSibling, "Test 10").to.equal(field7.firstSibling);
expect(field7.lastSibling.firstSibling.firstSibling.lastSibling, "Test 11").to.equal(field7.lastSibling);
expect(field7.parent, "Test 12").to.be.instanceof(c3.ClassSymbol);
const parent7 = field7.parent as c3.ClassSymbol;
expect(parent7.indexOfChild(field7), "Test 13").to.equal(2);
expect(parent7.firstChild, "Test 14").to.equal(field7.firstSibling);
expect(parent7.lastChild, "Test 15").to.equal(field7.lastSibling);
// A local variable (a single one in a block).
const var1 = variables[286];
expect(var1, "Test 16").not.to.be.undefined;
expect(var1.firstSibling, "Test 17").to.equal(var1);
expect(var1.lastSibling.name, "Test 18").to.equal("var1");
expect(var1.previousSibling, "Test 19").to.be.undefined;
expect(var1.nextSibling, "Test 20").to.undefined;
expect(var1.firstSibling.firstSibling.firstSibling.firstSibling, "Test 21").to.equal(var1.firstSibling);
expect(var1.lastSibling.lastSibling.lastSibling.lastSibling, "Test 22").to.equal(var1.lastSibling);
expect(var1.firstSibling.lastSibling.firstSibling.firstSibling, "Test 23").to.equal(var1.firstSibling);
expect(var1.lastSibling.firstSibling.firstSibling.lastSibling, "Test 24").to.equal(var1.lastSibling);
const block1 = var1.parent as c3.ScopedSymbol;
expect(block1.indexOfChild(field7), "Test 25").to.equal(-1);
expect(block1.indexOfChild(var1), "Test 26").to.equal(0);
expect(block1.firstChild, "Test 27").to.equal(var1.firstSibling);
expect(block1.lastChild, "Test 28").to.equal(var1.lastSibling);
// A global variable.
const var15 = variables[19];
expect(var15, "Test 29").not.to.be.undefined;
expect(var15.firstSibling, "Test 30").to.equal(symbolTable.firstChild);
expect(var15.lastSibling.name, "Test 31").to.equal("globalConst33");
expect(var15.previousSibling, "Test 32").to.equal(variables[18]);
expect(var15.nextSibling?.name, "Test 33").to.equal("globalConst0");
expect(var15.parent, "Test 34").to.be.instanceof(c3.SymbolTable);
const st1 = var15.parent as c3.ScopedSymbol;
expect(st1.indexOfChild(var15), "Test 35").to.equal(29);
expect(st1.firstChild, "Test 36").to.equal(var15.firstSibling);
expect(st1.lastChild, "Test 37").to.equal(var15.lastSibling);
const next = variables[284].next;
expect(next, "Test 38").not.to.be.undefined;
expect(next!.qualifiedName(".", true), "Test 39").to.equal("main.class8.method7.block1.var1");
const symbol = await symbolTable.symbolWithContext(dummyNode);
expect(symbol, "Test 40").not.to.be.undefined;
expect(symbol!.qualifiedName(".", true), "Test 41").to.equal("main.class0.method1.block2.var1");
});
});
describe("Simple expression parser:", () => {
it("Most simple setup", () => {
// No customization happens here, so the c3 engine only returns lexer tokens.
const inputStream = CharStreams.fromString("var c = a + b()");
const lexer = new ExprLexer(inputStream);
const tokenStream = new CommonTokenStream(lexer);
const parser = new ExprParser(tokenStream);
const errorListener = new ErrorListener();
parser.addErrorListener(errorListener);
parser.expression();
expect(errorListener.errorCount, "Test 1").equals(0);
const core = new c3.CodeCompletionCore(parser);
// 1) At the input start.
let candidates = core.collectCandidates(0);
expect(candidates.tokens.size, "Test 2").to.equal(3);
expect(candidates.tokens.has(ExprLexer.VAR), "Test 3").to.equal(true);
expect(candidates.tokens.has(ExprLexer.LET), "Test 4").to.equal(true);
expect(candidates.tokens.has(ExprLexer.ID), "Test 5").to.equal(true);
expect(candidates.tokens.get(ExprLexer.VAR), "Test 6").to.eql([ExprLexer.ID, ExprLexer.EQUAL]);
expect(candidates.tokens.get(ExprLexer.LET), "Test 7").to.eql([ExprLexer.ID, ExprLexer.EQUAL]);
expect(candidates.tokens.get(ExprLexer.ID), "Test 8").to.eql([]);
// 2) On the first whitespace. In real implementations you would do some additional checks where in the
// whitespace the caret is, as the outcome is different depending on that position.
candidates = core.collectCandidates(1);
expect(candidates.tokens.size, "Test 9").to.equal(1);
expect(candidates.tokens.has(ExprLexer.ID), "Test 10").to.equal(true);
// 3) On the variable name ('c').
candidates = core.collectCandidates(2);
expect(candidates.tokens.size, "Test 11").to.equal(1);
expect(candidates.tokens.has(ExprLexer.ID), "Test 12").to.equal(true);
// 4) On the equal sign (ignoring whitespace positions from now on).
candidates = core.collectCandidates(4);
expect(candidates.tokens.size, "Test 13").to.equal(1);
expect(candidates.tokens.has(ExprLexer.EQUAL), "Test 14").to.equal(true);
// 5) On the variable reference 'a'. But since we have not configure the c3 engine to return us var refs
// (or function refs for that matter) we only get an ID here.
candidates = core.collectCandidates(6);
expect(candidates.tokens.size, "Test 15").to.equal(1);
expect(candidates.tokens.has(ExprLexer.ID), "Test 16").to.equal(true);
// 6) On the '+' operator. Usually you would not show operators as candidates, but we have not set up the
// c3 engine yet to not return them.
candidates = core.collectCandidates(8);
expect(candidates.tokens.size, "Test 17").to.equal(5);
expect(candidates.tokens.has(ExprLexer.PLUS), "Test 18").to.equal(true);
expect(candidates.tokens.has(ExprLexer.MINUS), "Test 19").to.equal(true);
expect(candidates.tokens.has(ExprLexer.MULTIPLY), "Test 20").to.equal(true);
expect(candidates.tokens.has(ExprLexer.DIVIDE), "Test 21").to.equal(true);
expect(candidates.tokens.has(ExprLexer.OPEN_PAR), "Test 22").to.equal(true);
});
it("Typical setup", () => {
const inputStream = CharStreams.fromString("var c = a + b");
const lexer = new ExprLexer(inputStream);
const tokenStream = new CommonTokenStream(lexer);
const parser = new ExprParser(tokenStream);
const errorListener = new ErrorListener();
parser.addErrorListener(errorListener);
parser.expression();
expect(errorListener.errorCount, "Test 1").equals(0);
const core = new c3.CodeCompletionCore(parser);
// Ignore operators and the generic ID token.
core.ignoredTokens = new Set([
ExprLexer.ID, ExprLexer.PLUS, ExprLexer.MINUS, ExprLexer.MULTIPLY, ExprLexer.DIVIDE, ExprLexer.EQUAL,
]);
// Tell the engine to return certain rules to us, which we could use to look up values in a symbol table.
core.preferredRules = new Set([ExprParser.RULE_functionRef, ExprParser.RULE_variableRef]);
// 1) At the input start.
let candidates = core.collectCandidates(0);
expect(candidates.tokens.size, "Test 2").to.equal(2);
expect(candidates.tokens.has(ExprLexer.VAR), "Test 3").to.equal(true);
expect(candidates.tokens.has(ExprLexer.LET), "Test 4").to.equal(true);
expect(candidates.tokens.get(ExprLexer.VAR), "Test 5").to.eql([ExprLexer.ID, ExprLexer.EQUAL]);
expect(candidates.tokens.get(ExprLexer.LET), "Test 6").to.eql([ExprLexer.ID, ExprLexer.EQUAL]);
// 2) On the variable name ('c').
candidates = core.collectCandidates(2);
expect(candidates.tokens.size, "Test 7").to.equal(0);
// 4) On the equal sign.
candidates = core.collectCandidates(4);
expect(candidates.tokens.size, "Test 8").to.equal(0);
// 5) On the variable reference 'a'.
candidates = core.collectCandidates(6);
expect(candidates.tokens.size, "Test 9").to.equal(0);
expect(candidates.rules.size, "Test 10").to.equal(2);
// Here we get 2 rule indexes, derived from 2 different IDs possible at this caret position.
// These are what we told the engine above to be preferred rules for us.
expect(candidates.rules.size, "Test 11").to.equal(2);
expect(candidates.rules.get(ExprParser.RULE_functionRef)?.startTokenIndex, "Test 12").to.equal(6);
expect(candidates.rules.get(ExprParser.RULE_variableRef)?.startTokenIndex, "Test 13").to.equal(6);
// 6) On the whitespace just after the variable reference 'a' (but it could still be a function reference!)
candidates = core.collectCandidates(7);
expect(candidates.tokens.size, "Test 14").to.equal(0);
expect(candidates.rules.size, "Test 15").to.equal(1);
// Our function rule should start at the ID reference of token 'a'
expect(candidates.rules.get(ExprParser.RULE_functionRef)?.startTokenIndex, "Test 16").to.equal(6);
});
it("Recursive preferred rule", () => {
const inputStream = CharStreams.fromString("var c = a + b");
const lexer = new ExprLexer(inputStream);
const tokenStream = new CommonTokenStream(lexer);
const parser = new ExprParser(tokenStream);
const errorListener = new ErrorListener();
parser.addErrorListener(errorListener);
parser.expression();
expect(errorListener.errorCount, "Test 1").equals(0);
const core = new c3.CodeCompletionCore(parser);
// Tell the engine to return certain rules to us, which we could use to look up values in a symbol table.
core.preferredRules = new Set([ExprParser.RULE_simpleExpression]);
// 1) On the variable reference 'a'.
let candidates = core.collectCandidates(6);
expect(candidates.rules.size, "Test 2").to.equal(1);
// The start token of the simpleExpression rule begins at token 'a'
expect(candidates.rules.get(ExprParser.RULE_simpleExpression)?.startTokenIndex, "Test 3").to.equal(6);
// 2) On the variable reference 'b'.
core.translateRulesTopDown = false;
candidates = core.collectCandidates(10);
expect(candidates.rules.size, "Test 4").to.equal(1);
// When translateRulesTopDown is false, startTokenIndex should match the start token for the lower index
// (less specific) rule in the expression, which is 'a'.
expect(candidates.rules.get(ExprParser.RULE_simpleExpression)?.startTokenIndex, "Test 5").to.equal(6);
// 3) On the variable reference 'b' topDown preferred rules.
core.translateRulesTopDown = true;
candidates = core.collectCandidates(10);
expect(candidates.rules.size, "Test 6").to.equal(1);
// When translateRulesTopDown is true, startTokenIndex should match the start token for the higher index
// (more specific) rule in the expression, which is 'b'.
expect(candidates.rules.get(ExprParser.RULE_simpleExpression)?.startTokenIndex, "Test 7").to.equal(10);
});
it("Candidate rules with different start tokens", () => {
const inputStream = CharStreams.fromString("var c = a + b");
const lexer = new ExprLexer(inputStream);
const tokenStream = new CommonTokenStream(lexer);
const parser = new ExprParser(tokenStream);
const errorListener = new ErrorListener();
parser.addErrorListener(errorListener);
parser.expression();
expect(errorListener.errorCount, "Test 1").equals(0);
const core = new c3.CodeCompletionCore(parser);
// Tell the engine to return certain rules to us, which we could use to look up values in a symbol table.
core.preferredRules = new Set([ExprParser.RULE_assignment, ExprParser.RULE_variableRef]);
// Return higher index rules first, meaning we could get both assignment and variableRef rules as candidates
core.translateRulesTopDown = true;
// 1) On the token 'var'.
let candidates = core.collectCandidates(0);
expect(candidates.rules.size, "Test 2").to.equal(2);
// // The start token of the assignment and variableRef rules begin at token 'var'
expect(candidates.rules.get(ExprParser.RULE_assignment)?.startTokenIndex, "Test 3").to.equal(0);
expect(candidates.rules.get(ExprParser.RULE_variableRef)?.startTokenIndex, "Test 4").to.equal(0);
// 2) On the variable reference 'a'.
candidates = core.collectCandidates(6);
expect(candidates.rules.size, "Test 5").to.equal(2);
// The start token of the assignment rule begins at token 'var'
expect(candidates.rules.get(ExprParser.RULE_assignment)?.startTokenIndex, "Test 6").to.equal(0);
// The start token of the variableRef rule begins at token 'a'
expect(candidates.rules.get(ExprParser.RULE_variableRef)?.startTokenIndex, "Test 7").to.equal(6);
});
});
describe("C++14 parser:", () => {
it("Simple C++ example", () => {
// We are trying here to get useful code completion candidates without adjusting the grammar in any way.
// We use the grammar as downloaded from the ANTLR grammar directory and set up the c3 engine
// instead in a way that still returns useful info. This limits us somewhat.
const inputStream = CharStreams.fromString("class A {\n" +
"public:\n" +
" void test() {\n" +
" }\n" +
"};\n",
);
const lexer = new CPP14Lexer(inputStream);
const tokenStream = new CommonTokenStream(lexer);
/*
tokenStream.fill();
for (let token of tokenStream.getTokens())
console.log(token.toString());
*/
const parser = new CPP14Parser(tokenStream);
const errorListener = new ErrorListener();
parser.addErrorListener(errorListener);
parser.translationunit();
expect(errorListener.errorCount, "Test 1").equals(0);
const core = new c3.CodeCompletionCore(parser);
// Ignore operators and the generic ID token.
core.ignoredTokens = new Set([
CPP14Lexer.Identifier,
CPP14Lexer.LeftParen, CPP14Lexer.RightParen,
CPP14Lexer.Operator, CPP14Lexer.Star, CPP14Lexer.And, CPP14Lexer.AndAnd,
CPP14Lexer.LeftBracket,
CPP14Lexer.Ellipsis,
CPP14Lexer.Doublecolon, CPP14Lexer.Semi,
]);
// For a C++ grammar you can of course get many candidates of all kind. For this test we focus only on a
// few, namely namespace, class and variable references. For variable references there is no own rule, only
// an "idexpression" as part of the primary expression.
core.preferredRules = new Set([
CPP14Parser.RULE_classname, CPP14Parser.RULE_namespacename, CPP14Parser.RULE_idexpression,
]);
// 1) At the input start.
let candidates = core.collectCandidates(0);
expect(candidates.tokens.size, "Test 2").to.equal(40);
expect(candidates.tokens.has(CPP14Lexer.Extern), "Test 3").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Mutable), "Test 4").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Register), "Test 5").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Static), "Test 6").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Thread_local), "Test 7").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Decltype), "Test 8").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Char), "Test 9").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Char16), "Test 10").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Char32), "Test 11").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Wchar), "Test 12").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Bool), "Test 13").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Short), "Test 14").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Int), "Test 15").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Long), "Test 16").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Signed), "Test 17").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Unsigned), "Test 18").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Float), "Test 19").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Double), "Test 20").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Void), "Test 21").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Auto), "Test 22").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Class), "Test 23").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Struct), "Test 24").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Union), "Test 25").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Enum), "Test 26").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Typename), "Test 27").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Const), "Test 28").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Volatile), "Test 29").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Explicit), "Test 30").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Inline), "Test 31").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Virtual), "Test 32").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Friend), "Test 33").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Typedef), "Test 34").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Constexpr), "Test 35").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Alignas), "Test 36").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Asm), "Test 37").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Namespace), "Test 38").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Using), "Test 39").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Static_assert), "Test 40").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Template), "Test 41").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.EOF), "Test 42").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Identifier), "Test 43").to.equal(false);
// The returned list can contain more than one entry for a particular rule, if there are multiple
// parser rule paths leading to it.
expect(candidates.rules.size, "Test 44").to.equal(3);
expect(candidates.rules.get(CPP14Parser.RULE_namespacename)?.ruleList, "Test 45").to.eql([
CPP14Parser.RULE_translationunit,
CPP14Parser.RULE_declarationseq,
CPP14Parser.RULE_declaration,
CPP14Parser.RULE_functiondefinition,
CPP14Parser.RULE_declarator,
CPP14Parser.RULE_ptrdeclarator,
CPP14Parser.RULE_ptroperator,
CPP14Parser.RULE_nestednamespecifier,
]);
//Same as above
expect(candidates.rules.get(CPP14Parser.RULE_classname)?.ruleList, "Test 46").to.eql([
CPP14Parser.RULE_translationunit,
CPP14Parser.RULE_declarationseq,
CPP14Parser.RULE_declaration,
CPP14Parser.RULE_functiondefinition,
CPP14Parser.RULE_declarator,
CPP14Parser.RULE_ptrdeclarator,
CPP14Parser.RULE_ptroperator,
CPP14Parser.RULE_nestednamespecifier,
CPP14Parser.RULE_typename,
]);
// 2) Within the method body.
// Note when counting token indexes: the C++14 grammar skips all whitespaces,
// hence there are no tokens for them.
candidates = core.collectCandidates(10);
const idexpressionStack = [
CPP14Parser.RULE_translationunit,
CPP14Parser.RULE_declarationseq,
CPP14Parser.RULE_declaration,
CPP14Parser.RULE_functiondefinition,
CPP14Parser.RULE_declspecifierseq,
CPP14Parser.RULE_declspecifier,
CPP14Parser.RULE_typespecifier,
CPP14Parser.RULE_classspecifier,
CPP14Parser.RULE_memberspecification,
CPP14Parser.RULE_memberspecification,
CPP14Parser.RULE_memberdeclaration,
CPP14Parser.RULE_memberdeclaratorlist,
CPP14Parser.RULE_memberdeclarator,
CPP14Parser.RULE_braceorequalinitializer,
CPP14Parser.RULE_bracedinitlist,
CPP14Parser.RULE_initializerlist,
CPP14Parser.RULE_initializerclause,
CPP14Parser.RULE_assignmentexpression,
CPP14Parser.RULE_logicalorexpression,
CPP14Parser.RULE_logicalandexpression,
CPP14Parser.RULE_inclusiveorexpression,
CPP14Parser.RULE_exclusiveorexpression,
CPP14Parser.RULE_andexpression,
CPP14Parser.RULE_equalityexpression,
CPP14Parser.RULE_relationalexpression,
CPP14Parser.RULE_shiftexpression,
CPP14Parser.RULE_additiveexpression,
CPP14Parser.RULE_multiplicativeexpression,
CPP14Parser.RULE_pmexpression,
CPP14Parser.RULE_castexpression,
CPP14Parser.RULE_unaryexpression,
CPP14Parser.RULE_postfixexpression,
CPP14Parser.RULE_primaryexpression,
];
expect(candidates.rules.size, "Test 47").to.equal(3);
expect(candidates.rules.get(CPP14Parser.RULE_idexpression)?.ruleList, "Test 48").to.eql(idexpressionStack);
expect(candidates.rules.get(CPP14Parser.RULE_classname)?.ruleList, "Test 48.1").to.eql([
...idexpressionStack.slice(0, idexpressionStack.length - 1),
CPP14Parser.RULE_simpletypespecifier,
CPP14Parser.RULE_nestednamespecifier,
CPP14Parser.RULE_typename,
]);
expect(candidates.rules.get(CPP14Parser.RULE_namespacename)?.ruleList, "Test 48.2").to.eql([
...idexpressionStack.slice(0, idexpressionStack.length - 1),
CPP14Parser.RULE_simpletypespecifier,
CPP14Parser.RULE_nestednamespecifier,
]);
// We should receive more specific rules when translating top down.
core.translateRulesTopDown = true;
candidates = core.collectCandidates(10);
expect(candidates.rules.size, "Test 49").to.equal(3);
expect(candidates.rules.get(CPP14Parser.RULE_idexpression)?.ruleList, "Test 50").to.eql(idexpressionStack);
expect(candidates.rules.get(CPP14Parser.RULE_classname)?.ruleList, "Test 51").to.eql([
...idexpressionStack.slice(0, idexpressionStack.length - 1),
CPP14Parser.RULE_simpletypespecifier,
CPP14Parser.RULE_nestednamespecifier,
CPP14Parser.RULE_typename,
]);
expect(candidates.rules.get(CPP14Parser.RULE_namespacename)?.ruleList, "Test 52").to.eql([
...idexpressionStack.slice(0, idexpressionStack.length - 1),
CPP14Parser.RULE_simpletypespecifier,
CPP14Parser.RULE_nestednamespecifier,
]);
// We are starting a primary expression in a function body, so everything related to expressions and
// control flow is allowed here. We only check for a few possible keywords.
expect(candidates.tokens.size, "Test 53").to.equal(82);
expect(candidates.tokens.has(CPP14Lexer.If), "Test 54").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.This), "Test 55").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.New), "Test 56").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Case), "Test 57").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.While), "Test 58").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Throw), "Test 59").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Override), "Test 60").to.equal(false);
expect(candidates.tokens.has(CPP14Lexer.Export), "Test 61").to.equal(false);
expect(candidates.tokens.has(CPP14Lexer.Private), "Test 62").to.equal(false);
expect(candidates.tokens.has(CPP14Lexer.Protected), "Test 63").to.equal(false);
//Fixing issue #12 causes this to be included that was previously not returned
expect(candidates.tokens.has(CPP14Lexer.Decltype), "Test 64").to.equal(true);
}).timeout(5000);
it("Simple C++ example with errors in input", () => {
const inputStream = CharStreams.fromString("class A {\n" +
"public:\n" +
" void test() {\n" +
" if ()" +
" }\n" +
"};\n",
);
const lexer = new CPP14Lexer(inputStream);
const tokenStream = new CommonTokenStream(lexer);
const parser = new CPP14Parser(tokenStream);
parser.removeErrorListeners();
const errorListener = new ErrorListener();
parser.addErrorListener(errorListener);
parser.translationunit();
expect(errorListener.errorCount, "Test 1").equals(3);
const core = new c3.CodeCompletionCore(parser);
// Ignore operators and the generic ID token.
core.ignoredTokens = new Set([
CPP14Lexer.Identifier,
//CPP14Lexer.LeftParen, CPP14Lexer.RightParen, Let parentheses show up in this test
CPP14Lexer.Operator, CPP14Lexer.Star, CPP14Lexer.And, CPP14Lexer.AndAnd,
CPP14Lexer.LeftBracket,
CPP14Lexer.Ellipsis,
CPP14Lexer.Doublecolon, CPP14Lexer.Semi,
]);
core.preferredRules = new Set([
CPP14Parser.RULE_classname, CPP14Parser.RULE_namespacename, CPP14Parser.RULE_idexpression,
]);
core.showDebugOutput = false;
core.showRuleStack = false;
let candidates = core.collectCandidates(11); // At the opening parenthesis.
expect(candidates.tokens.size, "Test 2").to.equal(1);
expect(candidates.tokens.has(CPP14Lexer.LeftParen), "Test 3").to.equal(true);
// At the closing parenthesis -> again everything in an expression allowed
// (no control flow this time, though).
candidates = core.collectCandidates(12);
expect(candidates.tokens.size, "Test 4").to.equal(65);
expect(candidates.tokens.has(CPP14Lexer.If), "Test 5").to.equal(false);
expect(candidates.tokens.has(CPP14Lexer.This), "Test 6").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.New), "Test 7").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Case), "Test 8").to.equal(false);
expect(candidates.tokens.has(CPP14Lexer.While), "Test 9").to.equal(false);
expect(candidates.tokens.has(CPP14Lexer.Throw), "Test 10").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Override), "Test 11").to.equal(false);
expect(candidates.tokens.has(CPP14Lexer.Export), "Test 12").to.equal(false);
expect(candidates.tokens.has(CPP14Lexer.Private), "Test 13").to.equal(false);
expect(candidates.tokens.has(CPP14Lexer.Protected), "Test 14").to.equal(false);
//Fixing issue #12 causes this to be included that was previously not returned
expect(candidates.tokens.has(CPP14Lexer.Decltype), "Test 15").to.equal(true);
candidates = core.collectCandidates(13); // After the error position -> no suggestions.
expect(candidates.tokens.size, "Test 16").to.equal(0);
expect(candidates.rules.size, "Test 17").to.equal(0);
});
it("Real C++ file", () => {
this.slow(10000);
const source = fs.readFileSync(path.join(__dirname, "../../test/Parser.cpp")).toString();
const inputStream = CharStreams.fromString(source);
const lexer = new CPP14Lexer(inputStream);
const tokenStream = new CommonTokenStream(lexer);
/*
tokenStream.fill();
for (let token of tokenStream.getTokens())
console.log(token.toString());
*/
const parser = new CPP14Parser(tokenStream);
const errorListener = new ErrorListener();
parser.addErrorListener(errorListener);
parser.translationunit();
expect(errorListener.errorCount, "Test 1").equals(0);
const core = new c3.CodeCompletionCore(parser);
// Ignore operators and the generic ID token.
core.ignoredTokens = new Set([
CPP14Lexer.Identifier,
CPP14Lexer.LeftParen, CPP14Lexer.RightParen,
CPP14Lexer.Operator, CPP14Lexer.Star, CPP14Lexer.And, CPP14Lexer.AndAnd,
CPP14Lexer.LeftBracket,
CPP14Lexer.Ellipsis,
CPP14Lexer.Doublecolon, CPP14Lexer.Semi,
]);
core.preferredRules = new Set([
CPP14Parser.RULE_classname, CPP14Parser.RULE_namespacename, CPP14Parser.RULE_idexpression,
]);
let candidates = core.collectCandidates(3469);
const idexpressionStack = [
CPP14Parser.RULE_translationunit,
CPP14Parser.RULE_declarationseq,
CPP14Parser.RULE_declaration,
CPP14Parser.RULE_functiondefinition,
CPP14Parser.RULE_functionbody,
CPP14Parser.RULE_compoundstatement,
CPP14Parser.RULE_statementseq,
CPP14Parser.RULE_statement,
CPP14Parser.RULE_declarationstatement,
CPP14Parser.RULE_blockdeclaration,
CPP14Parser.RULE_simpledeclaration,
CPP14Parser.RULE_initdeclaratorlist,
CPP14Parser.RULE_initdeclarator,
CPP14Parser.RULE_declarator,
CPP14Parser.RULE_noptrdeclarator,
CPP14Parser.RULE_declaratorid,
];
expect(candidates.rules.size, "Test 47").to.equal(3);
expect(candidates.rules.get(CPP14Parser.RULE_idexpression)?.ruleList, "Test 48").to.eql(idexpressionStack);
// We should receive more specific rules when translating top down.
core.translateRulesTopDown = true;
candidates = core.collectCandidates(3469);
expect(candidates.rules.size, "Test 49").to.equal(3);
expect(candidates.rules.get(CPP14Parser.RULE_idexpression)?.ruleList, "Test 50").to.eql(idexpressionStack);
expect(candidates.rules.get(CPP14Parser.RULE_classname)?.ruleList, "Test 51").to.eql([
...idexpressionStack,
CPP14Parser.RULE_idexpression,
CPP14Parser.RULE_qualifiedid,
CPP14Parser.RULE_nestednamespecifier,
CPP14Parser.RULE_typename,
]);
expect(candidates.rules.get(CPP14Parser.RULE_namespacename)?.ruleList, "Test 52").to.eql([
...idexpressionStack,
CPP14Parser.RULE_idexpression,
CPP14Parser.RULE_qualifiedid,
CPP14Parser.RULE_nestednamespecifier,
]);
// We are starting a primary expression in a function body, so everything related to expressions and
// control flow is allowed here. We only check for a few possible keywords.
expect(candidates.tokens.size, "Test 53").to.equal(82);
expect(candidates.tokens.has(CPP14Lexer.If), "Test 54").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.This), "Test 55").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.New), "Test 56").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Case), "Test 57").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.While), "Test 58").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Throw), "Test 59").to.equal(true);
expect(candidates.tokens.has(CPP14Lexer.Override), "Test 60").to.equal(false);
expect(candidates.tokens.has(CPP14Lexer.Export), "Test 61").to.equal(false);
expect(candidates.tokens.has(CPP14Lexer.Private), "Test 62").to.equal(false);
expect(candidates.tokens.has(CPP14Lexer.Protected), "Test 63").to.equal(false);
// Fixing issue #12 causes this to be included that was previously not returned.
expect(candidates.tokens.has(CPP14Lexer.Decltype), "Test 64").to.equal(true);
}).timeout(60000);
});
describe("Predicated foo bar:", () => {
const inputStream = CharStreams.fromString("");
it("`bar` disabled, then enabled", () => {
{
const lexer = new PredicatedFooBarLexer(inputStream);
const tokenStream = new CommonTokenStream(lexer);
const parser = new PredicatedFooBarParser(tokenStream);
parser.nonEmptyExpression();
const core = new c3.CodeCompletionCore(parser);
// 1) At the input start.
let candidates = core.collectCandidates(0);
// delete workaround token
candidates.tokens.delete(PredicatedFooBarParser.EOF);
expect(candidates.tokens.size, "Test 1").to.equal(1);
expect(candidates.tokens.has(PredicatedFooBarParser.FOO), "Test 2").to.equal(true);
expect(candidates.tokens.has(PredicatedFooBarParser.BAR), "Test 2").to.equal(false);
}
{
const lexer = new PredicatedFooBarLexer(inputStream);
const tokenStream = new CommonTokenStream(lexer);
const parser = new PredicatedFooBarParser(tokenStream);
parser.hasBar = true; // enable the `bar`-rule
parser.nonEmptyExpression();
const core = new c3.CodeCompletionCore(parser);
// 1) At the input start.
let candidates = core.collectCandidates(0);
// delete workaround token
candidates.tokens.delete(PredicatedFooBarParser.EOF);
expect(candidates.tokens.size, "Test 1a").to.equal(2);
expect(candidates.tokens.has(PredicatedFooBarParser.FOO), "Test 2a").to.equal(true);
expect(candidates.tokens.has(PredicatedFooBarParser.BAR), "Test 2a").to.equal(true);
}
});
it("`bar` enabled, then disabled", () => {
{
const lexer = new PredicatedFooBarLexer(inputStream);
const tokenStream = new CommonTokenStream(lexer);
const parser = new PredicatedFooBarParser(tokenStream);
parser.hasBar = true; // enable the `bar`-rule
parser.nonEmptyExpression();
const core = new c3.CodeCompletionCore(parser);
// 1) At the input start.
let candidates = core.collectCandidates(0);
// delete workaround token
candidates.tokens.delete(PredicatedFooBarParser.EOF);
expect(candidates.tokens.size, "Test 1").to.equal(2);
expect(candidates.tokens.has(PredicatedFooBarParser.FOO), "Test 2").to.equal(true);
expect(candidates.tokens.has(PredicatedFooBarParser.BAR), "Test 2").to.equal(true);
}
{
const lexer = new PredicatedFooBarLexer(inputStream);
const tokenStream = new CommonTokenStream(lexer);
const parser = new PredicatedFooBarParser(tokenStream);
parser.nonEmptyExpression();
const core = new c3.CodeCompletionCore(parser);
// 1) At the input start.
let candidates = core.collectCandidates(0);
// delete workaround token
candidates.tokens.delete(PredicatedFooBarParser.EOF);
expect(candidates.tokens.size, "Test 1b").to.equal(1);
expect(candidates.tokens.has(PredicatedFooBarParser.FOO), "Test 2b").to.equal(true);
expect(candidates.tokens.has(PredicatedFooBarParser.BAR), "Test 2b").to.equal(false);
}
});
});
}); | the_stack |
import { ReferenceExpression, InstanceElement } from '@salto-io/adapter-api'
import { HUBSPOT, OBJECTS_NAMES } from '../../src/constants'
import { Types } from '../../src/transformers/transformer'
const firstFormMock = {
portalId: 6774238,
guid: '3e2e7ef3-d0d4-418f-92e0-ad40ae2b622c',
name: 'formTest1',
action: '',
method: 'POST',
cssClass: 'abc',
followUpId: 'DEPRECATED',
editable: true,
createdAt: 1571588456053,
cloneable: true,
}
const secondFormMock = {
portalId: 6774238,
guid: '123e11f3-111-418f-92e0-cwwwe2b6999',
name: 'formTest2',
action: '',
method: 'POST',
cssClass: 'css',
followUpId: 'DEPRECATED',
editable: false,
createdAt: 1561581451052,
cloneable: true,
captchaEnabled: false,
}
export const formsMockArray = [
firstFormMock,
secondFormMock,
] as unknown
export const g1PropInstance = new InstanceElement(
'g1',
Types.hubspotObjects[OBJECTS_NAMES.CONTACT_PROPERTY],
{
name: 'g1',
label: 'g1',
type: 'string',
fieldType: 'text',
description: 'g1 property',
hidden: false,
displayOrder: 1,
},
[HUBSPOT, 'records', Types.hubspotObjects[OBJECTS_NAMES.CONTACT_PROPERTY].elemID.name, 'g1'],
)
const g1PropReference = new ReferenceExpression(
g1PropInstance.elemID,
g1PropInstance,
g1PropInstance
)
export const formInstance = new InstanceElement(
'mockForm',
Types.hubspotObjects[OBJECTS_NAMES.FORM],
{
portalId: 6774238,
guid: 'guid',
name: 'formName',
action: '',
method: 'POST',
cssClass: '',
editable: true,
deletable: false,
createdAt: 1500588456053,
redirect: 'google.com',
submitText: '',
cloneable: false,
captchaEnabled: true,
formFieldGroups: [
{
fields: [
{
name: 'g1',
label: 'g1!',
type: 'string',
fieldType: 'text',
description: 'g1 property',
required: false,
hidden: false,
displayOrder: 1,
defaultValue: '',
isSmartField: false,
selectedOptions: [],
options: [],
dependentFieldFilters: [
{
filters: [
{
operator: 'EQ',
strValue: 'em@salto.io',
boolValue: false,
numberValue: 0,
strValues: [],
numberValues: [],
},
],
dependentFormField: {
name: 'date_of_birth',
label: 'Date of birth override',
type: 'string',
fieldType: 'text',
description: 'l',
groupName: 'contactinformation',
displayOrder: 1,
required: false,
selectedOptions: [],
options: [],
enabled: true,
hidden: false,
isSmartField: false,
unselectedLabel: 'unselected',
placeholder: 'place',
dependentFieldFilters: [],
labelHidden: false,
propertyObjectType: 'CONTACT',
metaData: [],
},
formFieldAction: 'DISPLAY',
},
],
},
],
default: true,
isSmartGroup: false,
},
{
fields: [
{
name: 'value',
label: 'Value',
type: 'string',
fieldType: 'text',
description: '',
required: false,
hidden: false,
defaultValue: '',
isSmartField: false,
displayOrder: 1,
selectedOptions: ['val1'],
options: [
{
label: 'opt1',
value: 'val1',
hidden: true,
readOnly: true,
},
],
},
],
default: true,
isSmartGroup: false,
},
],
ignoreCurrentValues: false,
inlineMessage: 'inline',
themeName: 'theme',
notifyRecipients: '',
},
)
export const datePropInstance = new InstanceElement(
'date_of_birth',
Types.hubspotObjects[OBJECTS_NAMES.CONTACT_PROPERTY],
{
name: 'date_of_birth',
label: 'Date of birth',
type: 'string',
fieldType: 'text',
description: 'date of birth',
hidden: false,
displayOrder: 1,
},
[HUBSPOT, 'records', Types.hubspotObjects[OBJECTS_NAMES.CONTACT_PROPERTY].elemID.name, 'date_of_birth'],
)
const datePropReference = new ReferenceExpression(
datePropInstance.elemID,
datePropInstance,
datePropInstance
)
export const valuePropInstance = new InstanceElement(
'value',
Types.hubspotObjects[OBJECTS_NAMES.CONTACT_PROPERTY],
{
name: 'value',
label: 'Value',
type: 'string',
fieldType: 'text',
description: 'value property',
hidden: false,
options: [
{
label: 'opt',
value: 'val1',
hidden: true,
readOnly: true,
},
],
displayOrder: 1,
},
[HUBSPOT, 'records', Types.hubspotObjects[OBJECTS_NAMES.CONTACT_PROPERTY].elemID.name, 'value'],
)
const valuePropReference = new ReferenceExpression(
valuePropInstance.elemID,
valuePropInstance,
valuePropInstance
)
export const beforeFormInstanceValuesMock = {
name: 'beforeUpdateInstance',
guid: 'guid',
followUpId: 'DEPRECATED',
editable: true,
cloneable: true,
captchaEnabled: false,
inlineMessage: 'inline',
redirect: 'google.com',
themeName: 'theme',
createdAt: 1500588456053,
formFieldGroups: [
{
fields: [
{
contactProperty: g1PropReference,
contactPropertyOverrides: {
label: 'g1!',
},
dependentFieldFilters: [
{
filters: [
{
operator: 'EQ',
strValue: 'em@salto.io',
boolValue: false,
numberValue: 0,
strValues: [],
numberValues: [],
},
],
dependentFormField: {
contactProperty: datePropReference,
contactPropertyOverrides: {
label: 'Date of birth override',
},
isSmartField: false,
required: false,
placeholder: 'place',
},
formFieldAction: 'DISPLAY',
},
],
},
],
default: true,
isSmartGroup: false,
},
{
fields: [
{
contactProperty: valuePropReference,
contactPropertyOverrides: {
options: [
{
label: 'opt1',
value: 'val1',
hidden: true,
readOnly: true,
},
],
},
isSmartField: false,
required: false,
selectedOptions: ['val1'],
},
],
default: true,
isSmartGroup: false,
},
],
}
export const afterFormInstanceValuesMock = {
name: 'afterUpdateInstance',
guid: 'guid',
followUpId: 'DEPRECATED',
editable: true,
cloneable: true,
captchaEnabled: false,
inlineMessage: 'inline',
redirect: 'google.com',
themeName: 'theme',
createdAt: 1500588456053,
formFieldGroups: [
{
fields: [
{
contactProperty: g1PropReference,
contactPropertyOverrides: {
label: 'g1!',
},
helpText: 'helpText',
dependentFieldFilters: [
{
filters: [
{
operator: 'EQ',
strValue: 'em@salto.io',
boolValue: false,
numberValue: 0,
strValues: [],
numberValues: [],
},
],
dependentFormField: {
contactProperty: datePropReference,
helpText: 'HELP!',
contactPropertyOverrides: {
label: 'Date of birth override',
},
isSmartField: false,
required: false,
placeholder: 'place',
},
formFieldAction: 'DISPLAY',
},
],
},
],
default: true,
isSmartGroup: false,
},
{
fields: [
{
contactProperty: valuePropReference,
contactPropertyOverrides: {
options: [
{
label: 'opt1',
value: 'val1',
hidden: true,
readOnly: true,
},
],
},
isSmartField: false,
required: false,
selectedOptions: ['val1'],
},
],
default: true,
isSmartGroup: false,
},
],
}
/**
* Workflow Mock Instances
*/
const firstWorkflowMock = {
id: 12345,
name: 'workflowTest1',
type: 'PROPERTY_ANCHOR',
unsupportedField: 'bla',
enabled: true,
insertedAt: 13423432,
updatedAt: 2423432,
internal: false,
onlyExecOnBizDays: false,
listening: true,
allowContactToTriggerMultipleTimes: true,
onlyEnrollManually: false,
enrollOnCriteriaUpdate: true,
lastUpdatedBy: 'asb@gm.il',
supressionListIds: [
1234,
1,
],
eventAnchor: {
contactPropertyAnchor: 'hs_content_membership_registered_at',
},
nurtureTimeRange: {
enabled: false,
startHour: 9,
stopHour: 10,
},
segmentCriteria: [
[
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'hs_email_domain',
value: 'gmail.com;salto.io',
},
],
[
{
filterFamily: 'CompanyPropertyValue',
withinTimeMode: 'PAST',
propertyObjectType: 'COMPANY',
operator: 'EQ',
type: 'string',
property: 'name',
value: 'Salto',
},
],
[
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'hs_email_domain',
value: 'salto.com',
},
],
],
goalCriteria: [
[
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'firstname',
value: 'Adam;Ben;Maayan',
},
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'industry',
value: 'abc',
},
],
],
actions: [
{
type: 'DELAY',
delayMillis: 0,
actionId: 170629910,
anchorSetting: {
execTimeOfDay: '11:30 AM',
execTimeInMinutes: 690,
boundary: 'ON',
},
stepId: 2,
},
{
type: 'SET_CONTACT_PROPERTY',
propertyName: 'fax',
newValue: 'abcdefg',
actionId: 170629911,
stepId: 2,
},
{
type: 'BRANCH',
actionId: 170629912,
filtersListId: 29,
stepId: 2,
acceptActions: [
{
type: 'SMS_NOTIFICATION',
staticTo: '+113455333434',
body: 'Hello world',
actionId: 170629913,
stepId: 1,
},
],
rejectActions: [
{
type: 'SMS_NOTIFICATION',
staticTo: '+113455333434',
body: 'Hello world',
actionId: 170629913,
stepId: 1,
},
],
},
],
}
const secondWorkflowMock = {
id: 123456,
name: 'workflowTest2',
type: 'PROPERTY_ANCHOR',
unsupportedField: 'bla',
enabled: true,
insertedAt: 13423432,
updatedAt: 2423432,
internal: false,
onlyExecOnBizDays: false,
listening: true,
allowContactToTriggerMultipleTimes: true,
onlyEnrollManually: false,
enrollOnCriteriaUpdate: true,
lastUpdatedBy: 'asb@gm.il',
supressionListIds: [
1234,
1,
],
eventAnchor: {
contactPropertyAnchor: 'hs_content_membership_registered_at',
},
nurtureTimeRange: {
enabled: false,
startHour: 9,
stopHour: 10,
},
segmentCriteria: [
[
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'hs_email_domain',
value: 'gmail.com;salto.io',
},
],
[
{
filterFamily: 'CompanyPropertyValue',
withinTimeMode: 'PAST',
propertyObjectType: 'COMPANY',
operator: 'EQ',
type: 'string',
property: 'name',
value: 'Salto',
},
],
[
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'hs_email_domain',
value: 'salto.com',
},
],
],
goalCriteria: [
[
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'firstname',
value: 'Adam;Ben;Maayan',
},
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'industry',
value: 'abc',
},
],
],
actions: [
{
type: 'DELAY',
delayMillis: 0,
actionId: 170629910,
anchorSetting: {
execTimeOfDay: '11:30 AM',
execTimeInMinutes: 690,
boundary: 'ON',
},
stepId: 2,
},
{
type: 'SET_CONTACT_PROPERTY',
propertyName: 'fax',
newValue: 'abcdefg',
actionId: 170629911,
stepId: 2,
},
{
type: 'BRANCH',
actionId: 170629912,
filtersListId: 29,
stepId: 2,
acceptActions: [
{
type: 'SMS_NOTIFICATION',
staticTo: '+113455333434',
body: 'Hello world',
actionId: 170629913,
stepId: 1,
},
],
rejectActions: [
{
type: 'SMS_NOTIFICATION',
staticTo: '+113455333434',
body: 'Hello world',
actionId: 170629913,
stepId: 1,
},
],
},
],
}
export const workflowsMock = {
id: 1234,
name: 'workflowTest',
type: 'PROPERTY_ANCHOR',
unsupportedField: 'bla',
enabled: true,
insertedAt: 13423432,
updatedAt: 2423432,
internal: false,
onlyExecOnBizDays: false,
listening: true,
allowContactToTriggerMultipleTimes: true,
onlyEnrollManually: false,
enrollOnCriteriaUpdate: true,
lastUpdatedBy: 'asb@gm.il',
supressionListIds: [
1234,
1,
],
eventAnchor: {
contactPropertyAnchor: 'hs_content_membership_registered_at',
},
nurtureTimeRange: {
enabled: false,
startHour: 9,
stopHour: 10,
},
segmentCriteria: [
[
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'hs_email_domain',
value: 'gmail.com;salto.io',
},
],
[
{
filterFamily: 'CompanyPropertyValue',
withinTimeMode: 'PAST',
propertyObjectType: 'COMPANY',
operator: 'EQ',
type: 'string',
property: 'name',
value: 'Salto',
},
],
[
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'hs_email_domain',
value: 'salto.com',
},
],
],
goalCriteria: [
[
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'firstname',
value: 'Adam;Ben;Maayan',
},
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'industry',
value: 'abc',
},
],
],
actions: [
{
type: 'DELAY',
delayMillis: 0,
actionId: 170629910,
anchorSetting: {
execTimeOfDay: '11:30 AM',
execTimeInMinutes: 690,
boundary: 'ON',
},
stepId: 2,
},
{
type: 'SET_CONTACT_PROPERTY',
propertyName: 'fax',
newValue: 'abcdefg',
actionId: 170629911,
stepId: 2,
},
{
type: 'BRANCH',
actionId: 170629912,
filtersListId: 29,
stepId: 2,
acceptActions: [
{
type: 'SMS_NOTIFICATION',
staticTo: '+113455333434',
body: 'Hello world',
actionId: 170629913,
stepId: 1,
},
],
rejectActions: [
{
type: 'SMS_NOTIFICATION',
staticTo: '+113455333434',
body: 'Hello world',
actionId: 170629913,
stepId: 1,
},
],
},
],
}
export const workflowsCreateResponse = {
portalId: 62515,
id: 9274658,
name: workflowsMock.name,
updatedAt: 1579426531143,
insertedAt: 1579426531213,
type: workflowsMock.type,
enabled: workflowsMock.enabled,
description: '',
contactCounts: {
active: 0,
enrolled: 0,
},
eventAnchor: {
contactPropertyAnchor: 'hs_content_membership_registered_at',
},
migrationStatus: {
portalId: 62515,
flowId: 7102706,
workflowId: 5488642,
migrationStatus: 'EXECUTION_MIGRATED',
platformOwnsActions: true,
lastSuccessfulMigrationTimestamp: null,
},
originalAuthorUserId: 215482,
creationSource: {
sourceApplication: {
source: 'WORKFLOWS_APP',
serviceName: 'https://app.hubspot.com/workflows/6962502/platform/create/new',
},
createdByUser: {
userId: 9379192,
userEmail: 'adam.rosenthal@salto.io',
},
createdAt: 1579069732474,
},
updateSource: {
sourceApplication: {
source: 'WORKFLOWS_APP',
serviceName: 'https://app.hubspot.com/workflows/6962502/platform/flow/18538464/edit/actions/enrollment/filters',
},
updatedByUser: {
userId: 9379192,
userEmail: 'adam.rosenthal@salto.io',
},
updatedAt: 1579070462059,
contactListIds: {
enrolled: 20,
active: 21,
completed: 22,
succeeded: 23,
},
},
internal: false,
onlyExecOnBizDays: false,
listening: true,
allowContactToTriggerMultipleTimes: true,
onlyEnrollManually: false,
enrollOnCriteriaUpdate: true,
lastUpdatedBy: 'asb@gm.il',
supressionListIds: [
12345,
12,
],
nurtureTimeRange: {
enabled: false,
startHour: 9,
stopHour: 10,
},
segmentCriteria: [
[
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'hs_email_domain',
value: 'gmail.com;salto.io',
},
],
[
{
filterFamily: 'CompanyPropertyValue',
withinTimeMode: 'PAST',
propertyObjectType: 'COMPANY',
operator: 'EQ',
type: 'string',
property: 'name',
value: 'Salto',
},
],
[
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'hs_email_domain',
value: 'salto.com',
},
],
],
goalCriteria: [
[
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'firstname',
value: 'Adam;Ben;Maayan',
},
{
filterFamily: 'PropertyValue',
withinTimeMode: 'PAST',
operator: 'EQ',
type: 'string',
property: 'industry',
value: 'abc',
},
],
],
actions: [
{
type: 'DELAY',
delayMillis: 0,
actionId: 170629910,
anchorSetting: {
execTimeOfDay: '11:30 AM',
execTimeInMinutes: 690,
boundary: 'ON',
},
stepId: 2,
},
{
type: 'SET_CONTACT_PROPERTY',
propertyName: 'fax',
newValue: 'abcdefg',
actionId: 170629911,
stepId: 2,
},
{
type: 'BRANCH',
actionId: 170629912,
filtersListId: 29,
stepId: 2,
acceptActions: [
{
type: 'SMS_NOTIFICATION',
staticTo: '+113455333434',
body: 'Hello world',
actionId: 170629913,
stepId: 1,
},
],
rejectActions: [
{
type: 'SMS_NOTIFICATION',
staticTo: '+113455333434',
body: 'Hello world',
actionId: 170629913,
stepId: 1,
},
],
},
],
}
export const workflowsMockArray = [
firstWorkflowMock,
secondWorkflowMock,
workflowsMock,
]
/*
* Contact Property
*/
export const contactPropertyMock = {
name: 'dropdownexample',
label: 'DropDownExample',
description: 'description',
groupName: 'contactinformation',
type: 'enumeration',
fieldType: 'select',
hidden: false,
options: [
{
description: 'desc A',
label: 'A',
hidden: false,
displayOrder: 0,
value: 'A',
},
{
description: 'desc B',
label: 'B2',
hidden: false,
displayOrder: 1,
value: 'B2',
},
{
description: 'desc C',
label: 'C22',
hidden: false,
displayOrder: 2,
value: 'C22',
},
],
deleted: false,
createdAt: 1578482459242,
formField: true,
displayOrder: -1,
readOnlyValue: false,
readOnlyDefinition: false,
mutableDefinitionNotDeletable: false,
favorited: false,
favoritedOrder: -1,
calculated: false,
externalOptions: false,
displayMode: 'current_value',
updatedAt: 1580989573781,
hasUniqueValue: false,
createdUserId: 9379192,
searchableInGlobalSearch: false,
unsupported: 'lala',
}
const firstContactPropertyMock = {
name: 'dropdownexamplefirst',
label: 'DropDownExampleFirst',
description: 'description',
groupName: 'contactinformation',
type: 'enumeration',
fieldType: 'select',
hidden: false,
options: [
{
description: 'desc A',
label: 'A',
hidden: false,
displayOrder: 0,
value: 'A First',
},
{
description: 'desc B',
label: 'B',
hidden: false,
displayOrder: 1,
value: 'B First',
},
{
description: 'desc C',
label: 'C',
hidden: false,
displayOrder: 2,
value: 'C First',
},
],
deleted: false,
createdAt: 1578482459242,
formField: true,
displayOrder: -1,
readOnlyValue: false,
readOnlyDefinition: false,
mutableDefinitionNotDeletable: false,
favorited: false,
favoritedOrder: -1,
calculated: false,
externalOptions: false,
displayMode: 'current_value',
updatedAt: 1580989573781,
hasUniqueValue: false,
createdUserId: 9379192,
searchableInGlobalSearch: false,
}
const secondContactPropertyMock = {
name: 'dropdownexampleSecond',
label: 'DropDownExampleSecond',
description: 'description',
groupName: 'contactinformation',
type: 'enumeration',
fieldType: 'select',
hidden: false,
options: [
{
description: 'desc A',
label: 'A',
hidden: false,
displayOrder: 0,
value: 'A Second',
},
{
description: 'desc B',
label: 'B',
hidden: false,
displayOrder: 1,
value: 'B Second',
},
{
description: 'desc C',
label: 'C',
hidden: false,
displayOrder: 2,
value: 'C Second',
},
],
deleted: false,
createdAt: 1578482459242,
formField: true,
displayOrder: -1,
readOnlyValue: false,
readOnlyDefinition: false,
mutableDefinitionNotDeletable: false,
favorited: false,
favoritedOrder: -1,
calculated: false,
externalOptions: false,
displayMode: 'current_value',
updatedAt: 1580989573781,
hasUniqueValue: false,
createdUserId: 9379192,
searchableInGlobalSearch: false,
}
export const contactPropertyCreateResponse = {
calculated: false,
createdAt: 1581235926150,
createdUserId: null,
currencyPropertyName: null,
deleted: false,
description: 'description',
displayMode: 'current_value',
displayOrder: -1,
externalOptions: false,
favorited: false,
favoritedOrder: -1,
fieldType: 'select',
formField: true,
groupName: 'contactinformation',
hasUniqueValue: false,
hidden: false,
hubspotDefined: null,
isCustomizedDefault: false,
label: 'DropDownExample',
mutableDefinitionNotDeletable: false,
name: 'dropdownexample',
numberDisplayHint: null,
optionSortStrategy: null,
options: [
{
description: 'desc A',
displayOrder: 0,
doubleData: null,
hidden: false,
label: 'A',
readOnly: null,
value: 'A',
},
{
description: 'desc B',
displayOrder: 1,
doubleData: null,
hidden: false,
label: 'B2',
readOnly: null,
value: 'B2',
},
{
description: 'desc C',
displayOrder: 2,
doubleData: null,
hidden: false,
label: 'C22',
readOnly: null,
value: 'C22',
},
],
optionsAreMutable: null,
readOnlyDefinition: false,
readOnlyValue: false,
referencedObjectType: null,
searchTextAnalysisMode: null,
searchableInGlobalSearch: false,
showCurrencySymbol: null,
textDisplayHint: null,
type: 'enumeration',
updatedAt: 1581235926150,
updatedUserId: null,
}
export const contactPropertyMocks = [
contactPropertyMock,
firstContactPropertyMock,
secondContactPropertyMock,
] as unknown
/**
* MarketingEmail Mock Instances
*/
const firstMarketingEmailMock = {
ab: true,
abHoursToWait: 12,
abVariation: false,
abSampleSizeDefault: 'MASTER',
abSamplingDefault: 'MASTER',
abStatus: 'MASTER',
abSuccessMetric: 'OPENS_BY_DELIVERED',
abTestId: '1234',
abTestPercentage: 40,
absoluteUrl: 'google.com',
allEmailCampaignIds: [
123,
],
analyticsPageId: '1234',
archived: false,
author: 'mail@gmail.com',
authorEmail: 'mail123@gmail.com',
authorName: 'userName',
blogEmailType: 'daily',
campaign: 'campaignID',
campaignName: 'campaignName',
clonedFrom: 1234,
createPage: false,
created: 12334567,
currentlyPublished: true,
domain: 'ynet.com',
emailBody: 'main email body',
emailNote: 'email notes',
emailType: 'AB_EMAIL',
feedbackEmailCategory: 'CUSTOM',
feedbackSurveyId: 1234,
folderId: 999,
freezeDate: 170456443,
fromName: 'sender name',
htmlTitle: 'title',
id: 111111,
isGraymailSuppressionEnabled: false,
isLocalTimezoneSend: false,
isPublished: true,
name: 'marketingEmail instance name',
authorAt: 124543,
authorUserId: 12345,
canSpamSettingsId: 67899,
flexArea: {
main: {
boxFirstElementIndex: 0,
boxLastElementIndex: 0,
boxed: false,
isSingleColumnFullWidth: false,
sections: [
{
columns: [
{
id: 'builtin_column_0-0',
widgets: ['builtin_module_0_0_0'],
width: 12,
},
],
id: 'builtin_section-0',
style: {
backgroundColor: '#EAF0F6',
backgroundType: 'CONTENT',
paddingBottom: '10px',
paddingTop: '10px',
},
},
],
},
},
isRecipientFatigueSuppressionEnabled: false,
leadFlowId: 1234,
liveDomain: 'my-website.hs-sites.com',
mailingListsExcluded: [1],
mailingListsIncluded: [2],
maxRssEntries: 5,
metaDescription: '',
pageExpirtyDate: 1234563463,
pageExpiryRedirectId: 356,
previewKey: 'abcDeGHY',
processingStatus: 'UNDEFINED',
publishDate: 12423432523,
publishedAt: 143243253253,
publishedById: 23,
publishedByName: 'John Doe',
publishImmediately: true,
publishedUrl: '',
replyTo: 'mail@gmail.com',
resolvedDomain: 'ynet.com',
rssEmailAuthorLineTemplate: 'By, ',
rssEmailNlogImageMaxWidth: 300,
rssEmailByTest: 'By',
rssEmailClickThroughText: 'Read more',
rssEmailCommentText: 'Comment',
rssEmailEntryTemplate: '',
rssEmailEntryTemplateEnabled: false,
rssEmailUrl: '',
rssToEmailTiming: {
repeats: 'daily',
// eslint-disable-next-line camelcase
repeats_on_monthly: 1,
// eslint-disable-next-line camelcase
repeats_on_weekly: 1,
time: '9:00 am',
},
slug: 'slug-23412423423',
smartEmailFields: {},
styleSettings: {
// eslint-disable-next-line camelcase
background_color: '#EAF0F6',
},
subcategory: 'blog_email',
subject: 'Subject line',
subscription: 123456,
subscriptionBlogId: 1234567890,
// eslint-disable-next-line camelcase
subscription_name: 'Default HubSpot Blog Subscription',
templatePath: 'generated_layouts/1345.html',
trasactional: false,
unpublishedAt: 0,
updated: 1230005253,
updatedById: 2,
url: 'website-url.com',
useRssHeadlineAsSubject: false,
vidsExcluded: [1234],
vidsIncluded: [12],
widgets: {
// eslint-disable-next-line camelcase
builtin_module_0_0_0: {
body: {
alignment: 'center',
// eslint-disable-next-line camelcase
hs_enable_module_padding: true,
img: {
alt: 'HubSpot logo orange',
height: 72,
src: 'https://static.hsappstatic.net/TemplateAssets/static-1.46/img/hs_default_template_images/email_dnd_template_images/company-logo-orange.png',
width: 240,
},
// eslint-disable-next-line camelcase
module_id: 1367093,
},
// eslint-disable-next-line camelcase
child_css: {},
css: {},
id: 'builtin_module_0_0_0',
// eslint-disable-next-line camelcase
module_id: 1367093,
name: 'builtin_module_0_0_0',
order: 1,
type: 'module',
},
},
workflowNames: [],
}
const secondMarketingEmailMock = {
ab: false,
abHoursToWait: 4,
abVariation: false,
abSampleSizeDefault: 'MASTER',
abSamplingDefault: 'MASTER',
abStatus: 'VARIANT',
abSuccessMetric: 'OPENS_BY_DELIVERED',
abTestId: '1234',
abTestPercentage: 30,
absoluteUrl: 'google.com',
allEmailCampaignIds: [],
analyticsPageId: '432423',
archived: false,
author: 'mail1@gmail.com',
authorEmail: 'mail13@gmail.com',
authorName: 'userNameOther',
blogEmailType: 'daily',
campaign: 'campaignID',
campaignName: 'campaignName',
clonedFrom: 1234,
createPage: true,
created: 12334567,
currentlyPublished: true,
domain: 'one.com',
emailBody: 'main body',
emailNote: 'emails notes',
emailType: 'ABC_EMAIL',
feedbackEmailCategory: 'CUSTOM',
feedbackSurveyId: 1234,
folderId: 919,
freezeDate: 170456443,
fromName: 'sender name',
htmlTitle: 'title',
id: 222222,
isGraymailSuppressionEnabled: true,
isLocalTimezoneSend: true,
isPublished: true,
name: 'marketingEmail instance2 name',
authorAt: 124543,
authorUserId: 12345,
canSpamSettingsId: 67899,
flexArea: {
main: {
boxFirstElementIndex: 0,
boxLastElementIndex: 0,
boxed: false,
isSingleColumnFullWidth: false,
sections: [
{
columns: [
{
id: 'builtin_column_0-0',
widgets: ['builtin_module_0_0_0'],
width: 12,
},
],
id: 'builtin_section-0',
style: {
backgroundColor: '#EAF0F6',
backgroundType: 'CONTENT',
paddingBottom: '10px',
paddingTop: '10px',
},
},
],
},
},
isRecipientFatigueSuppressionEnabled: false,
leadFlowId: 1234,
liveDomain: 'my-website.hs-sites.com',
mailingListsExcluded: [1],
mailingListsIncluded: [2],
maxRssEntries: 5,
metaDescription: '',
pageExpirtyDate: 1234563463,
pageExpiryRedirectId: 356,
previewKey: 'abcDeGHY',
processingStatus: 'UNDEFINED',
publishDate: 12423432523,
publishedAt: 143243253253,
publishedById: 23,
publishedByName: 'John Doe',
publishImmediately: true,
publishedUrl: '',
replyTo: 'mail@gmail.com',
resolvedDomain: 'ynet.com',
rssEmailAuthorLineTemplate: 'By, ',
rssEmailNlogImageMaxWidth: 300,
rssEmailByTest: 'By',
rssEmailClickThroughText: 'Read more',
rssEmailCommentText: 'Comment',
rssEmailEntryTemplate: '',
rssEmailEntryTemplateEnabled: false,
rssEmailUrl: '',
rssToEmailTiming: {
repeats: 'daily',
// eslint-disable-next-line camelcase
repeats_on_monthly: 1,
// eslint-disable-next-line camelcase
repeats_on_weekly: 1,
time: '9:00 am',
},
slug: 'slug-23412423423',
smartEmailFields: {},
styleSettings: {
// eslint-disable-next-line camelcase
background_color: '#EAF0F6',
},
subcategory: 'blog_email',
subject: 'Subject line 2',
subscription: 123456,
subscriptionBlogId: 1234567890,
// eslint-disable-next-line camelcase
subscription_name: 'Default HubSpot Blog Subscription',
templatePath: 'generated_layouts/1345.html',
trasactional: false,
unpublishedAt: 0,
updated: 1230005253,
updatedById: 2,
url: 'website-url.com',
useRssHeadlineAsSubject: false,
vidsExcluded: [1234],
vidsIncluded: [12],
widgets: {
// eslint-disable-next-line camelcase
builtin_module_0_0_0: {
body: {
alignment: 'center',
// eslint-disable-next-line camelcase
hs_enable_module_padding: true,
img: {
alt: 'HubSpot logo orange',
height: 72,
src: 'https://static.hsappstatic.net/TemplateAssets/static-1.46/img/hs_default_template_images/email_dnd_template_images/company-logo-orange.png',
width: 240,
},
// eslint-disable-next-line camelcase
module_id: 1367093,
},
// eslint-disable-next-line camelcase
child_css: {},
css: {},
id: 'builtin_module_0_0_0',
// eslint-disable-next-line camelcase
module_id: 1367093,
name: 'builtin_module_0_0_0',
order: 1,
type: 'module',
},
},
workflowNames: [],
}
const thirdMarketingEmailMock = {
ab: false,
abHoursToWait: 11,
abVariation: false,
abSampleSizeDefault: 'VARIANT',
abSamplingDefault: 'MASTER',
abStatus: 'VARIANT',
abSuccessMetric: 'OPENS_BY_DELIVERED',
abTestId: '6543',
abTestPercentage: 12345,
absoluteUrl: 'google.com',
allEmailCampaignIds: [],
analyticsPageId: 'email ID',
archived: false,
author: 'mail,e@gmail.com',
authorEmail: 'mail134@gmail.com',
authorName: 'userNameOther1',
blogEmailType: 'daily',
campaign: 'campaignID',
campaignName: 'campaignName',
clonedFrom: 1234,
createPage: true,
created: 12334567,
currentlyPublished: true,
domain: 'one.com',
emailBody: 'main body',
emailNote: 'emails notes',
emailType: 'ABC_EMAIL',
feedbackEmailCategory: 'CUSTOM',
feedbackSurveyId: 111,
folderId: 919,
freezeDate: 170456443,
fromName: 'sender name',
htmlTitle: 'title',
id: 973287,
isGraymailSuppressionEnabled: true,
isLocalTimezoneSend: true,
isPublished: true,
name: 'marketingEmail instance3 name',
authorAt: 124543,
authorUserId: 12345,
canSpamSettingsId: 67899,
flexArea: {
main: {
boxFirstElementIndex: 0,
boxLastElementIndex: 0,
boxed: false,
isSingleColumnFullWidth: false,
sections: [
{
columns: [
{
id: 'builtin_column_0-0',
widgets: ['builtin_module_0_0_0'],
width: 12,
},
],
id: 'builtin_section-0',
style: {
backgroundColor: '#EAF0F6',
backgroundType: 'CONTENT',
paddingBottom: '10px',
paddingTop: '10px',
},
},
],
},
},
isRecipientFatigueSuppressionEnabled: false,
leadFlowId: 1234,
liveDomain: 'my-website.hs-sites.com',
mailingListsExcluded: [1],
mailingListsIncluded: [2],
maxRssEntries: 5,
metaDescription: '',
pageExpirtyDate: 1234563463,
pageExpiryRedirectId: 356,
previewKey: 'abcDeGHY',
processingStatus: 'UNDEFINED',
publishDate: 12423432523,
publishedAt: 143243253253,
publishedById: 23,
publishedByName: 'John Doe',
publishImmediately: true,
publishedUrl: '',
replyTo: 'mail@gmail.com',
resolvedDomain: 'ynet.com',
rssEmailAuthorLineTemplate: 'By, ',
rssEmailNlogImageMaxWidth: 300,
rssEmailByTest: 'By',
rssEmailClickThroughText: 'Read more',
rssEmailCommentText: 'Comment',
rssEmailEntryTemplate: '',
rssEmailEntryTemplateEnabled: false,
rssEmailUrl: '',
rssToEmailTiming: {
repeats: 'daily',
// eslint-disable-next-line camelcase
repeats_on_monthly: 1,
// eslint-disable-next-line camelcase
repeats_on_weekly: 1,
time: '9:00 am',
},
slug: 'slug-23412423423',
smartEmailFields: {},
styleSettings: {
// eslint-disable-next-line camelcase
background_color: '#EAF0F6',
},
subcategory: 'blog_email',
subject: 'Subject line 2',
subscription: 123456,
subscriptionBlogId: 1234567890,
// eslint-disable-next-line camelcase
subscription_name: 'Default HubSpot Blog Subscription',
templatePath: 'generated_layouts/1345.html',
trasactional: false,
unpublishedAt: 0,
updated: 1230005253,
updatedById: 2,
url: 'website-url.com',
useRssHeadlineAsSubject: false,
vidsExcluded: [1234],
vidsIncluded: [12],
widgets: {
// eslint-disable-next-line camelcase
builtin_module_0_0_0: {
body: {
alignment: 'center',
// eslint-disable-next-line camelcase
hs_enable_module_padding: true,
img: {
alt: 'HubSpot logo orange',
height: 72,
src: 'https://static.hsappstatic.net/TemplateAssets/static-1.46/img/hs_default_template_images/email_dnd_template_images/company-logo-orange.png',
width: 240,
},
// eslint-disable-next-line camelcase
module_id: 1367093,
},
// eslint-disable-next-line camelcase
child_css: {},
css: {},
id: 'builtin_module_0_0_0',
// eslint-disable-next-line camelcase
module_id: 1367093,
name: 'builtin_module_0_0_0',
order: 1,
type: 'module',
},
},
workflowNames: [],
}
export const marketingEmailMock = {
name: 'newTestMarketingEmail',
ab: false,
abHoursToWait: 123,
abVariation: false,
abStatus: 'VARIANT',
archived: false,
author: 'mail,e@gmail.com',
authorEmail: 'mail134@gmail.com',
authorName: 'userNameOther1',
blogEmailType: 'daily',
campaign: 'campaignID',
campaignName: 'campaignName',
clonedFrom: 1234,
created: 12334567,
emailBody: 'main body',
emailType: 'ABC_EMAIL',
feedbackEmailCategory: 'CUSTOM',
feedbackSurveyId: 111,
folderId: 919,
freezeDate: 170456443,
fromName: 'sender name',
id: 973111,
isGraymailSuppressionEnabled: true,
isLocalTimezoneSend: true,
authorAt: 124543,
authorUserId: 12345,
canSpamSettingsId: 67899,
categoryId: 2,
contentCategoryType: 2,
flexArea: '{"main":{"boxFirstElementIndex":0,"boxLastElementIndex":0,"boxed":false,"isSingleColumnFullWidth":false,"sections":[{"columns":[{"id":"builtin_column_0-0","widgets":["builtin_module_0_0_0"],"width":12}],"id":"builtin_section-0","style":{"backgroundColor":"#EAF0F6","backgroundType":"CONTENT","paddingBottom":"10px","paddingTop":"10px"}}]}}',
isRecipientFatigueSuppressionEnabled: false,
leadFlowId: 1234,
liveDomain: 'my-website.hs-sites.com',
mailingListsExcluded: [1],
mailingListsIncluded: [2],
maxRssEntries: 5,
metaDescription: '',
pageExpirtyDate: 1234563463,
pageExpiryRedirectId: 356,
previewKey: 'abcDeGHY',
processingStatus: 'UNDEFINED',
publishDate: 12423432523,
publishedAt: 143243253253,
publishedById: 23,
publishedByName: 'John Doe',
publishImmediately: true,
publishedUrl: '',
replyTo: 'mail@gmail.com',
resolvedDomain: 'ynet.com',
rssEmailAuthorLineTemplate: 'By, ',
rssEmailNlogImageMaxWidth: 300,
rssEmailByTest: 'By',
rssEmailClickThroughText: 'Read more',
rssEmailCommentText: 'Comment',
rssEmailEntryTemplate: '',
rssEmailEntryTemplateEnabled: false,
rssEmailUrl: '',
rssToEmailTiming: {
repeats: 'daily',
// eslint-disable-next-line camelcase
repeats_on_monthly: 1,
// eslint-disable-next-line camelcase
repeats_on_weekly: 1,
time: '9:00 am',
},
slug: 'slug-23412423423',
smartEmailFields: '{}',
styleSettings: '{ "background_color": "#EAF0F6" }',
subcategory: 'blog_email',
subject: 'Subject line 2',
subscription: 123456,
subscriptionBlogId: 1234567890,
// eslint-disable-next-line camelcase
subscription_name: 'Default HubSpot Blog Subscription',
templatePath: 'generated_layouts/1345.html',
trasactional: false,
unpublishedAt: 0,
updated: 1230005253,
updatedById: 2,
url: 'website-url.com',
useRssHeadlineAsSubject: false,
vidsExcluded: [1234],
vidsIncluded: [12],
widgets: '{"builtin_module_0_0_0":{"body":{"alignment":"center","hs_enable_module_padding":true,"img":{"alt":"HubSpot logo orange","height":72,"src":"https://static.hsappstatic.net/TemplateAssets/static-1.46/img/hs_default_template_images/email_dnd_template_images/company-logo-orange.png","width":240},"module_id":1367093},"child_css":{},"css":{},"id":"builtin_module_0_0_0","module_id":1367093,"name":"builtin_module_0_0_0","order":1,"type":"module"}}',
workflowNames: [],
}
export const marketingEmailCreateResponse = {
name: 'newTestMarketingEmail',
ab: false,
abHoursToWait: 123,
abVariation: false,
abSampleSizeDefault: null,
abSamplingDefault: null,
abStatus: 'VARIANT',
archived: false,
author: 'mail,e@gmail.com',
authorEmail: 'mail134@gmail.com',
authorName: 'userNameOther1',
blogEmailType: 'daily',
campaign: 'campaignID',
campaignName: 'campaignName',
clonedFrom: 1234,
createPage: false,
created: 12334567,
currentlyPublished: false,
domain: '',
emailBody: 'main body',
emailNote: '',
emailType: 'ABC_EMAIL',
feedbackEmailCategory: 'CUSTOM',
feedbackSurveyId: 111,
folderId: 919,
freezeDate: 170456443,
fromName: 'sender name',
htmlTitle: '',
id: 1234566,
isGraymailSuppressionEnabled: true,
isLocalTimezoneSend: true,
isPublished: false,
authorAt: 124543,
authorUserId: 12345,
canSpamSettingsId: 67899,
categoryId: 2,
contentCategoryType: 2,
flexArea: {
main: {
boxFirstElementIndex: 0,
boxLastElementIndex: 0,
boxed: false,
isSingleColumnFullWidth: false,
sections: [
{
columns: [
{
id: 'builtin_column_0-0',
widgets: ['builtin_module_0_0_0'],
width: 12,
},
],
id: 'builtin_section-0',
style: {
backgroundColor: '#EAF0F6',
backgroundType: 'CONTENT',
paddingBottom: '10px',
paddingTop: '10px',
},
},
],
},
},
isRecipientFatigueSuppressionEnabled: false,
leadFlowId: 1234,
liveDomain: 'my-website.hs-sites.com',
mailingListsExcluded: [1],
mailingListsIncluded: [2],
maxRssEntries: 5,
metaDescription: '',
pageExpirtyDate: 1234563463,
pageExpiryRedirectId: 356,
previewKey: 'abcDeGHY',
processingStatus: 'UNDEFINED',
publishDate: 12423432523,
publishedAt: 143243253253,
publishedById: 23,
publishedByName: 'John Doe',
publishImmediately: true,
publishedUrl: '',
replyTo: 'mail@gmail.com',
resolvedDomain: 'ynet.com',
rssEmailAuthorLineTemplate: 'By, ',
rssEmailNlogImageMaxWidth: 300,
rssEmailByTest: 'By',
rssEmailClickThroughText: 'Read more',
rssEmailCommentText: 'Comment',
rssEmailEntryTemplate: '',
rssEmailEntryTemplateEnabled: false,
rssEmailUrl: '',
rssToEmailTiming: {
repeats: 'daily',
// eslint-disable-next-line camelcase
repeats_on_monthly: 1,
// eslint-disable-next-line camelcase
repeats_on_weekly: 1,
time: '9:00 am',
},
slug: 'slug-23412423423',
smartEmailFields: {},
styleSettings: {
// eslint-disable-next-line camelcase
background_color: '#EAF0F6',
},
subcategory: 'blog_email',
subject: 'Subject line 2',
subscription: 123456,
subscriptionBlogId: 1234567890,
// eslint-disable-next-line camelcase
subscription_name: 'Default HubSpot Blog Subscription',
templatePath: 'generated_layouts/1345.html',
trasactional: false,
unpublishedAt: 0,
updated: 1230005253,
updatedById: 2,
url: 'website-url.com',
useRssHeadlineAsSubject: false,
vidsExcluded: [1234],
vidsIncluded: [12],
widgets: {
// eslint-disable-next-line camelcase
builtin_module_0_0_0: {
body: {
alignment: 'center',
// eslint-disable-next-line camelcase
hs_enable_module_padding: true,
img: {
alt: 'HubSpot logo orange',
height: 72,
src: 'https://static.hsappstatic.net/TemplateAssets/static-1.46/img/hs_default_template_images/email_dnd_template_images/company-logo-orange.png',
width: 240,
},
// eslint-disable-next-line camelcase
module_id: 1367093,
},
// eslint-disable-next-line camelcase
child_css: {},
css: {},
id: 'builtin_module_0_0_0',
// eslint-disable-next-line camelcase
module_id: 1367093,
name: 'builtin_module_0_0_0',
order: 1,
type: 'module',
},
},
workflowNames: [],
}
export const marketingEmailMockArray = [
firstMarketingEmailMock,
secondMarketingEmailMock,
thirdMarketingEmailMock,
marketingEmailMock,
] | the_stack |
import MarkupSection, {
DEFAULT_TAG_NAME,
VALID_MARKUP_SECTION_TAGNAMES,
isMarkupSection as sectionIsMarkupSection,
} from '../models/markup-section'
import { VALID_LIST_SECTION_TAGNAMES, isListSection as sectionIsListSection } from '../models/list-section'
import { VALID_LIST_ITEM_TAGNAMES, isListItem as sectionIsListItem } from '../models/list-item'
import { LIST_SECTION_TYPE, LIST_ITEM_TYPE, MARKUP_SECTION_TYPE } from '../models/types'
import Markup, { VALID_MARKUP_TAGNAMES } from '../models/markup'
import {
getAttributes,
normalizeTagName,
isTextNode,
isCommentNode,
NODE_TYPES,
isElementNode,
} from '../utils/dom-utils'
import { any, forEach, contains } from '../utils/array-utils'
import { transformHTMLText, trimSectionText } from '../parsers/dom'
import assert, { assertType, expect } from '../utils/assert'
import PostNodeBuilder from '../models/post-node-builder'
import Section from '../models/_section'
import Marker from '../models/marker'
import Markerable, { isMarkerable } from '../models/_markerable'
import { Cloneable } from '../models/_cloneable'
const SKIPPABLE_ELEMENT_TAG_NAMES = ['style', 'head', 'title', 'meta'].map(normalizeTagName)
const NEWLINES = /\s*\n\s*/g
function sanitize(text: string) {
return text.replace(NEWLINES, ' ')
}
/**
* parses an element into a section, ignoring any non-markup
* elements contained within
* @private
*/
interface SectionParserOptions {
plugins?: SectionParserPlugin[]
}
interface SectionParserState {
section?: Cloneable<Section> | null
text?: string
markups?: Markup[]
}
interface SectionParseEnv {
addSection: (section: Cloneable<Section>) => void
addMarkerable: (marker: Marker) => void
nodeFinished(): void
}
export type SectionParserPlugin = (node: Node, builder: PostNodeBuilder, env: SectionParseEnv) => void
type SectionParserNode = HTMLElement | Text | Comment
export default class SectionParser {
builder: PostNodeBuilder
plugins: SectionParserPlugin[]
sections!: Cloneable<Section>[]
state!: SectionParserState
constructor(builder: PostNodeBuilder, options: SectionParserOptions = {}) {
this.builder = builder
this.plugins = options.plugins || []
}
parse(element: HTMLElement) {
if (this._isSkippable(element)) {
return []
}
this.sections = []
this.state = {}
this._updateStateFromElement(element)
let finished = false
// top-level text nodes will be run through parseNode later so avoid running
// the node through parserPlugins twice
if (!isTextNode(element)) {
finished = this.runPlugins(element)
}
if (!finished) {
let childNodes = isTextNode(element) ? [element] : element.childNodes
forEach(childNodes, el => {
this.parseNode(el as SectionParserNode)
})
}
this._closeCurrentSection()
return this.sections
}
runPlugins(node: Node) {
let isNodeFinished = false
let env = {
addSection: (section: Cloneable<Section>) => {
// avoid creating empty paragraphs due to wrapper elements around
// parser-plugin-handled elements
if (this.state.section && isMarkerable(this.state.section) && !this.state.section.text && !this.state.text) {
this.state.section = null
} else {
this._closeCurrentSection()
}
this.sections.push(section)
},
addMarkerable: (marker: Marker) => {
let { state } = this
let { section } = state
// if the first element doesn't create it's own state and it's plugin
// handler uses `addMarkerable` we won't have a section yet
if (!section) {
state.text = ''
state.section = this.builder.createMarkupSection(normalizeTagName('p'))
section = state.section
}
assertType<Markerable>(
'Markerables can only be appended to markup sections and list item sections',
section,
section && section.isMarkerable
)
if (state.text) {
this._createMarker()
}
section.markers.append(marker)
},
nodeFinished() {
isNodeFinished = true
},
}
for (let i = 0; i < this.plugins.length; i++) {
let plugin = this.plugins[i]
plugin(node, this.builder, env)
if (isNodeFinished) {
return true
}
}
return false
}
/* eslint-disable complexity */
parseNode(node: SectionParserNode) {
if (!this.state.section) {
this._updateStateFromElement(node)
}
let nodeFinished = this.runPlugins(node)
if (nodeFinished) {
return
}
// handle closing the current section and starting a new one if we hit a
// new-section-creating element.
if (this.state.section && isElementNode(node) && node.tagName) {
let tagName = normalizeTagName(node.tagName)
let isListSection = contains(VALID_LIST_SECTION_TAGNAMES, tagName)
let isListItem = contains(VALID_LIST_ITEM_TAGNAMES, tagName)
let isMarkupSection = contains(VALID_MARKUP_SECTION_TAGNAMES, tagName)
let isNestedListSection = isListSection && this.state.section.isListItem
let lastSection = this.sections[this.sections.length - 1]
// lists can continue after breaking out for a markup section,
// in that situation, start a new list using the same list type
if (isListItem && sectionIsMarkupSection(this.state.section)) {
this._closeCurrentSection()
this._updateStateFromElement(node.parentElement!)
}
// we can hit a list item after parsing a nested list, when that happens
// and the lists are of different types we need to make sure we switch
// the list type back
if (isListItem && lastSection && sectionIsListSection(lastSection)) {
let parentElement = expect(node.parentElement, 'expected node to have parent element')
let parentElementTagName = normalizeTagName(parentElement.tagName)
if (parentElementTagName !== lastSection.tagName) {
this._closeCurrentSection()
this._updateStateFromElement(parentElement)
}
}
// if we've broken out of a list due to nested section-level elements we
// can hit the next list item without having a list section in the current
// state. In this instance we find the parent list node and use it to
// re-initialize the state with a new list section
if (
isListItem &&
!(this.state.section.isListItem || this.state.section.isListSection) &&
!lastSection.isListSection
) {
this._closeCurrentSection()
this._updateStateFromElement(node.parentElement!)
}
// if we have consecutive list sections of different types (ul, ol) then
// ensure we close the current section and start a new one
let isNewListSection =
lastSection &&
sectionIsListSection(lastSection) &&
this.state.section.isListItem &&
isListSection &&
tagName !== lastSection.tagName
if (isNewListSection || (isListSection && !isNestedListSection) || isMarkupSection || isListItem) {
// don't break out of the list for list items that contain a single <p>.
// deals with typical case of <li><p>Text</p></li><li><p>Text</p></li>
if (
this.state.section.isListItem &&
tagName === 'p' &&
!node.nextSibling &&
contains(
VALID_LIST_ITEM_TAGNAMES,
normalizeTagName(expect(node.parentElement, 'expected node to have parent element').tagName)
)
) {
this.parseElementNode(node)
return
}
// avoid creating empty paragraphs due to wrapper elements around
// section-creating elements
if (isMarkerable(this.state.section) && !this.state.text && this.state.section.markers.length === 0) {
this.state.section = null
} else {
this._closeCurrentSection()
}
this._updateStateFromElement(node)
}
if (this.state.section && this.state.section.isListSection) {
// ensure the list section is closed and added to the sections list.
// _closeCurrentSection handles pushing list items onto the list section
this._closeCurrentSection()
forEach(node.childNodes, node => {
this.parseNode(node as SectionParserNode)
})
return
}
}
switch (node.nodeType) {
case NODE_TYPES.TEXT:
this.parseTextNode(node as Text)
break
case NODE_TYPES.ELEMENT:
this.parseElementNode(node as HTMLElement)
break
}
}
parseElementNode(element: HTMLElement) {
let { state } = this
assert('expected markups to be non-null', state.markups)
const markups = this._markupsFromElement(element)
if (markups.length && state.text!.length && isMarkerable(state.section!)) {
this._createMarker()
}
state.markups.push(...markups)
forEach(element.childNodes, node => {
this.parseNode(node as SectionParserNode)
})
if (markups.length && state.text!.length && state.section!.isMarkerable) {
// create the marker started for this node
this._createMarker()
}
// pop the current markups from the stack
state.markups.splice(-markups.length, markups.length)
}
parseTextNode(textNode: Text) {
let { state } = this
state.text += sanitize(textNode.textContent!)
}
_updateStateFromElement(element: SectionParserNode) {
if (isCommentNode(element)) {
return
}
let { state } = this
state.section = this._createSectionFromElement(element)
state.markups = this._markupsFromElement(element)
state.text = ''
}
_closeCurrentSection() {
let { sections, state } = this
let lastSection = sections[sections.length - 1]
if (!state.section) {
return
}
// close a trailing text node if it exists
if (state.text!.length && state.section.isMarkerable) {
this._createMarker()
}
// push listItems onto the listSection or add a new section
if (sectionIsListItem(state.section) && lastSection && sectionIsListSection(lastSection)) {
trimSectionText(state.section)
lastSection.items.append(state.section)
} else {
// avoid creating empty markup sections, especially useful for indented source
if (
isMarkerable(state.section) &&
!state.section.text.trim() &&
!any(state.section.markers, marker => marker.isAtom)
) {
state.section = null
state.text = ''
return
}
// remove empty list sections before creating a new section
if (lastSection && sectionIsListSection(lastSection) && lastSection.items.length === 0) {
sections.pop()
}
sections.push(state.section)
}
state.section = null
state.text = ''
}
_markupsFromElement(element: HTMLElement | Text) {
let { builder } = this
let markups: Markup[] = []
if (isTextNode(element)) {
return markups
}
const tagName = normalizeTagName(element.tagName)
if (this._isValidMarkupForElement(tagName, element)) {
markups.push(builder.createMarkup(tagName, getAttributes(element)))
}
this._markupsFromElementStyle(element).forEach(markup => markups.push(markup))
return markups
}
_isValidMarkupForElement(tagName: string, element: HTMLElement) {
if (VALID_MARKUP_TAGNAMES.indexOf(tagName) === -1) {
return false
} else if (tagName === 'b') {
// google docs add a <b style="font-weight: normal;"> that should not
// create a "b" markup
return element.style.fontWeight !== 'normal'
}
return true
}
_markupsFromElementStyle(element: HTMLElement) {
let { builder } = this
let markups: Markup[] = []
let { fontStyle, fontWeight } = element.style
if (fontStyle === 'italic') {
markups.push(builder.createMarkup('em'))
}
if (fontWeight === 'bold' || fontWeight === '700') {
markups.push(builder.createMarkup('strong'))
}
return markups
}
_createMarker() {
let { state } = this
let text = transformHTMLText(state.text!)
let marker = this.builder.createMarker(text, state.markups)
assertType<Markerable>('expected section to be markerable', state.section, isMarkerable(state.section!))
state.section.markers.append(marker)
state.text = ''
}
_getSectionDetails(element: HTMLElement | Text) {
let sectionType: string,
tagName: string,
inferredTagName = false
if (isTextNode(element)) {
tagName = DEFAULT_TAG_NAME
sectionType = MARKUP_SECTION_TYPE
inferredTagName = true
} else {
tagName = normalizeTagName(element.tagName)
// blockquote>p is valid html and should be treated as a blockquote section
// rather than a plain markup section
if (
tagName === 'p' &&
element.parentElement &&
normalizeTagName(element.parentElement.tagName) === 'blockquote'
) {
tagName = 'blockquote'
}
if (contains(VALID_LIST_SECTION_TAGNAMES, tagName)) {
sectionType = LIST_SECTION_TYPE
} else if (contains(VALID_LIST_ITEM_TAGNAMES, tagName)) {
sectionType = LIST_ITEM_TYPE
} else if (contains(VALID_MARKUP_SECTION_TAGNAMES, tagName)) {
sectionType = MARKUP_SECTION_TYPE
} else {
sectionType = MARKUP_SECTION_TYPE
tagName = DEFAULT_TAG_NAME
inferredTagName = true
}
}
return { sectionType, tagName, inferredTagName }
}
_createSectionFromElement(element: Comment | HTMLElement) {
if (isCommentNode(element)) {
return
}
let { builder } = this
let section: Cloneable<Section>
let { tagName, sectionType, inferredTagName } = this._getSectionDetails(element)
switch (sectionType) {
case LIST_SECTION_TYPE:
section = builder.createListSection(tagName)
break
case LIST_ITEM_TYPE:
section = builder.createListItem()
break
case MARKUP_SECTION_TYPE:
section = builder.createMarkupSection(tagName)
;(section as MarkupSection)._inferredTagName = inferredTagName
break
default:
assert('Cannot parse section from element', false)
}
return section
}
_isSkippable(element: Node) {
return isElementNode(element) && contains(SKIPPABLE_ELEMENT_TAG_NAMES, normalizeTagName(element.tagName))
}
} | the_stack |
import { Observable, Subscription, BehaviorSubject, fromEvent } from 'rxjs';
import { debounceTime, map, distinctUntilChanged } from 'rxjs/operators';
import { AfterContentInit, Directive, ElementRef, Input, OnDestroy, Optional } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { BooleanInput, coerceBooleanProperty } from '@angular/cdk/coercion';
import { TocHeadDirective } from './toc-head.directive';
import { tocLinkfromStaticElement } from './toc-link';
import { TOC_AREA_DIRECTIVE_TOKEN } from './toc-area.token';
const DEFAULT_OFFSET_CACHE: [number, number] = [0, 0];
const DEFAULT_SELECTOR = `h1[id]:not(.no-toc), h2[id]:not(.no-toc), h3[id]:not(.no-toc)\
, h1 > a[id].anchor, h2 > a[id].anchor, h3 > a[id].anchor`;
function isPromise<T>(value: any | Promise<T>): value is Promise<T> {
return value && typeof (<any> value).subscribe !== 'function' && typeof (value as any).then === 'function';
}
/**
* A logical container and unit of work for a table of contents.
* [[TocAreaDirective]] represents A group of [[TocHeadDirective]] and with them form an instance of
* table of contents.
*
* [[TocAreaDirective]] contains the logic for handling the behaviour, which includes
* adding/removing [[TocHeadDirective]] instances and handling scrolling to reflect the active
* link.
*
* [[TocComponent]] uses [[TocAreaDirective]] to create a UI representation of the TOC.
*
* [[TocAreaDirective]] can works in a Directive mode or in standalone mode.
*
* ## Directive mode
* In this mode, [[TocAreaDirective]] works with the [[TocHeadDirective]] directive using the
* angular DI system and collects all instances of [[TocHeadDirective]] within its scope.
* When the angular router is used, [[TocAreaDirective]] will use [[ActivatedRoute]] via DI
* to automatically detect changes to the fragment portion of the URL and will try to scroll to
* the link representing the fragment.
*
* > The HTML element H1, H2 and H3 when set with an `id` attribute (`<h1 id="4">Title</h1>`) are
* triggered by [[TocHeadDirective]], to exclude such elements add the class `no-toc`.
*
* ## Standalone mode
* In this mode, [[TocAreaDirective]] requires manual instantiation by the developer and does not
* go through the templates.
* Standalone mode provides TOC support for static HTML content where [[TocHeadDirective]] are
* manually created by searching for matching elements using the querySelector API.
* [[TocHeadDirective]] support this scenario with [[TocAreaDirective#fromElement]]
*
* To automatically scroll a header link element into view when the fragment portion of a URL has
* changed the developer needs to manually register to such notification and then use
* [[TocAreaDirective.scrollTo]] to try and scroll it into view.
* An alternative, easier way, is to initialize [[TocAreaDirective]] with an [[ActivatedRoute]]
* instance and [[TocAreaDirective]] will take care of fragment changes.
*/
@Directive({
selector: '[pblContentTocArea]',
exportAs: 'pblContentTocArea',
providers: [
{ provide: TOC_AREA_DIRECTIVE_TOKEN, useExisting: TocAreaDirective }, // We use a token to prevent circular dep warning cause TocAreaDirective is runtime-used here
]
})
export class TocAreaDirective implements AfterContentInit, OnDestroy {
@Input()
set scrollContainer(value: Element) {
this._isWindowContainer = !value;
const scrollContainer = value || window;
if (scrollContainer !== this._scrollContainer) {
if (this._scrollSubscription) {
this._scrollSubscription.unsubscribe();
}
this._scrollContainer = scrollContainer;
if (scrollContainer) {
this._scrollSubscription = fromEvent(this._scrollContainer, 'scroll')
.pipe(debounceTime(10))
.subscribe(() => this.onScroll());
}
}
}
@Input() tocTitle: string;
/**
* When true will treat the internal content as static and will query for possible links.
* Query selector can be customised in [[TocAreaDirective.selector]].
*
* > Using `staticHtmlMode` when angular renders the internal content is possible but not
* recommended. Duplicate links will register (has workaround) and order is not preserved,
* angular elements will comes before or after static elements. (before on first route rendering,
* after on 2nd route rendering [same route, different params])
*/
@Input() staticHtmlMode: boolean | Promise<any>;
/**
* The selector to use when `staticHtmlMode` is true.
* When not set default to [[TocAreaDirective#defaultSelector]]
*
* You can apply generic selector such as `a[id][name][level]` or to work in `staticHtmlMode` and
* support link elements activated by angular without duplication: `a[id][name][level]:not([ng-reflect-id])`
*/
@Input() selector: string;
readonly hasLinks: Observable<boolean>;
readonly linksChanged: Observable<TocHeadDirective[]>;
readonly activeLinkChanged: Observable<TocHeadDirective | undefined>;
private links: TocHeadDirective[] = [];
private _linksChanged$: BehaviorSubject<TocHeadDirective[]>;
private _activeLink$: BehaviorSubject<TocHeadDirective | undefined>;
private _fragmentSubscription: Subscription;
private _scrollSubscription: Subscription;
private _urlFragment = '';
private _scrollContainer: Element | Window;
private _lastHeight: number;
private _isWindowContainer: boolean;
private _offsetCache: [number, number] = DEFAULT_OFFSET_CACHE;
private _activeReInit: Promise<any>;
private get containerHeight(): number {
return this._isWindowContainer
? (<Window> this._scrollContainer).innerHeight
: (<HTMLElement> this._scrollContainer).scrollHeight;
}
/** Gets the scroll offset of the scroll container */
private get getScrollOffset(): number {
return this._isWindowContainer
? (<Window> this._scrollContainer).pageYOffset
: (<HTMLElement> this._scrollContainer).scrollTop +
(<HTMLElement> this._scrollContainer).getBoundingClientRect().top;
}
constructor(@Optional() route?: ActivatedRoute, @Optional() private elRef?: ElementRef) {
this._activeLink$ = new BehaviorSubject<TocHeadDirective | undefined>(undefined);
this._linksChanged$ = new BehaviorSubject<TocHeadDirective[]>(this.links);
this.linksChanged = this._linksChanged$.asObservable();
this.activeLinkChanged = this._activeLink$.asObservable();
this.hasLinks = this._linksChanged$.pipe(
map( links => links.length > 1 ),
distinctUntilChanged(),
);
if (route) {
this._fragmentSubscription = route.fragment.subscribe(fragment => {
this._urlFragment = fragment;
if (fragment) {
this.scrollTo(fragment);
}
});
}
}
/**
* Creates an instance of [[TocHeadDirective]] for use outside of angular.
* This will allow treating [[TocHeadDirective]] as a simple class to implement TOC on static
* HTML content using querySelector API.
* @param element
* @param tocArea
* @return {TocHeadDirective}
*/
static fromElement(element: HTMLElement, tocArea: TocAreaDirective): TocHeadDirective {
const staticLink = tocLinkfromStaticElement(element);
const tocHead = new TocHeadDirective(new ElementRef(staticLink.element), tocArea);
Object.assign(tocHead.link, staticLink.link);
tocArea.initLink(tocHead);
return tocHead;
}
ngAfterContentInit(): void {
const el: HTMLElement = this.elRef && this.elRef.nativeElement;
if (el && isPromise(this.staticHtmlMode)) {
this.staticHtmlMode.then( () => {
this.queryLinksAndAdd(el);
});
} else if (el && coerceBooleanProperty(this.staticHtmlMode)) {
this.queryLinksAndAdd(el);
}
}
reinitQueryLinks(p: Promise<any>): Promise<boolean> {
const el: HTMLElement = this.elRef && this.elRef.nativeElement;
this._activeReInit = p;
return new Promise<boolean>( (res, rej) => {
p.then( () => {
if (this._activeReInit !== p) {
return this._activeReInit;
}
this.links = [];
this.queryLinksAndAdd(el);
this._linksChanged$.next(this.links);
this._activeReInit = undefined;
return this.links.length > 1;
})
.then(res).catch(rej);
});
}
/**
* analyze link and publish links changed event
* @param tocLink
*/
initLink(tocLink: TocHeadDirective): void {
if (this._urlFragment && this._urlFragment === tocLink.link.id) {
this.scrollIntoView(tocLink);
}
this._linksChanged$.next(this.links);
}
/**
* Add the tocLink to the collection but does not analyze or publish links changed event
* @param tocLink
*/
add(tocLink: TocHeadDirective): void {
this.links.push(tocLink);
}
remove(tocLink: TocHeadDirective): void {
const linkIdx = this.links.indexOf(tocLink);
if (linkIdx > -1) {
this.links.splice(linkIdx, 1);
this._linksChanged$.next(this.links);
if (linkIdx <= this._offsetCache[1]) {
this._offsetCache = DEFAULT_OFFSET_CACHE;
}
}
}
ngOnDestroy(): void {
this._linksChanged$.complete();
this._activeLink$.complete();
if (this._fragmentSubscription) {
this._fragmentSubscription.unsubscribe();
}
if (this._scrollSubscription) {
this._scrollSubscription.unsubscribe();
}
}
/**
* Try to find a [[TocHeadDirective]] using the supplied `fragment`
* (i.e. fragment equals [[TocLink.id]]) and if found scroll it into view.
* @param fragment
*/
scrollTo(fragment: string): void {
const tocLink = this.links.find(l => l.link.id === fragment);
if (tocLink) {
this.scrollIntoView(tocLink);
}
}
private scrollIntoView(tocLink: TocHeadDirective): void {
// scroll after angular finishes rendering the page
// so resizing operation, element init expansion etc are taking into consideration
setTimeout(() => {
this._activeLink$.next(tocLink);
tocLink.scrollIntoView();
});
}
private queryLinksAndAdd(el: HTMLElement): void {
const headers = el.querySelectorAll(this.selector || DEFAULT_SELECTOR);
Array.from(headers).forEach(node => {
TocAreaDirective.fromElement(<any> node, this);
});
}
private onScroll(): void {
const height = this.containerHeight;
const scrollOffset = this.getScrollOffset;
/* We check if the height of the scroll container has changed since last scroll
If it changed we need to calculate all top positions for the links elemnts as they might
have change. A good example is an expending element that when opened or closed change the top
position for all header links below it. */
if (height !== this._lastHeight) {
let offset = scrollOffset;
// The top position of the header link DOM element contains the top section
// and the scrollOffset also contains it, we reduce one.
if (!this._isWindowContainer) {
offset -= (<HTMLElement> this._scrollContainer).getBoundingClientRect().top;
}
for (let i = 0, len = this.links.length; i < len; i++) {
this.links[i].reCalcPosition(offset);
}
// cache the height
this._lastHeight = height;
}
this.setActive(scrollOffset);
}
/**
* Set the active header link based on the scrolling offset.
* The implementation assumes linear scrolling is common so each call to setActive creates a state
* for the next call to come. The state holds the last offset and active link index.
* With the state the direction of the scroll is known, and based on the direction of scrolling
* the array of links is iterated (up/down) from that last active index.
*
* This will average iterations to O(1), when each scroll usually either doesn't change the active
* header or changes it to the next/prev header.
* @param scrollOffset
*/
private setActive(scrollOffset: number): void {
const arr = this.links;
const direction = scrollOffset >= this._offsetCache[0] ? 1 : -1;
for (let i = this._offsetCache[1]; !!arr[i]; i = i + direction) {
if (this.isLinkActive(scrollOffset, arr[i], arr[i + 1])) {
if (arr[i] !== this._activeLink$.getValue()) {
this._offsetCache = [scrollOffset, i];
this._activeLink$.next(arr[i]);
}
return;
}
}
this._offsetCache = DEFAULT_OFFSET_CACHE;
this._activeLink$.next(undefined);
}
private isLinkActive(scrollOffset: number, currentLink: TocHeadDirective, nextLink: TocHeadDirective): boolean {
// A link is considered active if the page is scrolled passed the anchor without also
// being scrolled passed the next link
return scrollOffset >= currentLink.link.top && !(nextLink && nextLink.link.top < scrollOffset);
}
static get defaultSelector(): typeof DEFAULT_SELECTOR {
return DEFAULT_SELECTOR;
}
static ngAcceptInputType_staticHtmlMode: BooleanInput;
} | the_stack |
import { getRandStr, getStoreItem, isServer, onStoreChange, setStoreItem, TUser } from '@cromwell/core';
import { useEffect } from 'react';
import { getRestApiClient } from '../api/CRestApiClient';
import { useForceUpdate } from './forceUpdate';
/**
* Common object with info about result of used operation.
*/
export type TAuthClientOperationResult = {
/**
* Available codes:
* 200 - Sing in success;
* 201 - Sing out success;
* 202 - Reset password procedure initiation success (forgot pass);
* 203 - Reset password success. Password changed in DB;
* 204 - User registration (sign up) success.
* 400 - Empty email or password (frontend validation);
* 401 - Incorrect email or password (server validation);
* 402 - Already processing another request;
* 403 - Too many requests;
* 404 - Failed to sing out;
* 405 - Empty secret code (frontend validation);
* 406 - Exceeded reset password attempts;
* 407 - Missing user credentials on user registration operation;
*/
code: number;
message: string;
success: boolean;
error?: any;
user?: TUser;
}
/**
* Wrapper around Cromwell CMS REST API for working with user authentication on frontend.
* Use it as a hook:
* ```tsx
* import { useAuthClient } from '@cromwell/core-frontend';
*
* const MyComponent = () => {
* const client = useAuthClient();
* const user = client.userInfo;
* }
* ```
*
* If you only need to track account of logged user you can use
* `useUserInfo` core hook which will your keep component updated:
* import { useUserInfo } from '@cromwell/core-frontend';
*/
class AuthClient {
/** @internal */
constructor() {
onStoreChange('userInfo', (info) => {
this?.triggerUpdateListeners();
if (!isServer() && info?.id) {
window.localStorage.setItem(this.userEverLoggedStorageKey, 'true');
}
});
}
/**
* Account of currently logged user or 'undefined' if user is not logged in.
*/
public get userInfo() {
return getStoreItem('userInfo');
}
/** @internal */
private _isLoading = false;
/**
* Has any pending API request? Client will not make any other requests until
* pending one is not resolved.
*/
public get isPending() {
return this._isLoading;
}
/** @internal */
private userEverLoggedStorageKey = 'crw_user_was_logged';
/** @internal */
private set isLoading(loading) {
this._isLoading = loading;
this.triggerUpdateListeners();
}
/** @internal */
private updateListeners: Record<string, (() => void)> = {};
/** @internal */
private triggerUpdateListeners() {
for (const listener of Object.values(this.updateListeners)) {
listener();
}
}
/** @internal */
public addOnUpdateListener(cb: (() => any)): string {
const cbId = getRandStr(8);
this.updateListeners[cbId] = cb;
return cbId;
}
/** @internal */
public removeOnUpdateListener(cbId: string) {
delete this.updateListeners[cbId];
}
/**
* Check if a user is logged in and re-store user info in global store.
*/
public async reviveAuth() {
if (!(!isServer() && !getStoreItem('userInfo')
&& window.localStorage.getItem(this.userEverLoggedStorageKey))) {
return false;
}
const user = await getRestApiClient().getUserInfo({ disableLog: true }).catch(() => null);
if (getStoreItem('userInfo')) return true;
if (!user?.id) {
window.localStorage.removeItem(this.userEverLoggedStorageKey);
return false;
}
setStoreItem('userInfo', user);
return true;
}
/**
* Perform sign in request
* @param email
* @param password
*/
public async signIn(email: string, password: string): Promise<TAuthClientOperationResult> {
if (!email || !password) return {
code: 400,
message: 'Empty email or password',
success: false,
};
if (this.isLoading) return {
code: 402,
message: 'Already processing another request',
success: false,
};
const client = getRestApiClient();
this.isLoading = true;
let result: TAuthClientOperationResult;
try {
const user = await client?.login({
email,
password,
});
if (user?.id) {
setStoreItem('userInfo', user);
result = {
code: 200,
message: 'Sign is success',
success: true,
user,
};
} else {
throw new Error('!user');
}
} catch (error: any) {
console.error(error);
let info = error?.message;
try {
info = JSON.parse(error.message)
} catch (e) { }
if (info?.statusCode === 429) {
result = {
code: 403,
message: 'To many requests',
error,
success: false
};
} else {
result = {
code: 401,
message: 'Incorrect email or password',
error,
success: false
};
}
}
this.isLoading = false;
return result;
}
/**
* Perform sign out request
*/
public async signOut(): Promise<TAuthClientOperationResult> {
if (this.isLoading) return {
code: 402,
message: 'Already processing another request',
success: false,
};
try {
await getRestApiClient()?.logOut();
if (!isServer() && window.localStorage.getItem(this.userEverLoggedStorageKey)) {
window.localStorage.removeItem(this.userEverLoggedStorageKey);
}
} catch (error) {
console.error(error);
return {
code: 404,
message: 'Failed to sing out',
error,
success: false,
};
}
setStoreItem('userInfo', undefined);
return {
code: 201,
message: 'Sing out success',
success: true,
};
}
/**
* Initiate reset password procedure. Will send an email with a secret code to use in
* `resetPassword` method
* @param email
* @returns
*/
public async forgotPassword(email: string): Promise<TAuthClientOperationResult> {
if (!email) return {
code: 400,
message: 'Empty email',
success: false,
};
if (this.isLoading) return {
code: 402,
message: 'Already processing another request',
success: false,
};
this.isLoading = true;
const client = getRestApiClient();
let result: TAuthClientOperationResult;
try {
const success = await client?.forgotPassword({ email });
if (success) {
result = {
code: 202,
message: 'Forgot password success',
success: true,
};
} else {
throw new Error('!success');
}
} catch (error: any) {
console.error(error);
let info = error?.message;
try {
info = JSON.parse(error.message)
} catch (e) { }
if (info?.statusCode === 429) {
result = {
code: 403,
message: 'To many requests',
error,
success: false
};
} else {
result = {
code: 401,
message: 'Incorrect email or password',
error,
success: false
};
}
}
this.isLoading = false;
return result;
}
/**
* Reset and change user password. Finish reset password procedure.
* @param email
* @param newPassword
* @param code - Secret code sent on user email
*/
public async resetPassword(email: string, newPassword: string, code: string): Promise<TAuthClientOperationResult> {
if (!email || !newPassword) return {
code: 400,
message: 'Empty email or password',
success: false,
};
if (!code) return {
code: 405,
message: 'Empty secret code',
success: false,
};
if (this.isLoading) return {
code: 402,
message: 'Already processing another request',
success: false,
};
this.isLoading = true;
const client = getRestApiClient();
let result: TAuthClientOperationResult;
try {
const success = await client?.resetPassword({
email,
code,
newPassword,
});
if (success) {
result = {
code: 203,
message: 'Reset password success',
success: true,
}
} else {
throw new Error('!success');
}
} catch (error: any) {
console.error(error);
let info = error?.message;
try {
info = JSON.parse(error.message)
} catch (error) { }
if (info?.statusCode === 429) {
result = {
code: 403,
message: 'To many requests',
error,
success: false
};
} else if (info?.statusCode === 417) {
result = {
code: 406,
message: 'Exceeded reset password attempts',
error,
success: false
};
} else {
result = {
code: 401,
message: 'Incorrect email or password',
error,
success: false
};
}
}
this.isLoading = false;
return result;
}
/**
* Public user registration method (sign up). User will have `customer` role.
* To create a user with another role use GraphQL client and pass full
* user (TCreateUser) input (admin auth required)
* @param email
* @param password
* @param fullName
*/
public async signUp(email: string, password: string, fullName: string): Promise<TAuthClientOperationResult> {
if (!email || !password) return {
code: 400,
message: 'Empty email or password',
success: false,
};
if (!fullName) return {
code: 406,
message: 'Empty user name',
success: false,
};
if (this.isLoading) return {
code: 402,
message: 'Already processing another request',
success: false,
};
this.isLoading = true;
const client = getRestApiClient();
let result: TAuthClientOperationResult;
try {
const user = await client?.signUp({
email,
password,
fullName,
});
if (!user?.id) {
throw new Error('!user');
}
result = {
code: 204,
message: 'User registration (sign up) success.',
success: true,
user,
}
} catch (error: any) {
console.error(error);
let info = error?.message;
try {
info = JSON.parse(error.message)
} catch (e) { }
if (info?.statusCode === 429) {
result = {
code: 403,
message: 'To many requests',
error,
success: false
};
} else {
result = {
code: 401,
message: 'Incorrect e-mail or password or e-mail already has been taken',
error,
success: false
};
}
}
this.isLoading = false;
return result;
}
}
let authClient: AuthClient;
export const getAuthClient = (): AuthClient => {
if (!authClient) authClient = new AuthClient();
return authClient;
}
export const useAuthClient = (): AuthClient => {
const update = useForceUpdate();
useEffect(() => {
const cbId = getAuthClient().addOnUpdateListener(() => update());
return () => {
getAuthClient().removeOnUpdateListener(cbId);
}
});
return getAuthClient();
} | the_stack |
import {
Msg,
TransactionalMsg,
RPCErrorResponseMsg,
ClosePluginMsg,
WindowConfigMsg,
UIConfirmRequestMsg, UIConfirmResponseMsg,
FetchRequestMsg, FetchResponseMsg,
UIInputRequestMsg, UIInputResponseMsg, isUIRangeInputRequest,
LoadScriptMsg,
UpdateSavedScriptsIndexMsg,
WorkerCreateRequestMsg, WorkerCreateResponseMsg,
WorkerMessageMsg, WorkerErrorMsg, WorkerCtrlMsg,
WorkerSetFrameMsg,
} from "../common/messages"
import * as Eval from "./eval"
import { config } from "./config"
import { resolveOrigSourcePos } from "./srcpos"
import { dlog, print } from "./util"
import { editor } from "./editor"
import { InputViewZone } from "./viewzone"
import { UIInput } from "./ui-input"
import { UIRangeInput, UIRangeInputInit } from "./ui-range"
import savedScripts from "./saved-scripts"
import * as workerTemplate from "./worker-template"
import { scriptenv } from "../figma-plugin/scriptenv"
import { UIWindow } from "./uiwindow"
import app from "./app"
// const defaultApiVersion = "1.0.0" // used when there's no specific requested version
// // try to parse version from URL query string
// export const apiVersion = (() => {
// if (document && document.location) {
// let s = document.location.search
// dlog(s)
// }
// return defaultApiVersion
// })()
export function sendMsg<T extends Msg>(msg :T, transfer? :Transferable[]) {
parent.postMessage(msg, '*', transfer)
}
export class FigmaPluginEvalRuntime implements Eval.Runtime {
send<T>(m :T) {
parent.postMessage(m, '*')
}
}
function sendWindowConfigMsg() {
let msg :WindowConfigMsg = {
type: "window-config",
width: config.windowSize[0],
height: config.windowSize[1],
}
parent.postMessage(msg, '*')
}
async function rpc_reply<T extends TransactionalMsg>(
id :string,
resType :T["type"],
f :() => Promise<Omit<T, "id"|"type">>,
) {
let reply = {}
try {
reply = await f()
parent.postMessage({ type: resType, id, ...reply }, '*')
} catch(e) {
dlog(`rpc error: ${e.stack||e}`)
let m :RPCErrorResponseMsg = {
type: "rpc-error-response",
responseType: resType,
id,
name: e.name || "Error",
message: e.message || "error",
stack: String(e.stack) || "error",
}
parent.postMessage(m, '*')
}
}
function rpc_confirm(req :UIConfirmRequestMsg) {
rpc_reply<UIConfirmResponseMsg>(req.id, "ui-confirm-response", async () => {
let answer = confirm(req.question)
return { answer }
})
}
function rpc_fetch(req :FetchRequestMsg) {
rpc_reply<FetchResponseMsg>(req.id, "fetch-response", async () => {
let r = await fetch(req.input, req.init)
let headers :Record<string,string> = {}
r.headers.forEach((v, k) => {
headers[k] = v
})
let body :Uint8Array|null = r.body ? new Uint8Array(await r.arrayBuffer()) : null
let response = {
headers,
redirected: r.redirected,
status: r.status,
statusText: r.statusText,
resType: r.type,
url: r.url,
body,
}
dlog("fetch response", response)
return response
})
}
interface ScripterWorkerI {
postMessage(message :any, transfer? :Transferable[]) :void
terminate() :void
onmessage :(this: ScripterWorkerI, ev: MessageEvent) => any
onmessageerror :(this: ScripterWorkerI, ev: MessageEvent) => any
onerror :(this: ScripterWorkerI, ev: ErrorEvent) => any
}
const iframeWorkers = new Map<MessageEventSource,IFrameWorker>()
let iframeWorkersInit = false
function worker_iframeInit() {
if (iframeWorkersInit) {
return
}
iframeWorkersInit = true
window.addEventListener('message', ev => {
let worker = iframeWorkers.get(ev.source)
//dlog("iframe supervisor got message", ev, {worker})
if (worker) {
worker._onmessage(ev)
ev.stopPropagation()
ev.preventDefault()
}
})
window.addEventListener('messageerror', ev => {
let worker = iframeWorkers.get(ev.source)
//dlog("iframe supervisor got messageerror", ev, {worker})
if (worker) {
worker.onmessageerror(ev)
ev.stopPropagation()
ev.preventDefault()
}
})
}
type ScripterWorkerIframeConfig = scriptenv.ScripterWorkerIframeConfig
class IFrameWorker implements ScripterWorkerI {
readonly workerId :string
readonly frame :HTMLIFrameElement
readonly window :UIWindow|null = null
readonly recvq :{ message :any, transfer? :Transferable[] }[] = []
readonly iframeUrl :string // non-empty when content is loaded from URL
onmessage :(this: ScripterWorkerI, ev: MessageEvent) => any
onmessageerror :(this: ScripterWorkerI, ev: MessageEvent) => any
onerror :(this: ScripterWorkerI, ev: ErrorEvent) => any
ready = false
closed = false
constructor(workerId :string, scriptBody :string, config :ScripterWorkerIframeConfig) {
// laily initialize one-time, app-wide iframe support
worker_iframeInit()
this.workerId = workerId
this.frame = document.createElement("iframe")
const frame = this.frame
// is the scriptBody really a URL?
const iframeUrl = this.iframeUrl = /^https?:\/\/[^\r\n]+$/.test(scriptBody) ? scriptBody : ""
frame.setAttribute(
"sandbox",
"allow-scripts allow-modals allow-pointer-lock" + (
// when the iframe is constructed with a script, set allow-same-origin to allow us
// to interact with the iframe's document.
// However, for security reasons, do NOT set this when the worker is loaded from an
// arbitrary URL, as the URL could be pointed to the scripter website which would
// or at least could pose a risk. Better safe than sorry :–)
iframeUrl ? "" : " allow-same-origin"
)
)
frame.onerror = err => {
this.onerror(err instanceof ErrorEvent ? err : new ErrorEvent(String(err)))
frame.onerror = null
}
// decide on size for iframe
const edbounds = window.document.getElementById("editor").getBoundingClientRect()
let width = 0, height = 0
if (config.width !== undefined) {
width = Math.round(config.width)
if (config.height !== undefined) {
// width & height provided
height = Math.round(config.height)
} else {
// only width provided; set height to same
height = config.height = width
}
} else if (config.height !== undefined) {
// only height provided; set width to same
width = height = config.width = Math.round(config.height)
} else {
// neither width nor height provided. Use percentage of viewport.
width = Math.round(edbounds.width * 0.9)
height = Math.round(width * 0.8)
}
if (config.visible) {
// visible, interactive iframe in an iframe-win container
if (config.height !== undefined) {
// add title height, since user size is requested size of the content, not window.
height += UIWindow.TitleHeight
}
let title = config.title || "Worker"
if (DEBUG) {
title += ` [Worker#${workerId} iframe#${iframeWorkers.size}]`
}
const win = new UIWindow(frame, {
x: config.x,
y: config.y,
width,
height,
title,
})
win.on("close", () => { this.close() })
frame.onload = () => {
dlog(`worker#${workerId} iframe loaded`)
// win.focus()
if (iframeUrl) {
// url-based iframes will not send __scripter_iframe_ready, so trigger onReady now
this.onReady()
} else {
// add key event handler to script iframes
try {
let doc = frame.contentWindow.document
doc.addEventListener("keydown", app.handleKeyDownEvent, {capture:true})
} catch (e) {
console.warn(`IFrameWorker error while accessing frame document: ${e.stack||e}`)
}
}
// remove handler
frame.onload = null
}
this.window = win
} else {
// hidden iframe
Object.assign(frame.style, {
position: "fixed",
zIndex: "-1",
left: "0px",
top: "0px",
width: width + "px",
height: height + "px",
visibility: "hidden",
pointerEvents: "none",
})
document.body.appendChild(frame)
if (iframeUrl) {
// url-based iframes will not send __scripter_iframe_ready, so trigger onReady now
frame.onload = () => { this.onReady() }
}
}
iframeWorkers.set(frame.contentWindow, this)
// set src to begin loading iframe
if (iframeUrl) {
frame.src = iframeUrl
} else {
let blobParts = [
`<html><head></head><body><script type='text/javascript'>`,
workerTemplate.frame[0], // generated from worker-frame-template.js
workerTemplate.worker[0], // generated from worker-template.js
JSON.stringify(scriptBody),
workerTemplate.worker[1],
workerTemplate.frame[1],,
`</script></body></html>`,
]
dlog("running worker script", blobParts.join(""))
let url = URL.createObjectURL(new Blob(blobParts, {type: "text/html;charset=utf8"} ))
frame.src = url
setTimeout(() => { URL.revokeObjectURL(url) }, 1)
}
}
onReady() {
dlog("iframe ready. recvq:", this.recvq)
// replace postMessage function
if (this.iframeUrl) {
// contentWindow.postMessage is normal iframe function
this.postMessage = (message, transfer) => {
this.frame.contentWindow.postMessage(message, "*", transfer)
}
} else {
// frame.contentWindow.postMessage is the actual postMessage function
// defined in worker-template.js -- it's API is different from the iframe one.
//
// This, because w/self/window can not be derived from and must be mutated inside worker,
// which causes the worker to replace the window.postMessage function, which is used to
// deliver messages to the worker. The __scripterPostMessage property contains a ref to the
// actual, verbatim window.postMessage function.
//
// Caution: Accessing this.frame.contentWindow when iframeUrl is not empty causes
// an exception.
const postMessage = this.frame.contentWindow["__scripterPostMessage"]
if (postMessage) {
this.postMessage = (message, transfer) => {
postMessage.call(this.frame.contentWindow, message, "*", transfer)
}
} else {
this.postMessage = (message, transfer) => {
this.frame.contentWindow.postMessage(message, "*", transfer)
}
}
}
this.ready = true
for (let { message, transfer } of this.recvq) {
this.postMessage(message, transfer)
}
this.recvq.length = 0
}
_onmessage(ev :MessageEvent) {
if (ev.data === "__scripter_iframe_ready") {
this.ready || this.onReady()
} else if (ev.data === "__scripter_iframe_close") {
// closed itself
this.terminate()
} else {
this.onmessage(ev)
}
}
postMessage(message :any, transfer? :Transferable[]) :void {
// implementation replaced by onReady()
this.recvq.push({ message, transfer })
}
close() {
worker_onclose(this.workerId)
this.terminate()
}
terminate() :void {
dlog("figma-plugin-bridge/IFrameWorker.terminate. this.closed:", this.closed)
if (this.closed) {
return
}
this.closed = true
iframeWorkers.delete(this.frame.contentWindow)
if (this.window) {
this.window.close()
} else {
this.frame.parentElement.removeChild(this.frame)
}
this.frame.src = "about:blank"
;(this as any).frame = null
}
}
function worker_createWebWorker(scriptBody :string) :ScripterWorkerI {
let blobParts = [
workerTemplate.worker[0], // generated from worker-template.js
scriptBody,
workerTemplate.worker[1]
]
let workerURL = URL.createObjectURL(new Blob(blobParts, {type: "application/javascript"} ))
let worker = new Worker(workerURL)
URL.revokeObjectURL(workerURL)
return worker as any as ScripterWorkerI
}
let workerIdGen = 0
let workers = new Map<string,ScripterWorkerI>()
function rpc_worker_create(req :WorkerCreateRequestMsg) {
rpc_reply<WorkerCreateResponseMsg>(req.id, "worker-create-res", async () => {
dlog("rpc_worker_create", req)
let workerId = req.workerId
let worker :ScripterWorkerI
if (req.iframe) {
// launch an iframe-based worker
let config :ScripterWorkerIframeConfig = typeof req.iframe == "object" ? req.iframe : {}
worker = new IFrameWorker(workerId, req.js, config)
} else {
worker = worker_createWebWorker(req.js)
}
workers.set(workerId, worker)
// forward messages to the plugin process
worker.onmessage = ev => {
dlog(`app got message from worker#${workerId}`, ev.data)
let d = ev.data.data
if (d && typeof d == "object") {
const type = d.type
if (type == "__scripter_close") {
return worker_onclose(workerId)
} else if (type == "__scripter_toplevel_err") {
let stack = d.stack
if (stack != "") {
stack = stack.replace(/\sblob:.+:(\d+):(\d+)/g, " <worker-script>:$1:$2")
}
sendMsg<WorkerErrorMsg>({ type: "worker-error", workerId, error: {
error: d.message,
message: stack || d.message,
} })
worker.terminate()
return worker_onclose(workerId)
}
}
sendMsg<WorkerMessageMsg>({
type: "worker-message",
evtype: "message",
workerId,
data: ev.data.data,
transfer: ev.data.transfer,
}, ev.data.transfer)
}
worker.onmessageerror = (ev :MessageEvent) => {
sendMsg<WorkerMessageMsg>({
type: "worker-message",
evtype: "messageerror",
workerId,
data: ev.data,
})
}
worker.onerror = (ev :ErrorEvent) => {
console.error("worker error event", ev)
worker.terminate()
sendMsg<WorkerErrorMsg>({ type: "worker-error", workerId, error: {
colno: ev.colno,
error: String(ev.error),
filename: ev.filename,
lineno: ev.lineno,
message: ev.message,
} })
worker_onclose(workerId)
}
return {
workerId,
}
})
}
function worker_onclose(workerId :string) {
dlog("worker_onclose", workerId)
if (workers.has(workerId)) {
dlog("worker_onclose", workerId, "FOUND")
workers.delete(workerId)
sendMsg<WorkerCtrlMsg>({
type: "worker-ctrl",
workerId,
signal: "close",
})
}
}
function worker_get(msg :{ workerId :string }) : ScripterWorkerI | null {
let worker = workers.get(msg.workerId)
if (!worker) {
// this happens naturally for close & terminate messages, as close & terminate
// are naturally racey.
dlog(`ignoring message for non-existing worker#${msg.workerId||""}`, {msg})
return null
}
return worker
}
function worker_postMessage(msg :WorkerMessageMsg) {
let worker = worker_get(msg)
if (!worker) { return }
worker.postMessage(msg.data, msg.transfer)
}
function worker_ctrl(msg :WorkerCtrlMsg) {
// "terminate" is currently the only supported signal
if (msg.signal != "terminate") {
console.warn(`worker_ctrl unexpected signal ${msg.signal}`)
return
}
let worker = worker_get(msg)
if (!worker) { return }
worker.terminate()
worker_onclose(msg.workerId)
}
function worker_setFrame(msg :WorkerSetFrameMsg) {
let worker = worker_get(msg) as IFrameWorker
if (!worker) { return }
worker.window!.setBounds(msg.x, msg.y, msg.width, msg.height)
}
function createUIInput(msg :UIInputRequestMsg) :UIInput {
if (isUIRangeInputRequest(msg)) {
if (msg.init && "value" in msg.init) {
let v = msg.init.value
if (typeof v != "number") {
v = parseFloat(v)
if (isNaN(v)) {
delete msg.init.value
} else {
msg.init.value = v
}
}
}
return new UIRangeInput(msg.init)
} else {
throw new Error(`unknown input type "${msg.controllerType}"`)
}
}
let uiInputInstances = new Map<string,InputViewZone>()
function rpc_ui_input(msg :UIInputRequestMsg) {
rpc_reply<UIInputResponseMsg>(msg.id, "ui-input-response", async () => {
let viewZone = uiInputInstances.get(msg.instanceId)
if (!viewZone) {
let pos = msg.srcPos as SourcePos
if (pos.line == 0) {
dlog("[rpc ui-input-response]: ignoring; zero srcPos", msg)
return { value: 0, done: true }
}
let sourceMapJson = Eval.getSourceMapForRequest(msg.scriptReqId)
if (!sourceMapJson) {
throw new Error("no source map found for script invocation #" + msg.scriptReqId)
}
pos = await resolveOrigSourcePos(pos, msg.srcLineOffset, sourceMapJson)
if (!pos.line) {
return { value: 0, done: true }
}
// DISABLED: replacing view zone can lead to infinite loops
// viewZone = editor.viewZones.get(pos) as InputViewZone|null
// if (viewZone && !((viewZone as any) instanceof InputViewZone)) {
// // replace other view zone on same line
// viewZone.removeFromEditor()
// viewZone = null
// }
let input = createUIInput(msg)
viewZone = new InputViewZone(pos.line, input)
if (editor.viewZones.add(viewZone) == "") {
// existing view zone conflict
return { value: input.value, done: true }
}
// associate instanceId with the new viewZone
uiInputInstances.set(msg.instanceId, viewZone)
viewZone.addListener("remove", () => {
// Note: view zone cleans up all listeners after the remove event,
// so no need for us to removeListener here.
uiInputInstances.delete(msg.instanceId)
})
}
// else if (viewZone.nextResolver) {
// console.warn("[scripter/rpc_ui_input] enqueueResolver while this.nextResolver != null", {
// instanceId: msg.instanceId,
// })
// }
return new Promise(resolve => {
viewZone.enqueueResolver(resolve)
})
})
}
export function start() {
// signal to plugin that we are ready
parent.postMessage({ type: "ui-init" }, '*')
sendWindowConfigMsg()
}
export function init() {
let runtime = new FigmaPluginEvalRuntime()
let messageHandler = Eval.setRuntime(runtime)
window.onmessage = ev => {
if (ev.source !== parent) {
// message is not from the Figma plugin
return
}
let msg = ev.data
if (msg && typeof msg == "object") {
switch (msg.type) {
case "eval-response":
case "print":
messageHandler(msg)
break
case "ui-confirm":
rpc_confirm(msg as UIConfirmRequestMsg)
break
case "fetch-request":
rpc_fetch(msg as FetchRequestMsg)
break
case "ui-input-request":
rpc_ui_input(msg as UIInputRequestMsg)
// return // return to avoid logging these high-frequency messages
break
case "worker-create-req":
rpc_worker_create(msg as WorkerCreateRequestMsg)
break
case "worker-message":
worker_postMessage(msg as WorkerMessageMsg)
break
case "worker-ctrl":
worker_ctrl(msg as WorkerCtrlMsg)
break
case "worker-setFrame":
worker_setFrame(msg as WorkerSetFrameMsg)
break
case "load-script":
editor.loadScriptFromFigma(msg as LoadScriptMsg)
break
case "update-save-scripts-index":
savedScripts.updateFromPlugin((msg as UpdateSavedScriptsIndexMsg).index)
break
}
}
// if (DEBUG) {
// let data2 :any = ev.data
// if (ev.data && typeof ev.data == "object") {
// data2 = {}
// for (let k of Object.keys(ev.data)) {
// let v = ev.data[k]
// if (v && typeof v == "object" && v.buffer instanceof ArrayBuffer) {
// v = `[${v.constructor.name} ${v.length}]`
// } else if (v instanceof ArrayBuffer) {
// v = `[ArrayBuffer ${v.byteLength}]`
// }
// data2[k] = v
// }
// }
// dlog("ui received message", JSON.stringify({ origin: ev.origin, data: data2 }, null," "))
// }
// Note: Unknown messages are legitimate as they are sent by other parts of the
// app, like for instance Monaco. It's important we let them be and let them bubble.
dlog("ui received message", ev.data && ev.data.type, { origin: ev.origin, data: ev.data })
}
// hook up config event observation
config.on("change", ev => {
if (ev.key == "windowSize") {
sendWindowConfigMsg()
}
})
// handle ESC-ESC to close
let lastEscapeKeypress = 0
// escapeToCloseThreshold
// When ESC is pressed at least twice within this time window, the plugin closes.
const escapeToCloseThreshold = 150
let isClosing = false
function closePlugin() {
if (isClosing) {
return
}
isClosing = true
let sendCloseSignal = () => {
runtime.send<ClosePluginMsg>({type:"close-plugin"})
}
if (editor.isScriptRunning()) {
// stop the running script and give it a few milliseconds to finish
editor.stopCurrentScript()
setTimeout(sendCloseSignal, 50)
} else {
sendCloseSignal()
}
}
app.addKeyEventHandler(ev => {
// Note: Rest of app key bindings are in app.ts
if (ev.code == "KeyP" && (ev.metaKey || ev.ctrlKey) && ev.altKey) {
// meta-alt-P
closePlugin()
return true
}
})
} | the_stack |
import { err, ERROR } from "../errors";
import type { Component } from "./Component";
import { ManagedList } from "./ManagedList";
import { logUnhandledException } from "./UnhandledErrorEmitter";
import { HIDDEN } from "./util";
import { formatValue } from "./format";
import { I18nString } from "./I18nService";
/** Running ID for new `Binding` instances */
let _nextBindingUID = 16;
/** Definition of a reader instance that provides a bound value */
interface BoundReader {
readonly boundParent: Component;
getValue(hint?: any): any;
}
/**
* Component property binding base class.
* Bindings should be created using the `bind` and `bindf` functions, and used as a property of the object passed to `Component.with`.
*/
export class Binding {
/** Returns true if given value is an instance of `Binding` */
static isBinding(value: any): value is Binding {
return !!(value && value.isComponentBinding && value instanceof Binding);
}
/** Create a new binding for given property and default value. See `bind`. */
constructor(source?: string, defaultValue?: any) {
let path: string[] | undefined;
let propertyName = source !== undefined ? String(source) : undefined;
if (propertyName) this._source = source;
// parse property name, path, and filters
if (propertyName !== undefined) {
let parts = String(propertyName).split("|");
path = parts.shift()!.split(".");
propertyName = path.shift()!;
while (propertyName[0] === "!") {
propertyName = propertyName.slice(1);
this.addFilter("!");
}
if (!path.length) path = undefined;
for (let part of parts) this.addFilter(part);
}
this.propertyName = propertyName;
// create a reader class that provides a value getter
let self = this;
this.Reader = class {
/** Create a new reader, linked to given bound parent */
constructor(public readonly boundParent: Component) {}
/** The current (filtered) value for this binding */
getValue(propertyHint?: any) {
let result =
arguments.length > 0
? propertyHint
: propertyName !== undefined
? (this.boundParent as any)[propertyName]
: undefined;
// find nested properties
if (path) {
for (let i = 0; i < path.length && result != undefined; i++) {
let p = path[i] as string;
if (
typeof result === "object" &&
!(p in result) &&
typeof result.get === "function"
) {
result = result.get(p);
} else {
result = result[p];
}
}
}
// return filtered result
if (self._filter) {
result = self._filter(result, this.boundParent);
}
return result === undefined && defaultValue !== undefined ? defaultValue : result;
}
};
}
/** Method for duck typing, always returns true */
isComponentBinding(): true {
return true;
}
/** Unique ID for this binding */
readonly id = HIDDEN.BINDING_ID_PREFIX + _nextBindingUID++;
/** @internal Constructor for a reader, that reads current bound and filtered values */
Reader: new (boundParent: Component) => BoundReader;
/** Name of the property that should be observed for this binding (highest level only, does not include names of nested properties or keys) */
readonly propertyName?: string;
/** Nested bindings, if any (e.g. for string format bindings, see `bindf`) */
get bindings() {
return this._bindings as ReadonlyArray<Binding>;
}
/** @internal */
protected _bindings?: Binding[];
/** Parent binding, if any (e.g. for nested bindings in string format bindings) */
parent?: Binding;
/**
* Add a filter to this binding, which transforms values to a specific type or format, optionally localized using the currently registered `I18nService`. Filters can be chained by adding multiple filters in order of execution.
* The argument may be any of the format placeholders that are available for `strf`, except for comments and plural forms -- without the leading `%` sign or grouping `{` and `}`, e.g. `s`, `+8i`, `.5f`, `?`, and `local:date`.
* @note Filters can also be specified after the `|` (pipe) separator in string argument given to the `Binding` constructor, or `bind` function.
*/
addFilter(fmt: string) {
fmt = String(fmt).trim();
// store new chained filter
let oldFilter = this._filter;
this._filter = (v, boundParent) => {
if (oldFilter) v = oldFilter(v, boundParent);
return formatValue(fmt, v);
};
return this;
}
/** Add a boolean transform to this binding: use the given value _instead_ of the bound value if that is equal to true (according to the `==` operator) */
then(trueValue: any) {
// store new chained filter
let oldFilter = this._filter;
this._filter = (v, boundParent) => {
if (oldFilter) v = oldFilter(v, boundParent);
return v ? trueValue : v;
};
return this;
}
/**
* Add a boolean transform to this binding: use the given value _instead_ of the bound value if that is equal to false (according to the `==` operator)
* @note Alternatively, use the `defaultValue` argument to `bind()` to specify a default value without an extra step.
*/
else(falseValue: any) {
// store new chained filter
let oldFilter = this._filter;
this._filter = (v, boundParent) => {
if (oldFilter) v = oldFilter(v, boundParent);
return v ? v : falseValue;
};
return this;
}
/** Add a filter to this binding to compare the bound value to the given value(s), the result is always either `true` (at least one match) or `false` (none match) */
match(...values: any[]) {
let oldFilter = this._filter;
this._filter = (v, boundParent) => {
if (oldFilter) v = oldFilter(v, boundParent);
return values.some(w => w === v);
};
return this;
}
/** Add a filter to this binding to compare the bound value to the given value(s), the result is always either `true` (none match) or `false` (at least one match) */
nonMatch(...values: any[]) {
let oldFilter = this._filter;
this._filter = (v, boundParent) => {
if (oldFilter) v = oldFilter(v, boundParent);
return !values.some(w => w === v);
};
return this;
}
/**
* Add an 'and' term to this binding (i.e. logical and, like `&&` operator).
* @note The combined binding can only be bound to a single component, e.g. within a list view cell, bindings targeting both the list element and the activity can **not** be combined using this method.
*/
and(source: Binding): this;
and(source: string, defaultValue?: any): this;
and(source: string | Binding, defaultValue?: any) {
let binding = source instanceof Binding ? source : new Binding(source, defaultValue);
binding.parent = this;
if (this._source) this._source += " and " + String(source);
if (!this._bindings) this._bindings = [];
this._bindings.push(binding);
// add filter to get value from binding and AND together
let oldFilter = this._filter;
this._filter = (v, boundParent) => {
if (oldFilter) v = oldFilter(v, boundParent);
let bound = boundParent.getBoundBinding(binding);
if (!bound) throw err(ERROR.Binding_NotFound, this.toString());
return v && bound.value;
};
return this;
}
/**
* Add an 'or' term to this binding (i.e. logical or, like `||` operator).
* @note The combined binding can only be bound to a single component, e.g. within a list view cell, bindings targeting both the list element and the activity can **not** be combined using this method.
*/
or(source: Binding): this;
or(source: string, defaultValue?: any): this;
or(source: string | Binding, defaultValue?: any) {
let binding = source instanceof Binding ? source : new Binding(source, defaultValue);
binding.parent = this;
if (this._source) this._source += " or " + String(source);
if (!this._bindings) this._bindings = [];
this._bindings.push(binding);
// add filter to get value from binding and AND together
let oldFilter = this._filter;
this._filter = (v, boundParent) => {
if (oldFilter) v = oldFilter(v, boundParent);
let bound = boundParent.getBoundBinding(binding);
if (!bound) throw err(ERROR.Binding_NotFound, this.toString());
return v || bound.value;
};
return this;
}
/** Log a message to the console whenever the value of this binding changes, for debugging purposes */
debuggerLog() {
let oldFilter = this._filter;
this._filter = (v, boundParent) => {
if (oldFilter) v = oldFilter(v, boundParent);
console.log("--- ", this.toString(), v);
return v;
};
return this;
}
/** Return a string representation of this binding, for error messages and debug logging */
toString() {
return "bind(" + (this._source || "") + ")";
}
/** Chained filter function, if any */
private _filter?: (v: any, boundParent: Component) => any;
/** Binding source text */
private _source?: string;
}
/**
* Represents a set of bindings (see `Binding`) that are compiled into a single string value.
* @note Use the `bindf` function to create instances of this class.
*/
export class StringFormatBinding extends Binding {
/** Create a new binding for given format string and bindings. See `bindf`. */
constructor(format: string, ...args: Array<string | Binding>) {
super(undefined);
this._format = format;
// add bindings that are specified inline as ${...}
if (!args.length) {
format = String(format).replace(/\$\{[^}]+\}/g, s => {
args.push(s.slice(2, -1));
return "%s";
});
}
// store bindings for use by component constructor
let bindings = (this._bindings = args.map(a => {
let binding = a instanceof Binding ? a : new Binding(a);
binding.parent = this;
return binding;
}));
// amend reader to get values from bindings and compile text
this.Reader = class extends this.Reader {
constructor(boundParent: Component) {
super(boundParent);
this.i18nString = new I18nString(format);
}
i18nString: I18nString;
getValue() {
// take values for all bindings first
let values = bindings.map((binding, i) => {
let bound = this.boundParent.getBoundBinding(binding);
if (!bound) throw err(ERROR.Binding_NotFound, args[i]);
return bound.value;
});
// use I18nString to format string with values
let result = this.i18nString.update(values).toString();
return super.getValue(result);
}
};
}
private _format: string;
toString() {
return "bindf(" + JSON.stringify(this._format) + ")";
}
}
export namespace Binding {
/** Binding type (duck typed) */
export interface Type {
isComponentBinding(): true;
}
/**
* @internal A list of components that are actively bound to a specific binding. Also includes a method to update the value on all components, using the `Component.updateBoundValue` method.
*/
export class Bound extends ManagedList<Component> {
/** Create a new bound instance for given binding and its currently bound parent component */
constructor(public binding: Binding, boundParent: Component) {
super();
if (binding.parent) {
// find bound parent first
let parent = boundParent.getBoundBinding(binding.parent);
if (!parent) throw err(ERROR.Binding_ParentNotFound);
this.parent = parent;
}
// set own properties
this.propertyName = binding.propertyName;
this._reader = new binding.Reader(boundParent);
}
/** Bound parent binding */
readonly parent?: Bound;
/** Bound property name (highest level only, same as `Binding.propertyName`) */
readonly propertyName?: string;
/** Returns true if there already is an actively bound value */
hasValue() {
return !!this._updatedValue;
}
/** The current bound value, taken from the bound parent component (or cached) */
get value() {
// use existing value, or get a value from the reader
return this._updatedValue ? this._lastValue : this._reader.getValue();
}
/** Update all components in the list with a new value. The current value of the source property (i.e. using `Binding.propertyName`) may be passed in if it is already known. */
updateComponents(_v?: any) {
if (!this.count && !this.parent) {
// do not update, invalidate stored value
this._updatedValue = false;
return;
}
// get a new value and check if an update is even necessary
let value = this._reader.getValue(...arguments); // _v if given
if (!this._updatedValue || this._lastValue !== value) {
this._updatedValue = true;
let oldValue = this._lastValue;
this._lastValue = value;
if (this.parent) {
// update parent instead
this.parent.updateComponents();
return;
}
// go through all components and update the bound value
let id = this.binding.id;
this.forEach((component: any) => {
try {
if (typeof component[id] !== "function") {
throw err(ERROR.Binding_NoComponent);
}
component[id](value, oldValue);
} catch (err) {
logUnhandledException(err);
}
});
}
}
/** True if stored value is up to date */
private _updatedValue?: boolean;
private _reader: InstanceType<Binding["Reader"]>;
private _lastValue: any;
}
}
/**
* Returns a new binding, which can be used as a component preset (see `Component.with`) to update components dynamically with the value of an observed property on the bound parent component, such as the `AppActivity` for a view, the `Application` for an activity, or the `ViewComponent` for nested views.
*
* The bound property name is specified using the first argument. Nested properties are allowed (e.g. `foo.bar`), but _only_ the first property will be observed.
*
* If a nested property does not exist, but a `get` method does (e.g. `ManagedMap.get()`), then this method is called with the property name as its only argument, and the resulting value used as the bound value.
*
* The property name may be appended with a `|` (pipe) character and a *filter* name: see `Binding.addFilter` for available filters. Multiple filters may be chained together if their names are separated with more pipe characters.
*
* For convenience, `!property` is automatically rewritten as `property|!` to negate property values, and `!!property` to convert any value to a boolean value.
*
* A default value may also be specified. This value is used when the bound value itself is undefined.
*/
export function bind(propertyName?: string, defaultValue?: any) {
return new Binding(propertyName, defaultValue);
}
/**
* Returns a new binding, which can be used as a component preset (see `Component.with`) to update components dynamically with a string that includes property values from the bound parent component, such as the `AppActivity` for a view, the `Application` for an activity, or the `ViewComponent` for nested views.
*
* The format string may contain placeholders for bound values; as soon as the value of a binding changes, the formatted string is also updated. Bindings are specified as strings, in the same format as the argument to `bind()`, using parameters (e.g. `"foo"`) OR placeholders such as `${foo}` which add bindings as if created using `bind("foo")`.
*
* Strings are translated and following the same rules as `strf`, refer to its documentation for a list of available formatting placeholders.
*/
export function bindf(format: string, ...bindings: string[]) {
return new StringFormatBinding(format, ...bindings);
} | the_stack |
import { ContractInterface, ethers, Signer } from "ethers";
import { IStorage } from "./interfaces/IStorage";
import { RemoteStorage } from "./classes/remote-storage";
import {
Edition,
EditionDrop,
KNOWN_CONTRACTS_MAP,
Marketplace,
NFTCollection,
NFTDrop,
Pack,
REMOTE_CONTRACT_TO_CONTRACT_TYPE,
SignatureDrop,
Split,
Token,
Vote,
} from "../contracts";
import { SDKOptions } from "../schema/sdk-options";
import { IpfsStorage } from "./classes/ipfs-storage";
import { RPCConnectionHandler } from "./classes/rpc-connection-handler";
import type {
ContractForContractType,
ContractType,
NetworkOrSignerOrProvider,
SignerOrProvider,
ValidContractInstance,
} from "./types";
import { IThirdwebContract__factory } from "contracts";
import { ContractDeployer } from "./classes/contract-deployer";
import { SmartContract } from "../contracts/smart-contract";
import invariant from "tiny-invariant";
import { TokenDrop } from "../contracts/token-drop";
import { ContractPublisher } from "./classes/contract-publisher";
import { ContractMetadata } from "./classes";
import {
ChainOrRpc,
getProviderForNetwork,
getReadOnlyProvider,
} from "../constants";
import { UserWallet } from "./wallet/UserWallet";
import { Multiwrap } from "../contracts/multiwrap";
/**
* The main entry point for the thirdweb SDK
* @public
*/
export class ThirdwebSDK extends RPCConnectionHandler {
/**
* Get an instance of the thirdweb SDK based on an existing ethers signer
*
* @example
* ```javascript
* // get a signer from somewhere (createRandom is being used purely for example purposes)
* const signer = ethers.Wallet.createRandom();
*
* // get an instance of the SDK with the signer already setup
* const sdk = ThirdwebSDK.fromSigner(signer, "mainnet");
* ```
*
* @param signer - a ethers Signer to be used for transactions
* @param network - the network (chain) to connect to (e.g. "mainnet", "rinkeby", "polygon", "mumbai"...) or a fully formed RPC url
* @param options - the SDK options to use
* @returns an instance of the SDK
*
* @beta
*/
static fromSigner(
signer: Signer,
network?: ChainOrRpc,
options: SDKOptions = {},
storage: IStorage = new IpfsStorage(),
): ThirdwebSDK {
const sdk = new ThirdwebSDK(network || signer, options, storage);
sdk.updateSignerOrProvider(signer);
return sdk;
}
/**
* Get an instance of the thirdweb SDK based on a private key.
*
* @remarks
* This should only be used for backend services or scripts, with the private key stored in a secure way.
* **NEVER** expose your private key to the public in any way.
*
* @example
* ```javascript
* const sdk = ThirdwebSDK.fromPrivateKey("SecretPrivateKey", "mainnet");
* ```
*
* @param privateKey - the private key - **DO NOT EXPOSE THIS TO THE PUBLIC**
* @param network - the network (chain) to connect to (e.g. "mainnet", "rinkeby", "polygon", "mumbai"...) or a fully formed RPC url
* @param options - the SDK options to use
* @returns an instance of the SDK
*
* @beta
*/
static fromPrivateKey(
privateKey: string,
network: ChainOrRpc,
options: SDKOptions = {},
storage: IStorage = new IpfsStorage(),
): ThirdwebSDK {
const signerOrProvider = getProviderForNetwork(network);
const provider = Signer.isSigner(signerOrProvider)
? signerOrProvider.provider
: typeof signerOrProvider === "string"
? getReadOnlyProvider(signerOrProvider)
: signerOrProvider;
const signer = new ethers.Wallet(privateKey, provider);
return ThirdwebSDK.fromSigner(signer, network, options, storage);
}
/**
* @internal
* the cache of contracts that we have already seen
*/
private contractCache = new Map<
string,
ValidContractInstance | SmartContract
>();
/**
* @internal
* should never be accessed directly, use {@link ThirdwebSDK.getPublisher} instead
*/
private _publisher: ContractPublisher;
/**
* Internal handler for uploading and downloading files
*/
private storageHandler: IStorage;
/**
* New contract deployer
*/
public deployer: ContractDeployer;
/**
* Interact with the connected wallet
*/
public wallet: UserWallet;
/**
* Upload and download files from IPFS or from your own storage service
*/
public storage: RemoteStorage;
constructor(
network: ChainOrRpc | SignerOrProvider,
options: SDKOptions = {},
storage: IStorage = new IpfsStorage(),
) {
const signerOrProvider = getProviderForNetwork(network);
super(signerOrProvider, options);
this.storageHandler = storage;
this.storage = new RemoteStorage(storage);
this.deployer = new ContractDeployer(signerOrProvider, options, storage);
this.wallet = new UserWallet(signerOrProvider, options);
this._publisher = new ContractPublisher(
signerOrProvider,
this.options,
this.storageHandler,
);
}
/**
* Get an instance of a Drop contract
* @param contractAddress - the address of the deployed contract
* @returns the contract
*/
public getNFTDrop(contractAddress: string): NFTDrop {
return this.getBuiltInContract(
contractAddress,
NFTDrop.contractType,
) as NFTDrop;
}
/**
* Get an instance of a SignatureDrop contract
* @param contractAddress - the address of the deployed contract
* @returns the contract
* @internal
*/
public getSignatureDrop(contractAddress: string): SignatureDrop {
return this.getBuiltInContract(
contractAddress,
SignatureDrop.contractType,
) as SignatureDrop;
}
/**
* Get an instance of a NFT Collection contract
* @param address - the address of the deployed contract
* @returns the contract
*/
public getNFTCollection(address: string): NFTCollection {
return this.getBuiltInContract(
address,
NFTCollection.contractType,
) as NFTCollection;
}
/**
* Get an instance of a Edition Drop contract
* @param address - the address of the deployed contract
* @returns the contract
*/
public getEditionDrop(address: string): EditionDrop {
return this.getBuiltInContract(
address,
EditionDrop.contractType,
) as EditionDrop;
}
/**
* Get an instance of an Edition contract
* @param address - the address of the deployed contract
* @returns the contract
*/
public getEdition(address: string): Edition {
return this.getBuiltInContract(address, Edition.contractType) as Edition;
}
/**
* Get an instance of a Token Drop contract
* @param address - the address of the deployed contract
* @returns the contract
*/
public getTokenDrop(address: string): TokenDrop {
return this.getBuiltInContract(
address,
TokenDrop.contractType,
) as TokenDrop;
}
/**
* Get an instance of a Token contract
* @param address - the address of the deployed contract
* @returns the contract
*/
public getToken(address: string): Token {
return this.getBuiltInContract(address, Token.contractType) as Token;
}
/**
* Get an instance of a Vote contract
* @param address - the address of the deployed contract
* @returns the contract
*/
public getVote(address: string): Vote {
return this.getBuiltInContract(address, Vote.contractType) as Vote;
}
/**
* Get an instance of a Splits contract
* @param address - the address of the deployed contract
* @returns the contract
*/
public getSplit(address: string): Split {
return this.getBuiltInContract(address, Split.contractType) as Split;
}
/**
* Get an instance of a Marketplace contract
* @param address - the address of the deployed contract
* @returns the contract
*/
public getMarketplace(address: string): Marketplace {
return this.getBuiltInContract(
address,
Marketplace.contractType,
) as Marketplace;
}
/**
* Get an instance of a Pack contract
* @param address - the address of the deployed contract
* @returns the contract
*/
public getPack(address: string): Pack {
return this.getBuiltInContract(address, Pack.contractType) as Pack;
}
/**
* Get an instance of a Multiwrap contract
* @param address - the address of the deployed contract
* @returns the contract
* @beta
*/
public getMultiwrap(address: string): Multiwrap {
return this.getBuiltInContract(
address,
Multiwrap.contractType,
) as Multiwrap;
}
/**
*
* @internal
* @param address - the address of the contract to instantiate
* @param contractType - optional, the type of contract to instantiate
* @returns a promise that resolves with the contract instance
*/
public getBuiltInContract<TContractType extends ContractType = ContractType>(
address: string,
contractType: TContractType,
): ContractForContractType<TContractType> {
// if we have a contract in the cache we will return it
// we will do this **without** checking any contract type things for simplicity, this may have to change in the future?
if (this.contractCache.has(address)) {
return this.contractCache.get(
address,
) as ContractForContractType<TContractType>;
}
if (contractType === "custom") {
throw new Error(
"To get an instance of a custom contract, use getContract(address)",
);
}
const newContract = new KNOWN_CONTRACTS_MAP[
contractType as keyof typeof KNOWN_CONTRACTS_MAP
](this.getSignerOrProvider(), address, this.storageHandler, this.options);
this.contractCache.set(address, newContract);
// return the new contract
return newContract as ContractForContractType<TContractType>;
}
/**
* @param contractAddress - the address of the contract to attempt to resolve the contract type for
* @returns the {@link ContractType} for the given contract address
* @throws if the contract type cannot be determined (is not a valid thirdweb contract)
*/
public async resolveContractType(
contractAddress: string,
): Promise<ContractType> {
const contract = IThirdwebContract__factory.connect(
contractAddress,
this.getSignerOrProvider(),
);
const remoteContractType = ethers.utils
.toUtf8String(await contract.contractType())
// eslint-disable-next-line no-control-regex
.replace(/\x00/g, "");
invariant(
remoteContractType in REMOTE_CONTRACT_TO_CONTRACT_TYPE,
`${remoteContractType} is not a valid contract type, falling back to custom contract`,
);
return REMOTE_CONTRACT_TO_CONTRACT_TYPE[
remoteContractType as keyof typeof REMOTE_CONTRACT_TO_CONTRACT_TYPE
];
}
/**
* Return all the contracts deployed by the specified address
* @param walletAddress - the deployed address
*/
public async getContractList(walletAddress: string) {
const addresses = await (
await this.deployer.getRegistry()
).getContractAddresses(walletAddress);
const addressesWithContractTypes = await Promise.all(
addresses.map(async (address) => {
let contractType: ContractType = "custom";
try {
contractType = await this.resolveContractType(address);
} catch (e) {
// this going to happen frequently and be OK, we'll just catch it and ignore it
}
let metadata: ContractMetadata<any, any> | undefined;
if (contractType === "custom") {
try {
metadata = (await this.getContract(address)).metadata;
} catch (e) {
console.log(
`Couldn't get contract metadata for custom contract: ${address}`,
);
}
} else {
metadata = this.getBuiltInContract(address, contractType).metadata;
}
return {
address,
contractType,
metadata,
};
}),
);
return addressesWithContractTypes
.filter((e) => e.metadata)
.map(({ address, contractType, metadata }) => {
invariant(metadata, "All ThirdwebContracts require metadata");
return {
address,
contractType,
metadata: () => metadata.get(),
};
});
}
/**
* Update the active signer or provider for all contracts
* @param network - the new signer or provider
*/
public override updateSignerOrProvider(network: NetworkOrSignerOrProvider) {
super.updateSignerOrProvider(network);
this.updateContractSignerOrProvider();
}
private updateContractSignerOrProvider() {
this.wallet.onNetworkUpdated(this.getSignerOrProvider());
this.deployer.updateSignerOrProvider(this.getSignerOrProvider());
this._publisher.updateSignerOrProvider(this.getSignerOrProvider());
for (const [, contract] of this.contractCache) {
contract.onNetworkUpdated(this.getSignerOrProvider());
}
}
/**
* Get an instance of a Custom ThirdwebContract
* @param address - the address of the deployed contract
* @returns the contract
* @beta
*/
public async getContract(address: string) {
if (this.contractCache.has(address)) {
return this.contractCache.get(address) as SmartContract;
}
try {
const publisher = this.getPublisher();
const metadata = await publisher.fetchContractMetadataFromAddress(
address,
);
return this.getContractFromAbi(address, metadata.abi);
} catch (e) {
throw new Error(`Error fetching ABI for this contract\n\n${e}`);
}
}
/**
* Get an instance of a Custom contract from a json ABI
* @param address - the address of the deployed contract
* @param abi - the JSON abi
* @returns the contract
* @beta
*/
public getContractFromAbi(address: string, abi: ContractInterface) {
if (this.contractCache.has(address)) {
return this.contractCache.get(address) as SmartContract;
}
const contract = new SmartContract(
this.getSignerOrProvider(),
address,
abi,
this.storageHandler,
this.options,
);
this.contractCache.set(address, contract);
return contract;
}
/**
* @internal
*/
public getPublisher(): ContractPublisher {
return this._publisher;
}
} | the_stack |
* @packageDocumentation
* @module ui
*/
import { ccclass, help, executeInEditMode, executionOrder, menu, requireComponent, tooltip, type, editorOnly, editable, serializable, visible } from 'cc.decorator';
import { EDITOR, DEV } from 'internal:constants';
import { Component } from '../core/components';
import { UITransform } from '../2d/framework/ui-transform';
import { Size, Vec2, Vec3 } from '../core/math';
import { errorID, warnID } from '../core/platform/debug';
import { View } from '../core/platform/view';
import visibleRect from '../core/platform/visible-rect';
import { Scene } from '../core/scene-graph';
import { Node } from '../core/scene-graph/node';
import { ccenum } from '../core/value-types/enum';
import { TransformBit } from '../core/scene-graph/node-enum';
import { legacyCC } from '../core/global-exports';
import { NodeEventType } from '../core/scene-graph/node-event';
const _tempScale = new Vec2();
// returns a readonly size of the node
export function getReadonlyNodeSize (parent: Node | Scene) {
if (parent instanceof Scene) {
if (EDITOR) {
// const canvasComp = parent.getComponentInChildren(Canvas);
if (!View.instance) {
throw new Error('cc.view uninitiated');
}
return View.instance.getDesignResolutionSize();
}
return visibleRect;
} else if (parent._uiProps.uiTransformComp) {
return parent._uiProps.uiTransformComp.contentSize;
} else {
return Size.ZERO;
}
}
export function computeInverseTransForTarget (widgetNode: Node, target: Node, out_inverseTranslate: Vec2, out_inverseScale: Vec2) {
if (widgetNode.parent) {
_tempScale.set(widgetNode.parent.getScale().x, widgetNode.parent.getScale().y);
} else {
_tempScale.set(0, 0);
}
let scaleX = _tempScale.x;
let scaleY = _tempScale.y;
let translateX = 0;
let translateY = 0;
for (let node = widgetNode.parent; ;) {
if (!node) {
// ERROR: widgetNode should be child of target
out_inverseTranslate.x = out_inverseTranslate.y = 0;
out_inverseScale.x = out_inverseScale.y = 1;
return;
}
const pos = node.getPosition();
translateX += pos.x;
translateY += pos.y;
node = node.parent; // loop increment
if (node !== target) {
if (node) {
_tempScale.set(node.getScale().x, node.getScale().y);
} else {
_tempScale.set(0, 0);
}
const sx = _tempScale.x;
const sy = _tempScale.y;
translateX *= sx;
translateY *= sy;
scaleX *= sx;
scaleY *= sy;
} else {
break;
}
}
out_inverseScale.x = scaleX !== 0 ? (1 / scaleX) : 1;
out_inverseScale.y = scaleY !== 0 ? (1 / scaleY) : 1;
out_inverseTranslate.x = -translateX;
out_inverseTranslate.y = -translateY;
}
/**
* @en Enum for Widget's alignment mode, indicating when the widget should refresh.
*
* @zh Widget 的对齐模式,表示 Widget 应该何时刷新。
*/
export enum AlignMode {
/**
* @en Only align once when the Widget is enabled for the first time.
* This will allow the script or animation to continue controlling the current node.
* It will only be aligned once before the end of frame when onEnable is called,then immediately disables the Widget.
*
* @zh 仅在 Widget 第一次激活时对齐一次,便于脚本或动画继续控制当前节点。<br/>
* 开启后会在 onEnable 时所在的那一帧结束前对齐一次,然后立刻禁用该 Widget。
*/
ONCE = 0,
/**
* @en Keep aligning all the way.
*
* @zh 始终保持对齐。
*/
ALWAYS = 1,
/**
* @en
* At the beginning, the widget will be aligned as the method 'ONCE'.
* After that the widget will be aligned only when the size of screen is modified.
*
* @zh
* 一开始会像 ONCE 一样对齐一次,之后每当窗口大小改变时还会重新对齐。
*/
ON_WINDOW_RESIZE = 2,
}
ccenum(AlignMode);
/**
* @en Enum for Widget's alignment flag, indicating when the widget select alignment.
*
* @zh Widget 的对齐标志,表示 Widget 选择对齐状态。
*/
export enum AlignFlags {
/**
* @en Align top.
*
* @zh 上边对齐。
*/
TOP = 1 << 0,
/**
* @en Align middle.
*
* @zh 垂直中心对齐。
*/
MID = 1 << 1,
/**
* @en Align bottom.
*
* @zh 下边对齐。
*/
BOT = 1 << 2,
/**
* @en Align left.
*
* @zh 左边对齐。
*/
LEFT = 1 << 3,
/**
* @en Align center.
*
* @zh 横向中心对齐。
*/
CENTER = 1 << 4,
/**
* @en Align right.
*
* @zh 右边对齐。
*/
RIGHT = 1 << 5,
/**
* @en Align horizontal.
*
* @zh 横向对齐。
*/
HORIZONTAL = LEFT | CENTER | RIGHT,
/**
* @en Align vertical.
*
* @zh 纵向对齐。
*/
VERTICAL = TOP | MID | BOT,
}
const TOP_BOT = AlignFlags.TOP | AlignFlags.BOT;
const LEFT_RIGHT = AlignFlags.LEFT | AlignFlags.RIGHT;
/**
* @en
* Stores and manipulate the anchoring based on its parent.
* Widget are used for GUI but can also be used for other things.
* Widget will adjust current node's position and size automatically,
* but the results after adjustment can not be obtained until the next frame unless you call [[updateAlignment]] manually.
*
* @zh Widget 组件,用于设置和适配其相对于父节点的边距,Widget 通常被用于 UI 界面,也可以用于其他地方。<br/>
* Widget 会自动调整当前节点的坐标和宽高,不过目前调整后的结果要到下一帧才能在脚本里获取到,除非你先手动调用 [[updateAlignment]]。
*/
@ccclass('cc.Widget')
@help('i18n:cc.Widget')
@executionOrder(110)
@menu('UI/Widget')
@requireComponent(UITransform)
@executeInEditMode
export class Widget extends Component {
/**
* @en
* Specifies an alignment target that can only be one of the parent nodes of the current node.
* The default value is null, and when null, indicates the current parent.
*
* @zh
* 指定一个对齐目标,只能是当前节点的其中一个父节点,默认为空,为空时表示当前父节点。
*/
@type(Node)
@tooltip('i18n:widget.target')
get target () {
return this._target;
}
set target (value) {
if (this._target === value) {
return;
}
this._unregisterTargetEvents();
this._target = value;
this._registerTargetEvents();
if (EDITOR /* && !cc.engine._isPlaying */ && this.node.parent) {
// adjust the offsets to keep the size and position unchanged after target changed
legacyCC._widgetManager.updateOffsetsToStayPut(this);
}
this._validateTargetInDEV();
this._recursiveDirty();
}
/**
* @en
* Whether to align to the top.
*
* @zh
* 是否对齐上边。
*/
@tooltip('i18n:widget.align_top')
get isAlignTop () {
return (this._alignFlags & AlignFlags.TOP) > 0;
}
set isAlignTop (value) {
this._setAlign(AlignFlags.TOP, value);
this._recursiveDirty();
}
/**
* @en
* Whether to align to the bottom.
*
* @zh
* 是否对齐下边。
*/
@tooltip('i18n:widget.align_bottom')
get isAlignBottom () {
return (this._alignFlags & AlignFlags.BOT) > 0;
}
set isAlignBottom (value) {
this._setAlign(AlignFlags.BOT, value);
this._recursiveDirty();
}
/**
* @en
* Whether to align to the left.
*
* @zh
* 是否对齐左边。
*/
@tooltip('i18n:widget.align_left')
get isAlignLeft () {
return (this._alignFlags & AlignFlags.LEFT) > 0;
}
set isAlignLeft (value) {
this._setAlign(AlignFlags.LEFT, value);
this._recursiveDirty();
}
/**
* @en
* Whether to align to the right.
*
* @zh
* 是否对齐右边。
*/
@tooltip('i18n:widget.align_right')
get isAlignRight () {
return (this._alignFlags & AlignFlags.RIGHT) > 0;
}
set isAlignRight (value) {
this._setAlign(AlignFlags.RIGHT, value);
this._recursiveDirty();
}
/**
* @en
* Whether to align vertically.
*
* @zh
* 是否垂直方向对齐中点,开启此项会将垂直方向其他对齐选项取消。
*/
@tooltip('i18n:widget.align_h_center')
get isAlignVerticalCenter () {
return (this._alignFlags & AlignFlags.MID) > 0;
}
set isAlignVerticalCenter (value) {
if (value) {
this.isAlignTop = false;
this.isAlignBottom = false;
this._alignFlags |= AlignFlags.MID;
} else {
this._alignFlags &= ~AlignFlags.MID;
}
this._recursiveDirty();
}
/**
* @en
* Whether to align horizontally.
*
* @zh
* 是否水平方向对齐中点,开启此选项会将水平方向其他对齐选项取消。
*/
@tooltip('i18n:widget.align_v_center')
get isAlignHorizontalCenter () {
return (this._alignFlags & AlignFlags.CENTER) > 0;
}
set isAlignHorizontalCenter (value) {
if (value) {
this.isAlignLeft = false;
this.isAlignRight = false;
this._alignFlags |= AlignFlags.CENTER;
} else {
this._alignFlags &= ~AlignFlags.CENTER;
}
this._recursiveDirty();
}
/**
* @en
* Whether to stretch horizontally, when enable the left and right alignment will be stretched horizontally,
* the width setting is invalid (read only).
*
* @zh
* 当前是否水平拉伸。当同时启用左右对齐时,节点将会被水平拉伸。此时节点的宽度(只读)。
*/
@visible(false)
get isStretchWidth () {
return (this._alignFlags & LEFT_RIGHT) === LEFT_RIGHT;
}
/**
* @en
* Whether to stretch vertically, when enable the left and right alignment will be stretched vertically,
* then height setting is invalid (read only).
*
* @zh
* 当前是否垂直拉伸。当同时启用上下对齐时,节点将会被垂直拉伸,此时节点的高度(只读)。
*/
@visible(false)
get isStretchHeight () {
return (this._alignFlags & TOP_BOT) === TOP_BOT;
}
// ALIGN MARGINS
/**
* @en
* The margins between the top of this node and the top of parent node,
* the value can be negative, Only available in 'isAlignTop' open.
*
* @zh
* 本节点顶边和父节点顶边的距离,可填写负值,只有在 isAlignTop 开启时才有作用。
*/
@tooltip('i18n:widget.top')
get top () {
return this._top;
}
set top (value) {
this._top = value;
this._recursiveDirty();
}
/**
* @EditorOnly Not for user
*/
@editable
get editorTop () {
return this._isAbsTop ? this._top : (this._top * 100);
}
set editorTop (value) {
this._top = this._isAbsTop ? value : (value / 100);
this._recursiveDirty();
}
/**
* @en
* The margins between the bottom of this node and the bottom of parent node,
* the value can be negative, Only available in 'isAlignBottom' open.
*
* @zh
* 本节点底边和父节点底边的距离,可填写负值,只有在 isAlignBottom 开启时才有作用。
*/
@tooltip('i18n:widget.bottom')
get bottom () {
return this._bottom;
}
set bottom (value) {
this._bottom = value;
this._recursiveDirty();
}
/**
* @EditorOnly Not for user
*/
@editable
get editorBottom () {
return this._isAbsBottom ? this._bottom : (this._bottom * 100);
}
set editorBottom (value) {
this._bottom = this._isAbsBottom ? value : (value / 100);
this._recursiveDirty();
}
/**
* @en
* The margins between the left of this node and the left of parent node,
* the value can be negative, Only available in 'isAlignLeft' open.
*
* @zh
* 本节点左边和父节点左边的距离,可填写负值,只有在 isAlignLeft 开启时才有作用。
*/
@tooltip('i18n:widget.left')
get left () {
return this._left;
}
set left (value) {
this._left = value;
this._recursiveDirty();
}
/**
* @EditorOnly Not for user
*/
@editable
get editorLeft () {
return this._isAbsLeft ? this._left : (this._left * 100);
}
set editorLeft (value) {
this._left = this._isAbsLeft ? value : (value / 100);
this._recursiveDirty();
}
/**
* @en
* The margins between the right of this node and the right of parent node,
* the value can be negative, Only available in 'isAlignRight' open.
*
* @zh
* 本节点右边和父节点右边的距离,可填写负值,只有在 isAlignRight 开启时才有作用。
*/
@tooltip('i18n:widget.right')
get right () {
return this._right;
}
set right (value) {
this._right = value;
this._recursiveDirty();
}
/**
* @EditorOnly Not for user
*/
@editable
get editorRight () {
return this._isAbsRight ? this._right : (this._right * 100);
}
set editorRight (value) {
this._right = this._isAbsRight ? value : (value / 100);
this._recursiveDirty();
}
/**
* @en
* Horizontally aligns the midpoint offset value,
* the value can be negative, Only available in 'isAlignHorizontalCenter' open.
*
* @zh
* 水平居中的偏移值,可填写负值,只有在 isAlignHorizontalCenter 开启时才有作用。
*/
@tooltip('i18n:widget.horizontal_center')
get horizontalCenter () {
return this._horizontalCenter;
}
set horizontalCenter (value) {
this._horizontalCenter = value;
this._recursiveDirty();
}
/**
* @EditorOnly Not for user
*/
@editable
get editorHorizontalCenter () {
return this._isAbsHorizontalCenter ? this._horizontalCenter : (this._horizontalCenter * 100);
}
set editorHorizontalCenter (value) {
this._horizontalCenter = this._isAbsHorizontalCenter ? value : (value / 100);
this._recursiveDirty();
}
/**
* @en
* Vertically aligns the midpoint offset value,
* the value can be negative, Only available in 'isAlignVerticalCenter' open.
*
* @zh
* 垂直居中的偏移值,可填写负值,只有在 isAlignVerticalCenter 开启时才有作用。
*/
@tooltip('i18n:widget.vertical_center')
get verticalCenter () {
return this._verticalCenter;
}
set verticalCenter (value) {
this._verticalCenter = value;
this._recursiveDirty();
}
/**
* @EditorOnly Not for user
*/
@editable
get editorVerticalCenter () {
return this._isAbsVerticalCenter ? this._verticalCenter : (this._verticalCenter * 100);
}
set editorVerticalCenter (value) {
this._verticalCenter = this._isAbsVerticalCenter ? value : (value / 100);
this._recursiveDirty();
}
/**
* @en
* If true, top is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height.
*
* @zh
* 如果为 true,"top" 将会以像素作为边距,否则将会以相对父物体高度的比例(0 到 1)作为边距。
*/
@editable
get isAbsoluteTop () {
return this._isAbsTop;
}
set isAbsoluteTop (value) {
if (this._isAbsTop === value) {
return;
}
this._isAbsTop = value;
this._autoChangedValue(AlignFlags.TOP, this._isAbsTop);
}
/**
* @en
* If true, bottom is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height.
*
* @zh
* 如果为 true,"bottom" 将会以像素作为边距,否则将会以相对父物体高度的比例(0 到 1)作为边距。
*/
@editable
get isAbsoluteBottom () {
return this._isAbsBottom;
}
set isAbsoluteBottom (value) {
if (this._isAbsBottom === value) {
return;
}
this._isAbsBottom = value;
this._autoChangedValue(AlignFlags.BOT, this._isAbsBottom);
}
/**
* @en
* If true, left is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's width.
*
* @zh
* 如果为 true,"left" 将会以像素作为边距,否则将会以相对父物体宽度的比例(0 到 1)作为边距。
*/
@editable
get isAbsoluteLeft () {
return this._isAbsLeft;
}
set isAbsoluteLeft (value) {
if (this._isAbsLeft === value) {
return;
}
this._isAbsLeft = value;
this._autoChangedValue(AlignFlags.LEFT, this._isAbsLeft);
}
/**
* @en
* If true, right is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's width.
*
* @zh
* 如果为 true,"right" 将会以像素作为边距,否则将会以相对父物体宽度的比例(0 到 1)作为边距。
*/
@editable
get isAbsoluteRight () {
return this._isAbsRight;
}
set isAbsoluteRight (value) {
if (this._isAbsRight === value) {
return;
}
this._isAbsRight = value;
this._autoChangedValue(AlignFlags.RIGHT, this._isAbsRight);
}
/**
* @en
* If true, horizontalCenter is pixel margin, otherwise is percentage (0 - 1) margin.
*
* @zh
* 如果为 true,"horizontalCenter" 将会以像素作为偏移值,反之为比例(0 到 1)。
*/
@editable
get isAbsoluteHorizontalCenter () {
return this._isAbsHorizontalCenter;
}
set isAbsoluteHorizontalCenter (value) {
if (this._isAbsHorizontalCenter === value) {
return;
}
this._isAbsHorizontalCenter = value;
this._autoChangedValue(AlignFlags.CENTER, this._isAbsHorizontalCenter);
}
/**
* @en
* If true, verticalCenter is pixel margin, otherwise is percentage (0 - 1) margin.
*
* @zh
* 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为比例(0 到 1)。
*/
@editable
get isAbsoluteVerticalCenter () {
return this._isAbsVerticalCenter;
}
set isAbsoluteVerticalCenter (value) {
if (this._isAbsVerticalCenter === value) {
return;
}
this._isAbsVerticalCenter = value;
this._autoChangedValue(AlignFlags.MID, this._isAbsVerticalCenter);
}
/**
* @en
* Specifies the alignment mode of the Widget, which determines when the widget should refresh.
*
* @zh
* 指定 Widget 的对齐模式,用于决定 Widget 应该何时刷新。
*
* @example
* ```
* import { Widget } from 'cc';
* widget.alignMode = Widget.AlignMode.ON_WINDOW_RESIZE;
* ```
*/
@type(AlignMode)
@tooltip('i18n:widget.align_mode')
get alignMode () {
return this._alignMode;
}
set alignMode (value) {
this._alignMode = value;
this._recursiveDirty();
}
/**
* @zh
* 对齐开关,由 AlignFlags 组成
*/
@editable
get alignFlags () {
return this._alignFlags;
}
set alignFlags (value) {
if (this._alignFlags === value) {
return;
}
this._alignFlags = value;
this._recursiveDirty();
}
public static AlignMode = AlignMode;
public _lastPos = new Vec3();
public _lastSize = new Size();
public _dirty = true;
public _hadAlignOnce = false;
@serializable
private _alignFlags = 0;
@serializable
private _target: Node | null = null;
@serializable
private _left = 0;
@serializable
private _right = 0;
@serializable
private _top = 0;
@serializable
private _bottom = 0;
@serializable
private _horizontalCenter = 0;
@serializable
private _verticalCenter = 0;
@serializable
private _isAbsLeft = true;
@serializable
private _isAbsRight = true;
@serializable
private _isAbsTop = true;
@serializable
private _isAbsBottom = true;
@serializable
private _isAbsHorizontalCenter = true;
@serializable
private _isAbsVerticalCenter = true;
// original size before align
@serializable
private _originalWidth = 0;
@serializable
private _originalHeight = 0;
@serializable
private _alignMode = AlignMode.ON_WINDOW_RESIZE;
@serializable
@editorOnly
private _lockFlags = 0;
/**
* @en
* Immediately perform the widget alignment. You need to manually call this method only if
* you need to get the latest results after the alignment before the end of current frame.
*
* @zh
* 立刻执行 widget 对齐操作。这个接口一般不需要手工调用。
* 只有当你需要在当前帧结束前获得 widget 对齐后的最新结果时才需要手动调用这个方法。
*
* @example
* ```ts
* import { log } from 'cc';
* widget.top = 10; // change top margin
* log(widget.node.y); // not yet changed
* widget.updateAlignment();
* log(widget.node.y); // changed
* ```
*/
public updateAlignment () {
legacyCC._widgetManager.updateAlignment(this.node);
}
public _validateTargetInDEV () {
if (!DEV) {
return;
}
const target = this._target;
if (target) {
const isParent = this.node !== target && this.node.isChildOf(target);
if (!isParent) {
errorID(6500);
this.target = null;
}
}
}
public setDirty () {
this._recursiveDirty();
}
public onEnable () {
this.node.getPosition(this._lastPos);
this._lastSize.set(this.node._uiProps.uiTransformComp!.contentSize);
legacyCC._widgetManager.add(this);
this._hadAlignOnce = false;
this._registerEvent();
this._registerTargetEvents();
}
public onDisable () {
legacyCC._widgetManager.remove(this);
this._unregisterEvent();
this._unregisterTargetEvents();
}
public onDestroy () {
this._removeParentEvent();
}
public _adjustWidgetToAllowMovingInEditor (eventType: TransformBit) {}
public _adjustWidgetToAllowResizingInEditor () {}
public _adjustWidgetToAnchorChanged () {
this.setDirty();
}
public _adjustTargetToParentChanged (oldParent: Node) {
if (oldParent) {
this._unregisterOldParentEvents(oldParent);
}
if (this.node.getParent()) {
this._registerTargetEvents();
}
this._setDirtyByMode();
}
protected _registerEvent () {
if (EDITOR && !legacyCC.GAME_VIEW) {
this.node.on(NodeEventType.TRANSFORM_CHANGED, this._adjustWidgetToAllowMovingInEditor, this);
this.node.on(NodeEventType.SIZE_CHANGED, this._adjustWidgetToAllowResizingInEditor, this);
} else {
this.node.on(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
this.node.on(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this);
}
this.node.on(NodeEventType.ANCHOR_CHANGED, this._adjustWidgetToAnchorChanged, this);
this.node.on(NodeEventType.PARENT_CHANGED, this._adjustTargetToParentChanged, this);
}
protected _unregisterEvent () {
if (EDITOR && !legacyCC.GAME_VIEW) {
this.node.off(NodeEventType.TRANSFORM_CHANGED, this._adjustWidgetToAllowMovingInEditor, this);
this.node.off(NodeEventType.SIZE_CHANGED, this._adjustWidgetToAllowResizingInEditor, this);
} else {
this.node.off(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
this.node.off(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this);
}
this.node.off(NodeEventType.ANCHOR_CHANGED, this._adjustWidgetToAnchorChanged, this);
}
protected _removeParentEvent () {
this.node.off(NodeEventType.PARENT_CHANGED, this._adjustTargetToParentChanged, this);
}
protected _autoChangedValue (flag: AlignFlags, isAbs: boolean) {
const current = (this._alignFlags & flag) > 0;
if (!current) {
return;
}
const parentUiProps = this.node.parent && this.node.parent._uiProps;
const parentTrans = parentUiProps && parentUiProps.uiTransformComp;
const size = parentTrans ? parentTrans.contentSize : visibleRect;
if (this.isAlignLeft && flag === AlignFlags.LEFT) {
this._left = isAbs ? this._left * size.width : this._left / size.width;
} else if (this.isAlignRight && flag === AlignFlags.RIGHT) {
this._right = isAbs ? this._right * size.width : this._right / size.width;
} else if (this.isAlignHorizontalCenter && flag === AlignFlags.CENTER) {
this._horizontalCenter = isAbs ? this._horizontalCenter * size.width : this._horizontalCenter / size.width;
} else if (this.isAlignTop && flag === AlignFlags.TOP) {
this._top = isAbs ? this._top * size.height : this._top / size.height;
} else if (this.isAlignBottom && flag === AlignFlags.BOT) {
this._bottom = isAbs ? this._bottom * size.height : this._bottom / size.height;
} else if (this.isAbsoluteVerticalCenter && flag === AlignFlags.MID) {
this._verticalCenter = isAbs ? this._verticalCenter / size.height : this._verticalCenter / size.height;
}
this._recursiveDirty();
}
protected _registerTargetEvents () {
const target = this._target || this.node.parent;
if (target) {
if (target.getComponent(UITransform)) {
target.on(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
target.on(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this);
target.on(NodeEventType.ANCHOR_CHANGED, this._setDirtyByMode, this);
}
}
}
protected _unregisterTargetEvents () {
const target = this._target || this.node.parent;
if (target) {
target.off(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
target.off(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this);
target.off(NodeEventType.ANCHOR_CHANGED, this._setDirtyByMode, this);
}
}
protected _unregisterOldParentEvents (oldParent: Node) {
const target = this._target || oldParent;
if (target) {
target.off(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
target.off(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this);
}
}
protected _setDirtyByMode () {
if (this.alignMode === AlignMode.ALWAYS || EDITOR) {
this._recursiveDirty();
}
}
private _setAlign (flag: AlignFlags, isAlign: boolean) {
const current = (this._alignFlags & flag) > 0;
if (isAlign === current) {
return;
}
const isHorizontal = (flag & LEFT_RIGHT) > 0;
const trans = this.node._uiProps.uiTransformComp!;
if (isAlign) {
this._alignFlags |= flag;
if (isHorizontal) {
this.isAlignHorizontalCenter = false;
if (this.isStretchWidth) {
// become stretch
this._originalWidth = trans.width;
// test check conflict
if (EDITOR /* && !cc.engine.isPlaying */) {
// TODO:
// _Scene.DetectConflict.checkConflict_Widget(this);
}
}
} else {
this.isAlignVerticalCenter = false;
if (this.isStretchHeight) {
// become stretch
this._originalHeight = trans.height;
// test check conflict
if (EDITOR /* && !cc.engine.isPlaying */) {
// TODO:
// _Scene.DetectConflict.checkConflict_Widget(this);
}
}
}
if (EDITOR && this.node.parent) {
// adjust the offsets to keep the size and position unchanged after alignment changed
legacyCC._widgetManager.updateOffsetsToStayPut(this, flag);
}
} else {
if (isHorizontal) {
if (this.isStretchWidth) {
// will cancel stretch
trans.width = this._originalWidth;
}
} else if (this.isStretchHeight) {
// will cancel stretch
trans.height = this._originalHeight;
}
this._alignFlags &= ~flag;
}
}
private _recursiveDirty () {
if (this._dirty) {
return;
}
this._dirty = true;
}
}
export declare namespace Widget {
export type AlignMode = EnumAlias<typeof AlignMode>;
}
// cc.Widget = module.exports = Widget;
legacyCC.internal.computeInverseTransForTarget = computeInverseTransForTarget;
legacyCC.internal.getReadonlyNodeSize = getReadonlyNodeSize; | the_stack |
import { SpanStatusCode } from "@azure/core-tracing";
import { createSpan } from "../tracing";
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import * as coreHttp from "@azure/core-http";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { DeviceUpdateClientContext } from "../deviceUpdateClientContext";
import {
Deployment,
DeploymentsGetAllDeploymentsNextOptionalParams,
DeploymentsGetAllDeploymentsOptionalParams,
DeploymentDeviceState,
DeploymentsGetDeploymentDevicesNextOptionalParams,
DeploymentsGetDeploymentDevicesOptionalParams,
DeploymentsGetAllDeploymentsResponse,
DeploymentsGetDeploymentResponse,
DeploymentsCreateOrUpdateDeploymentResponse,
DeploymentsGetDeploymentStatusResponse,
DeploymentsGetDeploymentDevicesResponse,
DeploymentsCancelDeploymentResponse,
DeploymentsRetryDeploymentResponse,
DeploymentsGetAllDeploymentsNextResponse,
DeploymentsGetDeploymentDevicesNextResponse
} from "../models";
/** Class representing a Deployments. */
export class Deployments {
private readonly client: DeviceUpdateClientContext;
/**
* Initialize a new instance of the class Deployments class.
* @param client Reference to the service client
*/
constructor(client: DeviceUpdateClientContext) {
this.client = client;
}
/**
* Gets a list of deployments.
* @param options The options parameters.
*/
public listAllDeployments(
options?: DeploymentsGetAllDeploymentsOptionalParams
): PagedAsyncIterableIterator<Deployment> {
const iter = this.getAllDeploymentsPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.getAllDeploymentsPagingPage(options);
}
};
}
private async *getAllDeploymentsPagingPage(
options?: DeploymentsGetAllDeploymentsOptionalParams
): AsyncIterableIterator<Deployment[]> {
let result = await this._getAllDeployments(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._getAllDeploymentsNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *getAllDeploymentsPagingAll(
options?: DeploymentsGetAllDeploymentsOptionalParams
): AsyncIterableIterator<Deployment> {
for await (const page of this.getAllDeploymentsPagingPage(options)) {
yield* page;
}
}
/**
* Gets a list of devices in a deployment along with their state. Useful for getting a list of failed
* devices.
* @param deploymentId Deployment identifier.
* @param options The options parameters.
*/
public listDeploymentDevices(
deploymentId: string,
options?: DeploymentsGetDeploymentDevicesOptionalParams
): PagedAsyncIterableIterator<DeploymentDeviceState> {
const iter = this.getDeploymentDevicesPagingAll(deploymentId, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.getDeploymentDevicesPagingPage(deploymentId, options);
}
};
}
private async *getDeploymentDevicesPagingPage(
deploymentId: string,
options?: DeploymentsGetDeploymentDevicesOptionalParams
): AsyncIterableIterator<DeploymentDeviceState[]> {
let result = await this._getDeploymentDevices(deploymentId, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._getDeploymentDevicesNext(deploymentId, continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *getDeploymentDevicesPagingAll(
deploymentId: string,
options?: DeploymentsGetDeploymentDevicesOptionalParams
): AsyncIterableIterator<DeploymentDeviceState> {
for await (const page of this.getDeploymentDevicesPagingPage(deploymentId, options)) {
yield* page;
}
}
/**
* Gets a list of deployments.
* @param options The options parameters.
*/
private async _getAllDeployments(
options?: DeploymentsGetAllDeploymentsOptionalParams
): Promise<DeploymentsGetAllDeploymentsResponse> {
const { span, updatedOptions } = createSpan(
"DeviceUpdateClient-_getAllDeployments",
coreHttp.operationOptionsToRequestOptionsBase(options || {})
);
const operationArguments: coreHttp.OperationArguments = {
options: updatedOptions
};
try {
const result = await this.client.sendOperationRequest(
operationArguments,
getAllDeploymentsOperationSpec
);
return result as DeploymentsGetAllDeploymentsResponse;
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
throw error;
} finally {
span.end();
}
}
/**
* Gets the properties of a deployment.
* @param deploymentId Deployment identifier.
* @param options The options parameters.
*/
async getDeployment(
deploymentId: string,
options?: coreHttp.OperationOptions
): Promise<DeploymentsGetDeploymentResponse> {
const { span, updatedOptions } = createSpan(
"DeviceUpdateClient-getDeployment",
coreHttp.operationOptionsToRequestOptionsBase(options || {})
);
const operationArguments: coreHttp.OperationArguments = {
deploymentId,
options: updatedOptions
};
try {
const result = await this.client.sendOperationRequest(
operationArguments,
getDeploymentOperationSpec
);
return result as DeploymentsGetDeploymentResponse;
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
throw error;
} finally {
span.end();
}
}
/**
* Creates or updates a deployment.
* @param deploymentId Deployment identifier.
* @param deployment The deployment properties.
* @param options The options parameters.
*/
async createOrUpdateDeployment(
deploymentId: string,
deployment: Deployment,
options?: coreHttp.OperationOptions
): Promise<DeploymentsCreateOrUpdateDeploymentResponse> {
const { span, updatedOptions } = createSpan(
"DeviceUpdateClient-createOrUpdateDeployment",
coreHttp.operationOptionsToRequestOptionsBase(options || {})
);
const operationArguments: coreHttp.OperationArguments = {
deploymentId,
deployment,
options: updatedOptions
};
try {
const result = await this.client.sendOperationRequest(
operationArguments,
createOrUpdateDeploymentOperationSpec
);
return result as DeploymentsCreateOrUpdateDeploymentResponse;
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
throw error;
} finally {
span.end();
}
}
/**
* Deletes a deployment.
* @param deploymentId Deployment identifier.
* @param options The options parameters.
*/
async deleteDeployment(
deploymentId: string,
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse> {
const { span, updatedOptions } = createSpan(
"DeviceUpdateClient-deleteDeployment",
coreHttp.operationOptionsToRequestOptionsBase(options || {})
);
const operationArguments: coreHttp.OperationArguments = {
deploymentId,
options: updatedOptions
};
try {
const result = await this.client.sendOperationRequest(
operationArguments,
deleteDeploymentOperationSpec
);
return result as coreHttp.RestResponse;
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
throw error;
} finally {
span.end();
}
}
/**
* Gets the status of a deployment including a breakdown of how many devices in the deployment are in
* progress, completed, or failed.
* @param deploymentId Deployment identifier.
* @param options The options parameters.
*/
async getDeploymentStatus(
deploymentId: string,
options?: coreHttp.OperationOptions
): Promise<DeploymentsGetDeploymentStatusResponse> {
const { span, updatedOptions } = createSpan(
"DeviceUpdateClient-getDeploymentStatus",
coreHttp.operationOptionsToRequestOptionsBase(options || {})
);
const operationArguments: coreHttp.OperationArguments = {
deploymentId,
options: updatedOptions
};
try {
const result = await this.client.sendOperationRequest(
operationArguments,
getDeploymentStatusOperationSpec
);
return result as DeploymentsGetDeploymentStatusResponse;
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
throw error;
} finally {
span.end();
}
}
/**
* Gets a list of devices in a deployment along with their state. Useful for getting a list of failed
* devices.
* @param deploymentId Deployment identifier.
* @param options The options parameters.
*/
private async _getDeploymentDevices(
deploymentId: string,
options?: DeploymentsGetDeploymentDevicesOptionalParams
): Promise<DeploymentsGetDeploymentDevicesResponse> {
const { span, updatedOptions } = createSpan(
"DeviceUpdateClient-_getDeploymentDevices",
coreHttp.operationOptionsToRequestOptionsBase(options || {})
);
const operationArguments: coreHttp.OperationArguments = {
deploymentId,
options: updatedOptions
};
try {
const result = await this.client.sendOperationRequest(
operationArguments,
getDeploymentDevicesOperationSpec
);
return result as DeploymentsGetDeploymentDevicesResponse;
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
throw error;
} finally {
span.end();
}
}
/**
* Cancels a deployment.
* @param deploymentId Deployment identifier.
* @param options The options parameters.
*/
async cancelDeployment(
deploymentId: string,
options?: coreHttp.OperationOptions
): Promise<DeploymentsCancelDeploymentResponse> {
const { span, updatedOptions } = createSpan(
"DeviceUpdateClient-cancelDeployment",
coreHttp.operationOptionsToRequestOptionsBase(options || {})
);
const operationArguments: coreHttp.OperationArguments = {
deploymentId,
options: updatedOptions
};
try {
const result = await this.client.sendOperationRequest(
operationArguments,
cancelDeploymentOperationSpec
);
return result as DeploymentsCancelDeploymentResponse;
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
throw error;
} finally {
span.end();
}
}
/**
* Retries a deployment with failed devices.
* @param deploymentId Deployment identifier.
* @param options The options parameters.
*/
async retryDeployment(
deploymentId: string,
options?: coreHttp.OperationOptions
): Promise<DeploymentsRetryDeploymentResponse> {
const { span, updatedOptions } = createSpan(
"DeviceUpdateClient-retryDeployment",
coreHttp.operationOptionsToRequestOptionsBase(options || {})
);
const operationArguments: coreHttp.OperationArguments = {
deploymentId,
options: updatedOptions
};
try {
const result = await this.client.sendOperationRequest(
operationArguments,
retryDeploymentOperationSpec
);
return result as DeploymentsRetryDeploymentResponse;
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
throw error;
} finally {
span.end();
}
}
/**
* GetAllDeploymentsNext
* @param nextLink The nextLink from the previous successful call to the GetAllDeployments method.
* @param options The options parameters.
*/
private async _getAllDeploymentsNext(
nextLink: string,
options?: DeploymentsGetAllDeploymentsNextOptionalParams
): Promise<DeploymentsGetAllDeploymentsNextResponse> {
const { span, updatedOptions } = createSpan(
"DeviceUpdateClient-_getAllDeploymentsNext",
coreHttp.operationOptionsToRequestOptionsBase(options || {})
);
const operationArguments: coreHttp.OperationArguments = {
nextLink,
options: updatedOptions
};
try {
const result = await this.client.sendOperationRequest(
operationArguments,
getAllDeploymentsNextOperationSpec
);
return result as DeploymentsGetAllDeploymentsNextResponse;
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
throw error;
} finally {
span.end();
}
}
/**
* GetDeploymentDevicesNext
* @param deploymentId Deployment identifier.
* @param nextLink The nextLink from the previous successful call to the GetDeploymentDevices method.
* @param options The options parameters.
*/
private async _getDeploymentDevicesNext(
deploymentId: string,
nextLink: string,
options?: DeploymentsGetDeploymentDevicesNextOptionalParams
): Promise<DeploymentsGetDeploymentDevicesNextResponse> {
const { span, updatedOptions } = createSpan(
"DeviceUpdateClient-_getDeploymentDevicesNext",
coreHttp.operationOptionsToRequestOptionsBase(options || {})
);
const operationArguments: coreHttp.OperationArguments = {
deploymentId,
nextLink,
options: updatedOptions
};
try {
const result = await this.client.sendOperationRequest(
operationArguments,
getDeploymentDevicesNextOperationSpec
);
return result as DeploymentsGetDeploymentDevicesNextResponse;
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
throw error;
} finally {
span.end();
}
}
}
// Operation Specifications
const serializer = new coreHttp.Serializer(Mappers, /* isXml */ false);
const getAllDeploymentsOperationSpec: coreHttp.OperationSpec = {
path: "/deviceupdate/{instanceId}/v2/management/deployments",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.PageableListOfDeployments
}
},
queryParameters: [Parameters.filter],
urlParameters: [Parameters.accountEndpoint, Parameters.instanceId],
headerParameters: [Parameters.accept],
serializer
};
const getDeploymentOperationSpec: coreHttp.OperationSpec = {
path: "/deviceupdate/{instanceId}/v2/management/deployments/{deploymentId}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.Deployment
},
404: {
isError: true
}
},
urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.deploymentId],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateDeploymentOperationSpec: coreHttp.OperationSpec = {
path: "/deviceupdate/{instanceId}/v2/management/deployments/{deploymentId}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Deployment
},
404: {
isError: true
}
},
requestBody: Parameters.deployment,
urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.deploymentId],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const deleteDeploymentOperationSpec: coreHttp.OperationSpec = {
path: "/deviceupdate/{instanceId}/v2/management/deployments/{deploymentId}",
httpMethod: "DELETE",
responses: {
200: {},
404: {
isError: true
}
},
urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.deploymentId],
serializer
};
const getDeploymentStatusOperationSpec: coreHttp.OperationSpec = {
path: "/deviceupdate/{instanceId}/v2/management/deployments/{deploymentId}/status",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.DeploymentStatus
},
404: {
isError: true
}
},
urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.deploymentId],
headerParameters: [Parameters.accept],
serializer
};
const getDeploymentDevicesOperationSpec: coreHttp.OperationSpec = {
path: "/deviceupdate/{instanceId}/v2/management/deployments/{deploymentId}/devicestates",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.PageableListOfDeploymentDeviceStates
},
404: {
isError: true
}
},
queryParameters: [Parameters.filter],
urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.deploymentId],
headerParameters: [Parameters.accept],
serializer
};
const cancelDeploymentOperationSpec: coreHttp.OperationSpec = {
path: "/deviceupdate/{instanceId}/v2/management/deployments/{deploymentId}",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.Deployment
},
404: {
isError: true
}
},
queryParameters: [Parameters.action1],
urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.deploymentId],
headerParameters: [Parameters.accept],
serializer
};
const retryDeploymentOperationSpec: coreHttp.OperationSpec = {
path: "/deviceupdate/{instanceId}/v2/management/deployments/{deploymentId}",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.Deployment
},
404: {
isError: true
}
},
queryParameters: [Parameters.action2],
urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.deploymentId],
headerParameters: [Parameters.accept],
serializer
};
const getAllDeploymentsNextOperationSpec: coreHttp.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.PageableListOfDeployments
}
},
queryParameters: [Parameters.filter],
urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.nextLink],
headerParameters: [Parameters.accept],
serializer
};
const getDeploymentDevicesNextOperationSpec: coreHttp.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.PageableListOfDeploymentDeviceStates
},
404: {
isError: true
}
},
queryParameters: [Parameters.filter],
urlParameters: [
Parameters.accountEndpoint,
Parameters.instanceId,
Parameters.nextLink,
Parameters.deploymentId
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import {
getAllCookies,
getDefaultCookieStoreId,
generateCookiesForAltAccountRequest,
} from './cookie-handler'
import { stripSensitiveInfo } from '../common'
const BEARER_TOKEN = `AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA`
const TD_BEARER_TOKEN = `AAAAAAAAAAAAAAAAAAAAAF7aAAAAAAAASCiRjWvh7R5wxaKkFp7MM%2BhYBqM%3DbQ0JPmjU9F6ZoMhDfI4uTNAaQuTDm2uO9x3WFVr2xBZ2nhjdP0`
// const TD2_BEARER_TOKEN = `AAAAAAAAAAAAAAAAAAAAAFQODgEAAAAAVHTp76lzh3rFzcHbmHVvQxYYpTw%3DckAlMINMjmCwxUcaXbAN4XqJVdgMJaHqNOFgPMK0zN1qLqLQCF`
const gqlDataMap = new Map<string, GraphQLQueryData>()
function stripSensitiveInfoFromArrayOfUsers(users: TwitterUser[]): TwitterUser[] {
return users.map(stripSensitiveInfo)
}
function stripSensitiveInfoFromResponse(response: UserListResponse): UserListResponse {
return {
users: stripSensitiveInfoFromArrayOfUsers(response.users),
next_cursor_str: response.next_cursor_str,
}
}
export class TwClient {
public prefix = 'api.twitter.com'
// prefix = 'twitter.com/i/api'
public constructor(private readonly ctorOptions: TwClientOptions) {}
public get options(): TwClientOptions {
const { actAsUserId, cookieStoreId, asTweetDeck } = this.ctorOptions
return { actAsUserId, cookieStoreId, asTweetDeck }
}
public async getMyself(): Promise<TwitterUser> {
return await this.request1('get', '/account/verify_credentials.json').then(stripSensitiveInfo)
}
public async getRateLimitStatus(): Promise<LimitStatus> {
const response = await this.request1('get', '/application/rate_limit_status.json')
return response.resources
}
public async blockUser(user: TwitterUser): Promise<TwitterUser> {
if (user.blocking) {
return user
}
return this.blockUserById(user.id_str)
}
public async unblockUser(user: TwitterUser): Promise<TwitterUser> {
if (!user.blocking) {
return user
}
return this.unblockUserById(user.id_str)
}
public async muteUser(user: TwitterUser): Promise<TwitterUser> {
if (user.muting) {
return user
}
return await this.request1('post', '/mutes/users/create.json', {
user_id: user.id_str,
})
}
public async unmuteUser(user: TwitterUser): Promise<TwitterUser> {
if (!user.muting) {
return user
}
return await this.request1('post', '/mutes/users/destroy.json', {
user_id: user.id_str,
})
}
public async unfollowUser(user: TwitterUser): Promise<TwitterUser> {
if (!user.following) {
return user
}
return await this.request1('post', '/friendships/destroy.json', {
user_id: user.id_str,
})
}
public async blockUserById(userId: string): Promise<TwitterUser> {
return await this.request1('post', '/blocks/create.json', {
user_id: userId,
include_entities: false,
skip_status: true,
})
}
public async unblockUserById(userId: string): Promise<TwitterUser> {
return await this.request1('post', '/blocks/destroy.json', {
user_id: userId,
include_entities: false,
skip_status: true,
})
}
public async getTweetById(tweetId: string): Promise<Tweet> {
return await this.request1('get', '/statuses/show.json', {
id: tweetId,
// 2020-11-28
// - include_entities:
// 멘션한 유저 체인블락 기능을 구현하기 위해
// entities 속성이 필요하다
// - tweet_mode: 'extended'
// 트윗이 길면 텍스트 뿐만 아니라 멘션한 유저도 적게 가져오더라.
include_entities: true,
tweet_mode: 'extended',
include_ext_alt_text: false,
include_card_uri: false,
})
}
public async getFollowsIds(
followKind: FollowKind,
user: TwitterUser,
cursor = '-1'
): Promise<UserIdsResponse> {
return await this.request1('get', `/${followKind}/ids.json`, {
user_id: user.id_str,
stringify_ids: true,
count: 5000,
cursor,
})
}
public async getFollowsUserList(
followKind: FollowKind,
user: TwitterUser,
cursor = '-1'
): Promise<UserListResponse> {
return await this.request1('get', `/${followKind}/list.json`, {
user_id: user.id_str,
count: 200,
skip_status: false,
include_user_entities: false,
cursor,
}).then(stripSensitiveInfoFromResponse)
}
public async getMultipleUsers(options: GetMultipleUsersOption): Promise<TwitterUser[]> {
const user_id = 'user_id' in options ? options.user_id : []
const screen_name = 'screen_name' in options ? options.screen_name : []
if (user_id.length <= 0 && screen_name.length <= 0) {
console.warn('warning: empty user_id/screen_name')
return []
}
if (user_id.length > 100 || screen_name.length > 100) {
throw new Error('too many users! (> 100)')
}
const requestParams: URLParamsObj = {}
if (user_id.length > 0) {
requestParams.user_id = user_id
} else if (screen_name.length > 0) {
requestParams.screen_name = screen_name
} else {
throw new Error('unreachable')
}
return await this.request1('get', '/users/lookup.json', requestParams).then(
stripSensitiveInfoFromArrayOfUsers
)
}
public async getSingleUser(options: GetSingleUserOption): Promise<TwitterUser> {
const requestParams: URLParamsObj = {
skip_status: true,
include_entities: false,
}
if ('user_id' in options) {
requestParams.user_id = options.user_id
} else if ('screen_name' in options) {
requestParams.screen_name = options.screen_name
}
return await this.request1('get', '/users/show.json', requestParams).then(stripSensitiveInfo)
}
public async getFriendships(users: TwitterUser[]): Promise<FriendshipResponse> {
const userIds = users.map(user => user.id_str)
if (userIds.length === 0) {
return []
}
if (userIds.length > 100) {
throw new Error('too many users! (> 100)')
}
return await this.request1('get', '/friendships/lookup.json', {
user_id: userIds,
})
}
public async getRelationship(
sourceUser: TwitterUser,
targetUser: TwitterUser
): Promise<Relationship> {
const source_id = sourceUser.id_str
const target_id = targetUser.id_str
const response = await this.request1('get', '/friendships/show.json', {
source_id,
target_id,
})
return response.relationship
}
public async getReactedUserList(
reaction: ReactionKind,
tweet: Tweet,
cursor = '-1'
): Promise<UserListResponse> {
let requestPath = ''
switch (reaction) {
case 'retweeted':
requestPath = '/statuses/retweeted_by.json'
break
case 'liked':
requestPath = '/statuses/favorited_by.json'
break
}
return await this.request1('get', requestPath, {
id: tweet.id_str,
count: 200,
cursor,
}).then(stripSensitiveInfoFromResponse)
}
public async getRetweetersIds(tweet: Tweet): Promise<UserIdsResponse> {
return await this.request1('get', '/statuses/retweeters/ids.json', {
id: tweet.id_str,
count: 100,
// cursor: <- 한 번 요청에 최대치(100명)을 가져올 수 있으므로 굳이 cursor를 쓰는 의미가 없다.
stringify_ids: true,
})
}
public async getBlockedUsersIds(cursor = '-1'): Promise<UserIdsResponse> {
return await this.request1('get', '/blocks/ids.json', {
stringify_ids: true,
cursor,
})
}
public async searchUsers(query: string, cursor?: string): Promise<APIv2Response> {
return await this.request2('get', '/search/adaptive.json', {
q: query,
result_filter: 'user',
count: 200,
query_source: 'typed_query',
pc: 1,
spelling_corrections: 0,
cursor,
// ext: 'mediaStats,highlightedLabel',
})
}
public async searchQuotedUsers(tweetId: string, cursor?: string): Promise<APIv2Response> {
return await this.request2('get', '/search/adaptive.json', {
q: `quoted_tweet_id:${tweetId}`,
vertical: 'tweet_detail_quote',
count: 200,
pc: 1,
spelling_corrections: 0,
cursor,
})
}
public async getAudioSpaceById(spaceId: string): Promise<AudioSpace> {
const queryData = await getQueryDataByOperationName('AudioSpaceById')
return await this.requestGraphQL(queryData, {
id: spaceId,
isMetatagsQuery: false,
withTweetResult: true,
withReactions: true,
withSuperFollowsTweetFields: true,
withSuperFollowsUserFields: true,
withUserResults: true,
withBirdwatchPivots: true,
withScheduledSpaces: true,
}).then(response => {
const { audioSpace } = response.data
if ('metadata' in audioSpace) {
return audioSpace
} else {
throw new Error("This space is expired or doesn't exists.")
}
})
}
public async getTweetReactionV2Timeline(tweet: Tweet): Promise<ReactionV2Timeline> {
const queryData = await getQueryDataByOperationName('GetTweetReactionTimeline')
return await this.requestGraphQL(queryData, {
tweetId: tweet.id_str,
withHighlightedLabel: false,
withSuperFollowsUserFields: false,
}).then(response => response.data.tweet_result_by_rest_id.result.reaction_timeline)
}
public async getTweetDeckContributees(): Promise<Contributee[]> {
if (!this.options.asTweetDeck) {
throw new Error('this should call from tweetdeck')
}
return await this.request1('get', '/users/contributees.json')
}
private async sendRequest(request: RequestInit, url: URL) {
let newCsrfToken = ''
let maxRetryCount = 3
while (maxRetryCount-- > 0) {
if (newCsrfToken) {
insertHeader(request.headers!, 'x-redblock-override-ct0', newCsrfToken)
}
const response = await fetch(url.toString(), request)
const responseJson = await response.json()
if (response.ok) {
return responseJson
} else {
if (!newCsrfToken) {
newCsrfToken = response.headers.get('x-redblock-new-ct0') || ''
if (newCsrfToken) {
continue
}
}
return Promise.reject(responseJson as Promise<ErrorResponse>)
}
}
}
private async request1(method: HTTPMethods, path: string, paramsObj: URLParamsObj = {}) {
const fetchOptions = await prepareTwitterRequest({ method }, this.options)
const url = new URL(`https://${this.prefix}/1.1${path}`)
let params: URLSearchParams
if (method === 'get') {
params = url.searchParams
} else {
params = new URLSearchParams()
fetchOptions.body = params
}
prepareParams(params, paramsObj)
const cookieStoreId = this.options.cookieStoreId || (await getDefaultCookieStoreId())
// 파이어폭스 외의 다른 브라우저에선 webRequest의 request details에서 cookieStoreId 속성이 없다.
// 따라서 헤더를 통해 알아낼 수 있도록 여기서 헤더를 추가한다.
if (path === '/blocks/create.json') {
insertHeader(fetchOptions.headers!, 'x-redblock-cookie-store-id', cookieStoreId)
}
return this.sendRequest(fetchOptions, url)
}
private async request2(method: HTTPMethods, path: string, paramsObj: URLParamsObj = {}) {
const fetchOptions = await prepareTwitterRequest({ method }, this.options)
const url = new URL(`https://${this.prefix}/2${path}`)
let params: URLSearchParams
if (method === 'get') {
params = url.searchParams
} else {
params = new URLSearchParams()
fetchOptions.body = params
}
prepareParams(params, paramsObj)
return this.sendRequest(fetchOptions, url)
}
private async requestGraphQL(
{ queryId, operationName }: GraphQLQueryData,
variables: URLParamsObj = {}
) {
const fetchOptions = await prepareTwitterRequest({ method: 'get' }, this.options)
const url = new URL(`https://${this.prefix}/graphql/${queryId}/${operationName}`)
const encodedVariables = JSON.stringify(variables)
url.searchParams.set('variables', encodedVariables)
return this.sendRequest(fetchOptions, url)
}
}
function insertHeader(
headers: Headers | Record<string, string> | string[][],
name: string,
value: string
) {
if (headers instanceof Headers) {
headers.set(name, value)
} else if (Array.isArray(headers)) {
headers.push([name, value])
} else {
headers[name] = value
}
}
async function prepareTwitterRequest(
obj: RequestInit,
clientOptions: TwClientOptions
): Promise<RequestInit> {
const headers = new Headers()
// x-csrf-token 헤더는 webrequest.ts 에서 채워줌
if (clientOptions.asTweetDeck) {
headers.set('authorization', `Bearer ${TD_BEARER_TOKEN}`)
headers.set(
'x-twitter-client-version',
'Twitter-TweetDeck-blackbird-chrome/4.0.200604103812 web/'
)
} else {
headers.set('authorization', `Bearer ${BEARER_TOKEN}`)
}
headers.set('x-twitter-active-user', 'yes')
headers.set('x-twitter-auth-type', 'OAuth2Session')
headers.set('x-redblock-request', 'UwU')
const storeId = clientOptions.cookieStoreId
// 컨테이너 탭의 인증정보를 담아 요청하기 위해 덮어씌우는 쿠키
const cookies = await getAllCookies({ storeId })
headers.set(
'x-redblock-override-cookies',
cookies.map(({ name, value }) => `${name}=${value}`).join('; ')
)
// 다계정 로그인 관련
if (clientOptions.actAsUserId) {
if (clientOptions.asTweetDeck) {
headers.set('x-act-as-user-id', clientOptions.actAsUserId)
} else {
const extraCookies = await generateCookiesForAltAccountRequest(clientOptions)
const encodedExtraCookies = new URLSearchParams(
extraCookies as unknown as Record<string, string>
)
headers.set('x-redblock-act-as-cookies', encodedExtraCookies.toString())
}
}
const result: RequestInit = {
method: 'get',
mode: 'cors',
credentials: 'include',
referrer: 'https://twitter.com/',
headers,
}
if (clientOptions.asTweetDeck) {
result.referrer = 'https://tweetdeck.twitter.com/'
}
Object.assign(result, obj)
return result
}
function setDefaultParams(params: URLSearchParams): void {
params.set('include_profile_interstitial_type', '1')
params.set('include_blocking', '1')
params.set('include_blocked_by', '1')
params.set('include_followed_by', '1')
params.set('include_want_retweets', '1')
params.set('include_mute_edge', '1')
params.set('include_can_dm', '1')
params.set('include_quote_count', '1')
params.set('include_can_media_tag', '1')
params.set('skip_status', '1')
params.set('cards_platform', 'Web-12')
params.set('include_cards', '1')
params.set('include_ext_alt_text', 'true')
params.set('include_quote_count', 'true')
params.set('include_reply_count', '1')
params.set('tweet_mode', 'extended')
params.set('include_entities', 'true')
params.set('include_user_entities', 'true')
params.set('include_ext_media_color', 'true')
params.set('include_ext_media_availability', 'true')
params.set('send_error_codes', 'true')
params.set('simple_quoted_tweet', 'true')
params.set(
'ext',
'mediaStats,highlightedLabel,signalsReactionPerspective,signalsReactionMetadata,voiceInfo,birdwatchPivot,superFollowMetadata'
)
}
function prepareParams(params: URLSearchParams, additional: URLParamsObj = {}): void {
setDefaultParams(params)
for (const [key, value] of Object.entries(additional)) {
if (value == null) {
continue
}
params.set(key, value.toString())
}
}
export function getNextCursorFromAPIv2Response(response: APIv2Response): string | null {
try {
const { instructions } = response.timeline
const entries: any[] = []
for (const inst of instructions) {
if ('addEntries' in inst) {
entries.push(...inst.addEntries.entries)
} else if ('replaceEntry' in inst) {
entries.push(inst.replaceEntry.entry)
}
}
entries.reverse()
const bottomEntry = entries.find(entry => entry.entryId === 'sq-cursor-bottom')
if (!bottomEntry) {
return null
}
return bottomEntry.content.operation.cursor.value
} catch (err) {
console.warn('failed to find v2 cursor in %o', response)
if (err instanceof TypeError) {
return null
} else {
throw err
}
}
}
export class RateLimitError extends Error {
public constructor(message: string, public readonly response?: Response) {
super(message)
}
}
interface GraphQLQueryData {
queryId: string
operationName: string
operationType: 'query' | 'mutation'
}
async function fetchGraphQLQueryData() {
if (gqlDataMap.size > 0) {
return
}
const twitter = await fetch('https://twitter.com/').then(resp => resp.text())
const domparser = new DOMParser()
const parsed = domparser.parseFromString(twitter, 'text/html')
const mainScriptTag = parsed.querySelector<HTMLScriptElement>('script[src*="client-web/main."]')!
const mainScript = await fetch(mainScriptTag.src).then(resp => resp.text())
const regexp =
/{queryId:"(?<queryId>[0-9A-Za-z_-]+)",operationName:"(?<operationName>\w+)",operationType:"(?<operationType>\w+)"/g
for (const match of mainScript.matchAll(regexp)) {
const { queryId, operationName, operationType } = match.groups as unknown as GraphQLQueryData
gqlDataMap.set(operationName, { queryId, operationName, operationType })
}
}
async function getQueryDataByOperationName(operationName: string): Promise<GraphQLQueryData> {
if (gqlDataMap.size <= 0) {
await fetchGraphQLQueryData()
}
const queryData = gqlDataMap.get(operationName)
if (!queryData) {
throw new Error('failed to find gql data for: ' + operationName)
}
return queryData
}
export function isTwitterErrorMessage(obj: any): obj is ErrorResponse {
if (obj == null || typeof obj !== 'object') {
return false
}
if (!('errors' in obj && Array.isArray(obj.errors))) {
return false
}
return true
}
export function errorToString(error: unknown): string {
console.error(error)
if (isTwitterErrorMessage(error)) {
return error.errors[0].message
} else if (error instanceof Error) {
return `${error.name}: ${error.message}`
} else {
return String(error)
}
}
type HTTPMethods = 'get' | 'delete' | 'post' | 'put'
type URLParamsObj = {
[key: string]: string | number | boolean | null | undefined | string[] | number[]
}
export interface TwitterUser {
id_str: string
screen_name: string
name: string
blocked_by: boolean
blocking: boolean
muting: boolean
// 1st-party API에선 이 속성이 안 지워진듯. 따라서 그냥 사용한다.
following: boolean
followed_by: boolean
follow_request_sent: boolean
friends_count: number
followers_count: number
protected: boolean
verified: boolean
created_at: string // datetime example: 'Sun Jun 29 05:52:09 +0000 2014'
description: string
profile_image_url_https: string
location: string
status?: Tweet
}
export type TwitterUserEntities = Record<string, TwitterUser>
type ConnectionType =
| 'following'
| 'following_requested'
| 'followed_by'
| 'blocking'
| 'blocked_by'
| 'muting'
| 'none'
interface Friendship {
name: string
screen_name: string
id_str: string
connections: ConnectionType[]
}
type FriendshipResponse = Friendship[]
interface Relationship {
source: {
id_str: string
screen_name: string
following: boolean
followed_by: boolean
live_following: boolean
following_received: boolean
following_requested: boolean
notifications_enabled: boolean
can_dm: boolean
can_media_tag: boolean
blocking: boolean
blocked_by: boolean
muting: boolean
want_retweets: boolean
all_replies: boolean
marked_spam: boolean
}
target: {
id_str: string
screen_name: string
following: boolean
followed_by: boolean
following_received: boolean
following_requested: boolean
}
}
export interface UserListResponse {
next_cursor_str: string
users: TwitterUser[]
}
export interface UserIdsResponse {
next_cursor_str: string
ids: string[]
}
export interface Tweet {
id_str: string
// conversation_id_str: string
user: TwitterUser
// 트윗이 140자 넘으면 얘가 undefined로 나오더라.
// text: string
full_text: string
lang: string
source: string
source_name: string
source_url: string
// possibly_sensitive_editable: boolean
// user_id_str: string
created_at: string
reply_count: number
retweet_count: number
favorite_count: number
favorited: boolean
retweeted: boolean
display_text_range: [number, number]
quote_count: number
is_quote_status: boolean
quoted_status?: Tweet
quoted_status_permalink?: {
// url, display
expanded: string
}
in_reply_to_status_id_str?: string
in_reply_to_user_id_str?: string
in_reply_to_screen_name?: string
entities: {
user_mentions?: UserMentionEntity[]
urls?: UrlEntity[]
}
ext: {
// 남들의 반응
signalsReactionMetadata: SignalsReactionMetadata
// 내 반응. 당장 안 쓰이므로 생략
// signalsReactionPerspective
}
}
interface UserMentionEntity {
id_str: string
name: string
screen_name: string
}
interface UrlEntity {
expanded_url: string
}
export interface AudioSpace {
metadata: {
rest_id: string
state: 'Running' | 'Ended' | 'NotStarted'
title: string
created_at: number // timestamp (ex. 1621037312345)
started_at: number
updated_at: number
scheduled_start: number
is_locked: boolean
}
participants: {
total: number
admins: AudioSpaceParticipant[]
speakers: AudioSpaceParticipant[]
listeners: AudioSpaceParticipant[]
}
}
interface AudioSpaceParticipant {
twitter_screen_name: string
display_name: string
avatar_url: string
}
export interface Limit {
limit: number
remaining: number
reset: number
}
export interface LimitStatus {
application: {
'/application/rate_limit_status': Limit
}
blocks: {
// note: POST API (create, destroy) not exists.
'/blocks/list': Limit
'/blocks/ids': Limit
}
followers: {
'/followers/ids': Limit
'/followers/list': Limit
}
friends: {
'/friends/list': Limit
'/friends/ids': Limit
}
statuses: {
'/statuses/retweeted_by': Limit
'/statuses/retweeters/ids': Limit
'/statuses/retweets/:id': Limit
'/statuses/favorited_by': Limit
}
users: {
'/users/lookup': Limit
}
search: {
'/search/adaptive': Limit
}
}
export interface APIv2Response {
globalObjects: {
tweets: { [tweetId: string]: Tweet }
users: { [userId: string]: TwitterUser }
}
timeline: {
id: string
instructions: any[]
}
}
interface Contributee {
admin: boolean
user: TwitterUser
}
export type ReactionV2Kind = 'Like' | 'Cheer' | 'Hmm' | 'Sad' | 'Haha'
interface SignalsReactionMetadata {
r: {
ok: {
reactionTypeMap: [ReactionV2Kind, number][]
}
}
}
interface ReactionV2MapItem {
type: ReactionV2Kind
count: number
}
interface ReactionV2TimelineEntry {
user_results: {
// 프로텍트 계정 등에서 반응한 경우 유저정보가 없는 빈 object가 온다.
result:
| {
// id: string
rest_id: string
legacy: Omit<TwitterUser, 'id_str'>
}
| {}
}
reaction_type: ReactionV2Kind
}
interface ReactionV2Timeline {
reactionTypeMap: ReactionV2MapItem[]
tweet_reaction_timeline_entries: ReactionV2TimelineEntry[]
}
interface ErrorResponseItem {
code: number
message: string
}
export interface ErrorResponse {
errors: ErrorResponseItem[]
}
type GetMultipleUsersOption = { user_id: string[] } | { screen_name: string[] }
type GetSingleUserOption = { user_id: string } | { screen_name: string } | the_stack |
namespace SchemeDesigner {
/**
* SchemeObject class
* @author Nikitchenko Sergey <nikitchenko.sergey@yandex.ru>
*/
export class SchemeObject
{
/**
* Object unique id
*/
protected id: number;
/**
* X position
*/
protected x: number;
/**
* Y position
*/
protected y: number;
/**
* Width
*/
protected width: number;
/**
* Height
*/
protected height: number;
/**
* Is active
*/
protected active: boolean = true;
/**
* Rotation
*/
protected rotation: number = 0;
/**
* Is hovered
*/
public isHovered: boolean = false;
/**
* Cursor style
*/
public cursorStyle: string = 'pointer';
/**
* Render function
*/
protected renderFunction: Function = function() {};
/**
* Click function
*/
protected clickFunction: Function;
/**
* Mouse over function
*/
protected mouseOverFunction: Function;
/**
* Mouse leave function
*/
protected mouseLeaveFunction: Function;
/**
* Check point in object
*/
protected pointInObjectFunction: Function;
/**
* Clear function
*/
protected clearFunction: Function = function() {};
/**
* All params of object
*/
protected params: any;
/**
* Layer id
*/
protected layerId: string;
/**
* Constructor
* @param {Object} params
*/
constructor(params: any)
{
this.id = Tools.generateUniqueId();
Tools.configure(this, params);
this.params = params;
}
/**
* Set layer id
* @param {string} layerId
*/
public setLayerId(layerId: string)
{
this.layerId = layerId;
}
/**
* Get layer id
* @return {string}
*/
public getLayerId(): string
{
return this.layerId;
}
/**
* Get id
* @returns {number}
*/
public getId(): number
{
return this.id;
}
/**
* Get x
* @returns {number}
*/
public getX(): number
{
return this.x;
}
/**
* Get y
* @returns {number}
*/
public getY(): number
{
return this.y;
}
/**
* Get width
* @returns {number}
*/
public getWidth(): number
{
return this.width;
}
/**
* Get height
* @returns {number}
*/
public getHeight(): number
{
return this.height;
}
/**
* Get params
* @return {any}
*/
public getParams(): any
{
return this.params;
}
/**
* Rendering object
* @param scheme
* @param view
*/
public render(scheme: Scheme, view: View): void
{
this.renderFunction(this, scheme, view);
}
/**
* Clear object
* @param scheme
* @param view
*/
public clear(scheme: Scheme, view: View): void
{
this.clearFunction(this, scheme, view);
}
/**
* Click on object
* @param {MouseEvent} e
* @param {Scheme} schemeDesigner
* @param view
* @return null|boolean
*/
public click(e: MouseEvent, schemeDesigner: Scheme, view: View): null|boolean
{
if (typeof this.clickFunction === 'function') {
return this.clickFunction(this, schemeDesigner, view, e);
}
return null;
}
/**
* Mouse over
* @param {MouseEvent} e
* @param {Scheme} schemeDesigner
* @param view
* @return null|boolean
*/
public mouseOver(e: MouseEvent | TouchEvent, schemeDesigner: Scheme, view: View): null|boolean
{
if (typeof this.mouseOverFunction === 'function') {
return this.mouseOverFunction(this, schemeDesigner, view, e);
}
return null;
}
/**
* Mouse leave
* @param {MouseEvent} e
* @param {Scheme} schemeDesigner
* @param view
* @return null|boolean
*/
public mouseLeave(e: MouseEvent | TouchEvent, schemeDesigner: Scheme, view: View): null|boolean
{
if (typeof this.mouseLeaveFunction === 'function') {
return this.mouseLeaveFunction(this, schemeDesigner, view, e);
}
return null;
}
/**
* Check point in object
* @param point
* @param schemeDesigner
* @param view
* @return boolean
*/
public checkPointInObject(point: Coordinates, schemeDesigner: Scheme, view: View): boolean
{
if (typeof this.pointInObjectFunction === 'function') {
return this.pointInObjectFunction(this, point, schemeDesigner, view);
}
return true;
}
/**
* Set x
* @param {number} value
*/
public setX(value: number): void
{
this.x = value;
}
/**
* Set y
* @param {number} value
*/
public setY(value: number): void
{
this.y = value;
}
/**
* Set width
* @param {number} value
*/
public setWidth(value: number): void
{
this.width = value;
}
/**
* Set height
* @param {number} value
*/
public setHeight(value: number): void
{
this.height = value;
}
/**
* Set cursorStyle
* @param {string} value
*/
public setCursorStyle(value: string): void
{
this.cursorStyle = value;
}
/**
* Set rotation
* @param {number} value
*/
public setRotation(value: number): void
{
this.rotation = value;
}
/**
* Set renderFunction
* @param {Function} value
*/
public setRenderFunction(value: Function): void
{
this.renderFunction = value;
}
/**
* Set clickFunction
* @param {Function} value
*/
public setClickFunction(value: Function): void
{
this.clickFunction = value;
}
/**
* Set clearFunction
* @param {Function} value
*/
public setClearFunction(value: Function): void
{
this.clearFunction = value;
}
/**
* Set mouseOverFunction
* @param {Function} value
*/
public setMouseOverFunction(value: Function): void
{
this.mouseOverFunction = value;
}
/**
* Set mouseLeaveFunction
* @param {Function} value
*/
public setMouseLeaveFunction(value: Function): void
{
this.mouseLeaveFunction = value;
}
/**
* Set pointInObjectFunction
* @param {Function} value
*/
public setPointInObjectFunction(value: Function): void
{
this.pointInObjectFunction = value;
}
/**
* Bounding rect
* @returns BoundingRect
*/
public getBoundingRect(): BoundingRect
{
return {
left: this.x,
top: this.y,
right: this.x + this.width,
bottom: this.y + this.height
};
}
/**
* Outer bound rect
* @returns {BoundingRect}
*/
public getOuterBoundingRect(): BoundingRect
{
let boundingRect = this.getBoundingRect();
if (!this.rotation) {
return boundingRect;
}
// rotate from center
let rectCenterX = (boundingRect.left + boundingRect.right) / 2;
let rectCenterY = (boundingRect.top + boundingRect.bottom) / 2;
let axis: Coordinates = {x: rectCenterX, y: rectCenterY};
let leftTop = Tools.rotatePointByAxis({x: this.x, y: this.y}, axis, this.rotation);
let leftBottom = Tools.rotatePointByAxis({x: this.x, y: this.y + this.height}, axis, this.rotation);
let rightTop = Tools.rotatePointByAxis({x: this.x + this.width, y: this.y}, axis, this.rotation);
let rightBottom = Tools.rotatePointByAxis({x: this.x + this.width, y: this.y + this.height}, axis, this.rotation);
return {
left: Math.min(leftTop.x, leftBottom.x, rightTop.x, rightBottom.x),
top: Math.min(leftTop.y, leftBottom.y, rightTop.y, rightBottom.y),
right: Math.max(leftTop.x, leftBottom.x, rightTop.x, rightBottom.x),
bottom: Math.max(leftTop.y, leftBottom.y, rightTop.y, rightBottom.y),
};
}
/**
* Get rotation
* @returns {number}
*/
public getRotation(): number
{
return this.rotation;
}
/**
* Get is active
* @return {boolean}
*/
public isActive(): boolean
{
return this.active;
}
/**
* Set active
* @param {boolean} value
*/
public setActive(value: boolean): void
{
this.active = value;
}
}
} | the_stack |
import React, {createContext, useContext, useMemo} from 'react'
import cn from 'classnames'
import {Avatar} from '../Avatar/Avatar'
import {Text} from '../Typography/Text'
import {Icon} from '../Icon/Icon'
import {Progress} from '../../icons'
import type {ReactNode, ElementType, HTMLAttributes, ComponentPropsWithoutRef, HTMLProps, PropsWithRef} from 'react'
import type {IconSizeProp} from '../Icon/Icon'
import type {TextSizeProp} from '../Typography/Text'
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'
export type ListVariantProps = 'bullet' | 'number' | 'avatar' | 'progress' | 'icon' | 'contained'
export type ListSizeProp = 'md' | 'lg' | 'xl' | '2xl' | '3xl'
export type ListVerticalPadding = 'py-0' | 'py-2'
interface Props extends HTMLAttributes<HTMLUListElement> {
/**
* The size of the elements of the list.
* @defaultValue md
*/
size?: ListSizeProp
/**
* The font size of the text.
* @defaultValue md
*/
component?: ElementType
}
export type ListProps = PropsWithRef<Props> & {horizontal?: boolean}
const ListContext = createContext<{size: ListSizeProp}>({size: 'md'})
const spaceBetweenList: ListByStringSizes<string> = {
md: 'space-y-3',
lg: 'space-y-2',
xl: 'space-y-2',
'2xl': 'space-y-2',
'3xl': 'space-y-2'
}
type ListByStringSizes<T> = {
[k in ListSizeProp]: T
}
type TextSizes = ListByStringSizes<TextSizeProp>
type ListPaddings = ListByStringSizes<ListVerticalPadding>
const textSize: TextSizes = {
md: 'md',
lg: 'md',
xl: 'lg',
'2xl': 'xl',
'3xl': '2xl'
}
const verticalPadding: ListPaddings = {
md: 'py-0',
lg: 'py-2',
xl: 'py-2',
'2xl': 'py-2',
'3xl': 'py-2'
}
function List({
component: Component = 'ul',
size = 'md',
horizontal = false,
className,
children,
...props
}: ListProps) {
const classes = cn(
`text-gray-600 dark:text-gray-200`,
horizontal ? 'space-y-0' : spaceBetweenList[size],
verticalPadding[size],
className
)
const currentSize = useMemo<ListSizeProp>(() => size, [size])
return (
<ListContext.Provider value={{size: currentSize}}>
<Component
className={classes}
/**
* This role intends to fix the Safari accessibility issue with list-style-type: none
* @see https://www.scottohara.me/blog/2019/01/12/lists-and-safari.html
*/
role="list"
{...props}>
{children}
</Component>
</ListContext.Provider>
)
}
const spaceInnerItems: ListByStringSizes<string> = {
md: 'space-x-2',
lg: 'space-x-2',
xl: 'space-x-2',
'2xl': 'space-x-3',
'3xl': 'space-x-4'
}
function RenderListChildren({children}: {children: ReactNode}) {
const {size} = useContext(ListContext)
return <>{typeof children === 'string' ? <Text size={textSize[size]}>{children}</Text> : children}</>
}
function ListItem(props: ComponentPropsWithoutRef<'li'>) {
const {size} = useContext(ListContext)
const {children, className, ...rest} = props
return (
<li className={cn('flex items-center', spaceInnerItems[size], className)} {...rest}>
<RenderListChildren>{children}</RenderListChildren>
</li>
)
}
function PrefixedItem(props: ComponentPropsWithoutRef<'div'>) {
const {children, ...rest} = props
return (
<div className={cn('flex items-center')} {...rest}>
<RenderListChildren>{children}</RenderListChildren>
</div>
)
}
const containerSize: ListByStringSizes<string> = {
md: 'w-10 h-10',
lg: 'w-14 h-14',
xl: 'w-16 h-16',
'2xl': 'w-20 h-20',
'3xl': 'w-24 h-24'
}
function ListInnerContainer(props: HTMLProps<HTMLDivElement>) {
const {size} = useContext(ListContext)
return <div className={cn('flex items-center justify-center', containerSize[size])} {...props} />
}
const bulletSize: ListByStringSizes<string> = {
md: 'w-1.5 h-1.5',
lg: 'w-2 h-2',
xl: 'w-2.5 h-2.5',
'2xl': 'w-3 h-3',
'3xl': 'w-3.5 h-3.5'
}
function Bullet({size, ...props}: {size: string} & ComponentPropsWithoutRef<'div'>) {
const classes = cn('rounded-full bg-gray-800 dark:bg-gray-200', bulletSize[size], props.className)
return <div {...props} className={classes} />
}
function PrefixedListMarker({isOrdered, listNumber}: {isOrdered: boolean; listNumber: number}) {
const {size} = useContext(ListContext)
return isOrdered ? <Text size={textSize[size]}>{listNumber}.</Text> : <Bullet size={size} />
}
function BuildPrefixedList({component = 'ul', className, ...props}: ListProps) {
const {children, ...rest} = props
const isOrdered = component === 'ol'
const classes = cn(isOrdered ? 'list-decimal' : 'list-disc', 'list-inside', className)
return (
<List className={classes} component="ol" {...rest}>
{React.Children.map(children, (child, index) => {
return (
<ListItem key={`ol-${props.id}-${index}`}>
<ListInnerContainer>
<PrefixedListMarker isOrdered={component === 'ol'} listNumber={index + 1} />
</ListInnerContainer>
{child}
</ListItem>
)
})}
</List>
)
}
function OrderedList({...props}: Exclude<ListProps, 'component'>) {
return <BuildPrefixedList {...props} component="ol" />
}
function UnorderedList({...props}: Exclude<ListProps, 'component'>) {
return <BuildPrefixedList {...props} component="ul" />
}
export type ListAvatarItemProps = HTMLProps<HTMLLIElement> & Pick<HTMLProps<HTMLImageElement>, 'src' | 'alt'>
function ListAvatarItem({src, alt, children, ...props}: ListAvatarItemProps) {
const {size} = useContext(ListContext)
return (
<ListItem {...props}>
<ListInnerContainer>
<Avatar src={src} alt={alt} size={size} />
</ListInnerContainer>
<RenderListChildren>{children}</RenderListChildren>
</ListItem>
)
}
export type ListItemContentProps = {
label: string
description: string
className?: string | string[]
}
const textSizeForLabel: TextSizes = {
md: 'sm',
lg: 'md',
xl: 'lg',
'2xl': 'xl',
'3xl': '2xl'
}
const textSizeForDescription: TextSizes = {
md: 'sm',
lg: 'md',
xl: 'lg',
'2xl': 'lg',
'3xl': 'lg'
}
const spacingBetweenText: ListByStringSizes<string> = {
md: '',
lg: '',
xl: '',
'2xl': 'space-y-0.5',
'3xl': 'space-y-2'
}
function ListItemContent({label, description, className}: ListItemContentProps) {
const {size} = useContext(ListContext)
const isLabelBold = size !== '2xl' && size !== '3xl' && description !== undefined
return (
<div className={cn('flex flex-col w-full', spacingBetweenText[size], className)}>
<Text size={textSizeForLabel[size]} bold={isLabelBold}>
{label}
</Text>
<Text size={textSizeForDescription[size]}>{description}</Text>
</div>
)
}
const iconSize: ListByStringSizes<string> = {
md: 'w-4 h-4',
lg: 'w-4.5 h-4.5',
xl: 'w-5 h-5',
'2xl': 'h-7 w-7',
'3xl': 'h-9 w-9'
}
const faIconSize: ListByStringSizes<string> = {
md: 'text-md',
lg: 'text-lg',
xl: 'text-xl',
'2xl': 'text-2xl',
'3xl': 'text-3xl'
}
export type ListIconProps = HTMLProps<HTMLLIElement> & {icon: ElementType; iconColor?: string}
function ListIconItem({icon, children, iconColor = 'text-current', ...props}: ListIconProps) {
const {size} = useContext(ListContext)
return (
<ListItem {...props}>
<ListInnerContainer>
<Icon icon={icon} variant="ghost" className={cn(iconSize[size], iconColor)} />
</ListInnerContainer>
<RenderListChildren>{children}</RenderListChildren>
</ListItem>
)
}
function ListFAIconItem({icon, children, iconColor = 'text-current', ...props}: ListIconProps) {
const {size} = useContext(ListContext)
return (
<ListItem {...props}>
<ListInnerContainer>
<FontAwesomeIcon icon={icon} className={cn(iconColor, faIconSize[size], props.className)} />
</ListInnerContainer>
<RenderListChildren>{children}</RenderListChildren>
</ListItem>
)
}
const progressIconSize: ListByStringSizes<IconSizeProp> = {
md: 'xs',
lg: 'sm',
xl: 'md',
'2xl': 'lg',
'3xl': 'xl'
}
function ListProgressItem({children, ...props}: HTMLProps<HTMLLIElement>) {
const {size} = useContext(ListContext)
return (
<ListItem {...props}>
<ListInnerContainer>
<Icon
icon={Progress}
variant="solid"
size={progressIconSize[size]}
className="text-gray-800 dark:text-white"
containerProps={{className: 'bg-success-500 dark:bg-success-400'}}
/>
</ListInnerContainer>
<RenderListChildren>{children}</RenderListChildren>
</ListItem>
)
}
export type ListContainedProps = HTMLProps<HTMLLIElement> & {containedValue: number | string}
const containedTextSize: ListByStringSizes<TextSizeProp> = {
md: 'xs',
lg: 'sm',
xl: 'md',
'2xl': 'lg',
'3xl': 'xl'
}
const containedCircleSize: ListByStringSizes<string> = {
md: 'w-4.5 h-4.5',
lg: 'w-6 h-6',
xl: 'w-8 h-8',
'2xl': 'w-10 h-10',
'3xl': 'w-12 h-12'
}
export type ListContainedNumberProps = {
value: string | number
}
function ListContainedNumber({value}: ListContainedNumberProps) {
const {size} = useContext(ListContext)
const isBold = size !== '3xl'
return (
<div
className={cn(
'flex items-center justify-center rounded-full text-gray-50 bg-gray-800',
containedCircleSize[size]
)}>
<Text bold={isBold} size={containedTextSize[size]}>
{value}
</Text>
</div>
)
}
function ListContainedItem({containedValue, children, ...props}: ListContainedProps) {
return (
<ListItem {...props}>
<ListInnerContainer>
<ListContainedNumber value={containedValue} />
</ListInnerContainer>
<RenderListChildren>{children}</RenderListChildren>
</ListItem>
)
}
export {
List,
UnorderedList,
PrefixedItem as UnorderedListItem,
OrderedList,
PrefixedItem as OrderedListItem,
ListItem,
ListInnerContainer,
ListItemContent,
ListAvatarItem,
ListIconItem,
ListFAIconItem,
ListProgressItem,
ListContainedItem,
ListContainedNumber
} | the_stack |
import { Injectable, Autowired, INJECTOR_TOKEN, Injector } from '@opensumi/di';
import { IRPCProtocol } from '@opensumi/ide-connection';
import { Disposable, QuickPickService, localize, formatLocalize, ILogger } from '@opensumi/ide-core-browser';
import {
IAuthenticationService,
IAuthenticationProvider,
AuthenticationSessionsChangeEvent,
AuthenticationSession,
AuthenticationGetSessionOptions,
} from '@opensumi/ide-core-common';
import { IDialogService, IMessageService } from '@opensumi/ide-overlay';
import { IMainThreadAuthentication, ExtHostAPIIdentifier, IExtHostAuthentication } from '../../../common/vscode';
import { IActivationEventService } from '../../types';
@Injectable({ multiple: true })
export class MainThreadAuthenticationProvider extends Disposable implements IAuthenticationProvider {
@Autowired(IAuthenticationService)
protected readonly authenticationService: IAuthenticationService;
@Autowired(QuickPickService)
protected readonly quickPickService: QuickPickService;
@Autowired(IDialogService)
protected readonly dialogService: IDialogService;
@Autowired(IMessageService)
protected readonly messageService: IMessageService;
@Autowired(ILogger)
protected readonly logger: ILogger;
private _accounts = new Map<string, string[]>(); // Map account name to session ids
private _sessions = new Map<string, string>(); // Map account id to name
constructor(
private readonly _proxy: IExtHostAuthentication,
public readonly id: string,
public readonly label: string,
public readonly supportsMultipleAccounts: boolean,
) {
super();
}
public async initialize(): Promise<void> {
return this.registerCommandsAndContextMenuItems();
}
public async manageTrustedExtensions(accountName: string) {
const allowedExtensions = await this.authenticationService.getAllowedExtensions(this.id, accountName);
if (!allowedExtensions.length) {
this.dialogService.info(localize('authentication.noTrustedExtensions'));
return;
}
const usages = await this.authenticationService.getAccountUsages(this.id, accountName);
const items = allowedExtensions.map((extension) => {
const usage = usages.find((usage) => extension.id === usage.extensionId);
return {
label: extension.name,
description: usage ? localize('authentication.accountLastUsedDate') : localize('authentication.notUsed'),
value: extension,
};
});
const trustedExtension = await this.quickPickService.show(items, {
title: localize('authentication.manageTrustedExtensions'),
placeholder: localize('authentication.manageExtensions'),
});
if (trustedExtension) {
await this.authenticationService.setAllowedExtensions(this.id, accountName, [trustedExtension]);
}
}
async signOut(accountName: string): Promise<void> {
const accountUsages = await this.authenticationService.getAccountUsages(this.id, accountName);
const sessionsForAccount = this._accounts.get(accountName);
const message = accountUsages.length
? formatLocalize(
'authentication.signOutMessage',
accountName,
accountUsages.map((usage) => usage.extensionName).join('\n'),
)
: formatLocalize('authentication.signOutMessageSimple', accountName);
const result = await this.dialogService.info(message, [localize('ButtonCancel'), localize('ButtonOK')]);
if (result === localize('ButtonOK')) {
sessionsForAccount?.forEach((sessionId) => this.logout(sessionId));
await this.authenticationService.removeAccountUsage(this.id, accountName);
await this.authenticationService.removeAllowedExtensions(this.id, accountName);
}
}
async getSessions(): Promise<ReadonlyArray<AuthenticationSession>> {
return this._proxy.$getSessions(this.id);
}
public hasSessions(): boolean {
return !!this._sessions.size;
}
async updateSessionItems(event: AuthenticationSessionsChangeEvent): Promise<void> {
const { added, removed } = event;
const session = await this._proxy.$getSessions(this.id);
const addedSessions = session.filter((session) => added.some((s) => s.id === session.id));
removed.forEach((session) => {
const accountName = this._sessions.get(session.id);
if (accountName) {
this._sessions.delete(session.id);
const sessionsForAccount = this._accounts.get(accountName) || [];
const sessionIndex = sessionsForAccount.indexOf(session.id);
sessionsForAccount.splice(sessionIndex);
if (!sessionsForAccount.length) {
this._accounts.delete(accountName);
}
}
});
addedSessions.forEach((session) => this.registerSession(session));
}
private async registerCommandsAndContextMenuItems(): Promise<void> {
try {
const sessions = await this._proxy.$getSessions(this.id);
sessions.forEach((session) => this.registerSession(session));
} catch (err) {
this.logger.error(err);
}
}
private registerSession(session: AuthenticationSession) {
this._sessions.set(session.id, session.account.label);
const existingSessionsForAccount = this._accounts.get(session.account.label);
if (existingSessionsForAccount) {
this._accounts.set(session.account.label, existingSessionsForAccount.concat(session.id));
return;
} else {
this._accounts.set(session.account.label, [session.id]);
}
}
login(scopes: string[]): Promise<AuthenticationSession> {
return this._proxy.$login(this.id, scopes);
}
async logout(sessionId: string): Promise<void> {
await this._proxy.$logout(this.id, sessionId);
this.messageService.info(localize('authentication.signedOut'));
}
}
@Injectable({ multiple: true })
export class MainThreadAuthentication extends Disposable implements IMainThreadAuthentication {
private readonly _proxy: IExtHostAuthentication;
@Autowired(INJECTOR_TOKEN)
protected readonly injector: Injector;
@Autowired(IAuthenticationService)
protected readonly authenticationService: IAuthenticationService;
@Autowired(IDialogService)
protected readonly dialogService: IDialogService;
@Autowired(IMessageService)
protected readonly messageService: IMessageService;
@Autowired(QuickPickService)
protected readonly quickPickService: QuickPickService;
@Autowired(IActivationEventService)
protected readonly activationService: IActivationEventService;
constructor(protocol: IRPCProtocol) {
super();
this._proxy = protocol.getProxy(ExtHostAPIIdentifier.ExtHostAuthentication);
this.addDispose(
this.authenticationService.onDidChangeSessions((e) => {
this._proxy.$onDidChangeAuthenticationSessions(e.providerId, e.label, e.event);
}),
);
this.addDispose(
this.authenticationService.onDidRegisterAuthenticationProvider((info) => {
this._proxy.$onDidChangeAuthenticationProviders([info], []);
}),
);
this.addDispose(
this.authenticationService.onDidUnregisterAuthenticationProvider((info) => {
this._proxy.$onDidChangeAuthenticationProviders([], [info]);
}),
);
}
$getProviderIds(): Promise<string[]> {
return Promise.resolve(this.authenticationService.getProviderIds());
}
async $registerAuthenticationProvider(id: string, label: string, supportsMultipleAccounts: boolean): Promise<void> {
const provider = this.injector.get(MainThreadAuthenticationProvider, [
this._proxy,
id,
label,
supportsMultipleAccounts,
]);
await provider.initialize();
this.authenticationService.registerAuthenticationProvider(id, provider);
this.addDispose(
Disposable.create(() => {
this.$unregisterAuthenticationProvider(id);
}),
);
}
$unregisterAuthenticationProvider(id: string): void {
this.authenticationService.unregisterAuthenticationProvider(id);
}
$ensureProvider(id: string): Promise<void> {
return this.activationService.fireEvent('onAuthenticationRequest', id);
}
$sendDidChangeSessions(id: string, event: AuthenticationSessionsChangeEvent): void {
this.authenticationService.sessionsUpdate(id, event);
}
$getSessions(id: string): Promise<ReadonlyArray<AuthenticationSession>> {
return this.authenticationService.getSessions(id);
}
$login(providerId: string, scopes: string[]): Promise<AuthenticationSession> {
return this.authenticationService.login(providerId, scopes);
}
$logout(providerId: string, sessionId: string): Promise<void> {
return this.authenticationService.logout(providerId, sessionId);
}
private async doGetSession(
providerId: string,
scopes: string[],
extensionId: string,
extensionName: string,
options: AuthenticationGetSessionOptions,
): Promise<AuthenticationSession | undefined> {
const sessions = await this.authenticationService.getSessions(providerId, scopes, true);
const supportsMultipleAccounts = this.authenticationService.supportsMultipleAccounts(providerId);
// Error cases
if (options.forceNewSession && !sessions.length) {
throw new Error('No existing sessions found.');
}
if (options.forceNewSession && options.createIfNone) {
throw new Error(
'Invalid combination of options. Please remove one of the following: forceNewSession, createIfNone',
);
}
if (options.forceNewSession && options.silent) {
throw new Error('Invalid combination of options. Please remove one of the following: forceNewSession, silent');
}
if (options.createIfNone && options.silent) {
throw new Error('Invalid combination of options. Please remove one of the following: createIfNone, silent');
}
// Check if the sessions we have are valid
if (!options.forceNewSession && sessions.length) {
if (supportsMultipleAccounts) {
if (options.clearSessionPreference) {
await this.authenticationService.removeExtensionSessionId(extensionName, providerId);
} else {
const existingSessionPreference = await this.authenticationService.getExtensionSessionId(
extensionName,
providerId,
);
if (existingSessionPreference) {
const matchingSession = sessions.find((session) => session.id === existingSessionPreference);
if (
matchingSession &&
(await this.authenticationService.isAccessAllowed(providerId, matchingSession.account.label, extensionId))
) {
return matchingSession;
}
}
}
} else if (await this.authenticationService.isAccessAllowed(providerId, sessions[0].account.label, extensionId)) {
return sessions[0];
}
}
// We may need to prompt because we don't have a valid session
// modal flows
if (options.createIfNone || options.forceNewSession) {
const providerName = this.authenticationService.getLabel(providerId);
const detail = typeof options.forceNewSession === 'object' ? options.forceNewSession!.detail : undefined;
const isAllowed = await this.loginPrompt(providerName, extensionName, !!options.forceNewSession, detail);
if (!isAllowed) {
throw new Error('User did not consent to login.');
}
const session =
sessions?.length && !options.forceNewSession && supportsMultipleAccounts
? await this.selectSession(
providerId,
providerName,
extensionId,
extensionName,
sessions,
scopes,
!!options.clearSessionPreference,
)
: await this.authenticationService.login(providerId, scopes);
await this.authenticationService.updatedAllowedExtension(
providerId,
session.account.label,
extensionId,
extensionName,
true,
);
await this.authenticationService.setExtensionSessionId(extensionName, providerId, session.id);
return session;
}
// passive flows (silent or default)
const validSession = sessions.find((s) =>
this.authenticationService.isAccessAllowed(providerId, s.account.label, extensionId),
);
if (!options.silent && !validSession) {
await this.authenticationService.requestNewSession(providerId, scopes, extensionId, extensionName);
}
return validSession;
}
async $getSession(
providerId: string,
scopes: string[],
extensionId: string,
extensionName: string,
options: { createIfNone: boolean; clearSessionPreference: boolean },
): Promise<AuthenticationSession | undefined> {
const session = await this.doGetSession(providerId, scopes, extensionId, extensionName, options);
if (session) {
await this.authenticationService.addAccountUsage(providerId, session.account.label, extensionId, extensionName);
}
return session;
}
async selectSession(
providerId: string,
providerName: string,
extensionId: string,
extensionName: string,
potentialSessions: readonly AuthenticationSession[],
scopes: string[],
clearSessionPreference: boolean,
): Promise<AuthenticationSession> {
if (!potentialSessions.length) {
throw new Error('No potential sessions found');
}
if (clearSessionPreference) {
await this.authenticationService.removeExtensionSessionId(extensionName, providerId);
} else {
const existingSessionPreference = await this.authenticationService.getExtensionSessionId(
extensionName,
providerId,
);
if (existingSessionPreference) {
const matchingSession = potentialSessions.find((session) => session.id === existingSessionPreference);
if (matchingSession) {
const allowed = await this.$getSessionsPrompt(
providerId,
matchingSession.account.label,
providerName,
extensionId,
extensionName,
);
if (allowed) {
return matchingSession;
}
}
}
}
const items = potentialSessions.map((session) => ({
label: session.account.label,
value: session,
}));
items.push({
label: localize('authentication.useOtherAccount'),
// 如果登录其他账户则放置一个 undefined 的值用来判断
value: undefined as unknown as AuthenticationSession,
});
const selectedSession = await this.quickPickService.show(items, {
title: formatLocalize('authentication.selectAccount', extensionName, providerName),
placeholder: formatLocalize('authentication.getSessionPlaceholder', extensionName),
ignoreFocusOut: true,
});
const session = selectedSession ?? (await this.authenticationService.login(providerId, scopes));
const accountName = session.account.label;
const allowList = await this.authenticationService.getAllowedExtensions(providerId, accountName);
if (!allowList.find((allowed) => allowed.id === extensionId)) {
allowList.push({ id: extensionId, name: extensionName });
await this.authenticationService.setAllowedExtensions(providerId, accountName, allowList);
}
await this.authenticationService.setExtensionSessionId(extensionName, providerId, session.id);
return session;
}
async $getSessionsPrompt(
providerId: string,
accountName: string,
providerName: string,
extensionId: string,
extensionName: string,
): Promise<boolean> {
const allowList = await this.authenticationService.getAllowedExtensions(providerId, accountName);
const extensionData = allowList.find((extension) => extension.id === extensionId);
if (extensionData) {
await this.authenticationService.addAccountUsage(providerId, accountName, extensionId, extensionName);
return true;
}
const choice = await this.dialogService.info(
formatLocalize('authentication.confirmAuthenticationAccess', extensionName, providerName, accountName),
[localize('ButtonCancel'), localize('ButtonAllow')],
);
const allow = choice === localize('ButtonAllow');
if (allow) {
this.authenticationService.addAccountUsage(providerId, accountName, extensionId, extensionName);
allowList.push({ id: extensionId, name: extensionName });
await this.authenticationService.setAllowedExtensions(providerId, accountName, allowList);
}
return allow;
}
// TODO: dialog detail 待实现
async loginPrompt(
providerName: string,
extensionName: string,
recreatingSession: boolean,
_detail?: string,
): Promise<boolean> {
const choice = await this.dialogService.info(
recreatingSession
? formatLocalize('authentication.confirmReLogin', extensionName, providerName)
: formatLocalize('authentication.confirmLogin', extensionName, providerName),
[localize('ButtonCancel'), localize('ButtonAllow')],
);
return choice === localize('ButtonAllow');
}
async $setTrustedExtensionAndAccountPreference(
providerId: string,
accountName: string,
extensionId: string,
extensionName: string,
sessionId: string,
): Promise<void> {
const allowList = await this.authenticationService.getAllowedExtensions(providerId, accountName);
if (!allowList.find((allowed) => allowed.id === extensionId)) {
allowList.push({ id: extensionId, name: extensionName });
await this.authenticationService.setAllowedExtensions(providerId, accountName, allowList);
}
await this.authenticationService.setExtensionSessionId(extensionName, providerId, sessionId);
await this.authenticationService.addAccountUsage(providerId, accountName, extensionId, extensionName);
}
} | the_stack |
import { Injectable } from '@angular/core';
// services
import { NotificationsService } from '../abstract/notifications.service';
import { LoggerInstance } from '../logger/loggerInstance';
import { LoggerService } from 'src/chat21-core/providers/abstract/logger.service';
// firebase
// import * as firebase from 'firebase/app';
import firebase from "firebase/app";
import 'firebase/messaging';
import 'firebase/auth';
@Injectable({ providedIn: 'root' })
export class FirebaseNotifications extends NotificationsService {
// public BUILD_VERSION: string;
private FCMcurrentToken: string;
private userId: string;
private tenant: string;
private vapidkey: string;
private logger: LoggerService = LoggerInstance.getInstance();
constructor() {
super();
}
initialize(tenant: string, vapId: string): void {
this.tenant = tenant
this.vapidkey = vapId
this.logger.info('[FIREBASE-NOTIFICATIONS] initialize - tenant ', this.tenant)
if (!('serviceWorker' in navigator)) {
// , disable or hide UI.
this.logger.error("[FIREBASE-NOTIFICATIONS] initialize - Service Worker isn't supported on this browser", navigator)
return;
}
if (('serviceWorker' in navigator)) {
// this.logger.log("[FIREBASE-NOTIFICATIONS] initialize - Service Worker is supported on this browser ", navigator)
navigator.serviceWorker.getRegistrations().then((serviceWorkerRegistrations) => {
this.logger.log("[FIREBASE-NOTIFICATIONS] initialize - Service Worker is supported on this browser serviceWorkerRegistrations", serviceWorkerRegistrations)
if (serviceWorkerRegistrations.length > 0) {
serviceWorkerRegistrations.forEach(registration => {
this.logger.log("[FIREBASE-NOTIFICATIONS] initialize - Service Worker is supported on this browser registration ", registration)
// this.logger.log("[FIREBASE-NOTIFICATIONS] initialize - Service Worker is supported on this browser registrations scriptURL", registrations.active.scriptURL)
// this.logger.log("[FIREBASE-NOTIFICATIONS] initialize - Service Worker is supported on this browser registrations state", registrations.active.state)
});
} else {
this.logger.log("[FIREBASE-NOTIFICATIONS] initialize - Service Worker is supported on this browser - !not registered",)
// navigator.serviceWorker.register('http://localhost:8101/firebase-messaging-sw.js')
// .then(function (registration) {
// console.log('Service worker successfully registered.');
// return registration;
// }).catch(function (err) {
// console.error('Unable to register service worker.', err);
// });
}
});
}
}
getNotificationPermissionAndSaveToken(currentUserUid) {
// this.tenant = this.getTenant();
this.logger.log('initialize FROM [APP-COMP] - [FIREBASE-NOTIFICATIONS] calling requestPermission - tenant ', this.tenant, ' currentUserUid ', currentUserUid)
// this.logger.log('[FIREBASE-NOTIFICATIONS] calling requestPermission - currentUserUid ', currentUserUid)
this.userId = currentUserUid;
// Service Worker explicit registration to explicitly define sw location at a path,
// const swRegistration = async () => {
// try {
// await navigator.serviceWorker.register('http://localhost:8101/firebase-messaging-sw.js');
// } catch (error) {
// console.error(error);
// }
// }
if (firebase.messaging.isSupported()) {
const messaging = firebase.messaging();
// messaging.requestPermission()
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
this.logger.log('[FIREBASE-NOTIFICATIONS] >>>> requestPermission Notification permission granted.');
return messaging.getToken({ vapidKey: this.vapidkey })
}
}).then(FCMtoken => {
this.logger.log('[FIREBASE-NOTIFICATIONS] >>>> requestPermission FCMtoken', FCMtoken)
// Save FCM Token in Firebase
this.FCMcurrentToken = FCMtoken;
this.updateToken(FCMtoken, currentUserUid)
}).catch((err) => {
this.logger.error('[FIREBASE-NOTIFICATIONS] >>>> requestPermission ERR: Unable to get permission to notify.', err);
});
} else {
this.logger.log('[FIREBASE-NOTIFICATIONS] >>>> FIREBASE MESSAGING IS NOT SUPPORTED')
}
}
// getNotificationPermissionAndSaveToken(currentUserUid) {
// // this.tenant = this.getTenant();
// this.logger.log('[FIREBASE-NOTIFICATIONS] calling requestPermission - tenant ', this.tenant)
// this.logger.log('[FIREBASE-NOTIFICATIONS] calling requestPermission - currentUserUid ', currentUserUid)
// this.userId = currentUserUid;
// const messaging = firebase.messaging();
// if (firebase.messaging.isSupported()) {
// // messaging.requestPermission()
// Notification.requestPermission().then((permission) => {
// if (permission === 'granted') {
// this.logger.log('[FIREBASE-NOTIFICATIONS] >>>> requestPermission Notification permission granted.');
// messaging.getToken({ vapidKey: 'BOsgS2ADwspKdWAmiFDZXEYqY1HSYADVfJT3j67wsySh3NxaViJqoabPJH8WM02wb5r8cQIm5TgM0UK047Z1D1c'}).then((currentToken) => {
// if (currentToken) {
// this.sendTokenToServer(currentToken);
// // updateUIForPushEnabled(currentToken);
// } else {
// // Show permission request UI
// console.log('No registration token available. Request permission to generate one.');
// // ...
// }
// }).catch((err) => {
// console.log('An error occurred while retrieving token. ', err);
// // ...
// });
// resetUI()
// } else {
// this.logger.error('Unable to get permission to notify.');
// }
// })
// }
// }
// sendTokenToServer(currentToken) {
// if (!this.isTokenSentToServer()) {
// console.log('Sending token to server...');
// // TODO(developer): Send the current token to your server.
// this.setTokenSentToServer(true);
// } else {
// console.log('Token already sent to server so won\'t send it again ' +
// 'unless it changes');
// }
// }
// isTokenSentToServer() {
// return window.localStorage.getItem('sentToServer') === '1';
// }
// setTokenSentToServer(sent) {
// window.localStorage.setItem('sentToServer', sent ? '1' : '0');
// }
removeNotificationsInstance(callback: (string) => void) {
var self = this;
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
self.logger.debug('[FIREBASE-NOTIFICATIONS] - FB User is signed in. ', user)
self.logger.log('[FIREBASE-NOTIFICATIONS] >>>> removeNotificationsInstance > this.userId', self.userId);
self.logger.log('[FIREBASE-NOTIFICATIONS] >>>> removeNotificationsInstance > FCMcurrentToken', self.FCMcurrentToken);
// this.logger.log('[FIREBASE-NOTIFICATIONS] >>>> removeNotificationsInstance > this.tenant', this.tenant);
} else {
self.logger.debug('[FIREBASE-NOTIFICATIONS] - No FB user is signed in. ', user)
}
});
const urlNodeFirebase = '/apps/' + self.tenant
const connectionsRefinstancesId = urlNodeFirebase + '/users/' + self.userId + '/instances/'
self.logger.log('[FIREBASE-NOTIFICATIONS] >>>> connectionsRefinstancesId ', connectionsRefinstancesId);
let connectionsRefURL = '';
if (connectionsRefinstancesId) {
connectionsRefURL = connectionsRefinstancesId + self.FCMcurrentToken;
const connectionsRef = firebase.database().ref().child(connectionsRefURL);
self.logger.log('[FIREBASE-NOTIFICATIONS] >>>> connectionsRef ', connectionsRef);
self.logger.log('[FIREBASE-NOTIFICATIONS] >>>> connectionsRef url ', connectionsRefURL);
connectionsRef.off()
connectionsRef.remove()
.then(() => {
self.logger.log("[FIREBASE-NOTIFICATIONS] >>>> removeNotificationsInstance > Remove succeeded.")
callback('success')
}).catch((error) => {
self.logger.error("[FIREBASE-NOTIFICATIONS] >>>> removeNotificationsInstance Remove failed: " + error.message)
callback('error')
}).finally(() => {
self.logger.log('[FIREBASE-NOTIFICATIONS] COMPLETED');
})
}
}
// removeNotificationsInstance() {
// let promise = new Promise((resolve, reject) => {
// this.appStoreService.getInstallation(this.projectId).then((res) => {
// console.log("Get Installation Response: ", res);
// resolve(res);
// }).catch((err) => {
// console.error("Error getting installation: ", err);
// reject(err);
// })
// })
// return promise;
// }
// ********** PRIVATE METHOD - START ****************//
private updateToken(FCMcurrentToken, currentUserUid) {
this.logger.log('[FIREBASE-NOTIFICATIONS] >>>> getPermission > updateToken ', FCMcurrentToken);
// this.afAuth.authState.take(1).subscribe(user => {
if (!currentUserUid || !FCMcurrentToken) {
return
};
const connection = FCMcurrentToken;
const updates = {};
const urlNodeFirebase = '/apps/' + this.tenant
const connectionsRefinstancesId = urlNodeFirebase + '/users/' + currentUserUid + '/instances/';
// this.connectionsRefinstancesId = this.urlNodeFirebase + "/users/" + userUid + "/instances/";
const device_model = {
device_model: navigator.userAgent,
language: navigator.language,
platform: 'ionic',
platform_version: this.BUILD_VERSION
}
updates[connectionsRefinstancesId + connection] = device_model;
this.logger.log('[FIREBASE-NOTIFICATIONS] >>>> getPermission > updateToken in DB', updates);
firebase.database().ref().update(updates)
}
// ********** PRIVATE METHOD - END ****************//
} | the_stack |
import { walkPreOrder, walk } from '../walker';
import { Nodes } from '../nodes';
import { ParsingContext } from '../ParsingContext';
import {
Type,
TypeHelpers,
InjectableTypes,
TypeType,
TypeAlias,
FunctionType,
UnionType,
IntersectionType,
areEqualTypes,
RefType,
NeverType,
NativeTypes,
UNRESOLVED_TYPE,
TraitType,
StackType,
StructType,
FunctionSignatureType
} from '../types';
import { isValidType } from './typeHelpers';
import { annotations, Annotation, IAnnotationConstructor } from '../annotations';
import {
UnexpectedType,
NotAValidType,
LysTypeError,
CannotInferReturnType,
UnreachableCode,
TypeMismatch,
NotAFunction,
InvalidOverload,
InvalidCall,
DEBUG_TYPES
} from '../NodeError';
import { last, flatten } from '../helpers';
import { MessageCollector } from '../MessageCollector';
import { printAST } from '../../utils/astPrinter';
import { getDocument } from '../phases/helpers';
import { Scope } from '../Scope';
// At some point, we'll cut off the analysis passes and assume
// we're making no forward progress. This should happen only
// on the case of bugs in the analyzer.
export const MaxAnalysisPassCount = 100;
function createTypeAlias(name: Nodes.NameIdentifierNode, value: Type, parsingContext: ParsingContext) {
const document = getDocument(name);
if (!document) throw new LysTypeError('Cannot find document', name);
const discriminant = parsingContext.getTypeDiscriminant(document.moduleName, name.name);
const alias = new TypeAlias(name, value);
alias.discriminant = discriminant;
return alias;
}
export type LysPropertyDescription = {
type: Type;
setter: boolean;
getter: boolean;
method: boolean;
};
export abstract class TypeResolver {
public didAnalysisChange = false;
public nodeAnnotations = new Map<Nodes.Node, Set<Annotation>>();
private nonResolvedNodes = new Set<Nodes.Node>();
private readonly walk = walkPreOrder(this.onEnterNode.bind(this), this.onLeaveNode.bind(this));
constructor(
public documentNode: Nodes.DocumentNode,
public parsingContext: ParsingContext,
public messageCollector: MessageCollector = new MessageCollector()
) {}
analyze() {
this.didAnalysisChange = false;
this.messageCollector.errors.length = 0;
this.nonResolvedNodes.clear();
this.nodeAnnotations.clear();
this.walk(this.documentNode, this.parsingContext);
this.documentNode.analysis.version++;
// If we've already analyzed the file the max number of times,
// just give up and admit defeat. This should happen only in
// the case of analyzer bugs.
if (this.documentNode.analysis.version >= MaxAnalysisPassCount) {
this.messageCollector.error(
`Hit max analysis pass count for ${this.documentNode.moduleName}`,
this.documentNode.astNode
);
return false;
}
return this.didAnalysisChange;
}
requiresTypeAnalysis(): boolean {
if (this.documentNode.analysis.version >= MaxAnalysisPassCount) {
return false;
}
if (this.didAnalysisChange) {
return true;
}
let allTypesResolved = true;
walk(this.documentNode, this.parsingContext, node => {
if (node instanceof Nodes.ExpressionNode) {
if (!node.isTypeResolved) {
allTypesResolved = false;
this.nonResolvedNodes.add(node);
return false;
}
}
if (node instanceof Nodes.FunctionNode) {
if (!isValidType(this.getType(node.functionName))) {
allTypesResolved = false;
this.nonResolvedNodes.add(node);
return false;
}
}
if (node instanceof Nodes.TypeNode) {
if (!isValidType(this.getType(node))) {
allTypesResolved = false;
this.nonResolvedNodes.add(node);
return false;
}
}
if (node instanceof Nodes.TypeDirectiveNode) {
if (!isValidType(this.getType(node.variableName))) {
allTypesResolved = false;
this.nonResolvedNodes.add(node);
return false;
}
}
if (node instanceof Nodes.OverloadedFunctionNode) {
if (!isValidType(this.getType(node.functionName))) {
allTypesResolved = false;
this.nonResolvedNodes.add(node);
return false;
}
}
});
if (DEBUG_TYPES) {
this.nonResolvedNodes.forEach($ => console.log(printAST($)));
}
this.documentNode.analysis.areTypesResolved = allTypesResolved;
return !allTypesResolved;
}
protected abstract onLeaveNode(
node: Nodes.Node,
parsingContext: ParsingContext,
parent: Nodes.Node | null
): void | boolean;
protected abstract onEnterNode(_node: Nodes.Node, parsingContext: ParsingContext, parent: Nodes.Node | null): void;
protected setType(node: Nodes.Node, type: Type | null) {
const currentType = TypeHelpers.getNodeType(node);
const areEqual = (currentType && type && areEqualTypes(type, currentType)) || false;
TypeHelpers.setNodeType(node, type);
if (type === UNRESOLVED_TYPE) {
node.isTypeResolved = false;
}
if (!areEqual && type) {
this.setAnalysisChanged();
}
}
protected removeStashedNodeAnnotation(node: Nodes.Node, annotation: Annotation): boolean {
const annotations = this.nodeAnnotations.get(node);
if (!annotations) return false;
return annotations.delete(annotation);
}
protected getStashedNodeAnnotation<T extends Annotation>(
node: Nodes.Node,
klass: IAnnotationConstructor<T>
): T | null {
const annotations = this.nodeAnnotations.get(node);
if (!annotations) return null;
for (let annotation of annotations) {
if (annotation instanceof klass) return annotation;
}
return null;
}
protected stashNodeAnnotation(node: Nodes.Node, annotation: Annotation) {
const annotations = this.nodeAnnotations.get(node) || new Set();
if (!this.nodeAnnotations.has(node)) {
this.nodeAnnotations.set(node, annotations);
}
annotations.add(annotation);
}
protected getType(node: Nodes.Node): Type | null {
const type = TypeHelpers.getNodeType(node);
return type;
}
protected setAnalysisChanged() {
this.didAnalysisChange = true;
}
}
export class TypeAnalyzer extends TypeResolver {
protected onLeaveNode(node: Nodes.Node, _parsingContext: ParsingContext, parent: Nodes.Node) {
if (!node.scope) {
this.messageCollector.errorIfBranchDoesntHaveAny(`Node ${node.nodeName} has no scope`, node);
return;
}
const nodeScope = node.scope;
if (node instanceof Nodes.MatcherNode) {
console.assert(parent instanceof Nodes.PatternMatcherNode);
this.processMatcherNode(node, parent as Nodes.PatternMatcherNode);
} else if (node instanceof Nodes.LiteralNode) {
if (node.resolvedReference) {
const type = this.getType(node.resolvedReference.referencedNode);
this.setType(node, this.getTypeTypeType(node, type, this.messageCollector));
}
} else if (node instanceof Nodes.ReferenceNode) {
if (node.resolvedReference) {
const type = this.getType(node.resolvedReference.referencedNode);
if (isValidType(type)) {
if (type instanceof TypeType && node.hasAnnotation(annotations.IsValueNode)) {
if (type.of instanceof TypeAlias) {
const fnType = this.resolveTypeMember(node, type.of, 'apply', this.messageCollector, nodeScope);
// TODO: a better error would be X is not callable
if (fnType) {
const fun = this.findFunctionOverload(
fnType,
[],
node,
null,
false,
this.messageCollector,
true,
nodeScope
);
if (isValidType(fun) && fun instanceof FunctionType) {
this.annotateImplicitCall(node, fun, [], this.messageCollector, nodeScope);
if (fun.signature.returnType) {
this.setType(node, fun.signature.returnType);
return;
}
}
this.messageCollector.errorIfBranchDoesntHaveAny(type.inspect(100), node);
}
}
this.messageCollector.error(new UnexpectedType(type, node));
} else if (type instanceof FunctionSignatureType && node.hasAnnotation(annotations.IsValueNode)) {
const currentAnnotation = this.getStashedNodeAnnotation(node, annotations.IsFunctionReference);
if (currentAnnotation) {
currentAnnotation.fun = type;
} else {
this.stashNodeAnnotation(node, new annotations.IsFunctionReference(type));
}
}
this.setType(node, type);
} else {
this.messageCollector.errorIfBranchDoesntHaveAny(
`Unable to resolve name "${node.resolvedReference.toString()}"${(type &&
' ' + (type as any).inspect(100)) ||
printAST(node.resolvedReference.referencedNode)}`,
node
);
if (node.resolvedReference.moduleName) {
if (!this.documentNode.importedModules.has(node.resolvedReference.moduleName)) {
this.messageCollector.errorIfBranchDoesntHaveAny(
`Document is not importing "${node.resolvedReference.moduleName}"`,
node
);
}
}
this.setType(node, UNRESOLVED_TYPE);
}
} else {
this.messageCollector.errorIfBranchDoesntHaveAny('Unable to resolve name', node);
}
} else if (node instanceof Nodes.IsExpressionNode) {
const booleanType = node.booleanReference
? this.getTypeTypeType(node, this.getType(node.booleanReference.referencedNode), this.messageCollector)
: null;
const lhsType = this.getType(node.lhs);
const rhsType = this.getTypeTypeType(node.rhs, this.getType(node.rhs), this.messageCollector);
if (isValidType(lhsType)) {
if (!this.canBeAssigned(lhsType, RefType.instance, nodeScope)) {
this.messageCollector.error(
`"is" expression can only be used with reference types, used with: "${lhsType}"`,
node.astNode
);
this.setType(node, booleanType);
return;
}
if (isValidType(rhsType)) {
const valueType = this.resolveTypeMember(node.rhs, rhsType, 'is', this.messageCollector, nodeScope);
if (valueType) {
const fun = this.findFunctionOverload(
valueType,
[rhsType],
node,
null,
false,
this.messageCollector,
false,
nodeScope
);
if (fun instanceof FunctionType) {
node.resolvedFunctionType = fun;
this.setType(node, fun.signature.returnType!);
return;
} else {
this.messageCollector.error(
`This statement is always false, type "${lhsType}" can never be "${rhsType}". "${rhsType}" has no overload for \`fun is(arg: ${lhsType}): boolean\`.`,
node.astNode
);
this.setType(node, booleanType);
}
} else {
this.messageCollector.error(
`This statement is always false, type "${lhsType}" can never be "${rhsType}". "${rhsType}" has no "is" function implementation.`,
node.astNode
);
this.setType(node, booleanType);
}
} else {
this.messageCollector.errorIfBranchDoesntHaveAny(`Error with "is"`, node.rhs);
this.setType(node, booleanType);
}
} else {
this.messageCollector.errorIfBranchDoesntHaveAny(`Error with "is"`, node.lhs);
this.setType(node, booleanType);
}
} else if (node instanceof Nodes.AsExpressionNode) {
const lhsType = this.getType(node.lhs);
if (isValidType(lhsType)) {
const rhsType = this.getTypeTypeType(node.rhs, this.getType(node.rhs), this.messageCollector);
if (isValidType(rhsType)) {
if (lhsType.equals(rhsType) && rhsType.equals(lhsType)) {
this.messageCollector.warning(`This cast is useless "${lhsType}" as "${rhsType}"`, node);
if (!node.hasAnnotation(annotations.ByPassFunction)) {
this.stashNodeAnnotation(node, new annotations.ByPassFunction());
}
this.setType(node, rhsType);
return;
}
const memberType = this.resolveTypeMember(node.lhs, lhsType, 'as', this.messageCollector, nodeScope);
if (memberType) {
const fun = this.findFunctionOverload(
memberType,
[lhsType],
node,
rhsType,
false,
new MessageCollector(),
false,
nodeScope
);
if (fun instanceof FunctionType && isValidType(fun.signature.returnType)) {
this.annotateImplicitCall(node, fun, [node.lhs], this.messageCollector, nodeScope);
this.setType(node, fun.signature.returnType);
} else {
this.messageCollector.errorIfBranchDoesntHaveAny(
new LysTypeError(`Cannot convert type "${lhsType}" into "${rhsType}"`, node.lhs)
);
this.setType(node, UNRESOLVED_TYPE);
}
}
} else {
this.messageCollector.errorIfBranchDoesntHaveAny('Cannot resolve type 1', node.rhs);
}
} else {
this.messageCollector.errorIfBranchDoesntHaveAny('Cannot resolve type 2', node.lhs);
}
} else if (node instanceof Nodes.BinaryExpressionNode) {
const lhsType = this.getType(node.lhs);
const rhsType = this.getType(node.rhs);
if (isValidType(lhsType)) {
const memberName = node.operator.name;
const memberType = this.resolveTypeMember(node, lhsType, memberName, this.messageCollector, nodeScope);
if (memberType) {
if (isValidType(rhsType)) {
const argumentTypes = [lhsType, rhsType];
const fun = this.findFunctionOverload(
memberType,
argumentTypes,
node,
null,
false,
this.messageCollector,
true,
nodeScope
);
if (isValidType(fun) && fun instanceof FunctionType) {
this.annotateImplicitCall(node, fun, [node.lhs, node.rhs], this.messageCollector, nodeScope);
this.setType(node, fun.signature.returnType!);
} else {
this.setType(node, UNRESOLVED_TYPE);
}
} else {
this.messageCollector.errorIfBranchDoesntHaveAny('Cannot resolve type 3', node.rhs);
}
} else {
this.setType(node, UNRESOLVED_TYPE);
}
} else {
this.messageCollector.errorIfBranchDoesntHaveAny('Cannot resolve type 4 ' + printAST(node.lhs), node.lhs);
this.setType(node, UNRESOLVED_TYPE);
}
} else if (node instanceof Nodes.UnaryExpressionNode) {
const rhsType = this.getType(node.rhs);
if (isValidType(rhsType)) {
const memberName = node.operator.name;
const memberType = this.resolveTypeMember(node, rhsType, memberName, this.messageCollector, nodeScope);
if (memberType) {
const argumentTypes = [rhsType];
const fun = this.findFunctionOverload(
memberType,
argumentTypes,
node,
null,
false,
new MessageCollector(),
true,
nodeScope
);
if (isValidType(fun) && fun instanceof FunctionType) {
this.annotateImplicitCall(node, fun, node.argumentsNode, this.messageCollector, nodeScope);
this.setType(node, fun.signature.returnType!);
} else {
this.messageCollector.errorIfBranchDoesntHaveAny(
`Cannot apply operator "${memberName}" in type "${rhsType}"`,
node
);
this.setType(node, rhsType);
}
}
}
} else if (node instanceof Nodes.IfNode) {
const condition = this.getType(node.condition);
const booleanType = node.booleanReference
? this.getTypeTypeType(
node.condition,
this.getType(node.booleanReference.referencedNode),
this.messageCollector
)
: null;
const truePart = this.getType(node.truePart);
if (condition) {
if (booleanType) {
this.ensureCanBeAssignedWithImplicitConversion(
condition,
booleanType,
node.condition,
this.messageCollector,
nodeScope
);
} else {
this.messageCollector.error('Cannot resolve "boolean"', node.condition.astNode);
}
}
if (node.hasAnnotation(annotations.IsValueNode)) {
if (!node.falsePart) {
this.messageCollector.error('A ternary operation requires an else branch', node.astNode);
}
if (isValidType(truePart)) {
const falsePart = node.falsePart ? this.getType(node.falsePart) : null;
if (isValidType(falsePart)) {
this.setType(node, new UnionType([truePart, falsePart]).simplify(nodeScope));
} else {
this.messageCollector.error('Else not resolved', node.astNode);
this.setType(node, new UnionType([truePart, UNRESOLVED_TYPE]).simplify(nodeScope));
}
return;
}
} else {
this.setType(node, InjectableTypes.void);
}
} else if (node instanceof Nodes.AssignmentNode) {
const lhsType = this.getType(node.lhs);
const rhsType = this.getType(node.rhs);
if (!isValidType(lhsType)) {
this.messageCollector.error('Cannot resolve type', node.lhs.astNode);
return;
}
if (!isValidType(rhsType)) {
this.messageCollector.error('Cannot resolve type', node.rhs.astNode);
return;
}
// TODO: unhack my heart
if (node.lhs instanceof Nodes.MemberNode) {
const call = this.getStashedNodeAnnotation(node.lhs, annotations.ImplicitCall);
if (call) {
this.messageCollector.error('!!!1 This node already has an ' + call.toString(), node.lhs.astNode);
return;
}
const prop = this.describeProperty(lhsType);
if (prop) {
if (prop.setter) {
const memberLhsType = this.getType(node.lhs.lhs)!;
const fun = this.findFunctionOverload(
lhsType,
[memberLhsType, rhsType],
node.lhs,
null,
false,
this.messageCollector,
true,
nodeScope
);
if (isValidType(fun) && fun instanceof FunctionType) {
if (!fun.name.hasAnnotation(annotations.Setter)) {
this.messageCollector.error(
new LysTypeError(
`Cannot assign to "${node.lhs.memberName.name}" because it is a read-only property.`,
node.lhs.memberName
)
);
this.setType(node, UNRESOLVED_TYPE);
} else {
this.annotateImplicitCall(node, fun, [node.lhs.lhs, node.rhs], this.messageCollector, nodeScope);
this.setType(node, fun.signature.returnType!);
}
} else {
this.messageCollector.error('Overload not found', node.rhs.astNode);
this.setType(node, UNRESOLVED_TYPE);
return;
}
} else {
this.messageCollector.error(
new LysTypeError(
`Cannot assign to "${node.lhs.memberName.name}" because it is a read-only property.`,
node.lhs.memberName
)
);
this.setType(node, UNRESOLVED_TYPE);
}
} else {
if (!this.messageCollector.hasErrorForBranch(node.lhs.astNode)) {
this.messageCollector.error('Invalid property !', node.lhs.astNode);
}
this.setType(node, UNRESOLVED_TYPE);
return;
}
} else if (node.lhs instanceof Nodes.BinaryExpressionNode) {
const call = this.getStashedNodeAnnotation(node.lhs, annotations.ImplicitCall);
if (call) {
this.removeStashedNodeAnnotation(node.lhs, call);
}
const memberLhsType = this.getType(node.lhs.lhs);
const memberRhsType = this.getType(node.lhs.rhs);
if (!isValidType(memberLhsType)) {
this.messageCollector.error('Cannot resolve type', node.lhs.lhs.astNode);
return;
}
if (!isValidType(memberRhsType)) {
this.messageCollector.error('Cannot resolve type', node.lhs.rhs.astNode);
return;
}
const memberName = node.lhs.operator.name;
const memberType = this.resolveTypeMember(node, memberLhsType, memberName, this.messageCollector, nodeScope);
if (memberType) {
const fun = this.findFunctionOverload(
memberType,
[memberLhsType, memberRhsType, rhsType],
node.lhs,
null,
false,
this.messageCollector,
true,
node.lhs.scope!
);
if (isValidType(fun) && fun instanceof FunctionType) {
this.annotateImplicitCall(
node,
fun,
[node.lhs.lhs, node.lhs.rhs, node.rhs],
this.messageCollector,
nodeScope
);
this.setType(node, fun.signature.returnType!);
} else {
this.messageCollector.error('Overload not found', node.rhs.astNode);
}
} else {
this.setType(node, UNRESOLVED_TYPE);
}
} else {
const result = this.ensureCanBeAssignedWithImplicitConversion(
rhsType,
lhsType,
node.rhs,
this.messageCollector,
nodeScope
);
if (!NeverType.isNeverType(rhsType) && rhsType.nativeType === NativeTypes.void) {
this.messageCollector.error(
'The expression returns a void value, which cannot be assigned to any value',
node.rhs.astNode
);
}
if (node.hasAnnotation(annotations.IsValueNode)) {
this.setType(node, result.type);
} else {
this.setType(node, InjectableTypes.void);
}
}
} else if (node instanceof Nodes.FunctionCallNode) {
const functionType = this.getType(node.functionNode);
if (isValidType(functionType)) {
const argumentTypes = node.argumentsNode.map($ => this.getType($)!);
const validArguments = argumentTypes.every($ => isValidType($));
if (validArguments && isValidType(functionType)) {
if (
node.functionNode instanceof Nodes.MemberNode &&
this.getStashedNodeAnnotation(node.functionNode, annotations.MethodCall)
) {
// Detect if we are calling a <instance>.method(...)
// to inject the "self" argument
const fun = this.findFunctionOverload(
functionType,
[this.getType(node.functionNode.lhs)!, ...argumentTypes],
node,
null,
false,
this.messageCollector,
true,
nodeScope
);
if (isValidType(fun) && fun instanceof FunctionType) {
this.annotateImplicitCall(
node,
fun,
[node.functionNode.lhs, ...node.argumentsNode],
this.messageCollector,
nodeScope
);
this.setType(node, fun.signature.returnType!);
} else {
this.setType(node, UNRESOLVED_TYPE);
}
} else {
const fun = this.findFunctionOverload(
functionType,
argumentTypes,
node,
null,
false,
this.messageCollector,
true,
nodeScope
);
if (isValidType(fun) && fun instanceof FunctionType) {
this.annotateImplicitCall(node, fun, node.argumentsNode, this.messageCollector, nodeScope);
this.setType(node, fun.signature.returnType!);
} else if (isValidType(fun) && fun instanceof FunctionSignatureType) {
const currentAnnotation = this.getStashedNodeAnnotation(node, annotations.IsFunctionReference);
if (currentAnnotation) {
currentAnnotation.fun = fun;
} else {
this.stashNodeAnnotation(node, new annotations.IsFunctionReference(fun));
}
this.setType(node, fun.returnType!);
} else {
this.setType(node, UNRESOLVED_TYPE);
}
}
}
} else {
this.messageCollector.errorIfBranchDoesntHaveAny('Not a function', node.functionNode);
}
} else if (node instanceof Nodes.FunctionNode) {
const functionType = new FunctionType(node.functionName);
node.parameters.forEach(($, ix) => {
const parameterType = this.getType($.parameterName);
functionType.signature.parameterNames[ix] = $.parameterName.name;
functionType.signature.parameterTypes[ix] = parameterType!;
});
const retType = node.functionReturnType
? this.getTypeFromTypeNode(node.functionReturnType, this.messageCollector)
: null;
if (isValidType(retType)) {
functionType.signature.returnType = retType;
} else {
this.messageCollector.errorIfBranchDoesntHaveAny('Cannot resolve return type', node.functionReturnType || node);
}
if (node.body) {
const inferedReturnType = this.getType(node.body);
if (inferedReturnType) {
if (inferedReturnType instanceof TypeType) {
this.messageCollector.error(new UnexpectedType(inferedReturnType, node.body));
} else {
this.ensureCanBeAssignedWithImplicitConversion(
inferedReturnType,
functionType.signature.returnType!,
node.body,
this.messageCollector,
nodeScope
);
}
} else {
this.messageCollector.errorIfBranchDoesntHaveAny(new CannotInferReturnType(node.body || node));
}
}
this.setType(node.functionName, functionType);
} else if (node instanceof Nodes.ParameterNode) {
// TODO: const valueType = TypeHelpers.getNodeType(node.defaultValue);
// TODO: verify assignability
const typeType = node.parameterType ? this.getTypeFromTypeNode(node.parameterType, this.messageCollector) : null;
if (isValidType(typeType)) {
this.setType(node.parameterName, typeType);
} else {
this.messageCollector.errorIfBranchDoesntHaveAny('Cannot infer type 6' + typeType, node);
}
} else if (node instanceof Nodes.VarDeclarationNode) {
const valueType = TypeHelpers.getNodeType(node.value);
const typeType = node.variableType ? this.getTypeFromTypeNode(node.variableType, this.messageCollector) : null;
if (node.variableType) {
if (isValidType(valueType) && isValidType(typeType)) {
const ret = this.ensureCanBeAssignedWithImplicitConversion(
valueType,
typeType,
node.value,
this.messageCollector,
nodeScope
);
node.value = ret.node;
this.setType(node.variableName, ret.type);
} else if (isValidType(typeType)) {
this.setType(node.variableName, typeType);
} else if (isValidType(valueType)) {
this.setType(node.variableName, valueType);
} else {
this.setType(node.variableName, UNRESOLVED_TYPE);
}
} else if (valueType) {
this.setType(node.variableName, valueType);
} else {
this.setType(node.variableName, UNRESOLVED_TYPE);
}
} else if (node instanceof Nodes.BlockNode) {
if (node.hasAnnotation(annotations.IsValueNode)) {
if (node.statements.length === 0) {
this.setType(node, InjectableTypes.void);
} else {
const lastStatement = last(node.statements);
const type = this.getType(lastStatement);
if (isValidType(type)) {
this.setType(node, type);
} else {
this.messageCollector.errorIfBranchDoesntHaveAny('Cannot resolve type 6', lastStatement);
}
}
} else {
this.setType(node, InjectableTypes.void);
}
} else if (node instanceof Nodes.MemberNode) {
const lhsType = this.getType(node.lhs);
if (!isValidType(lhsType)) {
this.messageCollector.errorIfBranchDoesntHaveAny('Cannot resolve type 5', node.lhs);
this.setType(node, UNRESOLVED_TYPE);
return;
}
if (node.operator === '.^') {
if (lhsType instanceof TypeType) {
const allowedTypeSchemas = lhsType.schema();
if (node.memberName.name in allowedTypeSchemas) {
this.setType(node, allowedTypeSchemas[node.memberName.name]);
return;
} else {
const keys = Object.keys(allowedTypeSchemas);
if (keys.length) {
this.messageCollector.error(
new LysTypeError(`Invalid schema property. Available options: ${keys.join(', ')}`, node.memberName)
);
} else {
this.messageCollector.error(new LysTypeError(`The type "${lhsType}" has no schema`, node.lhs));
}
}
} else {
this.messageCollector.errorIfBranchDoesntHaveAny(new NotAValidType(node.lhs, lhsType));
}
this.setType(node, UNRESOLVED_TYPE);
} else {
if (lhsType instanceof TypeType) {
const memberName = node.memberName.name;
const memberType = this.resolveTypeMember(
node.memberName,
lhsType.of,
memberName,
this.messageCollector,
nodeScope
);
if (memberType) {
if (node.hasAnnotation(annotations.IsValueNode)) {
/**
* This branch covers Type.'variable
*
* impl Test {
* var CONST = 1
* }
*
* Test.CONST
* ^^^^^^^^^^
*/
// a if (memberType.referencedNode) {
// a node.resolvedReference = new Reference(
// a memberType.referencedNode,
// a nodeScope,
// a 'VALUE',
// a memberType.referencedNode.astNode.moduleName
// a );
// a } else {
// a this.messageCollector.errorIfBranchDoesntHaveAny(new NotAValidType(node.lhs));
// a }
if (!node.resolvedReference) {
this.messageCollector.errorIfBranchDoesntHaveAny('Reference not resolved', node.lhs);
}
}
this.setType(node, memberType);
} else {
this.setType(node, UNRESOLVED_TYPE);
}
} else if (lhsType instanceof TypeAlias) {
// we are inside if (node is MemberNode)
// lhsType is typeOf(node.lhs)
// lhsType is TypeAlias means we are receiving a value as LHS
// i.e: "asd".length
const memberName = node.memberName.name;
const memberType = this.resolveTypeMember(
node.memberName,
lhsType,
memberName,
this.messageCollector,
nodeScope
);
if (memberType) {
const isValueNode = !node.hasAnnotation(annotations.IsAssignationLHS);
if (isValueNode) {
const prop = this.describeProperty(memberType);
if (prop) {
if (prop.getter) {
const fun = this.findFunctionOverload(
memberType,
[lhsType],
node,
null,
false,
this.messageCollector,
false,
nodeScope
);
if (isValidType(fun) && fun instanceof FunctionType) {
this.annotateImplicitCall(node, fun, [node.lhs], this.messageCollector, nodeScope);
this.setType(node, fun.signature.returnType!);
} else {
this.messageCollector.error(
new LysTypeError(
`${lhsType}.${memberName} is not a valid property getter ${fun} ${memberType.inspect(100)}`,
node.memberName
)
);
this.setType(node, UNRESOLVED_TYPE);
}
} else if (prop.method) {
this.stashNodeAnnotation(node, new annotations.MethodCall());
this.setType(node, memberType);
} else {
this.messageCollector.error(
new LysTypeError(`${lhsType}.${memberName} is not a getter or method`, node.memberName)
);
this.setType(node, UNRESOLVED_TYPE);
}
} else {
this.messageCollector.error(
new LysTypeError(`${lhsType}.${memberName} is not a getter or method`, node.memberName)
);
this.setType(node, UNRESOLVED_TYPE);
}
} else {
this.setType(node, memberType);
}
} else {
this.setType(node, UNRESOLVED_TYPE);
}
} else {
this.messageCollector.errorIfBranchDoesntHaveAny(
`Don't know how to find a member in "${lhsType}"`,
node.memberName
);
}
}
} else if (node instanceof Nodes.ImplDirective) {
if (node.baseImpl && node.baseImpl.resolvedReference) {
const trait = this.getType(node.baseImpl.resolvedReference.referencedNode);
if (node.targetImpl.resolvedReference) {
const targetType = this.getType(node.targetImpl.resolvedReference.referencedNode);
if (node.selfTypeName && targetType) {
this.setType(node.selfTypeName, targetType);
}
}
if (trait) {
if (trait instanceof TraitType) {
if (!isValidType(trait)) {
this.messageCollector.errorIfBranchDoesntHaveAny('Trait not ready', node.baseImpl);
} else {
const requiredImplementations = new Set(trait.traitNode.namespaceNames.keys());
const givenImplementations: string[] = [];
// verify every implementation function against the trait's signatures
for (let [name, nameNode] of node.namespaceNames) {
givenImplementations.push(name);
const type = this.getType(nameNode);
const signature = trait.getSignatureOf(name);
if (signature && type && !type.canBeAssignedTo(signature, nodeScope)) {
this.messageCollector.errorIfBranchDoesntHaveAny(new TypeMismatch(type, signature, nameNode));
}
if (requiredImplementations.has(name)) {
requiredImplementations.delete(name);
} else {
// TODO: check extra names and suggest private implementations
}
}
if (requiredImplementations.size) {
this.messageCollector.errorIfBranchDoesntHaveAny(
`Not all functions are implemented, missing: ${Array.from(requiredImplementations).join(', ')}`,
node.baseImpl
);
}
}
} else {
// TODO: test this
this.messageCollector.errorIfBranchDoesntHaveAny(`${trait.inspect(100)} is not a trait`, node.baseImpl);
}
}
}
if (node.targetImpl.resolvedReference) {
// this will fail if the resolved reference is not a type
this.getTypeTypeType(
node.targetImpl,
this.getType(node.targetImpl.resolvedReference.referencedNode),
this.messageCollector
);
}
} else if (node instanceof Nodes.TypeDirectiveNode) {
if (node.valueType) {
let valueType = this.getTypeFromTypeNode(node.valueType, this.messageCollector);
if (isValidType(valueType)) {
const type = createTypeAlias(node.variableName, valueType, this.parsingContext);
type.name.impls.forEach(impl => {
if (impl.baseImpl && impl.baseImpl.resolvedReference) {
const trait = this.getType(impl.baseImpl.resolvedReference.referencedNode);
if (trait instanceof TraitType) {
type.traits.set(impl, trait);
}
}
});
this.setType(node.variableName, TypeType.of(type));
} else {
this.messageCollector.errorIfBranchDoesntHaveAny('Invalid type', node.valueType || node);
}
} else {
this.messageCollector.errorIfBranchDoesntHaveAny('Missing value type', node);
}
} else if (node instanceof Nodes.FunctionTypeNode) {
const signatureType = new FunctionSignatureType();
node.parameters.forEach(($, ix) => {
const parameterType = this.getTypeFromTypeNode($.parameterType, this.messageCollector);
signatureType.parameterTypes[ix] = parameterType!;
});
const retType = node.returnType ? this.getTypeFromTypeNode(node.returnType, this.messageCollector) : null;
if (isValidType(retType)) {
signatureType.returnType = retType;
} else {
this.messageCollector.errorIfBranchDoesntHaveAny('Cannot resolve return type', node.returnType || node);
}
this.setType(node, signatureType);
} else if (node instanceof Nodes.IntersectionTypeNode) {
const of = node.of.map($ => this.getTypeTypeType($, this.getType($), this.messageCollector)) as Type[];
this.setType(node, new IntersectionType(of));
} else if (node instanceof Nodes.UnionTypeNode) {
const of = node.of.map($ => this.getTypeTypeType($, this.getType($), this.messageCollector)) as Type[];
this.setType(node, new UnionType(of));
} else if (node instanceof Nodes.OverloadedFunctionNode) {
const incomingTypes = node.functions.map(fun => {
if (!fun.functionNode.hasAnnotation(annotations.IsOverloaded)) {
this.stashNodeAnnotation(fun.functionNode, new annotations.IsOverloaded());
}
return this.getType(fun.functionNode.functionName);
});
const incomingFunctionTypes: FunctionType[] = [];
for (let incomingType of incomingTypes) {
if (incomingType instanceof FunctionType) {
incomingFunctionTypes.push(incomingType);
} else {
this.messageCollector.error(
`All members of an overloaded function should be functions, but found ${incomingType}`,
node.astNode
);
}
}
const newType = new IntersectionType(incomingFunctionTypes);
this.setType(node.functionName, newType);
} else if (node instanceof Nodes.WasmExpressionNode) {
this.setType(node, InjectableTypes.never);
} else if (node instanceof Nodes.UnknownExpressionNode) {
this.setType(node, InjectableTypes.never);
} else if (node instanceof Nodes.LoopNode) {
this.setType(node, InjectableTypes.void);
} else if (node instanceof Nodes.PatternMatcherNode) {
if (node.hasAnnotation(annotations.IsValueNode)) {
const restType = node.carryType;
if (isValidType(restType) && !NeverType.isNeverType(restType)) {
this.messageCollector.error(`Match is not exhaustive, not covered types: "${restType}"`, node.astNode);
}
const retType = UnionType.of(node.matchingSet.map($ => this.getType($)!)).simplify(nodeScope);
this.setType(node, retType);
} else {
this.setType(node, InjectableTypes.void);
}
// TODO: warn if empty matcher
} else if (node instanceof Nodes.VarDeclarationNode) {
if (node.hasAnnotation(annotations.IsValueNode)) {
this.messageCollector.error('This should be an expression. A declaration was found.', node.astNode);
}
this.setType(node, InjectableTypes.void);
} else if (node instanceof Nodes.ExpressionNode) {
const type = this.getType(node);
if (!isValidType(type)) {
this.messageCollector.errorIfBranchDoesntHaveAny(`Cannot resolve type of node ${node.nodeName}`, node);
}
}
}
protected onEnterNode(node: Nodes.Node) {
if (node instanceof Nodes.PatternMatcherNode) {
// this value must be cleared in every execution
delete node.carryType;
}
}
private processMatcherNode(node: Nodes.MatcherNode, parent: Nodes.PatternMatcherNode) {
if (!node.scope) {
this.messageCollector.errorIfBranchDoesntHaveAny(`Node ${node.nodeName} has no scope`, node);
return;
}
const nodeScope = node.scope;
const carryType = parent.carryType || this.getType(parent.lhs);
if (!isValidType(carryType)) {
return;
}
if (!parent.carryType) {
parent.carryType = carryType;
}
const booleanType = node.booleanReference
? this.getTypeTypeType(node, this.getType(node.booleanReference.referencedNode), this.messageCollector)
: null;
if (!isValidType(booleanType)) {
return;
}
if (NeverType.isNeverType(carryType)) {
this.messageCollector.error(new UnreachableCode(node.rhs));
this.messageCollector.error(carryType.inspect(10), node.rhs.astNode);
this.stashNodeAnnotation(node.rhs, new annotations.IsUnreachable());
this.setType(node, UNRESOLVED_TYPE);
return;
}
if (node instanceof Nodes.MatchDefaultNode) {
this.removeTypeFromMatcherFlow(parent, carryType);
} else if (node instanceof Nodes.MatchLiteralNode) {
const argumentType = this.getType(node.literal);
if (!isValidType(argumentType)) {
return;
}
const eqFunction = this.resolveTypeMember(node.literal, carryType, '==', this.messageCollector, nodeScope);
if (eqFunction) {
const argTypes = [carryType, argumentType];
const fun = this.findFunctionOverload(
eqFunction,
argTypes,
node.literal,
null,
false,
new MessageCollector(),
true,
nodeScope
);
if (isValidType(fun) && fun instanceof FunctionType) {
node.resolvedFunctionType = fun;
if (!this.canBeAssigned(fun.signature.returnType!, booleanType, nodeScope)) {
this.messageCollector.error(new TypeMismatch(fun.signature.returnType!, booleanType, node));
}
} else {
this.messageCollector.error(new TypeMismatch(carryType, argumentType, node.literal));
this.messageCollector.error(new UnreachableCode(node.rhs));
this.stashNodeAnnotation(node.rhs, new annotations.IsUnreachable());
}
}
} else if (node instanceof Nodes.MatchCaseIsNode) {
const argumentType = this.getTypeTypeType(
node.typeReference,
this.getType(node.typeReference),
this.messageCollector
);
if (!isValidType(argumentType)) {
return;
}
if (node.declaredName) {
this.setType(node.declaredName, argumentType);
}
if (!this.canBeAssigned(carryType, RefType.instance, nodeScope)) {
this.messageCollector.error(
`"is" expression can only be used with reference types, used with: "${carryType}"`,
node.astNode
);
} else if (
!this.canBeAssigned(carryType, argumentType, nodeScope) &&
!this.canBeAssigned(argumentType, carryType, nodeScope)
) {
this.messageCollector.error(new TypeMismatch(carryType, argumentType, node.typeReference));
this.messageCollector.error(new UnreachableCode(node.rhs));
this.stashNodeAnnotation(node.rhs, new annotations.IsUnreachable());
} else {
const eqFunction = this.resolveTypeMember(
node.typeReference,
argumentType,
'is',
this.messageCollector,
nodeScope
);
if (eqFunction) {
const fun = this.findFunctionOverload(
eqFunction,
[argumentType],
node,
null,
false,
new MessageCollector(),
false,
nodeScope
);
if (isValidType(fun) && fun instanceof FunctionType) {
node.resolvedFunctionType = fun;
if (!this.canBeAssigned(fun.signature.returnType!, booleanType, nodeScope)) {
this.messageCollector.error(new TypeMismatch(fun.signature.returnType!, booleanType, node));
}
this.removeTypeFromMatcherFlow(parent, argumentType);
} else {
this.messageCollector.error(new TypeMismatch(carryType, argumentType, node.typeReference));
this.messageCollector.error(new UnreachableCode(node.rhs));
this.stashNodeAnnotation(node.rhs, new annotations.IsUnreachable());
}
}
}
}
const result = this.getType(node.rhs);
if (node.hasAnnotation(annotations.IsValueNode)) {
this.setType(node, result);
} else {
this.setType(node, InjectableTypes.void);
}
}
private annotateImplicitCall(
nodeToAnnotate: Nodes.Node,
fun: FunctionType,
argumentNodes: Nodes.ExpressionNode[],
messageCollector: MessageCollector,
scope: Scope
) {
const oldAnnotation = this.getStashedNodeAnnotation(nodeToAnnotate, annotations.ImplicitCall);
const newAnnotation = new annotations.ImplicitCall(
this.createImplicitCall(nodeToAnnotate, fun, argumentNodes, messageCollector, scope)
);
if (oldAnnotation) {
if (!fun.equals(oldAnnotation.implicitCall.resolvedFunctionType!)) {
messageCollector.error(
new LysTypeError(`This node already has an ${oldAnnotation} trying to add ${newAnnotation}`, nodeToAnnotate)
);
}
} else {
this.stashNodeAnnotation(nodeToAnnotate, newAnnotation);
}
}
private removeTypeFromMatcherFlow(node: Nodes.PatternMatcherNode, typeToRemove: Type) {
let carryType = node.carryType;
if (!isValidType(carryType)) {
return;
}
if (!isValidType(typeToRemove)) {
return;
}
if (carryType instanceof UnionType) {
carryType = carryType.expand(node.scope!);
} else {
carryType = UnionType.of(carryType).expand(node.scope!);
}
let matchingValueType = carryType instanceof UnionType ? carryType : UnionType.of(carryType);
const newType = matchingValueType.subtract(typeToRemove, node.scope!);
matchingValueType = UnionType.of(newType);
node.carryType = matchingValueType.simplify(node.scope!);
}
private getTypeTypeType(node: Nodes.Node, type: Type | null, messageCollector: MessageCollector): Type | null {
if (type instanceof TypeType) {
return type.of;
} else {
if (type) {
messageCollector.errorIfBranchDoesntHaveAny(new NotAValidType(node, type));
}
return null;
}
}
private getTypeFromTypeNode(node: Nodes.Node, messageCollector: MessageCollector): Type | null {
if (node instanceof Nodes.ReferenceNode) {
return this.getTypeTypeType(node, TypeHelpers.getNodeType(node), messageCollector);
} else if (
node instanceof Nodes.FunctionTypeNode ||
node instanceof Nodes.IntersectionTypeNode ||
node instanceof Nodes.UnionTypeNode ||
node instanceof Nodes.InjectedTypeNode ||
node instanceof Nodes.StructTypeNode ||
node instanceof Nodes.StackTypeNode
) {
return TypeHelpers.getNodeType(node);
} else {
messageCollector.errorIfBranchDoesntHaveAny(new NotAValidType(node, null));
return null;
}
}
private resolveTypeMember(
errorNode: Nodes.Node | null,
type: Type,
memberName: string,
messageCollector: MessageCollector,
scope: Scope
): Type | false {
if (type && type instanceof TypeAlias) {
const types = type.getTypeMember(memberName, $ => this.getType($));
if (types.length) {
const ret: Type[] = [];
for (let result of types) {
const [referencedNode, memberType] = result;
const parent = referencedNode.parent;
if (!isValidType(memberType)) {
return false;
}
if (parent && parent instanceof Nodes.DirectiveNode) {
if (!parent.isPublic) {
const declScope = referencedNode.scope;
if (!declScope) {
if (errorNode) {
messageCollector.error(new LysTypeError(`Name's parent has no scope`, type.name));
}
return false;
}
if (!scope) {
if (errorNode) {
messageCollector.error(new LysTypeError(`Scope is null`, errorNode));
console.trace();
}
return false;
}
if (!scope.isDescendantOf(declScope)) {
if (errorNode) {
messageCollector.error(
new LysTypeError(`Name "${memberName}" is private in ${type.name.name}`, errorNode)
);
}
continue;
}
}
}
ret.push(memberType);
}
if (ret.length > 1) {
return new IntersectionType(ret).simplify();
}
if (ret.length === 1) {
return ret[0];
}
if (errorNode) {
messageCollector.errorIfBranchDoesntHaveAny(new LysTypeError(`Type is not ready`, errorNode));
}
return false;
} else {
if (errorNode) {
messageCollector.error(
new LysTypeError(`Property "${memberName}" doesn't exist on type "${type}".`, errorNode)
);
}
// Since the members are calculated in the scope phase we return
// `never` type so the type check execution can continue
return InjectableTypes.never;
}
} else {
if (errorNode) {
if (!NeverType.isNeverType(type)) {
messageCollector.error(
new LysTypeError(`Type ${type.inspect(10)} has no members. Members are stored in type aliases.`, errorNode)
);
}
}
}
return false;
}
private findFunctionOverload(
incommingType: Type,
argTypes: Type[],
errorNode: Nodes.Node | null,
returnType: Type | null,
strict: boolean,
messageCollector: MessageCollector,
automaticCoercion: boolean,
scope: Scope
): Type | null {
if (incommingType instanceof TypeType) {
return this.findFunctionOverload(
incommingType.of,
argTypes,
errorNode,
returnType,
strict,
messageCollector,
automaticCoercion,
scope
);
}
if (incommingType instanceof IntersectionType) {
const matchList: { fun: FunctionType; score: number; casts: (FunctionType | null)[] }[] = [];
for (let fun of incommingType.of) {
if (fun instanceof FunctionType) {
if (strict) {
if (this.acceptsTypes(fun.signature, argTypes, strict, automaticCoercion, scope)) {
if (!returnType || fun.signature.returnType!.equals(returnType)) {
return fun;
}
}
} else {
const result = this.acceptsTypes(fun.signature, argTypes, strict, automaticCoercion, scope);
if (result) {
if (!returnType || this.canBeAssigned(fun.signature.returnType!, returnType, scope)) {
matchList.push({ fun, score: result.score, casts: result.casts });
}
}
}
} else {
if (errorNode) {
messageCollector.error(new NotAFunction(fun, errorNode));
}
return null;
}
}
if (matchList.length === 1) {
return matchList[0].fun;
} else if (matchList.length > 1) {
matchList.sort((a, b) => {
if (a.score < b.score) {
return 1;
} else if (a.score > b.score) {
return -1;
} else {
return 0;
}
});
if (matchList[0].score > matchList[1].score) {
return matchList[0].fun;
}
let selectedOverload = 0;
if (errorNode) {
messageCollector.warning(
`Implicit overload with ambiguity.\nPicking overload ${matchList[
selectedOverload
].fun.toString()} for types (${argTypes
.map($ => $.toString())
.join(', ')})\nComplete list of overloads:\n${matchList
.map($ => ' ' + $.fun.toString() + ' score: ' + $.score)
.join('\n')}`,
errorNode
);
}
return matchList[selectedOverload].fun;
}
if (errorNode) {
if (incommingType.of.length > 1) {
messageCollector.error(new InvalidOverload(incommingType, argTypes, errorNode));
} else {
const fun = incommingType.of[0] as FunctionType;
messageCollector.error(new InvalidCall(fun.signature.parameterTypes, argTypes, errorNode));
}
return null;
}
return new UnionType((incommingType.of as FunctionType[]).map(($: FunctionType) => $.signature.returnType!));
} else if (incommingType instanceof FunctionType) {
const queryResult = this.acceptsTypes(incommingType.signature, argTypes, strict, automaticCoercion, scope);
if (!queryResult) {
if (errorNode) {
messageCollector.error(new InvalidCall(incommingType.signature.parameterTypes, argTypes, errorNode));
} else {
return null;
}
}
return incommingType;
} else if (incommingType instanceof FunctionSignatureType) {
const queryResult = this.acceptsTypes(incommingType, argTypes, strict, automaticCoercion, scope);
if (!queryResult) {
if (errorNode) {
messageCollector.error(new InvalidCall(incommingType.parameterTypes, argTypes, errorNode));
} else {
return null;
}
}
return incommingType;
} else {
if (errorNode && !NeverType.isNeverType(incommingType)) {
messageCollector.error(new NotAFunction(incommingType, errorNode));
}
return null;
}
}
private findImplicitTypeCasting(
errorNode: Nodes.Node | null,
from: Type,
to: Type,
messageCollector: MessageCollector,
scope: Scope
): FunctionType | null {
if (this.canBeAssigned(from, to, scope)) {
return null;
}
if (from instanceof TypeAlias) {
try {
const fnType = this.resolveTypeMember(errorNode, from, 'as', messageCollector, scope);
if (fnType) {
const fun = this.findFunctionOverload(fnType, [from], null, to, true, messageCollector, true, scope);
if (fun instanceof FunctionType) {
if (!fun.name.hasAnnotation(annotations.Explicit)) {
if (this.canBeAssigned(fun.signature.returnType!, to, scope)) {
return fun;
}
}
}
}
} catch (e) {
return null;
}
}
return null;
}
private sizeInBytes(type: Type, defaultSize: number) {
if (type instanceof StackType) {
return type.byteSize;
}
if (type instanceof RefType) {
return type.byteSize;
}
switch (type.binaryenType) {
case NativeTypes.i32:
case NativeTypes.f32:
return 4;
case NativeTypes.i64:
case NativeTypes.f64:
return 8;
}
return defaultSize;
}
private acceptsTypes(
type: FunctionSignatureType,
types: Type[],
strict: boolean,
automaticCoercion: boolean,
scope: Scope
): { score: number; casts: (FunctionType | null)[] } | null {
if (type.parameterTypes.length !== types.length) {
return null;
}
let score = 1;
let casts: (FunctionType | null)[] = [];
if (type.parameterTypes.length === 0) {
return { score: Infinity, casts: [] };
}
for (let index = 0; index < types.length; index++) {
const argumentType = types[index];
const parameterType = type.parameterTypes[index];
const equals = argumentType.equals(parameterType);
if (equals) {
score += 1;
casts.push(null);
} else if (!strict) {
const cleanAssignation = this.canBeAssigned(argumentType, parameterType, scope);
if (cleanAssignation) {
score += this.getTypeSimilarity(argumentType, parameterType);
} else if (automaticCoercion) {
try {
const implicitCast = this.findImplicitTypeCasting(
null,
argumentType,
parameterType,
new MessageCollector(),
scope
);
if (implicitCast) {
casts.push(implicitCast);
const dataLossInBytes = this.sizeInBytes(parameterType, 0) / this.sizeInBytes(argumentType, 1);
if (isNaN(dataLossInBytes)) return null;
score += 0.5 * Math.min(((types.length - index) / types.length) * dataLossInBytes, 1);
} else {
return null;
}
} catch {
return null;
}
} else {
return null;
}
} else {
return null;
}
}
return {
score,
casts
};
}
private downToRefTypes(type: Type): (RefType | StructType)[] {
let argType = type;
while (true) {
if (argType instanceof StructType) {
return [argType];
} else if (argType instanceof RefType) {
return [argType];
} else if (argType instanceof TypeAlias) {
argType = argType.of;
} else if (argType instanceof UnionType) {
return flatten(argType.of.map($ => this.downToRefTypes($)));
} else {
return [];
}
}
}
private getTypeSimilarity(lhs: Type, rhs: Type) {
if (rhs.equals(lhs) && lhs.equals(rhs)) {
return 1;
}
const lhsTypes = this.downToRefTypes(lhs);
if (lhsTypes.length === 0) return 0;
const rhsTypes = this.downToRefTypes(rhs);
if (rhsTypes.length === 0) return 0;
let results: number[] = [];
lhsTypes.forEach(lhs => rhsTypes.forEach(rhs => results.push(lhs.typeSimilarity(rhs))));
return Math.max.apply(Math, results);
}
private canBeAssigned(sourceType: Type, targetType: Type, scope: Scope): boolean {
if (!sourceType || !sourceType.canBeAssignedTo) {
console.trace();
console.log(sourceType, sourceType.toString());
console.log(sourceType.inspect(10));
}
return sourceType.canBeAssignedTo(targetType, scope);
}
private ensureCanBeAssignedWithImplicitConversion(
sourceType: Type,
targetType: Type,
node: Nodes.ExpressionNode,
messageCollector: MessageCollector,
scope: Scope
) {
if (
sourceType instanceof IntersectionType &&
targetType instanceof FunctionSignatureType &&
this.canBeAssigned(sourceType, targetType, scope)
) {
for (let fun of sourceType.of) {
if (this.canBeAssigned(fun, targetType, scope)) {
if (fun instanceof FunctionType) {
const currentAnnotation = this.getStashedNodeAnnotation(node, annotations.FunctionInTable);
if (currentAnnotation) {
currentAnnotation.nameIdentifier = fun.name;
} else {
this.stashNodeAnnotation(node, new annotations.FunctionInTable(fun.name));
}
}
return { node, type: targetType };
}
}
} else if (this.canBeAssigned(sourceType, targetType, scope)) {
return { node, type: targetType };
} else {
const implicitCast = this.findImplicitTypeCasting(node, sourceType, targetType, new MessageCollector(), scope);
if (implicitCast) {
return { node: this.createImplicitCall(node, implicitCast, [node], messageCollector, scope), type: targetType };
}
}
messageCollector.error(new TypeMismatch(sourceType, targetType, node));
return { node, type: targetType };
}
private createImplicitCall(
node: Nodes.Node,
fun: FunctionType,
args: Nodes.ExpressionNode[],
messageCollector: MessageCollector,
scope: Scope
) {
const functionCallNode = new Nodes.InjectedFunctionCallNode(node.astNode);
functionCallNode.scope = node.scope;
functionCallNode.argumentsNode = args;
functionCallNode.annotate(new annotations.Injected());
functionCallNode.resolvedFunctionType = fun;
this.ensureArgumentCoercion(
functionCallNode,
fun.signature,
args.map($ => this.getType($)!),
messageCollector,
scope
);
TypeHelpers.setNodeType(functionCallNode, fun.signature.returnType!);
return functionCallNode;
}
private ensureArgumentCoercion(
node: Nodes.AbstractFunctionCallNode,
fun: FunctionSignatureType,
argsTypes: Type[],
messageCollector: MessageCollector,
scope: Scope
) {
node.argumentsNode.forEach((argNode, i) => {
const argType = argsTypes[i];
if (argType) {
const ret = this.ensureCanBeAssignedWithImplicitConversion(
argType,
fun.parameterTypes[i],
argNode,
messageCollector,
scope
);
node.argumentsNode[i] = ret.node;
} else {
messageCollector.error(new LysTypeError('type is undefined', node.argumentsNode[i]));
}
});
}
private describeProperty(type: Type): LysPropertyDescription | void {
if (type instanceof FunctionType) {
return {
type,
method: type.name.hasAnnotation(annotations.Method),
getter: type.name.hasAnnotation(annotations.Getter),
setter: type.name.hasAnnotation(annotations.Setter)
};
}
if (type instanceof IntersectionType) {
const ret: LysPropertyDescription = {
type,
getter: false,
setter: false,
method: false
};
type.of
.map($ => this.describeProperty($))
.forEach($ => {
if ($) {
ret.getter = ret.getter || $.getter;
ret.setter = ret.setter || $.setter;
ret.method = ret.method || $.method;
}
});
if (ret.getter || ret.setter || ret.method) {
return ret;
}
}
return void 0;
}
} | the_stack |
import {
CdkCell,
CdkCellDef,
CdkColumnDef,
CdkFooterCell,
CdkFooterCellDef,
CdkHeaderCell,
CdkHeaderCellDef,
} from '@angular/cdk/table';
import {
Directive,
ElementRef,
EventEmitter,
isDevMode,
NgZone,
OnDestroy,
OnInit,
Output,
Renderer2,
} from '@angular/core';
import { TsDocumentService } from '@terminus/ngx-tools/browser';
import { untilComponentDestroyed } from '@terminus/ngx-tools/utilities';
import { TsUILibraryError } from '@terminus/ui/utilities';
import {
fromEvent,
Subject,
} from 'rxjs';
import {
take,
takeUntil,
} from 'rxjs/operators';
import {
TsColumnDefDirective,
tsTableColumnAlignmentTypesArray,
} from './column';
/**
* The minimum width for columns
*/
export const TS_TABLE_MIN_COLUMN_WIDTH = 70;
// Unique ID for each instance
let cellNextUniqueId = 0;
let headerNextUniqueId = 0;
/**
* Set the column alignment styles
*
* @param column - The column definition
* @param renderer - The Renderer2
* @param elementRef - The element ref to add the class to
*/
export function setColumnAlignment(column: TsColumnDefDirective, renderer: Renderer2, elementRef: ElementRef): void {
if (column.alignment) {
// Verify the alignment value is allowed
if (tsTableColumnAlignmentTypesArray.indexOf(column.alignment) < 0 && isDevMode()) {
throw new TsUILibraryError(`TsCellDirective: "${column.alignment}" is not an allowed alignment.`
+ `See "TsTableColumnAlignment" type for available options.`);
}
renderer.addClass(elementRef.nativeElement, `ts-cell--align-${column.alignment}`);
}
}
/**
* Cell definition for the {@link TsTableComponent}.
*
* Captures the template of a column's data row cell as well as cell-specific properties.
*/
@Directive({
selector: '[tsCellDef]',
providers: [{
provide: CdkCellDef,
useExisting: TsCellDefDirective,
}],
})
export class TsCellDefDirective extends CdkCellDef {}
/**
* Header cell definition for the {@link TsTableComponent}.
*
* Captures the template of a column's header cell and as well as cell-specific properties.
*/
@Directive({
selector: '[tsHeaderCellDef]',
providers: [{
provide: CdkHeaderCellDef,
useExisting: TsHeaderCellDefDirective,
}],
})
export class TsHeaderCellDefDirective extends CdkHeaderCellDef {}
/**
* Define the event object for header cell resize events
*/
export class TsHeaderCellResizeEvent {
constructor(
// The header cell instance that originated the event
public instance: TsHeaderCellDirective,
// The new width
public width: number,
) {}
}
/**
* Header cell template container that adds the right classes and role.
*/
@Directive({
// eslint-disable-next-line @angular-eslint/directive-selector
selector: 'ts-header-cell, th[ts-header-cell]',
host: {
'class': 'ts-header-cell',
'role': 'columnheader',
'[id]': 'uid',
},
exportAs: 'tsHeaderCell',
})
export class TsHeaderCellDirective extends CdkHeaderCell implements OnInit, OnDestroy {
/**
* Store a reference to the column
*/
public column!: TsColumnDefDirective;
/**
* Stream used inside takeUntil pipes
*/
private killStream$ = new Subject<void>();
/**
* Define the class for the resizable element
*/
private readonly resizerClass = 'ts-header-cell__resizer';
/**
* Store the starting offset when a resize event begins
*/
public startOffsetX = 0;
/**
* Store the starting width of a cell before resizing
*/
public startWidth = 0;
/**
* Define the default component ID
*/
public readonly uid = `ts-table-header-cell-${headerNextUniqueId++}`;
/**
* Store the current cell width
*/
public width = 'auto';
/**
* Return the current set width
*/
public get cellWidth(): number {
return parseInt(this.width, 0);
}
/**
* Return a reference to the resize element
*/
private get resizeElement(): HTMLElement | null {
return this.elementRef.nativeElement.querySelector(`.${this.resizerClass}`);
}
/**
* Event emitted when the cell is resized
*/
@Output()
public readonly resized = new EventEmitter<TsHeaderCellResizeEvent>();
constructor(
public columnDef: CdkColumnDef,
public elementRef: ElementRef,
private renderer: Renderer2,
private documentService: TsDocumentService,
private ngZone: NgZone,
) {
super(columnDef, elementRef);
}
/**
* Initial setup
*/
public ngOnInit(): void {
this.column = this.columnDef as TsColumnDefDirective;
this.elementRef.nativeElement.classList.add(`ts-column-${this.column.cssClassFriendlyName}`);
// eslint-disable-next-line no-underscore-dangle
if (this.column._stickyEnd) {
this.elementRef.nativeElement.classList.add(`ts-table__column--sticky-end`);
}
if (this.column.sticky) {
this.elementRef.nativeElement.classList.add(`ts-table__column--sticky`);
}
setColumnAlignment(this.column, this.renderer, this.elementRef);
}
/**
* Remove all event listeners when destroyed
*/
public ngOnDestroy(): void {
this.killStream$.complete();
}
/**
* Inject the resize 'grabber' element.
*
* Called by {@link TsTableComponent}
*/
public injectResizeElement(): void {
// If the element has been injected before, remove it
if (this.resizeElement) {
this.renderer.removeChild(this.elementRef.nativeElement, this.resizeElement);
}
const resizeElement = this.renderer.createElement('span');
resizeElement.classList.add(this.resizerClass);
resizeElement.classList.add(`${this.resizerClass}--${this.columnDef.cssClassFriendlyName}`);
resizeElement.title = 'Drag to resize column.';
this.renderer.appendChild(this.elementRef.nativeElement, resizeElement);
this.ngZone.runOutsideAngular(() => {
// TODO: Refactor deprecation
// eslint-disable-next-line deprecation/deprecation
fromEvent<MouseEvent>(resizeElement, 'mousedown')
.pipe(untilComponentDestroyed<MouseEvent>(this))
.subscribe(e => this.onResizeColumn(e));
// TODO: Refactor deprecation
// eslint-disable-next-line deprecation/deprecation
fromEvent<MouseEvent>(resizeElement, 'click')
.pipe(untilComponentDestroyed<MouseEvent>(this))
.subscribe(e => e.stopPropagation());
// TODO: Refactor deprecation
// eslint-disable-next-line deprecation/deprecation
fromEvent<MouseEvent>(resizeElement, 'mouseenter')
.pipe(untilComponentDestroyed<MouseEvent>(this))
.subscribe(() => this.syncHoverClass(true));
// TODO: Refactor deprecation
// eslint-disable-next-line deprecation/deprecation
fromEvent<MouseEvent>(resizeElement, 'mouseleave')
.pipe(untilComponentDestroyed<MouseEvent>(this))
.subscribe(() => this.syncHoverClass(false));
});
}
/**
* Return the new width if above the minimum width
*
* @param start - The starting width
* @param difference - The amount moved
* @returns The final column width
*/
private static determineWidth(start: number, difference: number): number {
const total = start + difference;
return (total >= TS_TABLE_MIN_COLUMN_WIDTH) ? total : TS_TABLE_MIN_COLUMN_WIDTH;
}
/**
* Save initial width and offset, bind to more events
*
* @param event - The mouse event
*/
private onResizeColumn(event: MouseEvent): void {
this.startOffsetX = event.clientX;
this.startWidth = this.cellWidth;
// TODO: Refactor deprecation
// eslint-disable-next-line deprecation/deprecation
fromEvent<MouseEvent>(this.documentService.document, 'mousemove')
.pipe(
untilComponentDestroyed(this),
takeUntil(this.killStream$),
).subscribe(e => {
const diff = e.clientX - this.startOffsetX;
const newWidth = TsHeaderCellDirective.determineWidth(this.startWidth, diff);
// istanbul ignore else
if (newWidth) {
this.setColumnWidth(newWidth);
}
});
// TODO: Refactor deprecation
// eslint-disable-next-line deprecation/deprecation
fromEvent<MouseEvent>(this.documentService.document, 'mouseup')
.pipe(
untilComponentDestroyed(this),
take(1),
).subscribe(() => {
this.startOffsetX = 0;
this.startWidth = 0;
this.killStream$.next(void 0);
this.resized.emit(new TsHeaderCellResizeEvent(this, this.elementRef.nativeElement.offsetWidth));
});
}
/**
* Set the column width style and save the width
*
* @param width - The width to set
*/
public setColumnWidth(width: number): void {
this.renderer.setStyle(this.elementRef.nativeElement, 'width', `${width}px`);
this.width = `${width}px`;
}
/**
* Sync the hovered class
*
* @param isHovered - Whether the resize element is currently hovered
*/
private syncHoverClass(isHovered: boolean): void {
isHovered
? this.renderer.addClass(this.elementRef.nativeElement, 'ts-cell--resizing')
: this.renderer.removeClass(this.elementRef.nativeElement, 'ts-cell--resizing');
}
}
/**
* Cell template container that adds the right classes and role.
*/
@Directive({
// eslint-disable-next-line @angular-eslint/directive-selector
selector: 'ts-cell, td[ts-cell]',
host: {
class: 'ts-cell',
role: 'gridcell',
},
})
export class TsCellDirective extends CdkCell implements OnInit {
/**
* Store a reference to the column
*/
public column!: TsColumnDefDirective;
/**
* Define the default component ID
*/
public readonly uid = `ts-table-cell-${cellNextUniqueId++}`;
constructor(
public elementRef: ElementRef,
private columnDef: CdkColumnDef,
private renderer: Renderer2,
) {
super(columnDef, elementRef);
}
/**
* Initial setup
*/
public ngOnInit(): void {
// HACK: Changing the type in the constructor from `CdkColumnDef` to `TsColumnDefDirective` doesn't seem to play well with the CDK.
// Coercing the type here is a hack, but allows us to reference properties that do not exist on the underlying `CdkColumnDef`.
this.column = this.columnDef as TsColumnDefDirective;
// Set a custom class for each column
this.elementRef.nativeElement.classList.add(`ts-column-${this.column.cssClassFriendlyName}`);
setColumnAlignment(this.column, this.renderer, this.elementRef);
// eslint-disable-next-line no-underscore-dangle
if (this.column._stickyEnd) {
this.elementRef.nativeElement.classList.add(`ts-table__column--sticky-end`);
}
if (this.column.sticky) {
this.elementRef.nativeElement.classList.add(`ts-table__column--sticky`);
}
}
}
/**
* Footer cell definition for the mat-table.
*
* Captures the template of a column's footer cell and as well as cell-specific properties.
*/
@Directive({
selector: '[tsFooterCellDef]',
providers: [{
provide: CdkFooterCellDef,
useExisting: TsFooterCellDefDirective,
}],
})
export class TsFooterCellDefDirective extends CdkFooterCellDef {}
/**
* Footer cell template container that adds the right classes and role.
*/
@Directive({
// eslint-disable-next-line @angular-eslint/directive-selector
selector: 'ts-footer-cell, td[ts-footer-cell]',
host: {
class: 'ts-footer-cell',
role: 'gridcell',
},
})
export class TsFooterCellDirective extends CdkFooterCell implements OnInit {
/**
* Store a reference to the column
*/
public column!: TsColumnDefDirective;
constructor(
public columnDef: CdkColumnDef,
public elementRef: ElementRef,
private renderer: Renderer2,
) {
super(columnDef, elementRef);
}
/**
* Initial setup
*/
public ngOnInit(): void {
// HACK: Changing the type in the constructor from `CdkColumnDef` to `TsColumnDefDirective` doesn't seem to play well with the CDK.
// Coercing the type here is a hack, but allows us to reference properties that do not exist on the underlying `CdkColumnDef`.
this.column = this.columnDef as TsColumnDefDirective;
// Set a custom class for each column
this.elementRef.nativeElement.classList.add(`ts-column-${this.column.cssClassFriendlyName}`);
setColumnAlignment(this.column, this.renderer, this.elementRef);
// eslint-disable-next-line no-underscore-dangle
if (this.column._stickyEnd) {
this.elementRef.nativeElement.classList.add(`ts-table__column--sticky-end`);
}
if (this.column.sticky) {
this.elementRef.nativeElement.classList.add(`ts-table__column--sticky`);
}
}
} | the_stack |
import type { Faker } from '../..';
import type { DateEntryDefinition } from '../../definitions';
import { FakerError } from '../../errors/faker-error';
/**
* Converts date passed as a string, number or Date to a Date object.
* If nothing or a non parseable value is passed, takes current date.
*
* @param date Date
*/
function toDate(date?: string | Date | number): Date {
date = new Date(date);
if (isNaN(date.valueOf())) {
date = new Date();
}
return date;
}
/**
* Module to generate dates.
*/
export class _Date {
constructor(private readonly faker: Faker) {
// Bind `this` so namespaced is working correctly
for (const name of Object.getOwnPropertyNames(_Date.prototype)) {
if (name === 'constructor' || typeof this[name] !== 'function') {
continue;
}
this[name] = this[name].bind(this);
}
}
/**
* Generates a random date in the past.
*
* @param years The range of years the date may be in the past. Defaults to `1`.
* @param refDate The date to use as reference point for the newly generated date. Defaults to now.
*
* @see faker.date.recent()
*
* @example
* faker.date.past() // '2021-12-03T05:40:44.408Z'
* faker.date.past(10) // '2017-10-25T21:34:19.488Z'
* faker.date.past(10, '2020-01-01T00:00:00.000Z') // '2017-08-18T02:59:12.350Z'
*/
past(years?: number, refDate?: string | Date | number): Date {
const date = toDate(refDate);
const range = {
min: 1000,
max: (years || 1) * 365 * 24 * 3600 * 1000,
};
let past = date.getTime();
past -= this.faker.datatype.number(range); // some time from now to N years ago, in milliseconds
date.setTime(past);
return date;
}
/**
* Generates a random date in the future.
*
* @param years The range of years the date may be in the future. Defaults to `1`.
* @param refDate The date to use as reference point for the newly generated date. Defaults to now.
*
* @see faker.date.soon()
*
* @example
* faker.date.future() // '2022-11-19T05:52:49.100Z'
* faker.date.future(10) // '2030-11-23T09:38:28.710Z'
* faker.date.future(10, '2020-01-01T00:00:00.000Z') // '2020-12-13T22:45:10.252Z'
*/
future(years?: number, refDate?: string | Date | number): Date {
const date = toDate(refDate);
const range = {
min: 1000,
max: (years || 1) * 365 * 24 * 3600 * 1000,
};
let future = date.getTime();
future += this.faker.datatype.number(range); // some time from now to N years later, in milliseconds
date.setTime(future);
return date;
}
/**
* Generates a random date between the given boundaries.
*
* @param from The early date boundary.
* @param to The late date boundary.
*
* @example
* faker.date.between('2020-01-01T00:00:00.000Z', '2030-01-01T00:00:00.000Z') // '2026-05-16T02:22:53.002Z'
*/
between(from: string | Date | number, to: string | Date | number): Date {
const fromMs = toDate(from).getTime();
const toMs = toDate(to).getTime();
const dateOffset = this.faker.datatype.number(toMs - fromMs);
return new Date(fromMs + dateOffset);
}
/**
* Generates n random dates between the given boundaries.
*
* @param from The early date boundary.
* @param to The late date boundary.
* @param num The number of dates to generate. Defaults to `3`.
*
* @example
* faker.date.betweens('2020-01-01T00:00:00.000Z', '2030-01-01T00:00:00.000Z')
* // [
* // 2022-07-02T06:00:00.000Z,
* // 2024-12-31T12:00:00.000Z,
* // 2027-07-02T18:00:00.000Z
* // ]
* faker.date.betweens('2020-01-01T00:00:00.000Z', '2030-01-01T00:00:00.000Z', 2)
* // [ 2023-05-02T16:00:00.000Z, 2026-09-01T08:00:00.000Z ]
*/
betweens(
from: string | Date | number,
to: string | Date | number,
num: number = 3
): Date[] {
const dates: Date[] = [];
while (dates.length < num) {
dates.push(this.between(from, to));
}
return dates.sort((a, b) => a.getTime() - b.getTime());
}
/**
* Generates a random date in the recent past.
*
* @param days The range of days the date may be in the past. Defaults to `1`.
* @param refDate The date to use as reference point for the newly generated date. Defaults to now.
*
* @see faker.date.past()
*
* @example
* faker.date.recent() // '2022-02-04T02:09:35.077Z'
* faker.date.recent(10) // '2022-01-29T06:12:12.829Z'
* faker.date.recent(10, '2020-01-01T00:00:00.000Z') // '2019-12-27T18:11:19.117Z'
*/
recent(days?: number, refDate?: string | Date | number): Date {
const date = toDate(refDate);
const range = {
min: 1000,
max: (days || 1) * 24 * 3600 * 1000,
};
let future = date.getTime();
future -= this.faker.datatype.number(range); // some time from now to N days ago, in milliseconds
date.setTime(future);
return date;
}
/**
* Generates a random date in the near future.
*
* @param days The range of days the date may be in the future. Defaults to `1`.
* @param refDate The date to use as reference point for the newly generated date. Defaults to now.
*
* @see faker.date.future()
*
* @example
* faker.date.soon() // '2022-02-05T09:55:39.216Z'
* faker.date.soon(10) // '2022-02-11T05:14:39.138Z'
* faker.date.soon(10, '2020-01-01T00:00:00.000Z') // '2020-01-01T02:40:44.990Z'
*/
soon(days?: number, refDate?: string | Date | number): Date {
const date = toDate(refDate);
const range = {
min: 1000,
max: (days || 1) * 24 * 3600 * 1000,
};
let future = date.getTime();
future += this.faker.datatype.number(range); // some time from now to N days later, in milliseconds
date.setTime(future);
return date;
}
/**
* Returns a random name of a month.
*
* @param options The optional options to use.
* @param options.abbr Whether to return an abbreviation. Defaults to `false`.
* @param options.context Whether to return the name of a month in a context. Defaults to `false`.
*
* @example
* faker.date.month() // 'October'
* faker.date.month({ abbr: true }) // 'Feb'
* faker.date.month({ context: true }) // 'June'
* faker.date.month({ abbr: true, context: true }) // 'Sep'
*/
month(options?: { abbr?: boolean; context?: boolean }): string {
const abbr = options?.abbr ?? false;
const context = options?.context ?? false;
const source = this.faker.definitions.date.month;
let type: keyof DateEntryDefinition;
if (abbr) {
if (context && source['abbr_context'] != null) {
type = 'abbr_context';
} else {
type = 'abbr';
}
} else if (context && source['wide_context'] != null) {
type = 'wide_context';
} else {
type = 'wide';
}
return this.faker.helpers.arrayElement(source[type]);
}
/**
* Returns a random day of the week.
*
* @param options The optional options to use.
* @param options.abbr Whether to return an abbreviation. Defaults to `false`.
* @param options.context Whether to return the day of the week in a context. Defaults to `false`.
*
* @example
* faker.date.weekday() // 'Monday'
* faker.date.weekday({ abbr: true }) // 'Thu'
* faker.date.weekday({ context: true }) // 'Thursday'
* faker.date.weekday({ abbr: true, context: true }) // 'Fri'
*/
weekday(options?: { abbr?: boolean; context?: boolean }): string {
const abbr = options?.abbr ?? false;
const context = options?.context ?? false;
const source = this.faker.definitions.date.weekday;
let type: keyof DateEntryDefinition;
if (abbr) {
if (context && source['abbr_context'] != null) {
type = 'abbr_context';
} else {
type = 'abbr';
}
} else if (context && source['wide_context'] != null) {
type = 'wide_context';
} else {
type = 'wide';
}
return this.faker.helpers.arrayElement(source[type]);
}
/**
* Returns a random birthdate.
*
* @param options The options to use to generate the birthdate. If no options are set, an age between 18 and 80 (inclusive) is generated.
* @param options.min The minimum age or year to generate a birthdate.
* @param options.max The maximum age or year to generate a birthdate.
* @param options.refDate The date to use as reference point for the newly generated date. Defaults to `now`.
* @param options.mode The mode to generate the birthdate. Supported modes are `'age'` and `'year'` .
*
* There are two modes available `'age'` and `'year'`:
* - `'age'`: The min and max options define the age of the person (e.g. `18` - `42`).
* - `'year'`: The min and max options define the range the birthdate may be in (e.g. `1900` - `2000`).
*
* Defaults to `year`.
*
* @example
* faker.date.birthdate() // 1977-07-10T01:37:30.719Z
* faker.date.birthdate({ min: 18, max: 65, mode: 'age' }) // 2003-11-02T20:03:20.116Z
* faker.date.birthdate({ min: 1900, max: 2000, mode: 'year' }) // 1940-08-20T08:53:07.538Z
*/
birthdate(
options: {
min?: number;
max?: number;
mode?: 'age' | 'year';
refDate?: string | Date | number;
} = {}
): Date {
const mode = options.mode === 'age' ? 'age' : 'year';
const refDate = toDate(options.refDate);
const refYear = refDate.getUTCFullYear();
// If no min or max is specified, generate a random date between (now - 80) years and (now - 18) years respectively
// So that people can still be considered as adults in most cases
// Convert to epoch timestamps
let min: number;
let max: number;
if (mode === 'age') {
min = new Date(refDate).setUTCFullYear(refYear - (options.max ?? 80) - 1);
max = new Date(refDate).setUTCFullYear(refYear - (options.min ?? 18));
} else {
// Avoid generating dates the first and last date of the year
// to avoid running into other years depending on the timezone.
min = new Date(Date.UTC(0, 0, 2)).setUTCFullYear(
options.min ?? refYear - 80
);
max = new Date(Date.UTC(0, 11, 30)).setUTCFullYear(
options.max ?? refYear - 18
);
}
if (max < min) {
throw new FakerError(`Max ${max} should be larger then min ${min}.`);
}
return new Date(this.faker.datatype.number({ min, max }));
}
} | the_stack |
import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, Validators } from '@angular/forms';
// Third party imports
import { distinctUntilChanged, takeUntil } from 'rxjs/operators';
// App imports
import AppServices from '../../../../../../../shared/service/appServices';
import { IAAS_DEFAULT_CIDRS, IpFamilyEnum } from '../../../../../../../shared/constants/app.constants';
import { managementClusterPlugin } from "../../../constants/wizard.constants";
import { NetworkField, NetworkIpv4StepMapping, NetworkIpv6StepMapping } from './network-step.fieldmapping';
import { StepFormDirective } from '../../../step-form/step-form';
import { StepMapping } from '../../../field-mapping/FieldMapping';
import { TanzuEventType } from 'src/app/shared/service/Messenger';
import { ValidationService } from '../../../validation/validation.service';
@Component({
selector: 'app-shared-network-step',
templateUrl: './network-step.component.html',
styleUrls: ['./network-step.component.scss']
})
export class SharedNetworkStepComponent extends StepFormDirective implements OnInit {
static description = 'Specify how TKG networking is provided and global network settings';
form: FormGroup;
cniType: string;
additionalNoProxyInfo: string;
fullNoProxy: string;
infraServiceAddress: string = '';
loadingNetworks: boolean = false; // only used by vSphere
hideNoProxyWarning: boolean = true; // only used by vSphere
constructor(protected validationService: ValidationService) {
super();
}
protected supplyEnablesNetworkName(): boolean {
return false;
}
protected supplyEnablesNoProxyWarning(): boolean {
return false;
}
protected supplyNetworkNameInstruction(): string {
return '';
}
protected supplyNetworks(): { displayName?: string }[] {
return [];
}
protected supplyStepMapping(): StepMapping {
return this.ipFamily === IpFamilyEnum.IPv4 ? NetworkIpv4StepMapping : NetworkIpv6StepMapping;
}
// This method may be overridden by subclasses that describe this step using different fields
protected supplyFieldsAffectingStepDescription(): string[] {
return [NetworkField.CLUSTER_SERVICE_CIDR, NetworkField.CLUSTER_POD_CIDR];
}
private customizeForm() {
const cidrs = [NetworkField.CLUSTER_SERVICE_CIDR, NetworkField.CLUSTER_POD_CIDR];
cidrs.forEach(cidr => {
this.registerOnIpFamilyChange(cidr, [
this.validationService.isValidIpNetworkSegment()], [
this.validationService.isValidIpv6NetworkSegment(),
this.setCidrs
]);
});
this.registerStepDescriptionTriggers({fields: this.supplyFieldsAffectingStepDescription()});
this.setValidators();
}
ngOnInit() {
super.ngOnInit();
AppServices.userDataFormService.buildForm(this.formGroup, this.wizardName, this.formName, this.supplyStepMapping());
this.htmlFieldLabels = AppServices.fieldMapUtilities.getFieldLabelMap(this.supplyStepMapping());
this.storeDefaultLabels(this.supplyStepMapping());
this.registerDefaultFileImportedHandler(this.eventFileImported, this.supplyStepMapping());
this.registerDefaultFileImportErrorHandler(this.eventFileImportError);
this.customizeForm();
this.listenToEvents();
this.subscribeToServices();
}
setValidators() {
const configuredCni = AppServices.appDataService.getPluginFeature(managementClusterPlugin, 'cni');
if (configuredCni && ['antrea', 'calico', 'none'].includes(configuredCni)) {
this.cniType = configuredCni;
} else {
this.cniType = 'antrea';
}
if (this.cniType === 'none') {
[NetworkField.CLUSTER_SERVICE_CIDR, NetworkField.CLUSTER_POD_CIDR].forEach( field => this.disarmField(field, false));
} else {
if (this.cniType === 'calico') {
this.disarmField(NetworkField.CLUSTER_SERVICE_CIDR, false);
}
this.setCidrs();
if (this.enableNetworkName) {
this.setNetworkNameValidator();
}
}
}
private setNetworkNameValidator() {
const control = this.formGroup.controls['networkName'];
if (control) {
control.setValidators([Validators.required]);
}
}
setCidrs = () => {
if (this.cniType === 'antrea') {
this.resurrectField(NetworkField.CLUSTER_SERVICE_CIDR, [
Validators.required,
this.validationService.noWhitespaceOnEnds(),
this.ipFamily === IpFamilyEnum.IPv4 ?
this.validationService.isValidIpNetworkSegment() : this.validationService.isValidIpv6NetworkSegment(),
this.validationService.isIpUnique([this.formGroup.get(NetworkField.CLUSTER_POD_CIDR)])
], this.ipFamily === IpFamilyEnum.IPv4 ?
IAAS_DEFAULT_CIDRS.CLUSTER_SVC_CIDR : IAAS_DEFAULT_CIDRS.CLUSTER_SVC_IPV6_CIDR, { onlySelf: true });
}
this.resurrectField(NetworkField.CLUSTER_POD_CIDR, [
Validators.required,
this.validationService.noWhitespaceOnEnds(),
this.ipFamily === IpFamilyEnum.IPv4 ?
this.validationService.isValidIpNetworkSegment() : this.validationService.isValidIpv6NetworkSegment(),
this.validationService.isIpUnique([this.formGroup.get(NetworkField.CLUSTER_SERVICE_CIDR)])
], this.ipFamily === IpFamilyEnum.IPv4 ?
IAAS_DEFAULT_CIDRS.CLUSTER_POD_CIDR : IAAS_DEFAULT_CIDRS.CLUSTER_POD_IPV6_CIDR, { onlySelf: true });
}
listenToEvents() {
this.listenToCidrEvents();
this.listenToNoProxyEvents();
}
private listenToCidrEvents() {
const cidrFields = [NetworkField.CLUSTER_SERVICE_CIDR, NetworkField.CLUSTER_POD_CIDR];
cidrFields.forEach((field) => {
this.formGroup.get(field).valueChanges.pipe(
distinctUntilChanged((prev, curr) => JSON.stringify(prev) === JSON.stringify(curr)),
takeUntil(this.unsubscribe)
).subscribe((value) => {
this.generateFullNoProxy();
this.triggerStepDescriptionChange();
});
});
}
private listenToNoProxyEvents() {
this.formGroup.get('noProxy').valueChanges.pipe(
distinctUntilChanged((prev, curr) => JSON.stringify(prev) === JSON.stringify(curr)),
takeUntil(this.unsubscribe)
).subscribe((value) => {
this.onNoProxyChange(value);
this.triggerStepDescriptionChange();
});
AppServices.messenger.subscribe<{ info: string }>(TanzuEventType.NETWORK_STEP_GET_NO_PROXY_INFO, event => {
this.additionalNoProxyInfo = event.payload.info;
this.generateFullNoProxy();
}, this.unsubscribe);
}
// onNoProxyChange() is protected to allow subclasses to override
protected onNoProxyChange(value: string) {
this.generateFullNoProxy();
}
// This is a method only implemented by the vSphere child class (which overrides this method);
// we need a method in this class because the general HTML references it;
// however it should only be called when enableNetworkName is true (which only the vSphere subclass sets)
loadNetworks() {
console.error('loadNetworks() was called, but no implementation is available. (enableNetworkName= ' + this.enableNetworkName + ')');
}
generateFullNoProxy() {
const noProxy = this.formGroup.get(NetworkField.NO_PROXY);
if (noProxy && !noProxy.value) {
this.fullNoProxy = '';
return;
}
const clusterServiceCidr = this.formGroup.get(NetworkField.CLUSTER_SERVICE_CIDR);
const clusterPodCidr = this.formGroup.get(NetworkField.CLUSTER_POD_CIDR);
const noProxyList = [
...noProxy.value.split(','),
this.additionalNoProxyInfo,
clusterServiceCidr && clusterServiceCidr.value,
clusterPodCidr && clusterPodCidr.value,
'localhost',
'127.0.0.1',
'.svc',
'.svc.cluster.local'
];
this.fullNoProxy = noProxyList.filter(elem => elem).join(',');
}
toggleProxySetting(fromSavedData?: boolean) {
const proxySettingFields = [
NetworkField.HTTP_PROXY_URL,
NetworkField.HTTP_PROXY_USERNAME,
NetworkField.HTTP_PROXY_PASSWORD,
NetworkField.HTTPS_IS_SAME_AS_HTTP,
NetworkField.HTTPS_PROXY_URL,
NetworkField.HTTPS_PROXY_USERNAME,
NetworkField.HTTPS_PROXY_PASSWORD,
NetworkField.NO_PROXY
];
if (!fromSavedData) {
this.formGroup.markAsPending();
}
if (this.formGroup.value[NetworkField.PROXY_SETTINGS]) {
this.resurrectField(NetworkField.HTTP_PROXY_URL, [
Validators.required,
this.validationService.isHttpOrHttps()
], this.formGroup.value[NetworkField.HTTP_PROXY_URL],
{ onlySelf: true }
);
this.resurrectField(NetworkField.NO_PROXY, [],
this.formGroup.value[NetworkField.NO_PROXY] || this.infraServiceAddress,
{ onlySelf: true }
);
if (!this.formGroup.value[NetworkField.HTTPS_IS_SAME_AS_HTTP]) {
this.resurrectField(NetworkField.HTTPS_PROXY_URL, [
Validators.required,
this.validationService.isHttpOrHttps()
], this.formGroup.value[NetworkField.HTTPS_PROXY_URL],
{ onlySelf: true }
);
} else {
const httpsFields = [
NetworkField.HTTPS_PROXY_URL,
NetworkField.HTTPS_PROXY_USERNAME,
NetworkField.HTTPS_PROXY_PASSWORD,
];
httpsFields.forEach((field) => {
this.disarmField(field, true);
});
}
} else {
proxySettingFields.forEach((field) => {
this.disarmField(field, true);
});
}
}
getCniTypeLabel() {
if (this.cniType === "none") {
return "None";
} else if (this.cniType === "calico") {
return "Calico";
} else {
return "Antrea"
}
}
// Reset the relevant fields upon data center change
resetFieldsUponDCChange() {
const fieldsToReset = ['networkName'];
fieldsToReset.forEach(f => this.formGroup.get(f) && this.formGroup.get(f).setValue('', { onlySelf: true }));
}
dynamicDescription(): string {
const serviceCidr = this.getFieldValue(NetworkField.CLUSTER_SERVICE_CIDR, true);
const podCidr = this.getFieldValue(NetworkField.CLUSTER_POD_CIDR, true);
if (serviceCidr && podCidr) {
return `Cluster Service CIDR: ${serviceCidr} Cluster Pod CIDR: ${podCidr}`;
}
if (podCidr) {
return `Cluster Pod CIDR: ${podCidr}`;
}
return SharedNetworkStepComponent.description;
}
// allows subclasses to subscribe to services during ngOnInit by overriding this method
protected subscribeToServices() {
}
protected storeUserData() {
// We store an entry for fullNoProxy (if we have a value) so it will display on the confirmation page
if (this.fullNoProxy) {
const entry = { display: this.fullNoProxy, value: this.fullNoProxy };
AppServices.userDataService.store(this.createUserDataIdentifier('fullProxyList'), entry);
}
this.storeUserDataFromMapping(this.supplyStepMapping());
this.storeDefaultDisplayOrder(this.supplyStepMapping());
}
// These network-related methods are referenced in the HTML, but used only by vSphere
get enableNoProxyWarning(): boolean {
return this.supplyEnablesNoProxyWarning();
}
get enableNetworkName(): boolean {
return this.supplyEnablesNetworkName();
}
get networkNameInstruction(): string {
return this.supplyNetworkNameInstruction();
}
get networks(): { displayName?: string }[] {
return this.supplyNetworks();
}
} | the_stack |
import * as _ from 'underscore';
import { CombatantTypes, IEnemy, IPartyMember } from './base-entity';
import { EntityWithEquipment } from './entity/entity.model';
import { EntityItemTypes } from './entity/entity.reducer';
import {
ITemplateArmor,
ITemplateBaseItem,
ITemplateMagic,
ITemplateWeapon,
} from './game-data/game-data.model';
import { getStatIncreaseForLevelUp, getXPForLevel } from './levels';
/**
* Query options used when calculating combat values
*/
export interface IMechanicsQuery<
StateType = CombatantTypes,
EquipmentType = ITemplateBaseItem,
AgainstType = CombatantTypes
> {
/** The query entity */
state: StateType;
/** Any weapons the query entity has equipped */
equipment?: EquipmentType[];
/**
* An optional target entity that is associated with the query. What
* this value means depends on the particular mechanics query function
* that is being called.
*/
against?: AgainstType | null;
}
/**
* Combat and leveling mechanics for party members. This is used mainly for
* calculating combat hits/misses/damage and leveling up character stats.
*/
export class PartyMechanics {
static getAttack(query: IMechanicsQuery<IPartyMember, ITemplateWeapon>): number {
const { state, equipment = [], against = null } = query;
const weaponAttack: number = equipment
// Assume it's a weapon
.map((w) => w.attack)
// Remove undefined values (maybe it was armor?)
.filter((v) => v)
// Sum the values
.reduce((prev, next) => prev + next, 0);
return weaponAttack + state.strength[0] / 2;
}
static getDefense(query: IMechanicsQuery<IPartyMember, ITemplateArmor>): number {
const { state, equipment = [], against = null } = query;
const totalDefense: number = equipment
// Assume it's a piece of armor
.map((w) => w.defense)
// Remove falsy values (maybe it was a weapon?)
.filter((v) => v)
// Sum the values
.reduce((prev, next) => prev + next, 0);
return totalDefense;
}
static getEvasion(query: IMechanicsQuery<IPartyMember, ITemplateArmor>): number {
const { state, equipment = [], against = null } = query;
const armorWeight: number = equipment
// Assume it's a piece of armor
.map((w: ITemplateArmor) => w.weight)
// Remove falsy values (maybe it was a weapon?)
.filter((v) => v)
// Sum the values
.reduce((prev, next) => prev + next, 0);
// This is the original FF evasion formula <3 :heart: <3
return 48 + state.agility[0] - armorWeight;
}
/**
* Calculate the hit percentage against the given enemy with the given weapons.
*
* Returns the hit percentage as a value between 0-100 (or more).
* @param weapons The weapon(s) we have equipped
* @param against The enemy (or null) we're trying to hit
*/
static getHitPercent(query: IMechanicsQuery<IPartyMember, ITemplateWeapon>): number {
const { state, equipment = [], against = null } = query;
const weaponHitPercent: number = equipment
// Assume it's a weapon
.map((w) => w.hit)
// Remove falsy values (maybe it was a weapon?)
.filter((v) => v)
// Sum the values
.reduce((prev, next) => prev + next, 0);
// Add the player hit percent to the sum of the weapons
return state.hitpercent[0] + weaponHitPercent;
}
}
/** Combat mechanics for Enemy entities */
export class EnemyMechanics {
static getAttack(query: IMechanicsQuery<IEnemy>): number {
return query.state.attack;
}
static getDefense(query: IMechanicsQuery<IEnemy>): number {
return query.state.defense;
}
static getEvasion(query: IMechanicsQuery<IEnemy>): number {
return 0;
}
static getHitPercent(query: IMechanicsQuery<IEnemy>): number {
return query.state.hitpercent;
}
}
export type MagicFunction = (
caster: EntityWithEquipment,
spell: ITemplateMagic,
target: ICalculateMagicTarget
) => IMagicTargetDelta;
export interface ICombatDamage {
attacker: CombatantTypes;
defender: CombatantTypes;
totalDamage: number;
damages: number[];
}
export interface ICalculateDamageConfig {
attackerType: 'party' | 'enemy';
attacker: CombatantTypes;
defenderType: 'party' | 'enemy';
defender: CombatantTypes;
attackerWeapons?: ITemplateWeapon[];
defenderArmor?: ITemplateArmor[];
verbose?: boolean;
}
/**
* Describe the various effects that should be applied to the target of
* this magic. The values are null if no change takes place.
*/
export interface IMagicTargetDelta {
target: CombatantTypes;
/** How many health points to add to the entity */
healthDelta?: number;
/** How many mana points to add to the entity */
magicDelta?: number;
/** A list of statuses to add to the entity */
statusAdd?: string[];
/** A list of statuses to remove from the entity */
statusRemove?: string[];
/** A list of template item ids to add to the entity's inventory */
itemGive?: string[];
/** A list of entity ids to remove from the target's inventory and add to the caster's inventory */
itemTake?: string[];
/** A list of entity item ids to destroy and remove from the entity's inventory */
itemDestroy?: string[];
}
/**
* A summary of the calculated effects a cast spell has on one or more targets and
* the caster.
*/
export interface IMagicEffects {
/** How many health points to add to the entity (usually negative) */
healthDelta?: number;
/** How many mana points to add to the entity (usually negative) */
magicDelta?: number;
/** The effects on each individual target */
targets: IMagicTargetDelta[];
}
export interface ICalculateMagicTarget {
entity: IEnemy | EntityWithEquipment;
inventory: EntityItemTypes[];
weapons: EntityItemTypes[];
armors: EntityItemTypes[];
}
export interface ICalculateMagicEffectsConfig {
casterType: 'party' | 'enemy';
caster: CombatantTypes;
targetsType: 'party' | 'enemy';
targets: ICalculateMagicTarget[];
spells?: ITemplateMagic[];
verbose?: boolean;
}
export function calculateMagicEffects(
config: ICalculateMagicEffectsConfig
): IMagicEffects {
const magicEffectName = config.spells[0].effect as MagicFunctionNames;
let spell: MagicFunction | null = SPELLS[magicEffectName];
if (spell === null) {
throw new Error('Unknown magic effect: ' + magicEffectName);
}
// Calculate effects for each target
const targetDeltas: IMagicTargetDelta[] = config.targets.map(
(target: ICalculateMagicTarget) => {
return spell(config.caster as EntityWithEquipment, config.spells[0], target);
}
);
return {
magicDelta: config.spells[0].magiccost,
targets: targetDeltas,
};
}
export const SPELLS = {
'elemental-damage': spellElementalDamage,
'modify-hp': spellModifyHP,
'modify-mp': spellModifyMP,
};
export type MagicFunctionNames = keyof typeof SPELLS;
export function spellElementalDamage(
caster: EntityWithEquipment,
spell: ITemplateMagic,
target: ICalculateMagicTarget
): IMagicTargetDelta {
// TODO: Check equipment for element-specific bonuses
return {
target: target.entity,
healthDelta: -((spell.magnitude * caster.intelligence[0]) / 4),
};
}
export function spellModifyHP(
caster: EntityWithEquipment,
spell: ITemplateMagic,
target: ICalculateMagicTarget
): IMagicTargetDelta {
// If the spell benefits a user, it restores health, otherwise it drains health.
const directionMultiplier = spell.benefit ? 1 : -1;
const delta = (spell.magnitude * caster.intelligence[0]) / 4;
return {
target: target.entity,
healthDelta: delta * directionMultiplier,
};
}
export function spellModifyMP(
caster: EntityWithEquipment,
spell: ITemplateMagic,
target: ICalculateMagicTarget
): IMagicTargetDelta {
// If the spell benefits a user, it restores mana, otherwise it drains mana.
const directionMultiplier = spell.benefit ? 1 : -1;
const delta = (spell.magnitude * caster.intelligence[0]) / 4;
return {
target: target.entity,
magicDelta: delta * directionMultiplier,
};
}
export function calculateDamage(config: ICalculateDamageConfig): ICombatDamage {
const {
attacker,
attackerType,
defender,
defenderType,
attackerWeapons = [],
defenderArmor = [],
verbose = true,
} = config;
const attackMechanics = attackerType === 'party' ? PartyMechanics : EnemyMechanics;
const defenseMechanics = defenderType === 'party' ? PartyMechanics : EnemyMechanics;
const roll: number = _.random(0, 200);
const defenderEvasion: number = defenseMechanics.getEvasion({
state: defender as any,
});
const hitPct = attackMechanics.getHitPercent({
state: attacker as any, // NOTE: hacks because TS & the types here instead of | :(
equipment: attackerWeapons,
against: defender,
});
const hitChance = Math.min(160 + hitPct, 255) - defenderEvasion;
let isHit = false;
if (roll === 200) {
isHit = false;
} else if (roll === 0) {
isHit = false;
} else {
isHit = roll <= hitChance;
}
if (!isHit) {
return {
attacker,
defender,
totalDamage: 0,
damages: [],
};
}
const tableData: { [key: string]: any }[] = [];
const hitMultiply = 1;
// The required hit percentage to land 2 consecutive hits
const doubleHitThreshold = 32;
// (1 + hitPct / doubleHitThreshold) * hitMultiplier
// Min of 1, Max of 2
const numHits = Math.min(
2,
Math.max(1, Math.floor((1 + hitPct / doubleHitThreshold) * hitMultiply))
);
const damages: number[] = [];
for (let i = 0; i < numHits; i++) {
const attackMin: number = attackMechanics.getAttack({
state: attacker as any,
equipment: attackerWeapons,
});
const attackMax = attackMin * 2;
const adjustedAttack = Math.max(
1,
Math.floor(Math.random() * (attackMax - attackMin + 1)) + attackMin
);
const defense: number = defenseMechanics.getDefense({
state: defender as any,
equipment: defenderArmor,
});
let buffDefense: number = 0;
// Apply guarding buff = Max(3, defense * 1.3)
if (defender.status.indexOf('guarding') !== -1) {
buffDefense = Math.max(3, Math.round(defense * 1.3));
}
const damage: number = Math.max(1, adjustedAttack - (defense + buffDefense));
tableData.push({
attacker: attacker,
attack: adjustedAttack,
damage: damage,
defender: defender,
defense: defense,
buffDefense: buffDefense,
hitPercentage: hitPct,
hit: isHit,
});
damages.push(damage);
}
// Sum the values
const totalDamage = Math.floor(damages.reduce((prev, next) => prev + next, 0));
// Print attack summary to console
if (verbose) {
if (damages.length > 1) {
tableData.push({ attacker: 'Total Damage', damage: totalDamage });
}
console.table(tableData);
}
return {
attacker,
defender,
totalDamage,
damages,
};
}
export function awardLevelUp(model: IPartyMember): IPartyMember {
const nextLevel: number = model.level + 1;
const variedHPBonus = Math.max(10, model.level * 4) + Math.random() * 10;
const bonusHP = model.level < 10 ? variedHPBonus : 0;
const bonusMP =
Math.random() * Math.max(2, (model.level * model.intelligence[0]) / 4);
const deltaHP = Math.ceil(model.vitality[0] / 4 + bonusHP);
let deltaMP = Math.ceil(model.intelligence[0] / 4 + bonusMP);
if (model.intelligence[0] == 0) {
deltaMP = 0;
}
const newHP = model.maxhp + deltaHP;
const newMP = model.maxmp + deltaMP;
const strength = newStatValue(
model,
model.strength,
getStatIncreaseForLevelUp(model, 'strength')
);
const agility = newStatValue(
model,
model.agility,
getStatIncreaseForLevelUp(model, 'agility')
);
const intelligence = newStatValue(
model,
model.intelligence,
getStatIncreaseForLevelUp(model, 'intelligence')
);
const luck = newStatValue(
model,
model.luck,
getStatIncreaseForLevelUp(model, 'luck')
);
const magicdefense = newStatValue(model, model.magicdefense);
const hitpercent = newStatValue(model, model.hitpercent);
return {
...model,
level: nextLevel,
maxhp: newHP,
maxmp: newMP,
mp: newMP,
hp: newHP,
strength,
agility,
intelligence,
luck,
magicdefense,
hitpercent,
};
}
export function awardExperience(exp: number, model: IPartyMember): IPartyMember {
const newExp: number = model.exp + exp;
let result: IPartyMember = {
...model,
exp: newExp,
};
const nextLevel: number = getXPForLevel(model.level + 1);
if (newExp >= nextLevel) {
result = awardLevelUp(model);
}
return result;
}
export function newStatValue(
model: IPartyMember,
stat: number[],
add: number = 0
): number[] {
let newValue = stat[0] + add;
if (stat.length > 1) {
newValue += stat[1];
return [newValue, stat[1]];
}
return [newValue];
}
export interface IPartyStatsDiff {
/** The entity that was diff'd */
readonly eid: string;
/** The entity name */
readonly name: string;
/** The entity level */
readonly level: number;
/** How many health points were gained while leveling up */
readonly hp: number;
/** How many mana points were gained while leveling up */
readonly mp: number;
/** How many points strength was increased by while leveling up */
readonly strength: number;
/** How many points agility was increased by while leveling up */
readonly agility: number;
/** How many points intelligence was increased by while leveling up */
readonly intelligence: number;
/** How many points vitality was increased by while leveling up */
readonly vitality: number;
/** How many points luck was increased by while leveling up */
readonly luck: number;
/** How many points hitpercent was increased by while leveling up */
readonly hitpercent: number;
/** How many points magicdefense was increased by while leveling up */
readonly magicdefense: number;
}
/**
* Given two party member snapshots, return the delta between their
* stat values. Useful for calculating stat increases while showing
* level up notifications, e.g. "Strength went up by 3!"
* @param before The party member data before
* @param after The party member data after
*/
export function diffPartyMember(
before: IPartyMember,
after: IPartyMember
): IPartyStatsDiff {
return {
name: after.name,
level: after.level,
eid: after.eid,
strength: after.strength[0] - before.strength[0],
agility: after.agility[0] - before.agility[0],
intelligence: after.intelligence[0] - before.intelligence[0],
vitality: after.vitality[0] - before.vitality[0],
luck: after.luck[0] - before.luck[0],
hitpercent: after.hitpercent[0] - before.hitpercent[0],
magicdefense: after.magicdefense[0] - before.magicdefense[0],
hp: after.hp - before.hp,
mp: after.mp - before.mp,
};
} | the_stack |
module TDev.AST {
export module Merge {
//var mergeLog = Util.log;
var mergeLog = (x) => {return};
var getTime = () => Util.perfNow();
var seqTime = [];
var sccTime = 0;
var treeTime = [];
var imTime = 0;
var oldSeqMerge = false;
var numChecks = 0;
export var badAstMsg = "malformed ASTs";
function enc(s : string) : string {
return "!"+s
}
function dec(s : string) : string {
return s.substr(1)
}
function getStableName(x : Stmt) : string {
if(x instanceof App) {
return "***"; // TODO XXX - is this an okay globally-unique symbol for the app ID?
} else {
return enc(x.getStableName());
}
}
function setStableName(x : Stmt, name : string) {
x.setStableName(dec(name));
}
function containsId(
table : { [s:string]:HashNode},
id : string
) : boolean {
if(table[id]) {
return true;
} else {
return false;
}
}
function containsArrow(
table : { [s:string]:HashNode},
id1 : string,
id2 : string
) : boolean {
var a = table[id1];
if(oldSeqMerge) {
if(a && a.successors.indexOf(id2) >= 0) {
return true;
} else {
return false;
}
} else {
var b = table[id2];
if(a && b && a.order < b.order) {
return true;
} else {
return false;
}
}
}
function getNodeHash(sh : HashNode[]) : {[s:string]:HashNode} {
var result : {[s:string]:HashNode} = {};
sh.forEach(x => {
result[x.name] = x;
});
return result;
}
function getChildren(s : HashNode) : HashNode[] {
if(!s) return[];
var stmts : Stmt[] = <Stmt[]>(s.stmt.children().filter(x => x instanceof Stmt));
if (s.stmt instanceof If &&
stmts.length == 2 &&
stmts[1] instanceof CodeBlock &&
(<CodeBlock>stmts[1]).isBlockPlaceholder())
stmts.pop()
//if(s.stmt instanceof Block) {
return stmts.map(function(x : Stmt, i : number) {
return new HashNode(s.name, getStableName(x), [], x);
});
/*} else {
return stmts.map(function(x : Stmt, i : number) {
return new HashNode(s.name, s.name+"_"+i, [], x);
});
}*/
}
export class HashNode {
public parent : string;
public name : string;
public successors : string[];
public stmt : Stmt;
public order : number;
public used : boolean;
constructor(parent : string, name : string, successors : string[], stmt : Stmt) {
this.parent = parent;
this.name = name;
this.successors = successors;
this.stmt = stmt;
}
public toString() : string {
return ""+this.name+":("+this.parent+"):["+/*this.successors.join(",")+*/"]"
}
}
function getStmt(table : { [s:string]:HashNode}, key : string) : Stmt {
if(table[key]) {
return table[key].stmt;
} else {
return null;
}
}
export function getIds(sl : Stmt[], allIds : string[]) : {[s:string]:HashNode} {
var nodeIndex = 0;
// returns the flattened list
function flatten(
sl : HashNode[],
table : { [s:string]:HashNode},
arr : string[]
) : string[] {
return sl.reduce(
function(acc2 : string[], x : HashNode, i : number) {
//mergeLog("getIds: "+x.name+" => "+x.toString());
x.order = nodeIndex++;
table[x.name] = null;
var theParent : string = undefined;
theParent = x.parent;
table[x.name] = x;
allIds.push(x.name);
acc2.push(x.name);
return flatten(getChildren(x), table, acc2);
},
arr
);
}
var result : { [s:string]:HashNode } = {};
var flat = flatten(sl.map((x : Stmt) => new HashNode(undefined, getStableName(x), [], x)), result, []);
flat.forEach(function(x,i) {
result[x].successors = flat.slice(i+1,flat.length)
});
return result;
}
function transitiveClosure(
succMap : { [s : string] : {[t:string] : number } }
) {
var keys = Object.keys(succMap);
mergeLog(">>> transitive closure: "+keys.length)
keys.forEach(k => {
keys.forEach(i => {
keys.forEach (j => {
succMap[i][j] = succMap[i][j] ||
(succMap[i][k] && succMap[k][j]);
})
})
})
}
export function stronglyConnectedComponents(
succMap : { [s : string] : {[t:string] : number } },
keys : string[],
resultAssignment : { [s : string] : number },
debug = false
) : string[][] {
//if(debug) console.log("SCC: "+keys.length);
var index = 0;
var stack = [];
var stackVals = {};
var indices = {};
var lowlink = {};
var result : string[][] = [];
var currentComponent : string[] = [];
keys.forEach(v => {
if(!indices[v]) strongConnect(v);
});
function strongConnect(v : string, depth = 0) {
//mergeLog("strongConnect("+v+"): "+depth);
//if(debug) numChecks++;
indices[v] = index;
lowlink[v] = index;
index++;
stack.push(v);
stackVals[v] = true;
// for each edge (v,w) ...
var temp = succMap[v];
if(temp) {
Object.keys(temp).forEach(w => {
//var check = temp[w];
//Util.assert(check > 0);
//if(check) {
// do the following:
if(indices[w] == undefined) {
strongConnect(w, depth+1);
lowlink[v] = Math.min(lowlink[v], lowlink[w]);
} else {
//var sccStart = getTime();
//var ind = stack.indexOf(w);
var ind = stackVals[w]
//var sccEnd = getTime();
//if(debug) sccTime += (sccEnd-sccStart);
if(ind >= 0) {
lowlink[v] = Math.min(lowlink[v], indices[w]);
}
}
//}
});
}
if(lowlink[v] == indices[v]) {
currentComponent = [];
do {
var w = stack.pop();
delete stackVals[w];
currentComponent.push(w);
} while(w != v);
result.push(currentComponent);
}
}
result.forEach((comp,index) => {
comp.forEach(v => {
resultAssignment[v] = index;
});
});
return result;
}
function initMatrix(
succMap : { [s : string] : {[t:string] : number } },
keys : string[],
init : number = 0
) {
keys.forEach(i => {
succMap[i] = {};
/*keys.forEach(j => {
succMap[i][j] = init;
});*/
});
}
function printMatrix(m : { [s : string] : {[t:string] : number } }) {
var str = "";
Object.keys(m).forEach(j => {
str += ", "+j;
});
mergeLog(str);
Object.keys(m).forEach(i => {
str = "";
Object.keys(m).forEach(j => {
str += ", "+m[i][j];
});
mergeLog(i+str);
})
}
function tokensToStr(a:Token[]) : string {
return a.map((x:Token) => x.getText()).join(" ");
}
function strToTokens(s:string) : Token[] {
return s.split(/\s+/).map((y:string) => {var t = new Literal(); t.data = y; return t});
}
export function merge3(o:Stmt, a:Stmt, b:Stmt, datacollector?:(IMergeData)=>void) : Stmt {
if(datacollector) {
sccTime = 0;
imTime = 0;
seqTime = [0,0,0,0,0,0,0,0,0,0];
treeTime = [0,0,0,0,0,0,0];
numChecks = 0;
}
/*if(!noprint) {
myO = o;
myA = a;
myB = b;
}*/
var start = getTime();
mergeLog(">>> Merge: "+getTime()+" begin merge3");
mergeLog(">>> Merge: "+getTime()+" get IDs");
var lo = [];
var la = [];
var lb = [];
var hashO = getIds([o], lo);
var hashA = getIds([a], la);
var hashB = getIds([b], lb);
function combineTokens(tl:Token[]) : Token[] {
return TDev.AST.ExprParser.parse0(tl).map(
(x:StackOp) => {
if(x.expr) {
return <Token>(x.expr);
} else {
return TDev.AST.mkOp(x.op);
}
}
);
}
function merge3tokens(eOt:Token[], eAt:Token[], eBt:Token[], combine) : Token[] {
//mergeLog(">>> merge3tokens: "+tokensToStr(eOt)+"; "+tokensToStr(eAt)+"; "+tokensToStr(eBt));
var i = 0;
//var com = combine ? ((x:Token[]) => combineTokens(x)) : ((x:Token[]) => x);
var com = ((x:Token[]) => x);
var eO = new ExprHolder(); eO.tokens = com(eOt);
var eA = new ExprHolder(); eA.tokens = com(eAt);
var eB = new ExprHolder(); eB.tokens = com(eBt);
var tmap : { [s : string] : Token } = {};
var index = 0; // unique id for tokens
// the following function compares ThingRef tokens by Decl ID,
// and otherwise uses the default token-distance function
var f = (tokenDist) => {
return (a:Token, b:Token) => {
if((!a) || (!b)) {
return tokenDist(a,b);
// TODO XXX - something is wrong with the following
} /*else if((a instanceof ThingRef) && (b instanceof ThingRef)) {
console.log(">>> comparing: "+a+", "+b+" -> ");
console.log(">>> "+(<ThingRef>a).def.getStableName());
console.log(">>> "+(<ThingRef>b).def.getStableName());
if((<ThingRef>a).def.getStableName() == (<ThingRef>b).def.getStableName()) {
return 0;
} else {
return 3;
}
}*/ else {
return tokenDist(a,b);
}
};
};
TDev.AST.Diff.diffExprs(eO, eA, {}, f);
TDev.AST.Diff.diffExprs(eO, eB, {}, f);
var da = eA.diffTokens;
var db = eB.diffTokens;
// compute IDs for the base tokens
var arrO = [];
for(var i = 0; i < da.length; i+=2) {
if(da[i]) {
var name = ""+index;
tmap[name] = da[i];
index++;
arrO.push(name);
}
}
// compute IDs for the A tokens
var arrA = [];
var j = 0; // keeps track of position in base
for(i = 1; i < da.length; i+=2) {
if(da[i]) {
if(da[i-1]) {
arrA.push(""+j);
} else {
var name = ""+index;
tmap[""+index] = da[i];
index++;
arrA.push(name);
}
}
if(da[i-1]) j++;
}
// compute IDs for the B tokens
var arrB = [];
j = 0; // keeps track of position in base
for(i = 1; i < db.length; i+=2) {
if(db[i]) {
if(db[i-1]) {
arrB.push(""+j);
} else {
var name = ""+index;
tmap[""+index] = db[i];
index++;
arrB.push(name);
}
}
if(db[i-1]) j++;
}
//mergeLog(">>>> O=["+arrO.join(",")+"], A=["+arrA.join(",")+"], B=["+arrB.join(",")+"]");
function mapper(x:string[]) : App {
var v = new App(null); // TODO - use Block
v.things = x.map((y:string)=>{
var z = new Decl();
z.setStableName(y);
return z;
});
return v;
}
var result : App = <App>merge3(mapper(arrO),mapper(arrA),mapper(arrB));
return result.things.map((x:Decl)=>tmap[x.getStableName()]);
}
var maxDepth = 0;
function merge3node(
oN : HashNode,
aN : HashNode,
bN : HashNode,
cmap : { [s : string] : string[] },
depth = 0
) : Stmt {
// NOTE - oN,aN,bN must agree on the name (stableName)
maxDepth = Math.max(depth, maxDepth);
var id;
if(oN) {
id = oN.name;
} else if(aN) {
id = aN.name;
} else if(bN) {
id = bN.name;
} else {
return null;
}
//mergeLog("merge3node("+id+"): "+maxDepth);
// "id" should be defined by now
var childs = cmap[id];
if(!childs) {
childs = [];
}
var newChilds = [];
//if(!id) {
// mergeLog("BAD!"); // TODO - get rid of
//} else {
newChilds = childs.map(function(x : string) {
//mergeLog(" trying: "+x+" : "+[hashO,hashA,hashB].map(y=>y[x]).join(", "));
return merge3node(hashO[x], hashA[x], hashB[x], cmap, depth+1);
});
//}
function getNewChild(index : number) : Stmt {
var rc = newChilds[index];
if(rc) {
return rc;
} else {
return null;
}
}
function merge3inputs(f, combine) {
var oTok = []; if(oN) oTok = f(oN.stmt);
var aTok = []; if(aN) aTok = f(aN.stmt);
var bTok = []; if(bN) bTok = f(bN.stmt);
return merge3tokens(oTok, aTok, bTok, combine);
}
/*
(Stmt)
-RecordField
-ResolveClause
Binding
-ActionBinding
-KindBinding
*(Comment)
(Block)
-(CodeBlock)
-(ConditionBlock)
-(ParameterBlock)
-(BindingBlock)
-(ResolveBlock)
-(FieldBlock)
-(InlineActionBlock)
*(For)
*(Foreach)
*(While)
*(If)
*(Box)
*(ExprStmt)
*(InlineActions)
*(InlineAction)
(ForeachClause)
*(Where)
-(ActionParameter)
-(ActionHeader)
(Decl)
(PropertyDecl)
*(GlobalDef)
*(Action)
*(RecordDef)
*(LibraryRef)
(SingletonDef)
(PlaceholderDef)
-(LocalDef)
-(App)
*/
// construct a new node containing newChilds
function test(x) {
var t1 = !oN || (oN.stmt instanceof x);
var t2 = !aN || (aN.stmt instanceof x);
var t3 = !bN || (bN.stmt instanceof x);
return t1 && t2 && t3;
}
function getChange(f) {
if(!aN && !bN) {
return undefined; // TODO - this should never happen?
} else if(!aN) {
return f(bN.stmt);
} else if(!bN) {
return f(aN.stmt);
} else if(!oN) {
return f(aN.stmt);
}
// at this point, oN.stmt,aN.stmt,bN.stmt are all defined
if(f(oN.stmt) == f(aN.stmt)) {
return f(bN.stmt);
} else {
return f(aN.stmt);
}
}
function mergeExprHolder(f) {
var temp = new ExprHolder();
temp.tokens = merge3inputs(x => f(x).tokens, true);
return temp
}
var result : Stmt = null;
var newName = undefined;
if(test(RecordField)) {
var dataKind = getChange(x => (<RecordField>x).dataKind);
var isKey = getChange(x => (<RecordField>x).isKey);
var nm = getChange(x => (<RecordField>x).getName());
result = new RecordField(nm, dataKind, isKey); // TODO - correct args?
} else if(test(ResolveClause)) {
var nm = getChange(x => (<ResolveClause>x).name);
result = new ResolveClause(nm);
(<ResolveClause>result).kindBindings = <BindingBlock>getNewChild(0); // TODO - check cast?
(<ResolveClause>result).actionBindings = <BindingBlock>getNewChild(1);
(<ResolveClause>result).defaultLib = getChange(x => (<ResolveClause>x).defaultLib);
// TODO - more properties?
} else if(test(ActionBinding)) {
var nm = getChange(x => (<ActionBinding>x).formalName);
result = new ActionBinding(nm);
(<ActionBinding>result).actualLib = getChange(x => (<ActionBinding>x).actualLib);
(<ActionBinding>result).actualName = getChange(x => (<ActionBinding>x).actualName);
(<ActionBinding>result).actual = getChange(x => (<ActionBinding>x).actual);
(<ActionBinding>result).isExplicit = getChange(x => (<ActionBinding>x).isExplicit);
} else if(test(KindBinding)) {
var nm = getChange(x => (<KindBinding>x).formalName);
result = new KindBinding(nm);
(<KindBinding>result).actual = getChange(x => (<KindBinding>x).actual);
(<KindBinding>result).isExplicit = getChange(x => (<KindBinding>x).isExplicit);
} else if(test(Binding)) {
var nm = getChange(x => (<Binding>x).formalName);
result = new Binding(nm);
(<Binding>result).isExplicit = getChange(x => (<Binding>x).isExplicit);
} else if(test(Comment)) {
result = new Comment();
(<Comment>result).text = tokensToStr(merge3inputs(x => strToTokens((<Comment>x).text), false));
//(<Comment>result).text = getChange(x => (<Comment>x).text);
} else if(test(CodeBlock)) {
//mergeLog("CodeBlock");
result = new CodeBlock();
(<CodeBlock>result).stmts = newChilds;
(<CodeBlock>result).flags = getChange(x => (<CodeBlock>x).flags);
} else if(test(ConditionBlock)) {
//mergeLog("ConditionBlock");
result = new ConditionBlock();
(<ConditionBlock>result).stmts = newChilds;
} else if(test(ParameterBlock)) {
//mergeLog("ParameterBlock");
result = new ParameterBlock();
(<ParameterBlock>result).stmts = newChilds;
} else if(test(BindingBlock)) {
//mergeLog("BindingBlock");
result = new BindingBlock();
(<BindingBlock>result).stmts = newChilds;
} else if(test(ResolveBlock)) {
//mergeLog("ResolveBlock");
result = new ResolveBlock();
(<ResolveBlock>result).stmts = newChilds;
} else if(test(FieldBlock)) {
//mergeLog("FieldBlock");
result = new FieldBlock();
(<FieldBlock>result).stmts = newChilds;
(<FieldBlock>result).parentDef = getChange(x => (<FieldBlock>x).parentDef);
} else if(test(InlineActionBlock)) {
//mergeLog("InlineActionBlock");
result = new InlineActionBlock();
(<InlineActionBlock>result).stmts = newChilds;
} else if(test(Block)) {
throw Error(badAstMsg);
//mergeLog("Block");
result = new Block();
(<Block>result).stmts = newChilds;
} else if(test(For)) {
//mergeLog("For");
result = new For();
(<For>result).body = <CodeBlock>getNewChild(0); // TODO - check cast?
(<For>result).boundLocal = getChange(x => (<For>x).boundLocal);
(<For>result).upperBound = mergeExprHolder(x => (<For>x).upperBound);
} else if(test(Foreach)) {
//mergeLog("Foreach");
result = new Foreach();
(<Foreach>result).conditions = <ConditionBlock>getNewChild(0); // TODO - check cast?
(<Foreach>result).body = <CodeBlock>getNewChild(1);
(<Foreach>result).boundLocal = getChange(x => (<Foreach>x).boundLocal);
(<Foreach>result).collection = mergeExprHolder(x => (<Foreach>x).collection);
} else if(test(While)) {
//mergeLog("While");
result = new While();
(<While>result).body = <CodeBlock>getNewChild(0); // TODO - check cast?
(<While>result).condition = mergeExprHolder(x => (<While>x).condition);
} else if(test(OptionalParameter)) {
result = new OptionalParameter();
(<OptionalParameter>result)._opt_name = getChange(x => (<OptionalParameter>x).getName());
(<OptionalParameter>result).expr = mergeExprHolder(x => (<OptionalParameter>x).expr);
} else if(test(If)) {
//mergeLog("If");
result = new If();
(<If>result).rawThenBody = <CodeBlock>getNewChild(0); // TODO - check cast?
var elseBody = <CodeBlock>getNewChild(1);
if (!elseBody) {
elseBody = Parser.emptyBlock()
elseBody.stmts[0].initStableName()
}
(<If>result).rawElseBody = elseBody;
(<If>result).rawCondition = mergeExprHolder(x => (<If>x).rawCondition);
(<If>result).isElseIf = getChange(x => (<If>x).isElseIf);
(<If>result).displayElse = getChange(x => (<If>x).displayElse);
} else if(test(Box)) {
//mergeLog("Box");
result = new Box();
(<Box>result).body = <CodeBlock>getNewChild(0); // TODO - check cast?
} else if(test(InlineActions)) {
//mergeLog("InlineActions");
result = new InlineActions();
(<InlineActions>result).actions = <InlineActionBlock>getNewChild(0); // TODO - check cast?
(<InlineActions>result).expr = mergeExprHolder(x => (<InlineActions>x).expr)
} else if(test(ExprStmt)) {
//mergeLog("ExprStmt");
result = new ExprStmt();
(<ExprStmt>result).expr = mergeExprHolder(x => (<ExprStmt>x).expr)
} else if(test(InlineAction)) {
//mergeLog("InlineAction");
result = new InlineAction();
(<InlineAction>result).body = <CodeBlock>getNewChild(0); // TODO - check cast?
(<InlineAction>result).name = getChange(x => (<InlineAction>x).name);
(<InlineAction>result).isOptional = getChange(x => (<InlineAction>x).isOptional);
(<InlineAction>result).isImplicit = getChange(x => (<InlineAction>x).isImplicit);
(<InlineAction>result).inParameters = getChange(x => (<InlineAction>x).inParameters);
(<InlineAction>result).outParameters = getChange(x => (<InlineAction>x).outParameters);
} else if(test(Where)) {
//mergeLog("Where");
result = new Where();
(<Where>result).condition = mergeExprHolder(x => (<Where>x).condition);
} else if(test(ForeachClause)) {
//mergeLog("ForeachClause");
result = new ForeachClause();
} else if(test(ActionParameter)) {
//mergeLog("ActionParameter");
result = new ActionParameter(mkLocal(
getChange(x => (<ActionParameter>x).getName()),
getChange(x => (<ActionParameter>x).getKind())
));
} else if(test(ActionHeader)) {
//mergeLog("ActionHeader");
result = new ActionHeader(new Action());
(<ActionHeader>result).inParameters = (<ParameterBlock>getNewChild(0)); // TODO - check cast?
(<ActionHeader>result).outParameters = (<ParameterBlock>getNewChild(1));
(<ActionHeader>result).action.body = (<CodeBlock>getNewChild(2));
} else if(test(GlobalDef)) {
//mergeLog("GlobalDef");
result = new GlobalDef();
(<GlobalDef>result).readonly = getChange(x => (<GlobalDef>x).readonly);
(<GlobalDef>result).comment = getChange(x => (<GlobalDef>x).comment);
(<GlobalDef>result).url = getChange(x => (<GlobalDef>x).url);
(<GlobalDef>result).isResource = getChange(x => (<GlobalDef>x).isResource);
(<GlobalDef>result).isTransient = getChange(x => (<GlobalDef>x).isTransient);
(<GlobalDef>result).cloudEnabled = getChange(x => (<GlobalDef>x).cloudEnabled);
(<GlobalDef>result).debuggingData = getChange(x => (<GlobalDef>x).debuggingData);
(<GlobalDef>result).cloudEnabled = getChange(x => (<GlobalDef>x).cloudEnabled);
} else if(test(Action)) {
//mergeLog("Action");
result = new Action();
var ah : ActionHeader = (<ActionHeader>getNewChild(0)); // TODO - check cast?
(<Action>result).body = ah.action.body;
ah.action = (<Action>result);
ah.inParameters.parent = result;
ah.outParameters.parent = result;
(<Action>result).header = ah;
(<Action>result).isPrivate = getChange(x => (<Action>x).isPrivate);
(<Action>result)._isPage = getChange(x => (<Action>x)._isPage);
(<Action>result)._isTest = getChange(x => (<Action>x)._isTest);
(<Action>result)._isActionTypeDef = getChange(x => (<Action>x)._isActionTypeDef);
(<Action>result).isAtomic = getChange(x => (<Action>x).isAtomic);
(<Action>result).eventInfo = getChange(x => (<Action>x).eventInfo);
(<Action>result).isOffline = getChange(x => (<Action>x).isOffline);
(<Action>result).isQuery = getChange(x => (<Action>x).isQuery);
(<Action>result)._isTest = getChange(x => (<Action>x)._isTest);
// TODO XXX make sure the following is okay
if(getChange(x => (<Action>x).modelParameter)) {
(<Action>result).modelParameter = <ActionParameter>ah.inParameters.stmts.shift();
}
} else if(test(RecordDef)) {
result = new RecordDef();
(<RecordDef>result).keys = (<FieldBlock>getNewChild(0)); // TODO - check cast?
(<RecordDef>result).values = (<FieldBlock>getNewChild(1));
(<RecordDef>result).description = getChange(x => (<RecordDef>x).description);
(<RecordDef>result).recordType = getChange(x => (<RecordDef>x).recordType);
(<RecordDef>result).cloudEnabled = getChange(x => (<RecordDef>x).cloudEnabled);
(<RecordDef>result).persistent = getChange(x => (<RecordDef>x).persistent);
(<RecordDef>result)._isExported = getChange(x => (<RecordDef>x)._isExported);
newName = getChange(x => (<RecordDef>x).getCoreName());
// TODO - what other things do we need to set here?
} else if(test(LibraryRef)) {
result = new LibraryRef();
(<LibraryRef>result).resolveClauses = (<ResolveBlock>getNewChild(0));
(<LibraryRef>result).guid = getChange(x => (<LibraryRef>x).guid);
(<LibraryRef>result).pubid = getChange(x => (<LibraryRef>x).pubid);
(<LibraryRef>result)._publicActions = getChange(x => (<LibraryRef>x)._publicActions);
(<LibraryRef>result)._publicKinds = getChange(x => (<LibraryRef>x)._publicKinds);
// TODO - what other things do we need to set here?
} else if(test(PropertyDecl)) {
throw Error(badAstMsg);
//mergeLog("PropertyDecl");
result = new PropertyDecl();
} else if(test(SingletonDef)) {
throw Error(badAstMsg);
//mergeLog("SingletonDef");
result = new SingletonDef();
(<SingletonDef>result)._isBrowsable = getChange(x => (<SingletonDef>x)._isBrowsable);
} else if(test(PlaceholderDef)) {
throw Error(badAstMsg);
//mergeLog("PlaceholderDef");
result = new PlaceholderDef();
} else if(test(LocalDef)) {
//mergeLog("LocalDef");
result = new LocalDef();
} else if(test(App)) {
//mergeLog("App");
result = new App(null);
(<App>result).rootId = getChange(x => (<App>x).rootId);
(<App>result).icon = getChange(x => (<App>x).icon);
(<App>result).color = getChange(x => (<App>x).color);
(<App>result).comment = getChange(x => (<App>x).comment);
(<App>result).iconArtId = getChange(x => (<App>x).iconArtId);
(<App>result).splashArtId = getChange(x => (<App>x).splashArtId);
App.metaMapping.forEach(k => {
result[k] = getChange(x => x[k])
});
(<App>result).setPlatform(getChange(x => (<App>x).getPlatformRaw()));
(<App>result).things = <Decl[]>newChilds;
// TODO XXX
} else if(test(Decl)) {
//mergeLog("Decl");
result = new Decl();
(<Decl>result)._wasTypechecked = getChange(x => (<Decl>x)._wasTypechecked);
(<Decl>result).deleted = getChange(x => (<Decl>x).deleted);
// TODO - do we need to handle this parent separately?
(<Decl>result).wasAutoNamed = getChange(x => (<Decl>x).wasAutoNamed);
(<Decl>result).diffStatus = getChange(x => (<Decl>x).diffStatus);
(<Decl>result).diffAltDecl = getChange(x => (<Decl>x).diffAltDecl);
} else if(test(Stmt)) {
throw Error(badAstMsg);
//mergeLog("Stmt");
result = new Stmt();
} else {
//mergeLog("<<NONE>>");
throw Error(badAstMsg); // TODO - can't merge - what should we do here?
//result = new CodeBlock();
//(<CodeBlock>result).stmts = newChilds;
}
result._kind = getChange(x => x._kind); // TODO XXX
setStableName(result, id);
if(newName) result.setName(newName)
else result.setName(getChange(x => x.getName()));
newChilds.forEach(function(x:Stmt) {
x.parent = result;
});
return result;
}
mergeLog(">>> Merge: "+getTime()+" init maps");
var tt = getTime();
var parentMap : { [s : string] : string } = {};
var parentTemp : { [s : string] : boolean } = {};
var added : { [s : string] : boolean } = {};
var succMap : { [s : string] : {[t:string] : number } } = {};
// TODO XXX - don't use "for"!
Object.keys(hashO).forEach(key => { parentMap[key] = null; });
Object.keys(hashA).forEach(key => { parentMap[key] = null; });
Object.keys(hashB).forEach(key => { parentMap[key] = null; });
var tt2 = getTime(); treeTime[0]+=(tt2-tt); tt = tt2; // 0
mergeLog(">>> Merge: "+getTime()+" step 1");
// step 1 - perform additions and deletions
Object.keys(parentMap).forEach(x => {
var intersect = (containsId(hashA,x) &&
containsId(hashB,x) && containsId(hashO,x));
if(
!(((containsId(hashA,x) || containsId(hashB,x)) &&
!(containsId(hashO,x))) || intersect)
) {
delete parentMap[x];
} else if(!intersect) {
added[x] = true;
}
});
var tt2 = getTime(); treeTime[1]+=(tt2-tt); tt = tt2; // 1
//if(!noprint) console.log("added: "+Object.keys(added));
mergeLog(">>> Merge: "+getTime()+" step 2");
function applyChanges(f) {
Object.keys(parentMap).forEach(x => {
var pO = hashO[x];
var pA = hashA[x];
var pB = hashB[x];
f(x,parentMap,(pO ? pO.parent : undefined),(pA ? pA.parent : undefined),(pB ? pB.parent : undefined));
});
}
applyChanges((x,parentMap,pO,pA,pB) => { if(pA != pO) {/*console.log("locking: "+x);*/ parentTemp[x]=true;} parentMap[x]=pA });
applyChanges((x,parentMap,pO,pA,pB) => { if(pB != pA && !parentTemp[x]) parentMap[x]=pB });
var tt2 = getTime(); treeTime[2]+=(tt2-tt); tt = tt2; // 2
var roots = [];
var pk = Object.keys(parentMap)
pk.forEach(k => {
var src = parentMap[k];
var dst = k;
/*if(!succMap[src] && src) {
succMap[src] = {};
}
if(!succMap[dst] && dst) {
succMap[dst] = {};
}*/
if(src && dst) {
if(!succMap[src]) succMap[src] = {};
succMap[src][dst] = 1;
}
if(!src) roots.push(dst);
// TODO - get rid of:
//console.log("--- item="+k+", parent="+parentMap[k])
});
var tt2 = getTime(); treeTime[3]+=(tt2-tt); tt = tt2; // 3
var table : { [s : string] : number } = {};
var conn = stronglyConnectedComponents(succMap, pk, table);
succMap = null;
var tt2 = getTime(); treeTime[4]+=(tt2-tt); tt = tt2; // 4
//mergeLog("strongly connected components: ");
//mergeLog(table);
//mergeLog("roots = "+roots.map(x => x+"("+table[x]+")").join(", "));
function processChildren(cl : string[], done : {[t:string] : boolean }) {
cl.forEach((x:string) => {
//mergeLog("processing: "+x);
var pA = hashA[x];
var childA = getNodeHash(getChildren(pA));
var childAll = Object.keys(childA);
//var childAll = Object.keys(succMap).map(k => succMap[x][k] ? k : undefined).filter(k => !!k);
//mergeLog(" childs: "+childAll.join(","));
//childAll.sort(); // TODO - get rid of
childAll.forEach(y => {
if(table[x] != table[y] && !done[table[y]]) {
if(parentMap[y]) parentMap[y] = x;
done[table[y]] = true;
}
});
processChildren(childAll, done);
});
}
var initDone : {[t:string] : boolean } = {};
conn.forEach(comp => {
comp.forEach(x => {
if(comp.length <= 1) initDone[table[x]] = true;
});
});
var tt2 = getTime(); treeTime[5]+=(tt2-tt); tt = tt2; // 5
//mergeLog("initDone:");
//mergeLog(initDone);
processChildren(roots, initDone);
//mergeLog(parentMap);
// step 2 - determine parents
/*Object.keys(parentMap).forEach(x => {
var temp;
if(
containsId(hashO,x) && containsId(hashA,x) &&
containsId(hashB,x)
) {
var p1 = hashO[x];
var p2 = hashA[x];
var p3 = hashB[x];
mergeLog(" check 1: ("+p1.parent+" = "+p2.parent+", "+p3.parent+")");
if(p1.parent==p2.parent) {
temp = p3;
} else {
temp = p2;
}
} else if(containsId(hashA,x)) {
mergeLog(" check 2:");
var p2 = hashA[x];
temp = p2;
} else { // containsId(hashB,x)
mergeLog(" check 3:");
var p3 = hashB[x];
temp = p3;
}
mergeLog("setting parent of "+x+" to "+temp.parent);
parentMap[x] = temp.parent;
});*/
var tt2 = getTime(); treeTime[6]+=(tt2-tt); tt = tt2; // 6
mergeLog(">>> Merge: "+getTime()+" step 3: "+Object.keys(parentMap).length);
// step 3 - determine ordering
var startX = getTime();
var childMap : { [s : string] : string[] } = {};
Object.keys(parentMap).forEach(x => {
var p = parentMap[x];
if(childMap[p]) {
if(childMap[p].indexOf(x) < 0) {
childMap[p].push(x);
}
} else {
childMap[p] = [x];
}
});
var tt2 = getTime(); seqTime[0]+=(tt2-tt); tt = tt2; // 0
function addEdge(theX : string, theY : string, edgeMap : { [s : string] : {[t:string] : number } }, v : number = 1) {
if(!edgeMap[theY][theX]) {
edgeMap[theX][theY] = v;
}
}
Object.keys(childMap).forEach(px => {
var childs = childMap[px];
mergeLog(">>> processing children: "+px+": "+getTime());
// now we want to order "childs"
////////////////////////////////////
var addMap : { [s : string] : HashNode[] } = {};
var edgeMap : { [s : string] : {[t : string] : number} } = {};
initMatrix(edgeMap, childs);
if(oldSeqMerge) {
// part (a) - take the ones where A (left) disagrees
//if(ck.length > 2000) throw new Error("Too many children: "+ck.length) // TODO XXX - get rid of
mergeLog(">>> part A: "+childs.length);
childs.forEach(i => {
childs.forEach(j => {
if(i != j) {
var theX = i;
var theY = j;
if (
containsArrow(hashA, theX, theY) &&
(
!containsArrow(hashO, theX, theY)
||
!containsArrow(hashB, theY, theX)
)
) addEdge(theX, theY, edgeMap);
//if(theRes != temp) console.log(">>>>>>>>>>>>>>>> theRes != temp: ("+theRes+" != "+temp+"): "+msg);
}
});
});
transitiveClosure(edgeMap);
mergeLog(">>> part C");
// part (c) - take the ones where B (right) disagrees
childs.forEach(i => {
childs.forEach(j => {
if(i != j) {
var theX = i;
var theY = j;
/*if(
containsArrow(hashB, theX, theY) &&
(
containsArrow(hashO, theY, theX) &&
containsArrow(hashA, theY, theX)
)
) {
addEdge(theX, theY, edgeMap);
}*/
if(
containsArrow(hashB, theX, theY) &&
(
(
containsArrow(hashO, theY, theX) &&
containsArrow(hashA, theY, theX)
) ||
(
!containsArrow(hashO, theY, theX) &&
!containsArrow(hashA, theY, theX)
)
)
) {
addEdge(theX, theY, edgeMap);
}
}
})
});
transitiveClosure(edgeMap);
mergeLog(">>> part E");
// part (e) - add edges from A to B where ordering is unknown
childs.forEach(i => {
childs.forEach(j => {
if(i != j) {
var theX = i;
var theY = j;
if(
(
containsId(hashA, theX) &&
!containsId(hashB, theX)
) &&
(
containsId(hashB, theY) &&
!containsId(hashA, theY)
)
) {
addEdge(theX, theY, edgeMap);
}
}
})
});
transitiveClosure(edgeMap);
} else {
// part (a) - take the ones where A (left) disagrees
var imStart = getTime();
// slow
var sla = childs.reduce((acc:HashNode[],x:string) => {
var y = hashA[x];
if(y) {
y.used = false;
acc.push(y);
}
return acc;
}, []).sort((x,y) => x.order < y.order ? -1 : 1) //.map(x => x.name)
var slb = childs.reduce((acc:HashNode[],x:string) => {
var y = hashB[x];
if(y) {
y.used = false;
acc.push(y);
}
return acc
}, []).sort((x,y) => x.order < y.order ? -1 : 1) //.map(x => x.name)
/*var sla2 = la.filter(x => !!edgeMap[x])
var slb2 = lb.filter(x => !!edgeMap[x])
var theCheck = (sla2.toString() == sla.toString() && slb2.toString() == slb.toString());
if(!theCheck) {
console.log("sla = "+sla+"\nsla2 = "+sla2);
console.log("slb = "+slb+"\nslb2 = "+slb2);
}
Util.assert(theCheck);*/
var imEnd = getTime();
imTime += (imEnd-imStart);
var tt2 = getTime(); seqTime[1]+=(tt2-tt); tt = tt2; // 1
sla.reduce((prevs:HashNode[],curr:HashNode) => {
if(added[curr ? curr.name : undefined]) {
prevs.forEach((prev:HashNode) => {
if(!addMap[prev ? prev.name : undefined]) addMap[prev ? prev.name : undefined] = [];
//addMap[prev].push(curr);
addMap[prev ? prev.name : undefined].unshift(curr);
})
}
prevs.push(curr);
return prevs;
}, [undefined]);
slb.reduce((prevs:HashNode[],curr:HashNode) => {
if(added[curr ? curr.name : undefined]) {
prevs.forEach((prev:HashNode) => {
if(!addMap[prev ? prev.name : undefined]) addMap[prev ? prev.name : undefined] = [];
//addMap[prev].push(curr);
addMap[prev ? prev.name : undefined].unshift(curr);
})
}
prevs.push(curr);
return prevs;
}, [undefined]);
childs = childs.filter(x => !added[x]);
var tt2 = getTime(); seqTime[2]+=(tt2-tt); tt = tt2; // 2
mergeLog(">>> part A: "+childs.length);
childs.forEach(i => {
childs.forEach(j => {
if(i != j) {
var theX = i;
var theY = j;
if (
containsArrow(hashA, theX, theY) &&
(
!containsArrow(hashO, theX, theY)
||
!containsArrow(hashB, theY, theX)
)
) addEdge(theX, theY, edgeMap, 1);
//if(theRes != temp) console.log(">>>>>>>>>>>>>>>> theRes != temp: ("+theRes+" != "+temp+"): "+msg);
}
});
});
var tt2 = getTime(); seqTime[3]+=(tt2-tt); tt = tt2; // 3
mergeLog(">>> part B");
// part (c) - take the ones where B (right) disagrees
childs.forEach(i => {
childs.forEach(j => {
if(i != j) {
var theX = i;
var theY = j;
if(
containsArrow(hashB, theX, theY) &&
(
(
containsArrow(hashO, theY, theX) &&
containsArrow(hashA, theY, theX)
)
)
) {
addEdge(theX, theY, edgeMap, 2);
}
}
})
});
var tt2 = getTime(); seqTime[4]+=(tt2-tt); tt = tt2; // 4
mergeLog(">>> SCC: "+childs.length);
var nums : { [s : string] : number} = {};
var comps = stronglyConnectedComponents(edgeMap, childs, nums, (childs.length > 100));
var tt2 = getTime(); seqTime[5]+=(tt2-tt); tt = tt2; // 5
mergeLog(">>> comps");
// delete all B edges which are in a non-trivial strongly-connected component,
// replacing them with opposing A edges
comps.forEach(comp => {
if(comp.length <= 1) return; // ignore
comp.forEach(x => {
comp.forEach(y => {
if(edgeMap[x][y] >= 2) {
edgeMap[x][y] = 0
edgeMap[y][x] = 1
}
})
})
});
var tt2 = getTime(); seqTime[6]+=(tt2-tt); tt = tt2; // 6
}
////////////////////////////////////
//printMatrix(edgeMap);
mergeLog(">>> sorting");
childs.sort((a,b) => {
if(true || oldSeqMerge) { // TODO XXX - remove
if(edgeMap[a][b] > 0) {
return -1;
} else if(edgeMap[b][a] > 0) {
return 1;
} else {
throw "merge exception: ("+a+", "+b+") not ordered";
}
}
});
edgeMap = null;
var tt2 = getTime(); seqTime[7]+=(tt2-tt); tt = tt2; // 7
function pop(answer : string[]) {
//if(!first && !init) return answer;
if(childs.length == 0) return answer;
var first = childs.pop();
var a = addMap[first];
if(a) {
// NOTE - var "a" is in backwards order, i.e. the last element should appear
// first in the result
a.forEach(x => {
if(x && !x.used) {
x.used = true;
answer.unshift(x.name);
}
});
//childs = a.concat(childs);
}
if(first) answer.unshift(first);
return pop(answer);
}
if(!oldSeqMerge) {
childs.unshift(undefined);
childs = pop([]);
childMap[px] = childs;
}
sla.forEach(x => x.used = false);
slb.forEach(x => x.used = false);
addMap = null;
var tt2 = getTime(); seqTime[8]+=(tt2-tt); tt = tt2; // 8
});
var endX = getTime();
//seqTime += (endX-startX);
var theTemp : string = undefined;
delete childMap[theTemp];
Object.keys(childMap).forEach(x => {
var childs = childMap[x];
var s = "";
if(x == getStableName(o)) {
s = "<<ROOT>>";
}
mergeLog(">>> Merge: parent="+x+", child="+childs.join(", ")+" | "+s);
});
// TODO - childMap can now be used directly
// to produce the new merged AST
var end1 = getTime();
mergeLog(">>> Merge: "+getTime()+" doing node-level merge...");
//var rtemp = o; // TODO - see the above note
var rtemp = merge3node(
new HashNode(undefined, getStableName(o), [], o),
new HashNode(undefined, getStableName(a), [], a),
new HashNode(undefined, getStableName(b), [], b),
childMap
);
var end = getTime();
if (datacollector) {
var mergedata = <IMergeData> {};
mergedata.totaltime = (end - start);
mergedata.nodeleveltime = (end - end1);
mergedata.seqtime = seqTime;
mergedata.treetime = treeTime;
mergedata.scctime = sccTime;
mergedata.numchecks = numChecks;
mergedata.deviceinfo = Browser.platformCaps;
mergedata.releaseid = Cloud.currentReleaseId;
datacollector(mergedata);
// TODO XXX - print this?
//mergeLog(">>> Merge: " + getTime() + " >>> TOTAL TIME: " + mergedata.totaltime + ", NODE-LEVEL TIME: " + mergedata.nodeleveltime + ", seqTime =" + seqTime + " (" + seqTime + "), treeTime = " + treeTime + ", sccTime = " + sccTime + ", numChecks = " + numChecks);
}
return rtemp;
}
export interface IMergeData {
totaltime: number;
nodeleveltime: number;
seqtime: number[];
treetime: number[];
scctime: number;
numchecks: number;
deviceinfo: string[];
releaseid: string;
}
export var theO = undefined;
export var theA = undefined;
export var theB = undefined;
export var theM = undefined;
function getApp(text:string) {
var app = (<any>TDev).AST.Parser.parseScript(text);
(<any>TDev).AST.TypeChecker.tcApp(app);
var v = new TDev.AST.InitIdVisitor(false);
v.dispatch(app);
return app;
}
export function testMerge(idO="yqum", idA="yqum", idB="xspn") {
(<any>TDev).ScriptCache.getScriptAsync(idO).then(textO =>
(<any>TDev).ScriptCache.getScriptAsync(idA).then(textA =>
(<any>TDev).ScriptCache.getScriptAsync(idB).then(textB => {
var table = {};
[[idO,textO],[idA,textA],[idB,textB]].forEach(x => {
if(!table[x[0]]) {
table[x[0]] = getApp(x[1])
}
})
function doMerge(idO:string, idA:string, idB:string, compareTo:string) {
theO = table[idO];
theA = table[idA];
theB = table[idB];
var m = (<any>TDev).AST.Merge.merge3(theO,theA,theB);
(<any>TDev).AST.TypeChecker.tcApp(m);
theM = m;
var success = false;
var str = "merge("+idO+","+idA+","+idB+")";
if(table[compareTo] && m.serialize().replace(/\s*/g,"") != table[compareTo].serialize().replace(/\s*/g,"")) {
str += (" =/= ");
m.things.forEach((th,i) => {
if(m.things[i].serialize().replace(/\s*/g,"") != table[compareTo].things[i].serialize().replace(/\s*/g,"")) {
console.log("unequal: "+i);
}
});
} else {
success = true;
str += (" = ");
}
console.log(str+""+compareTo+(!success ? " ((FAIL!))" : " (success)"));
}
console.log("testing merge(x,x,x)");
doMerge(idO,idO,idO,idO);
doMerge(idA,idA,idA,idA);
doMerge(idB,idB,idB,idB);
console.log("testing merge(x,y,x)");
doMerge(idO,idA,idO,idA);
doMerge(idO,idB,idO,idB);
doMerge(idA,idB,idA,idB);
doMerge(idA,idO,idA,idO);
doMerge(idB,idA,idB,idA);
doMerge(idB,idO,idB,idO);
console.log("testing merge(x,x,y)");
doMerge(idO,idO,idA,idA);
doMerge(idO,idO,idB,idB);
doMerge(idA,idA,idB,idB);
doMerge(idA,idA,idO,idO);
doMerge(idB,idB,idA,idA);
doMerge(idB,idB,idO,idO);
}
)
)
)
}
export function basicTest(o:string, a:string, b:string) {
if(!o) {
o =
"meta version \"v2.2,js,ctx,refs,localcloud,unicodemodel,allasync\";\n"+
"meta name \"awe-inspiring script\";\n"+
"meta rootId \"nLWNALhDdDnO6mTvydoNe8aI\";\n"+
"meta allowExport \"yes\";\n"+
"meta platform \"current\";\n"+
"meta parentIds \"\";\n"+
"#main\n"+
"action main() {\n"+
" #x1QgKIXXV6P3GL4v $x1 := 1;\n"+
" #nrxemFg0cPs5bQh7 $x2 := 12;\n"+
"}\n"+
"#main2\n"+
"action main2() {\n"+
" #x1QgKIXXV6P3GL4v1 $x1 := 1;\n"+
" #nrxemFg0cPs5bQh72 $x2 := 12;\n"+
" #rpYjyryilrIApEv14 $x4 := 123;\n"+
"}\n"
}
if(!a) {
a =
"meta version \"v2.2,js,ctx,refs,localcloud,unicodemodel,allasync\";\n"+
"meta name \"awe-inspiring script\";\n"+
"meta rootId \"nLWNALhDdDnO6mTvydoNe8aI\";\n"+
"meta allowExport \"yes\";\n"+
"meta platform \"current\";\n"+
"meta parentIds \"\";\n"+
"#main\n"+
"action main() {\n"+
" #nrxemFg0cPs5bQh7 $x2 := 12;\n"+
" #x1QgKIXXV6P3GL4v $x1 := 1;\n"+
"}\n"+
"#main2\n"+
"action main2() {\n"+
" #x1QgKIXXV6P3GL4v1 $x1 := 1;\n"+
" #nrxemFg0cPs5bQh72 $x2 := 12;\n"+
" #rpYjyryilrIApEv03 $x3 := 123;\n"+
"}\n"
}
if(!b) {
b =
"meta version \"v2.2,js,ctx,refs,localcloud,unicodemodel,allasync\";\n"+
"meta name \"awe-inspiring script\";\n"+
"meta rootId \"nLWNALhDdDnO6mTvydoNe8aI\";\n"+
"meta allowExport \"yes\";\n"+
"meta platform \"current\";\n"+
"meta parentIds \"\";\n"+
"#main\n"+
"action main() {\n"+
" #x1QgKIXXV6P3GL4v $x1 := 1;\n"+
" #nrxemFg0cPs5bQh7 $x2 := 12;\n"+
" #rpYjyryilrIApEv0 $x3 := 123;\n"+
" #rpYjyryilrIApEv1 $x4 := 123;\n"+
" #rpYjyryilrIApEv2 $x5 := 123;\n"+
" #rpYjyryilrIApEv3 $x6 := 123;\n"+
"}\n"+
"#main2\n"+
"action main2() {\n"+
" #nrxemFg0cPs5bQh72 $x2 := 12;\n"+
" #x1QgKIXXV6P3GL4v1 $x1 := 1;\n"+
"}\n"
}
theO = getApp(o);
theA = getApp(a);
theB = getApp(b);
var m = (<any>TDev).AST.Merge.merge3(theO,theA,theB);
(<any>TDev).AST.TypeChecker.tcApp(m);
theM = m;
}
}
class Normalizer
extends NodeVisitor
{
visitStmt(s:Stmt)
{
this.visitChildren(s)
}
visitCodeBlock(b:CodeBlock)
{
var newStmts = []
var lastPlace = false
b.stmts.forEach(s => {
if (s.isPlaceholder() && lastPlace) return
lastPlace = s.isPlaceholder()
newStmts.push(s)
})
b.stmts = newStmts
this.visitChildren(b)
}
}
export function mergeScripts(baseText:string, ourText:string, otherText:string)
{
var prep = (s:string) => {
var app = Parser.parseScript(s, [])
TypeChecker.tcScript(app, true)
new InitIdVisitor(false).dispatch(app)
return app
}
var baseApp = prep(baseText)
var ourApp = prep(ourText)
var otherApp = prep(otherText)
var mergedApp = <App>Merge.merge3(baseApp, ourApp, otherApp)
mergedApp.parentIds = ourApp.parentIds.slice(0)
// new Normalizer().dispatch(mergedApp)
Diff.diffApps(ourApp, mergedApp, { useStableNames: false })
return mergedApp
}
} | the_stack |
import { parse, Spec, Block } from "comment-parser";
import {
addStarsToTheBeginningOfTheLines,
convertToModernType,
formatType,
detectEndOfLine,
findTokenIndex,
findPluginByParser,
} from "./utils";
import { DESCRIPTION, PARAM, RETURNS } from "./tags";
import {
TAGS_DESCRIPTION_NEEDED,
TAGS_GROUP_HEAD,
TAGS_GROUP_CONDITION,
TAGS_NAMELESS,
TAGS_ORDER,
TAGS_SYNONYMS,
TAGS_TYPELESS,
TAGS_VERTICALLY_ALIGN_ABLE,
} from "./roles";
import { AST, AllOptions, PrettierComment, Token } from "./types";
import { stringify } from "./stringify";
import { Parser } from "prettier";
import { SPACE_TAG_DATA } from "./tags";
/** @link https://prettier.io/docs/en/api.html#custom-parser-api} */
export const getParser = (originalParse: Parser["parse"], parserName: string) =>
function jsdocParser(
text: string,
parsers: Parameters<Parser["parse"]>[1],
options: AllOptions,
): AST {
const prettierParse =
findPluginByParser(parserName, options)?.parse || originalParse;
const ast = prettierParse(text, parsers, options) as AST;
// jsdocParser is deprecated,this is backward compatible will be remove
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
if (options.jsdocParser === false) {
return ast;
}
options = {
...options,
printWidth: options.jsdocPrintWidth ?? options.printWidth,
};
const eol =
options.endOfLine === "auto" ? detectEndOfLine(text) : options.endOfLine;
options = { ...options, endOfLine: "lf" };
ast.comments.forEach((comment) => {
if (!isBlockComment(comment)) return;
const tokenIndex = findTokenIndex(ast.tokens, comment);
const paramsOrder = getParamsOrders(ast, tokenIndex);
/** Issue: https://github.com/hosseinmd/prettier-plugin-jsdoc/issues/18 */
comment.value = comment.value.replace(/^([*]+)/g, "*");
// Create the full comment string with line ends normalized to \n
// This means that all following code can assume \n and should only use
// \n.
const commentString = `/*${comment.value.replace(/\r\n?/g, "\n")}*/`;
/**
* Check if this comment block is a JSDoc. Based on:
* https://github.com/jsdoc/jsdoc/blob/master/packages/jsdoc/plugins/commentsOnly.js
*/
if (!/^\/\*\*[\s\S]+?\*\/$/.test(commentString)) return;
const parsed = parse(commentString, {
spacing: "preserve",
})[0];
comment.value = "";
if (!parsed) {
// Error on commentParser
return;
}
normalizeTags(parsed);
convertCommentDescToDescTag(parsed);
const commentContentPrintWidth = getIndentationWidth(
comment,
text,
options,
);
let maxTagTitleLength = 0;
let maxTagTypeLength = 0;
let maxTagNameLength = 0;
let tags = parsed.tags
// Prepare tags data
.map(({ type, optional, ...rest }) => {
if (type) {
/**
* Convert optional to standard
* https://jsdoc.app/tags-type.html#:~:text=Optional%20parameter
*/
type = type.replace(/[=]$/, () => {
optional = true;
return "";
});
type = convertToModernType(type);
type = formatType(type, {
...options,
printWidth: commentContentPrintWidth,
});
}
return {
...rest,
type,
optional,
} as Spec;
});
// Group tags
tags = sortTags(tags, paramsOrder, options);
if (options.jsdocSeparateReturnsFromParam) {
tags = tags.flatMap((tag, index) => {
if (tag.tag === RETURNS && tags[index - 1]?.tag === PARAM) {
return [SPACE_TAG_DATA, tag];
}
return [tag];
});
}
tags
.map(addDefaultValueToDescription)
.map(assignOptionalAndDefaultToName)
.map(({ type, name, description, tag, ...rest }) => {
const isVerticallyAlignAbleTags =
TAGS_VERTICALLY_ALIGN_ABLE.includes(tag);
if (isVerticallyAlignAbleTags) {
maxTagTitleLength = Math.max(maxTagTitleLength, tag.length);
maxTagTypeLength = Math.max(maxTagTypeLength, type.length);
maxTagNameLength = Math.max(maxTagNameLength, name.length);
}
return {
type,
name,
description: description.trim(),
tag,
...rest,
};
})
.filter(({ description, tag }) => {
if (!description && TAGS_DESCRIPTION_NEEDED.includes(tag)) {
return false;
}
return true;
})
// Create final jsDoc string
.forEach((tagData, tagIndex, finalTagsArray) => {
comment.value += stringify(
tagData,
tagIndex,
finalTagsArray,
{ ...options, printWidth: commentContentPrintWidth },
maxTagTitleLength,
maxTagTypeLength,
maxTagNameLength,
);
});
comment.value = comment.value.trimEnd();
if (comment.value) {
comment.value = addStarsToTheBeginningOfTheLines(
comment.value,
options,
);
}
if (eol === "cr") {
comment.value = comment.value.replace(/\n/g, "\r");
} else if (eol === "crlf") {
comment.value = comment.value.replace(/\n/g, "\r\n");
}
});
ast.comments = ast.comments.filter(
(comment) => !(isBlockComment(comment) && !comment.value),
);
return ast;
};
function sortTags(
tags: Spec[],
paramsOrder: string[] | undefined,
options: AllOptions,
): Spec[] {
let canGroupNextTags = false;
let shouldSortAgain = false;
tags = tags
.reduce<Spec[][]>((tagGroups, cur) => {
if (
tagGroups.length === 0 ||
(TAGS_GROUP_HEAD.includes(cur.tag) && canGroupNextTags)
) {
canGroupNextTags = false;
tagGroups.push([]);
}
if (TAGS_GROUP_CONDITION.includes(cur.tag)) {
canGroupNextTags = true;
}
tagGroups[tagGroups.length - 1].push(cur);
return tagGroups;
}, [])
.flatMap((tagGroup, index, array) => {
// sort tags within groups
tagGroup.sort((a, b) => {
if (
paramsOrder &&
paramsOrder.length > 1 &&
a.tag === PARAM &&
b.tag === PARAM
) {
const aIndex = paramsOrder.indexOf(a.name);
const bIndex = paramsOrder.indexOf(b.name);
if (aIndex > -1 && bIndex > -1) {
//sort params
return aIndex - bIndex;
}
return 0;
}
return (
getTagOrderWeight(a.tag, options) - getTagOrderWeight(b.tag, options)
);
});
// add an empty line between groups
if (array.length - 1 !== index) {
tagGroup.push(SPACE_TAG_DATA);
}
if (
index > 0 &&
tagGroup[0]?.tag &&
!TAGS_GROUP_HEAD.includes(tagGroup[0].tag)
) {
shouldSortAgain = true;
}
return tagGroup;
});
return shouldSortAgain ? sortTags(tags, paramsOrder, options) : tags;
}
/**
* Control order of tags by weights. Smaller value brings tag higher.
*/
function getTagOrderWeight(tag: string, options: AllOptions): number {
if (tag === DESCRIPTION && !options.jsdocDescriptionTag) {
return -1;
}
const index = TAGS_ORDER.indexOf(tag);
return index === -1 ? TAGS_ORDER.indexOf("other") : index;
}
function isBlockComment(comment: PrettierComment): boolean {
return comment.type === "CommentBlock" || comment.type === "Block";
}
function getIndentationWidth(
comment: PrettierComment,
text: string,
options: AllOptions,
): number {
const line = text.split(/\r\n?|\n/g)[comment.loc.start.line - 1];
let spaces = 0;
let tabs = 0;
for (let i = comment.loc.start.column - 1; i >= 0; i--) {
const c = line[i];
if (c === " ") {
spaces++;
} else if (c === "\t") {
tabs++;
} else {
break;
}
}
return options.printWidth - (spaces + tabs * options.tabWidth) - " * ".length;
}
const TAGS_ORDER_LOWER = TAGS_ORDER.map((tagOrder) => tagOrder.toLowerCase());
/**
* This will adjust the casing of tag titles, resolve synonyms, fix
* incorrectly parsed tags, correct incorrectly assigned names and types, and
* trim spaces.
*
* @param parsed
*/
function normalizeTags(parsed: Block): void {
parsed.tags = parsed.tags.map(
({ tag, type, name, description, default: _default, ...rest }) => {
tag = tag || "";
type = type || "";
name = name || "";
description = description || "";
_default = _default?.trim();
/** When the space between tag and type is missing */
const tagSticksToType = tag.indexOf("{");
if (tagSticksToType !== -1 && tag[tag.length - 1] === "}") {
type = tag.slice(tagSticksToType + 1, -1) + " " + type;
tag = tag.slice(0, tagSticksToType);
}
tag = tag.trim();
const lower = tag.toLowerCase();
const tagIndex = TAGS_ORDER_LOWER.indexOf(lower);
if (tagIndex >= 0) {
tag = TAGS_ORDER[tagIndex];
} else if (lower in TAGS_SYNONYMS) {
// resolve synonyms
tag = TAGS_SYNONYMS[lower as keyof typeof TAGS_SYNONYMS];
}
type = type.trim();
name = name.trim();
if (name && TAGS_NAMELESS.includes(tag)) {
description = `${name} ${description}`;
name = "";
}
if (type && TAGS_TYPELESS.includes(tag)) {
description = `{${type}} ${description}`;
type = "";
}
description = description.trim();
return {
tag,
type,
name,
description,
default: _default,
...rest,
};
},
);
}
/**
* This will merge the comment description and all `@description` tags into one
* `@description` tag.
*
* @param parsed
*/
function convertCommentDescToDescTag(parsed: Block): void {
let description = parsed.description || "";
parsed.description = "";
parsed.tags = parsed.tags.filter(({ description: _description, tag }) => {
if (tag.toLowerCase() === DESCRIPTION) {
if (_description.trim()) {
description += "\n\n" + _description;
}
return false;
} else {
return true;
}
});
if (description) {
parsed.tags.unshift({
tag: DESCRIPTION,
description,
name: undefined as any,
type: undefined as any,
source: [],
optional: false,
problems: [],
});
}
}
/**
* This is for find params of function name in code as strings of array
*/
function getParamsOrders(ast: AST, tokenIndex: number): string[] | undefined {
let paramsOrder: string[] | undefined;
let params: Token[] | undefined;
try {
// next token
const nextTokenType = ast.tokens[tokenIndex + 1]?.type;
if (typeof nextTokenType !== "object") {
return undefined;
}
// Recognize function
if (nextTokenType.label === "function") {
let openedParenthesesCount = 1;
const tokensAfterComment = ast.tokens.slice(tokenIndex + 4);
const endIndex = tokensAfterComment.findIndex(({ type }) => {
if (typeof type === "string") {
return false;
} else if (type.label === "(") {
openedParenthesesCount++;
} else if (type.label === ")") {
openedParenthesesCount--;
}
return openedParenthesesCount === 0;
});
params = tokensAfterComment.slice(0, endIndex + 1);
}
// Recognize arrow function
if (nextTokenType.label === "const") {
let openedParenthesesCount = 1;
let tokensAfterComment = ast.tokens.slice(tokenIndex + 1);
const firstParenthesesIndex = tokensAfterComment.findIndex(
({ type }) => typeof type === "object" && type.label === "(",
);
tokensAfterComment = tokensAfterComment.slice(firstParenthesesIndex + 1);
const endIndex = tokensAfterComment.findIndex(({ type }) => {
if (typeof type === "string") {
return false;
} else if (type.label === "(") {
openedParenthesesCount++;
} else if (type.label === ")") {
openedParenthesesCount--;
}
return openedParenthesesCount === 0;
});
const arrowItem: Token | undefined = tokensAfterComment[endIndex + 1];
if (
typeof arrowItem?.type === "object" &&
arrowItem.type.label === "=>"
) {
params = tokensAfterComment.slice(0, endIndex + 1);
}
}
paramsOrder = params
?.filter(({ type }) => typeof type === "object" && type.label === "name")
.map(({ value }) => value);
} catch {
//
}
return paramsOrder;
}
/**
* If the given tag has a default value, then this will add a note to the
* description with that default value. This is done because TypeScript does
* not display the documented JSDoc default value (e.g. `@param [name="John"]`).
*
* If the description already contains such a note, it will be updated.
*/
function addDefaultValueToDescription(tag: Spec): Spec {
if (tag.optional && tag.default) {
let { description } = tag;
// remove old note
description = description.replace(/[ \t]*Default is `.*`\.?$/, "");
// add a `.` at the end of previous sentences
if (description && !/[.\n]$/.test(description)) {
description += ".";
}
description += ` Default is \`${tag.default}\``;
return {
...tag,
description: description.trim(),
};
} else {
return tag;
}
}
/**
* This will combine the `name`, `optional`, and `default` properties into name
* setting the other two to `false` and `undefined` respectively.
*/
function assignOptionalAndDefaultToName({
name,
optional,
default: default_,
...rest
}: Spec): Spec {
if (name && optional) {
// Figure out if tag type have default value
if (default_) {
name = `[${name}=${default_}]`;
} else {
name = `[${name}]`;
}
}
return {
...rest,
name: name,
optional: optional,
default: default_,
};
} | the_stack |
import { strict as assert } from "assert";
import { ZonedDateTime } from "@js-joda/core";
import got from "got";
import * as yamlParser from "js-yaml";
import {
enrichHeadersWithAuthTokenFile,
globalTestSuiteSetupOnce,
httpTimeoutSettings,
log,
logHTTPResponse,
rndstring,
timestampToNanoSinceEpoch,
CLUSTER_BASE_URL,
CORTEX_API_TLS_VERIFY,
TENANT_DEFAULT_API_TOKEN_FILEPATH,
TENANT_DEFAULT_CORTEX_API_BASE_URL,
TENANT_SYSTEM_API_TOKEN_FILEPATH,
TENANT_SYSTEM_CORTEX_API_BASE_URL,
TENANT_SYSTEM_LOKI_API_BASE_URL
} from "./testutils";
import {
waitForCortexMetricResult,
waitForPrometheusTarget
} from "./testutils/metrics";
import { waitForLokiQueryResult, LokiQueryResult } from "./testutils/logs";
async function listConfigNames(
authTokenFilepath: string | undefined,
urlSuffix: string
): Promise<string[]> {
const getResponse = await got.get(`${CLUSTER_BASE_URL}/api/v1/${urlSuffix}`, {
throwHttpErrors: false,
timeout: httpTimeoutSettings,
headers: enrichHeadersWithAuthTokenFile(authTokenFilepath, {}),
https: { rejectUnauthorized: CORTEX_API_TLS_VERIFY }
});
logHTTPResponse(getResponse);
assert(getResponse.statusCode == 200);
const body: Record<string, string>[] = yamlParser.load(getResponse.body);
return body.map(entry => entry["name"]);
}
async function storeConfig(
authTokenFilepath: string | undefined,
urlSuffix: string,
config: string
) {
const postResponse = await got.post(
`${CLUSTER_BASE_URL}/api/v1/${urlSuffix}`,
{
body: config,
throwHttpErrors: false,
timeout: httpTimeoutSettings,
headers: enrichHeadersWithAuthTokenFile(authTokenFilepath, {}),
https: { rejectUnauthorized: CORTEX_API_TLS_VERIFY }
}
);
logHTTPResponse(postResponse);
assert(postResponse.statusCode == 200);
// After a successful store, list the configs for logs
await listConfigNames(authTokenFilepath, urlSuffix);
}
async function deleteAllConfigs(
authTokenFilepath: string | undefined,
urlSuffix: string
) {
for (const name of await listConfigNames(authTokenFilepath, urlSuffix)) {
await deleteConfig(authTokenFilepath, urlSuffix, name);
}
}
async function deleteConfig(
authTokenFilepath: string | undefined,
urlSuffix: string,
name: string
) {
const deleteResponse = await got.delete(
`${CLUSTER_BASE_URL}/api/v1/${urlSuffix}/${name}`,
{
throwHttpErrors: false,
timeout: httpTimeoutSettings,
headers: enrichHeadersWithAuthTokenFile(authTokenFilepath, {}),
https: { rejectUnauthorized: CORTEX_API_TLS_VERIFY }
}
);
logHTTPResponse(deleteResponse);
assert(deleteResponse.statusCode == 200);
}
async function setupExporter(
authTokenFilepath: string | undefined,
exporterConfig: string,
credentialContent: string | null
) {
if (credentialContent != null) {
await storeConfig(authTokenFilepath, "credentials", credentialContent);
}
await storeConfig(authTokenFilepath, "exporters", exporterConfig);
}
async function cleanExporter(authTokenFilepath: string | undefined) {
log.info("Deleting exporters/credentials");
await deleteAllConfigs(authTokenFilepath, "exporters");
await deleteAllConfigs(authTokenFilepath, "credentials");
}
async function getExporterMetric(
cortexBaseUrl: string,
query: string
): Promise<string> {
log.info(`Waiting for exporter metric: ${query}`);
// Instant query - get current value
// https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries
const queryParams = {
query
};
const resultArray = await waitForCortexMetricResult(
cortexBaseUrl,
queryParams,
"query",
300 // normally <10s, but needs to be longer because stackdriver exporter can be slow to perform first scrape
);
const value = resultArray[0]["value"][1];
log.info(`Got exporter metric for query=${query}: ${value}`);
return value;
}
async function getExporterLog(
exporterNamespace: string,
exporterName: string,
logMessage: string
): Promise<LokiQueryResult> {
const query = `{k8s_namespace_name="${exporterNamespace}",k8s_container_name="exporter",k8s_pod_name=~"exporter-${exporterName}-.+"} |= "${logMessage}"`;
log.info(`Waiting for exporter log: ${query}`);
const ts = ZonedDateTime.now();
const queryParams = {
query,
direction: "BACKWARD",
limit: "10",
start: timestampToNanoSinceEpoch(ts.minusHours(1)),
end: timestampToNanoSinceEpoch(ts.plusHours(1))
};
const entries = await waitForLokiQueryResult(
TENANT_SYSTEM_LOKI_API_BASE_URL,
queryParams,
undefined, // expectedEntryCount
false, // logDetails
1, // expectedStreamCount
true, // buildhash
// Default is 30s, which is plenty for default-tenant.
// Meanwhile system-tenant seems to take as long as 62s for an entry to appear.
120 // maxWaitSeconds
);
log.info(`Got exporter log for query=${query}: ${entries.entries}`);
return entries;
}
async function testExporterMetric(
tenant: string,
cortexBaseUrl: string,
authTokenFilepath: string | undefined,
jobName: string,
exporterConfig: string,
credentialContent: string | null,
expectedMetricQuery: string
) {
await setupExporter(authTokenFilepath, exporterConfig, credentialContent);
await waitForPrometheusTarget(tenant, jobName);
await getExporterMetric(cortexBaseUrl, expectedMetricQuery);
await cleanExporter(authTokenFilepath);
}
async function testExporterLog(
authTokenFilepath: string | undefined,
exporterConfig: string,
credentialContent: string | null,
exporterNamespace: string,
exporterName: string,
logMessage: string
) {
await setupExporter(authTokenFilepath, exporterConfig, credentialContent);
await getExporterLog(exporterNamespace, exporterName, logMessage);
await cleanExporter(authTokenFilepath);
}
function getExporterName(type: string) {
// The exporter name is used in the K8s deployment name.
// As such, the exporter name can only contain letters, numbers, and '-'.
// rndstring() can return '_', so replace all '_'s with '0' just so that they fit.
// (use regex with /g to ensure ALL instances are replaced)
return `testexporters-${rndstring()
.slice(0, 5)
.toLowerCase()
.replace(/_/g, "0")}-${type}`;
}
// TODO(nick): rewrite these tests as integration UI tests
suite.skip("Metric exporter tests", function () {
suiteSetup(async function () {
log.info("suite setup");
globalTestSuiteSetupOnce();
log.info("Deleting any preexisting exporters/credentials");
await cleanExporter(TENANT_DEFAULT_API_TOKEN_FILEPATH);
await cleanExporter(TENANT_SYSTEM_API_TOKEN_FILEPATH);
});
suiteTeardown(async function () {
log.info("suite teardown");
});
test("Cloudwatch exporter", async function () {
const exporterName = getExporterName("cloudwatch");
const exporterConfig = `
name: ${exporterName}
type: cloudwatch
credential: ${exporterName}
# nested yaml payload defined by cloudwatch exporter:
config:
region: us-west-2
metrics:
- aws_namespace: Buildkite
aws_metric_name: ScheduledJobsCount
aws_dimensions: [Org, Queue]
aws_statistics: [Sum]
- aws_namespace: Buildkite
aws_metric_name: RunningJobsCount
aws_dimensions: [Org, Queue]
aws_statistics: [Sum]
- aws_namespace: Buildkite
aws_metric_name: WaitingJobsCount
aws_dimensions: [Org, Queue]
aws_statistics: [Sum]
`;
// Bogus credential value. Just check for an "auth failed" metric.
const exporterCred = `
name: ${exporterName}
type: aws-key
value:
AWS_ACCESS_KEY_ID: foo
AWS_SECRET_ACCESS_KEY: bar
`;
const jobName = `exporter-${exporterName}`;
const metricQuery = `cloudwatch_exporter_scrape_error{job="${jobName}"}`;
await testExporterMetric(
"default",
TENANT_DEFAULT_CORTEX_API_BASE_URL,
TENANT_DEFAULT_API_TOKEN_FILEPATH,
jobName,
exporterConfig,
exporterCred,
metricQuery
);
await testExporterMetric(
"system",
TENANT_SYSTEM_CORTEX_API_BASE_URL,
TENANT_SYSTEM_API_TOKEN_FILEPATH,
jobName,
exporterConfig,
exporterCred,
metricQuery
);
});
test("Stackdriver exporter", async function () {
const exporterName = getExporterName("stackdriver");
const exporterConfig = `
name: ${exporterName}
type: stackdriver
credential: ${exporterName}
config:
monitoring.metrics-type-prefixes:
- compute.googleapis.com/instance/cpu
- compute.googleapis.com/instance/disk
google.project-id:
- phony-project-12345
monitoring.metrics-interval: '5m'
monitoring.metrics-offset: '0s'
`;
// Bogus credential value. Just check for an "auth failed" metric.
const exporterCred = `
name: ${exporterName}
type: gcp-service-account
value: |-
{
"type": "service_account",
"project_id": "phony-project-12345",
"private_key_id": "phony_id",
"private_key": "phony_key"
}
`;
const jobName = `exporter-${exporterName}`;
// this metric can take >30s to appear:
const metricQuery = `stackdriver_monitoring_scrape_errors_total{job="${jobName}"}`;
await testExporterMetric(
"default",
TENANT_DEFAULT_CORTEX_API_BASE_URL,
TENANT_DEFAULT_API_TOKEN_FILEPATH,
jobName,
exporterConfig,
exporterCred,
metricQuery
);
await testExporterMetric(
"system",
TENANT_SYSTEM_CORTEX_API_BASE_URL,
TENANT_SYSTEM_API_TOKEN_FILEPATH,
jobName,
exporterConfig,
exporterCred,
metricQuery
);
});
test("Blackbox exporter", async function () {
const exporterName = getExporterName("blackbox");
const exporterConfig = `
name: ${exporterName}
type: blackbox
config:
probes:
- target: prometheus.io
module: http_2xx
- target: example.com
module: http_2xx
- target: 1.1.1.1
module: dns_opstrace_mx
- target: 8.8.8.8
module: dns_opstrace_mx
modules:
http_2xx:
prober: http
timeout: 5s
http:
preferred_ip_protocol: "ip4"
dns_opstrace_mx:
prober: dns
timeout: 5s
dns:
preferred_ip_protocol: "ip4"
transport_protocol: tcp
dns_over_tls: true
query_name: opstrace.com
query_type: MX
`;
const jobName = `exporter-${exporterName}`;
// The probe metrics should be labeled with module and target params:
const metricQuery = `probe_success{job="${jobName}",module="http_2xx",target="example.com"}`;
await testExporterMetric(
"default",
TENANT_DEFAULT_CORTEX_API_BASE_URL,
TENANT_DEFAULT_API_TOKEN_FILEPATH,
jobName,
exporterConfig,
null,
metricQuery
);
await testExporterMetric(
"system",
TENANT_SYSTEM_CORTEX_API_BASE_URL,
TENANT_SYSTEM_API_TOKEN_FILEPATH,
jobName,
exporterConfig,
null,
metricQuery
);
});
test("Azure exporter", async function () {
const exporterName = getExporterName("azure");
const exporterConfig = `
name: ${exporterName}
type: azure
credential: ${exporterName}
config:
resource_groups:
- resource_group: mygroup
resource_types:
- "Microsoft.Storage/storageAccounts"
metrics:
- name: Availability
- name: Egress
- name: Ingress
- name: SuccessE2ELatency
- name: SuccessServerLatency
- name: Transactions
- name: UsedCapacity
`;
// Bogus credential value. Just check for an "auth failed" log message.
const exporterCred = `
name: ${exporterName}
type: azure-service-principal
value:
AZURE_SUBSCRIPTION_ID: foo
AZURE_TENANT_ID: testtenantshouldfail
AZURE_CLIENT_ID: bar
AZURE_CLIENT_SECRET: baz
`;
const expectedLogMessage = "Tenant 'testtenantshouldfail' not found";
await testExporterLog(
TENANT_DEFAULT_API_TOKEN_FILEPATH,
exporterConfig,
exporterCred,
"default-tenant",
exporterName,
expectedLogMessage
);
await testExporterLog(
TENANT_SYSTEM_API_TOKEN_FILEPATH,
exporterConfig,
exporterCred,
"system-tenant",
exporterName,
expectedLogMessage
);
});
}); | the_stack |
import {Context, ErrorHandlingResult, SqsQueue, SqsTimeoutError} from "../../../src/sqs";
import { v4 as uuidv4 } from "uuid";
import envVars from "../../../src/config/env";
import DoneCallback = jest.DoneCallback;
import waitUntil from "../../utils/waitUntil";
import statsd from "../../../src/config/statsd";
import {sqsQueueMetrics} from "../../../src/config/metric-names";
import anything = jasmine.anything;
import {getLogger} from "../../../src/config/logger";
const TEST_QUEUE_URL = envVars.SQS_TEST_QUEUE_URL;
const TEST_QUEUE_REGION = envVars.SQS_TEST_QUEUE_REGION;
const TEST_QUEUE_NAME = "test";
type TestMessage = { msg: string }
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
//We have to disable this rule here hence there is no way to have a proper test for sqs queue with await here
/* eslint-disable jest/no-done-callback */
const testLogger = getLogger("sqstest");
describe("SqsQueue tests", () => {
const mockRequestHandler = jest.fn();
const mockErrorHandler = jest.fn();
const testMaxQueueAttempts = 3;
const generatePayload = (): TestMessage => ({ msg: uuidv4() });
const createSqsQueue = (timeout: number, maxAttempts: number = testMaxQueueAttempts) => {
return new SqsQueue({
queueName: TEST_QUEUE_NAME,
queueUrl: TEST_QUEUE_URL,
queueRegion: TEST_QUEUE_REGION,
longPollingIntervalSec: 0,
timeoutSec: timeout,
maxAttempts: maxAttempts
},
mockRequestHandler,
mockErrorHandler);
};
let queue: SqsQueue<TestMessage>;
describe("Normal execution tests", () => {
let statsdIncrementSpy;
beforeEach(() => {
testLogger.info("Running test: [" + expect.getState().currentTestName + "]")
statsdIncrementSpy = jest.spyOn(statsd, "increment");
queue = createSqsQueue(10);
queue.sqs.purgeQueue();
queue.start();
mockErrorHandler.mockImplementation(() : ErrorHandlingResult => {
return {retryable: false, isFailure: true};
})
});
afterEach(async () => {
statsdIncrementSpy.mockRestore();
queue.stop();
queue.sqs.purgeQueue();
await queue.waitUntilListenerStopped();
testLogger.info("Finished test cleanup for [" + expect.getState().currentTestName + "]")
});
it("Message gets received", (done: DoneCallback) => {
const testPayload = generatePayload();
mockRequestHandler.mockImplementation((context: Context<TestMessage>) => {
expect(context.payload).toStrictEqual(testPayload);
done();
});
queue.sendMessage(testPayload);
});
it("Queue is restartable", async (done: DoneCallback) => {
const testPayload = generatePayload();
mockRequestHandler.mockImplementation((context: Context<TestMessage>) => {
expect(context.payload).toStrictEqual(testPayload);
done();
});
queue.stop();
//delaying to make sure all asynchronous invocations inside the queue will be finished and it will stop
await queue.waitUntilListenerStopped();
queue.start();
queue.sendMessage(testPayload);
});
it("Message received with delay", (done: DoneCallback) => {
const testPayload = generatePayload();
const receivedTime = {time: Date.now()};
mockRequestHandler.mockImplementation((context: Context<TestMessage>) => {
context.log.info("hi");
const currentTime = Date.now();
expect(currentTime - receivedTime.time).toBeGreaterThanOrEqual(1000);
done();
});
queue.sendMessage(testPayload, 1);
});
it("Message gets executed exactly once", (done: DoneCallback) => {
const testPayload = generatePayload();
const testData: { messageId: undefined | string } = {messageId: undefined};
mockRequestHandler.mockImplementation((context: Context<TestMessage>) => {
try {
expect(context.payload).toStrictEqual(testPayload);
if (!testData.messageId) {
testData.messageId = context.message.MessageId;
} else if (testData.messageId === context.message.MessageId) {
done.fail("Message was received more than once");
} else {
done.fail("Different message on the tests queue");
}
} catch (err) {
done.fail(err);
}
});
queue.sendMessage(testPayload);
//code before the pause
setTimeout(function () {
if (testData.messageId) {
done();
} else {
done.fail("No message was received");
}
}, 3000);
});
it("Messages are not processed in parallel", async (done: DoneCallback) => {
const testPayload = generatePayload();
const receivedTime = {time: Date.now(), counter: 0};
mockRequestHandler.mockImplementation(async (context: Context<TestMessage>) => {
try {
if (receivedTime.counter == 0) {
receivedTime.counter++;
context.log.info("Delaying the message");
await delay(1000);
context.log.info("Message processed after delay");
return;
}
const currentTime = Date.now();
expect(currentTime - receivedTime.time).toBeGreaterThanOrEqual(1000);
done();
} catch (err) {
done(err);
}
});
await queue.sendMessage(testPayload);
await queue.sendMessage(testPayload);
});
it("Retries with the correct delay", async (done: DoneCallback) => {
const testErrorMessage = "Something bad happened";
const testPayload = generatePayload();
const receivedTime = {time: Date.now(), receivesCounter: 0, errorHandlingCounter: 0};
mockRequestHandler.mockImplementation(async (context: Context<TestMessage>) => {
if (receivedTime.receivesCounter == 0) {
receivedTime.receivesCounter++;
context.log.info("Throwing error on first processing");
throw new Error("Something bad happened");
}
expect(receivedTime.receivesCounter).toBe(1);
expect(receivedTime.errorHandlingCounter).toBe(1);
const currentTime = Date.now();
expect(currentTime - receivedTime.time).toBeGreaterThanOrEqual(1000);
done();
return;
});
mockErrorHandler.mockImplementation((error: Error, context: Context<TestMessage>) : ErrorHandlingResult => {
expect(context.payload.msg).toBe(testPayload.msg)
expect(error.message).toBe(testErrorMessage)
receivedTime.errorHandlingCounter++;
return {retryable: true, retryDelaySec: 1, isFailure: true}
})
await queue.sendMessage(testPayload);
});
it("Message deleted from the queue when unretryable", async () => {
const testPayload = generatePayload();
const queueDeletionSpy = jest.spyOn(queue.sqs, "deleteMessage");
const expected : {ReceiptHandle?: string} = {ReceiptHandle: ""};
mockRequestHandler.mockImplementation(async (context: Context<TestMessage>) => {
expected.ReceiptHandle = context.message.ReceiptHandle;
throw new Error("Something bad happened");
});
mockErrorHandler.mockImplementation(() : ErrorHandlingResult => {
return {retryable: false, isFailure: true};
})
await queue.sendMessage(testPayload);
await waitUntil(async () => {
expect(queueDeletionSpy).toBeCalledTimes(1)
})
expect(statsdIncrementSpy).toBeCalledWith(sqsQueueMetrics.failed, anything());
});
it("Message deleted from the queue when error is not a failure and failure metric not sent", async () => {
const testPayload = generatePayload();
const queueDeletionSpy = jest.spyOn(queue.sqs, "deleteMessage");
const expected : {ReceiptHandle?: string} = {ReceiptHandle: ""};
mockRequestHandler.mockImplementation(async (context: Context<TestMessage>) => {
expected.ReceiptHandle = context.message.ReceiptHandle;
throw new Error("Something bad happened");
});
mockErrorHandler.mockImplementation(() : ErrorHandlingResult => {
return {isFailure: false};
})
await queue.sendMessage(testPayload);
await waitUntil(async () => {
expect(queueDeletionSpy).toBeCalledTimes(1)
})
expect(statsdIncrementSpy).not.toBeCalledWith(sqsQueueMetrics.failed, anything());
});
});
describe("Timeouts tests", () => {
beforeEach(() => {
queue = createSqsQueue(1);
queue.sqs.purgeQueue();
queue.start();
});
afterEach(async () => {
queue.stop();
queue.sqs.purgeQueue();
await queue.waitUntilListenerStopped();
});
it("Timeout works", async (done: DoneCallback) => {
const testPayload = generatePayload();
const receivedTime = {time: Date.now(), counter: 0};
mockRequestHandler.mockImplementation(async (context: Context<TestMessage>) => {
context.log.info("Delaying the message for 2 secs");
await delay(2000);
return;
});
mockErrorHandler.mockImplementation((error: Error, context: Context<TestMessage>) => {
try {
expect(context.payload.msg).toBe(testPayload.msg);
expect(error).toBeInstanceOf(SqsTimeoutError);
const currentTime = Date.now();
expect(currentTime - receivedTime.time).toBeGreaterThanOrEqual(1000);
} catch (err) {
done.fail(err);
}
done();
return {retryable: false};
})
await queue.sendMessage(testPayload);
});
it("Receive Count and Max Attempts are populated correctly", async (done: DoneCallback) => {
const testPayload = generatePayload();
const receiveCounter = {receivesCounter: 0};
mockRequestHandler.mockImplementation(async (context: Context<TestMessage>) => {
/* eslint-disable jest/no-conditional-expect */
try {
if (receiveCounter.receivesCounter == 0) {
expect(context.receiveCount).toBe(1)
expect(context.lastAttempt).toBe(false)
} else if (receiveCounter.receivesCounter == 1) {
expect(context.receiveCount).toBe(2)
expect(context.lastAttempt).toBe(false)
} else if (receiveCounter.receivesCounter == 2) {
expect(context.receiveCount).toBe(3)
expect(context.lastAttempt).toBe(true)
done();
return;
}
} catch(err) {
done.fail(err)
}
receiveCounter.receivesCounter++;
throw new Error("Something bad happened");
});
mockErrorHandler.mockImplementation((_error: Error, _context: Context<TestMessage>): ErrorHandlingResult => {
return {retryable: receiveCounter.receivesCounter < 3, retryDelaySec: 0, isFailure: true}
})
await queue.sendMessage(testPayload);
});
});
}); | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type MakeOfferModalTestsQueryVariables = {};
export type MakeOfferModalTestsQueryResponse = {
readonly artwork: {
readonly " $fragmentRefs": FragmentRefs<"MakeOfferModal_artwork">;
} | null;
};
export type MakeOfferModalTestsQuery = {
readonly response: MakeOfferModalTestsQueryResponse;
readonly variables: MakeOfferModalTestsQueryVariables;
};
/*
query MakeOfferModalTestsQuery {
artwork(id: "pumpkins") {
...MakeOfferModal_artwork
id
}
}
fragment CollapsibleArtworkDetails_artwork on Artwork {
image {
url
width
height
}
internalID
title
date
saleMessage
attributionClass {
name
id
}
category
manufacturer
publisher
medium
conditionDescription {
details
}
certificateOfAuthenticity {
details
}
framed {
details
}
dimensions {
in
cm
}
signatureInfo {
details
}
artistNames
}
fragment InquiryMakeOfferButton_artwork on Artwork {
internalID
}
fragment MakeOfferModal_artwork on Artwork {
...CollapsibleArtworkDetails_artwork
...InquiryMakeOfferButton_artwork
internalID
isEdition
editionSets {
internalID
editionOf
isOfferableFromInquiry
listPrice {
__typename
... on Money {
display
}
... on PriceRange {
display
}
}
dimensions {
cm
in
}
id
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"kind": "Literal",
"name": "id",
"value": "pumpkins"
}
],
v1 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "internalID",
"storageKey": null
},
v2 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v3 = [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "details",
"storageKey": null
}
],
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "in",
"storageKey": null
},
v5 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "cm",
"storageKey": null
},
v6 = [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "display",
"storageKey": null
}
],
v7 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "String"
},
v8 = {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "ID"
},
v9 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "ArtworkInfoRow"
},
v10 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "dimensions"
},
v11 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Boolean"
},
v12 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Int"
};
return {
"fragment": {
"argumentDefinitions": [],
"kind": "Fragment",
"metadata": null,
"name": "MakeOfferModalTestsQuery",
"selections": [
{
"alias": null,
"args": (v0/*: any*/),
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "artwork",
"plural": false,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "MakeOfferModal_artwork"
}
],
"storageKey": "artwork(id:\"pumpkins\")"
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": [],
"kind": "Operation",
"name": "MakeOfferModalTestsQuery",
"selections": [
{
"alias": null,
"args": (v0/*: any*/),
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "artwork",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "image",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "url",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "width",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "height",
"storageKey": null
}
],
"storageKey": null
},
(v1/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "title",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "date",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "saleMessage",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "AttributionClass",
"kind": "LinkedField",
"name": "attributionClass",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
(v2/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "category",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "manufacturer",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "publisher",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "medium",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"kind": "LinkedField",
"name": "conditionDescription",
"plural": false,
"selections": (v3/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"kind": "LinkedField",
"name": "certificateOfAuthenticity",
"plural": false,
"selections": (v3/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"kind": "LinkedField",
"name": "framed",
"plural": false,
"selections": (v3/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "dimensions",
"kind": "LinkedField",
"name": "dimensions",
"plural": false,
"selections": [
(v4/*: any*/),
(v5/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"kind": "LinkedField",
"name": "signatureInfo",
"plural": false,
"selections": (v3/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "artistNames",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isEdition",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "EditionSet",
"kind": "LinkedField",
"name": "editionSets",
"plural": true,
"selections": [
(v1/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "editionOf",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isOfferableFromInquiry",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "listPrice",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
{
"kind": "InlineFragment",
"selections": (v6/*: any*/),
"type": "Money",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": (v6/*: any*/),
"type": "PriceRange",
"abstractKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "dimensions",
"kind": "LinkedField",
"name": "dimensions",
"plural": false,
"selections": [
(v5/*: any*/),
(v4/*: any*/)
],
"storageKey": null
},
(v2/*: any*/)
],
"storageKey": null
},
(v2/*: any*/)
],
"storageKey": "artwork(id:\"pumpkins\")"
}
]
},
"params": {
"id": "b5eba9e53aa06c9d23d44db5a24b18ce",
"metadata": {
"relayTestingSelectionTypeInfo": {
"artwork": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Artwork"
},
"artwork.artistNames": (v7/*: any*/),
"artwork.attributionClass": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "AttributionClass"
},
"artwork.attributionClass.id": (v8/*: any*/),
"artwork.attributionClass.name": (v7/*: any*/),
"artwork.category": (v7/*: any*/),
"artwork.certificateOfAuthenticity": (v9/*: any*/),
"artwork.certificateOfAuthenticity.details": (v7/*: any*/),
"artwork.conditionDescription": (v9/*: any*/),
"artwork.conditionDescription.details": (v7/*: any*/),
"artwork.date": (v7/*: any*/),
"artwork.dimensions": (v10/*: any*/),
"artwork.dimensions.cm": (v7/*: any*/),
"artwork.dimensions.in": (v7/*: any*/),
"artwork.editionSets": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "EditionSet"
},
"artwork.editionSets.dimensions": (v10/*: any*/),
"artwork.editionSets.dimensions.cm": (v7/*: any*/),
"artwork.editionSets.dimensions.in": (v7/*: any*/),
"artwork.editionSets.editionOf": (v7/*: any*/),
"artwork.editionSets.id": (v8/*: any*/),
"artwork.editionSets.internalID": (v8/*: any*/),
"artwork.editionSets.isOfferableFromInquiry": (v11/*: any*/),
"artwork.editionSets.listPrice": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "ListPrice"
},
"artwork.editionSets.listPrice.__typename": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "String"
},
"artwork.editionSets.listPrice.display": (v7/*: any*/),
"artwork.framed": (v9/*: any*/),
"artwork.framed.details": (v7/*: any*/),
"artwork.id": (v8/*: any*/),
"artwork.image": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Image"
},
"artwork.image.height": (v12/*: any*/),
"artwork.image.url": (v7/*: any*/),
"artwork.image.width": (v12/*: any*/),
"artwork.internalID": (v8/*: any*/),
"artwork.isEdition": (v11/*: any*/),
"artwork.manufacturer": (v7/*: any*/),
"artwork.medium": (v7/*: any*/),
"artwork.publisher": (v7/*: any*/),
"artwork.saleMessage": (v7/*: any*/),
"artwork.signatureInfo": (v9/*: any*/),
"artwork.signatureInfo.details": (v7/*: any*/),
"artwork.title": (v7/*: any*/)
}
},
"name": "MakeOfferModalTestsQuery",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = 'efadc2d19d925e83e12e60ad8a4333c9';
export default node; | the_stack |
import _ = require('underscore');
import Q = require('q');
import Validation = require('./Validation');
import Validators = require('./BasicValidators');
//var Validation = require("business-rules-engine");
//var Validators = require('business-rules-engine/commonjs/BasicValidators');
//var Validation = require('../validation/Validation.js');
//var Validators = require('../validation/BasicValidators.js');
/**
* Support for declarative validation rules definition.
*
* + declarative [JSON schema](http://json-schema.org/) with validation keywords [JSON Schema Validation](http://json-schema.org/latest/json-schema-validation.html)
* + declarative raw JSON data annotated with meta data - using keywords from [JQuery validation plugin](http://jqueryvalidation.org/)
*/
module FormSchema {
/**
* It represents factory that creates an concrete validation rule.
*/
export interface IValidationRuleFactory{
/**
* Create an validation rule
* @param name - the name of rule
*/
CreateRule(name:string):Validation.IAbstractValidationRule<any>;
/**
* Create an abstract validator.
*/
CreateAbstractValidator():Validation.IAbstractValidator<any>;
}
/**
* It represents the JSON schema factory for creating validation rules based on JSON form schema.
* It uses constraints keywords from JSON Schema Validation specification.
*/
export class JsonSchemaRuleFactory implements IValidationRuleFactory{
/**
* Default constructor
* @param jsonSchema JSON schema for business rules.
*/
constructor(private jsonSchema:any){
}
/**
* Return abstract validation rule by traversing JSON schema.
* @returns {IAbstractValidator<any>} return validation rule
*/
public CreateAbstractValidator():Validation.IAbstractValidator<any>{
return this.ParseAbstractRule(this.jsonSchema);
}
/**
* Return concrete validation rule structured according to JSON schema.
* @param name validation rule name
* @returns {IAbstractValidationRule<any>} return validation rule
*/
public CreateRule(name:string):Validation.IAbstractValidationRule<any>{
return this.ParseAbstractRule(this.jsonSchema).CreateRule(name);
}
/**
* Returns an concrete validation rules structured according to JSON schema.
*/
private ParseAbstractRule(formSchema:any):Validation.IAbstractValidator<any> {
var rule = new Validation.AbstractValidator<any>();
for (var key in formSchema) {
var item = formSchema[key];
var type = item[Util.TYPE_KEY];
if (type === "object") {
rule.ValidatorFor(key, this.ParseAbstractRule(item[Util.PROPERTIES_KEY]));
}
else if (type === "array") {
_.each(this.ParseValidationAttribute(item),function(validator){ rule.RuleFor(key,validator)});
rule.ValidatorFor(key, this.ParseAbstractRule(item[Util.ARRAY_KEY][Util.PROPERTIES_KEY]), true);
}
else {
_.each(this.ParseValidationAttribute(item),function(validator){ rule.RuleFor(key,validator)});
}
}
return rule;
}
/**
* Return list of property validators that corresponds json items for JSON form validation tags.
* See keywords specifications -> http://json-schema.org/latest/json-schema-validation.html
*/
private ParseValidationAttribute(item:any):Array<any> {
var validators = new Array<any>();
if (item === undefined) return validators;
//5. Validation keywords sorted by instance types
//http://json-schema.org/latest/json-schema-validation.html
//5.1. - Validation keywords for numeric instances (number and integer)
// multipleOf validation
validation = item["multipleOf"];
if (validation !== undefined) {
validators.push(new Validators.MultipleOfValidator(validation));
}
// maximum validation
validation = item["maximum"];
if (validation !== undefined) {
validators.push(new Validators.MaxValidator(validation,item["exclusiveMaximum"]));
}
// minimum validation
validation = item["minimum"];
if (validation !== undefined) {
validators.push(new Validators.MinValidator(validation,item["exclusiveMinimum"]));
}
//5.2. - Validation keywords for strings
// maxLength validation
validation = item["maxLength"];
if (validation !== undefined) {
validators.push(new Validators.MaxLengthValidator(validation));
}
// minLength validation
validation = item["minLength"];
if (validation !== undefined) {
validators.push(new Validators.MinLengthValidator(validation));
}
// pattern validation
validation = item["pattern"];
if (validation !== undefined) {
validators.push(new Validators.PatternValidator(validation));
}
//5.3. Validation keywords for arrays
//TODO: additionalItems and items
// min items validation
validation= item["minItems"];
if (validation !== undefined) {
validators.push( new Validators.MinItemsValidator(validation))
}
// max items validation
validation = item["maxItems"];
if (validation !== undefined) {
validators.push( new Validators.MaxItemsValidator(validation))
}
// uniqueItems validation
validation = item["uniqueItems"];
if (validation !== undefined) {
validators.push( new Validators.UniqItemsValidator())
}
//5.4. Validation keywords for objects
//TODO: maxProperties, minProperties, additionalProperties, properties and patternProperties, dependencies
// required validation
var validation = item["required"];
if (validation !== undefined && validation) {
validators.push(new Validators.RequiredValidator());
}
//5.5. Validation keywords for any instance type
// enum validation
validation = item["enum"];
if (validation !== undefined) {
validators.push(new Validators.EnumValidator(validation))
}
// type validation
var validation = item["type"];
if (validation !== undefined) {
validators.push(new Validators.TypeValidator(validation));
}
//7.3.2 email
validation = item["email"];
if (validation !== undefined) {
validators.push(new Validators.EmailValidator())
}
//7.3.6 url
validation = item["uri"];
if (validation !== undefined) {
validators.push(new Validators.UrlValidator())
}
//TODO: allOf,anyOf,oneOf,not,definitions
return validators;
}
}
/**
* It represents the JSON schema factory for creating validation rules based on raw JSON data annotated by validation rules.
* It uses constraints keywords from JQuery validation plugin.
*/
export class JQueryValidationRuleFactory implements IValidationRuleFactory {
static RULES_KEY = "rules";
static DEFAULT_KEY = "default";
/**
* Default constructor
* @param metaData - raw JSON data annotated by validation rules
*/
constructor(private metaData:any){
}
/**
* Return abstract validation rule by traversing raw JSON data annotated by validation rules.
* @returns {IAbstractValidator<any>} return validation rule
*/
public CreateAbstractValidator():Validation.IAbstractValidator<any>{
return this.ParseAbstractRule(this.metaData);
}
/**
* Return an concrete validation rule by traversing raw JSON data annotated by validation rules.
* @param name validation rule name
* @returns {IValidationRule<any>} return validation rule
*/
public CreateRule(name:string):Validation.IAbstractValidationRule<any>{
return this.ParseAbstractRule(this.metaData).CreateRule(name);
}
/**
* Returns an concrete validation rule structured according to JSON schema.
*/
private ParseAbstractRule(metaData:any):Validation.IAbstractValidator<any> {
var rule = new Validation.AbstractValidator<any>();
for (var key in metaData) {
var item = metaData[key];
var rules = item[JQueryValidationRuleFactory.RULES_KEY];
if ( _.isArray(item)) {
if (item[1] !== undefined) {
_.each(this.ParseValidationAttribute(item[1]), function (validator) {
rule.RuleFor(key, validator)
});
}
rule.ValidatorFor(key, this.ParseAbstractRule(item[0]), true);
}
else if (rules !== undefined) {
_.each(this.ParseValidationAttribute(rules),function(validator){ rule.RuleFor(key,validator)})
}
else if (_.isObject(item)) {
rule.ValidatorFor(key, this.ParseAbstractRule(item));
}
else {
//ignore
continue;
}
}
return rule;
}
/**
* Return list of property validators that corresponds json items for JQuery validation pluging tags.
* See specification - http://jqueryvalidation.org/documentation/
*/
private ParseValidationAttribute(item:any):Array<any> {
var validators = new Array<any>();
if (item === undefined) return validators;
var validation = item["required"];
if (validation !== undefined && validation) {
validators.push(new Validators.RequiredValidator());
}
var validation = item["remote"];
if (validation !== undefined && validation) {
validators.push(new Validators.RemoteValidator(validation));
}
// maxLength validation
validation = item["maxlength"];
if (validation !== undefined) {
validators.push(new Validators.MaxLengthValidator(validation))
}
// minLength validation
validation = item["minlength"];
if (validation !== undefined) {
validators.push(new Validators.MinLengthValidator(validation))
}
// rangelength validation
validation = item["rangelength"];
if (validation !== undefined) {
validators.push(new Validators.RangeLengthValidator(validation))
}
// maximum validation
validation = item["max"];
if (validation !== undefined) {
validators.push(new Validators.MaxValidator(validation));
}
// minimum validation
validation = item["min"];
if (validation !== undefined) {
validators.push(new Validators.MinValidator(validation));
}
// range validation
validation = item["range"];
if (validation !== undefined) {
validators.push(new Validators.RangeValidator(validation));
}
validation = item["email"];
if (validation !== undefined) {
validators.push(new Validators.EmailValidator())
}
validation = item["url"];
if (validation !== undefined) {
validators.push(new Validators.UrlValidator())
}
validation = item["date"];
if (validation !== undefined) {
validators.push(new Validators.DateValidator())
}
validation = item["dateISO"];
if (validation !== undefined) {
validators.push(new Validators.DateISOValidator())
}
validation = item["number"];
if (validation !== undefined) {
validators.push(new Validators.NumberValidator())
}
validation = item["digits"];
if (validation !== undefined) {
validators.push(new Validators.DigitValidator())
}
validation = item["creditcard"];
if (validation !== undefined) {
validators.push(new Validators.CreditCardValidator())
}
validation = item["equalTo"];
if (validation !== undefined) {
validators.push(new Validators.EqualToValidator(validation))
}
// min items validation
validation= item["minItems"];
if (validation !== undefined) {
validators.push( new Validators.MinItemsValidator(validation))
}
// max items validation
validation = item["maxItems"];
if (validation !== undefined) {
validators.push( new Validators.MaxItemsValidator(validation))
}
// uniqueItems validation
validation = item["uniqueItems"];
if (validation !== undefined) {
validators.push( new Validators.UniqItemsValidator())
}
// enum validation
validation = item["enum"];
if (validation !== undefined) {
validators.push(new Validators.EnumValidator(validation))
}
// // pattern validation
// validation = item["pattern"];
// if (validation !== undefined) {
// validators.push(new Validators.PatternValidator(validation))
// }
return validators;
}
}
/**
* It represents utility for JSON schema form manipulation.
*/
export class Util {
static TYPE_KEY = "type";
static PROPERTIES_KEY = "properties";
static DEFAULT_KEY = "default";
static ARRAY_KEY = "items";
/**
* Returns the initial JSON data structured according to JSON schema.
* The data are initilizied with default values.
*/
static InitValues(formSchema:any, data?:any) {
var data = data || {};
for (var key in formSchema) {
var item = formSchema[key];
var type = item[Util.TYPE_KEY];
if (type === "object") {
data[key] = {};
Util.InitValues(item[Util.PROPERTIES_KEY], data[key]);
}
else if (type === "array") {
data[key] = [];
}
else {
var defaultValue = item[Util.DEFAULT_KEY];
if (defaultValue === undefined) continue;
// Type casting
if (type === 'boolean') {
if (defaultValue === '0') {
defaultValue = false;
} else {
defaultValue = !!defaultValue;
}
}
if ((type === 'number') ||
(type === 'integer')) {
if (_.isString(defaultValue)) {
if (!defaultValue.length) {
defaultValue = null;
} else if (!isNaN(Number(defaultValue))) {
defaultValue = Number(defaultValue);
}
}
}
if ((type === 'string') &&
(defaultValue === '')) {
defaultValue = null;
}
//TODO: default value
data[key] = defaultValue;
}
}
return data;
}
}
}
export = FormSchema | the_stack |
import * as React from 'react';
import { useEffect, useState } from 'react';
import styles from './PhotoSync.module.scss';
import * as strings from 'PhotoSyncWebPartStrings';
import { HttpClient } from '@microsoft/sp-http';
import { DisplayMode } from '@microsoft/sp-core-library';
import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle";
import { ProgressIndicator } from 'office-ui-fabric-react/lib/ProgressIndicator';
import { Pivot, PivotItem } from 'office-ui-fabric-react/lib/Pivot';
import { AppContext, AppContextProps } from '../common/AppContext';
import { IHelper } from '../common/helper';
import ConfigPlaceholder from '../common/ConfigPlaceholder';
import { IPropertyFieldGroupOrPerson } from '@pnp/spfx-property-controls/lib/propertyFields/peoplePicker';
import MessageContainer from '../common/MessageContainer';
import { MessageScope, IUserInfo, IAzFuncValues } from '../common/IModel';
import { WebPartContext } from '@microsoft/sp-webpart-base';
import UserSelectionSync from './UserSelectionSync';
import BulkPhotoSync from './BulkPhotoSync';
import SyncJobs from './SyncJobs';
const map: any = require('lodash/map');
export interface IPhotoSyncProps {
context: WebPartContext;
httpClient: HttpClient;
siteUrl: string;
domainName: string;
helper: IHelper;
displayMode: DisplayMode;
useFullWidth: boolean;
appTitle: string;
updateProperty: (value: string) => void;
AzFuncUrl: string;
UseCert: boolean;
dateFormat: string;
allowedUsers: IPropertyFieldGroupOrPerson[];
openPropertyPane: () => void;
enableBulkUpdate: boolean;
tempLib: string;
deleteThumbnails: boolean;
}
const PhotoSync: React.FunctionComponent<IPhotoSyncProps> = (props) => {
const [loading, setLoading] = useState<boolean>(true);
const [accessDenied, setAccessDenied] = useState<boolean>(false);
const [listExists, setListExists] = useState<boolean>(false);
const [selectedMenu, setSelectedMenu] = useState<string>('0');
const [pivotItems, setPivotItems] = useState<any[]>([]);
const [disablePivot, setdisablePivot] = useState<boolean>(false);
const headerButtonProps = { 'disabled': disablePivot };
const parentCtxValues: AppContextProps = {
context: props.context,
siteurl: props.siteUrl,
domainName: props.domainName,
helper: props.helper,
displayMode: props.displayMode,
openPropertyPane: props.openPropertyPane,
tempLib: props.tempLib,
deleteThumbnails: props.deleteThumbnails
};
const showConfig = !props.tempLib; //!props.templateLib || !props.AzFuncUrl || !props.tempLib ? true : false;
const _useFullWidth = () => {
const jQuery: any = require('jquery');
if (props.useFullWidth) {
jQuery("#workbenchPageContent").prop("style", "max-width: none");
jQuery(".SPCanvas-canvas").prop("style", "max-width: none");
jQuery(".CanvasZone").prop("style", "max-width: none");
} else {
jQuery("#workbenchPageContent").prop("style", "max-width: 924px");
}
};
const _checkAndCreateLists = async () => {
setLoading(false);
let listCheck: boolean = await props.helper.checkAndCreateLists();
if (listCheck) setListExists(true);
};
const _checkForAccess = async () => {
setLoading(true);
let currentUserInfo: IUserInfo = await props.helper.getCurrentUserCustomInfo();
if (currentUserInfo.IsSiteAdmin) {
_checkAndCreateLists();
} else {
let allowedGroups: string[] = map(props.allowedUsers, 'login');
let accessAllowed: boolean = props.helper.checkCurrentUserGroup(allowedGroups, currentUserInfo.Groups);
console.log("Access allowed: ", accessAllowed);
if (accessAllowed) {
_checkAndCreateLists();
} else {
setLoading(false);
setAccessDenied(true);
}
}
};
const _updatePivotMenus = () => {
let pvitems: any[] = [];
if (props.enableBulkUpdate) {
pvitems = [
<PivotItem headerText={strings.TabMenu2} itemKey="1" itemIcon="BulkUpload" headerButtonProps={headerButtonProps}></PivotItem>,
];
}
setPivotItems(pvitems);
};
const _onMenuClick = (item?: PivotItem, ev?: React.MouseEvent<HTMLElement, MouseEvent>): void => {
if (item) {
if (item.props.itemKey == "0") {
} else if (item.props.itemKey == "1") {
}
setSelectedMenu(item.props.itemKey);
}
};
const _prepareJSONForAzFunc = (data: IAzFuncValues[], itemid: number, folderPath: string): string => {
let finalJson: string = "";
let tenantName: string = props.siteUrl.split("." + props.domainName)[0];
if (data && data.length > 0) {
let userPhotoObj = new Object();
userPhotoObj['adminurl'] = `${tenantName}-admin.${props.domainName}`;
userPhotoObj['mysiteurl'] = `${tenantName}-my.${props.domainName}`;
userPhotoObj['targetSiteUrl'] = props.siteUrl;
userPhotoObj['picfolder'] = folderPath + "/";
userPhotoObj['clearPhotos'] = props.deleteThumbnails;
userPhotoObj['usecert'] = props.UseCert ? props.UseCert : false;
userPhotoObj['itemId'] = itemid;
userPhotoObj['value'] = data;
finalJson = JSON.stringify(userPhotoObj);
}
return finalJson;
};
const _updateSPWithPhoto = async (data: IAzFuncValues[], itemid: number) => {
setdisablePivot(true);
let tempFolderPath: string = await props.helper.getLibraryDetails(props.tempLib);
let finalJson: string = _prepareJSONForAzFunc(data, itemid, tempFolderPath);
await props.helper.updateSyncItem(itemid, finalJson);
props.helper.runAzFunction(props.httpClient, finalJson, props.AzFuncUrl, itemid);
setdisablePivot(false);
};
useEffect(() => {
_useFullWidth();
}, [props.useFullWidth]);
useEffect(() => {
_checkForAccess();
}, [props.allowedUsers]);
useEffect(() => {
_updatePivotMenus();
}, [props.enableBulkUpdate]);
return (
<AppContext.Provider value={parentCtxValues}>
<div className={styles.photoSync}>
<div className={styles.container}>
<div className={styles.row}>
<div className={styles.column}>
<WebPartTitle displayMode={props.displayMode} title={props.appTitle ? props.appTitle : strings.DefaultAppTitle} updateProperty={props.updateProperty} />
{showConfig ? (
<ConfigPlaceholder />
) : (
<>
{loading ? (
<ProgressIndicator label={strings.AccessCheckDesc} description={strings.PropsLoader} />
) : (
<>
{accessDenied ? (
<MessageContainer MessageScope={MessageScope.SevereWarning} Message={strings.AccessDenied} />
) : (
<>
{!listExists ? (
<ProgressIndicator label={strings.ListCreationText} description={strings.PropsLoader} />
) : (
<>
<div>
<Pivot defaultSelectedKey="0" selectedKey={selectedMenu} onLinkClick={_onMenuClick} className={styles.periodmenu}>
<PivotItem headerText={strings.TabMenu1} itemKey="0" itemIcon="SchoolDataSyncLogo" headerButtonProps={headerButtonProps}></PivotItem>
{pivotItems}
<PivotItem headerText={strings.TabMenu3} itemKey="2" itemIcon="SyncStatus" headerButtonProps={headerButtonProps}></PivotItem>
</Pivot>
</div>
{/* Individual Selection photo sync */}
{selectedMenu == "0" &&
<div>
<UserSelectionSync updateSPWithPhoto={_updateSPWithPhoto} />
</div>
}
{/* Bulk photo sync */}
{selectedMenu == "1" &&
<BulkPhotoSync updateSPWithPhoto={_updateSPWithPhoto} />
}
{/* Overall status of the sync jobs */}
{selectedMenu == "2" &&
<SyncJobs dateFormat={props.dateFormat} />
}
</>
)}
</>
)}
</>
)}
</>
)}
</div>
</div>
</div>
</div>
</AppContext.Provider>
);
};
export default PhotoSync; | the_stack |
function lookupInUnicodeMap(code: number, map: ReadonlyArray<number>): boolean {
// Bail out quickly if it couldn't possibly be in the map.
if (code < map[0]) {
return false;
}
// Perform binary search in one of the Unicode range maps
let lo = 0;
let hi: number = map.length;
let mid: number;
while (lo + 1 < hi) {
mid = lo + (hi - lo) / 2;
// mid has to be even to catch a range's beginning
mid -= mid % 2;
if (map[mid] <= code && code <= map[mid + 1]) {
return true;
}
if (code < map[mid]) {
hi = mid;
} else {
lo = mid + 2;
}
}
return false;
}
const enum CharacterCodes {
maxAsciiCharacter = 0x7f,
_ = 0x5f,
$ = 0x24,
_0 = 0x30,
_9 = 0x39,
a = 0x61,
z = 0x7a,
A = 0x41,
Z = 0x5a
}
export function isES3IdentifierStart(ch: number): boolean {
return (
(ch >= CharacterCodes.A && ch <= CharacterCodes.Z) ||
(ch >= CharacterCodes.a && ch <= CharacterCodes.z) ||
ch === CharacterCodes.$ ||
ch === CharacterCodes._ ||
(ch > CharacterCodes.maxAsciiCharacter && lookupInUnicodeMap(ch, unicodeES3IdentifierStart))
);
}
export function isES3IdentifierPart(ch: number): boolean {
return (
(ch >= CharacterCodes.A && ch <= CharacterCodes.Z) ||
(ch >= CharacterCodes.a && ch <= CharacterCodes.z) ||
(ch >= CharacterCodes._0 && ch <= CharacterCodes._9) ||
ch === CharacterCodes.$ ||
ch === CharacterCodes._ ||
(ch > CharacterCodes.maxAsciiCharacter && lookupInUnicodeMap(ch, unicodeES3IdentifierPart))
);
}
/*
As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
IdentifierStart ::
Can contain Unicode 3.0.0 categories:
Uppercase letter (Lu),
Lowercase letter (Ll),
Titlecase letter (Lt),
Modifier letter (Lm),
Other letter (Lo), or
Letter number (Nl).
IdentifierPart :: =
Can contain IdentifierStart + Unicode 3.0.0 categories:
Non-spacing mark (Mn),
Combining spacing mark (Mc),
Decimal number (Nd), or
Connector punctuation (Pc).
Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
*/
const unicodeES3IdentifierStart = [
170,
170,
181,
181,
186,
186,
192,
214,
216,
246,
248,
543,
546,
563,
592,
685,
688,
696,
699,
705,
720,
721,
736,
740,
750,
750,
890,
890,
902,
902,
904,
906,
908,
908,
910,
929,
931,
974,
976,
983,
986,
1011,
1024,
1153,
1164,
1220,
1223,
1224,
1227,
1228,
1232,
1269,
1272,
1273,
1329,
1366,
1369,
1369,
1377,
1415,
1488,
1514,
1520,
1522,
1569,
1594,
1600,
1610,
1649,
1747,
1749,
1749,
1765,
1766,
1786,
1788,
1808,
1808,
1810,
1836,
1920,
1957,
2309,
2361,
2365,
2365,
2384,
2384,
2392,
2401,
2437,
2444,
2447,
2448,
2451,
2472,
2474,
2480,
2482,
2482,
2486,
2489,
2524,
2525,
2527,
2529,
2544,
2545,
2565,
2570,
2575,
2576,
2579,
2600,
2602,
2608,
2610,
2611,
2613,
2614,
2616,
2617,
2649,
2652,
2654,
2654,
2674,
2676,
2693,
2699,
2701,
2701,
2703,
2705,
2707,
2728,
2730,
2736,
2738,
2739,
2741,
2745,
2749,
2749,
2768,
2768,
2784,
2784,
2821,
2828,
2831,
2832,
2835,
2856,
2858,
2864,
2866,
2867,
2870,
2873,
2877,
2877,
2908,
2909,
2911,
2913,
2949,
2954,
2958,
2960,
2962,
2965,
2969,
2970,
2972,
2972,
2974,
2975,
2979,
2980,
2984,
2986,
2990,
2997,
2999,
3001,
3077,
3084,
3086,
3088,
3090,
3112,
3114,
3123,
3125,
3129,
3168,
3169,
3205,
3212,
3214,
3216,
3218,
3240,
3242,
3251,
3253,
3257,
3294,
3294,
3296,
3297,
3333,
3340,
3342,
3344,
3346,
3368,
3370,
3385,
3424,
3425,
3461,
3478,
3482,
3505,
3507,
3515,
3517,
3517,
3520,
3526,
3585,
3632,
3634,
3635,
3648,
3654,
3713,
3714,
3716,
3716,
3719,
3720,
3722,
3722,
3725,
3725,
3732,
3735,
3737,
3743,
3745,
3747,
3749,
3749,
3751,
3751,
3754,
3755,
3757,
3760,
3762,
3763,
3773,
3773,
3776,
3780,
3782,
3782,
3804,
3805,
3840,
3840,
3904,
3911,
3913,
3946,
3976,
3979,
4096,
4129,
4131,
4135,
4137,
4138,
4176,
4181,
4256,
4293,
4304,
4342,
4352,
4441,
4447,
4514,
4520,
4601,
4608,
4614,
4616,
4678,
4680,
4680,
4682,
4685,
4688,
4694,
4696,
4696,
4698,
4701,
4704,
4742,
4744,
4744,
4746,
4749,
4752,
4782,
4784,
4784,
4786,
4789,
4792,
4798,
4800,
4800,
4802,
4805,
4808,
4814,
4816,
4822,
4824,
4846,
4848,
4878,
4880,
4880,
4882,
4885,
4888,
4894,
4896,
4934,
4936,
4954,
5024,
5108,
5121,
5740,
5743,
5750,
5761,
5786,
5792,
5866,
6016,
6067,
6176,
6263,
6272,
6312,
7680,
7835,
7840,
7929,
7936,
7957,
7960,
7965,
7968,
8005,
8008,
8013,
8016,
8023,
8025,
8025,
8027,
8027,
8029,
8029,
8031,
8061,
8064,
8116,
8118,
8124,
8126,
8126,
8130,
8132,
8134,
8140,
8144,
8147,
8150,
8155,
8160,
8172,
8178,
8180,
8182,
8188,
8319,
8319,
8450,
8450,
8455,
8455,
8458,
8467,
8469,
8469,
8473,
8477,
8484,
8484,
8486,
8486,
8488,
8488,
8490,
8493,
8495,
8497,
8499,
8505,
8544,
8579,
12293,
12295,
12321,
12329,
12337,
12341,
12344,
12346,
12353,
12436,
12445,
12446,
12449,
12538,
12540,
12542,
12549,
12588,
12593,
12686,
12704,
12727,
13312,
19893,
19968,
40869,
40960,
42124,
44032,
55203,
63744,
64045,
64256,
64262,
64275,
64279,
64285,
64285,
64287,
64296,
64298,
64310,
64312,
64316,
64318,
64318,
64320,
64321,
64323,
64324,
64326,
64433,
64467,
64829,
64848,
64911,
64914,
64967,
65008,
65019,
65136,
65138,
65140,
65140,
65142,
65276,
65313,
65338,
65345,
65370,
65382,
65470,
65474,
65479,
65482,
65487,
65490,
65495,
65498,
65500
];
const unicodeES3IdentifierPart = [
170,
170,
181,
181,
186,
186,
192,
214,
216,
246,
248,
543,
546,
563,
592,
685,
688,
696,
699,
705,
720,
721,
736,
740,
750,
750,
768,
846,
864,
866,
890,
890,
902,
902,
904,
906,
908,
908,
910,
929,
931,
974,
976,
983,
986,
1011,
1024,
1153,
1155,
1158,
1164,
1220,
1223,
1224,
1227,
1228,
1232,
1269,
1272,
1273,
1329,
1366,
1369,
1369,
1377,
1415,
1425,
1441,
1443,
1465,
1467,
1469,
1471,
1471,
1473,
1474,
1476,
1476,
1488,
1514,
1520,
1522,
1569,
1594,
1600,
1621,
1632,
1641,
1648,
1747,
1749,
1756,
1759,
1768,
1770,
1773,
1776,
1788,
1808,
1836,
1840,
1866,
1920,
1968,
2305,
2307,
2309,
2361,
2364,
2381,
2384,
2388,
2392,
2403,
2406,
2415,
2433,
2435,
2437,
2444,
2447,
2448,
2451,
2472,
2474,
2480,
2482,
2482,
2486,
2489,
2492,
2492,
2494,
2500,
2503,
2504,
2507,
2509,
2519,
2519,
2524,
2525,
2527,
2531,
2534,
2545,
2562,
2562,
2565,
2570,
2575,
2576,
2579,
2600,
2602,
2608,
2610,
2611,
2613,
2614,
2616,
2617,
2620,
2620,
2622,
2626,
2631,
2632,
2635,
2637,
2649,
2652,
2654,
2654,
2662,
2676,
2689,
2691,
2693,
2699,
2701,
2701,
2703,
2705,
2707,
2728,
2730,
2736,
2738,
2739,
2741,
2745,
2748,
2757,
2759,
2761,
2763,
2765,
2768,
2768,
2784,
2784,
2790,
2799,
2817,
2819,
2821,
2828,
2831,
2832,
2835,
2856,
2858,
2864,
2866,
2867,
2870,
2873,
2876,
2883,
2887,
2888,
2891,
2893,
2902,
2903,
2908,
2909,
2911,
2913,
2918,
2927,
2946,
2947,
2949,
2954,
2958,
2960,
2962,
2965,
2969,
2970,
2972,
2972,
2974,
2975,
2979,
2980,
2984,
2986,
2990,
2997,
2999,
3001,
3006,
3010,
3014,
3016,
3018,
3021,
3031,
3031,
3047,
3055,
3073,
3075,
3077,
3084,
3086,
3088,
3090,
3112,
3114,
3123,
3125,
3129,
3134,
3140,
3142,
3144,
3146,
3149,
3157,
3158,
3168,
3169,
3174,
3183,
3202,
3203,
3205,
3212,
3214,
3216,
3218,
3240,
3242,
3251,
3253,
3257,
3262,
3268,
3270,
3272,
3274,
3277,
3285,
3286,
3294,
3294,
3296,
3297,
3302,
3311,
3330,
3331,
3333,
3340,
3342,
3344,
3346,
3368,
3370,
3385,
3390,
3395,
3398,
3400,
3402,
3405,
3415,
3415,
3424,
3425,
3430,
3439,
3458,
3459,
3461,
3478,
3482,
3505,
3507,
3515,
3517,
3517,
3520,
3526,
3530,
3530,
3535,
3540,
3542,
3542,
3544,
3551,
3570,
3571,
3585,
3642,
3648,
3662,
3664,
3673,
3713,
3714,
3716,
3716,
3719,
3720,
3722,
3722,
3725,
3725,
3732,
3735,
3737,
3743,
3745,
3747,
3749,
3749,
3751,
3751,
3754,
3755,
3757,
3769,
3771,
3773,
3776,
3780,
3782,
3782,
3784,
3789,
3792,
3801,
3804,
3805,
3840,
3840,
3864,
3865,
3872,
3881,
3893,
3893,
3895,
3895,
3897,
3897,
3902,
3911,
3913,
3946,
3953,
3972,
3974,
3979,
3984,
3991,
3993,
4028,
4038,
4038,
4096,
4129,
4131,
4135,
4137,
4138,
4140,
4146,
4150,
4153,
4160,
4169,
4176,
4185,
4256,
4293,
4304,
4342,
4352,
4441,
4447,
4514,
4520,
4601,
4608,
4614,
4616,
4678,
4680,
4680,
4682,
4685,
4688,
4694,
4696,
4696,
4698,
4701,
4704,
4742,
4744,
4744,
4746,
4749,
4752,
4782,
4784,
4784,
4786,
4789,
4792,
4798,
4800,
4800,
4802,
4805,
4808,
4814,
4816,
4822,
4824,
4846,
4848,
4878,
4880,
4880,
4882,
4885,
4888,
4894,
4896,
4934,
4936,
4954,
4969,
4977,
5024,
5108,
5121,
5740,
5743,
5750,
5761,
5786,
5792,
5866,
6016,
6099,
6112,
6121,
6160,
6169,
6176,
6263,
6272,
6313,
7680,
7835,
7840,
7929,
7936,
7957,
7960,
7965,
7968,
8005,
8008,
8013,
8016,
8023,
8025,
8025,
8027,
8027,
8029,
8029,
8031,
8061,
8064,
8116,
8118,
8124,
8126,
8126,
8130,
8132,
8134,
8140,
8144,
8147,
8150,
8155,
8160,
8172,
8178,
8180,
8182,
8188,
8255,
8256,
8319,
8319,
8400,
8412,
8417,
8417,
8450,
8450,
8455,
8455,
8458,
8467,
8469,
8469,
8473,
8477,
8484,
8484,
8486,
8486,
8488,
8488,
8490,
8493,
8495,
8497,
8499,
8505,
8544,
8579,
12293,
12295,
12321,
12335,
12337,
12341,
12344,
12346,
12353,
12436,
12441,
12442,
12445,
12446,
12449,
12542,
12549,
12588,
12593,
12686,
12704,
12727,
13312,
19893,
19968,
40869,
40960,
42124,
44032,
55203,
63744,
64045,
64256,
64262,
64275,
64279,
64285,
64296,
64298,
64310,
64312,
64316,
64318,
64318,
64320,
64321,
64323,
64324,
64326,
64433,
64467,
64829,
64848,
64911,
64914,
64967,
65008,
65019,
65056,
65059,
65075,
65076,
65101,
65103,
65136,
65138,
65140,
65140,
65142,
65276,
65296,
65305,
65313,
65338,
65343,
65343,
65345,
65370,
65381,
65470,
65474,
65479,
65482,
65487,
65490,
65495,
65498,
65500
]; | the_stack |
import ts from 'typescript';
import WebIDL2 from 'webidl2';
import assert from 'assert';
export class CodeGen {
constructor(
private readonly context: ts.TransformationContext/*,
private readonly typeChecker: ts.TypeChecker*/
) {
const { factory } = this.context;
this.primitives = {
'boolean': () => factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword),
'octet': () => factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
'short': () => factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
'float': () => factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
'double': () => factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
'long': () => factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
'unsigned short': () => factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
'unsigned long': () => factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
'long long': () => factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
'void': () => factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword),
}
}
private readonly primitives: {
[idlType: string]: () => ts.TypeNode
};
private getSingleType = (type: WebIDL2.SingleTypeDescription): ts.TypeNode => {
const { factory } = this.context;
const [typeName] = CodeGen.classifyIdlType(type.idlType);
if (typeName in this.primitives) {
return this.primitives[typeName]();
}
return factory.createTypeReferenceNode(
factory.createIdentifier(typeName),
/*typeArguments*/undefined
);
};
private getType = (type: WebIDL2.IDLTypeDescription): ts.TypeNode => {
if (type.generic === '') {
if (type.union === false) {
return this.getSingleType(type);
}
}
throw new Error('erk');
};
private getParameterType = (type: WebIDL2.IDLTypeDescription): ts.TypeNode => {
const { factory } = this.context;
// not implemented: type.nullable
const typeNominal = this.getType(type);
if (ts.isTypeReferenceNode(typeNominal)) {
// user can submit either a WrappedObject, or a pointer
return factory.createUnionTypeNode([
typeNominal,
factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword)
]);
}
return typeNominal;
};
private getAttributeType = (type: WebIDL2.IDLTypeDescription): ts.TypeNode => {
// not implemented: type.nullable
return this.getType(type);
};
private getReturnType = (type: WebIDL2.IDLTypeDescription | null): ts.TypeNode => {
if (type === null) {
throw new Error('erk');
}
return this.getType(type);
};
private constructWrapperObjectHelper = (): ts.ClassDeclaration => {
const { factory } = this.context;
return factory.createClassDeclaration(
undefined,
[factory.createModifier(ts.SyntaxKind.ExportKeyword)],
factory.createIdentifier("WrapperObject"),
undefined,
undefined,
[
factory.createPropertyDeclaration(
undefined,
[
factory.createModifier(ts.SyntaxKind.ProtectedKeyword),
factory.createModifier(ts.SyntaxKind.StaticKeyword),
factory.createModifier(ts.SyntaxKind.ReadonlyKeyword)
],
factory.createIdentifier("__cache__"),
undefined,
factory.createTypeLiteralNode([factory.createIndexSignature(
undefined,
undefined,
[factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier("ptr"),
undefined,
factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
undefined
)],
factory.createTypeReferenceNode(
factory.createIdentifier("WrapperObject"),
undefined
)
)]),
undefined
),
factory.createPropertyDeclaration(
undefined,
[
factory.createModifier(ts.SyntaxKind.ProtectedKeyword),
factory.createModifier(ts.SyntaxKind.ReadonlyKeyword)
],
factory.createIdentifier("__class__"),
undefined,
factory.createTypeQueryNode(factory.createIdentifier("WrapperObject")),
undefined
),
factory.createPropertyDeclaration(
undefined,
[factory.createModifier(ts.SyntaxKind.ProtectedKeyword)],
factory.createIdentifier("ptr"),
factory.createToken(ts.SyntaxKind.QuestionToken),
factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
undefined
)
]
);
};
private constructVoidPtrHelper = (): ts.ClassDeclaration => {
const { factory } = this.context;
return factory.createClassDeclaration(
undefined,
[factory.createModifier(ts.SyntaxKind.ExportKeyword)],
factory.createIdentifier("VoidPtr"),
undefined,
[factory.createHeritageClause(
ts.SyntaxKind.ExtendsKeyword,
[factory.createExpressionWithTypeArguments(
factory.createIdentifier("WrapperObject"),
undefined
)]
)],
[
factory.createPropertyDeclaration(
undefined,
[
factory.createModifier(ts.SyntaxKind.ProtectedKeyword),
factory.createModifier(ts.SyntaxKind.StaticKeyword),
factory.createModifier(ts.SyntaxKind.ReadonlyKeyword)
],
factory.createIdentifier("__cache__"),
undefined,
factory.createTypeLiteralNode([factory.createIndexSignature(
undefined,
undefined,
[factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier("ptr"),
undefined,
factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
undefined
)],
factory.createTypeReferenceNode(
factory.createIdentifier("VoidPtr"),
undefined
)
)]),
undefined
),
factory.createPropertyDeclaration(
undefined,
[
factory.createModifier(ts.SyntaxKind.ProtectedKeyword),
factory.createModifier(ts.SyntaxKind.ReadonlyKeyword)
],
factory.createIdentifier("__class__"),
undefined,
factory.createTypeQueryNode(factory.createIdentifier("VoidPtr")),
undefined
),
factory.createPropertyDeclaration(
undefined,
[factory.createModifier(ts.SyntaxKind.ProtectedKeyword)],
factory.createIdentifier("ptr"),
factory.createToken(ts.SyntaxKind.QuestionToken),
factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
undefined
)
]
);
}
/**
* export const wrapPointer
*/
private constructWrapPointerHelper = (): ts.VariableStatement => {
const { factory } = this.context;
return factory.createVariableStatement(
[factory.createModifier(ts.SyntaxKind.ExportKeyword)],
factory.createVariableDeclarationList(
[factory.createVariableDeclaration(
factory.createIdentifier("wrapPointer"),
undefined,
factory.createFunctionTypeNode(
[factory.createTypeParameterDeclaration(
factory.createIdentifier("TargetClass"),
factory.createIntersectionTypeNode([
factory.createTypeQueryNode(factory.createIdentifier("WrapperObject")),
factory.createTypeLiteralNode([factory.createConstructSignature(
undefined,
[factory.createParameterDeclaration(
undefined,
undefined,
factory.createToken(ts.SyntaxKind.DotDotDotToken),
factory.createIdentifier("args"),
undefined,
factory.createArrayTypeNode(factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)),
undefined
)],
factory.createTypeReferenceNode(
factory.createIdentifier("InstanceType"),
[factory.createTypeReferenceNode(
factory.createIdentifier("TargetClass"),
undefined
)]
)
)])
]),
factory.createTypeQueryNode(factory.createIdentifier("WrapperObject"))
)],
[
factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier("pointer"),
undefined,
factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
undefined
),
factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier("targetType"),
factory.createToken(ts.SyntaxKind.QuestionToken),
factory.createTypeReferenceNode(
factory.createIdentifier("TargetClass"),
undefined
),
undefined
)
],
factory.createTypeReferenceNode(
factory.createIdentifier("InstanceType"),
[factory.createTypeReferenceNode(
factory.createIdentifier("TargetClass"),
undefined
)]
)
),
undefined
)],
ts.NodeFlags.Const
)
);
};
/**
* export const getPointer
*/
private constructGetPointerHelper = (): ts.VariableStatement => {
const { factory } = this.context;
return factory.createVariableStatement(
[factory.createModifier(ts.SyntaxKind.ExportKeyword)],
factory.createVariableDeclarationList(
[factory.createVariableDeclaration(
factory.createIdentifier("getPointer"),
undefined,
factory.createFunctionTypeNode(
undefined,
[factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier("instance"),
undefined,
factory.createTypeReferenceNode(
factory.createIdentifier("WrapperObject"),
undefined
),
undefined
)],
factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword)
),
undefined
)],
ts.NodeFlags.Const
)
);
};
/**
* export const castObject
*/
private constructCastObjectHelper = (): ts.VariableStatement => {
const { factory } = this.context;
return factory.createVariableStatement(
[factory.createModifier(ts.SyntaxKind.ExportKeyword)],
factory.createVariableDeclarationList(
[factory.createVariableDeclaration(
factory.createIdentifier("castObject"),
undefined,
factory.createFunctionTypeNode(
[factory.createTypeParameterDeclaration(
factory.createIdentifier("TargetClass"),
factory.createIntersectionTypeNode([
factory.createTypeQueryNode(factory.createIdentifier("WrapperObject")),
factory.createTypeLiteralNode([factory.createConstructSignature(
undefined,
[factory.createParameterDeclaration(
undefined,
undefined,
factory.createToken(ts.SyntaxKind.DotDotDotToken),
factory.createIdentifier("args"),
undefined,
factory.createArrayTypeNode(factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)),
undefined
)],
factory.createTypeReferenceNode(
factory.createIdentifier("InstanceType"),
[factory.createTypeReferenceNode(
factory.createIdentifier("TargetClass"),
undefined
)]
)
)])
]),
factory.createTypeQueryNode(factory.createIdentifier("WrapperObject"))
)],
[
factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier("instance"),
undefined,
factory.createTypeReferenceNode(
factory.createIdentifier("WrapperObject"),
undefined
),
undefined
),
factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier("targetType"),
factory.createToken(ts.SyntaxKind.QuestionToken),
factory.createTypeReferenceNode(
factory.createIdentifier("TargetClass"),
undefined
),
undefined
)
],
factory.createTypeReferenceNode(
factory.createIdentifier("InstanceType"),
[factory.createTypeReferenceNode(
factory.createIdentifier("TargetClass"),
undefined
)]
)
),
undefined
)],
ts.NodeFlags.Const
)
);
};
/**
* export const compare
*/
private constructCompareHelper = (): ts.VariableStatement => {
const { factory } = this.context;
return factory.createVariableStatement(
[factory.createModifier(ts.SyntaxKind.ExportKeyword)],
factory.createVariableDeclarationList(
[factory.createVariableDeclaration(
factory.createIdentifier("compare"),
undefined,
factory.createFunctionTypeNode(
undefined,
[
factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier("instance"),
undefined,
factory.createTypeReferenceNode(
factory.createIdentifier("WrapperObject"),
undefined
),
undefined
),
factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier("instance2"),
undefined,
factory.createTypeReferenceNode(
factory.createIdentifier("WrapperObject"),
undefined
),
undefined
)
],
factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword)
),
undefined
)],
ts.NodeFlags.Const
)
);
};
/**
* export const getCache
*/
private constructGetCacheHelper = (): ts.VariableStatement => {
const { factory } = this.context;
return factory.createVariableStatement(
[factory.createModifier(ts.SyntaxKind.ExportKeyword)],
factory.createVariableDeclarationList(
[factory.createVariableDeclaration(
factory.createIdentifier("getCache"),
undefined,
factory.createFunctionTypeNode(
[factory.createTypeParameterDeclaration(
factory.createIdentifier("Class"),
factory.createTypeQueryNode(factory.createIdentifier("WrapperObject")),
factory.createTypeQueryNode(factory.createIdentifier("WrapperObject"))
)],
[factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier("type"),
factory.createToken(ts.SyntaxKind.QuestionToken),
factory.createTypeReferenceNode(
factory.createIdentifier("Class"),
undefined
),
undefined
)],
factory.createTypeLiteralNode([factory.createIndexSignature(
undefined,
undefined,
[factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier("ptr"),
undefined,
factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
undefined
)],
factory.createTypeReferenceNode(
factory.createIdentifier("InstanceType"),
[factory.createTypeReferenceNode(
factory.createIdentifier("Class"),
undefined
)]
)
)])
),
undefined
)],
ts.NodeFlags.Const
)
);
};
/**
* export const destroy
*/
private constructDestroyHelper = (): ts.VariableStatement => {
const { factory } = this.context;
return factory.createVariableStatement(
[factory.createModifier(ts.SyntaxKind.ExportKeyword)],
factory.createVariableDeclarationList(
[factory.createVariableDeclaration(
factory.createIdentifier("destroy"),
undefined,
factory.createFunctionTypeNode(
undefined,
[factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier("instance"),
undefined,
factory.createTypeLiteralNode([factory.createMethodSignature(
undefined,
factory.createIdentifier("__destroy__"),
undefined,
undefined,
[],
factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword)
)]),
undefined
)],
factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword)
),
undefined
)],
ts.NodeFlags.Const
)
);
};
/**
* export const getClass
*/
private constructGetClassHelper = (): ts.VariableStatement => {
const { factory } = this.context;
return factory.createVariableStatement(
[factory.createModifier(ts.SyntaxKind.ExportKeyword)],
factory.createVariableDeclarationList(
[factory.createVariableDeclaration(
factory.createIdentifier("getClass"),
undefined,
factory.createFunctionTypeNode(
[factory.createTypeParameterDeclaration(
factory.createIdentifier("Class"),
factory.createTypeQueryNode(factory.createIdentifier("WrapperObject")),
undefined
)],
[factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier("instance"),
undefined,
factory.createTypeReferenceNode(
factory.createIdentifier("InstanceType"),
[factory.createTypeReferenceNode(
factory.createIdentifier("Class"),
undefined
)]
),
undefined
)],
factory.createTypeReferenceNode(
factory.createIdentifier("Class"),
undefined
)
),
undefined
)],
ts.NodeFlags.Const
)
);
};
/**
* export const NULL
*/
private constructNullHelper = (): ts.VariableStatement => {
const { factory } = this.context;
return factory.createVariableStatement(
[factory.createModifier(ts.SyntaxKind.ExportKeyword)],
factory.createVariableDeclarationList(
[factory.createVariableDeclaration(
factory.createIdentifier("NULL"),
undefined,
factory.createTypeReferenceNode(
factory.createIdentifier("WrapperObject"),
undefined
),
undefined
)],
ts.NodeFlags.Const
)
)
};
private helpers = (): ts.Statement[] => {
return [
this.constructWrapperObjectHelper(),
this.constructVoidPtrHelper(),
this.constructWrapPointerHelper(),
this.constructGetPointerHelper(),
this.constructCastObjectHelper(),
this.constructCompareHelper(),
this.constructGetCacheHelper(),
this.constructDestroyHelper(),
this.constructGetClassHelper(),
this.constructNullHelper(),
];
};
private getParameterDeclaration = (arg: WebIDL2.Argument): ts.ParameterDeclaration => {
const { factory } = this.context;
return factory.createParameterDeclaration(
/*decorators*/undefined,
/*modifiers*/undefined,
/*dotDotDotToken*/undefined,
/*name*/factory.createIdentifier(arg.name),
/*questionToken*/undefined,
/*type*/this.getParameterType(arg.idlType),
);
};
private getConstructor = (member: WebIDL2.ConstructorMemberType | WebIDL2.OperationMemberType): [ts.ConstructorDeclaration, ts.ConstructorDeclaration] | [] => {
const { factory } = this.context;
if (!member.arguments.length) {
// JS classes already have an implicit no-args constructor
return [];
}
const noArg: ts.ConstructorDeclaration = factory.createConstructorDeclaration(
/*decorators*/undefined,
/*modifiers*/undefined,
/*parameters*/undefined,
/*body*/undefined
);
ts.addSyntheticLeadingComment(
noArg,
ts.SyntaxKind.MultiLineCommentTrivia,
`*
* @deprecated no-arg construction is forbidden (throws errors).
* it's exposed in the types solely so that this class can be structurally-compatible with {@link WrapperObject}.
* @throws {string}
`,
true);
return [
noArg,
factory.createConstructorDeclaration(
/*decorators*/undefined,
/*modifiers*/undefined,
/*parameters*/member.arguments.map(this.getParameterDeclaration),
/*body*/undefined
)];
};
private getOperation = (member: WebIDL2.OperationMemberType): ts.MethodDeclaration => {
const { factory } = this.context;
return factory.createMethodDeclaration(
/*decorators*/undefined,
/*modifiers*/undefined,
/*asteriskToken*/undefined,
/*name*/factory.createIdentifier(member.name),
/*questionToken*/undefined,
/*typeParameters*/undefined,
/*parameters*/member.arguments.map(this.getParameterDeclaration),
this.getReturnType(member.idlType),
/*body*/undefined
);
};
private static classifyIdlType = (idlType: string): [typeName: string, isArr: boolean] => {
const arrayAttributeMatcher = /(.*)__arr$/;
const match: RegExpExecArray | null = arrayAttributeMatcher.exec(idlType);
if (match) {
const [,attrName] = match;
return [attrName, true];
}
return [idlType, false];
}
private static classifyIdlTypeDescription = (type: WebIDL2.IDLTypeDescription): [typeName: string, isArr: boolean] => {
if (type.generic === '') {
if (type.union === false) {
return CodeGen.classifyIdlType(type.idlType);
}
}
throw new Error('erk');
};
private getAttribute = (member: WebIDL2.AttributeMemberType): [ts.PropertyDeclaration, ts.MethodDeclaration, ts.MethodDeclaration] => {
const { factory } = this.context;
/**
* TODO: Box2D.idl doesn't currently use readonly attributes,
* but if we did need to support them, then we'd likely want to add a readonly modifier
* to the property declaration, and refrain from emitting a setter method.
*/
const [, isArr] = CodeGen.classifyIdlTypeDescription(member.idlType);
return [
factory.createPropertyDeclaration(
undefined,
undefined,
factory.createIdentifier(member.name),
undefined,
this.getAttributeType(member.idlType),
undefined
),
factory.createMethodDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier(`get_${member.name}`),
undefined,
undefined,
isArr ? [
factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier('index'),
factory.createToken(ts.SyntaxKind.QuestionToken),
factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
undefined
)
] : [],
this.getAttributeType(member.idlType),
undefined
),
factory.createMethodDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier(`set_${member.name}`),
undefined,
undefined,
[
...isArr ? [
factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier('index'),
undefined,
factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
undefined
)
] : [],
factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier(`${member.name}${isArr ? '_elem' : ''}`),
undefined,
this.getAttributeType(member.idlType),
undefined
)
],
factory.createToken(ts.SyntaxKind.VoidKeyword),
undefined
)
];
};
private getCommonClassBoilerplateMembers = (classIdentifierFactory: () => ts.EntityName): ts.ClassElement[] => {
const { factory } = this.context;
return [
factory.createPropertyDeclaration(
undefined,
[
factory.createModifier(ts.SyntaxKind.ProtectedKeyword),
factory.createModifier(ts.SyntaxKind.StaticKeyword),
factory.createModifier(ts.SyntaxKind.ReadonlyKeyword)
],
factory.createIdentifier("__cache__"),
undefined,
factory.createTypeLiteralNode([factory.createIndexSignature(
undefined,
undefined,
[factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier("ptr"),
undefined,
factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
undefined
)],
factory.createTypeReferenceNode(
classIdentifierFactory(),
undefined
)
)]),
undefined
),
factory.createPropertyDeclaration(
undefined,
[
factory.createModifier(ts.SyntaxKind.ProtectedKeyword),
factory.createModifier(ts.SyntaxKind.ReadonlyKeyword)
],
factory.createIdentifier("__class__"),
undefined,
factory.createTypeQueryNode(classIdentifierFactory()),
undefined
)
];
};
private getDeletableClassBoilerplateMembers = (): ts.ClassElement[] => {
const { factory } = this.context;
return [
factory.createMethodDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier("__destroy__"),
undefined,
undefined,
[],
factory.createToken(ts.SyntaxKind.VoidKeyword),
undefined
)
]
};
/**
* Additional members for classes which have a public constructor bound
*/
private getConstructibleClassBoilerplateMembers = (): ts.ClassElement[] => {
const { factory } = this.context;
return [
factory.createPropertyDeclaration(
undefined,
[factory.createModifier(ts.SyntaxKind.ProtectedKeyword)],
factory.createIdentifier("ptr"),
undefined,
factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
undefined
)
];
};
private static getParentClassName = (extAttr: WebIDL2.ExtendedAttribute): string => {
if (extAttr.rhs.type !== 'string') {
throw new Error('Unexpected rhs ${extAttr.rhs}');
}
return JSON.parse(extAttr.rhs.value);
}
private static isConstructorMember = (root: WebIDL2.InterfaceType | WebIDL2.InterfaceMixinType, member: WebIDL2.IDLInterfaceMemberType | WebIDL2.IDLInterfaceMixinMemberType): boolean => {
return member.type === 'constructor' || member.type === 'operation' && member.name === root.name;
};
private static isConstructibleType = (root: WebIDL2.InterfaceType | WebIDL2.InterfaceMixinType): boolean => {
if (root.type === 'interface mixin') {
return false;
}
return root.members.some((member: WebIDL2.IDLInterfaceMemberType): boolean => CodeGen.isConstructorMember(root, member));
};
private roots = (roots: WebIDL2.IDLRootType[]): Roots => {
const { factory } = this.context;
return roots.reduce<Roots>((acc: Roots, root: WebIDL2.IDLRootType): Roots => {
if (root.type === 'interface' || root.type === 'interface mixin') {
const jsImplementation: WebIDL2.ExtendedAttribute | undefined =
root.extAttrs.find((extAttr: WebIDL2.ExtendedAttribute): boolean =>
extAttr.name === 'JSImplementation');
const parentClassName: string = jsImplementation ? CodeGen.getParentClassName(jsImplementation)
: 'WrapperObject';
const isDeletable = !root.extAttrs.some((extAttr: WebIDL2.ExtendedAttribute): boolean =>
extAttr.name === 'NoDelete');
const isConstructibleType = CodeGen.isConstructibleType(root);
const classIdentifierFactory = () => factory.createIdentifier(root.name);
acc.statements.push(factory.createClassDeclaration(
/*decorators*/undefined,
/*modifiers*/[factory.createToken(ts.SyntaxKind.ExportKeyword)],
classIdentifierFactory(),
/*typeParameters*/undefined,
/*heritageClauses*/[factory.createHeritageClause(
ts.SyntaxKind.ExtendsKeyword,
[factory.createExpressionWithTypeArguments(
factory.createIdentifier(parentClassName),
undefined
)]
)],
/*members*/this.getCommonClassBoilerplateMembers(classIdentifierFactory)
.concat(isDeletable ? this.getDeletableClassBoilerplateMembers() : [])
.concat(isConstructibleType ? this.getConstructibleClassBoilerplateMembers() : [])
.concat(
(root.members as Array<WebIDL2.IDLInterfaceMemberType | WebIDL2.IDLInterfaceMixinMemberType>)
.flatMap<ts.ClassElement, Array<WebIDL2.IDLInterfaceMemberType | WebIDL2.IDLInterfaceMixinMemberType>>(
(member: WebIDL2.IDLInterfaceMemberType | WebIDL2.IDLInterfaceMixinMemberType): ts.ClassElement[] => {
if (CodeGen.isConstructorMember(root, member)) {
// tried to get this cast for free via type guard from ::isConstructorMember,
// but it makes TS wrongly eliminate 'operation' as a possible type outside of this block
return this.getConstructor(member as WebIDL2.ConstructorMemberType | WebIDL2.OperationMemberType);
}
if (member.type === 'operation') {
return [this.getOperation(member)];
}
if (member.type === 'attribute') {
return this.getAttribute(member);
}
throw new Error('erk');
}, []
)
)
));
return acc;
}
if (root.type === 'enum') {
acc.knownEnumNames.push(root.name);
if (!root.values.length) {
return acc;
}
const parseEnumPath = (path: string): { namespace: string[], constant: string } => {
const pathParts: string[] = path.split('::');
const namespace: string[] = pathParts.slice(0, pathParts.length-1);
const constant = pathParts[pathParts.length-1];
return { namespace, constant };
};
const representative = parseEnumPath(root.values[0].value);
const variableStatements: ts.VariableStatement[] = root.values.map(({ value }: WebIDL2.EnumType['values'][number]): ts.VariableStatement => {
const { namespace, constant } = parseEnumPath(value);
if (namespace.join('::') !== representative.namespace.join('::')) {
throw new Error (`Didn't expect WebIDL enums to contain values with differing namespaces. First was '${representative.namespace.join('::')}::${representative.constant}', but sibling '${namespace.join('::')}::${constant}' had a different namespace.`);
}
return factory.createVariableStatement(
undefined,
factory.createVariableDeclarationList(
[factory.createVariableDeclaration(
factory.createIdentifier(constant),
undefined,
factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
undefined
)],
ts.NodeFlags.Const | ts.NodeFlags.ContextFlags
)
);
});
const accumulated: ts.ModuleDeclaration | ts.VariableStatement[] =
representative.namespace.reduceRight<ts.ModuleDeclaration | ts.VariableStatement[]>((acc: ts.ModuleDeclaration | ts.VariableStatement[], namespacePart: string): ts.ModuleDeclaration | ts.VariableStatement[] => {
return factory.createModuleDeclaration(
undefined,
[factory.createModifier(ts.SyntaxKind.ExportKeyword)],
factory.createIdentifier(namespacePart),
factory.createModuleBlock(Array.isArray(acc) ? acc : [acc]),
ts.NodeFlags.Namespace | ts.NodeFlags.ExportContext | ts.NodeFlags.ContextFlags
);
}, variableStatements);
if (Array.isArray(accumulated)) {
acc.statements.push(...accumulated);
} else {
acc.statements.push(accumulated);
}
return acc;
}
if (root.type === 'includes') {
acc.includes[root.target] = root.includes;
return acc;
}
throw new Error('erk');
}, {
statements: [],
knownEnumNames: [],
includes: {}
});
};
codegen = (roots: WebIDL2.IDLRootType[], namespaceName: string): ts.Statement => {
const { factory } = this.context;
const { statements, knownEnumNames, includes } = this.roots(roots);
const elideEnumVisitor: ts.Visitor = node => {
if (ts.isTypeReferenceNode(node)) {
if (node.typeName.kind === ts.SyntaxKind.Identifier) {
if (knownEnumNames.includes(node.typeName.text)) {
return factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword);
}
}
}
return ts.visitEachChild(node, elideEnumVisitor, this.context);
};
const statementsWithEnumsElided = ts.visitNodes(factory.createNodeArray(statements), elideEnumVisitor);
const applyIncludeVisitor: ts.Visitor = node => {
if (ts.isClassDeclaration(node)) {
if (node.name.text in includes) {
if (node.heritageClauses?.length !== 1) {
throw new Error(`Expected exactly 1 heritage clause; found ${node.heritageClauses?.length}`);
}
return factory.updateClassDeclaration(
node,
node.decorators,
node.modifiers,
node.name,
node.typeParameters,
[factory.updateHeritageClause(node.heritageClauses[0], [
factory.createExpressionWithTypeArguments(
factory.createIdentifier(includes[node.name.text]),
undefined
)
])],
node.members
);
}
}
return ts.visitEachChild(node, applyIncludeVisitor, this.context);
};
const statementsWithIncludesApplied = ts.visitNodes(statementsWithEnumsElided, applyIncludeVisitor);
// const fix__class__Visitor: ts.Visitor = node => {
// if (ts.isPropertyDeclaration(node) &&
// ts.isIdentifier(node.name) && node.name.text === '__class__') {
// assert(ts.isTypeQueryNode(node.type));
// assert(ts.isIdentifier(node.type.exprName));
// return factory.updatePropertyDeclaration(
// node,
// node.decorators,
// node.modifiers,
// node.name,
// node.questionToken,
// factory.createIntersectionTypeNode([
// factory.createTypeQueryNode(factory.createIdentifier(node.type.exprName.text)),
// factory.createTypeQueryNode(factory.createIdentifier('WrapperObject'))
// ]),
// node.initializer
// );
// }
// return node;
// };
// const fix__class__OnClassesWithCustomConstructor: ts.Visitor = node => {
// if (ts.isClassDeclaration(node)) {
// if (node.heritageClauses?.some((heritageClause: ts.HeritageClause): boolean =>
// heritageClause.types.some(({ expression }: ts.ExpressionWithTypeArguments): boolean =>
// ts.isIdentifier(expression) && expression.text === 'WrapperObject'
// )
// ) && node.members.some((classElement: ts.ClassElement) => ts.isConstructorDeclaration(classElement))
// ) {
// // class inherits from WrapperObject and has an explicit constructor
// const __class__: ts.PropertyDeclaration | undefined = node.members.find((classElement: ts.ClassElement): classElement is ts.PropertyDeclaration =>
// ts.isPropertyDeclaration(classElement) &&
// ts.isIdentifier(classElement.name) && classElement.name.text === '__class__'
// );
// assert(__class__);
// return factory.updateClassDeclaration(
// node,
// node.decorators,
// node.modifiers,
// node.name,
// node.typeParameters,
// node.heritageClauses,
// ts.visitNodes(node.members, fix__class__Visitor)
// );
// }
// }
// return ts.visitEachChild(node, fix__class__OnClassesWithCustomConstructor, this.context);
// };
// const statementsWith__class__Fixed = ts.visitNodes(statementsWithIncludesApplied, fix__class__OnClassesWithCustomConstructor);
return factory.createModuleDeclaration(
/*decorators*/undefined,
/*modifiers*/[factory.createModifier(ts.SyntaxKind.DeclareKeyword)],
/*name*/factory.createIdentifier(namespaceName),
factory.createModuleBlock(
statementsWithIncludesApplied.concat(
this.helpers()
),
),
/*flags*/ts.NodeFlags.Namespace | ts.NodeFlags.ContextFlags,
);
};
}
interface Roots {
statements: ts.Statement[];
knownEnumNames: string[];
includes: {
[includer: string]: string;
}
} | the_stack |
import 'chrome://resources/polymer/v3_0/iron-selector/iron-selector.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {getDeepActiveElement} from 'chrome://resources/js/util.m.js';
import {IronSelectorElement} from 'chrome://resources/polymer/v3_0/iron-selector/iron-selector.js';
import {calculateSplices, html, PolymerElement, TemplateInstanceBase, templatize} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {BiMap} from './bimap.js';
export const NO_SELECTION: number = -1;
/**
* HTML class name used to recognize selectable items.
*/
const SELECTABLE_CLASS_NAME: string = 'selectable';
export const selectorNavigationKeys: readonly string[] =
Object.freeze(['ArrowUp', 'ArrowDown', 'Home', 'End']);
export interface InfiniteList {
$: {
selector: IronSelectorElement,
container: HTMLElement,
};
}
export class InfiniteList extends PolymerElement {
static get is() {
return 'infinite-list';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
maxHeight: {
type: Number,
observer: 'onMaxHeightChanged_',
},
items: {
type: Array,
observer: 'onItemsChanged_',
value: [],
},
};
}
maxHeight: number;
items: Array<Object>;
private instanceConstructors_:
Map<string,
new(args: {item: Object, index?: number}) =>
TemplateInstanceBase & HTMLElement>;
private instances_: Array<TemplateInstanceBase&HTMLElement>;
private selectableTypes_: Set<string>;
private selectableIndexToItemIndex_: BiMap<number, number>|null;
constructor() {
super();
/**
* A map of type names associated with constructors used for creating list
* item template instances.
*/
this.instanceConstructors_ = new Map();
/**
* An array of template instances each of which contain the HTMLElement
* associated with a given rendered item from the items array. The entries
* are ordered to match the item's index.
*/
this.instances_ = [];
/**
* A set of class names for which the selectable style class should be
* applied.
*/
this.selectableTypes_ = new Set();
/**
* Correlates the selectable item indexes to the `items` property indexes.
*/
this.selectableIndexToItemIndex_ = null;
}
ready() {
super.ready();
this.ensureTemplatized_();
this.addEventListener('scroll', () => this.onScroll_());
}
/**
* Create and insert as many DOM items as necessary to ensure all items are
* rendered.
*/
ensureAllDomItemsAvailable() {
if (this.items.length > 0) {
const shouldUpdateHeight = this.instances_.length !== this.items.length;
for (let i = this.instances_.length; i < this.items.length; i++) {
this.createAndInsertDomItem_(i);
}
if (shouldUpdateHeight) {
this.updateHeight_();
}
}
}
/**
* @param key Keyboard event key value.
* @param focusItem Whether to focus the selected item.
*/
navigate(key: string, focusItem?: boolean) {
const selector = this.$.selector;
if ((key === 'ArrowUp' && selector.selected === 0) || key === 'End') {
this.ensureAllDomItemsAvailable();
selector.selected = this.selectableIndexToItemIndex_!.size() - 1;
} else {
switch (key) {
case 'ArrowUp':
selector.selectPrevious();
break;
case 'ArrowDown':
selector.selectNext();
break;
case 'Home':
selector.selected = 0;
break;
case 'End':
this.$.selector.selected =
this.selectableIndexToItemIndex_!.size() - 1;
break;
}
}
if (focusItem) {
(selector.selectedItem as HTMLElement).focus({preventScroll: true});
}
}
ensureTemplatized_() {
// The user provided light-dom template(s) to use when stamping DOM items.
const templates = this.querySelectorAll('template');
assert(templates.length > 0, 'At least one template must be provided');
// Initialize a map of class names to template instance constructors. On
// inserting DOM nodes, a lookup will be performed against the map to
// determine the correct constructor to use for rendering a given class
// type.
templates.forEach(template => {
const className = assert(template.dataset['type']!);
if (template.dataset['selectable'] !== undefined) {
this.selectableTypes_.add(className);
}
const instanceProps = {
item: true,
// Selectable items require an `index` property to facilitate selection
// and navigation capabilities exposed through the `selected` and
// `selectedItem` properties, and the navigate method.
index: this.selectableTypes_.has(className),
};
this.instanceConstructors_.set(
className, templatize(template, this, {
parentModel: true,
instanceProps,
}) as {new (): TemplateInstanceBase & HTMLElement});
});
}
/**
* Create a DOM item and immediately insert it in the DOM tree. A reference is
* stored in the instances_ array for future item lifecycle operations.
*/
private createAndInsertDomItem_(index: number) {
const instance = this.createItemInstance_(index);
this.instances_[index] = assert(instance);
// Offset the insertion index to take into account the template elements
// that are present in the light DOM.
this.insertBefore(
instance.root, this.children[index + this.instanceConstructors_.size]!);
}
private createItemInstance_(itemIndex: number): TemplateInstanceBase
&HTMLElement {
const item = this.items[itemIndex]!;
const instanceConstructor =
assert(this.instanceConstructors_.get(item.constructor.name)!);
const itemSelectable = this.isItemSelectable_(item);
const args = itemSelectable ?
{item, index: this.selectableIndexToItemIndex_!.invGet(itemIndex)} :
{item};
const instance = new instanceConstructor(args);
if (itemSelectable) {
instance.children[0]!.classList.add(SELECTABLE_CLASS_NAME);
}
return instance;
}
/**
* @return The average DOM item height.
*/
private domItemAverageHeight_(): number {
// It must always be true that if this logic is invoked, there should be
// enough DOM items rendered to estimate an item average height. This is
// ensured by the logic that observes the items array.
const domItemCount = assert(this.instances_.length);
const lastDomItem = this.lastElementChild as HTMLElement;
return (lastDomItem.offsetTop + lastDomItem.offsetHeight) / domItemCount;
}
/**
* Create and insert as many DOM items as necessary to ensure the selectable
* item at the specified index is present.
*/
private ensureSelectableDomItemAvailable_(selectableItemIndex: number) {
const itemIndex =
this.selectableIndexToItemIndex_!.get(selectableItemIndex)!;
for (let i = this.instances_.length; i < itemIndex + 1; i++) {
this.createAndInsertDomItem_(i);
}
}
private getDomItem_(index: number): HTMLElement|undefined {
const instance = this.instances_[index];
if (instance === undefined) {
// TODO(crbug.com/1225247): Remove this after we root cause the issue.
console.error(`Unexpected call to non-existing instance index: ${
index}. Instance count: ${this.instances_.length}. Item count: ${
this.items.length}`);
return undefined;
}
return instance.children[0] as HTMLElement;
}
private getSelectableDomItem_(selectableItemIndex: number): HTMLElement
|undefined {
return this.getDomItem_(
this.selectableIndexToItemIndex_!.get(selectableItemIndex)!);
}
/**
* @return The number of items required to fill the current viewport.
*/
private viewportItemCount_(): number {
return Math.ceil(this.maxHeight / this.domItemAverageHeight_());
}
/**
* @return Whether DOM items were created or not.
*/
private fillViewHeight_(height: number): boolean {
const startTime = performance.now();
// Ensure we have added enough DOM items so that we are able to estimate
// item average height.
assert(this.items.length);
const initialDomItemCount = this.instances_.length;
if (initialDomItemCount === 0) {
this.createAndInsertDomItem_(0);
}
const desiredDomItemCount = Math.min(
Math.ceil(height / this.domItemAverageHeight_()), this.items.length);
// TODO(romanarora): Re-evaluate the average dom item height at given item
// insertion counts in order to determine more precisely the right number of
// items to render.
for (let i = this.instances_.length; i < desiredDomItemCount; i++) {
this.createAndInsertDomItem_(i);
}
// TODO(romanarora): Check if we have reached the desired height, and if not
// keep adding items.
if (initialDomItemCount !== desiredDomItemCount) {
performance.mark(`tab_search:infinite_list_view_updated:${
performance.now() - startTime}:metric_value`);
return true;
}
return false;
}
private isItemSelectable_(item: Object): boolean {
return this.selectableTypes_.has(item.constructor.name);
}
/**
* @return Whether a list item is selected and focused.
*/
private isItemSelectedAndFocused_(): boolean {
const selectedItemIndex = this.$.selector.selected;
if (selectedItemIndex !== undefined) {
const selectedItem =
this.getSelectableDomItem_(selectedItemIndex as number);
if (selectedItem === undefined) {
return false;
}
const deepActiveElement = getDeepActiveElement();
return selectedItem === deepActiveElement ||
(!!selectedItem.shadowRoot &&
selectedItem.shadowRoot.activeElement === deepActiveElement);
}
return false;
}
/**
* Handles key events when list item elements have focus.
*/
private onKeyDown_(e: KeyboardEvent) {
// Do not interfere with any parent component that manages 'shift' related
// key events.
if (e.shiftKey) {
return;
}
const selector = this.$.selector;
if (selector.selected === undefined) {
// No tabs matching the search text criteria.
return;
}
if (selectorNavigationKeys.includes(e.key)) {
this.navigate(e.key, true);
e.stopPropagation();
e.preventDefault();
}
}
/**
* Ensures that when the items property changes, only a chunk of the items
* needed to fill the current scroll position view are added to the DOM, thus
* improving rendering performance.
*/
private onItemsChanged_(newItems: Array<any>, oldItems: Array<any>) {
if (this.instanceConstructors_.size === 0) {
return;
}
if (newItems.length === 0) {
this.selectableIndexToItemIndex_ = new BiMap();
// If the new items array is empty, there is nothing to be rendered, so we
// remove any DOM items present.
this.removeDomItems_(0, this.instances_.length);
this.resetSelected_();
} else {
const itemSelectedAndFocused = this.isItemSelectedAndFocused_();
this.selectableIndexToItemIndex_ = new BiMap();
newItems.forEach((item, index) => {
if (this.isItemSelectable_(item)) {
this.selectableIndexToItemIndex_!.set(
this.selectableIndexToItemIndex_!.size(), index);
}
});
// If we had previously rendered some DOM items, we perform a partial
// update on them.
if (oldItems.length !== 0) {
// Update no more items than currently rendered and no less than what is
// required to fill the viewport.
const count =
Math.max(this.instances_.length, this.viewportItemCount_());
this.updateDomItems_(
newItems.slice(0, count), oldItems.slice(0, count));
}
this.fillViewHeight_(this.scrollTop + this.maxHeight);
// Since the new selectable items' length might be smaller than the old
// selectable items' length, we need to check if the selected index is
// still valid and if not adjust it.
const selector = this.$.selector;
if (selector.selected >= this.selectableIndexToItemIndex_!.size()) {
selector.selected = this.selectableIndexToItemIndex_!.size() - 1;
}
// Restore focus to the selected item if necessary.
if (itemSelectedAndFocused && selector.selected !== NO_SELECTION) {
this.getSelectableDomItem_(selector.selected as number)!.focus();
}
}
if (newItems.length !== oldItems.length) {
this.updateHeight_();
}
this.dispatchEvent(
new CustomEvent('viewport-filled', {bubbles: true, composed: true}));
}
private onMaxHeightChanged_(height: number) {
this.style.maxHeight = height + 'px';
}
/**
* Adds additional DOM items as needed to fill the view based on user scroll
* interactions.
*/
private onScroll_() {
const scrollTop = this.scrollTop;
if (scrollTop > 0 && this.instances_.length !== this.items.length) {
if (this.fillViewHeight_(scrollTop + this.maxHeight)) {
this.updateHeight_();
}
}
}
private updateDomItems_(newItems: Array<any>, oldItems: Array<any>) {
// Identify the differences between the original and new list of items.
// These are represented as splice objects containing removed and added
// item information at a given index. We leverage these splices to change
// only the affected items.
const splices = calculateSplices(newItems, oldItems);
for (const splice of splices) {
// If the splice applies to indices for which there are no instances yet
// there is no need to update them yet.
if (splice.index >= this.instances_.length) {
continue;
}
if (splice.addedCount === splice.removed.length) {
// If the number of added and removed items are equal, reuse the
// existing DOM instances and simply update their item binding.
const indexOfLastInstance =
Math.min(splice.index + splice.addedCount, this.instances_.length);
for (let i = splice.index; i < indexOfLastInstance; i++) {
// If the types don't match, we need to replace the existing instance.
if (oldItems[i].constructor !== newItems[i].constructor) {
this.getDomItem_(i)!.remove();
this.createAndInsertDomItem_(i);
continue;
}
(this.instances_[i] as unknown as {item: any}).item = newItems[i];
}
continue;
}
// For simplicity, if new items have been added, we remove the no longer
// accurate template instances following the splice index and allow the
// component to ensure the viewport is full. If no items were added, we
// simply remove the no longer existing items and update any following
// template instances.
// TODO(romanarora): Introduce a DOM item reuse pool for a more
// efficient update.
const removeCount = splice.addedCount !== 0 ?
this.instances_.length - splice.index :
splice.removed.length;
this.removeDomItems_(splice.index, removeCount);
}
// Update the index property of the selectable item instances as it may no
// longer be accurate after the splices have taken place.
this.updateSelectableItemInstanceIndexes_();
}
private removeDomItems_(index: number, count: number) {
this.instances_.splice(index, count).forEach(instance => {
this.removeChild(instance.children[0]!);
});
}
private updateSelectableItemInstanceIndexes_() {
for (let itemIndex = 0; itemIndex < this.instances_.length; itemIndex++) {
const selectableItemIndex =
this.selectableIndexToItemIndex_!.invGet(itemIndex);
if (selectableItemIndex !== undefined) {
(this.instances_[itemIndex] as unknown as {index: number}).index =
selectableItemIndex;
}
}
}
/**
* Sets the height of the component based on an estimated average DOM item
* height and the total number of items.
*/
private updateHeight_() {
const estScrollHeight = this.items.length > 0 ?
this.items.length * this.domItemAverageHeight_() :
0;
this.$.container.style.height = estScrollHeight + 'px';
}
/**
* Ensure the scroll view can fully display a preceding or following list item
* to the one selected, if existing.
*
* TODO(romanarora): Selection navigation behavior should be configurable. The
* approach followed below might not be desired by all component users.
*/
private onSelectedChanged_() {
const selector = this.$.selector;
if (selector.selected === undefined) {
return;
}
const selectedIndex = selector.selected;
if (selectedIndex === 0) {
this.scrollTo({top: 0, behavior: 'smooth'});
return;
}
if (selectedIndex === this.selectableIndexToItemIndex_!.size() - 1) {
this.getSelectableDomItem_(selectedIndex)!.scrollIntoView(
{behavior: 'smooth'});
return;
}
const previousItem =
this.getSelectableDomItem_((selector.selected as number) - 1)!;
if (previousItem.offsetTop < this.scrollTop) {
previousItem.scrollIntoView({behavior: 'smooth', block: 'nearest'});
return;
}
const nextItemIndex = (selector.selected as number) + 1;
if (nextItemIndex < this.selectableIndexToItemIndex_!.size()) {
this.ensureSelectableDomItemAvailable_(nextItemIndex);
const nextItem = this.getSelectableDomItem_(nextItemIndex)!;
if (nextItem.offsetTop + nextItem.offsetHeight >
this.scrollTop + this.offsetHeight) {
nextItem.scrollIntoView({behavior: 'smooth', block: 'nearest'});
}
}
}
/**
* Resets the selector's selection to the undefined state. This method
* suppresses a closure validation that would require modifying the
* IronSelectableBehavior's annotations for the selected property.
*/
private resetSelected_() {
this.$.selector.selected = undefined as unknown as string | number;
}
private selectableSelector_(): string {
return '.' + SELECTABLE_CLASS_NAME;
}
set selected(index: number) {
if (index === NO_SELECTION) {
this.resetSelected_();
return;
}
const selector = this.$.selector;
if (index !== selector.selected) {
assert(
index < this.selectableIndexToItemIndex_!.size(),
'Selection index is out of range.');
this.ensureSelectableDomItemAvailable_(index);
selector.selected = index;
}
}
/** @return The selected index or -1 if none selected. */
get selected(): number {
return this.$.selector.selected !== undefined ?
this.$.selector.selected as number :
NO_SELECTION;
}
get selectedItem(): Object|null {
if (this.$.selector.selected === undefined) {
return null;
}
return this.items[this.selectableIndexToItemIndex_!.get(
this.$.selector.selected as number)!]!;
}
}
declare global {
interface HTMLElementTagNameMap {
'infinite-list': InfiniteList;
}
}
customElements.define(InfiniteList.is, InfiniteList); | the_stack |
describe('jinqJS TypeScript Definition Suite', function() {
//'use strict'; //Disabled to allow one file to be used with client & node.js testing
enum SexEnum {
Male,
Female
}
interface IPerson {
Name: string;
Age: number;
Location: string;
Sex: SexEnum;
}
interface ISex {
Sex: SexEnum;
Location: string;
Title: string;
}
interface IPopulation {
Location: string;
People: number;
}
interface ITemp {
Location: string;
Temp: number;
}
interface IPersonPopulation extends IPerson, IPopulation {}
interface IPopulationTemp extends IPopulation, ITemp {}
interface IPersonSex extends IPerson, ISex { }
interface IPersonID extends IPerson {ID: number}
interface IPersonRowID extends IPerson { Row: number }
interface IHuman extends IPerson {IsHuman: boolean}
interface IOverTheHill extends jinqJsSafe.jinqJs { overTheHill(): jinqJsSafe.jinqJs; }
interface ISelectCustom extends jinqJsSafe.jinqJs { selectCustom<T>(field: string): T[]; }
var people1: IPerson[] = [
{ Name: 'Tom', Age: 29, Location: 'Port Jeff', Sex: SexEnum.Male },
{ Name: 'Jen', Age: 30, Location: 'Port Jeff', Sex: SexEnum.Female },
{ Name: 'Tom', Age: 14, Location: 'Port Jeff', Sex: SexEnum.Male },
{ Name: 'Diana', Age: 11, Location: 'Port Jeff', Sex: SexEnum.Female }
];
var people2: IPerson[] = [
{ Name: 'Tom', Age: 14, Location: 'Port Jeff', Sex: SexEnum.Male },
{ Name: 'Jane', Age: 20, Location: 'Smithtown', Sex: SexEnum.Female },
{ Name: 'Ken', Age: 57, Location: 'Islip', Sex: SexEnum.Male}
];
var people3: IPerson[] = [{ Name: 'Frank', Age: 1, Location: 'Melville', Sex: SexEnum.Male }];
var people4: IPerson[] = [{ Name: 'Frank', Age: 67, Location: 'Melville', Sex: SexEnum.Male }];
var sexType: ISex[] = [{ Sex: SexEnum.Male, Location: 'Islip', Title: 'Its a boy!' },
{ Sex: SexEnum.Female, Location: 'Islip', Title: 'Its a girl!' }];
var population: IPopulation[] = [
{ Location: 'Islip', People: 123 },
{ Location: 'Melville', People: 332 },
];
var temps: ITemp[] = [
{ Location: 'Islip', Temp: 85 }
];
var simpleAges1: number[] = [29, 2, 1, 57];
var simpleAges2: number[] = [14, 30, 1, 60];
var weatherSvc: string = 'http://api.openweathermap.org/data/2.5/weather?q=port%20jefferson,ny&appid=2de143494c0b295cca9337e1e96b00e0'
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
jinqJs = require('../../../jinqjs-unstable');
console.log('Testing node.js instance.');
}
else
console.log('Testing as client instance.');
describe('.from()', function() {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
it('sync', function() {
var result: IPerson[] = new jinqJs().from<IPerson>(people1).select<IPerson>();
expect(result .length).toEqual(4);
expect(result[0].Age).toEqual(29);
expect(result[3].Age).toEqual(11);
});
it('async', function(done) {
new jinqJs().from(weatherSvc, function(self) {
var resultAsync = self.select<any>();
expect(resultAsync.length).toEqual(1);
expect(resultAsync[0].coord.lat).toEqual(40.95);
done();
});
});
it('UNION All (Complex)', function() {
var result = new jinqJs().from<IPerson>(people1, people2, people3).select<IPerson>();
expect(result.length).toEqual(8);
expect(result[0].Age).toEqual(29);
expect(result[4].Age).toEqual(14);
expect(result[7].Age).toEqual(1);
});
it('UNION All (Simple)', function() {
var result = new jinqJs().from<number>(simpleAges1, simpleAges2).select<number>();
expect(result.length).toEqual(8);
expect(result[0]).toEqual(29);
expect(result[4]).toEqual(14);
});
});
describe('.concat()', function() {
it('(Complex)', function() {
var result = new jinqJs().from<IPerson>(people1).concat<IPerson>(people2, people3).select<IPerson>();
expect(result.length).toEqual(8);
expect(result[0].Age).toEqual(29);
expect(result[4].Age).toEqual(14);
expect(result[7].Age).toEqual(1);
});
it('(Simple)', function() {
var result = new jinqJs().from<number>(simpleAges1).concat<number>(simpleAges2, [88, 99]).select<number>();
expect(result.length).toEqual(10);
expect(result[0]).toEqual(29);
expect(result[4]).toEqual(14);
expect(result[8]).toEqual(88);
});
});
describe('.union()', function () {
it('(Complex)', function () {
var result = new jinqJs().from<IPerson>(people1).union<IPerson>(people2, people3).select<IPerson>();
expect(result.length).toEqual(7);
expect(result[0].Age).toEqual(29);
expect(result[2].Age).toEqual(14);
expect(result[4].Age).toEqual(20);
});
it('(Simple) Numbers', function () {
var result = new jinqJs().from<number>(simpleAges1).union<number>(simpleAges2, [30,50]).select();
expect(result.length).toEqual(8);
expect(result[0]).toEqual(29);
expect(result[6]).toEqual(60);
expect(result[7]).toEqual(50);
});
it('(Simple) Strings', function () {
var result = new jinqJs().from<string[]>(['Tom','Frank']).union<string>(['Bob', 'Tom' ], ['Chris']).select<string>();
expect(result.length).toEqual(4);
expect(result[0]).toEqual('Tom');
expect(result[3]).toEqual('Chris');
});
});
describe('.join() and .on()', function() {
it('(Complex - Single Collection)', function() {
var result = new jinqJs().from<IPerson[]>(people1).union<IPerson>(people2).join<IPopulation>(population).on('Location').select<IPopulation>();
expect(result.length).toEqual(1);
expect(result[0].People).toEqual(123);
});
it('(Complex - Multiple Collections)', function() {
var result = new jinqJs().from<IPerson>(people1).union<IPerson>(people2).join<any>(population, temps).on('Location').select<IPopulationTemp>();
expect(result.length).toEqual(1);
expect(result[0].People).toEqual(123);
expect(result[0].Temp).toEqual(85);
});
});
describe('.on()', function() {
it('(Complex - Multiple Columns)', function() {
var result = new jinqJs().from<IPerson[]>(people1).union<IPerson>(people2).join<ISex>(sexType).on('Location', 'Sex').select<IPersonSex>();
expect(result.length).toEqual(1);
expect(result[0].Title).toEqual('Its a boy!');
expect(result[0].Age).toEqual(57);
});
it('(Complex - Predicate - inner join)', function() {
var result = new jinqJs().from<IPerson[]>(people1, people2).join<ISex>(sexType).on<IPerson, ISex>(function(left, right) {
return left.Location === right.Location;
}).select<IPerson>();
//Multiple matches (Both are Male because its using the field from the left side collection)
expect(result.length).toEqual(2);
expect(result[0].Sex).toEqual(SexEnum.Male);
expect(result[1].Sex).toEqual(SexEnum.Male);
var result1 = new jinqJs().from<IPerson[]>(people1, people2).join<ISex>(sexType).on<IPerson, ISex>(function(left, right) {
return left.Location === right.Location && left.Sex === right.Sex;
}).select<IPersonSex>();
//Single match
expect(result1.length).toEqual(1);
expect(result1[0].Title).toEqual('Its a boy!');
expect(result1[0].Age).toEqual(57);
});
it('(Complex - Predicate - outer join)', function() {
var result = new jinqJs().from<IPerson[]>(people1, people2).leftJoin<ISex>(sexType).on<IPerson, ISex>(function(left, right) {
return left.Location === right.Location && left.Sex === right.Sex;
}).select<IPersonSex>();
expect(result.length).toEqual(7);
result = new jinqJs().from<IPerson>(people2).leftJoin<ISex>(sexType).on<IPerson, ISex>(function(left, right) {
return left.Location === right.Location && left.Sex === right.Sex;
}).select<IPersonSex>();
expect(result.length).toEqual(3);
expect(result[0].Age).toEqual(14);
expect(result[2].Age).toEqual(57);
expect(result[0].Title).toEqual('');
expect(result[1].Title).toEqual('');
expect(result[2].Title).toEqual('Its a boy!');
});
});
describe('.leftJoin()', function() {
it('Complex - Column', function() {
var result = new jinqJs().from<IPerson>(people2).leftJoin<IPopulation>(population).on('Location').select<IPopulation>();
expect(result.length).toEqual(3);
result = new jinqJs().from<IPopulation>(result).where('Location == Islip').select<IPopulation>();
expect(result[0].People).toEqual(123);
result = new jinqJs().from<IPerson>(people2).leftJoin<IPopulation>(population).on('Location').select<IPopulation>();
result = new jinqJs().from<IPopulation>(result).where('Location == Smithtown').select<IPopulation>();
expect(result[0].People).toEqual('');
});
it('Complex - Multiple Collections', function() {
var result = new jinqJs().from<IPerson>(people2).leftJoin<any>(population, temps).on('Location').select<IPopulationTemp>();
expect(result.length).toEqual(3);
expect(result[0].People).toEqual('');
expect(result[2].People).toEqual(123);
result = new jinqJs().from(result).where('Location == Islip').select<IPopulationTemp>();
expect(result[0].Temp).toEqual(85);
expect(result[0].People).toEqual(123);
result = new jinqJs().from<IPopulation>(people2).leftJoin<any>(population, temps).on('Location').select<IPopulationTemp>();
result = new jinqJs().from(result).where('Location == Smithtown').select<IPopulationTemp>();
expect(result[0].Temp).toEqual('');
expect(result[0].People).toEqual('');
});
it('Complex - Multiple Columns', function() {
var result = new jinqJs().from<IPerson>(people2).leftJoin<ISex>(sexType).on('Location', 'Sex').select<IPersonSex>();
expect(result.length).toEqual(3);
expect(result[0].Age).toEqual(14);
expect(result[2].Age).toEqual(57);
expect(result[0].Title).toEqual('');
expect(result[1].Title).toEqual('');
expect(result[2].Title).toEqual('Its a boy!');
result = new jinqJs().from<IPersonSex>(result).where('Location == Islip').select<IPersonSex>();
expect(result[0].Title).toEqual('Its a boy!');
result = new jinqJs().from<IPerson>(people2).leftJoin<ISex>(sexType).on('Location', 'Sex').select<IPersonSex>();
result = new jinqJs().from<IPersonSex>(result).where('Location == Smithtown').select<IPersonSex>();
expect(result[0].Title).toEqual('');
});
});
describe('.fullJoin()', function() {
it('Complex - Single Column', function() {
var result = new jinqJs().from<IPerson>(people2).fullJoin<IPopulation>(population).on('Location').select<IPopulationTemp>();
expect(result.length).toEqual(4);
expect(result[0].People).toEqual('');
expect(result[0].Location).toEqual('Port Jeff');
expect(result[1].People).toEqual('');
expect(result[2].People).toEqual(123);
expect(result[2].Location).toEqual('Islip');
expect(result[3].People).toEqual(332);
expect(result[3].Location).toEqual('Melville');
});
it('Complex - Multiple Columns', function() {
var result = new jinqJs().from<IPerson>(people2).fullJoin<ISex>(sexType).on('Sex', 'Location').select<IPersonSex>();
expect(result.length).toEqual(4);
expect(result[0].Title).toEqual('');
expect(result[2].Title).toEqual('Its a boy!');
expect(result[3].Title).toEqual('Its a girl!');
expect(result[3].Location).toEqual('Islip');
expect(result[3].Name).toBeNull();
});
});
describe('.in()', function() {
it('Complex - Complex to Complex (Single Column)', function() {
var result = new jinqJs().from<IPerson>(people1).in<IPerson>(people2, 'Name').select<IPerson>();
expect(result.length).toEqual(2);
});
it('Complex - Complex to Complex (Multiple Columns)', function() {
var result = new jinqJs().from<IPerson>(people1).in<IPerson>(people2, 'Name', 'Age').select<IPerson>();
expect(result.length).toEqual(1);
});
it('Complex - Complex to Simple (Single Column)', function() {
var result = new jinqJs().from<IPerson>(people1).in<string>(['Jen', 'Diana'], 'Name').select<IPerson>();
expect(result.length).toEqual(2);
});
it('Complex - Simple to Simple', function() {
var result = new jinqJs().from<number>([1, 2, 3, 4]).in<number>([3, 4, 5]).select<number>();
expect(result.length).toEqual(2);
});
describe('.not().in()', function() {
it('Complex - Complex to Complex (Single Column)', function() {
var result = new jinqJs().from<IPerson>(people1).not().in<IPerson>(people2, 'Name').select<IPerson>();
expect(result.length).toEqual(2);
expect(result[0].Age).toEqual(30);
expect(result[1].Age).toEqual(11);
});
it('Complex - Complex to Complex (Multiple Columns)', function() {
var result = new jinqJs().from<IPerson>(people1).not().in<IPerson>(people2, 'Name', 'Age').select<IPerson>();
expect(result.length).toEqual(3);
expect(result[0].Age).toEqual(29);
expect(result[1].Age).toEqual(30);
expect(result[2].Age).toEqual(11);
});
it('Complex - Complex to Simple (Single Column)', function() {
var result = new jinqJs().from<IPerson>(people1).not().in<string>(['Jen', 'Tom'], 'Name').select<IPerson>();
expect(result.length).toEqual(1);
expect(result[0].Name).toEqual('Diana');
});
it('Complex - Simple to Simple', function() {
var result = new jinqJs().from<number>([1, 2, 3, 4]).not().in<number>([2, 3, 4, 5]).select();
expect(result.length).toEqual(1);
expect(result[0]).toEqual(1);
});
});
});
describe('.where()', function() {
it('Complex - Multiple Simple Conditions', function() {
var result = new jinqJs().from<IPerson>(people1).where('Age < 20', 'Sex == ' + SexEnum.Male).select<IPerson>();
expect(result.length).toEqual(1);
expect(result[0].Age).toEqual(14);
});
it('Complex - Predicate Using row & index', function() {
var result = new jinqJs().from<IPerson>(people1).where<IPerson>( (row: IPerson, index: number) => { return index === 1 && row.Name === 'Jen'; }).select<IPerson>();
expect(result.length).toEqual(1);
expect(result[0].Age).toEqual(30);
});
it('Simple - Predicate Using row & index', function() {
var result = new jinqJs().from<number>([1, 2, 3, 4, 5, 6]).where<number>( (row: number, index: number) => { return row % 2 === 0; }).select();
expect(result.length).toEqual(3);
expect(result[0]).toEqual(2);
});
it('Simple - Simple Condition Using Contains', function() {
var result = new jinqJs().from<IPerson>(people1).where('Name * om').select<IPerson>();
expect(result.length).toEqual(2);
expect(result[0].Name === 'Tom' && result[1].Name === 'Tom').toBeTruthy();
});
it('Simple - Predicate Using row & index with the filter()', function() {
var result = new jinqJs().from<number>([1, 2, 3, 4, 5, 6]).filter<number>( (row: number, index: number) => { return row % 2 === 0; }).select();
expect(result.length).toEqual(3);
expect(result[0]).toEqual(2);
});
});
describe('.groupBy()', function() {
describe('.sum()', function() {
it('Complex - Multiple Columns', function() {
var result = new jinqJs().from<IPerson>(people1).groupBy('Name', 'Age').sum('Age').select<IPerson>();
expect(result.length).toEqual(4);
result = new jinqJs().from<IPerson>(result).where('Name == Tom').select<IPerson>();
expect(result.length).toEqual(2);
expect(result[0].Age === 29 && result[1].Age === 14).toBeTruthy();
});
it('Complex - Multiple Columns & Multiple Aggregate Columns', function() {
var result = new jinqJs().from<IPerson>(people2, people3, people4).leftJoin<IPopulation>(population).on('Location').groupBy('Name', 'Age').sum('Age', 'People').select<IPersonPopulation>();
expect(result.length).toEqual(5);
result = new jinqJs().from(result).where('Name == Frank').select<IPersonPopulation>();
expect(result.length).toEqual(2);
expect(result[0].Age === 1 && result[0].People === 332 && result[1].Age === 67 && result[1].People === 332).toBeTruthy();
});
it('Complex - Single Columns & Multiple Aggregate Columns', function() {
var result = new jinqJs().from<IPerson>(people2, people3, people4).leftJoin<IPopulation>(population).on('Location').groupBy('Name').sum('Age', 'People').select<IPersonPopulation>();
expect(result.length).toEqual(4);
result = new jinqJs().from(result).where('Name == Frank').select<IPersonPopulation>();
expect(result.length).toEqual(1);
expect(result[0].Age === 68 && result[0].People === 664).toBeTruthy();
});
it('Complex - Single Column', function() {
var result = new jinqJs().from<IPerson>(people1).groupBy('Name').sum('Age').select<IPerson>();
expect(result.length).toEqual(3);
result = new jinqJs().from(result).where('Name == Tom').select<IPerson>();
expect(result.length).toEqual(1);
expect(result[0].Age).toEqual(29 + 14);
});
it('Simple', function() {
var result = new jinqJs().from<number>([1, 2, 3, 4, 5]).sum().select();
expect(result.length).toEqual(1);
expect(result[0]).toEqual(15);
});
});
describe('.min()', function() {
it('Complex - Multiple Columns', function() {
var result = new jinqJs().from<IPerson>(people1).groupBy('Name', 'Age').min('Age').select<IPerson>();
expect(result.length).toEqual(4);
result = new jinqJs().from(result).where('Name == Tom').select<IPerson>();
expect(result.length).toEqual(2);
expect(result[0].Age === 29 && result[1].Age === 14).toBeTruthy();
});
it('Complex - Multiple Columns & Multiple Aggregate Columns', function() {
var result = new jinqJs().from<IPerson>(people2, people3, people4).leftJoin<IPopulation>(population).on('Location').groupBy('Name', 'Age').min('Age', 'People').select<IPersonPopulation>();
expect(result.length).toEqual(5);
result = new jinqJs().from(result).where('Name == Frank').select<IPersonPopulation>();
expect(result.length).toEqual(2);
expect(result[0].Age === 1 && result[0].People === 332 && result[1].Age === 67 && result[1].People === 332).toBeTruthy();
});
it('Complex - Single Columns & Multiple Aggregate Columns', function() {
var result = new jinqJs().from<IPerson>(people2, people3, people4).leftJoin<IPopulation>(population).on('Location').groupBy('Name').min('Age', 'People').select<IPersonPopulation>();
expect(result.length).toEqual(4);
result = new jinqJs().from(result).where('Name == Frank').select<IPersonPopulation>();
expect(result.length).toEqual(1);
expect(result[0].Age === 1 && result[0].People === 332).toBeTruthy();
});
it('Complex - Single Column', function() {
var result = new jinqJs().from<IPerson>(people1).groupBy('Name').min('Age').select<IPerson>();
expect(result.length).toEqual(3);
result = new jinqJs().from(result).where('Name == Tom').select<IPerson>();
expect(result.length).toEqual(1);
expect(result[0].Age).toEqual(14);
});
it('Simple', function() {
var result = new jinqJs().from<number>([2, 1, 3, 4, 5]).min().select<number>();
expect(result.length).toEqual(1);
expect(result[0]).toEqual(1);
});
});
describe('.max()', function() {
it('Complex - Multiple Columns', function() {
var result = new jinqJs().from<IPerson>(people1).groupBy('Name', 'Age').max('Age').select<IPerson>();
expect(result.length).toEqual(4);
result = new jinqJs().from(result).where('Name == Tom').select<IPerson>();
expect(result.length).toEqual(2);
expect(result[0].Age === 29 && result[1].Age === 14).toBeTruthy();
});
it('Complex - Multiple Columns & Multiple Aggregate Columns', function() {
var result = new jinqJs().from<IPerson>(people2, people3, people4).leftJoin<IPopulation>(population).on('Location').groupBy('Name', 'Age').max('Age', 'People').select<IPersonPopulation>();
expect(result.length).toEqual(5);
result = new jinqJs().from(result).where('Name == Frank').select<IPersonPopulation>();
expect(result.length).toEqual(2);
expect(result[0].Age === 1 && result[0].People === 332 && result[1].Age === 67 && result[1].People === 332).toBeTruthy();
});
it('Complex - Single Columns & Multiple Aggregate Columns', function() {
var result = new jinqJs().from<IPerson>(people2, people3, people4).leftJoin<IPopulation>(population).on('Location').groupBy('Name').max('Age', 'People').select<IPersonPopulation>();
expect(result.length).toEqual(4);
result = new jinqJs().from(result).where('Name == Frank').select<IPersonPopulation>();
expect(result.length).toEqual(1);
expect(result[0].Age === 67 && result[0].People === 332).toBeTruthy();
});
it('Complex - Single Column', function() {
var result = new jinqJs().from<IPerson>(people1).groupBy('Name').max('Age').select<IPerson>();
expect(result.length).toEqual(3);
result = new jinqJs().from(result).where('Name == Tom').select<IPerson>();
expect(result.length).toEqual(1);
expect(result[0].Age).toEqual(29);
});
it('Simple', function() {
var result = new jinqJs().from([2, 1, 3, 4, 5]).max().select();
expect(result.length).toEqual(1);
expect(result[0]).toEqual(5);
});
});
describe('.avg()', function() {
it('Complex - Multiple Columns', function() {
var result = new jinqJs().from<IPerson>(people1).groupBy('Name', 'Age').avg('Age').select<IPerson>();
expect(result.length).toEqual(4);
result = new jinqJs().from(result).where('Name == Tom').select<IPerson>();
expect(result.length).toEqual(2);
expect(result[0].Age === 29 && result[1].Age === 14).toBeTruthy();
});
it('Complex - Multiple Columns & Multiple Aggregate Columns', function() {
var result = new jinqJs().from<IPerson>(people2, people3, people4).leftJoin<IPopulation>(population).on('Location').groupBy('Name', 'Age').avg('Age', 'People').select<IPersonPopulation>();
expect(result.length).toEqual(5);
result = new jinqJs().from(result).where('Name == Frank').select<IPersonPopulation>();
expect(result.length).toEqual(2);
expect(result[0].Age === 1 && result[0].People === 332 && result[1].Age === 67 && result[1].People === 332).toBeTruthy();
});
it('Complex - Single Columns & Multiple Aggregate Columns', function() {
var result = new jinqJs().from<IPerson>(people2, people3, people4).leftJoin<IPopulation>(population).on('Location').groupBy('Name').avg('Age', 'People').select<IPersonPopulation>();
expect(result.length).toEqual(4);
result = new jinqJs().from(result).where('Name == Frank').select<IPersonPopulation>();
expect(result.length).toEqual(1);
expect(result[0].Age === 34 && result[0].People === 332).toBeTruthy();
});
it('Complex - Single Column', function() {
var result = new jinqJs().from<IPerson>(people1).groupBy('Name').avg('Age').select<IPerson>();
expect(result.length).toEqual(3);
result = new jinqJs().from(result).where('Name == Tom').select<IPerson>();
expect(result.length).toEqual(1);
expect(result[0].Age).toEqual(21.5);
});
it('Simple', function() {
var result = new jinqJs().from([2, 1, 3, 4, 5]).avg().select();
expect(result.length).toEqual(1);
expect(result[0]).toEqual(3);
});
});
describe('.count()', function() {
it('Complex - Multiple Columns', function() {
var result = new jinqJs().from<IPerson>(people1).groupBy('Name', 'Age').count('Age').select<IPerson>();
expect(result.length).toEqual(4);
result = new jinqJs().from(result).where('Name == Tom').select<IPerson>();
expect(result.length).toEqual(2);
expect(result[0].Age === 1 && result[1].Age === 1).toBeTruthy();
});
it('Complex - Multiple Columns & Multiple Aggregate Columns', function() {
var result = new jinqJs().from<IPerson>(people2, people3, people4).leftJoin<IPopulation>(population).on('Location').groupBy('Name', 'Age').count('Age', 'People').select<IPersonPopulation>();
expect(result.length).toEqual(5);
result = new jinqJs().from(result).where('Name == Frank').select<IPersonPopulation>();
expect(result.length).toEqual(2);
expect(result[0].Age === 1 && result[0].People === 1 && result[1].Age === 1 && result[1].People === 1).toBeTruthy();
});
it('Complex - Single Columns & Multiple Aggregate Columns', function() {
var result = new jinqJs().from<IPerson>(people2, people3, people4).leftJoin<IPopulation>(population).on('Location').groupBy('Name').count('Age', 'People').select<IPersonPopulation>();
expect(result.length).toEqual(4);
result = new jinqJs().from(result).where('Name == Frank').select<IPersonPopulation>();
expect(result.length).toEqual(1);
expect(result[0].Age === 2 && result[0].People === 2).toBeTruthy();
});
it('Complex - Single Column', function() {
var result = new jinqJs().from<IPerson>(people1).groupBy('Name').count('Age').select<IPerson>();
expect(result.length).toEqual(3);
result = new jinqJs().from(result).where('Name == Tom').select<IPerson>();
expect(result.length).toEqual(1);
expect(result[0].Age).toEqual(2);
});
});
describe('.distinct()', function() {
it('Complex - Single Column', function() {
var result = new jinqJs().from(people1).distinct('Location').select();
expect(result.length).toEqual(1);
});
it('Complex - Multiple Columns', function() {
var result = new jinqJs().from(people1).distinct('Name', 'Location').select();
expect(result.length).toEqual(3);
result = new jinqJs().from(result).where('Name == Tom').select();
expect(result.length).toEqual(1);
});
it('Complex - Array of Columns', function() {
var result = new jinqJs().from<IPerson>(people1).distinct(['Name', 'Location']).select<IPerson>();
expect(result.length).toEqual(3);
result = new jinqJs().from(result).where('Name == Tom').select<IPerson>();
expect(result.length).toEqual(1);
});
it('Simple', function() {
var result = new jinqJs().from([1, 2, 2, 3, 4, 3, 5]).distinct().select();
expect(result.length).toEqual(5);
expect(result[0]).toEqual(1);
expect(result[4]).toEqual(5);
});
});
});
describe('.orderBy()', function() {
it('Complex - Multiple Columns Simple', function() {
var result = new jinqJs().from<IPerson>(people1).orderBy('Name', 'Age').select<IPerson>();
expect(result[0].Name === 'Diana').toBeTruthy();
expect(result[2].Name === 'Tom' && result[2].Age === 14).toBeTruthy();
});
it('Complex - Multiple Columns Complex [field only]', function() {
var result = new jinqJs().from<IPerson>(people1).orderBy([{ field: 'Name' }, { field: 'Age' }]).select<IPerson>();
expect(result[0].Name === 'Diana').toBeTruthy();
expect(result[2].Name === 'Tom' && result[2].Age === 14).toBeTruthy();
});
it('Complex - Multiple Columns Complex [field by name & sort]', function() {
var result = new jinqJs().from<IPerson>(people1).orderBy([{ field: 'Name' }, { field: 'Age', sort: 'desc' }]).select<IPerson>();
expect(result[0].Name === 'Diana').toBeTruthy();
expect(result[2].Name === 'Tom' && result[2].Age === 29).toBeTruthy();
});
it('Complex - Multiple Columns Complex [field by positional # & sort]', function() {
var result = new jinqJs().from<IPerson>(people1).orderBy([{ field: 0, sort: 'asc' }, { field: 1, sort: 'desc' }]).select<IPerson>();
expect(result[0].Name === 'Diana').toBeTruthy();
expect(result[2].Name === 'Tom' && result[2].Age === 29).toBeTruthy();
});
it('Simple - Ascending Numbers', function() {
var result = new jinqJs().from([4, 2, 8, 1, 3]).orderBy([{ sort: 'asc' }]).select();
expect(result[0] === 1 && result[4] === 8).toBeTruthy();
});
it('Simple - Descending String', function() {
var result = new jinqJs().from(['Anna', 'Zillow', 'Mike']).orderBy([{ sort: 'desc' }]).select();
expect(result[0] === 'Zillow' &&
result[2] === 'Anna').toBeTruthy();
});
});
describe('.identity()', function() {
it('Complex - No Column', function() {
var result = new jinqJs().from<IPerson>(people1, people2).identity().select<IPersonID>();
expect(result.length).toEqual(7);
expect(result[0].ID).toEqual(1);
expect(result[6].ID).toEqual(7);
});
it('Complex - With Column', function() {
var result = new jinqJs().from<IPerson>(people1, people2).identity('Row').select<IPersonRowID>();
expect(result.length).toEqual(7);
expect(result[0].Row).toEqual(1);
expect(result[6].Row).toEqual(7);
});
it('Simple - No Column', function() {
var result = new jinqJs().from<number>(simpleAges1, simpleAges2).identity().select();
expect(result.length).toEqual(8);
expect((<any>result[0]).ID).toEqual(1);
expect((<any>result[7]).ID).toEqual(8);
});
it('Simple - With Column', function() {
var result = new jinqJs().from<number>(simpleAges1, simpleAges2).identity('Row').select();
expect(result.length).toEqual(8);
expect((<any>result[0]).Row).toEqual(1);
expect((<any>result[7]).Row).toEqual(8);
});
it('Global Identity Setting', function() {
new jinqJs({ includeIdentity: true });
var result = new jinqJs().from<number>(simpleAges1, simpleAges2).select();
expect(result.length).toEqual(8);
expect((<any>result[0]).ID).toEqual(1);
expect((<any>result[7]).ID).toEqual(8);
new jinqJs({ includeIdentity: false });
});
});
describe('.skip()', function() {
it('Complex - Fixed Number', function() {
var result = new jinqJs().from<IPerson>(people1).skip(3).select<IPerson>();
expect(result.length).toEqual(1);
expect(result[0].Age).toEqual(11);
});
it('Complex - Percent', function() {
var result = new jinqJs().from<IPerson>(people1).skip(.25).select<IPerson>();
expect(result.length).toEqual(3);
expect(result[0].Age).toEqual(30);
expect(result[2].Age).toEqual(11);
});
it('Simple - Fixed Number', function() {
var result = new jinqJs().from<string>(['Tom', 'Jen', 'Diana', 'Sandy']).skip(2).select();
expect(result.length).toEqual(2);
expect(result[0]).toEqual('Diana');
expect(result[1]).toEqual('Sandy');
});
it('Simple - Percent', function() {
var result = new jinqJs().from<string>(['Tom', 'Jen', 'Diana', 'Sandy']).skip(.75).select();
expect(result.length).toEqual(1);
expect(result[0]).toEqual('Sandy');
});
});
describe('.top()', function() {
it('Complex - Fixed Number', function() {
var result = new jinqJs().from<IPerson>(people1).top(2).select<IPerson>();
expect(result.length).toEqual(2);
expect(result[0].Age).toEqual(29);
expect(result[1].Age).toEqual(30);
});
it('Complex - Percent', function() {
var result = new jinqJs().from<IPerson>(people1).top(.75).select<IPerson>();
expect(result.length).toEqual(3);
expect(result[0].Age).toEqual(29);
expect(result[2].Age).toEqual(14);
});
it('Simple - Fixed Number', function() {
var result = new jinqJs().from<string>(['Tom', 'Jen', 'Diana', 'Sandy']).top(2).select();
expect(result.length).toEqual(2);
expect(result[0]).toEqual('Tom');
expect(result[1]).toEqual('Jen');
});
it('Simple - Percent', function() {
var result = new jinqJs().from<string>(['Tom', 'Jen', 'Diana', 'Sandy']).top(.75).select();
expect(result.length).toEqual(3);
expect(result[0]).toEqual('Tom');
expect(result[2]).toEqual('Diana');
});
});
describe('.bottom()', function() {
it('Complex - Fixed Number', function() {
var result = new jinqJs().from<IPerson>(people1).bottom(2).select<IPerson>();
expect(result.length).toEqual(2);
expect(result[0].Age).toEqual(14);
expect(result[1].Age).toEqual(11);
});
it('Complex - Percent', function() {
var result = new jinqJs().from<IPerson>(people1).bottom(.75).select<IPerson>();
expect(result.length).toEqual(3);
expect(result[0].Age).toEqual(30);
expect(result[2].Age).toEqual(11);
});
it('Simple - Fixed Number', function() {
var result = new jinqJs().from<string>(['Tom', 'Jen', 'Diana', 'Sandy']).bottom(2).select();
expect(result.length).toEqual(2);
expect(result[0]).toEqual('Diana');
expect(result[1]).toEqual('Sandy');
});
it('Simple - Percent', function() {
var result = new jinqJs().from<string>([8, 4, 2, 7]).bottom(.75).select();
expect(result.length).toEqual(3);
expect(result[0]).toEqual(4);
expect(result[2]).toEqual(7);
});
});
//TODO: SELECT STATEMENTS!!!!!
describe('.select()', function() {
it('Complex - Predicate Using row & index', function() {
var result = new jinqJs().from<IPerson>(people1).select( (row, index) => {
(<any>row).index = index + 1;
return row;
});
expect(result.length).toEqual(4);
expect((<any>result[0]).index).toEqual(1);
expect((<any>result[3]).index).toEqual(4);
});
it('Complex - Multiple Specific String Columns', function() {
var result = new jinqJs().from<IPerson>(people1).select<IPerson>('Age', 'Name');
expect(result.length).toEqual(4);
expect(result[0].Age).toEqual(29);
expect(result[0].Name).toEqual('Tom');
expect(result[0].Location).toBeUndefined();
});
it('Complex - Complex Array Object - Constant Column', function() {
var result = new jinqJs().from<IPerson>(people1).select<IHuman>([{ field: 'Age' }, { field: 'Name' }, { text: 'IsHuman', value: true }]);
expect(result.length).toEqual(4);
expect(result[0].Age).toEqual(29);
expect(result[0].Name).toEqual('Tom');
expect(result[0].Location).toBeUndefined();
expect(result[0].IsHuman).toBeTruthy();
});
it('Complex - Complex Array Object - Calculated Column', function() {
var result = new jinqJs().from<IPerson>(people1).select<IHuman>([{ field: 'Age' }, { field: 'Name' }, {
text: 'IsHuman', value: (row: IHuman) => {
row.IsHuman = true;
return row;
}
}]);
expect(result.length).toEqual(4);
expect(result[0].Age).toEqual(29);
expect(result[0].Name).toEqual('Tom');
expect(result[0].Location).toBeUndefined();
expect(result[0].IsHuman).toBeTruthy();
});
it('Complex - Complex Array Object - Change field text', function() {
var result = new jinqJs().from(people1).select<IPerson>([{ field: 'Age' }, { field: 'Name', text: 'Title' }]);
expect(result.length).toEqual(4);
expect(result[0].Age).toEqual(29);
expect(result[0].Name).toBeUndefined();
expect((<any>result[0]).Title).toEqual('Tom');
});
it('Simple - Converting a string array to a collection', function() {
var result = new jinqJs().from<string>(['Tom', 'Jen', 'Sandy']).select<IPerson>([{ text: 'Name' }]);
expect(result.length).toEqual(3);
expect(result[0].Name).toEqual('Tom');
});
it('Key/Value - Converting to collections using positional', function() {
var result = new jinqJs().from<any>([{ "john": 28 }, { "bob": 34 }, { "joe": 4 }]).select<any>([{ field: 0, text: 'Ages' }]);
expect(result.length).toEqual(3);
expect(result[0].Ages).toEqual(28);
});
});
describe('Extensibility', function() {
it('Plugin - Chaining', function() {
jinqJs.addPlugin('overTheHill', function(result) {
'use strict';
for (var i = result.length - 1; i > -1; i--) {
if (result[i].Age < 40)
result.splice(i, 1)
}
//Must return this when chaining functions.
return this;
});
var jinq = new jinqJs().from(people2) as IOverTheHill;
var result = jinq.overTheHill().select<IPerson>();
expect(result.length).toEqual(1);
expect(result[0].Age).toEqual(57);
});
it('Plugin - Parameters, Storage', function() {
jinqJs.addPlugin('selectCustom', function(result, args, store) {
'use strict';
store.timesCalled = store.timesCalled || 0;
store.timesCalled++;
if (store.timesCalled === 1) {
result.push({
Name: args[0],
TimesCalled: store.timesCalled
});
}
else {
result[result.length - 1].TimesCalled = store.timesCalled;
}
//Return array when ending with the jinqJs chain.
return result;
});
var jinq = new jinqJs().from(people2) as ISelectCustom;
var result = jinq.selectCustom<any>('Sample');
expect(result.length).toEqual(4);
expect(result[3].Name).toEqual('Sample');
expect(result[3].TimesCalled).toEqual(1);
result = jinq.selectCustom('Sample');
expect(result.length).toEqual(4);
expect(result[3].Name).toEqual('Sample');
expect(result[3].TimesCalled).toEqual(2);
});
});
describe('.update().at()', function() {
it('Simple - In-Place Update .at() with no Parameters.', function() {
var data = JSON.parse(JSON.stringify(people1));
new jinqJs()
.from(data)
.update<IPerson>( (coll, index) => { coll[index].Location = 'Port Jeff Sta.'; return null; } )
.at();
expect(data.length).toEqual(4);
expect(data[0].Location).toEqual('Port Jeff Sta.');
expect(data[1].Location).toEqual('Port Jeff Sta.');
expect(data[2].Location).toEqual('Port Jeff Sta.');
expect(data[3].Location).toEqual('Port Jeff Sta.');
});
it('Simple - Upate/Delete primitive types.', function() {
var simple = [3, 5, 4, 1, 2, 8, 4];
var data = new jinqJs()
.from(simple)
.distinct()
.delete()
.at<number>( (coll, index) => { return coll[index] <= 3; })
.orderBy([{ sort: 'asc' }])
.update<number>((coll, index) => { coll[index] = coll[index] + 100; return null;})
.at(function(coll, index) { return index % 2 === 0; })
.select();
expect(data.length).toEqual(3);
expect(data[0]).toEqual(104);
expect(data[1]).toEqual(5);
expect(data[2]).toEqual(108);
});
it('Simple - In-Place Update .at() with single string Parameter.', function() {
var data = JSON.parse(JSON.stringify(people1));
new jinqJs() //Sample doing in-place update
.from<IPerson>(data)
.update<IPerson>((coll, index) => { coll[index].Name = 'Thomas'; return null;})
.at('Name = Tom');
expect(data.length).toEqual(4);
expect(data[0].Name).toEqual('Thomas');
expect(data[1].Name).toEqual('Jen');
expect(data[2].Name).toEqual('Thomas');
});
it('Simple - In-Place Update .at() with multiple string Parameters.', function() {
var data = JSON.parse(JSON.stringify(people1));
new jinqJs() //Sample doing in-place update
.from<IPerson>(data)
.update<IPerson>((coll, index) => { coll[index].Name = 'Thomas'; return null;})
.at('Name = Tom', 'Age = 29');
expect(data.length).toEqual(4);
expect(data[0].Name).toEqual('Thomas');
expect(data[1].Name).toEqual('Jen');
expect(data[2].Name).toEqual('Tom');
});
it('Complex - Update with .at() predicate updating rows from a join returning results.', function() {
var result = new jinqJs()
.from<IPerson>(people1)
.join<ISex>(sexType)
.on('Sex')
.where('Age < 30')
.update<IPerson>((coll, index) => { coll[index].Name = 'Thomas'; return null;})
.at<IPerson> ( (coll, index) => { return (index === 1 && coll[index].Age === 14); })
.select<IPerson>();
expect(result.length).toEqual(3);
expect(result[0].Name).toEqual('Tom');
expect(result[1].Name).toEqual('Thomas');
expect(result[2].Name).toEqual('Diana');
});
});
describe('.delete().at()', function() {
it('Complex - with .at() with a single parameter.', function() {
var result = new jinqJs()
.from<IPerson>(people1)
.join<ISex>(sexType)
.on('Sex')
.where('Age < 30')
.update<IPerson>( (coll, index) => { coll[index].Name = 'Thomas'; return null; })
.at<IPerson>( (coll, index) => { return (index === 1 && coll[index].Age === 14); })
.delete()
.at('Age = 11')
.select<IPerson>();
expect(result.length).toEqual(2);
expect(result[0].Age).toEqual(29);
expect(result[1].Age).toEqual(14);
});
});
}); | the_stack |
import {
BigNumber,
BigNumberish,
ContractTransaction,
PayableOverrides,
Signer,
} from 'ethers'
import { HardhatRuntimeEnvironment } from 'hardhat/types'
import moment from 'moment'
import { getNativeToken } from '../../config'
import { getPrice } from '../../tasks'
import {
ERC20,
ITellerDiamond,
MainnetNFTFacetMock,
TellerNFT,
TellerNFTV2,
} from '../../types/typechain'
import { getFunds } from './get-funds'
import { mockCRAResponse } from './mock-cra-response'
import { mergeV2IDsToBalances, mintNFTV1, mintNFTV2, V2Balances } from './nft'
export enum LoanType {
ZERO_COLLATERAL,
UNDER_COLLATERALIZED,
OVER_COLLATERALIZED,
}
export interface LoanHelpersReturn {
diamond: ITellerDiamond
details: PromiseReturnType<typeof loanDetails>
repay: (amount: BigNumberish, from?: Signer) => ReturnType<typeof repayLoan>
escrowRepay: (
amount: BigNumberish,
from?: Signer
) => ReturnType<typeof escrowRepayLoan>
collateral: {
needed: () => ReturnType<typeof collateralNeeded>
current: () => ReturnType<typeof collateralCurrent>
deposit: (
amount: BigNumberish,
from?: Signer
) => ReturnType<typeof depositCollateral>
withdraw: (
amount: BigNumberish,
from?: Signer
) => ReturnType<typeof withdrawCollateral>
}
}
export const loanHelpers = async (
hre: HardhatRuntimeEnvironment,
loanID: string
): Promise<LoanHelpersReturn> => {
const { contracts } = hre
const diamond = await contracts.get<ITellerDiamond>('TellerDiamond')
const details = await loanDetails(hre, loanID)
return {
diamond,
details,
repay: (amount: BigNumberish, from?: Signer) =>
repayLoan({ diamond, details, amount, from }),
escrowRepay: (amount: BigNumberish, from?: Signer) =>
escrowRepayLoan({ diamond, details, amount, from }),
collateral: {
needed: () => collateralNeeded({ diamond, details }),
current: () => collateralCurrent({ diamond, details }),
deposit: (amount: BigNumberish, from?: Signer) =>
depositCollateral(hre, { diamond, details, amount, from }),
withdraw: (amount: BigNumberish, from?: Signer) =>
withdrawCollateral({ diamond, details, amount, from }),
},
}
}
interface CreateLoanWithNftArgs {
lendToken: string | ERC20
borrower: Signer
deployer?: string
amount?: BigNumberish
amountBN?: BigNumberish
duration?: moment.Duration
version: 1 | 2 | 3
}
export interface CreateLoanArgs {
lendToken: string | ERC20
collToken: string | ERC20
loanType: LoanType
amount?: BigNumberish
amountBN?: BigNumberish
borrower?: string
duration?: moment.Duration
nft?: boolean
}
export interface CreateLoanReturn {
tx: Promise<ContractTransaction>
getHelpers: () => Promise<LoanHelpersReturn>
}
// export const createLoan = async (
// hre: HardhatRuntimeEnvironment,
// args: CreateLoanArgs
// ): Promise<CreateLoanReturn> => {
// const {
// lendToken,
// collToken,
// loanType,
// amount = 100,
// amountBN,
// duration = moment.duration(1, 'day'),
// } = args
// const { contracts, tokens, getNamedAccounts, toBN } = hre
// const diamond = await contracts.get<ITellerDiamond>('TellerDiamond')
// const lendingToken =
// typeof lendToken === 'string' ? await tokens.get(lendToken) : lendToken
//
// const collateralToken =
// typeof collToken === 'string' ? await tokens.get(collToken) : collToken
// const borrower = args.borrower ?? (await getNamedAccounts()).borrower
// const loanAmount = amountBN ?? toBN(amount, await lendingToken.decimals())
// // Set up collateral
// let collateralRatio = 0
//
// switch (loanType) {
// case LoanType.ZERO_COLLATERAL:
// break
// case LoanType.UNDER_COLLATERALIZED:
// collateralRatio = 5000
// break
// case LoanType.OVER_COLLATERALIZED:
// collateralRatio = 15000
// break
// }
// // Get mock cra request and response
// const craReturn = await mockCRAResponse(hre, {
// lendingToken: lendingToken.address,
// loanAmount,
// loanTermLength: duration.asSeconds(),
// collateralRatio: collateralRatio,
// interestRate: '400',
// borrower,
// })
// // Create loan with terms
// const tx = diamond
// .connect(hre.ethers.provider.getSigner(borrower))
// .createLoanWithTerms(
// craReturn.request,
// [craReturn.responses],
// collateralToken.address,
// '0'
// )
// return {
// tx,
// getHelpers: async (): Promise<LoanHelpersReturn> => {
// await tx
// const allBorrowerLoans = await diamond.getBorrowerLoans(borrower)
// const loanID = allBorrowerLoans[allBorrowerLoans.length - 1].toString()
// return await loanHelpers(hre, loanID)
// },
// }
// }
/**
* @description: function helper that sets the collateral token and ratio and creates a mock CRA
* response to plug into the newly merged create loan function that:
* - sets the terms
* - deposits collateral
* - takes out the loan
*
* @param args: CreateLoanArgs parameters to create the loan
* @returns: Promise<CreateLoanReturn> helper variables to help run our tests
*/
export const takeOutLoanWithoutNfts = async (
hre: HardhatRuntimeEnvironment,
args: CreateLoanArgs
): Promise<CreateLoanReturn> => {
const {
lendToken,
collToken,
loanType,
amount = 100,
amountBN,
duration = moment.duration(1, 'day'),
} = args
const { contracts, tokens, getNamedAccounts, toBN } = hre
// define diamond contract
const diamond = await contracts.get<ITellerDiamond>('TellerDiamond')
// lending token
const lendingToken =
typeof lendToken === 'string' ? await tokens.get(lendToken) : lendToken
// collateral token
const collateralToken =
typeof collToken === 'string' ? await tokens.get(collToken) : collToken
const collateralIsNative =
collateralToken.address === getNativeToken(hre.network)
// set borrower and loan amount
const borrower = args.borrower ?? (await getNamedAccounts()).borrower
const loanAmount = amountBN ?? toBN(amount, await lendingToken.decimals())
// depending on the loan type, we set a different collateral ratio. 10000 = 100%
let collateralRatio = 0
switch (loanType) {
case LoanType.ZERO_COLLATERAL:
break
case LoanType.UNDER_COLLATERALIZED:
collateralRatio = 5000
break
case LoanType.OVER_COLLATERALIZED:
collateralRatio = 15000
break
}
// create our mock CRA response
const craReturn = await mockCRAResponse(hre, {
lendingToken: lendingToken.address,
loanAmount,
loanTermLength: duration.asSeconds(),
collateralRatio: collateralRatio,
interestRate: '400',
borrower,
})
const { value: collValue } = await getPrice(
{
src: await lendingToken.symbol(),
dst: await collateralToken.symbol(),
amount: hre.fromBN(loanAmount, await lendingToken.decimals()),
},
hre
)
const collAmount = hre.toBN(collValue, await collateralToken.decimals())
const nativeAmount = collateralIsNative ? collAmount : BigNumber.from(0)
if (!collateralIsNative) {
await getFunds({
tokenSym: await collateralToken.symbol(),
amount: collAmount,
to: borrower,
hre,
})
await collateralToken
.connect(hre.ethers.provider.getSigner(borrower))
.approve(diamond.address, collAmount)
}
// call the takeOutLoan function from the diamond
const tx = diamond
.connect(hre.ethers.provider.getSigner(borrower))
.takeOutLoan(
{ request: craReturn.request, responses: craReturn.responses },
collateralToken.address,
collAmount,
{ value: nativeAmount.toString() }
)
// return our transaction and our helper variable
return {
tx,
getHelpers: async (): Promise<LoanHelpersReturn> => {
await tx
const allBorrowerLoans = await diamond.getBorrowerLoans(borrower)
const loanID = allBorrowerLoans[allBorrowerLoans.length - 1].toString()
return await loanHelpers(hre, loanID)
},
}
}
interface TakeOutLoanWithNFTsReturn extends CreateLoanReturn {
nfts: {
v1: BigNumber[]
v2: V2Balances
}
}
/**
* @description: It creates, signs, apply with NFTs and takes out a loan in one function
* @param args: Arguments we specify to create our Loan by depositing NFT
* @returns Promise<CreateLoanReturn> that gives us data to help run our tests
*/
export const takeOutLoanWithNfts = async (
hre: HardhatRuntimeEnvironment,
args: CreateLoanWithNftArgs
): Promise<TakeOutLoanWithNFTsReturn> => {
const { contracts, tokens, ethers, toBN, getNamedSigner } = hre
const {
borrower,
lendToken,
amount = 100,
duration = moment.duration(1, 'day'),
version,
} = args
const coder = ethers.utils.defaultAbiCoder
const borrowerAddress = await borrower.getAddress()
const diamond = await contracts.get<ITellerDiamond>('TellerDiamond')
// lending token
const lendingToken =
typeof lendToken === 'string' ? await tokens.get(lendToken) : lendToken
// amount in loan
const loanAmount = toBN(amount, await lendingToken.decimals())
const nftsUsed: TakeOutLoanWithNFTsReturn['nfts'] = {
v1: [],
v2: mergeV2IDsToBalances([]),
}
let tx: Promise<ContractTransaction>
switch (version) {
case 1: {
const nft = await contracts.get<TellerNFT>('TellerNFT')
// Mint user NFTs to use
await mintNFTV1({
tierIndex: 0,
borrower: borrowerAddress,
hre,
})
await mintNFTV1({
tierIndex: 1,
borrower: borrowerAddress,
hre,
})
await mintNFTV1({
tierIndex: 2,
borrower: borrowerAddress,
hre,
})
// get all the borrower's NFTs
nftsUsed.v1 = await nft.getOwnedTokens(borrowerAddress)
// Set NFT approval
await nft.connect(borrower).setApprovalForAll(diamond.address, true)
// Stake NFTs by transferring from the msg.sender (borrower) to the diamond
await (diamond as any as MainnetNFTFacetMock)
.connect(borrower)
.mockStakeNFTsV1(nftsUsed.v1)
// Encode the NFT V1 token data for the function
const tokenData = coder.encode(
['uint16', 'bytes'],
[1, coder.encode(['uint256[]'], [nftsUsed.v1])]
)
// plug it in the takeOutLoanWithNFTs function
tx = diamond
.connect(borrower)
.takeOutLoanWithNFTs(
lendingToken.address,
loanAmount,
duration.asSeconds(),
tokenData
)
break
}
case 2: {
const nft = await contracts.get<TellerNFTV2>('TellerNFT_V2')
// Mint user NFTs to use
await mintNFTV2({
tierIndex: 1,
amount: 2,
borrower: borrowerAddress,
hre,
})
await mintNFTV2({
tierIndex: 2,
amount: 2,
borrower: borrowerAddress,
hre,
})
await mintNFTV2({
tierIndex: 3,
amount: 2,
borrower: borrowerAddress,
hre,
})
// get all the borrower's NFTs
const ownedNFTs = await nft.getOwnedTokens(borrowerAddress)
// Set NFT approval
await nft.connect(borrower).setApprovalForAll(diamond.address, true)
//
// // Stake NFTs by transferring from the msg.sender (borrower) to the diamond
nftsUsed.v2 = mergeV2IDsToBalances(ownedNFTs)
await nft
.connect(borrower)
.safeBatchTransferFrom(
borrowerAddress,
diamond.address,
nftsUsed.v2.ids,
nftsUsed.v2.balances,
'0x'
)
// Encode the NFT V2 token data for the function
const tokenData = coder.encode(
['uint16', 'bytes'],
[
2,
coder.encode(
['uint256[]', 'uint256[]'],
[nftsUsed.v2.ids, nftsUsed.v2.balances]
),
]
)
// plug it in the takeOutLoanWithNFTs function
tx = diamond
.connect(borrower)
.takeOutLoanWithNFTs(
lendingToken.address,
loanAmount,
duration.asSeconds(),
tokenData
)
break
}
case 3: {
// get nftv1 and nftv2
const nft = await contracts.get<TellerNFT>('TellerNFT')
const nftV2 = await contracts.get<TellerNFTV2>('TellerNFT_V2')
// Mint user NFTs to use (from v1 and v2)
await mintNFTV1({
tierIndex: 0,
borrower: borrowerAddress,
hre,
})
await mintNFTV1({
tierIndex: 1,
borrower: borrowerAddress,
hre,
})
await mintNFTV2({
tierIndex: 1,
amount: 2,
borrower: borrowerAddress,
hre,
})
await mintNFTV2({
tierIndex: 2,
amount: 2,
borrower: borrowerAddress,
hre,
})
// get all the borrower's NFTs V1
nftsUsed.v1 = await nft.getOwnedTokens(borrowerAddress)
// set nft approval
await nft.connect(borrower).setApprovalForAll(diamond.address, true)
// get all the borrower's NFTs V2
const ownedNFTs = await nftV2.getOwnedTokens(borrowerAddress)
await nftV2.connect(borrower).setApprovalForAll(diamond.address, true)
nftsUsed.v2 = mergeV2IDsToBalances(ownedNFTs)
// Set NFT approval
// Stake NFTs by transferring from the msg.sender (borrower) to the diamond
await (diamond as any as MainnetNFTFacetMock)
.connect(borrower)
.mockStakeNFTsV1(nftsUsed.v1)
await nftV2
.connect(borrower)
.safeBatchTransferFrom(
borrowerAddress,
diamond.address,
nftsUsed.v2.ids,
nftsUsed.v2.balances,
'0x'
)
// Encode the NFT V1 token data for the function
const tokenData = coder.encode(
['uint16', 'bytes'],
[
3,
coder.encode(
['uint256[]', 'uint256[]', 'uint256[]'],
[nftsUsed.v1, nftsUsed.v2.ids, nftsUsed.v2.balances]
),
]
)
// plug it in the takeOutLoanWithNFTs function
tx = diamond
.connect(borrower)
.takeOutLoanWithNFTs(
lendingToken.address,
loanAmount,
duration.asSeconds(),
tokenData
)
break
}
}
// return our transaction and our helper variables
return {
tx,
nfts: nftsUsed,
getHelpers: async (): Promise<LoanHelpersReturn> => {
await tx
const allBorrowerLoans = await diamond.getBorrowerLoans(borrowerAddress)
const loanID = allBorrowerLoans[allBorrowerLoans.length - 1].toString()
return await loanHelpers(hre, loanID)
},
}
}
interface LoanDetailsReturn {
lendingToken: ERC20
collateralToken: ERC20
loan: PromiseReturnType<typeof ITellerDiamond.prototype.getLoan>
debt: PromiseReturnType<typeof ITellerDiamond.prototype.getDebtOwed>
terms: PromiseReturnType<typeof ITellerDiamond.prototype.getLoanTerms>
totalOwed: BigNumber
borrower: {
address: string
signer: Signer
}
refresh: () => ReturnType<typeof loanDetails>
}
const loanDetails = async (
hre: HardhatRuntimeEnvironment,
loanID: BigNumberish
): Promise<LoanDetailsReturn> => {
const { contracts, tokens } = hre
const diamond = await contracts.get<ITellerDiamond>('TellerDiamond')
const loan = await diamond.getLoan(loanID)
const lendingToken = await tokens.get(loan.lendingToken)
const collateralToken = await tokens.get(loan.collateralToken)
const debt = await diamond.getDebtOwed(loan.id)
const totalOwed = debt.principalOwed.add(debt.interestOwed)
const terms = await diamond.getLoanTerms(loan.id)
const signer = await hre.ethers.provider.getSigner(loan.borrower)
return {
loan,
lendingToken,
collateralToken,
debt,
totalOwed,
terms,
borrower: { address: loan.borrower, signer },
refresh: () => loanDetails(hre, loanID),
}
}
interface CommonLoanArgs {
diamond: ITellerDiamond
details: LoanDetailsReturn
from?: Signer
}
interface DepositCollateralArgs extends CommonLoanArgs {
amount?: BigNumberish
}
const depositCollateral = async (
hre: HardhatRuntimeEnvironment,
args: DepositCollateralArgs
): Promise<ContractTransaction> => {
const {
diamond,
details,
amount = await collateralNeeded({ diamond, details }),
from = details.borrower.signer,
} = args
const { tokens } = hre
const weth = await tokens.get('WETH')
const collateralToken = await tokens.get(details.loan.collateralToken)
const options: PayableOverrides = {}
if (
hre.ethers.utils.getAddress(details.loan.collateralToken) ==
hre.ethers.utils.getAddress(weth.address)
) {
options.value = amount
} else {
await collateralToken.approve(diamond.address, amount)
}
return await diamond
.connect(from)
.depositCollateral(details.loan.id, amount, options)
}
interface WithdrawCollateralArgs extends CommonLoanArgs {
amount: BigNumberish
}
const withdrawCollateral = async (
args: WithdrawCollateralArgs
): Promise<ContractTransaction> => {
const { diamond, details, amount, from = details.borrower.signer } = args
return await diamond.connect(from).withdrawCollateral(amount, details.loan.id)
}
interface CollateralNeededArgs extends CommonLoanArgs {}
const collateralNeeded = async (
args: CollateralNeededArgs
): Promise<BigNumber> => {
const { diamond, details } = args
const { neededInCollateralTokens } =
await diamond.callStatic.getCollateralNeededInfo(details.loan.id)
return neededInCollateralTokens
}
interface CollateralCurrentArgs extends CommonLoanArgs {}
const collateralCurrent = async (
args: CollateralCurrentArgs
): Promise<BigNumber> => {
const { diamond, details } = args
return await diamond.getLoanCollateral(details.loan.id)
}
export interface RepayLoanArgs extends CommonLoanArgs {
amount: BigNumberish
}
export const repayLoan = async (
args: RepayLoanArgs
): Promise<ContractTransaction> => {
const {
diamond,
details: { loan, borrower },
amount,
from = borrower.signer,
} = args
return await diamond.connect(from).repayLoan(loan.id, amount)
}
export const escrowRepayLoan = async (
args: RepayLoanArgs
): Promise<ContractTransaction> => {
const {
diamond,
details: { loan, borrower },
amount,
from = borrower.signer,
} = args
return await diamond.connect(from).escrowRepay(loan.id, amount)
} | the_stack |
import { normalizeAddress } from '@0xcert/ethereum-utils';
import { MutationBase, MutationContext, MutationEvent } from '@0xcert/scaffold';
import { EventEmitter } from 'events';
import { MutationEventSignature, MutationEventTypeKind } from './types';
/**
* Possible mutation statuses.
*/
export enum MutationStatus {
INITIALIZED = 0,
PENDING = 1,
COMPLETED = 2,
}
/**
* Ethreum transaction mutation.
*/
export class Mutation extends EventEmitter implements MutationBase {
/**
* Mutation Id (transaction hash).
*/
protected _id: string;
/**
* Number of confirmations (blocks in blockchain after mutation is accepted) are necessary to mark a mutation complete.
*/
protected _confirmations = 0;
/**
* Id (address) of the sender.
*/
protected _senderId: string;
/**
* Id (address) of the receiver.
*/
protected _receiverId: string;
/**
* Provider instance.
*/
protected _provider: any;
/**
* Completion process heartbeat speed.
*/
protected _speed = 14000;
/**
* Completion process loop timer.
*/
protected _timer: any;
/**
* Completion process start timestamp.
*/
protected _started: number;
/**
* Current mutation status.
*/
protected _status: MutationStatus = MutationStatus.INITIALIZED;
/**
* Context.
*/
protected _context?: any;
/**
* Mutations logs.
*/
protected _logs: any[] = [];
/**
* Initialize mutation.
* @param provider Provider class with which we communicate with blockchain.
* @param id Smart contract address on which a mutation will be performed.
* @param context Mutation context.
*/
public constructor(provider: any, id: string, context?: MutationContext) {
super();
this._id = id;
this._provider = provider;
if (this._provider.sandbox) {
this._status = MutationStatus.COMPLETED;
}
this._context = context;
}
/**
* Gets smart contract address.
*/
public get id() {
return this._id;
}
/**
* Get provider intance.
*/
public get provider() {
return this._provider;
}
/**
* Gets the number of confirmations of mutation.
*/
public get confirmations() {
return this._confirmations;
}
/**
* Gets the sending address.
*/
public get senderId() {
return this._senderId;
}
/**
* Gets the receiving address.
*/
public get receiverId() {
return this._receiverId;
}
/**
* Gets mutation logs.
*/
public get logs() {
return this._logs;
}
/**
* Checks if mutation in pending.
*/
public isPending() {
return this._status === MutationStatus.PENDING;
}
/**
* Checks if mutation has reached the required number of confirmation.
*/
public isCompleted() {
return this._status === MutationStatus.COMPLETED;
}
/**
* Emits mutation event.
*/
public emit(event: MutationEvent.CONFIRM, mutation: Mutation);
public emit(event: MutationEvent.COMPLETE, mutation: Mutation);
public emit(event: MutationEvent.ERROR, error: any);
public emit(...args) {
super.emit.call(this, ...args);
return this;
}
/**
* Attaches on mutation events.
*/
public on(event: MutationEvent.CONFIRM, handler: (m: Mutation) => any);
public on(event: MutationEvent.COMPLETE, handler: (m: Mutation) => any);
public on(event: MutationEvent.ERROR, handler: (e: any, m: Mutation) => any);
public on(...args) {
super.on.call(this, ...args);
return this;
}
/**
* Once handler.
*/
public once(event: MutationEvent.CONFIRM, handler: (m: Mutation) => any);
public once(event: MutationEvent.COMPLETE, handler: (m: Mutation) => any);
public once(event: MutationEvent.ERROR, handler: (e: any, m: Mutation) => any);
public once(...args) {
super.once.call(this, ...args);
return this;
}
/**
* Dettaches from mutation events.
*/
public off(event: MutationEvent.ERROR, handler: (e: any, m: Mutation) => any);
public off(event: MutationEvent);
public off(event, handler?) {
if (handler) {
super.off(event, handler);
} else {
super.removeAllListeners(event);
}
return this;
}
/**
* Waits until mutation is resolved (mutation reaches the specified number of confirmations).
*/
public async complete() {
const start = this._status === MutationStatus.INITIALIZED;
if (this.isCompleted()) {
return this.resolveCurrentState();
} else if (!this.isPending()) {
this._status = MutationStatus.PENDING;
this._started = Date.now();
}
await new Promise((resolve, reject) => {
if (!this.isCompleted()) {
this.once(MutationEvent.COMPLETE, () => resolve(null));
this.once(MutationEvent.ERROR, (err) => reject(err));
} else {
resolve(null);
}
if (start) {
this.loopUntilCompleted();
}
});
return this;
}
/**
* Stops listening for confirmations.
*/
public forget() {
if (this._timer) {
clearTimeout(this._timer);
this._timer = undefined;
}
return this;
}
/**
* Resolves mutation with its current data.
*/
public async resolve() {
return this.resolveCurrentState();
}
/**
* Retries mutation with a higher gas price if possible. It uses the provider's retryGasMultiplier to
* calculate gas price.
* @notice Returns error if a mutation is already accepted onto the blockchain.
*/
public async retry() {
const tx = await this.getTransactionObject();
if (!tx) {
throw new Error('Mutation not found');
} else if (tx.blockNumber) {
throw new Error('Mutation already accepted onto the blockchain');
}
const gasPrice = await this._provider.post({
method: 'eth_gasPrice',
params: [],
});
const oldGasPrice = tx.gasPrice;
const retryGasPrice = gasPrice.result * this._provider.retryGasPriceMultiplier;
// We first calculate new gas price based on current network conditions and
// retryGasPriceMultiplier if calculated gas price is lower than the original gas price, then we
// use the retryGasPriceMultiplier with the original gas price.
const newGasPrice = retryGasPrice >= oldGasPrice ? retryGasPrice : oldGasPrice * this._provider.retryGasPriceMultiplier;
const attrs = {
from: tx.from,
data: tx.input,
nonce: tx.nonce,
value: tx.value,
gas: tx.gas,
gasPrice: `0x${Math.ceil(newGasPrice).toString(16)}`,
};
if (tx.to) {
attrs['to'] = tx.to;
}
const res = await this._provider.post({
method: 'eth_sendTransaction',
params: [attrs],
});
this._id = res.result;
}
/**
* Cancels mutation if possible.
* @notice Returns error if a mutation is already accepted onto the blockchain or if you are not the
* mutation maker.
*/
public async cancel() {
const tx = await this.getTransactionObject();
if (!tx) {
throw new Error('Mutation not found');
} else if (tx.blockNumber) {
throw new Error('Mutation already accepted onto the blockchain');
} else if (tx.from.toLowerCase() !== this._provider.accountId.toLowerCase()) {
throw new Error('You are not the maker of this mutation so you cannot cancel it.');
}
const newGasPrice = `0x${Math.ceil(tx.gasPrice * 1.1).toString(16)}`;
const attrs = {
from: tx.from,
to: tx.from,
nonce: tx.nonce,
value: '0x0',
gasPrice: newGasPrice,
};
const res = await this._provider.post({
method: 'eth_sendTransaction',
params: [attrs],
});
this._id = res.result;
}
/**
* Helper method that resolves current mutation status.
*/
protected async resolveCurrentState() {
const tx = await this.getTransactionObject();
if (tx && (!tx.to || tx.to === '0x0')) {
tx.to = await this.getTransactionReceipt().then((r) => r ? r.contractAddress : null);
}
if (tx && tx.to) {
this._senderId = normalizeAddress(tx.from);
this._receiverId = normalizeAddress(tx.to);
this._confirmations = await this.getLastBlock()
.then((lastBlock) => lastBlock - parseInt(tx.blockNumber || lastBlock))
.then((num) => num < 0 ? 0 : num); // -1 when pending transaction is moved to the next block.
if (this._confirmations >= this._provider.requiredConfirmations) {
await this.parseLogs();
this._status = MutationStatus.COMPLETED;
return this.emit(MutationEvent.COMPLETE, this); // success
} else {
this.emit(MutationEvent.CONFIRM, this);
}
}
}
/**
* Helper methods for waiting until mutation is completed.
* IMPORTANT: After submiting a transaction to the Ethereum network, the
* transaction can not be found for some seconds. This happens because the
* Ethereum nodes in a cluster are not in sync and we must wait some time for
* this to happen.
*/
protected async loopUntilCompleted() {
await this.resolveCurrentState();
if (this._provider.mutationTimeout === -1 || Date.now() - this._started < this._provider.mutationTimeout) {
this._timer = setTimeout(this.loopUntilCompleted.bind(this), this._speed);
} else {
this.emit(MutationEvent.ERROR, new Error('Mutation has timed out'));
}
}
/**
* Gets transaction data.
*/
protected async getTransactionObject() {
const res = await this._provider.post({
method: 'eth_getTransactionByHash',
params: [this.id],
});
return res.result;
}
/**
* Gets transaction receipt.
*/
protected async getTransactionReceipt() {
const res = await this._provider.post({
method: 'eth_getTransactionReceipt',
params: [this.id],
});
return res.result;
}
/**
* Gets the latest block number.
*/
protected async getLastBlock() {
const res = await this._provider.post({
method: 'eth_blockNumber',
});
return parseInt(res.result);
}
/**
* Parses transaction receipt logs.
*/
protected async parseLogs() {
try {
this._logs = [];
const eventSignatures: MutationEventSignature[] = this._context.getContext();
if (!eventSignatures) {
return;
}
const transactionReceipt = await this.getTransactionReceipt();
transactionReceipt.logs.forEach((log) => {
const eventSignature = eventSignatures.find((e) => e.topic === log.topics[0]);
if (!eventSignature) {
this._provider.log(JSON.stringify(log));
return;
}
const obj = {};
obj['event'] = eventSignature.name;
obj['address'] = log.address;
const normal = eventSignature.types.filter((t) => t.kind === MutationEventTypeKind.NORMAL);
const indexed = eventSignature.types.filter((t) => t.kind === MutationEventTypeKind.INDEXED);
if (normal.length > 0) {
const normalTypes = normal.map((n) => n.type);
const decoded = this._provider.encoder.decodeParameters(normalTypes, log.data);
normal.forEach((n, idx) => {
obj[n.name] = decoded[idx];
});
}
indexed.forEach((i, idx) => {
obj[i.name] = this._provider.encoder.decodeParameters([i.type], log.topics[idx + 1])[0];
});
this._logs.push(obj);
});
} catch (e) {
this._provider.log(e);
}
}
} | the_stack |
import { EventNames } from "../../../../enums/EventNames";
import { PointerActionType } from "../../../../enums/PointerActionType";
import { IDesignerMousePoint } from "../../../../interfaces/IDesignerMousePoint";
import { IPoint } from "../../../../interfaces/IPoint";
import { DesignItem } from "../../../item/DesignItem";
import { IDesignItem } from "../../../item/IDesignItem";
import { IPlacementService } from "../../../services/placementService/IPlacementService";
import { ExtensionType } from "../extensions/ExtensionType";
import { IDesignerCanvas } from "../IDesignerCanvas";
import { ITool } from "./ITool";
import { NamedTools } from './NamedTools';
import { DesignerCanvas } from '../designerCanvas';
export class PointerTool implements ITool {
readonly cursor: string = 'default';
private _movedSinceStartedAction: boolean = false;
private _initialPoint: IDesignerMousePoint;
private _actionType?: PointerActionType;
private _actionStartedDesignItem?: IDesignItem;
private _previousEventName: EventNames;
private _clickThroughElements: [designItem: IDesignItem, backupPointerEvents: string][] = []
private _dragOverExtensionItem: IDesignItem;
private _dragExtensionItem: IDesignItem;
private _moveItemsOffset: IPoint = { x: 0, y: 0 };
constructor() {
}
dispose(): void {
}
pointerEventHandler(designerView: IDesignerCanvas, event: PointerEvent, currentElement: Element) {
switch (event.type) {
case EventNames.PointerDown:
(<Element>event.target).setPointerCapture(event.pointerId);
this._movedSinceStartedAction = false;
break;
case EventNames.PointerUp:
(<Element>event.target).releasePointerCapture(event.pointerId);
break;
}
if (!event.altKey)
this._resetPointerEventsForClickThrough();
if (!currentElement)
return;
const currentPoint = designerView.getDesignerMousepoint(event, currentElement, event.type === 'pointerdown' ? null : this._initialPoint);
const currentDesignItem = DesignItem.GetOrCreateDesignItem(currentElement, designerView.serviceContainer, designerView.instanceServiceContainer);
if (this._actionType == null) {
this._initialPoint = currentPoint;
if (event.type == EventNames.PointerDown) {
this._actionStartedDesignItem = currentDesignItem;
designerView.snapLines.clearSnaplines();
if (currentDesignItem !== designerView.rootDesignItem) {
this._actionType = PointerActionType.Drag;
} else if (currentElement === <any>designerView || currentElement === designerView.rootDesignItem.element || currentElement == null) {
designerView.instanceServiceContainer.selectionService.setSelectedElements(null);
this._actionType = PointerActionType.DrawSelection;
} else {
this._actionType = PointerActionType.DragOrSelect;
}
}
}
if (event.type === EventNames.PointerMove) {
this._movedSinceStartedAction = this._movedSinceStartedAction || currentPoint.x != this._initialPoint.x || currentPoint.y != this._initialPoint.y;
if (this._actionType == PointerActionType.DrawSelection)
this._actionType = PointerActionType.DrawingSelection;
}
if (this._actionType == PointerActionType.DrawSelection || this._actionType == PointerActionType.DrawingSelection) {
this._pointerActionTypeDrawSelection(designerView, event, (<HTMLElement>currentElement));
} else if (this._actionType == PointerActionType.DragOrSelect || this._actionType == PointerActionType.Drag) {
this._pointerActionTypeDragOrSelect(designerView, event, currentDesignItem, currentPoint);
}
if (event.type == EventNames.PointerUp) {
designerView.snapLines.clearSnaplines();
if (this._actionType == PointerActionType.DrawSelection) {
if (currentDesignItem !== designerView.rootDesignItem)
designerView.instanceServiceContainer.selectionService.setSelectedElements([currentDesignItem]);
}
this._actionType = null;
this._actionStartedDesignItem = null;
this._movedSinceStartedAction = false;
this._initialPoint = null;
}
this._previousEventName = <EventNames>event.type;
}
private _pointerActionTypeDrawSelection(designerView: IDesignerCanvas, event: PointerEvent, currentElement: HTMLElement) {
const drawSelectionTool = designerView.serviceContainer.designerTools.get(NamedTools.DrawSelection);
if (drawSelectionTool) {
drawSelectionTool.pointerEventHandler(designerView, event, currentElement);
}
}
private _resetPointerEventsForClickThrough() {
if (!this._clickThroughElements.length)
return;
for (const e of this._clickThroughElements) {
(<HTMLElement>e[0].element).style.pointerEvents = e[1];
}
this._clickThroughElements = [];
}
private _pointerActionTypeDragOrSelect(designerView: IDesignerCanvas, event: PointerEvent, currentDesignItem: IDesignItem, currentPoint: IDesignerMousePoint) {
if (event.altKey) {
if (event.type == EventNames.PointerDown) {
this._clickThroughElements.push([currentDesignItem, (<HTMLElement>currentDesignItem.element).style.pointerEvents]);
(<HTMLElement>currentDesignItem.element).style.pointerEvents = 'none';
}
let currentElement = designerView.elementFromPoint(event.x, event.y) as HTMLElement;
if (DesignerCanvas.getHost(currentElement) !== designerView.overlayLayer)
currentDesignItem = DesignItem.GetOrCreateDesignItem(currentElement, designerView.serviceContainer, designerView.instanceServiceContainer);
} else {
this._resetPointerEventsForClickThrough();
}
switch (event.type) {
case EventNames.PointerDown:
{
this._actionStartedDesignItem = currentDesignItem;
this._moveItemsOffset = { x: 0, y: 0 };
if (event.shiftKey || event.ctrlKey) {
const index = designerView.instanceServiceContainer.selectionService.selectedElements.indexOf(currentDesignItem);
if (index >= 0) {
let newSelectedList = designerView.instanceServiceContainer.selectionService.selectedElements.slice(0);
newSelectedList.splice(index, 1);
designerView.instanceServiceContainer.selectionService.setSelectedElements(newSelectedList);
}
else {
let newSelectedList = designerView.instanceServiceContainer.selectionService.selectedElements.slice(0);
newSelectedList.push(currentDesignItem);
designerView.instanceServiceContainer.selectionService.setSelectedElements(newSelectedList);
}
} else {
if (designerView.instanceServiceContainer.selectionService.selectedElements.indexOf(currentDesignItem) < 0)
designerView.instanceServiceContainer.selectionService.setSelectedElements([currentDesignItem]);
}
if (designerView.alignOnSnap)
designerView.snapLines.calculateSnaplines(designerView.instanceServiceContainer.selectionService.selectedElements);
break;
}
case EventNames.PointerMove:
{
const elementMoved = currentPoint.x != this._initialPoint.x || currentPoint.y != this._initialPoint.y;
if (this._actionType != PointerActionType.Drag && elementMoved) {
this._actionType = PointerActionType.Drag;
}
if (this._movedSinceStartedAction) {
const currentContainerService = designerView.serviceContainer.getLastServiceWhere('containerService', x => x.serviceForContainer(this._actionStartedDesignItem.parent));
if (currentContainerService) {
const dragItem = this._actionStartedDesignItem.parent;
if (this._dragExtensionItem != dragItem) {
designerView.extensionManager.removeExtension(this._dragExtensionItem, ExtensionType.ContainerDrag);
designerView.extensionManager.applyExtension(dragItem, ExtensionType.ContainerDrag);
this._dragExtensionItem = dragItem;
}
else {
designerView.extensionManager.refreshExtension(dragItem, ExtensionType.ContainerDrag);
}
const canLeave = currentContainerService.canLeave(this._actionStartedDesignItem.parent, [this._actionStartedDesignItem]);
let newContainerElementDesignItem: IDesignItem = null;
let newContainerService: IPlacementService = null;
if (canLeave) {
//search for containers below mouse cursor.
//to do this, we need to disable pointer events for each in a loop and search wich element is there
let backupPEventsMap: Map<HTMLElement, string> = new Map();
let newContainerElement = designerView.elementFromPoint(event.x, event.y) as HTMLElement;
try {
checkAgain: while (newContainerElement != null) {
if (newContainerElement == this._actionStartedDesignItem.parent.element) {
newContainerElement = null;
} else if (newContainerElement == designerView.rootDesignItem.element) {
newContainerElementDesignItem = designerView.rootDesignItem;
newContainerService = designerView.serviceContainer.getLastServiceWhere('containerService', x => x.serviceForContainer(newContainerElementDesignItem));
break;
} else if (newContainerElement.getRootNode() !== designerView.shadowRoot || <any>newContainerElement === designerView.overlayLayer || <any>newContainerElement.parentElement === designerView.overlayLayer) {
backupPEventsMap.set(newContainerElement, newContainerElement.style.pointerEvents);
newContainerElement.style.pointerEvents = 'none';
const old = newContainerElement;
newContainerElement = designerView.elementFromPoint(event.x, event.y) as HTMLElement;
if (old === newContainerElement) {
newContainerElementDesignItem = null;
newContainerService = null;
break;
}
}
else if (newContainerElement == this._actionStartedDesignItem.element) {
backupPEventsMap.set(newContainerElement, newContainerElement.style.pointerEvents);
newContainerElement.style.pointerEvents = 'none';
const old = newContainerElement;
newContainerElement = designerView.elementFromPoint(event.x, event.y) as HTMLElement;
if (old === newContainerElement) {
newContainerElementDesignItem = null;
newContainerService = null;
break;
}
}
else {
//check we don't try to move a item over one of its children...
let par = newContainerElement.parentElement;
while (par) {
if (par == this._actionStartedDesignItem.element) {
backupPEventsMap.set(newContainerElement, newContainerElement.style.pointerEvents);
newContainerElement.style.pointerEvents = 'none';
const old = newContainerElement;
newContainerElement = designerView.elementFromPoint(event.x, event.y) as HTMLElement;
if (old === newContainerElement)
break;
continue checkAgain;
}
par = par.parentElement;
}
//end check
newContainerElementDesignItem = DesignItem.GetOrCreateDesignItem(newContainerElement, designerView.serviceContainer, designerView.instanceServiceContainer);
newContainerService = designerView.serviceContainer.getLastServiceWhere('containerService', x => x.serviceForContainer(newContainerElementDesignItem));
if (newContainerService) {
if (newContainerService.canEnter(newContainerElementDesignItem, [this._actionStartedDesignItem])) {
break;
} else {
newContainerElementDesignItem = null;
newContainerService = null;
}
}
backupPEventsMap.set(newContainerElement, newContainerElement.style.pointerEvents);
newContainerElement.style.pointerEvents = 'none';
const newC = designerView.elementFromPoint(event.x, event.y) as HTMLElement;
if (newContainerElement === newC)
break;
newContainerElement = newC;
}
}
}
finally {
for (let e of backupPEventsMap.entries()) {
e[0].style.pointerEvents = e[1];
}
}
if (newContainerElement != null) {
let p = newContainerElement
while (p != null) {
if (p === designerView.rootDesignItem.element)
break;
p = p.parentElement;
}
if (p == null) {
newContainerService = null;
newContainerElement = null;
}
}
//if we found a new enterable container create extensions
if (newContainerElement != null) {
const newContainerElementDesignItem = DesignItem.GetOrCreateDesignItem(newContainerElement, designerView.serviceContainer, designerView.instanceServiceContainer);
if (this._dragOverExtensionItem != newContainerElementDesignItem) {
designerView.extensionManager.removeExtension(this._dragOverExtensionItem, ExtensionType.ContainerDragOver);
designerView.extensionManager.applyExtension(newContainerElementDesignItem, ExtensionType.ContainerDragOver);
this._dragOverExtensionItem = newContainerElementDesignItem;
}
else {
designerView.extensionManager.refreshExtension(newContainerElementDesignItem, ExtensionType.ContainerDragOver);
}
} else {
if (this._dragOverExtensionItem) {
designerView.extensionManager.removeExtension(this._dragOverExtensionItem, ExtensionType.ContainerDragOver);
this._dragOverExtensionItem = null;
}
}
}
if (newContainerService && event.altKey) {
//TODO: all items, fix position
const oldOffset = currentContainerService.getElementOffset(this._actionStartedDesignItem.parent, this._actionStartedDesignItem);
const newOffset = newContainerService.getElementOffset(newContainerElementDesignItem, this._actionStartedDesignItem);
this._moveItemsOffset = { x: newOffset.x - oldOffset.x + this._moveItemsOffset.x, y: newOffset.y - oldOffset.y + this._moveItemsOffset.y };
currentContainerService.leaveContainer(this._actionStartedDesignItem.parent, [this._actionStartedDesignItem]);
newContainerElementDesignItem.insertChild(this._actionStartedDesignItem);
const cp: IDesignerMousePoint = { x: currentPoint.x - this._moveItemsOffset.x, y: currentPoint.y - this._moveItemsOffset.y, originalX: currentPoint.originalX - this._moveItemsOffset.x, originalY: currentPoint.originalY - this._moveItemsOffset.y, offsetInControlX: currentPoint.offsetInControlX, offsetInControlY: currentPoint.offsetInControlY, zoom: currentPoint.zoom };
newContainerService.enterContainer(newContainerElementDesignItem, [this._actionStartedDesignItem]);
newContainerService.place(event, designerView, this._actionStartedDesignItem.parent, this._initialPoint, cp, designerView.instanceServiceContainer.selectionService.selectedElements);
}
else {
const cp: IDesignerMousePoint = { x: currentPoint.x - this._moveItemsOffset.x, y: currentPoint.y - this._moveItemsOffset.y, originalX: currentPoint.originalX - this._moveItemsOffset.x, originalY: currentPoint.originalY - this._moveItemsOffset.y, offsetInControlX: currentPoint.offsetInControlX, offsetInControlY: currentPoint.offsetInControlY, zoom: currentPoint.zoom };
currentContainerService.place(event, designerView, this._actionStartedDesignItem.parent, this._initialPoint, cp, designerView.instanceServiceContainer.selectionService.selectedElements);
}
designerView.extensionManager.refreshExtensions(designerView.instanceServiceContainer.selectionService.selectedElements);
}
}
break;
}
case EventNames.PointerUp:
{
if (this._actionType == PointerActionType.DragOrSelect) {
if (this._previousEventName == EventNames.PointerDown && !event.shiftKey && !event.ctrlKey)
designerView.instanceServiceContainer.selectionService.setSelectedElements([currentDesignItem]);
return;
}
if (this._movedSinceStartedAction) {
let containerService = designerView.serviceContainer.getLastServiceWhere('containerService', x => x.serviceForContainer(this._actionStartedDesignItem.parent))
const cp = { x: currentPoint.x - this._moveItemsOffset.x, y: currentPoint.y - this._moveItemsOffset.y, originalX: currentPoint.originalX - this._moveItemsOffset.x, originalY: currentPoint.originalY - this._moveItemsOffset.y, offsetInControlX: currentPoint.offsetInControlX, offsetInControlY: currentPoint.offsetInControlY, zoom: currentPoint.zoom };
if (containerService) {
let cg = designerView.rootDesignItem.openGroup("Move Elements", designerView.instanceServiceContainer.selectionService.selectedElements);
containerService.finishPlace(event, designerView, this._actionStartedDesignItem.parent, this._initialPoint, cp, designerView.instanceServiceContainer.selectionService.selectedElements);
cg.commit();
}
designerView.extensionManager.removeExtension(this._dragExtensionItem, ExtensionType.ContainerDrag);
this._dragExtensionItem = null;
designerView.extensionManager.removeExtension(this._dragOverExtensionItem, ExtensionType.ContainerDragOver);
this._dragOverExtensionItem = null;
this._moveItemsOffset = { x: 0, y: 0 };
}
designerView.extensionManager.refreshExtensions(designerView.instanceServiceContainer.selectionService.selectedElements);
break;
}
}
}
} | the_stack |
import * as vscode from 'vscode';
import {ImportIndexer} from './ImportIndexer';
import { ImportIndex, Symbol, MatchMode } from './ImportIndex';
import {Importer} from './Importer';
import * as path from 'path';
export function activate( context: vscode.ExtensionContext ): void
{
let importer = new TypeScriptImporter(context);
if( importer.disabled )
return;
importer.start();
}
export function deactivate() {
}
class SymbolCompletionItem extends vscode.CompletionItem
{
constructor( doc: vscode.TextDocument, public m: Symbol, lowImportance: boolean )
{
super( m.name );
if( !m.type )
this.kind = vscode.CompletionItemKind.File;
else if( m.type.indexOf( "class" ) >= 0 )
this.kind = vscode.CompletionItemKind.Class;
else if( m.type.indexOf( "interface" ) >= 0 )
this.kind = vscode.CompletionItemKind.Interface;
else if( m.type.indexOf( "function" ) >= 0 )
this.kind = vscode.CompletionItemKind.Function;
else
this.kind = vscode.CompletionItemKind.Variable;
this.description = this.documentation = m.module || m.path;
if( lowImportance )
{
this.sortText = "zzzzzzzzzz" + m.name;
this.label = m.name;
this.insertText = m.name;
}
if( doc )
this.command = {
title: "import",
command: 'tsimporter.importSymbol',
arguments: [ doc, m ]
}
}
public description: string;
}
function getSelectedWord(): string {
if( !vscode.window.activeTextEditor )
return "";
let document = vscode.window.activeTextEditor.document;
if( !document )
return "";
let word = "";
let selection = vscode.window.activeTextEditor.selection;
if( selection ) {
let w: vscode.Range = selection;
if( selection.isEmpty )
w = document.getWordRangeAtPosition( selection.active );
if( w && w.isSingleLine ) {
word = document.getText( w );
}
}
return word;
}
export class TypeScriptImporter implements vscode.CompletionItemProvider, vscode.CodeActionProvider
{
public conf<T>( property: string, defaultValue?: T ): T
{
return vscode.workspace.getConfiguration( 'tsimporter' ).get<T>( property, defaultValue );
}
public disabled: boolean = false;
public noStatusBar: boolean = false;
private showNotifications: boolean;
private statusBar: vscode.StatusBarItem;
public indexer: ImportIndexer;
public codeCompletionIndexer: ImportIndexer;
public importer: Importer;
private removeFileExtensions: string[];
public lowImportance: boolean = false;
public emitSemicolon: boolean = true;
constructor( private context: vscode.ExtensionContext )
{
if( vscode.workspace.rootPath === undefined )
this.disabled = true;
else
this.disabled = this.conf<boolean>( "disabled" );
this.loadConfig();
}
protected loadConfig(): void {
this.showNotifications = this.conf<boolean>('showNotifications');
this.removeFileExtensions = this.conf<string>('removeFileExtensions', '.d.ts,.ts,.tsx').trim().split(/\s*,\s*/);
this.lowImportance = this.conf<boolean>('lowImportance', false);
this.emitSemicolon = this.conf<boolean>('emitSemicolon', true);
this.noStatusBar = this.conf<boolean>('noStatusBar', false);
}
public start(): void
{
this.indexer = new ImportIndexer( this );
this.indexer.attachFileWatcher();
this.codeCompletionIndexer = new ImportIndexer( this );
this.importer = new Importer( this );
let codeActionFixer = vscode.languages.registerCodeActionsProvider('typescript', this)
let completionItem = vscode.languages.registerCompletionItemProvider('typescript', this)
let codeActionFixerReact = vscode.languages.registerCodeActionsProvider('typescriptreact', this)
let completionItemReact = vscode.languages.registerCompletionItemProvider('typescriptreact', this)
let codeActionFixerVue = vscode.languages.registerCodeActionsProvider('vue', this)
let completionItemVue = vscode.languages.registerCompletionItemProvider('vue', this)
let reindexCommand = vscode.commands.registerCommand( 'tsimporter.reindex', ( ) => {
this.loadConfig();
this.indexer.reset();
this.indexer.attachFileWatcher();
this.indexer.scanAll( true );
});
let addImport = vscode.commands.registerCommand( 'tsimporter.addImport', ( ) => {
if( !vscode.window.activeTextEditor )
return;
let document = vscode.window.activeTextEditor.document;
let word = getSelectedWord();
this.codeCompletionIndexer.index.resetIndex();
this.codeCompletionIndexer.processFile( document.getText(), document.uri, false );
var definitions: SymbolCompletionItem[] = [];
this.indexer.index.getSymbols( word, true, MatchMode.ANY ).forEach( m => {
if( this.codeCompletionIndexer.index.getSymbols( m.name, false, MatchMode.EXACT ).length == 0 )
{
var ci = new SymbolCompletionItem( document, m, this.lowImportance );
definitions.push( ci );
}
} );
let importItem = item => {
if( item )
vscode.commands.executeCommand( item.command.command, item.command.arguments[0], item.command.arguments[1] );
};
if( definitions.length == 0 ) {
vscode.window.showInformationMessage( "no importable symbols found!" )
}
else if( definitions.length == 1 ) {
importItem( definitions[0] );
}
else {
vscode.window.showQuickPick<SymbolCompletionItem>( definitions ).then( importItem );
}
});
let openSymbol = vscode.commands.registerCommand( 'tsimporter.openSymbol', ( ) => {
let word = getSelectedWord();
var definitions: SymbolCompletionItem[] = [];
this.indexer.index.getSymbols( word, true, MatchMode.ANY ).forEach( m => {
if( m.path ) {
var ci = new SymbolCompletionItem( null, m, this.lowImportance );
definitions.push( ci );
}
} );
let openItem = item => {
if( item ) {
let uri = vscode.Uri.file( item.m.path );
console.log( uri );
vscode.workspace.openTextDocument( uri ).then(
r => {
vscode.window.showTextDocument( r );
},
f => {
console.error( "fault", f )
}
);
}
};
if( definitions.length == 0 ) {
vscode.window.showInformationMessage( "no importable symbols found!" )
}
else if( definitions.length == 1 ) {
openItem( definitions[0] );
}
else {
vscode.window.showQuickPick<SymbolCompletionItem>( definitions ).then( openItem );
}
});
let dumpSymbolsCommand = vscode.commands.registerCommand( 'tsimporter.dumpIndex', ( ) => {
let change = vscode.window.onDidChangeActiveTextEditor( e => {
change.dispose();
let edit = new vscode.WorkspaceEdit();
edit.insert(
e.document.uri,
new vscode.Position( 0, 0 ),
JSON.stringify( this.indexer.index, null, "\t" )
);
vscode.workspace.applyEdit( edit );
} );
vscode.commands.executeCommand( "workbench.action.files.newUntitledFile" );
});
let importCommand = vscode.commands.registerCommand('tsimporter.importSymbol', ( document: vscode.TextDocument, symbol: Symbol ) => {
this.importer.importSymbol( document, symbol );
});
this.statusBar = vscode.window.createStatusBarItem( vscode.StatusBarAlignment.Left, 1 );
this.setStatusBar( "initializing" );
this.statusBar.command = 'tsimporter.dumpIndex';
if( this.noStatusBar )
this.statusBar.hide();
else
this.statusBar.show();
this.context.subscriptions.push( codeActionFixer, completionItem, codeActionFixerReact, completionItemReact, codeActionFixerVue, completionItemVue, importCommand, dumpSymbolsCommand, this.statusBar );
vscode.commands.executeCommand('tsimporter.reindex', { showOutput: true });
}
public removeFileExtension( fileName: string ): string
{
for( var i = 0; i<this.removeFileExtensions.length; i++ )
{
var e = this.removeFileExtensions[i];
if( fileName.endsWith( e ) )
return fileName.substring( 0, fileName.length - e.length );
}
return fileName;
}
public showNotificationMessage( message: string ): void {
if( this.showNotifications )
vscode.window.showInformationMessage('[TypeScript Importer] ' + message );
}
private status: string = "Initializing";
public setStatusBar( status: string ) {
this.status = status;
if( this.statusBar )
this.statusBar.text = "[TypeScript Importer]: " + this.status;
}
/**
* Provide completion items for the given position and document.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param token A cancellation token.
* @return An array of completions, a [completion list](#CompletionList), or a thenable that resolves to either.
* The lack of a result can be signaled by returning `undefined`, `null`, or an empty array.
*/
provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): vscode.CompletionItem[] | Thenable<vscode.CompletionItem[]> | vscode.CompletionList | Thenable<vscode.CompletionList> {
var line = document.lineAt( position.line );
var lineText = line.text;
if( lineText ) {
var docText = document.getText();
var len = document.offsetAt( position );
let idx = 0;
enum MODE {
Code,
MultiLineComment,
LineComment,
SingleQuoteString,
DoubleQuoteString,
MultiLineString
}
let mode = MODE.Code;
while( idx < len ) {
let next = docText.substr( idx, 1 );
let next2 = docText.substr( idx, 2 );
switch( mode ) {
case MODE.Code: {
if( next2 == "/*" ) {
mode = MODE.MultiLineComment;
idx++;
}
else if( next2 == "//" ) {
mode = MODE.LineComment;
idx++;
}
else if( next == "'" )
mode = MODE.SingleQuoteString;
else if( next == '"' )
mode = MODE.DoubleQuoteString;
else if( next == '`' )
mode = MODE.MultiLineString;
} break;
case MODE.MultiLineComment: {
if( next2 == "*/" ) {
mode = MODE.Code;
idx++;
}
}break;
case MODE.LineComment: {
if( next == "\n" ) {
mode = MODE.Code;
}
}break;
case MODE.SingleQuoteString: {
if( next == "'" || next == "\n" )
mode = MODE.Code;
}break;
case MODE.DoubleQuoteString: {
if( next == '"' || next == "\n" )
mode = MODE.Code;
}break;
case MODE.MultiLineString: {
if( next == '`' )
mode = MODE.Code;
}break;
}
idx++;
}
//console.log( "parsed mode is", mode );
if( mode != MODE.Code )
return;
}
if( lineText && lineText.indexOf( "import" ) >= 0 && lineText.indexOf( "from" ) >= 0 )
{
var delims = ["'", '"'];
var end = position.character;
var start = end - 1;
while( delims.indexOf( lineText.charAt( start ) ) < 0 && start > 0 )
start --;
if( start > 0 )
{
var moduleText = lineText.substring( start + 1, end );
return this.provideModuleCompletionItems( moduleText, new vscode.Range( new vscode.Position( position.line, start + 1 ), new vscode.Position( position.line, position.character ) ) );
}
else
{
return [];
}
}
else// if( range )
{
let s = new Date().getTime();
let range: vscode.Range = null;//document.getWordRangeAtPosition( position );
let word = "";
if( range && range.isSingleLine && !range.isEmpty )
word = document.getText( range ).trim();
this.codeCompletionIndexer.index.resetIndex();
this.codeCompletionIndexer.processFile( document.getText(), document.uri, false );
var definitions: vscode.CompletionItem[] = [];
this.indexer.index.getSymbols( word, true, MatchMode.ANY ).forEach( m => {
if( this.codeCompletionIndexer.index.getSymbols( m.name, false, MatchMode.EXACT ).length == 0 )
{
var ci: vscode.CompletionItem = new SymbolCompletionItem( document, m, this.lowImportance );
definitions.push( ci );
}
} );
//console.log( "provided", definitions.length, "within", (new Date().getTime() - s), "ms" );
return definitions;
}
}
provideModuleCompletionItems( searchText: string, replaceRange: vscode.Range ): vscode.CompletionItem[]
{
var modules: vscode.CompletionItem[] = [];
this.indexer.index.getModules( searchText, true, MatchMode.ANY ).forEach( m => {
var ci: vscode.CompletionItem = new vscode.CompletionItem( m );
ci.kind = vscode.CompletionItemKind.File;
ci.textEdit = new vscode.TextEdit( replaceRange, m );
modules.push( ci );
} );
return modules;
}
/**
* Given a completion item fill in more data, like [doc-comment](#CompletionItem.documentation)
* or [details](#CompletionItem.detail).
*
* The editor will only resolve a completion item once.
*
* @param item A completion item currently active in the UI.
* @param token A cancellation token.
* @return The resolved completion item or a thenable that resolves to of such. It is OK to return the given
* `item`. When no result is returned, the given `item` will be used.
*/
resolveCompletionItem(item: vscode.CompletionItem, token: vscode.CancellationToken): vscode.CompletionItem | Thenable<vscode.CompletionItem> {
return item;
}
/**
* Provide commands for the given document and range.
*
* @param document The document in which the command was invoked.
* @param range The range for which the command was invoked.
* @param context Context carrying additional information.
* @param token A cancellation token.
* @return An array of commands or a thenable of such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken): vscode.Command[] | Thenable<vscode.Command[]> {
if( context && context.diagnostics )
{
for( var i=0; i<context.diagnostics.length; i++ )
{
var symbols = this.getSymbolsForDiagnostic( context.diagnostics[i].message );
if( symbols.length )
{
let handlers = [];
for( var s=0; s<symbols.length; s++ )
{
var symbol = symbols[s];
handlers.push( {
title: this.importer.createImportStatement( this.importer.createImportDefinition( symbol.name ), this.importer.resolveModule( document, symbol ) ),
command: 'tsimporter.importSymbol',
arguments: [ document, symbol ]
} );
};
return handlers;
}
}
}
return [];
}
private getSymbolsForDiagnostic( message: string ): Symbol[]
{
var test = /Cannot find name ['"](.*?)['"]\./;
var match: string[];
if ( message && ( match = test.exec( message ) ) )
{
let missing = match[1];
return this.indexer.index.getSymbols( missing, false, MatchMode.EXACT );
}
else
return [];
}
} | the_stack |
declare module Labs.Core {
/**
* Definition of a lab action. An action represents an interaction a user has taken with the lab.
*/
interface IAction {
/**
* The type of action taken.
*/
type: string;
/**
* The options sent with the action
*/
options: Core.IActionOptions;
/**
* The result of the action
*/
result: Core.IActionResult;
/**
* The time at which the action was completed. In milliseconds elapsed since 1 January 1970 00:00:00 UTC.
*/
time: number;
}
}
declare module Labs.Core {
/**
* The results of taking an action. Depending on the type of action these will either be set by the server side
* or provided by the client when taking the action.
*/
interface IActionResult {
}
}
declare module Labs.Core {
/**
* Base class for instances of a lab component. An instance is an instantiation of a component for a user. It contains
* a translated view of the component for a particular run of the lab. This view may exclude hidden information (answers, hints, etc...)
* and also contains IDs to identify the various instances.
*/
interface IComponentInstance extends Core.ILabObject, Core.IUserData {
/**
* The ID of the component this instance is associated with
*/
componentId: string;
/**
* The name of the component
*/
name: string;
/**
* value property map associated with the component
*/
values: {
[type: string]: Core.IValueInstance[];
};
}
}
declare module Labs.Core {
/**
* Information about the lab configuration.
*/
interface IConfigurationInfo {
/**
* The version of the host the lab configuration was created with.
*/
hostVersion: Core.IVersion;
}
}
declare module Labs.Core {
/**
* Response information coming from a connection call
*/
interface IConnectionResponse {
/**
* Initialization information or null if the app has not yet been initialized
*/
initializationInfo: Core.IConfigurationInfo;
/**
* The current mode the lab is running in
*/
mode: Core.LabMode;
/**
* Version information for server side
*/
hostVersion: Core.IVersion;
/**
* Information about the user
*/
userInfo: Core.IUserInfo;
}
}
declare module Labs.Core {
/**
* Options passed as part of a get action
*/
interface IGetActionOptions {
}
}
declare module Labs.Core {
/**
* Options passed as part of a lab create.
*/
interface ILabCreationOptions {
}
}
declare module Labs.Core {
/**
* Version information about the lab host
*/
interface ILabHostVersionInfo {
/**
* The API version of the host
*/
version: Core.IVersion;
}
}
declare module Labs.Core {
/**
* Definition of lab action options. These are the options passed when performing a given action.
*/
interface IActionOptions {
}
}
declare module Labs.Core {
/**
* Base interface for messages sent between the client and the host.
*/
interface IMessage {
}
}
declare module Labs.Core {
/**
* Base interface for responses to messages sent to the host.
*/
interface IMessageResponse {
}
}
declare module Labs.Core {
/**
* User information
*/
interface IUserInfo {
/**
* Unique identifier for the given lab user
*/
id: string;
/**
* Permissions the user has access to
*/
permissions: string[];
}
}
declare module Labs.Core {
/**
* An intance of an IValue
*/
interface IValueInstance {
/**
* ID for the value this instance represents
*/
valueId: string;
/**
* Flag indicating whether or not this value is considered a hint
*/
isHint: boolean;
/**
* Flag indicating whether or not the instance information contains the value.
*/
hasValue: boolean;
/**
* The value. May or may not be set depending on if it has been hidden.
*/
value?: any;
}
}
declare module Labs.Core {
/**
* Version information
*/
interface IVersion {
/**
* Major version
*/
major: number;
/**
* Minor version
*/
minor: number;
}
}
declare module Labs.Core {
/**
* Custom analytics configuration information. Allows the develper to specify which iframe to load
* in order to display custom analytics for a user's run of a lab.
*/
interface IAnalyticsConfiguration {
}
}
declare module Labs.Core {
/**
* Completion status for the lab. Passed when completing the lab to indicate the result of the interaction.
*/
interface ICompletionStatus {
}
}
declare module Labs.Core {
/**
* Interface for Labs.js callback methods
*/
interface ILabCallback<T> {
/**
* Callback signature
*
* @param { err } If an error has occurred this will be non-null
* @param { data } The data returned with the callback
*/
(err: any, data: T): void;
}
}
declare module Labs.Core {
/**
* A lab object contains a type field which indicates what type of object it is
*/
interface ILabObject {
/**
* The type name for the object
*/
type: string;
}
}
declare module Labs.Core {
/**
* Timeline configuration options. Allows the lab developer to specify a set of timeline configuration options.
*/
interface ITimelineConfiguration {
/**
* The duration of the lab in seconds
*/
duration: number;
/**
* A list of timeline capabilities the lab supports. i.e. play, pause, seek, fast forward...
*/
capabilities: string[];
}
}
declare module Labs.Core {
/**
* Base interface to represent custom user data stored on an object
*/
interface IUserData {
/**
* An optional data field stored on the object for custom fields.
*/
data?: any;
}
}
declare module Labs.Core {
/**
* Base class for values stored with a lab
*/
interface IValue {
/**
* Flag indicating whether or not this value is considered a hint
*/
isHint: boolean;
/**
* The value
*/
value: any;
}
}
declare module Labs.Core {
/**
* Lab configuration data structure
*/
interface IConfiguration extends Core.IUserData {
/**
* The version of the application associated with this configuration
*/
appVersion: Core.IVersion;
/**
* The components of the lab
*/
components: Core.IComponent[];
/**
* The name of the lab
*/
name: string;
/**
* Lab timeline configuration
*/
timeline: Core.ITimelineConfiguration;
/**
* Lab analytics configuration
*/
analytics: Core.IAnalyticsConfiguration;
}
}
declare module Labs.Core {
/**
* Base class for instances of a lab configuration. An instance is an instantiation of a configuration for a user. It contains
* a translated view of the configuration for a particular run of the lab. This view may exclude hidden information (answers, hints, etc...)
* and also contains IDs to identify the various instances.
*/
interface IConfigurationInstance extends Core.IUserData {
/**
* The version of the application associated with this configuration
*/
appVersion: Core.IVersion;
/**
* The components of the lab
*/
components: Core.IComponentInstance[];
/**
* The name of the lab
*/
name: string;
/**
* Lab timeline configuration
*/
timeline: Core.ITimelineConfiguration;
}
}
declare module Labs.Core {
/**
* Base class for components of a lab.
*/
interface IComponent extends Core.ILabObject, Core.IUserData {
/**
* The name of the component
*/
name: string;
/**
* value property map associated with the component
*/
values: {
[type: string]: Core.IValue[];
};
}
}
declare module Labs.Core {
/**
* The current mode of the lab. Whether in edit mode or view mode. Edit is when configuring the lab and view
* is when taking the lab.
*/
enum LabMode {
/**
* The lab is in edit mode. Meaning the user is configuring it
*/
Edit,
/**
* The lab is in view mode. Meaning the user is taking it
*/
View,
}
}
declare module Labs.Core {
/**
* The ILabHost interfaces provides an abstraction for connecting Labs.js to the host
*/
interface ILabHost {
/**
* Retrieves the versions supported by this lab host.
*/
getSupportedVersions(): Core.ILabHostVersionInfo[];
/**
* Initializes communication with the host
*
* @param { versions } The list of versions that the client of the host can make use of
* @param { callback } Callback for when the connection is complete
*/
connect(versions: Core.ILabHostVersionInfo[], callback: Core.ILabCallback<Core.IConnectionResponse>);
/**
* Stops communication with the host
*
* @param { completionStatus } The final status of the lab at the time of the disconnect
* @param { callback } Callback fired when the disconnect completes
*/
disconnect(callback: Core.ILabCallback<void>);
/**
* Adds an event handler for dealing with messages coming from the host. The resolved promsie
* will be returned back to the host
*
* @param { handler } The event handler
*/
on(handler: (string: any, any: any) => void);
/**
* Sends a message to the host
*
* @param { type } The type of message being sent
* @param { options } The options for that message
* @param { callback } Callback invoked once the message has been received
*/
sendMessage(type: string, options: Core.IMessage, callback: Core.ILabCallback<Core.IMessageResponse>);
/**
* Creates the lab. Stores the host information and sets aside space for storing the configuration and other elements.
*
* @param { options } Options passed as part of creation
*/
create(options: Core.ILabCreationOptions, callback: Core.ILabCallback<void>);
/**
* Gets the current lab configuration from the host
*
* @param { callback } Callback method for retrieving configuration information
*/
getConfiguration(callback: Core.ILabCallback<Core.IConfiguration>);
/**
* Sets a new lab configuration on the host
*
* @param { configuration } The lab configuration to set
* @param { callback } Callback fired when the configuration is set
*/
setConfiguration(configuration: Core.IConfiguration, callback: Core.ILabCallback<void>);
/**
* Retrieves the instance configuration for the lab
*
* @param { callback } Callback that will be called when the configuration instance is retrieved
*/
getConfigurationInstance(callback: Core.ILabCallback<Core.IConfigurationInstance>);
/**
* Gets the current state of the lab for the user
*
* @param { completionStatus } Callback that will return the current lab state
*/
getState(callback: Core.ILabCallback<any>);
/**
* Sets the state of the lab for the user
*
* @param { state } The lab state
* @param { callback } Callback that will be invoked when the state has been set
*/
setState(state: any, callback: Core.ILabCallback<void>);
/**
* Takes an attempt action
*
* @param { type } The type of action
* @param { options } The options provided with the action
* @param { callback } Callback which returns the final executed action
*/
takeAction(type: string, options: Core.IActionOptions, callback: Core.ILabCallback<Core.IAction>);
/**
* Takes an action that has already been completed
*
* @param { type } The type of action
* @param { options } The options provided with the action
* @param { result } The result of the action
* @param { callback } Callback which returns the final executed action
*/
takeAction(type: string, options: Core.IActionOptions, result: Core.IActionResult, callback: Core.ILabCallback<Core.IAction>);
/**
* Retrieves the actions for a given attempt
*
* @param { type } The type of get action
* @param { options } The options provided with the get action
* @param { callback } Callback which returns the list of completed actions
*/
getActions(type: string, options: Core.IGetActionOptions, callback: Core.ILabCallback<Core.IAction[]>);
}
}
declare module Labs.Core {
/**
* Static class representing the permissions allowed for the given user of the lab
*/
class Permissions {
/**
* Ability to edit the lab
*/
static Edit: string;
/**
* Ability to take the lab
*/
static Take: string;
}
}
declare module Labs.Core.Actions {
/**
* Closes the component and indicates there will be no future actions against it.
*/
var CloseComponentAction: string;
/**
* Closes a component and indicates there will be no more actions against it.
*/
interface ICloseComponentOptions extends Core.IActionOptions {
/**
* The component to close.
*/
componentId: string;
}
}
declare module Labs.Core.Actions {
/**
* Action to create a new attempt
*/
var CreateAttemptAction: string;
/**
* Creates a new attempt for the given component.
*/
interface ICreateAttemptOptions extends Core.IActionOptions {
/**
* The component the attempt is associated with
*/
componentId: string;
}
}
declare module Labs.Core.Actions {
/**
* The result of creating an attempt for the given component.
*/
interface ICreateAttemptResult extends Core.IActionResult {
/**
* The ID of the created attempt
*/
attemptId: string;
}
}
declare module Labs.Core.Actions {
/**
* Action to create a new component
*/
var CreateComponentAction: string;
/**
* Creates a new component
*/
interface ICreateComponentOptions extends Core.IActionOptions {
/**
* The component invoking the create component action.
*/
componentId: string;
/**
* The component to create
*/
component: Core.IComponent;
/**
* An (optional) field used to correlate this component across all instances of a lab.
* Allows the hosting system to identify different attempts at the same component.
*/
correlationId?: string;
}
}
declare module Labs.Core.Actions {
/**
* The result of creating a new component.
*/
interface ICreateComponentResult extends Core.IActionResult {
/**
* The created component instance
*/
componentInstance: Core.IComponentInstance;
}
}
declare module Labs.Core.Actions {
/**
* The result of a get value action
*/
interface IGetValueResult extends Core.IActionResult {
/**
* The retrieved value
*/
value: any;
}
}
declare module Labs.Core.Actions {
/**
* The result of submitting an answer for an attempt
*/
interface ISubmitAnswerResult extends Core.IActionResult {
/**
* An ID associated with the submission. Will be filled in by the server.
*/
submissionId: string;
/**
* Whether the attempt is complete due to this submission
*/
complete: boolean;
/**
* Scoring information associated with the submission
*/
score: any;
}
}
declare module Labs.Core.Actions {
/**
* Attempt timeout action
*/
var AttemptTimeoutAction: string;
/**
* Options for the attempt timeout action
*/
interface IAttemptTimeoutOptions extends Core.IActionOptions {
/**
* The ID of the attempt that timed out
*/
attemptId: string;
}
}
declare module Labs.Core.Actions {
/**
* Action to retrieve a value associated with an attempt.
*/
var GetValueAction: string;
interface IGetValueOptions extends Core.IActionOptions {
/**
* The component the get value is associated with
*/
componentId: string;
/**
* The attempt to get the value for
*/
attemptId: string;
/**
* The ID of the value to receive
*/
valueId: string;
}
}
declare module Labs.Core.Actions {
/**
* Resume attempt action. Used to indicate the user is resuming work on a given attempt.
*/
var ResumeAttemptAction: string;
/**
* Options associated with a resume attempt
*/
interface IResumeAttemptOptions extends Core.IActionOptions {
/**
* The component the attempt is associated with
*/
componentId: string;
/**
* The attempt that is being resumed
*/
attemptId: string;
}
}
declare module Labs.Core.Actions {
/**
* Action to submit an answer for a given attempt
*/
var SubmitAnswerAction: string;
/**
* Options for the submit answer action
*/
interface ISubmitAnswerOptions extends Core.IActionOptions {
/**
* The component the submission is associated with
*/
componentId: string;
/**
* The attempt the submission is associated with
*/
attemptId: string;
/**
* The answer being submitted
*/
answer: any;
}
}
declare module Labs.Core.GetActions {
/**
* Gets actions associated with a given component.
*/
var GetComponentActions: string;
/**
* Options associated with a get component actions
*/
interface IGetComponentActionsOptions extends Core.IGetActionOptions {
/**
* The component being searched for
*/
componentId: string;
/**
* The type of action being searched for
*/
action: string;
}
}
declare module Labs.Core.GetActions {
/**
* Get attempt get action. Retrieves all actions associated with a given attempt.
*/
var GetAttempt: string;
/**
* Options associated with a get attempt get action.
*/
interface IGetAttemptOptions extends Core.IGetActionOptions {
/**
* The attempt ID to retrieve all the actions for
*/
attemptId: string;
}
}
declare module Labs.Core {
/**
* Interface for EventManager callbacks
*/
interface IEventCallback {
(data: any): void;
}
}
declare module Labs {
var TimelineNextMessageType: string;
interface ITimelineNextMessage extends Labs.Core.IMessage {
status: Labs.Core.ICompletionStatus;
}
}
declare module Labs {
/**
* Base class for components instances
*/
class ComponentInstanceBase {
/**
* The ID of the component
*/
public _id: string;
/**
* The LabsInternal object for use by the component instance
*/
public _labs: Labs.LabsInternal;
constructor();
/**
* Attaches a LabsInternal to this component instance
*
* @param { id } The ID of the component
* @param { labs } The LabsInternal object for use by the instance
*/
public attach(id: string, labs: Labs.LabsInternal): void;
}
}
declare module Labs {
/**
* Class representing a component instance. An instance is an instantiation of a component for a user. It contains
* a translated view of the component for a particular run of the lab.
*/
class ComponentInstance<T> extends Labs.ComponentInstanceBase {
/**
* Constructs a new ComponentInstance.
*/
constructor();
/**
* Begins a new attempt at the component
*
* @param { callback } Callback fired when the attempt has been created
*/
public createAttempt(callback: Labs.Core.ILabCallback<T>): void;
/**
* Retrieves all attempts associated with the given component
*
* @param { callback } Callback fired once the attempts have been retrieved
*/
public getAttempts(callback: Labs.Core.ILabCallback<T[]>): void;
/**
* Retrieves the default create attempt options. Can be overriden by derived classes.
*/
public getCreateAttemptOptions(): Labs.Core.Actions.ICreateAttemptOptions;
/**
* method to built an attempt from the given action. Should be implemented by derived classes.
*
* @param { createAttemptResult } The create attempt action for the attempt
*/
public buildAttempt(createAttemptResult: Labs.Core.IAction): T;
}
}
declare module Labs {
/**
* Enumeration of the connection states
*/
enum ConnectionState {
/**
* Disconnected
*/
Disconnected,
/**
* In the process of connecting
*/
Connecting,
/**
* Connected
*/
Connected,
}
}
declare module Labs {
/**
* Helper class to manage a set of event handlers
*/
class EventManager {
private _handlers;
private getHandler(event);
/**
* Adds a new event handler for the given event
*
* @param { event } The event to add a handler for
* @param { handler } The event handler to add
*/
public add(event: string, handler: Labs.Core.IEventCallback): void;
/**
* Removes an event handler for the given event
*
* @param { event } The event to remove a handler for
* @param { handler } The event handler to remove
*/
public remove(event: string, handler: Labs.Core.IEventCallback): void;
/**
* Fires the given event
*
* @param { event } The event to fire
* @param { data } Data associated with the event
*/
public fire(event: string, data: any): void;
}
}
declare module Labs {
/**
* The LabEditor allows for the editing of the given lab. This includes getting and setting
* the entire configuration associated with the lab.
*/
class LabEditor {
private _labsInternal;
private _doneCallback;
/**
* Constructs a new LabEditor
*
* @param { labsInternal } LabsInternal to use with the editor
* @param { doneCallback } Callback to invoke when the editor is finished
*/
constructor(labsInternal: Labs.LabsInternal, doneCallback: Function);
/**
* Creates a new lab. This prepares the lab storage and saves the host version
*
* @param { labsInternal } LabsInternal to use with the editor
* @param { doneCallback } Callback to invoke when the editor is finished
* @param { callback } Callback fired once the LabEditor has been created
*/
static Create(labsInternal: Labs.LabsInternal, doneCallback: Function, callback: Labs.Core.ILabCallback<LabEditor>): void;
/**
* Gets the current lab configuration
*
* @param { callback } Callback fired once the configuration has been retrieved
*/
public getConfiguration(callback: Labs.Core.ILabCallback<Labs.Core.IConfiguration>): void;
/**
* Sets a new lab configuration
*
* @param { configuration } The configuration to set
* @param { callback } Callback fired once the configuration has been set
*/
public setConfiguration(configuration: Labs.Core.IConfiguration, callback: Labs.Core.ILabCallback<void>): void;
/**
* Indicates that the user is done editing the lab.
*
* @param { callback } Callback fired once the lab editor has finished
*/
public done(callback: Labs.Core.ILabCallback<void>): void;
}
}
declare module Labs {
/**
* A LabInstance is an instance of the configured lab for the current user. It is used to
* record and retrieve per user lab data.
*/
class LabInstance {
private _labsInternal;
private _doneCallback;
public data: any;
/**
* The components that make up the lab instance
*/
public components: Labs.ComponentInstanceBase[];
/**
* Constructs a new LabInstance
*
* @param { labsInternal } The LabsInternal to use with the instance
* @param { components } The components of the lab instance
* @param { doneCallback } Callback to invoke once the user is done taking the instance
* @param { data } Custom data attached to the lab
*/
constructor(labsInternal: Labs.LabsInternal, components: Labs.ComponentInstanceBase[], doneCallback: Function, data: any);
/**
* Creates a new LabInstance
*
* @param { labsInternal } The LabsInternal to use with the instance
* @param { doneCallback } Callback to invoke once the user is done taking the instance
* @param { callback } Callback that fires once the LabInstance has been created
*/
static Create(labsInternal: Labs.LabsInternal, doneCallback: Function, callback: Labs.Core.ILabCallback<LabInstance>): void;
/**
* Gets the current state of the lab for the user
*
* @param { callback } Callback that fires with the lab state
*/
public getState(callback: Labs.Core.ILabCallback<any>): void;
/**
* Sets the state of the lab for the user
*
* @param { state } The state to set
* @param { callback } Callback that fires once the state is set
*/
public setState(state: any, callback: Labs.Core.ILabCallback<void>): void;
/**
* Indicates that the user is done taking the lab.
*
* @param { callback } Callback fired once the lab instance has finished
*/
public done(callback: Labs.Core.ILabCallback<void>): void;
}
}
declare module Labs {
/**
* Method to use to construct a default ILabHost
*/
var DefaultHostBuilder: () => Core.ILabHost;
/**
* Initializes a connection with the host.
*
* @param { labHost } The (optional) ILabHost to use. If not specified will be constructed with the DefaultHostBuilder
* @param { callback } Callback to fire once the connection has been established
*/
function connect(callback: Core.ILabCallback<Core.IConnectionResponse>);
function connect(labHost: Core.ILabHost, callback: Core.ILabCallback<Core.IConnectionResponse>);
/**
* Returns whether or not the labs are connected to the host.
*/
function isConnected(): boolean;
/**
* Retrieves the information associated with a connection
*/
function getConnectionInfo(): Core.IConnectionResponse;
/**
* Disconnects from the host.
*
* @param { completionStatus } The final result of the lab interaction
*/
function disconnect(): void;
/**
* Opens the lab for editing. When in edit mode the configuration can be specified. A lab cannot be edited while it
* is being taken.
*
* @param { callback } Callback fired once the LabEditor is created
*/
function editLab(callback: Core.ILabCallback<LabEditor>): void;
/**
* Takes the given lab. This allows results to be sent for the lab. A lab cannot be taken while it is being edited.
*
* @param { callback } Callback fired once the LabInstance is created
*/
function takeLab(callback: Core.ILabCallback<LabInstance>): void;
/**
* Adds a new event handler for the given event
*
* @param { event } The event to add a handler for
* @param { handler } The event handler to add
*/
function on(event: string, handler: Core.IEventCallback): void;
/**
* Removes an event handler for the given event
*
* @param { event } The event to remove a handler for
* @param { handler } The event handler to remove
*/
function off(event: string, handler: Core.IEventCallback): void;
/**
* Retrieves the Timeline object that can be used to control the host's player control.
*/
function getTimeline(): Timeline;
/**
* Registers a function to deserialize the given type. Should be used by component authors only.
*
* @param { type } The type to deserialize
* @param { deserialize } The deserialization function
*/
function registerDeserializer(type: string, deserialize: (json: Core.ILabObject) => any): void;
/**
* Deserializes the given json object into an object. Should be used by component authors only.
*
* @param { json } The ILabObject to deserialize
*/
function deserialize(json: Core.ILabObject): any;
}
declare module Labs {
/**
* Class used to interface with the underlying ILabsHost interface.
*/
class LabsInternal {
/**
* Current state of the LabsInternal
*/
private _state;
/**
* The driver to send our commands to
*/
private _labHost;
/**
* Helper class to manage events in the system
*/
private _eventManager;
/**
* The cached configuration and state for the lab
*/
private _configuration;
/**
* The version of the host this LabsInternal is making use of
*/
private _hostVersion;
/**
* Start out queueing pending messages until we are notified to invoke them
*/
private _queuePendingMessages;
/**
* Pending messages to invoke from the EventManager
*/
private _pendingMessages;
/**
* Constructs a new LabsInternal
*
* @param { labHost } The ILabHost to make use of
*/
constructor(labHost: Labs.Core.ILabHost);
/**
* Connect to the host
*
* @param { callback } Callback that will return the IConnectionResponse when connected
*/
public connect(callback: Labs.Core.ILabCallback<Labs.Core.IConnectionResponse>): void;
/**
* Fires all pending messages
*/
public firePendingMessages(): void;
/**
* Creates a new lab
*
* @param { callback } Callback fired once the create operation completes
*/
public create(callback: Labs.Core.ILabCallback<void>): void;
/**
* Terminates the LabsInternal class and halts the connection.
*/
public dispose(): void;
/**
* Adds an event handler for the given event
*
* @param { event } The event to listen for
* @param { handler } Handler fired for the given event
*/
public on(event: string, handler: Labs.Core.IEventCallback): void;
/**
* Sends a message to the host
*
* @param { type } The type of message being sent
* @param { options } The options for that message
* @param { callback } Callback invoked once the message has been received
*/
public sendMessage(type: string, options: Labs.Core.IMessage, callback: Labs.Core.ILabCallback<Labs.Core.IMessageResponse>): void;
/**
* Removes an event handler for the given event
*
* @param { event } The event whose handler should be removed
* @param { handler } Handler to remove
*/
public off(event: string, handler: Labs.Core.IEventCallback): void;
/**
* Gets the current state of the lab for the user
*
* @param { callback } Callback that fires when the state is retrieved
*/
public getState(callback: Labs.Core.ILabCallback<any>): void;
/**
* Sets the state of the lab for the user
*
* @param { state } The state to set
* @param { callback } Callback fired once the state has been set
*/
public setState(state: any, callback: Labs.Core.ILabCallback<void>): void;
/**
* Gets the current lab configuration
*
* @param { callback } Callback that fires when the configuration is retrieved
*/
public getConfiguration(callback: Labs.Core.ILabCallback<Labs.Core.IConfiguration>): void;
/**
* Sets a new lab configuration
*
* @param { configuration } The lab configuration to set
* @param { callback } Callback that fires once the configuration has been set
*/
public setConfiguration(configuration: Labs.Core.IConfiguration, callback: Labs.Core.ILabCallback<void>): void;
/**
* Retrieves the configuration instance for the lab.
*
* @param { callback } Callback that fires when the configuration instance has been retrieved
*/
public getConfigurationInstance(callback: Labs.Core.ILabCallback<Labs.Core.IConfigurationInstance>): void;
/**
* Takes an action
*
* @param { type } The type of action to take
* @param { options } The options associated with the action
* @param { result } The result of the action
* @param { callback } Callback that fires once the action has completed
*/
public takeAction(type: string, options: Labs.Core.IActionOptions, callback: Labs.Core.ILabCallback<Labs.Core.IAction>);
public takeAction(type: string, options: Labs.Core.IActionOptions, result: Labs.Core.IActionResult, callback: Labs.Core.ILabCallback<Labs.Core.IAction>);
/**
* Retrieves actions
*
* @param { type } The type of get to perform
* @param { options } The options associated with the get
* @param { callback } Callback that fires with the completed actions
*/
public getActions(type: string, options: Labs.Core.IGetActionOptions, callback: Labs.Core.ILabCallback<Labs.Core.IAction[]>): void;
/**
* Checks whether or not the LabsInternal is initialized
*/
private checkIsInitialized();
}
}
declare module Labs {
/**
* Provides access to the labs.js timeline
*/
class Timeline {
private _labsInternal;
constructor(labsInternal: Labs.LabsInternal);
/**
* Used to indicate that the timeline should advance to the next slide.
*/
public next(completionStatus: Labs.Core.ICompletionStatus, callback: Labs.Core.ILabCallback<void>): void;
}
}
declare module Labs {
/**
* A ValueHolder is responsible for holding a value that when requested is tracked by labs.js.
* This value may be stored locally or stored on the server.
*/
class ValueHolder<T> {
/**
* The component the value is associated with
*/
private _componentId;
/**
* Attempt the value is associated with
*/
private _attemptId;
/**
* Underlying labs device
*/
private _labs;
/**
* Whether or not the value is a hint
*/
public isHint: boolean;
/**
* Whether or not the value has been requested.
*/
public hasBeenRequested: boolean;
/**
* Whether or not the value holder currently has the value.
*/
public hasValue: boolean;
/**
* The value held by the holder.
*/
public value: T;
/**
* The ID for the value
*/
public id: string;
/**
* Constructs a new ValueHolder
*
* @param { componentId } The component the value is associated with
* @param { attemptId } The attempt the value is associated with
* @param { id } The id of the value
* @param { labs } The labs device that can be used to request the value
* @param { isHint } Whether or not the value is a hint
* @param { hasBeenRequested } Whether or not the value has already been requested
* @param { hasValue } Whether or not the value is available
* @param { value } If hasValue is true this is the value, otherwise is optional
*/
constructor(componentId: string, attemptId: string, id: string, labs: Labs.LabsInternal, isHint: boolean, hasBeenRequested: boolean, hasValue: boolean, value?: T);
/**
* Retrieves the given value
*
* @param { callback } Callback that returns the given value
*/
public getValue(callback: Labs.Core.ILabCallback<T>): void;
/**
* Internal method used to actually provide a value to the value holder
*
* @param { value } The value to set for the holder
*/
public provideValue(value: T): void;
}
}
declare module Labs.Components {
/**
* Base class for attempts
*/
class ComponentAttempt {
public _componentId: string;
public _id: string;
public _labs: Labs.LabsInternal;
public _resumed: boolean;
public _state: Labs.ProblemState;
public _values: {
[type: string]: Labs.ValueHolder<any>[];
};
/**
* Constructs a new ComponentAttempt.
*
* @param { labs } The LabsInternal to use with the attempt
* @param { attemptId } The ID associated with the attempt
* @param { values } The values associated with the attempt
*/
constructor(labs: Labs.LabsInternal, componentId: string, attemptId: string, values: {
[type: string]: Labs.Core.IValueInstance[];
});
/**
* Verifies that the attempt has been resumed
*/
public verifyResumed(): void;
/**
* Returns whether or not the app has been resumed
*/
public isResumed(): boolean;
/**
* Used to indicate that the lab has resumed progress on the given attempt. Loads in existing data as part of this process. An attempt
* must be resumed before it can be used.
*
* @param { callback } Callback fired once the attempt is resumed
*/
public resume(callback: Labs.Core.ILabCallback<void>): void;
/**
* Helper method to send the resume action to the host
*/
private sendResumeAction(callback);
/**
* Runs over the retrieved actions for the attempt and populates the state of the lab
*/
private resumeCore(actions);
/**
* Retrieves the state of the lab
*/
public getState(): Labs.ProblemState;
public processAction(action: Labs.Core.IAction): void;
/**
* Retrieves the cached values associated with the attempt
*
* @param { key } The key to lookup in the value map
*/
public getValues(key: string): Labs.ValueHolder<any>[];
/**
* Makes use of a value in the value array
*/
private useValue(completedSubmission);
}
}
declare module Labs.Components {
/**
* A class representing an attempt at an activity component
*/
class ActivityComponentAttempt extends Components.ComponentAttempt {
constructor(labs: Labs.LabsInternal, componentId: string, attemptId: string, values: {
[type: string]: Labs.Core.IValueInstance[];
});
/**
* Called to indicate that the activity has completed
*
* @param { callback } Callback invoked once the activity has completed
*/
public complete(callback: Labs.Core.ILabCallback<void>): void;
/**
* Runs over the retrieved actions for the attempt and populates the state of the lab
*/
public processAction(action: Labs.Core.IAction): void;
}
}
declare module Labs.Components {
var ActivityComponentInstanceType: string;
class ActivityComponentInstance extends Labs.ComponentInstance<Components.ActivityComponentAttempt> {
/**
* The underlying IActivityComponentInstance this class represents
*/
public component: Components.IActivityComponentInstance;
/**
* Constructs a new ActivityComponentInstnace
*
* @param { component } The IActivityComponentInstance to create this class from
*/
constructor(component: Components.IActivityComponentInstance);
/**
* Builds a new ActivityComponentAttempt. Implements abstract method defined on the base class.
*
* @param { createAttemptResult } The result from a create attempt action
*/
public buildAttempt(createAttemptAction: Labs.Core.IAction): Components.ActivityComponentAttempt;
}
}
declare module Labs.Components {
/**
* Answer to a choice component problem
*/
class ChoiceComponentAnswer {
/**
* The answer value
*/
public answer: any;
/**
* Constructs a new ChoiceComponentAnswer
*/
constructor(answer: any);
}
}
declare module Labs.Components {
/**
* A class representing an attempt at a choice component
*/
class ChoiceComponentAttempt extends Components.ComponentAttempt {
private _submissions;
/**
* Constructs a new ChoiceComponentAttempt.
*
* @param { labs } The LabsInternal to use with the attempt
* @param { attemptId } The ID associated with the attempt
* @param { values } The values associated with the attempt
*/
constructor(labs: Labs.LabsInternal, componentId: string, attemptId: string, values: {
[type: string]: Labs.Core.IValueInstance[];
});
/**
* Used to mark that the lab has timed out
*
* @param { callback } Callback fired once the server has received the timeout message
*/
public timeout(callback: Labs.Core.ILabCallback<void>): void;
/**
* Retrieves all of the submissions that have previously been submitted for the given attempt
*/
public getSubmissions(): Components.ChoiceComponentSubmission[];
/**
* Submits a new answer that was graded by the lab and will not use the host to compute a grade.
*
* @param { answer } The answer for the attempt
* @param { result } The result of the submission
* @param { callback } Callback fired once the submission has been received
*/
public submit(answer: Components.ChoiceComponentAnswer, result: Components.ChoiceComponentResult, callback: Labs.Core.ILabCallback<Components.ChoiceComponentSubmission>): void;
public processAction(action: Labs.Core.IAction): void;
/**
* Helper method used to handle a returned submission from labs core
*/
private storeSubmission(completedSubmission);
}
}
declare module Labs.Components {
/**
* The name of the component instance. A choice component is a component that has multiple choice options and supports zero
* or more responses. Optionally there is a correct list of choices.
*/
var ChoiceComponentInstanceType: string;
/**
* Class representing a choice component instance
*/
class ChoiceComponentInstance extends Labs.ComponentInstance<Components.ChoiceComponentAttempt> {
/**
* The underlying IChoiceComponentInstance this class represents
*/
public component: Components.IChoiceComponentInstance;
/**
* Constructs a new ChoiceComponentInstance
*
* @param { component } The IChoiceComponentInstance to create this class from
*/
constructor(component: Components.IChoiceComponentInstance);
/**
* Builds a new ChoiceComponentAttempt. Implements abstract method defined on the base class.
*
* @param { createAttemptResult } The result from a create attempt action
*/
public buildAttempt(createAttemptAction: Labs.Core.IAction): Components.ChoiceComponentAttempt;
}
}
declare module Labs.Components {
/**
* The name of the component instance. A dynamic component is a component that allows for new components to be inserted within it.
*/
var DynamicComponentInstanceType: string;
/**
* Class representing a dynamic component. A dynamic component is used to create, at runtime, new components.
*/
class DynamicComponentInstance extends Labs.ComponentInstanceBase {
public component: Components.IDynamicComponentInstance;
/**
* Constructs a new dynamic component instance from the provided definition
*/
constructor(component: Components.IDynamicComponentInstance);
/**
* Retrieves all the components created by this dynamic component.
*/
public getComponents(callback: Labs.Core.ILabCallback<Labs.ComponentInstanceBase[]>): void;
/**
* Creates a new component.
*/
public createComponent(component: Labs.Core.IComponent, callback: Labs.Core.ILabCallback<Labs.ComponentInstanceBase>): void;
private createComponentInstance(action);
/**
* Used to indicate that there will be no more submissions associated with this component
*/
public close(callback: Labs.Core.ILabCallback<void>): void;
/**
* Returns whether or not the dynamic component is closed
*/
public isClosed(callback: Labs.Core.ILabCallback<boolean>): void;
}
}
declare module Labs.Components {
/**
* Type string for an ActivityComponent
*/
var ActivityComponentType: string;
/**
* An activity component is simply an activity for the taker to experience. Examples are viewing a web page
* or watching a video.
*/
interface IActivityComponent extends Labs.Core.IComponent {
/**
* Whether or not the input component is secure. This is not yet implemented.
*/
secure: boolean;
}
}
declare module Labs.Components {
interface IActivityComponentInstance extends Labs.Core.IComponentInstance {
}
}
declare module Labs.Components {
/**
* A choice for a problem
*/
interface IChoice {
/**
* Unique id to represent the choice
*/
id: string;
/**
* Display string to use to represent the value
* I think I should put this into the value type - have default ones show up - and then have custom values within
*/
name: string;
/**
* The value of the choice
*/
value: any;
}
}
declare module Labs.Components {
/**
* Type string to use with this type of component
*/
var ChoiceComponentType: string;
/**
* A choice problem is a problem type where the user is presented with a list of choices and then needs to select
* an answer from them.
*/
interface IChoiceComponent extends Labs.Core.IComponent {
/**
* The list of choices associated with the problem
*/
choices: Components.IChoice[];
/**
* A time limit for the problem
*/
timeLimit: number;
/**
* The maximum number of attempts allowed for the problem
*/
maxAttempts: number;
/**
* The max score for the problem
*/
maxScore: number;
/**
* Whether or not this problem has an answer
*/
hasAnswer: boolean;
/**
* The answer. Either an array if multiple answers are supported or a single ID if only one answer is supported.
*/
answer: any;
/**
* Whether or not the quiz is secure - meaning that secure fields are held from the user.
* This is not yet implemented.
*/
secure: boolean;
}
}
declare module Labs.Components {
/**
* An instance of a choice component
*/
interface IChoiceComponentInstance extends Labs.Core.IComponentInstance {
/**
* The list of choices associated with the problem
*/
choices: Components.IChoice[];
/**
* A time limit for the problem
*/
timeLimit: number;
/**
* The maximum number of attempts allowed for the problem
*/
maxAttempts: number;
/**
* The max score for the problem
*/
maxScore: number;
/**
* Whether or not this problem has an answer
*/
hasAnswer: boolean;
/**
* The answer. Either an array if multiple answers are supported or a single ID if only one answe is supported.
*/
answer: any;
/**
* Whether or not the quiz is secure - meaning that secure fields are held from the user
*/
secure: boolean;
}
}
declare module Labs.Components {
var Infinite: number;
/**
* Type string for a dynamic component
*/
var DynamicComponentType: string;
/**
* A dynamic component represents one that can generate other components at runtime.
* This can be used for branching questions, dynamically generated ones, etc...
*/
interface IDynamicComponent extends Labs.Core.IComponent {
/**
* An array containing the types of components this dynamic component may generate
*/
generatedComponentTypes: string[];
/**
* The maximum number of components that will be generated by this DynamicComponent. Or Labs.Components.Infinite if
* there is no cap.
*/
maxComponents: number;
}
}
declare module Labs.Components {
/**
* An instance of a dynamic component.
*/
interface IDynamicComponentInstance extends Labs.Core.IComponentInstance {
/**
* An array containing the types of components this dynamic component may generate
*/
generatedComponentTypes: string[];
/**
* The maximum number of components that will be generated by this DynamicComponent. Or Labs.Components.Infinite if
* there is no cap.
*/
maxComponents: number;
}
}
declare module Labs.Components {
/**
* A hint in a lab
*/
interface IHint extends Labs.Core.IValue {
/**
* Display value to use for the hint
*/
name: string;
}
}
declare module Labs.Components {
/**
* Type string to use with this type of component
*/
var InputComponentType: string;
/**
* An input problem is one in which the user enters an input which is checked against a correct value.
*/
interface IInputComponent extends Labs.Core.IComponent {
/**
* The max score for the input component
*/
maxScore: number;
/**
* Time limit associated with the input problem
*/
timeLimit: number;
/**
* Whether or not the component has an answer
*/
hasAnswer: boolean;
/**
* The answer to the component (if it exists)
*/
answer: any;
/**
* Whether or not the input component is secure. This is not yet implemented.
*/
secure: boolean;
}
}
declare module Labs.Components {
/**
* An input problem is one in which the user enters an input which is checked against a correct value.
*/
interface IInputComponentInstance extends Labs.Core.IComponentInstance {
/**
* The max score for the input component
*/
maxScore: number;
/**
* Time limit associated with the input problem
*/
timeLimit: number;
/**
* The answer to the component
*/
answer: any;
}
}
declare module Labs.Components {
/**
* Answer to an input component problem
*/
class InputComponentAnswer {
/**
* The answer value
*/
public answer: any;
/**
* Constructs a new InputComponentAnswer
*/
constructor(answer: any);
}
}
declare module Labs.Components {
/**
* A class representing an attempt at an input component
*/
class InputComponentAttempt extends Components.ComponentAttempt {
private _submissions;
constructor(labs: Labs.LabsInternal, componentId: string, attemptId: string, values: {
[type: string]: Labs.Core.IValueInstance[];
});
/**
* Runs over the retrieved actions for the attempt and populates the state of the lab
*/
public processAction(action: Labs.Core.IAction): void;
/**
* Retrieves all of the submissions that have previously been submitted for the given attempt
*/
public getSubmissions(): Components.InputComponentSubmission[];
/**
* Submits a new answer that was graded by the lab and will not use the host to compute a grade.
*
* @param { answer } The answer for the attempt
* @param { result } The result of the submission
* @param { callback } Callback fired once the submission has been received
*/
public submit(answer: Components.InputComponentAnswer, result: Components.InputComponentResult, callback: Labs.Core.ILabCallback<Components.InputComponentSubmission>): void;
/**
* Helper method used to handle a returned submission from labs core
*/
private storeSubmission(completedSubmission);
}
}
declare module Labs.Components {
/**
* The name of the component instance. An input component is a component that allows free form
* input from a user.
*/
var InputComponentInstanceType: string;
/**
* Class representing an input component instance
*/
class InputComponentInstance extends Labs.ComponentInstance<Components.InputComponentAttempt> {
/**
* The underlying IInputComponentInstance this class represents
*/
public component: Components.IInputComponentInstance;
/**
* Constructs a new InputComponentInstance
*
* @param { component } The IInputComponentInstance to create this class from
*/
constructor(component: Components.IInputComponentInstance);
/**
* Builds a new InputComponentAttempt. Implements abstract method defined on the base class.
*
* @param { createAttemptResult } The result from a create attempt action
*/
public buildAttempt(createAttemptAction: Labs.Core.IAction): Components.InputComponentAttempt;
}
}
declare module Labs.Components {
/**
* The result of an input component submission
*/
class InputComponentResult {
/**
* The score associated with the submission
*/
public score: any;
/**
* Whether or not the result resulted in the completion of the attempt
*/
public complete: boolean;
/**
* Constructs a new InputComponentResult
*
* @param { score } The score of the result
* @param { complete } Whether or not the result completed the attempt
*/
constructor(score: any, complete: boolean);
}
}
declare module Labs.Components {
/**
* Class that represents an input component submission
*/
class InputComponentSubmission {
/**
* The answer associated with the submission
*/
public answer: Components.InputComponentAnswer;
/**
* The result of the submission
*/
public result: Components.InputComponentResult;
/**
* The time at which the submission was received
*/
public time: number;
/**
* Constructs a new InputComponentSubmission
*
* @param { answer } The answer associated with the submission
* @param { result } The result of the submission
* @param { time } The time at which the submission was received
*/
constructor(answer: Components.InputComponentAnswer, result: Components.InputComponentResult, time: number);
}
}
declare module Labs {
/**
* State values for a lab
*/
enum ProblemState {
/**
* The problem is in progress
*/
InProgress,
/**
* The problem has timed out
*/
Timeout,
/**
* The problem has completed
*/
Completed,
}
}
declare module Labs.Components {
/**
* The result of a choice component submission
*/
class ChoiceComponentResult {
/**
* The score associated with the submission
*/
public score: any;
/**
* Whether or not the result resulted in the completion of the attempt
*/
public complete: boolean;
/**
* Constructs a new ChoiceComponentResult
*
* @param { score } The score of the result
* @param { complete } Whether or not the result completed the attempt
*/
constructor(score: any, complete: boolean);
}
}
declare module Labs.Components {
/**
* Class that represents a choice component submission
*/
class ChoiceComponentSubmission {
/**
* The answer associated with the submission
*/
public answer: Components.ChoiceComponentAnswer;
/**
* The result of the submission
*/
public result: Components.ChoiceComponentResult;
/**
* The time at which the submission was received
*/
public time: number;
/**
* Constructs a new ChoiceComponentSubmission
*
* @param { answer } The answer associated with the submission
* @param { result } The result of the submission
* @param { time } The time at which the submission was received
*/
constructor(answer: Components.ChoiceComponentAnswer, result: Components.ChoiceComponentResult, time: number);
}
}
declare module Labs {
/**
* General command used to pass messages between the client and host
*/
class Command {
public type: string;
public commandData: any;
/**
* Constructs a new command
*
* @param { type } The type of command
* @param { commandData } Optional data associated with the command
*/
constructor(type: string, commandData?: any);
}
}
/**
* Strings representing supported command types
*/
declare module Labs.CommandType {
var Connect: string;
var Disconnect: string;
var Create: string;
var GetConfigurationInstance: string;
var TakeAction: string;
var GetCompletedActions: string;
var ModeChanged: string;
var GetConfiguration: string;
var SetConfiguration: string;
var GetState: string;
var SetState: string;
var SendMessage: string;
}
declare module Labs.Core {
/**
* Static class containing the different event types.
*/
class EventTypes {
/**
* Mode changed event type. Fired whenever the lab mode is changed.
*/
static ModeChanged: string;
/**
* Event invoked when the app becomes active.
*/
static Activate: string;
/**
* Event invoked when the app is deactivated
*/
static Deactivate: string;
}
}
declare module Labs {
/**
* Command data associated with a GetActions command
*/
interface GetActionsCommandData {
/**
* The type of get
*/
type: string;
/**
* Options for the get command
*/
options: Labs.Core.IGetActionOptions;
}
}
declare module Labs {
/**
* Type of message being sent over the wire
*/
enum MessageType {
Message,
Completion,
Failure,
}
/**
* The message being sent
*/
class Message {
public id: number;
public labId: string;
public type: MessageType;
public payload: any;
constructor(id: number, labId: string, type: MessageType, payload: any);
}
/**
* Interface for defining event handlers
*/
interface IMessageHandler {
(origin: Window, data: any, callback: Labs.Core.ILabCallback<any>): void;
}
class MessageProcessor {
public isStarted: boolean;
public eventListener: EventListener;
public nextMessageId: number;
private messageMap;
public targetOrigin: string;
public messageHandler: IMessageHandler;
private _labId;
constructor(labId: string, targetOrigin: string, messageHandler: IMessageHandler);
private throwIfNotStarted();
private getNextMessageId();
private parseOrigin(href);
private listener(event);
private postMessage(targetWindow, message);
public start(): void;
public stop(): void;
public sendMessage(targetWindow: Window, data: any, callback: Labs.Core.ILabCallback<any>): void;
}
}
declare module Labs.Core {
/**
* Data associated with a mode changed event
*/
interface ModeChangedEventData {
/**
* The mode being set
*/
mode: string;
}
}
declare module Labs {
/**
* Data associated with a take action command
*/
interface SendMessageCommandData {
/**
* The type of message
*/
type: string;
/**
* Options associated with the message
*/
options: Labs.Core.IMessage;
}
}
declare module Labs {
/**
* Data associated with a take action command
*/
interface TakeActionCommandData {
/**
* The type of action
*/
type: string;
/**
* Options associated with the action
*/
options: Labs.Core.IActionOptions;
/**
* The result of the action
*/
result: Labs.Core.IActionResult;
}
}
declare module Labs {
interface IHostMessage {
type: string;
options: Labs.Core.IMessage;
response: Labs.Core.IMessageResponse;
}
class InMemoryLabHost implements Labs.Core.ILabHost {
private _version;
private _labState;
private _messages;
constructor(version: Labs.Core.IVersion);
public getSupportedVersions(): Labs.Core.ILabHostVersionInfo[];
public connect(versions: Labs.Core.ILabHostVersionInfo[], callback: Labs.Core.ILabCallback<Labs.Core.IConnectionResponse>): void;
public disconnect(callback: Labs.Core.ILabCallback<void>): void;
public on(handler: (string: any, any: any) => void): void;
public sendMessage(type: string, options: Labs.Core.IMessage, callback: Labs.Core.ILabCallback<Labs.Core.IMessageResponse>): void;
public getMessages(): IHostMessage[];
public create(options: Labs.Core.ILabCreationOptions, callback: Labs.Core.ILabCallback<void>): void;
public getConfiguration(callback: Labs.Core.ILabCallback<Labs.Core.IConfiguration>): void;
public setConfiguration(configuration: Labs.Core.IConfiguration, callback: Labs.Core.ILabCallback<void>): void;
public getState(callback: Labs.Core.ILabCallback<any>): void;
public setState(state: any, callback: Labs.Core.ILabCallback<void>): void;
public getConfigurationInstance(callback: Labs.Core.ILabCallback<Labs.Core.IConfigurationInstance>): void;
public takeAction(type: string, options: Labs.Core.IActionOptions, callback: Labs.Core.ILabCallback<Labs.Core.IAction>);
public takeAction(type: string, options: Labs.Core.IActionOptions, result: Labs.Core.IActionResult, callback: Labs.Core.ILabCallback<Labs.Core.IAction>);
public getActions(type: string, options: Labs.Core.IGetActionOptions, callback: Labs.Core.ILabCallback<Labs.Core.IAction[]>): void;
}
}
declare module Labs {
class InMemoryLabState {
private _configuration;
private _configurationInstance;
private _state;
private _actions;
private _nextId;
private _componentInstances;
constructor();
public getConfiguration(): Labs.Core.IConfiguration;
public setConfiguration(configuration: Labs.Core.IConfiguration): void;
public getState(): any;
public setState(state: any): void;
public getConfigurationInstance(): Labs.Core.IConfigurationInstance;
private getConfigurationInstanceFromConfiguration(configuration);
private getAndStoreComponentInstanceFromComponent(component);
public takeAction(type: string, options: Labs.Core.IActionOptions, result: any): Labs.Core.IAction;
private takeActionCore(type, options, result);
private findConfigurationValue(componentId, attemptId, valueId);
public getAllActions(): Labs.Core.IAction[];
public setActions(actions: Labs.Core.IAction[]): void;
public getActions(type: string, options: Labs.Core.IGetActionOptions): Labs.Core.IAction[];
}
}
interface OfficeInterface {
initialize: any;
context: any;
AsyncResultStatus: any;
Index: any;
GoToType: any;
}
declare var Office: OfficeInterface;
declare module Labs {
interface IPromise {
then(callback: Function);
}
class Resolver {
private _callbacks;
private _isResolved;
private _resolvedValue;
public promise: IPromise;
constructor();
public resolve(value?: any): void;
private fireCallbacks();
}
interface ILabsSettings {
/**
* The lab configuration
*/
configuration?: Labs.Core.IConfiguration;
/**
* The version of the host used to create the lab
*/
hostVersion?: Labs.Core.IVersion;
/**
* Boolean that is set to true when the lab is published
*/
published?: boolean;
/**
* The published ID of the lab
*/
publishedAppId?: string;
}
class OfficeJSLabHost implements Labs.Core.ILabHost {
private _officeInitialized;
private _labHost;
private _version;
static SettingsKeyName: string;
constructor();
public getSupportedVersions(): Labs.Core.ILabHostVersionInfo[];
public connect(versions: Labs.Core.ILabHostVersionInfo[], callback: Labs.Core.ILabCallback<Labs.Core.IConnectionResponse>): void;
public disconnect(callback: Labs.Core.ILabCallback<void>): void;
public on(handler: (string: any, any: any) => void): void;
public sendMessage(type: string, options: Labs.Core.IMessage, callback: Labs.Core.ILabCallback<Labs.Core.IMessageResponse>): void;
public create(options: Labs.Core.ILabCreationOptions, callback: Labs.Core.ILabCallback<void>): void;
public getConfiguration(callback: Labs.Core.ILabCallback<Labs.Core.IConfiguration>): void;
public setConfiguration(configuration: Labs.Core.IConfiguration, callback: Labs.Core.ILabCallback<void>): void;
public getConfigurationInstance(callback: Labs.Core.ILabCallback<Labs.Core.IConfigurationInstance>): void;
public getState(callback: Labs.Core.ILabCallback<any>): void;
public setState(state: any, callback: Labs.Core.ILabCallback<void>): void;
public takeAction(type: string, options: Labs.Core.IActionOptions, callback: Labs.Core.ILabCallback<Labs.Core.IAction>);
public takeAction(type: string, options: Labs.Core.IActionOptions, result: Labs.Core.IActionResult, callback: Labs.Core.ILabCallback<Labs.Core.IAction>);
public getActions(type: string, options: Labs.Core.IGetActionOptions, callback: Labs.Core.ILabCallback<Labs.Core.IAction[]>): void;
}
}
declare module Labs {
/**
* PostMessageLabHost - ILabHost that uses PostMessage for its communication mechanism
*/
class PostMessageLabHost implements Labs.Core.ILabHost {
private _handlers;
private _messageProcessor;
private _version;
private _targetWindow;
private _state;
private _deferredEvents;
constructor(labId: string, targetWindow: Window, targetOrigin: string);
private handleEvent(command, callback);
private invokeDeferredEvents(err);
private invokeEvent(err, command, callback);
public getSupportedVersions(): Labs.Core.ILabHostVersionInfo[];
public connect(versions: Labs.Core.ILabHostVersionInfo[], callback: Labs.Core.ILabCallback<Labs.Core.IConnectionResponse>): void;
public disconnect(callback: Labs.Core.ILabCallback<void>): void;
public on(handler: (string: any, any: any) => void): void;
public sendMessage(type: string, options: Labs.Core.IMessage, callback: Labs.Core.ILabCallback<Labs.Core.IMessageResponse>): void;
public create(options: Labs.Core.ILabCreationOptions, callback: Labs.Core.ILabCallback<void>): void;
public getConfiguration(callback: Labs.Core.ILabCallback<Labs.Core.IConfiguration>): void;
public setConfiguration(configuration: Labs.Core.IConfiguration, callback: Labs.Core.ILabCallback<void>): void;
public getConfigurationInstance(callback: Labs.Core.ILabCallback<Labs.Core.IConfigurationInstance>): void;
public getState(callback: Labs.Core.ILabCallback<any>): void;
public setState(state: any, callback: Labs.Core.ILabCallback<void>): void;
public takeAction(type: string, options: Labs.Core.IActionOptions, callback: Labs.Core.ILabCallback<Labs.Core.IAction>);
public takeAction(type: string, options: Labs.Core.IActionOptions, result: Labs.Core.IActionResult, callback: Labs.Core.ILabCallback<Labs.Core.IAction>);
public getActions(type: string, options: Labs.Core.IGetActionOptions, callback: Labs.Core.ILabCallback<Labs.Core.IAction[]>): void;
private sendCommand(command, callback);
}
}
declare module Labs {
class RichClientOfficeJSLabsHost implements Labs.Core.ILabHost {
private _handlers;
private _activeMode;
private _version;
private _labState;
private _createdHostVersion;
private _activeViewP;
constructor(configuration: Labs.Core.IConfiguration, createdHostVersion: Labs.Core.IVersion);
private getLabModeFromActiveView(view);
public getSupportedVersions(): Labs.Core.ILabHostVersionInfo[];
public connect(versions: Labs.Core.ILabHostVersionInfo[], callback: Labs.Core.ILabCallback<Labs.Core.IConnectionResponse>): void;
public disconnect(callback: Labs.Core.ILabCallback<void>): void;
public on(handler: (string: any, any: any) => void): void;
public sendMessage(type: string, options: Labs.Core.IMessage, callback: Labs.Core.ILabCallback<Labs.Core.IMessageResponse>): void;
public create(options: Labs.Core.ILabCreationOptions, callback: Labs.Core.ILabCallback<void>): void;
public getConfiguration(callback: Labs.Core.ILabCallback<Labs.Core.IConfiguration>): void;
public setConfiguration(configuration: Labs.Core.IConfiguration, callback: Labs.Core.ILabCallback<void>): void;
private updateStoredLabsState(callback);
public getConfigurationInstance(callback: Labs.Core.ILabCallback<Labs.Core.IConfigurationInstance>): void;
public getState(callback: Labs.Core.ILabCallback<any>): void;
public setState(state: any, callback: Labs.Core.ILabCallback<void>): void;
public takeAction(type: string, options: Labs.Core.IActionOptions, callback: Labs.Core.ILabCallback<Labs.Core.IAction>);
public takeAction(type: string, options: Labs.Core.IActionOptions, result: Labs.Core.IActionResult, callback: Labs.Core.ILabCallback<Labs.Core.IAction>);
public getActions(type: string, options: Labs.Core.IGetActionOptions, callback: Labs.Core.ILabCallback<Labs.Core.IAction[]>): void;
}
} | the_stack |
import { bootstrap } from 'aurelia-bootstrapper';
import { PLATFORM } from 'aurelia-pal';
import { ComponentTester, StageComponent } from 'aurelia-testing';
import { VirtualRepeat } from '../src/virtual-repeat';
import { ITestAppInterface } from './interfaces';
import './setup';
import { ensureScrolled, validateScrolledState, waitForNextFrame, scrollToEnd, waitForFrames } from './utilities';
PLATFORM.moduleName('src/virtual-repeat');
PLATFORM.moduleName('test/noop-value-converter');
PLATFORM.moduleName('src/infinite-scroll-next');
describe('vr-integration.instance-changed.spec.ts', () => {
let component: ComponentTester<VirtualRepeat>;
// let viewModel: any;
let items: string[];
let view: string;
let resources: any[];
beforeEach(() => {
component = undefined;
items = Array.from({ length: 100 }, (_: any, idx: number) => 'item' + idx);
// viewModel = { items: items };
resources = [
'src/virtual-repeat',
'test/noop-value-converter',
];
});
afterEach(() => {
try {
if (component) {
component.dispose();
}
} catch (ex) {
console.log('Error disposing component');
console.error(ex);
}
});
describe('<tr virtual-repeat.for>', () => {
beforeEach(() => {
view =
`<div style="height: 500px; overflow-y: auto">
<table style="border-spacing: 0">
<tr virtual-repeat.for="item of items" style="height: 50px;">
<td>\${item}</td>
</tr>
</table>
</div>`;
});
// In this test, it bootstraps a stage with 100 items
// 1. validates everythng is renderred correctly: number of rows, first index, bot buffer height
// 2. scrolls to bottom
// validates everything is renderred correctly: number of rows, first index, bot buffer height
// 3. shallow clones existing array, reverses then assign to current view model
// validates everything is renderred correctly: number of rows, first index, bot buffer height
it('renders with 100 items', async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const table = (component['host'] as HTMLElement).querySelector('table');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(table.tBodies[0].rows.length).toBe(2 + virtualRepeat.minViewsRequired * 2); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
table.parentElement.scrollTop = table.parentElement.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse();
await ensureScrolled(0);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(table.tBodies[0].rows.length).toBe(2 + virtualRepeat.minViewsRequired * 2, 'table > tr count'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
expect(virtualRepeat.$first).toBe(/*items count*/100 - /*views count*/virtualRepeat.minViewsRequired * 2, 'repeat._first 2');
for (let i = 0, ii = viewModel.items.length - virtualRepeat.$first; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + virtualRepeat.$first;
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${viewModel.items.length - currIndex - 1}`, `view[${i}].bindingContext.item`);
expect((view.firstChild as Element).firstElementChild.textContent).toBe(`item${viewModel.items.length - currIndex - 1}`);
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
});
// In this test, it bootstraps a stage with 100 items
// 1. validates everythng is renderred correctly: number of rows, first index, bot buffer height
// 2. scrolls to bottom
// validates everything is renderred correctly: number of rows, first index, bot buffer height
// 3. shallow clones existing array, reverses and slice from 0 to 30 then assign to current view model
// validates everything is renderred correctly: number of rows, first index, bot buffer height
it([
'renders with 100 items',
' -- reduces to 30',
' -- greater than (repeat._viewsLength)',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const table = (component['host'] as HTMLElement).querySelector('table');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(table.tBodies[0].rows.length).toBe(2 + virtualRepeat.minViewsRequired * 2); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
table.parentElement.scrollTop = table.parentElement.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 30);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(table.tBodies[0].rows.length).toBe(2 + virtualRepeat.minViewsRequired * 2, 'table > tr count'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(/*items count*/30 - /*element in views*/11 * 2, 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect((view.firstChild as Element).firstElementChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
});
// In this test, it bootstraps a stage with 100 items
// 1. validates everythng is renderred correctly: number of rows, first index, bot buffer height
// 2. scrolls to bottom
// validates everything is renderred correctly: number of rows, first index, bot buffer height
// 3. shallow clones existing array, reverses and slice from 0 to 30 then assign to current view model
// validates everything is renderred correctly: number of rows, first index, bot buffer height
it([
'renders with 100 items',
' -- reduces to 16',
' -- lesser than (repeat._viewsLength)',
' -- greater than (repeat.elementsInView)',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const table = (component['host'] as HTMLElement).querySelector('table');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(table.tBodies[0].rows.length).toBe(2 + virtualRepeat.minViewsRequired * 2); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
table.parentElement.scrollTop = table.parentElement.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 16);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(table.tBodies[0].rows.length).toBe(2 + 16, 'table > tr count'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(Math.max(0, /*items count*/16 - /*element in views*/11 * 2), 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect((view.firstChild as Element).firstElementChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
});
// In this test, it bootstraps a stage with 100 items
// 1. validates everythng is renderred correctly: number of rows, first index, bot buffer height
// 2. scrolls to bottom
// validates everything is renderred correctly: number of rows, first index, bot buffer height
// 3. shallow clones existing array, reverses and slice from 0 to 30 then assign to current view model
// validates everything is renderred correctly: number of rows, first index, bot buffer height
it([
'renders with 100 items',
' -- reduces to 8',
' -- lesser than (repeat.elementsInView)',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const table = (component['host'] as HTMLElement).querySelector('table');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(table.tBodies[0].rows.length).toBe(2 + virtualRepeat.minViewsRequired * 2); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
table.parentElement.scrollTop = table.parentElement.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 8);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(table.tBodies[0].rows.length).toBe(2 + 8, 'table > tr count'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(0, 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect((view.firstChild as Element).firstElementChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.topBufferHeight).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
expect(virtualRepeat.topBufferEl.getBoundingClientRect().height).toBe(0);
expect(virtualRepeat.bottomBufferEl.getBoundingClientRect().height).toBe(0);
});
// In this test, it bootstraps a stage with 100 items
// 1. validates everythng is renderred correctly: number of rows, first index, bot buffer height
// 2. scrolls to bottom
// validates everything is renderred correctly: number of rows, first index, bot buffer height
// 3. shallow clones existing array, reverses and slice from 0 to 30 then assign to current view model
// validates everything is renderred correctly: number of rows, first index, bot buffer height
it([
'renders with 100 items',
' -- reduces to 8',
' -- lesser than (repeat.elementsInView)',
' -- increase to 30',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const table = (component['host'] as HTMLElement).querySelector('table');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(table.tBodies[0].rows.length).toBe(2 + virtualRepeat.minViewsRequired * 2); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
const scrollerEl = table.parentElement;
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await waitForNextFrame();
expect(scrollerEl.scrollTop).toBe(50 * (100 - 500 / 50));
validateScrolledState(virtualRepeat, viewModel, 50);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 8);
await waitForNextFrame();
expect(scrollerEl.scrollTop).toBe(0);
validateScrolledState(virtualRepeat, viewModel, 50);
viewModel.items = createItems(30);
await waitForNextFrame();
await scrollToEnd(virtualRepeat);
expect(virtualRepeat.lastViewIndex()).toBe(29, 'repeat._lastViewIndex() 2');
expect(scrollerEl.scrollTop).toBe(50 * (30 - 500 / 50), 'scrollerEl.scrollTop 3');
validateScrolledState(virtualRepeat, viewModel, 50);
expect(virtualRepeat.bottomBufferEl.style.height).toBe(
`0px`,
'repeat.bottomBufferEl.height'
);
});
// In this test, it bootstraps a stage with 100 items
// 1. validates everythng is renderred correctly: number of rows, first index, bot buffer height
// 2. scrolls to bottom
// validates everything is renderred correctly: number of rows, first index, bot buffer height
// 3. shallow clones existing array, reverses and slice from 0 to 30 then assign to current view model
// validates everything is renderred correctly: number of rows, first index, bot buffer height
it([
'renders with 100 items',
' -- reduces to 11',
' -- equal to (repeat.elementsInView)',
' -- increase to 30',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const table = (component['host'] as HTMLElement).querySelector('table');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(table.tBodies[0].rows.length).toBe(2 + virtualRepeat.minViewsRequired * 2, 'elements count 1'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
const scrollerEl = table.parentElement;
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await waitForNextFrame();
expect(scrollerEl.scrollTop).toBe(50 * (100 - 500 / 50), 'scrollerEl.scrollTop 1');
validateScrolledState(virtualRepeat, viewModel, 50);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 11);
await waitForNextFrame();
expect(virtualRepeat.lastViewIndex()).toBe(10);
expect(scrollerEl.scrollTop).toBe(50, 'scrollerEl.scrollTop 2');
expect(virtualRepeat.bottomBufferHeight).toBe(0, 'repeat._botB-Height 2');
validateScrolledState(virtualRepeat, viewModel, 50);
viewModel.items = createItems(30);
await waitForNextFrame();
await scrollToEnd(virtualRepeat);
expect(virtualRepeat.lastViewIndex()).toBe(29, 'repeat._lastViewIndex() 2');
expect(scrollerEl.scrollTop).toBe(50 * (30 - 500 / 50), 'scrollerEl.scrollTop 3');
validateScrolledState(virtualRepeat, viewModel, 50);
expect(virtualRepeat.bottomBufferEl.style.height).toBe(
`0px`,
'repeat.bottomBufferEl.height'
);
});
});
describe('<tbody virtual-repeat.for>', () => {
beforeEach(() => {
view =
`<div style="height: 500px; overflow-y: auto">
<table style="border-spacing: 0">
<tbody virtual-repeat.for="item of items">
<tr style="height: 50px;">
<td>\${item}</td>
</tr>
</tbody>
</table>
</div>`;
});
it([
'tbody[repeat]',
'renders with 100 items',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const table = (component['host'] as HTMLElement).querySelector('table');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// buffers are TR element
expect(table.tBodies.length).toBe(virtualRepeat.minViewsRequired * 2, 'table.tBodies.length 1'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
table.parentElement.scrollTop = table.parentElement.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse();
await ensureScrolled();
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// buffers are TR elements
expect(table.tBodies.length).toBe(virtualRepeat.minViewsRequired * 2, 'table.tBodies.length 2'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
expect(virtualRepeat.$first).toBe(/*items count*/100 - /*views count*/virtualRepeat.minViewsRequired * 2, 'repeat._first 2');
for (let i = 0, ii = viewModel.items.length - virtualRepeat.$first; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + virtualRepeat.$first;
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${viewModel.items.length - currIndex - 1}`);
expect((view.firstChild as Element).firstElementChild.firstElementChild.textContent).toBe(`item${viewModel.items.length - currIndex - 1}`);
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
});
it([
'tbody[repeat]',
'renders with 100 items',
' -- reduces to 30',
' -- greater than (repeat._viewsLength)',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const table = (component['host'] as HTMLElement).querySelector('table');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// buffers are TR elements
expect(table.tBodies.length).toBe(virtualRepeat.minViewsRequired * 2, 'table.tBodies.length 1'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2), 'repeat._bottomBufferHeight');
// start more difficult cases
// 1. mutate scroll state
table.parentElement.scrollTop = table.parentElement.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 30);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// buffers are TR elements
expect(table.tBodies.length).toBe(virtualRepeat.minViewsRequired * 2, 'table.tBodies.length 2'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(/*items count*/30 - /*element in views*/11 * 2, 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect((view.firstChild as Element).firstElementChild.firstElementChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
});
it([
'tbody[repeat]',
'renders with 100 items',
' -- reduces to 30',
' -- greater than (repeat._viewsLength)',
' -- reduces to null',
' -- increase to 50',
' -- reduces to undefined',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const table = (component['host'] as HTMLElement).querySelector('table');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// buffers are TR elements
expect(table.tBodies.length).toBe(virtualRepeat.minViewsRequired * 2, 'table.tBodies.length 1'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2), 'repeat._bottomBufferHeight');
// start more difficult cases
const scrollerEl = table.parentElement;
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 30);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// buffers are TR elements
expect(table.tBodies.length).toBe(virtualRepeat.minViewsRequired * 2, 'table.tBodies.length 2'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(/*items count*/30 - /*element in views*/11 * 2, 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect((view.firstChild as Element).firstElementChild.firstElementChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = null;
await waitForNextFrame();
expect(virtualRepeat.minViewsRequired * 2).toBe(0, 'repeat._viewsLength [null]');
expect(table.tBodies.length).toBe(0, 'table.tBodies.length [null]');
expect(virtualRepeat.topBufferHeight).toBe(0, 'repeat._topBufferHeight [null]');
expect(virtualRepeat.bottomBufferHeight).toBe(0, 'repeat._bottomBufferHeight [null]');
viewModel.items = createItems(50);
await waitForNextFrame();
expect(table.tBodies.length).toBe(22, 'table.tBodies');
validateScrolledState(virtualRepeat, viewModel, 50);
viewModel.items = undefined;
await waitForNextFrame();
expect(virtualRepeat.items).toBe(undefined, 'repeat.items [undefined]');
expect(virtualRepeat.minViewsRequired * 2).toBe(0, 'repeat._viewsLength [undefined]');
expect(table.tBodies.length).toBe(0, 'table.tBodies.length [undefined]');
expect(virtualRepeat.topBufferHeight).toBe(0, 'repeat._topBufferHeight [undefined]');
expect(virtualRepeat.bottomBufferHeight).toBe(0, 'repeat._bottomBufferHeight [undefined]');
});
it([
'tbody[repeat]',
'renders with 100 items',
' -- reduces to 16',
' -- lesser than (repeat._viewsLength)',
' -- greater than (repeat.elementsInView)',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const table = (component['host'] as HTMLElement).querySelector('table');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// buffers are TR elements
expect(table.tBodies.length).toBe(virtualRepeat.minViewsRequired * 2, 'table.tBodies.length'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
table.parentElement.scrollTop = table.parentElement.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0, 'repeat._bottomBufferHeight');
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 16);
await waitForFrames(2);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// buffers are TR elements
expect(table.tBodies.length).toBe(16, 'table.tBodies.length'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(Math.max(0, /*items count*/16 - /*element in views*/11 * 2), 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect((view.firstChild as Element).firstElementChild.firstElementChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
});
it([
'tbody[repeat]',
'renders with 100 items',
' -- reduces to 8',
' -- lesser than (repeat.elementsInView)',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const table = (component['host'] as HTMLElement).querySelector('table');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// buffers are tr elements
expect(table.tBodies.length).toBe(virtualRepeat.minViewsRequired * 2, 'table.tBodies.length 1'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
table.parentElement.scrollTop = table.parentElement.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 8);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// buffers are tr elements
expect(table.tBodies.length).toBe(8, 'table.tBodies.length 2'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(0, 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect((view.firstChild as Element).firstElementChild.firstElementChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.topBufferHeight).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
expect(virtualRepeat.topBufferEl.getBoundingClientRect().height).toBe(0);
expect(virtualRepeat.bottomBufferEl.getBoundingClientRect().height).toBe(0);
});
// In this test, it bootstraps a stage with 100 items
// 1. validates everythng is renderred correctly: number of rows, first index, bot buffer height
// 2. scrolls to bottom
// validates everything is renderred correctly: number of rows, first index, bot buffer height
// 3. shallow clones existing array, reverses and slice from 0 to 30 then assign to current view model
// validates everything is renderred correctly: number of rows, first index, bot buffer height
it([
'tbody[repeat]',
'renders with 100 items',
' -- reduces to 11',
' -- equal to (repeat.elementsInView)',
' -- increase to 30',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const table = (component['host'] as HTMLElement).querySelector('table');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(table.tBodies.length).toBe(virtualRepeat.minViewsRequired * 2, 'elements count 1'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
const scrollerEl = table.parentElement;
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await waitForNextFrame();
expect(scrollerEl.scrollTop).toBe(50 * (100 - 500 / 50), 'scrollerEl.scrollTop 1');
validateScrolledState(virtualRepeat, viewModel, 50);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 11);
await waitForNextFrame();
expect(virtualRepeat.lastViewIndex()).toBe(10);
expect(scrollerEl.scrollTop).toBe(50, 'scrollerEl.scrollTop 2');
expect(virtualRepeat.bottomBufferHeight).toBe(0, 'repeat._botB-Height 2');
validateScrolledState(virtualRepeat, viewModel, 50);
viewModel.items = createItems(30);
await waitForNextFrame();
await scrollToEnd(virtualRepeat);
expect(virtualRepeat.lastViewIndex()).toBe(29, 'repeat._lastViewIndex() 2');
expect(scrollerEl.scrollTop).toBe(50 * (30 - 500 / 50), 'scrollerEl.scrollTop 3');
validateScrolledState(virtualRepeat, viewModel, 50);
expect(virtualRepeat.bottomBufferEl.style.height).toBe(
`0px`,
'repeat.bottomBufferEl.height'
);
});
});
describe('<div virtual-repeat.for>', () => {
beforeEach(() => {
view =
`<div class="scroller" style="height: 500px; overflow-y: auto">
<div virtual-repeat.for="item of items" style="height: 50px">\${item}</div>
</div>`;
});
it('renders with 100 items', async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(2 + virtualRepeat.minViewsRequired * 2, 'scrollerEl.children.length 1'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(
50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2),
'repeat._bottomBufferHeight'
);
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse();
await ensureScrolled();
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(2 + virtualRepeat.minViewsRequired * 2, 'scrollerEl.children.length 2'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
expect(virtualRepeat.$first).toBe(/*items count*/100 - /*views count*/virtualRepeat.minViewsRequired * 2, 'repeat._first 2');
for (let i = 0, ii = viewModel.items.length - virtualRepeat.$first; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + virtualRepeat.$first;
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${viewModel.items.length - currIndex - 1}`);
expect(view.firstChild.textContent).toBe(`item${viewModel.items.length - currIndex - 1}`);
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
});
it([
'renders with 100 items',
' -- reduces to 30',
' -- greater than (repeat._viewsLength)',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(2 + virtualRepeat.minViewsRequired * 2, 'scrollerEl.children.length 1'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2), 'repeat._bottomBufferHeight');
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 30);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(2 + virtualRepeat.minViewsRequired * 2, 'scrollerEl.children.length 2'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(/*items count*/30 - /*element in views*/11 * 2, 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect(view.firstChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
});
it([
'renders with 100 items',
' -- reduces to 16',
' -- lesser than (repeat._viewsLength)',
' -- greater than (repeat.elementsInView)',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(2 + virtualRepeat.minViewsRequired * 2, 'scrollerEl.children.length'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0, 'repeat._bottomBufferHeight');
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 16);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(2 + 16, 'scrollerEl.children.length'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(Math.max(0, /*items count*/16 - /*element in views*/11 * 2), 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect(view.firstChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
});
it([
'renders with 100 items',
' -- reduces to 8',
' -- lesser than (repeat.elementsInView)',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(2 + virtualRepeat.minViewsRequired * 2, 'scrollerEl.children.length 1'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 8);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(2 + 8, 'scrollerEl.children.length 2'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(0, 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect(view.firstChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.topBufferHeight).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
expect(virtualRepeat.topBufferEl.getBoundingClientRect().height).toBe(0);
expect(virtualRepeat.bottomBufferEl.getBoundingClientRect().height).toBe(0);
});
// In this test, it bootstraps a stage with 100 items
// 1. validates everythng is renderred correctly: number of rows, first index, bot buffer height
// 2. scrolls to bottom
// validates everything is renderred correctly: number of rows, first index, bot buffer height
// 3. shallow clones existing array, reverses and slice from 0 to 30 then assign to current view model
// validates everything is renderred correctly: number of rows, first index, bot buffer height
it([
'renders with 100 items',
' -- reduces to 11',
' -- equal to (repeat.elementsInView)',
' -- increase to 30',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items });
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(2 + virtualRepeat.minViewsRequired * 2, 'elements count 1'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await waitForNextFrame();
expect(scrollerEl.scrollTop).toBe(50 * (100 - 500 / 50), 'scrollerEl.scrollTop 1');
validateScrolledState(virtualRepeat, viewModel, 50);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 11);
await waitForNextFrame();
expect(virtualRepeat.lastViewIndex()).toBe(10);
expect(scrollerEl.scrollTop).toBe(50, 'scrollerEl.scrollTop 2');
expect(virtualRepeat.bottomBufferHeight).toBe(0, 'repeat._botB-Height 2');
validateScrolledState(virtualRepeat, viewModel, 50);
viewModel.items = createItems(30);
await waitForNextFrame();
await scrollToEnd(virtualRepeat);
expect(virtualRepeat.lastViewIndex()).toBe(29, 'repeat._lastViewIndex() 2');
expect(scrollerEl.scrollTop).toBe(50 * (30 - 500 / 50), 'scrollerEl.scrollTop 3');
validateScrolledState(virtualRepeat, viewModel, 50);
expect(virtualRepeat.bottomBufferEl.style.height).toBe(
`0px`,
'repeat.bottomBufferEl.height'
);
});
});
describe('div > (ul|ol) > li [repeat]', () => {
describe('ol > li', function() {
runTestSuit(
'div > ol > li [repeat]',
`<div class="scroller" style="height: 500px; overflow-y: auto">
<ul style="padding: 0; margin: 0; list-style: none;">
<li virtual-repeat.for="item of items" style="height: 50px">\${item}</li>
</ul>
</div>`
);
});
describe('ul > li', function() {
runTestSuit(
'div > ul > li [repeat]',
`<div class="scroller" style="height: 500px; overflow-y: auto">
<ol style="padding: 0; margin: 0; list-style: none;">
<li virtual-repeat.for="item of items" style="height: 50px; padding: 0; margin: 0;">\${item}</li>
</ol>
</div>`
);
});
function runTestSuit(title: string, $view: string) {
it([
title,
'renders with 100 items',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }, $view);
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.firstElementChild.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'scrollerEl.children.length 1'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(
50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2),
'repeat._bottomBufferHeight'
);
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse();
await ensureScrolled();
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.firstElementChild.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'scrollerEl.children.length 2'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
expect(virtualRepeat.$first).toBe(/*items count*/100 - /*views count*/virtualRepeat.minViewsRequired * 2, 'repeat._first 2');
for (let i = 0, ii = viewModel.items.length - virtualRepeat.$first; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + virtualRepeat.$first;
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${viewModel.items.length - currIndex - 1}`);
expect(view.firstChild.textContent).toBe(`item${viewModel.items.length - currIndex - 1}`);
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
});
it([
title,
'renders with 100 items',
' -- reduces to 30',
' -- greater than (repeat._viewsLength)',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }, $view);
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.firstElementChild.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'scrollerEl.children.length 1'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2), 'repeat._bottomBufferHeight');
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 30);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.firstElementChild.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'scrollerEl.children.length 2'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(/*items count*/30 - /*element in views*/11 * 2, 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect(view.firstChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
});
it([
title,
'renders with 100 items',
' -- reduces to 30',
' -- greater than (repeat._viewsLength)',
' -- reduces to null',
' -- increase to 50',
' -- reduces to undefined',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }, $view);
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.firstElementChild.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'scrollerEl.children.length 1'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2), 'repeat._bottomBufferHeight');
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 30);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.firstElementChild.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'scrollerEl.children.length 2'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(/*items count*/30 - /*element in views*/11 * 2, 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect(view.firstChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = null;
await waitForNextFrame();
expect(virtualRepeat.minViewsRequired * 2).toBe(0, 'repeat._viewsLength [null]');
expect(scrollerEl.firstElementChild.children.length).toBe(2, 'scrollerEl.firstElementChild.children.length [null]');
expect(virtualRepeat.topBufferHeight).toBe(0, 'repeat._topBufferHeight [null]');
expect(virtualRepeat.bottomBufferHeight).toBe(0, 'repeat._bottomBufferHeight [null]');
viewModel.items = createItems(50);
await waitForNextFrame();
validateScrolledState(virtualRepeat, viewModel, 50);
viewModel.items = undefined;
await waitForNextFrame();
expect(virtualRepeat.items).toBe(undefined, 'repeat.items [undefined]');
expect(virtualRepeat.minViewsRequired * 2).toBe(0, 'repeat._viewsLength [undefined]');
expect(scrollerEl.firstElementChild.children.length).toBe(2, 'scrollerEl.firstElementChild.children.length [undefined]');
expect(virtualRepeat.topBufferHeight).toBe(0, 'repeat._topBufferHeight [undefined]');
expect(virtualRepeat.bottomBufferHeight).toBe(0, 'repeat._bottomBufferHeight [undefined]');
});
it([
title,
'renders with 100 items',
' -- reduces to 16',
' -- lesser than (repeat._viewsLength)',
' -- greater than (repeat.elementsInView)',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }, $view);
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.firstElementChild.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'scrollerEl.children.length'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0, 'repeat._bottomBufferHeight');
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 16);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.firstElementChild.children.length).toBe(2 + 16, 'scrollerEl.children.length'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(Math.max(0, /*items count*/16 - /*element in views*/11 * 2), 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect(view.firstChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
});
it([
title,
'renders with 100 items',
' -- reduces to 8',
' -- lesser than (repeat.elementsInView)',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }, $view);
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.firstElementChild.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'scrollerEl.children.length 1'
); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 8);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.firstElementChild.children.length).toBe(2 + 8, 'scrollerEl.children.length 2'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(0, 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect(view.firstChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.topBufferHeight).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
expect(virtualRepeat.topBufferEl.getBoundingClientRect().height).toBe(0);
expect(virtualRepeat.bottomBufferEl.getBoundingClientRect().height).toBe(0);
});
// In this test, it bootstraps a stage with 100 items
// 1. validates everythng is renderred correctly: number of rows, first index, bot buffer height
// 2. scrolls to bottom
// validates everything is renderred correctly: number of rows, first index, bot buffer height
// 3. shallow clones existing array, reverses and slice from 0 to 30 then assign to current view model
// validates everything is renderred correctly: number of rows, first index, bot buffer height
it([
title,
'renders with 100 items',
' -- reduces to 11',
' -- equal to (repeat.elementsInView)',
' -- increase to 30',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }, $view);
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.firstElementChild.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'elements count 1'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await waitForNextFrame();
expect(scrollerEl.scrollTop).toBe(50 * (100 - 500 / 50), 'scrollerEl.scrollTop 1');
validateScrolledState(virtualRepeat, viewModel, 50);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 11);
await waitForNextFrame();
expect(virtualRepeat.firstViewIndex()).toBe(0);
expect(virtualRepeat.lastViewIndex()).toBe(10);
// expect(scrollerEl.scrollTop).toBe(50, 'scrollerEl.scrollTop 2');
expect(virtualRepeat.bottomBufferHeight).toBe(0, 'repeat._botB-Height 2');
validateScrolledState(virtualRepeat, viewModel, 50);
viewModel.items = createItems(30);
await waitForNextFrame();
// it's very difficult here to do the right assertion, since browser behaviors are different
await scrollToEnd(virtualRepeat);
expect(virtualRepeat.firstViewIndex()).toBe(30 - 22, 'repeat._first > 0');
expect(virtualRepeat.lastViewIndex()).toBe(29, 'repeat._lastViewIndex() 2');
expect(scrollerEl.scrollTop).toBe(50 * (30 - 500 / 50), 'scrollerEl.scrollTop 3');
validateScrolledState(virtualRepeat, viewModel, 50);
expect(virtualRepeat.bottomBufferEl.style.height).toBe(
`0px`,
'repeat.bottomBufferEl.height'
);
});
}
});
describe('(ul|ol) > li [virtual-repeat]', () => {
describe('ul > li', function() {
runTestSuit(
'ol > li [virtual-repeat]',
`<ul class="scroller" style="height: 500px; overflow-y: auto">
<li virtual-repeat.for="item of items" style="height: 50px">\${item}</li>
</ul>`
);
});
describe('ol > li', function() {
runTestSuit(
'ol > li [virtual-repeat]',
`<ol class="scroller" style="height: 500px; overflow-y: auto">
<li virtual-repeat.for="item of items" style="height: 50px">\${item}</li>
</ol>`
);
});
function runTestSuit(title: string, $view: string) {
it([
title,
'renders with 100 items',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }, $view);
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'scrollerEl.children.length 1'
); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(
50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2),
'repeat._bottomBufferHeight'
);
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse();
await ensureScrolled();
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'scrollerEl.children.length 2'
); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
expect(virtualRepeat.$first).toBe(/*items count*/100 - /*views count*/virtualRepeat.minViewsRequired * 2, 'repeat._first 2');
for (let i = 0, ii = viewModel.items.length - virtualRepeat.$first; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + virtualRepeat.$first;
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${viewModel.items.length - currIndex - 1}`);
expect(view.firstChild.textContent).toBe(`item${viewModel.items.length - currIndex - 1}`);
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
});
it([
title,
'renders with 100 items',
' -- reduces to 30',
' -- greater than (repeat._viewsLength)',
' -- reduces to null',
' -- increase to 50',
' -- reduces to undefined',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }, $view);
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'scrollerEl.children.length 1'
); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2), 'repeat._bottomBufferHeight');
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 30);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'scrollerEl.children.length 2'
); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(/*items count*/30 - /*element in views*/11 * 2, 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect(view.firstChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = null;
await waitForNextFrame();
expect(virtualRepeat.minViewsRequired * 2).toBe(0, 'repeat._viewsLength [null]');
expect(scrollerEl.children.length).toBe(2, 'scrollerEl.children.length [null]');
expect(virtualRepeat.topBufferHeight).toBe(0, 'repeat._topBufferHeight [null]');
expect(virtualRepeat.bottomBufferHeight).toBe(0, 'repeat._bottomBufferHeight [null]');
viewModel.items = createItems(50);
await waitForNextFrame();
validateScrolledState(virtualRepeat, viewModel, 50);
viewModel.items = undefined;
await waitForNextFrame();
expect(virtualRepeat.items).toBe(undefined, 'repeat.items [undefined]');
expect(virtualRepeat.minViewsRequired * 2).toBe(0, 'repeat._viewsLength [undefined]');
expect(scrollerEl.children.length).toBe(2, 'scrollerEl.children.length [undefined]');
expect(virtualRepeat.topBufferHeight).toBe(0, 'repeat._topBufferHeight [undefined]');
expect(virtualRepeat.bottomBufferHeight).toBe(0, 'repeat._bottomBufferHeight [undefined]');
});
it([
title,
'renders with 100 items',
' -- reduces to 30',
' -- greater than (repeat._viewsLength)',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }, $view);
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'scrollerEl.children.length 1'
); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2), 'repeat._bottomBufferHeight');
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 30);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'scrollerEl.children.length 2'
); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(/*items count*/30 - /*element in views*/11 * 2, 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect(view.firstChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
});
it([
title,
'renders with 100 items',
' -- reduces to 16',
' -- lesser than (repeat._viewsLength)',
' -- greater than (repeat.elementsInView)',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }, $view);
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(2 + virtualRepeat.minViewsRequired * 2, 'scrollerEl.children.length'); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0, 'repeat._bottomBufferHeight');
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 16);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(2 + 16, 'scrollerEl.children.length'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(Math.max(0, /*items count*/16 - /*element in views*/11 * 2), 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect(view.firstChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.bottomBufferHeight).toBe(0);
});
it([
title,
'renders with 100 items',
' -- reduces to 8',
' -- lesser than (repeat.elementsInView)',
].join('\n\t'), async () => {
const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }, $view);
const scrollerEl = (component['host'] as HTMLElement).querySelector('.scroller');
expect(virtualRepeat.minViewsRequired).toBe(Math.floor(500 / 50) + 1, 'repeat.elementsInView');
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(
2 + virtualRepeat.minViewsRequired * 2,
'scrollerEl.children.length 1'
); // 2 buffers + 20 rows based on 50 height
expect(virtualRepeat.$first).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(50 * (virtualRepeat.items.length - virtualRepeat.minViewsRequired * 2));
// start more difficult cases
// 1. mutate scroll state
scrollerEl.scrollTop = scrollerEl.scrollHeight;
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
// when scrolling, the first bound row is calculated differently compared to other scenarios
// as it can be known exactly what the last process was
// so it can create views with optimal number (scroll container height / itemHeight)
expect(virtualRepeat.$first).toBe(
/*items count*/100 - calcMaxViewsRequired(500, 50),
'repeat._first 1'
);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
viewModel.items = viewModel.items.slice(0).reverse().slice(0, 8);
await ensureScrolled(50);
expect(virtualRepeat.minViewsRequired * 2).toBe(22, 'repeat._viewsLength');
expect(scrollerEl.children.length).toBe(2 + 8, 'scrollerEl.children.length 2'); // 2 buffers + 20 rows based on 50 height
// This check is different from the above:
// after instance changed, it restart the "_first" view based on safe number of views
// this safe number of views is different with the case of no collection size changes
// this case triggers a scroll event
expect(virtualRepeat.$first).toBe(0, 'repeat._first 2');
// the following check is based on subtraction of total items count and total views count
// as total number of views hasn't been changed, and their binding contexts created by [repeat]
// haven't been changed either, despite scroll event happened
for (let i = 0, ii = viewModel.items.length - virtualRepeat.minViewsRequired * 2; ii > i; ++i) {
const view = virtualRepeat.view(i);
const currIndex = i + (viewModel.items.length - virtualRepeat.minViewsRequired * 2);
expect(view).not.toBeNull(`view-${i} !== null`);
expect(view.bindingContext.item).toBe(`item${100 - currIndex - 1}`, 'bindingContext.item');
expect(view.firstChild.textContent).toBe(`item${100 - currIndex - 1}`, 'row.textContent');
}
expect(virtualRepeat.topBufferHeight).toBe(0);
expect(virtualRepeat.bottomBufferHeight).toBe(0);
expect(virtualRepeat.topBufferEl.getBoundingClientRect().height).toBe(0);
expect(virtualRepeat.bottomBufferEl.getBoundingClientRect().height).toBe(0);
});
}
});
async function bootstrapComponent<T>($viewModel?: ITestAppInterface<T>, $view?: string) {
component = StageComponent
.withResources(resources)
.inView($view || view)
.boundTo($viewModel);
await component.create(bootstrap);
return { virtualRepeat: component.viewModel, viewModel: $viewModel, component: component };
}
function createItems(amount: number, name: string = 'item') {
return Array.from({ length: amount }, (_, index) => name + index);
}
function calcElementsInView(ct_h: number, item_h: number): number {
return item_h === 0 || ct_h === 0 ? 0 : (ct_h / item_h + 1);
}
function calcMaxViewsRequired(ct_h: number, item_h: number): number {
return calcElementsInView(ct_h, item_h) * 2;
}
}); | the_stack |
import {Convert} from "../ExtensionMethods";
import {EwsServiceXmlWriter} from "../Core/EwsServiceXmlWriter";
import {ExchangeService} from "../Core/ExchangeService";
import {LocationSource} from "../Enumerations/LocationSource";
import {XmlElementNames} from "../Core/XmlElementNames";
import {XmlNamespace} from "../Enumerations/XmlNamespace";
import {ComplexProperty} from "./ComplexProperty";
/**
* Represents PersonaPostalAddress.
*/
export class PersonaPostalAddress extends ComplexProperty {
private street: string = null;
private city: string = null;
private state: string = null;
private country: string = null;
private postalCode: string = null;
private postOfficeBox: string = null;
private type: string = null;
private latitude: number = null;
private longitude: number = null;
private accuracy: number = null;
private altitude: number = null;
private altitudeAccuracy: number = null;
private formattedAddress: string = null;
private uri: string = null;
private source: LocationSource = 0;
/**
* Gets or sets the Street.
*/
get Street(): string {
return this.street;
}
set Street(value: string) {
this.SetFieldValue<string>({ getValue: () => this.street, setValue: (fieldValue) => { this.street = fieldValue } }, value);
}
/**
* Gets or sets the City.
*/
get City(): string {
return this.city;
}
set City(value: string) {
this.SetFieldValue<string>({ getValue: () => this.city, setValue: (fieldValue) => { this.city = fieldValue } }, value);
}
/**
* Gets or sets the state.
*/
get State(): string {
return this.state;
}
set State(value: string) {
this.SetFieldValue<string>({ getValue: () => this.state, setValue: (fieldValue) => { this.state = fieldValue } }, value);
}
/**
* Gets or sets the Country.
*/
get Country(): string {
return this.country;
}
set Country(value: string) {
this.SetFieldValue<string>({ getValue: () => this.country, setValue: (fieldValue) => { this.country = fieldValue } }, value);
}
/**
* Gets or sets the PostalCode.
*/
get PostalCode(): string {
return this.postalCode;
}
set PostalCode(value: string) {
this.SetFieldValue<string>({ getValue: () => this.postalCode, setValue: (fieldValue) => { this.postalCode = fieldValue } }, value);
}
/**
* Gets or sets the PostOfficeBox.
*/
get PostOfficeBox(): string {
return this.postOfficeBox;
}
set PostOfficeBox(value: string) {
this.SetFieldValue<string>({ getValue: () => this.postOfficeBox, setValue: (fieldValue) => { this.postOfficeBox = fieldValue } }, value);
}
/**
* Gets or sets the Type.
*/
get Type(): string {
return this.type;
}
set Type(value: string) {
this.SetFieldValue<string>({ getValue: () => this.type, setValue: (fieldValue) => { this.type = fieldValue } }, value);
}
/**
* Gets or sets the location source type.
*/
get Source(): LocationSource {
return this.source;
}
set Source(value: LocationSource) {
this.SetFieldValue<LocationSource>({ getValue: () => this.source, setValue: (fieldValue) => { this.source = fieldValue } }, value);
}
/**
* Gets or sets the location Uri.
*/
get Uri(): string {
return this.uri;
}
set Uri(value: string) {
this.SetFieldValue<string>({ getValue: () => this.uri, setValue: (fieldValue) => { this.uri = fieldValue } }, value);
}
/**
* Gets or sets a value indicating location latitude.
*/
get Latitude(): number {
return this.latitude;
}
set Latitude(value: number) {
this.SetFieldValue<number>({ getValue: () => this.latitude, setValue: (fieldValue) => { this.latitude = fieldValue } }, value);
}
/**
* Gets or sets a value indicating location longitude.
*/
get Longitude(): number {
return this.longitude;
}
set Longitude(value: number) {
this.SetFieldValue<number>({ getValue: () => this.longitude, setValue: (fieldValue) => { this.longitude = fieldValue } }, value);
}
/**
* Gets or sets the location accuracy.
*/
get Accuracy(): number {
return this.accuracy;
}
set Accuracy(value: number) {
this.SetFieldValue<number>({ getValue: () => this.accuracy, setValue: (fieldValue) => { this.accuracy = fieldValue } }, value);
}
/**
* Gets or sets the location altitude.
*/
get Altitude(): number {
return this.altitude;
}
set Altitude(value: number) {
this.SetFieldValue<number>({ getValue: () => this.altitude, setValue: (fieldValue) => { this.altitude = fieldValue } }, value);
}
/**
* Gets or sets the location altitude accuracy.
*/
get AltitudeAccuracy(): number {
return this.altitudeAccuracy;
}
set AltitudeAccuracy(value: number) {
this.SetFieldValue<number>({ getValue: () => this.altitudeAccuracy, setValue: (fieldValue) => { this.altitudeAccuracy = fieldValue } }, value);
}
/**
* Gets or sets the street address.
*/
get FormattedAddress(): string {
return this.formattedAddress;
}
set FormattedAddress(value: string) {
this.SetFieldValue<string>({ getValue: () => this.formattedAddress, setValue: (fieldValue) => { this.formattedAddress = fieldValue } }, value);
}
/**
* @internal Initializes a new instance of the **PersonaPostalAddress** class.
*/
constructor();
/**
* Initializes a new instance of the **PersonaPostalAddress** class.
*
* @param {string} street The Street Address.
* @param {string} city The City value.
* @param {string} state The State value.
* @param {string} country The country value.
* @param {string} postalCode The postal code value.
* @param {string} postOfficeBox The Post Office Box.
* @param {LocationSource} locationSource The location Source.
* @param {string} locationUri The location Uri.
* @param {string} formattedAddress The location street Address in formatted address.
* @param {number} latitude The location latitude.
* @param {number} longitude The location longitude.
* @param {number} accuracy The location accuracy.
* @param {number} altitude The location altitude.
* @param {number} altitudeAccuracy The location altitude Accuracy.
*/
constructor(street: string, city: string, state: string, country: string, postalCode: string, postOfficeBox: string, locationSource: LocationSource, locationUri: string, formattedAddress: string, latitude: number, longitude: number, accuracy: number, altitude: number, altitudeAccuracy: number);
constructor(street?: string, city?: string, state?: string, country?: string, postalCode?: string, postOfficeBox?: string, locationSource?: LocationSource, locationUri?: string, formattedAddress?: string, latitude?: number, longitude?: number, accuracy?: number, altitude?: number, altitudeAccuracy?: number) {
super();
if (arguments.length === 0) return;
this.street = street;
this.city = city;
this.state = state;
this.country = country;
this.postalCode = postalCode;
this.postOfficeBox = postOfficeBox;
this.latitude = latitude;
this.longitude = longitude;
this.source = locationSource;
this.uri = locationUri;
this.formattedAddress = formattedAddress;
this.accuracy = accuracy;
this.altitude = altitude;
this.altitudeAccuracy = altitudeAccuracy;
}
/**
* @internal Loads service object from XML.
*
* @param {any} jsObject Json Object converted from XML.
* @param {ExchangeService} service The service.
*/
LoadFromXmlJsObject(jsObject: any, service: ExchangeService): void {
for (let key in jsObject) {
switch (key) {
case XmlElementNames.Street:
this.street = jsObject[key];
break;
case XmlElementNames.City:
this.city = jsObject[key];
break;
case XmlElementNames.Country:
this.country = jsObject[key];
break;
case XmlElementNames.PostalCode:
this.postalCode = jsObject[key];
break;
case XmlElementNames.PostOfficeBox:
this.postOfficeBox = jsObject[key];
break;
case XmlElementNames.PostalAddressType:
this.type = jsObject[key];
break;
case XmlElementNames.Latitude:
this.latitude = Convert.toNumber(jsObject[key]);
break;
case XmlElementNames.Longitude:
this.longitude = Convert.toNumber(jsObject[key]);
break;
case XmlElementNames.Accuracy:
this.accuracy = Convert.toNumber(jsObject[key]);
break;
case XmlElementNames.Altitude:
this.altitude = Convert.toNumber(jsObject[key]);
break;
case XmlElementNames.AltitudeAccuracy:
this.altitudeAccuracy = Convert.toNumber(jsObject[key]);
break;
case XmlElementNames.FormattedAddress:
this.formattedAddress = jsObject[key];
break;
case XmlElementNames.LocationUri:
this.uri = jsObject[key];
break;
case XmlElementNames.LocationSource:
this.source = LocationSource[<string>jsObject[key]];
break;
default:
break;
}
}
}
/**
* @internal Writes elements to XML.
*
* @param {EwsServiceXmlWriter} writer The writer.
*/
WriteElementsToXml(writer: EwsServiceXmlWriter): void {
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Street, this.street);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.City, this.city);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.State, this.state);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Country, this.country);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.PostalCode, this.postalCode);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.PostOfficeBox, this.postOfficeBox);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.PostalAddressType, this.type);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Latitude, this.latitude);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Longitude, this.longitude);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Accuracy, this.accuracy);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Altitude, this.altitude);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.AltitudeAccuracy, this.altitudeAccuracy);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.FormattedAddress, this.formattedAddress);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.LocationUri, this.uri);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.LocationSource, this.source);
}
/**
* @internal Writes to XML.
*
* @param {EwsServiceXmlWriter} writer The writer.
*/
WriteToXml(writer: EwsServiceXmlWriter): void {
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.PersonaPostalAddress);
this.WriteElementsToXml(writer);
writer.WriteEndElement(); // xmlElementName
}
} | the_stack |
import * as React from 'react'
import {render, act} from '@testing-library/react'
import useObserver from './useObserver'
import '@testing-library/jest-dom/extend-expect'
test('add hash internally', () => {
class TestClass {
current = 2
previous(): void {
this.current--
}
getCurrent(): number {
return this.current
}
}
const obj = new TestClass()
function ComponentUsingModel({model}: {model: TestClass}) {
useObserver(model)
return (
<div>
<button onClick={(): void => model.previous()}>
Change the numbers in first component
</button>
<div data-testid="numberInFirst">{model.getCurrent()}</div>
</div>
)
}
function OtherComponentUsingModel({model}: {model: TestClass}) {
useObserver(model)
return (
<div>
<button onClick={(): void => model.previous()}>
Change in the other component
</button>
<div data-testid="numberInOther">{model.getCurrent()}</div>
</div>
)
}
function ComponentWithNestedUseOfTheModelObject() {
return (
<>
<ComponentUsingModel model={obj} />
<OtherComponentUsingModel model={obj} />
</>
)
}
const {getByTestId, getByText} = render(
<ComponentWithNestedUseOfTheModelObject />
)
expect(getByTestId('numberInFirst')).toHaveTextContent('2')
expect(getByTestId('numberInOther')).toHaveTextContent('2')
getByText('Change the numbers in first component').click()
expect(getByTestId('numberInFirst')).toHaveTextContent('1')
expect(getByTestId('numberInOther')).toHaveTextContent('1')
})
test('that it can work with objects', () => {
const obj = {
foo: 'here',
mutateMe: () => {
obj.foo = 'there'
},
}
const ComponentUsingModel = ({model}: {model: typeof obj}) => {
useObserver(model)
return (
<div>
<div data-testid="foo">{model.foo}</div>
</div>
)
}
const {getByTestId} = render(<ComponentUsingModel model={obj} />)
expect(getByTestId('foo')).toHaveTextContent('here')
act(() => {
obj.mutateMe()
})
expect(getByTestId('foo')).toHaveTextContent('there')
})
test('that it can work with multiple objects', () => {
const obj1 = {
foo: 'here',
mutateMe: () => {
obj1.foo = 'there'
},
}
const obj2 = {
bar: 'pete',
mutateMe: () => {
obj2.bar = 'paul'
},
}
function ComponentUsingModel({
model1,
model2,
}: {
model1: typeof obj1
model2: typeof obj2
}) {
useObserver(model1)
useObserver(model2)
return (
<div>
<div data-testid="foo">{model1.foo}</div>
<div data-testid="bar">{model2.bar}</div>
</div>
)
}
const {getByTestId} = render(
<ComponentUsingModel model1={obj1} model2={obj2} />
)
expect(getByTestId('foo')).toHaveTextContent('here')
expect(getByTestId('bar')).toHaveTextContent('pete')
act(() => {
obj1.mutateMe()
})
expect(getByTestId('foo')).toHaveTextContent('there')
expect(getByTestId('bar')).toHaveTextContent('pete')
act(() => {
obj2.mutateMe()
})
expect(getByTestId('bar')).toHaveTextContent('paul')
})
test('that it can work with multiple objects', () => {
const obj1 = {
foo: 'here',
mutateMe: () => {
obj1.foo = 'there'
},
}
const obj2 = {
bar: 'pete',
mutateMe: () => {
obj2.bar = 'paul'
},
}
function ComponentUsingModel1({model}: {model: typeof obj1}) {
useObserver(model)
return (
<div>
<div data-testid="foo">{model.foo}</div>
</div>
)
}
function ComponentUsingModel2({model}: {model: typeof obj2}) {
useObserver(model)
return (
<div>
<div data-testid="bar">{model.bar}</div>
</div>
)
}
const getByTestId1 = render(<ComponentUsingModel1 model={obj1} />).getByTestId
const getByTestId2 = render(<ComponentUsingModel2 model={obj2} />).getByTestId
expect(getByTestId1('foo')).toHaveTextContent('here')
expect(getByTestId2('bar')).toHaveTextContent('pete')
act(() => {
obj1.mutateMe()
})
expect(getByTestId1('foo')).toHaveTextContent('there')
expect(getByTestId2('bar')).toHaveTextContent('pete')
act(() => {
obj2.mutateMe()
})
expect(getByTestId1('foo')).toHaveTextContent('there')
expect(getByTestId2('bar')).toHaveTextContent('paul')
})
test('add hash explicitly', () => {
class TestClass {
current = 2
previous(): void {
this.current--
}
getCurrent(): number {
return this.current
}
}
function ComponentUsingModel({model}: {model: TestClass}) {
const methods = useObserver(model)
return (
<div>
<button onClick={() => methods.previous()}>
Change the numbers in first component
</button>
<div data-testid="numberInFirst">{methods.getCurrent()}</div>
</div>
)
}
function OtherComponentUsingModel({model}: {model: TestClass}) {
const methods = useObserver(model)
return (
<div>
<button onClick={() => methods.previous()}>
Change in the other component
</button>
<div data-testid="numberInOther">{methods.getCurrent()}</div>
</div>
)
}
function ComponentWithNestedUseOfTheModelObject() {
const model = new TestClass()
return (
<>
<ComponentUsingModel model={model} />
<OtherComponentUsingModel model={model} />
</>
)
}
const {getByTestId, getByText} = render(
<ComponentWithNestedUseOfTheModelObject />
)
expect(getByTestId('numberInFirst')).toHaveTextContent('2')
expect(getByTestId('numberInOther')).toHaveTextContent('2')
getByText('Change the numbers in first component').click()
expect(getByTestId('numberInFirst')).toHaveTextContent('1')
expect(getByTestId('numberInOther')).toHaveTextContent('1')
})
test('have a global model', async () => {
class TestClass {
__current = 2
get current(): number {
return this.__current
}
set current(value: number) {
this.__current = value
}
previous(): void {
this.current--
}
getCurrent(): number {
return this.current
}
}
const model = new TestClass()
const useNumberChanger = () => {
return useObserver(model)
}
function ComponentUsingModel() {
const methods = useNumberChanger()
return (
<div>
<button onClick={() => methods.previous()}>
Change the numbers in first component
</button>
<div data-testid="numberInFirst">{methods.getCurrent()}</div>
</div>
)
}
function OtherComponentUsingModel() {
const methods = useNumberChanger()
return (
<div>
<button onClick={() => methods.previous()}>
Change in the other component
</button>
<div data-testid="numberInOther">{methods.getCurrent()}</div>
</div>
)
}
function ComponentWithNestedUseOfTheModelObject() {
return (
<>
<ComponentUsingModel />
<OtherComponentUsingModel />
</>
)
}
const {getByTestId, getByText} = render(
<ComponentWithNestedUseOfTheModelObject />
)
expect(getByTestId('numberInFirst')).toHaveTextContent('2')
expect(getByTestId('numberInOther')).toHaveTextContent('2')
expect(model.getCurrent()).toEqual(2)
getByText('Change the numbers in first component').click()
expect(getByTestId('numberInFirst')).toHaveTextContent('1')
expect(getByTestId('numberInOther')).toHaveTextContent('1')
expect(model.getCurrent()).toEqual(1)
act(() => {
model.previous()
})
expect(model.getCurrent()).toEqual(0)
expect(getByTestId('numberInFirst')).toHaveTextContent('0')
expect(getByTestId('numberInOther')).toHaveTextContent('0')
})
test('nested classes', () => {
class MemberClass {
__current = 2
get current(): number {
return this.__current
}
set current(value: number) {
this.__current = value
}
}
class TestClass {
member: MemberClass = new MemberClass()
previous(): void {
this.member.current--
}
getCurrent(): number {
return this.member.current
}
}
const model = new TestClass()
const useNumberChanger = () => {
return useObserver(model)
}
function ComponentUsingModel() {
const methods = useNumberChanger()
return (
<div>
<button onClick={() => methods.previous()}>
Change the numbers in first component
</button>
<div data-testid="numberInFirst">{methods.getCurrent()}</div>
</div>
)
}
function OtherComponentUsingModel() {
const methods = useNumberChanger()
return (
<div>
<button onClick={() => methods.previous()}>
Change in the other component
</button>
<div data-testid="numberInOther">{methods.getCurrent()}</div>
</div>
)
}
function ComponentWithNestedUseOfTheModelObject() {
return (
<>
<ComponentUsingModel />
<OtherComponentUsingModel />
</>
)
}
const {getByTestId, getByText} = render(
<ComponentWithNestedUseOfTheModelObject />
)
expect(getByTestId('numberInFirst')).toHaveTextContent('2')
expect(getByTestId('numberInOther')).toHaveTextContent('2')
expect(model.getCurrent()).toEqual(2)
getByText('Change the numbers in first component').click()
expect(getByTestId('numberInFirst')).toHaveTextContent('1')
expect(getByTestId('numberInOther')).toHaveTextContent('1')
expect(model.getCurrent()).toEqual(1)
act(() => {
model.previous()
})
expect(model.getCurrent()).toEqual(0)
expect(getByTestId('numberInFirst')).toHaveTextContent('0')
expect(getByTestId('numberInOther')).toHaveTextContent('0')
})
test('Changing a state of one model should not re-render a react component using a different model', () => {
const firstModel = {
foo: 'here',
mutateMe: () => {
firstModel.foo = 'there'
},
}
let firstComponentRerunTimes = 0
function ComponentUsingModel() {
firstComponentRerunTimes++
useObserver(firstModel)
return (
<div>
<div data-testid="foo">{firstModel.foo}</div>
</div>
)
}
const otherModel = {
someValue: 'someString',
changeMe(): void {
this.someValue = 'otherString'
},
getRerunTimes(): string {
return this.someValue
},
}
let differentComponentRerunTimes = 0
function ComponentUsingDifferentModel() {
differentComponentRerunTimes++
useObserver(otherModel)
return (
<div>
<div>{otherModel.getRerunTimes()}</div>
</div>
)
}
const {getByTestId} = render(<ComponentUsingModel />)
render(<ComponentUsingDifferentModel />)
expect(differentComponentRerunTimes).toEqual(1)
expect(firstComponentRerunTimes).toEqual(1)
expect(getByTestId('foo')).toHaveTextContent('here')
act(() => {
firstModel.mutateMe()
})
expect(getByTestId('foo')).toHaveTextContent('there')
expect(firstComponentRerunTimes).toEqual(2)
expect(differentComponentRerunTimes).toEqual(1)
act(() => {
otherModel.changeMe()
})
expect(differentComponentRerunTimes).toEqual(2)
expect(firstComponentRerunTimes).toEqual(2)
})
test('it should re-render when null fields are set to a value', () => {
const object = {field: null}
function Component() {
useObserver(object)
return (
<div data-testid="foo">
{object.field === null ? 'null' : object.field}
</div>
)
}
const {getByTestId} = render(<Component />)
expect(getByTestId('foo')).toHaveTextContent('null')
act(() => {
object.field = 'boo'
})
expect(getByTestId('foo')).toHaveTextContent('boo')
})
test('it should re-render when null fields are set to an object whose value changes', () => {
const object = {field: null}
function Component() {
useObserver(object)
return (
<div data-testid="foo">
{object.field === null ? 'null' : object.field.nested.deep}
</div>
)
}
const {getByTestId} = render(<Component />)
expect(getByTestId('foo')).toHaveTextContent('null')
act(() => {
object.field = {
nested: {
deep: 'value',
},
}
})
expect(getByTestId('foo')).toHaveTextContent('value')
act(() => {
object.field.nested.deep = 'fathoms'
})
expect(getByTestId('foo')).toHaveTextContent('fathoms')
})
test('it should re-render when multi-level depth fields are set to an object whose value changes - no proxy', () => {
const object = {field: null}
function Component() {
useObserver(object)
return (
<div data-testid="foo">
{object.field === null ? 'null' : object.field.nested.deep.very}
</div>
)
}
const {getByTestId} = render(<Component />)
expect(getByTestId('foo')).toHaveTextContent('null')
act(() => {
object.field = {
nested: {
deep: 'value',
},
}
})
act(() => {
object.field.nested = {
deep: {
very: 'deeper',
},
}
})
expect(getByTestId('foo')).toHaveTextContent('deeper')
act(() => {
object.field.nested.deep.very = 'fathoms'
})
expect(getByTestId('foo')).toHaveTextContent('fathoms')
})
test('it should re-render when array values change', () => {
const object = {arr: ['zero']}
function Component() {
useObserver(object)
return <div data-testid="foo">{object.arr.toString()}</div>
}
const {getByTestId} = render(<Component />)
act(() => {
object.arr[0] = 'one'
})
expect(getByTestId('foo')).toHaveTextContent('one')
act(() => {
object.arr.push('two')
})
expect(getByTestId('foo')).toHaveTextContent('one,two')
})
describe.skip('pending edge-cases', () => {
test('it should re-render when array values have objects whose internal values change', () => {
const object = {arr: []}
function Component() {
useObserver(object)
return <div data-testid="foo">{object.arr[0].hello}</div>
}
object.arr[0] = {
hello: 'world',
}
const {getByTestId} = render(<Component />)
expect(getByTestId('foo')).toHaveTextContent('world')
object.arr[0].hello = 'there'
expect(getByTestId('foo')).toHaveTextContent('there')
})
// test('it should re-render when multi-level depth fields are set to an object whose value changes - new field', () => {
// const object = {}
//
// function Component() {
// useObserver(object)
// return (
// <div data-testid="foo">
// {object &&
// object.field &&
// object.field.nested &&
// object.field.nested.deep
// ? object.field.nested.deep.very
// : 'null'}
// </div>
// )
// }
//
// const {getByTestId} = render(<Component />)
//
// expect(getByTestId('foo')).toHaveTextContent('null')
// act(() => {
// // @ts-ignore
// object.field = {
// nested: {
// deep: 'value',
// },
// }
//
// // @ts-ignore
// object.field.nested = {
// deep: {
// very: 'deeper',
// },
// }
// })
//
// expect(getByTestId('foo')).toHaveTextContent('deeper')
// act(() => {
// // @ts-ignore
// object.field.nested.deep.very = 'fathoms'
// })
// expect(getByTestId('foo')).toHaveTextContent('fathoms')
// })
})
test('unmounting one component does not cause other components to be unsubscribed', () => {
class TestClass {
current = 5
previous(): void {
this.current--
}
}
const model = new TestClass()
function ComponentUsingModel() {
const methods = useObserver(model)
return (
<div>
<button onClick={() => methods.previous()}>
Change the numbers in first component
</button>
<div data-testid="numberInFirst">{methods.current}</div>
</div>
)
}
function OtherComponentUsingModel() {
const methods = useObserver(model)
return (
<div>
<button onClick={() => methods.previous()}>
Change in the other component
</button>
<div data-testid="numberInOther">{methods.current}</div>
</div>
)
}
function ComponentWithNestedUseOfTheModelObject() {
useObserver(model)
return (
<>
<ComponentUsingModel />
{model.current > 3 ? <OtherComponentUsingModel /> : null}
</>
)
}
const {getByTestId, getByText} = render(
<ComponentWithNestedUseOfTheModelObject />
)
expect(getByTestId('numberInFirst')).toHaveTextContent('5')
expect(getByTestId('numberInOther')).toHaveTextContent('5')
expect(model.current).toEqual(5)
getByText('Change the numbers in first component').click()
expect(getByTestId('numberInFirst')).toHaveTextContent('4')
expect(getByTestId('numberInOther')).toHaveTextContent('4')
expect(model.current).toEqual(4)
act(() => {
model.previous()
})
expect(model.current).toEqual(3)
expect(getByTestId('numberInFirst')).toHaveTextContent('3')
act(() => {
model.previous()
})
expect(model.current).toEqual(2)
expect(getByTestId('numberInFirst')).toHaveTextContent('2')
}) | the_stack |
import test from "ava";
import { Keychain } from "../src";
// https://en.bitcoin.it/wiki/BIP_0032_TestVectors
const shortSeed = Buffer.from("000102030405060708090a0b0c0d0e0f", "hex");
const longSeed = Buffer.from(
"fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542",
"hex"
);
test("create master keychain from seed", (t) => {
const master = Keychain.fromSeed(shortSeed);
t.is(
master.privateKey.toString("hex"),
"e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35"
);
t.is(
master.identifier.toString("hex"),
"3442193e1bb70916e914552172cd4e2dbc9df811"
);
t.is(master.fingerprint, 876747070);
t.is(
master.chainCode.toString("hex"),
"873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508"
);
t.is(master.index, 0);
t.is(master.depth, 0);
t.is(master.parentFingerprint, 0);
});
test("derive children hardened", (t) => {
const master = Keychain.fromSeed(shortSeed);
const child = master.deriveChild(0, true);
t.is(
child.privateKey.toString("hex"),
"edb2e14f9ee77d26dd93b4ecede8d16ed408ce149b6cd80b0715a2d911a0afea"
);
t.is(
child.identifier.toString("hex"),
"5c1bd648ed23aa5fd50ba52b2457c11e9e80a6a7"
);
t.is(child.fingerprint, 1545328200);
t.is(
child.chainCode.toString("hex"),
"47fdacbd0f1097043b78c63c20c34ef4ed9a111d980047ad16282c7ae6236141"
);
t.is(child.index, 0);
t.is(child.depth, 1);
});
test("derive path", (t) => {
const master = Keychain.fromSeed(shortSeed);
t.is(
master.derivePath(`m/0'`).privateKey.toString("hex"),
"edb2e14f9ee77d26dd93b4ecede8d16ed408ce149b6cd80b0715a2d911a0afea"
);
const child = master.derivePath(`m/0'/1/2'`);
t.is(
child.privateKey.toString("hex"),
"cbce0d719ecf7431d88e6a89fa1483e02e35092af60c042b1df2ff59fa424dca"
);
t.is(
child.identifier.toString("hex"),
"ee7ab90cde56a8c0e2bb086ac49748b8db9dce72"
);
t.is(child.fingerprint, 4001020172);
t.is(
child.chainCode.toString("hex"),
"04466b9cc8e161e966409ca52986c584f07e9dc81f735db683c3ff6ec7b1503f"
);
t.is(child.index, 2);
t.is(child.depth, 3);
});
test("create master keychain from long seed", (t) => {
const master = Keychain.fromSeed(longSeed);
t.is(
master.privateKey.toString("hex"),
"4b03d6fc340455b363f51020ad3ecca4f0850280cf436c70c727923f6db46c3e"
);
t.is(
master.identifier.toString("hex"),
"bd16bee53961a47d6ad888e29545434a89bdfe95"
);
t.is(master.fingerprint, 3172384485);
t.is(
master.chainCode.toString("hex"),
"60499f801b896d83179a4374aeb7822aaeaceaa0db1f85ee3e904c4defbd9689"
);
t.is(master.index, 0);
t.is(master.depth, 0);
t.is(master.parentFingerprint, 0);
});
test("derive path large index", (t) => {
const master = Keychain.fromSeed(longSeed);
t.is(
master.derivePath(`m`).privateKey.toString("hex"),
"4b03d6fc340455b363f51020ad3ecca4f0850280cf436c70c727923f6db46c3e"
);
let child = master.derivePath(`0/2147483647'`);
t.is(
child.privateKey.toString("hex"),
"877c779ad9687164e9c2f4f0f4ff0340814392330693ce95a58fe18fd52e6e93"
);
t.is(
child.identifier.toString("hex"),
"d8ab493736da02f11ed682f88339e720fb0379d1"
);
t.is(child.fingerprint, 3635104055);
t.is(
child.chainCode.toString("hex"),
"be17a268474a6bb9c61e1d720cf6215e2a88c5406c4aee7b38547f585c9a37d9"
);
t.is(child.index, 2147483647);
t.is(child.depth, 2);
child = child.deriveChild(1, false);
t.is(
child.privateKey.toString("hex"),
"704addf544a06e5ee4bea37098463c23613da32020d604506da8c0518e1da4b7"
);
t.is(
child.identifier.toString("hex"),
"78412e3a2296a40de124307b6485bd19833e2e34"
);
t.is(child.fingerprint, 2017537594);
t.is(
child.chainCode.toString("hex"),
"f366f48f1ea9f2d1d3fe958c95ca84ea18e4c4ddb9366c336c927eb246fb38cb"
);
t.is(child.index, 1);
t.is(child.depth, 3);
child = child.deriveChild(2147483646, true);
t.is(
child.privateKey.toString("hex"),
"f1c7c871a54a804afe328b4c83a1c33b8e5ff48f5087273f04efa83b247d6a2d"
);
t.is(
child.identifier.toString("hex"),
"31a507b815593dfc51ffc7245ae7e5aee304246e"
);
t.is(child.fingerprint, 832899000);
t.is(
child.chainCode.toString("hex"),
"637807030d55d01f9a0cb3a7839515d796bd07706386a6eddf06cc29a65a0e29"
);
t.is(child.index, 2147483646);
t.is(child.depth, 4);
});
test("derive children no hardened", (t) => {
const master = Keychain.fromSeed(longSeed);
const child = master.deriveChild(0, false);
t.is(
child.privateKey.toString("hex"),
"abe74a98f6c7eabee0428f53798f0ab8aa1bd37873999041703c742f15ac7e1e"
);
t.is(
child.identifier.toString("hex"),
"5a61ff8eb7aaca3010db97ebda76121610b78096"
);
t.is(child.fingerprint, 1516371854);
t.is(
child.chainCode.toString("hex"),
"f0909affaa7ee7abe5dd4e100598d4dc53cd709d5a5c2cac40e7412f232f7c9c"
);
t.is(child.index, 0);
t.is(child.depth, 1);
});
test("create child keychain from public key", (t) => {
const child = Keychain.fromPublicKey(
Buffer.from(
"0357bfe1e341d01c69fe5654309956cbea516822fba8a601743a012a7896ee8dc2",
"hex"
),
Buffer.from(
"04466b9cc8e161e966409ca52986c584f07e9dc81f735db683c3ff6ec7b1503f",
"hex"
),
`m/0'/1/2'`
);
t.is(
child.identifier.toString("hex"),
"ee7ab90cde56a8c0e2bb086ac49748b8db9dce72"
);
t.is(child.fingerprint, 4001020172);
t.is(child.index, 2);
t.is(child.depth, 3);
const grandchild = child.deriveChild(2, false);
t.is(
grandchild.publicKey.toString("hex"),
"02e8445082a72f29b75ca48748a914df60622a609cacfce8ed0e35804560741d29"
);
t.is(
grandchild.chainCode.toString("hex"),
"cfb71883f01676f587d023cc53a35bc7f88f724b1f8c2892ac1275ac822a3edd"
);
t.is(
grandchild.identifier.toString("hex"),
"d880d7d893848509a62d8fb74e32148dac68412f"
);
t.is(grandchild.fingerprint, 3632322520);
t.is(grandchild.index, 2);
t.is(grandchild.depth, 4);
});
test("derive ckb keys", (t) => {
const master = Keychain.fromSeed(shortSeed);
const extendedKey = master.derivePath(`m/44'/309'/0'`);
t.is(
extendedKey.privateKey.toString("hex"),
"bb39d218506b30ca69b0f3112427877d983dd3cd2cabc742ab723e2964d98016"
);
t.is(
extendedKey.publicKey.toString("hex"),
"03e5b310636a0f6e7dcdfffa98f28d7ed70df858bb47acf13db830bfde3510b3f3"
);
t.is(
extendedKey.chainCode.toString("hex"),
"37e85a19f54f0a242a35599abac64a71aacc21e3a5860dd024377ffc7e6827d8"
);
const addressKey = extendedKey.deriveChild(0, false).deriveChild(0, false);
t.is(
addressKey.privateKey.toString("hex"),
"fcba4708f1f07ddc00fc77422d7a70c72b3456f5fef3b2f68368cdee4e6fb498"
);
t.is(
addressKey.publicKey.toString("hex"),
"0331b3c0225388c5010e3507beb28ecf409c022ef6f358f02b139cbae082f5a2a3"
);
t.is(
addressKey.chainCode.toString("hex"),
"c4b7aef857b625bbb0497267ed51151d090f81737f4f22a0ac3673483b927090"
);
});
test("derive ckb keys another seed", (t) => {
const master = Keychain.fromSeed(
// From mnemonic `tank planet champion pottery together intact quick police asset flower sudden question`
Buffer.from(
"1371018cfad5990f5e451bf586d59c3820a8671162d8700533549b0df61a63330e5cd5099a5d3938f833d51e4572104868bfac7cfe5b4063b1509a995652bc08",
"hex"
)
);
t.is(
master.privateKey.toString("hex"),
"37d25afe073a6ba17badc2df8e91fc0de59ed88bcad6b9a0c2210f325fafca61"
);
t.is(
master.derivePath(`m/44'/309'/0'`).privateKey.toString("hex"),
"2925f5dfcbee3b6ad29100a37ed36cbe92d51069779cc96164182c779c5dc20e"
);
t.is(
master
.derivePath(`m/44'/309'/0'`)
.deriveChild(0, false)
.privateKey.toString("hex"),
"047fae4f38b3204f93a6b39d6dbcfbf5901f2b09f6afec21cbef6033d01801f1"
);
t.is(
master.derivePath(`m/44'/309'/0'/0`).privateKey.toString("hex"),
"047fae4f38b3204f93a6b39d6dbcfbf5901f2b09f6afec21cbef6033d01801f1"
);
t.is(
master
.derivePath(`m/44'/309'/0'`)
.deriveChild(0, false)
.deriveChild(0, false)
.privateKey.toString("hex"),
"848422863825f69e66dc7f48a3302459ec845395370c23578817456ad6b04b14"
);
t.is(
master.derivePath(`m/44'/309'/0'/0/0`).privateKey.toString("hex"),
"848422863825f69e66dc7f48a3302459ec845395370c23578817456ad6b04b14"
);
});
test("derive ckb keys from master extended key", (t) => {
const privateKey = Buffer.from(
"37d25afe073a6ba17badc2df8e91fc0de59ed88bcad6b9a0c2210f325fafca61",
"hex"
);
const chainCode = Buffer.from(
"5f772d1e3cfee5821911aefa5e8f79d20d4cf6678378d744efd08b66b2633b80",
"hex"
);
const master = new Keychain(privateKey, chainCode);
t.is(
master.publicKey.toString("hex"),
"020720a7a11a9ac4f0330e2b9537f594388ea4f1cd660301f40b5a70e0bc231065"
);
t.is(
master.derivePath(`m/44'/309'/0'`).privateKey.toString("hex"),
"2925f5dfcbee3b6ad29100a37ed36cbe92d51069779cc96164182c779c5dc20e"
);
t.is(
master
.derivePath(`m/44'/309'/0'`)
.deriveChild(0, false)
.privateKey.toString("hex"),
"047fae4f38b3204f93a6b39d6dbcfbf5901f2b09f6afec21cbef6033d01801f1"
);
t.is(
master.derivePath(`m/44'/309'/0'/0`).privateKey.toString("hex"),
"047fae4f38b3204f93a6b39d6dbcfbf5901f2b09f6afec21cbef6033d01801f1"
);
t.is(
master
.derivePath(`m/44'/309'/0'`)
.deriveChild(0, false)
.deriveChild(0, false)
.privateKey.toString("hex"),
"848422863825f69e66dc7f48a3302459ec845395370c23578817456ad6b04b14"
);
t.is(
master.derivePath(`m/44'/309'/0'/0/0`).privateKey.toString("hex"),
"848422863825f69e66dc7f48a3302459ec845395370c23578817456ad6b04b14"
);
});
test("private key add", (t) => {
const privateKey = Buffer.from(
"9e919c96ac5a4caea7ba0ea1f7dd7bca5dca8a11e66ed633690c71e483a6e3c9",
"hex"
);
const toAdd = Buffer.from(
"36e92e33659808bf06c3e4302b657f39ca285f6bb5393019bb4e2f7b96e3f914",
"hex"
);
// @ts-ignore: Private method
const sum = Keychain.privateKeyAdd(privateKey, toAdd);
t.is(
sum.toString("hex"),
"d57acaca11f2556dae7df2d22342fb0427f2e97d9ba8064d245aa1601a8adcdd"
);
});
test("public key add", (t) => {
const publicKey = Buffer.from(
"03556b2c7e03b12845a973a6555b49fe44b0836fbf3587709fa73bb040ba181b21",
"hex"
);
const toAdd = Buffer.from(
"953fd6b91b51605d32a28ab478f39ab53c90103b93bd688330b118c460e9c667",
"hex"
);
// @ts-ignore: Private method
const sum = Keychain.publicKeyAdd(publicKey, toAdd);
t.is(
sum.toString("hex"),
"03db6eab66f918e434bae0e24fd73de1a2b293a2af9bd3ad53123996fa94494f37"
);
}); | the_stack |
"use strict";
// uuid: 3d515a83-c625-4829-bc61-de6eb79b72cd
// ------------------------------------------------------------------------
// Copyright (c) 2018 Alexandre Bento Freire. All rights reserved.
// Licensed under the MIT License+uuid License. See License.txt for details
// ------------------------------------------------------------------------
/** @module end-user | The lines bellow convey information for the end-user */
/**
* ## Description
*
* An **oscillator** is an optional interpolator that runs `t` from [easing(0), easing(1)]
* and the usually outputs a value from [-1, 1] where usually
* f(0) = 0 and f(1) = 0.
* Its output will be generate `v = valueStart + (value - valueStart) * oscillator(easing(t))`
* and then will be injected into a path as input.
*
* An oscillator has the following usages:
*
* 1. A rotational movement, where the oscillator defines the rotation and
* the easing the defines the speed.
*
* 2. Flashing elements, where an element changes its `opacity` or `text-shadow`,
* and these values oscillate between [0, 1].
*
* 3. Uni-dimensional oscillators. Unlike oscillators, the oscillators have their value stored
* in the Action Link, allowing to link the end value to the next animation.
*
* An oscillator if it's used together with an easing will if it's in the same dimension
* deform the wave and if it's in different dimensions the easing will define
* the speed of oscillator.
*
* The oscillators shares the namespace with [](easings), allowing any easing function
* to operate also as a oscillator.
* Since the main function of an oscillator is to return to its original position
* at the end of the animation cycle, when an easing is used as an oscillator the
* best is to use the following:
* ```json
* { iterationCount: 2,
* direction: alternate
* }
* ```
*
* One type of oscillators are `pulsars`.
* Pulsars only have energy during a certain amount of time,
* the rest of the time are motionless.
*
*
* ## Core oscillators
* **WARNING!** In the ABeamer 2.x these core oscillators will move `core-oscillators` plugin.
* To prevent breaking changes include now the js script `core-oscillators.js` on the html file.
*
* ABeamer has the following core oscillators:
*
* - `harmonic` - it generates a sinusoidal function that repeats it self every
* duration / cycles.
* @see gallery/animate-oscillator
*
* - `damped` - it's a sinusoidal function that reduces its amplitude due friction in
* every cycle.
* To reduce the user's effort, ABeamer uses cycles parameter to compute the friction.
*
* - `pulsar` - outside the range of [midpoint - spread, midpoint + spread]
* it will return 0, and inside the range will generate a function depending of
* the parameter `type`:
* * `normal` - a bell shape curve. this is the default type.
* * `sine` - a sinusoidal function.
* * `random` - a random value within [-1, 1].
* * `positive-random` - a random value with [0, 1].
* @see gallery/animate-pulsar
*/
namespace ABeamer {
// #generate-group-section
// ------------------------------------------------------------------------
// Oscillators
// ------------------------------------------------------------------------
// The following section contains data for the end-user
// generated by `gulp build-definition-files`
// -------------------------------
// #export-section-start: release
/**
* Defines the type of a oscillator function.
* An oscillator function is an interpolator that runs from [0, 1].
* Usually outputs a value from [-1, 1] but other values are also possible.
* An oscillator is mostly used to rotate an element returning to the original position.
*/
export type OscillatorFunc = (t: number, params: OscillatorParams,
args?: ABeamerArgs) => number;
/**
* Defines the oscillator type, which is either string representing a predefined
* oscillator function or a custom function (see oscillator function)
* The oscillator function interpolates from [0, 1].
*/
export type OscillatorHandler = OscillatorName | number | ExprString
| OscillatorFunc | EasingFunc;
/**
* Defines the Base parameters for every oscillator function.
* At the moment no parameter is required, but it can change in the future.
*/
export type OscillatorParams = AnyParams;
/** List of the built-in oscillators */
export enum OscillatorName {
harmonic = 1000, // lower ids are for easings.
damped,
pulsar,
}
/** Oscillator parameters defined in an Animation Property. */
export interface Oscillator {
/** Defines an Oscillator by Name, Expression or Code Handler */
handler: OscillatorHandler;
/** Params passed to the Oscillator. Depends on the Oscillator Type */
params?: AnyParams
| HarmonicOscillatorParams
| DampedOscillatorParams
| PulsarOscillatorParams
;
}
/** Function used to define what to do when a value is negative. */
export type NegativeFunc = (t: number) => number;
/**
* List of Negative built-in functions:
* - `abs` Math.abs
* - `clip` If v < 0 then v = 0
*/
export enum NegativeBuiltInFuncs {
none,
clip,
abs,
}
/** Params defined inside the props.oscillator.params, when `props.oscillator = 'harmonic'` */
export interface HarmonicOscillatorParams extends OscillatorParams {
/**
* Defines the number of full cycles (positive arc+negative arc)
* contained during the `duration` period.
* If `negativeHander = abs`, 1 cycle will have 2 arcs.
*/
cycles?: number;
/** Function used to define what to do when a value is negative. */
negativeHander?: NegativeBuiltInFuncs | string | NegativeFunc;
/** Allows to shift and scale the input of every oscillator. */
shift: number;
// cut: number;
}
/** Params defined inside the props.oscillator.params, when `props.oscillator = 'damped'` */
export interface DampedOscillatorParams {
frequency?: number;
/** Defines how much energy the oscillator will lose from one cycle to the next. */
friction?: number;
/** Function used to define what to do when a value is negative. */
negativeHander?: NegativeBuiltInFuncs | string | NegativeFunc;
}
/** List of the built-in pulsar type */
export enum PulsarType {
normal,
sine,
random,
positiveRandom,
}
/** Params defined inside the props.oscillator.params, when `props.oscillator = 'pulsar'` */
export interface PulsarOscillatorParams {
/** Type of pulsar defined by ID or string. */
type?: PulsarType | string;
/** The point where the pulsar reaches it's maximum value. */
midpoint?: number;
/**
* The amplitude around midpoint where the pulsar begins to receive value.
* The pulsar starts gaining energy at `midpoint-spread`, reaches the maximum value
* at `midpoint` and then decreases until reaches zero at `midpoint+spread`.
*/
spread?: number;
}
// #export-section-end: release
// -------------------------------
// ------------------------------------------------------------------------
// Implementation
// ------------------------------------------------------------------------
export function _oscillatorNumToStr(num: number): string {
return OscillatorName[num] || _easingNumToStr(num);
}
/** Transforms the user `negativeHandler` value into a Code Handler. */
function _parseNegativeHandler(negativeHander?: NegativeBuiltInFuncs
| string | NegativeFunc): NegativeFunc {
if (typeof negativeHander === 'string') {
negativeHander = NegativeBuiltInFuncs[negativeHander];
}
if (typeof negativeHander === 'number') {
switch (negativeHander) {
case NegativeBuiltInFuncs.abs: return (t) => Math.abs(t);
case NegativeBuiltInFuncs.clip: return (t) => Math.abs(t);
}
}
return negativeHander as NegativeFunc;
}
// ------------------------------------------------------------------------
// Harmonic Oscillator
// ------------------------------------------------------------------------
/** Internal parameters to the Harmonic Oscillator */
interface _WorkHarmonicOscillatorParams extends HarmonicOscillatorParams {
_isPrepared: boolean;
_negativeHandler: NegativeFunc;
_cycles: number;
_shift: number;
}
_easingFunctions['harmonic'] = _harmonicOscillator;
/** Implements the Harmonic Oscillator */
function _harmonicOscillator(t: number,
params: _WorkHarmonicOscillatorParams): number {
if (!params._isPrepared) {
params._cycles = params.cycles || 1;
params._negativeHandler = _parseNegativeHandler(params.negativeHander);
params._shift = params.shift || 0;
}
const cycles = params._cycles;
const v = Math.sin(Math.PI * 2 * (t + params._shift) * cycles);
return params._negativeHandler ? params._negativeHandler(v) : v;
}
// ------------------------------------------------------------------------
// Damped Oscillator
// ------------------------------------------------------------------------
/** Internal parameters to the Damped Oscillator */
interface _WorkDampedOscillatorParams extends DampedOscillatorParams {
_isPrepared: boolean;
_curFrequency: number;
_curAmplitude: number;
_scale: number;
_shift: number;
_negativeHandler: NegativeFunc;
}
_easingFunctions['damped'] = _dampedOscillator;
/** Implements the Damped Oscillator */
function _dampedOscillator(t: number,
params: _WorkDampedOscillatorParams): number {
if (!params._isPrepared) {
params._isPrepared = true;
params._curFrequency = params.frequency || 0.1;
params._curAmplitude = 1;
params._scale = 1 - (params.friction || 0.1);
params._shift = 0;
params._negativeHandler = _parseNegativeHandler(params.negativeHander);
}
let t1 = t - params._shift;
if (t1 >= params._curFrequency) {
params._shift = t;
params._curFrequency = params._curFrequency * params._scale;
params._curAmplitude = params._curAmplitude * params._scale;
t1 = t - params._shift;
}
// @TODO: Improve the damped function
const v = Math.sin(Math.PI * 2 * (t1 / params._curFrequency)) * params._curAmplitude;
return params._negativeHandler ? params._negativeHandler(v) : v;
}
// ------------------------------------------------------------------------
// Pulsar Oscillator
// ------------------------------------------------------------------------
/** Internal parameters to the Pulsar Oscillator */
interface _WorkPulsarOscillatorParams extends PulsarOscillatorParams {
_isPrepared: boolean;
}
_easingFunctions['pulsar'] = _pulsarOscillator;
/** Implements the Pulsar Oscillator */
function _pulsarOscillator(t: number,
params: _WorkPulsarOscillatorParams): number {
if (!params._isPrepared) {
params._isPrepared = true;
params.midpoint = params.midpoint || 0.5;
params.spread = params.spread || 0.1;
params.type = params.type || PulsarType.normal;
if (typeof params.type === 'string') {
params.type = PulsarType[params.type];
}
}
const midpoint = params.midpoint;
const spread = params.spread;
if (t <= midpoint - spread || t >= midpoint + spread) { return 0; }
const pulsarType = params.type as PulsarType;
switch (pulsarType) {
case PulsarType.normal:
let t1 = (t - (midpoint - spread)) / spread;
if (t > midpoint) { t1 = 2 - t1; }
return (Math.exp(t1) - 1) / (Math.E - 1);
case PulsarType.sine:
const t2 = (t - (midpoint - spread)) / spread;
return Math.sin(Math.PI * t2);
case PulsarType.random:
return Math.random() * 2 - 1;
case PulsarType.positiveRandom:
return Math.random();
}
}
} | the_stack |
import { action, computed, observable } from 'mobx'
import { observer } from 'mobx-react'
import * as React from 'react'
import { DataSource, Paper, PaperGroup, SorterConfig } from '../api/document'
import { get_current_article } from '../arxiv_page'
import { PAGE_LENGTH } from '../bib_config'
import { random_id } from '../bib_lib'
import { PaperDiv } from './PaperDiv'
// Function to sort Papers for ColumnView, sorts the Paper array in place
const sort_builder = (arr: Paper[], field: (p: Paper) => number|string, ord: 'up'|'down'): Paper[] => {
const sign = (ord === 'up') ? -1 : 1
return arr.sort((a, b) => {
if (field(a) > field(b)) { return -1 * sign }
if (field(a) < field(b)) { return +1 * sign }
if (a.simpletitle > b.simpletitle) { return +1 }
if (a.simpletitle < b.simpletitle) { return -1 }
return 0
})
}
@observer
export class ColumnView extends React.Component<{dataSource: DataSource, paperGroup: PaperGroup,
name: string}, {}> {
/**
* Filtered sorted papers for this column.
* @computed makes it so this value will trigger a render change when
* it's dependent observable values change.
*/
@computed
get fdata(): Paper[] {
if (!this.props.paperGroup) {
return []
}
const datacopy = this.props.paperGroup.documents.slice()
return this.filterPapers(this.sortPapers(this.props.paperGroup, datacopy))
}
/** Slice of fdata Papers for current page. */
@computed
get pdata(): Paper[] {
const papers = this.fdata
const start = PAGE_LENGTH * (this.page - 1)
const end = Math.min(start + PAGE_LENGTH, papers.length)
return papers.slice(start, end)
}
@computed
get cname(): string {
return this.props.paperGroup.header
}
@observable
sort_field: string = ''
@observable
sort_order: 'up' | 'down' = 'down'
@observable
filter_text: string = ''
@observable
page = 1
redrawMathJax() {
try {
// @ts-ignore -- accessing existing MathJax on page
MathJax.Hub.Queue(['Typeset', MathJax.Hub])
} catch (e) {
console.log('MathJax not found')
}
}
componentDidMount() {
this.redrawMathJax()
}
componentDidUpdate() {
this.redrawMathJax()
}
render() {
const filt = this.fdata
const group = this.props.paperGroup
const datasource = this.props.dataSource
const papers = group ? this.pdata : []
if (!this.props.paperGroup) {
return null
}
const N = group.documents.length
const group_count = (
(N === datasource.max_count) ? `${N.toString()}+` : N.toString()
)
let count_msg: string = ''
if (filt.length !== N) {
count_msg = `(${filt.length}/${group_count})`
} else {
count_msg = `(${group_count})`
}
const mailto = (
'mailto:' + datasource.email +
'?subject=Reference and citation data for arXiv article ' +
get_current_article()
)
const header = this.props.name.toLowerCase()
const aside = (
`Of this article's ${header}, only displaying the ${datasource.max_count} ` +
`most cited works. For all ${header}, follow this link to ${datasource.longname}.`
)
const star = (
N === datasource.max_count ?
<a title={aside} href={group.header_url} target='_blank'
className='bib-col-title bib-star' style={{color: 'red'}}>*</a> : null
)
const utils = (
<div className='bib-utils'>
<div className='center'>{this.create_filter_div()}</div>
<div className='center'>{this.create_sorter_div()}</div>
<div className='center'>{this.create_paging_div()}</div>
</div>
)
const utils_div = group.count === 0 ? null : utils
return (
<div className='bib-col' id={'col-' + this.props.name.toLocaleLowerCase()}>
<div className='bib-col-header'>
<span className='bib-col-center'>
<a className='bib-col-title' href={group.header_url}>
{this.props.name} {count_msg}</a> {star}
</span>
<div className='bib-branding bib-col-center'>
<div className='bib-col-aside bib-branding-info'>
<span>Data provided by:</span><br/>
<span>(<a href={mailto}>report data issues</a>)</span>
</div>
<div className='bib-branding-logo'>
<a target='_blank' href={datasource.homepage}>
<img alt={datasource.longname} src={datasource.logo} height='32px' width='auto'/>
</a>
</div>
</div>
</div>
{utils_div}
<div>
{papers.map(paper => <PaperDiv key={paper.index} paper={paper}/> )}
</div>
</div>
)
}
create_filter_div() {
const lblid = `bib-filter-input--${this.cname}`
return (
<div className='bib-filter'>
<label htmlFor={lblid} className='bib-filter-label'>Filter: </label>
<input type='search' id={lblid} className='bib-filter-input' value={this.filter_text}
onChange={
(e) => {
this.page = 1
this.filter_text = e.target.value
}
}/>
</div>
)
}
sortPapers(paperGroup: PaperGroup, data: Paper[]): Paper[] {
if (!paperGroup || ! data) { return [] }
if (this.sort_field === '' ) {
this.sort_field = paperGroup.sorting.sorters_default
}
const field = this.sort_field
const sorters = this.props.paperGroup.sorting.sorters
if (sorters[field] && sorters[field].func) {
return sort_builder(data, sorters[field].func, this.sort_order)
} else {
console.log(`Could not sort: no sort entry in sorter for '${field}'
Check datasource sorting configuration.`)
return data
}
}
filterPapers(data: Paper[]): Paper[] {
if (this.filter_text.length === 0 || this.filter_text === '') {
return data
}
const words = this.filter_text.toLocaleLowerCase().split(' ')
let output = data
for (const word of words) {
const newlist: Paper[] = []
for (const doc of output) {
if (doc.searchline.includes(word)) {
newlist.push(doc)
}
}
output = newlist
}
return output
}
totalPages(): number {
return Math.floor((this.fdata.length - 1) / PAGE_LENGTH) + 1
}
@action
toggle_sort() {
this.sort_order = this.sort_order === 'up' ? 'down' : 'up'
this.page = 1
//this.page = this.totalPages() - this.page + 1
}
@action
change_sort_field(field: string) {
this.sort_order = this.props.paperGroup.sorting.sorters_updown[field]
this.sort_field = field
this.page = 1
}
create_sorter_div() {
if (!this.props.paperGroup.sorting) {
return null
}
const lblid = `sort_field--${this.cname}`
return(
<div className='bib-sorter'>
<label htmlFor={lblid} className='sort-label'>Sort: </label>
<select className='sort_field' id={lblid}
onChange={(e) => {this.change_sort_field(e.target.value)}}
value={this.sort_field}>
{this.sort_options(this.props.paperGroup.sorting)}
</select>
<span className='bib-sort-arrow sort-label'>
<a href='javascript:;' onClick={(e) => {
e.preventDefault()
this.toggle_sort()
}}>
<span className={this.sort_order !== 'up' ? 'disabled' : ''}
title='Sort ascending'>▲</span>
<span className={this.sort_order !== 'down' ? 'disabled' : ''}
title='Sort descending'>▼</span>
</a>
</span>
</div>
)
}
sort_options( sortConfig: SorterConfig) {
if (!sortConfig) {
return []
}
return sortConfig.sorters_order.map(key => {
if (sortConfig.sorters[key]) {
return (
<option value={key} key={key}>{sortConfig.sorters[key].name}</option>
)
} else {
if (key) {
console.log(`No sorter with key '${key}' Check datasource sorting configuration.`)
}
return null
}
})
}
/**
* This is a bit of a mess, but it basically ensures that the page list
* looks visually uniform independent of the current page number. We want
* - always the same number of elements
* - always first / last pages, and prev / next
* < 1̲ 2 3 4 5 . 9 >
* < 1 2 3̲ 4 5 . 9 >
* < 1 2 3 4̲ 5 . 9 >
* < 1 . 4 5̲ 6 . 9 >
* < 1 . 5 6̲ 7 8 9 >
* This makes the numbers easier to navigate and more visually appealing.
*/
create_paging_div() {
if (!this.fdata) {return null}
const B = 1 /* number of buffer pages on each side of current */
const P = this.page /* shortcut to current page */
const L = this.totalPages() /* total pages */
const S = 2 * B + 2 * 2 + 1 /* number of total links in the pages sections:
2*buffer + 2*(first number + dots) + current */
const[langle, rangle, dots] = ['◀', '▶', '...']
const _nolink = (txt: string|number, classname?: string) => {
classname = (classname === undefined) ? 'disabled' : classname
return <li key={txt + random_id()} className={classname}><span>{txt}</span></li>
}
const _link = (n: number, txt?: string) => {
return (
<li key={n + (txt || 'none')}>
<a title={`Page ${n}`} href={`javascript:${n};`}
onClick={(e) => {e.preventDefault(); this.page = n}}>
{(txt === undefined) ? n : txt}</a>
</li>
)
}
const _inclink = (dir: -1|1) => { /* << >> links */
const txt = (dir < 0) ? langle : rangle
return ((P + dir < 1) || (P + dir > L)) ? _nolink(txt) : _link(P + dir, txt)
}
const _pagelink = (n: number, show_dots?: any) => {
const a = (show_dots === undefined) ? true : show_dots
return !a ? _nolink(dots) : ((n === P) ? _nolink(n, 'bold') : _link(n))
}
const page_links: JSX.Element[] = []
page_links.push(_inclink(-1))
if (L <= S) {
// just show all numbers if the number of pages is less than the slots
for (let i = 1; i <= L; i++) {
page_links.push(_pagelink(i))
}
} else {
// the first number (1) and dots if list too long
page_links.push(_pagelink(1))
page_links.push(_pagelink(2, P <= 1 + 2 + B))
// limit the beginning and end numbers to be appropriate ranges
const i0 = Math.min(L - 2 - 2 * B, Math.max(1 + 2, P - B))
const i1 = Math.max(1 + 2 + 2 * B, Math.min(L - 2, P + B))
for (let i = i0; i <= i1; i++) {
page_links.push(_pagelink(i))
}
// the last number (-1) and dots if list too long
page_links.push(_pagelink(L - 1, P >= L - 2 - B))
page_links.push(_pagelink(L - 0))
}
page_links.push(_inclink(+1))
const lblid = `bib-jump-label--${this.cname}`
return (
<div className='center bib-pager'>
<span>
<span>Pages:</span>
<ul className='bib-page-list'>{page_links}</ul>
<label htmlFor={lblid}>Skip: </label>
<select id={lblid} value={this.page} onChange={(e) => this.page = parseInt(e.target.value, 10) }>
{ [...Array(L).keys()].map( i => <option key={i} value={i + 1}>{i + 1}</option>)}
</select>
</span>
</div >
)
}
} | the_stack |
import Application from "../application";
import { I_rpcTimeout, I_rpcMsg, ServerInfo, rpcErr } from "../util/interfaceDefine";
import * as path from "path";
import * as fs from "fs";
import define = require("../util/define");
import * as appUtil from "../util/appUtil";
import { I_RpcSocket } from "./rpcSocketPool";
let app: Application;
let msgHandler: { [filename: string]: any } = {};
let rpcId = 1; // Must start from 1, not 0
let rpcRequest: { [id: number]: I_rpcTimeout } = {};
let rpcTimeMax: number = 10 * 1000; //overtime time
let outTime = 0; // Current time + timeout
/**
* init
* @param _app
*/
export function init(_app: Application) {
app = _app;
let rpcConfig = app.someconfig.rpc || {};
let timeout = Number(rpcConfig.timeout) || 0;
if (timeout >= 5) {
rpcTimeMax = timeout * 1000;
}
outTime = Date.now() + rpcTimeMax;
setInterval(() => {
outTime = Date.now() + rpcTimeMax;
}, 100);
setInterval(checkTimeout, 3000);
new rpc_create();
}
/**
* Process rpc messages
*
* [1] [1] [...] [...] [...]
* msgType rpcBufLen rpcBuf msgBuf bufLast
*/
export function handleMsg(sid: string, bufAll: Buffer) {
let rpcBufLen = bufAll.readUInt8(1);
let rpcMsg: I_rpcMsg = JSON.parse(bufAll.slice(2, 2 + rpcBufLen).toString());
let msg: any[];
if (rpcMsg.len === undefined) {
msg = JSON.parse(bufAll.slice(2 + rpcBufLen).toString());
} else {
msg = JSON.parse(bufAll.slice(2 + rpcBufLen, bufAll.length - rpcMsg.len).toString());
msg.push(bufAll.slice(bufAll.length - rpcMsg.len));
}
if (!rpcMsg.cmd) {
let timeout = rpcRequest[rpcMsg.id as number];
if (timeout) {
delete rpcRequest[rpcMsg.id as number];
timeout.cb(...msg);
}
} else {
let cmd = (rpcMsg.cmd as string).split('.');
if (rpcMsg.id) {
msg.push(getCallBackFunc(sid, rpcMsg.id));
}
msgHandler[cmd[0]][cmd[1]](...msg);
}
}
export function handleMsgAwait(sid: string, bufAll: Buffer) {
let rpcBufLen = bufAll.readUInt8(1);
let rpcMsg: I_rpcMsg = JSON.parse(bufAll.slice(2, 2 + rpcBufLen).toString());
let msg: any;
if (rpcMsg.len === undefined) {
msg = JSON.parse(bufAll.slice(2 + rpcBufLen).toString());
} else if (2 + rpcBufLen + rpcMsg.len === bufAll.length) {
msg = bufAll.slice(bufAll.length - rpcMsg.len);
} else {
msg = JSON.parse(bufAll.slice(2 + rpcBufLen, bufAll.length - rpcMsg.len).toString());
msg.push(bufAll.slice(bufAll.length - rpcMsg.len));
}
if (!rpcMsg.cmd) {
let timeout = rpcRequest[rpcMsg.id as number];
if (timeout) {
delete rpcRequest[rpcMsg.id as number];
timeout.cb(msg);
}
} else {
let cmd = (rpcMsg.cmd as string).split('.');
let res = msgHandler[cmd[0]][cmd[1]](...msg);
if (!rpcMsg.id) {
return;
}
if (res && typeof res.then === "function") {
res.then((data: any) => {
cbFunc(data);
});
} else {
cbFunc(res);
}
function cbFunc(data: any) {
let socket = app.rpcPool.getSocket(sid);
if (!socket) {
return;
}
if (data === undefined) {
data = null;
}
if (data instanceof Buffer) {
socket.send(getRpcMsg({ "id": rpcMsg.id }, Buffer.allocUnsafe(0), data, define.Rpc_Msg.rpcMsgAwait));
} else if (data instanceof Array && data[data.length - 1] instanceof Buffer) {
let tmpRes = [...data];
let buf: Buffer = tmpRes.pop();
socket.send(getRpcMsg({ "id": rpcMsg.id }, Buffer.from(JSON.stringify(tmpRes)), buf, define.Rpc_Msg.rpcMsgAwait));
} else {
socket.send(getRpcMsg({ "id": rpcMsg.id }, Buffer.from(JSON.stringify(data)), null as any, define.Rpc_Msg.rpcMsgAwait));
}
}
}
}
/**
* rpc structure
*/
class rpc_create {
private toId: string = "";
private notify: boolean = false;
private rpcObj: Rpc = {};
private rpcObjAwait: Rpc = {};
constructor() {
this.loadRemoteMethod();
}
loadRemoteMethod() {
let self = this;
app.rpc = this.rpcFunc.bind(this);
app.rpcAwait = this.rpcFuncAwait.bind(this);
let tmp_rpc_obj = this.rpcObj as any;
let tmp_rpc_obj_await = this.rpcObjAwait as any;
let dirName = path.join(app.base, define.some_config.File_Dir.Servers);
let exists = fs.existsSync(dirName);
if (!exists) {
return;
}
let thisSvrHandler: { "filename": string, "con": any }[] = [];
fs.readdirSync(dirName).forEach(function (serverName) {
let needRpc = !app.noRpcMatrix[appUtil.getNoRpcKey(app.serverType, serverName)];
if (!needRpc && serverName !== app.serverType) {
return;
}
let remoteDirName = path.join(dirName, serverName, '/remote');
let exists = fs.existsSync(remoteDirName);
if (exists) {
if (needRpc) {
tmp_rpc_obj[serverName] = {};
tmp_rpc_obj_await[serverName] = {};
}
fs.readdirSync(remoteDirName).forEach(function (fileName) {
if (!fileName.endsWith(".js")) {
return;
}
let fileBasename = path.basename(fileName, '.js');
let remote = require(path.join(remoteDirName, fileName));
if (remote.default && typeof remote.default === "function") {
if (needRpc) {
tmp_rpc_obj[serverName][fileBasename] = self.initFunc(serverName, fileBasename, remote.default.prototype, Object.getOwnPropertyNames(remote.default.prototype));
tmp_rpc_obj_await[serverName][fileBasename] = self.initFuncAwait(serverName, fileBasename, remote.default.prototype, Object.getOwnPropertyNames(remote.default.prototype));
}
if (serverName === app.serverType) {
thisSvrHandler.push({ "filename": fileBasename, "con": remote.default });
}
}
});
}
});
for (let one of thisSvrHandler) {
msgHandler[one.filename] = new one.con(app);
}
}
rpcFunc(serverId: string) {
this.toId = serverId;
return this.rpcObj;
}
rpcFuncAwait(serverId: string, notify = false) {
this.toId = serverId;
this.notify = notify;
return this.rpcObjAwait;
}
initFunc(serverType: string, filename: string, func: any, funcFields: string[]) {
let res: { [method: string]: Function } = {};
for (let field of funcFields) {
if (field !== "constructor" && typeof func[field] === "function") {
res[field] = this.proxyCb({ "serverType": serverType, "file_method": filename + "." + field });
}
}
return res;
}
initFuncAwait(serverType: string, filename: string, func: any, funcFields: string[]) {
let res: { [method: string]: Function } = {};
for (let field of funcFields) {
if (field !== "constructor" && typeof func[field] === "function") {
res[field] = this.proxyCbAwait({ "serverType": serverType, "file_method": filename + "." + field });
}
}
return res;
}
proxyCb(cmd: { "serverType": string, "file_method": string }) {
let self = this;
let func = function (...args: any[]) {
self.send(self.toId, cmd, args);
}
return func;
}
proxyCbAwait(cmd: { "serverType": string, "file_method": string }) {
let self = this;
let func = function (...args: any[]): Promise<any> | undefined {
return self.sendAwait(self.toId, self.notify, cmd, args);
}
return func;
}
send(sid: string, cmd: { "serverType": string, "file_method": string }, args: any[]) {
if (sid === "*") {
this.sendT(cmd, args);
return;
}
let cb: Function = null as any;
if (typeof args[args.length - 1] === "function") {
cb = args.pop();
}
let bufLast: Buffer = null as any;
if (args[args.length - 1] instanceof Buffer) {
bufLast = args.pop();
}
if (sid === app.serverId) {
sendRpcMsgToSelf(cmd, Buffer.from(JSON.stringify(args)), bufLast, cb);
return;
}
let socket = app.rpcPool.getSocket(sid);
if (!socket) {
if (cb) {
process.nextTick(() => {
cb(rpcErr.noServer);
});
}
return;
}
let rpcMsg: I_rpcMsg = {
"cmd": cmd.file_method
};
if (cb) {
let id = getRpcId();
rpcRequest[id] = { "cb": cb, "time": outTime, "await": false };
rpcMsg.id = id;
}
socket.send(getRpcMsg(rpcMsg, Buffer.from(JSON.stringify(args)), bufLast, define.Rpc_Msg.rpcMsg));
}
sendT(cmd: { "serverType": string, "file_method": string }, args: any[]) {
let servers = app.getServersByType(cmd.serverType);
if (servers.length === 0) {
return;
}
let bufLast: Buffer = null as any;
if (args[args.length - 1] instanceof Buffer) {
bufLast = args.pop();
}
let msgBuf = Buffer.from(JSON.stringify(args));
let bufEnd = getRpcMsg({ "cmd": cmd.file_method }, msgBuf, bufLast, define.Rpc_Msg.rpcMsg);
for (let one of servers) {
if (one.id === app.serverId) {
sendRpcMsgToSelf(cmd, msgBuf, bufLast);
} else {
let socket = app.rpcPool.getSocket(one.id);
socket && socket.send(bufEnd);
}
}
}
sendAwait(sid: string, notify: boolean, cmd: { "serverType": string, "file_method": string }, args: any[]): Promise<any> | undefined {
if (sid === "*") {
this.sendTAwait(cmd, args);
return undefined;
}
let bufLast: Buffer = null as any;
if (args[args.length - 1] instanceof Buffer) {
bufLast = args.pop();
}
if (sid === app.serverId) {
return sendRpcMsgToSelfAwait(cmd, Buffer.from(JSON.stringify(args)), bufLast, notify);
}
let socket = app.rpcPool.getSocket(sid);
if (!socket) {
return undefined;
}
let rpcMsg: I_rpcMsg = {
"cmd": cmd.file_method
};
let promise: Promise<any> = undefined as any;
if (!notify) {
let cb: Function = null as any;
promise = new Promise((resolve) => {
cb = resolve;
});
let id = getRpcId();
rpcRequest[id] = { "cb": cb, "time": outTime, "await": true };
rpcMsg.id = id;
}
socket.send(getRpcMsg(rpcMsg, Buffer.from(JSON.stringify(args)), bufLast, define.Rpc_Msg.rpcMsgAwait));
return promise;
}
sendTAwait(cmd: { "serverType": string, "file_method": string }, args: any[]) {
let servers = app.getServersByType(cmd.serverType);
if (servers.length === 0) {
return;
}
let bufLast: Buffer = null as any;
if (args[args.length - 1] instanceof Buffer) {
bufLast = args.pop();
}
let msgBuf = Buffer.from(JSON.stringify(args));
let bufEnd = getRpcMsg({ "cmd": cmd.file_method }, msgBuf, bufLast, define.Rpc_Msg.rpcMsgAwait);
for (let one of servers) {
if (one.id === app.serverId) {
sendRpcMsgToSelfAwait(cmd, msgBuf, bufLast, true);
} else {
let socket = app.rpcPool.getSocket(one.id);
socket && socket.send(bufEnd);
}
}
}
}
/**
* Get rpcId
*/
function getRpcId() {
let id = rpcId++;
if (rpcId > 9999999) {
rpcId = 1;
}
return id;
}
/**
* rpc timeout detection
*/
function checkTimeout() {
let now = Date.now();
for (let id in rpcRequest) {
if (rpcRequest[id].time < now) {
let one = rpcRequest[id];
delete rpcRequest[id];
one.await ? one.cb(undefined) : one.cb(rpcErr.timeout);
}
}
}
/**
* Send rpc message
*
* [4] [1] [1] [...] [...] [...]
* allMsgLen msgType rpcBufLen rpcBuf msgBuf bufLast
*/
function getRpcMsg(rpcMsg: I_rpcMsg, msgBuf: Buffer, bufLast: Buffer, t: define.Rpc_Msg) {
let buffLastLen = 0;
if (bufLast) {
buffLastLen = bufLast.length;
rpcMsg.len = buffLastLen;
}
let rpcBuf = Buffer.from(JSON.stringify(rpcMsg));
let buffEnd = Buffer.allocUnsafe(6 + rpcBuf.length + msgBuf.length + buffLastLen);
buffEnd.writeUInt32BE(buffEnd.length - 4, 0);
buffEnd.writeUInt8(t, 4);
buffEnd.writeUInt8(rpcBuf.length, 5);
rpcBuf.copy(buffEnd, 6);
msgBuf.copy(buffEnd, 6 + rpcBuf.length);
if (bufLast) {
bufLast.copy(buffEnd, buffEnd.length - buffLastLen);
}
return buffEnd;
}
/**
* Send rpc message to this server
*/
function sendRpcMsgToSelf(cmd: { "serverType": string, "file_method": string }, msgBuf: Buffer, bufLast: Buffer, cb?: Function) {
let args = JSON.parse(msgBuf.toString());
if (bufLast) {
args.push(bufLast);
}
if (cb) {
let id = getRpcId();
rpcRequest[id] = { "cb": cb, "time": outTime, "await": false };
args.push(getCallBackFuncSelf(id));
}
process.nextTick(() => {
let route = cmd.file_method.split('.');
let file = msgHandler[route[0]];
file[route[1]].apply(file, args);
});
}
/**
* Send rpc message to this server await
*/
function sendRpcMsgToSelfAwait(cmd: { "serverType": string, "file_method": string }, msgBuf: Buffer, bufLast: Buffer, notify: boolean): Promise<any> | undefined {
let args = JSON.parse(msgBuf.toString());
if (bufLast) {
args.push(bufLast);
}
if (notify) {
process.nextTick(() => {
let route = cmd.file_method.split('.');
let file = msgHandler[route[0]];
file[route[1]].apply(file, args);
});
return undefined;
}
let cb: Function = null as any;
let promise = new Promise((resolve) => {
cb = resolve;
});
let id = getRpcId();
rpcRequest[id] = { "cb": cb, "time": outTime, "await": true };
process.nextTick(() => {
let route = cmd.file_method.split('.');
let file = msgHandler[route[0]];
let res = file[route[1]].apply(file, args);
if (res && typeof res.then === "function") {
res.then((data: any) => {
cbFunc(data);
});
} else {
cbFunc(res);
}
function cbFunc(data: any) {
let timeout = rpcRequest[id];
if (!timeout) {
return;
}
delete rpcRequest[id];
if (data === undefined) {
data = null;
}
if (data instanceof Buffer) {
timeout.cb(data);
} else if (data instanceof Array && data[data.length - 1] instanceof Buffer) {
let tmpRes = [...data];
let buf: Buffer = tmpRes.pop();
tmpRes = JSON.parse(JSON.stringify(tmpRes));
tmpRes.push(buf);
timeout.cb(tmpRes);
} else {
timeout.cb(JSON.parse(JSON.stringify(data)));
}
}
});
return promise;
}
/**
* rpc callback
*/
function getCallBackFunc(sid: string, id: number) {
return function (...args: any[]) {
let bufLast: Buffer = null as any;
if (args[args.length - 1] instanceof Buffer) {
bufLast = args.pop();
}
let socket = app.rpcPool.getSocket(sid);
if (socket) {
socket.send(getRpcMsg({ "id": id }, Buffer.from(JSON.stringify(args)), bufLast, define.Rpc_Msg.rpcMsg));
}
}
}
/**
* rpc server callback
*/
function getCallBackFuncSelf(id: number) {
return function (...args: any[]) {
let buf: Buffer = null as any;
if (args[args.length - 1] instanceof Buffer) {
buf = args.pop();
}
args = JSON.parse(JSON.stringify(args));
if (buf) {
args.push(buf);
}
process.nextTick(() => {
let timeout = rpcRequest[id];
if (timeout) {
delete rpcRequest[id];
timeout.cb.apply(null, args);
}
});
}
} | the_stack |
import { tn } from '../text';
export interface Country {
name: string;
code: string;
}
/**
* Using a lean list of countries instead of an external dependency.
* All the libraries have a lot of extra data which is of no use to us at this point and unnecessarily takes up more space.
*/
export const countries: Country[] = [
{
name : tn.t('Andorra'),
code : 'AD'
},
{
name : tn.t('United Arab Emirates'),
code : 'AE'
},
{
name : tn.t('Afghanistan'),
code : 'AF'
},
{
name : tn.t('Antigua And Barbuda'),
code : 'AG'
},
{
name : tn.t('Anguilla'),
code : 'AI'
},
{
name : tn.t('Albania'),
code : 'AL'
},
{
name : tn.t('Armenia'),
code : 'AM'
},
{
name : tn.t('Angola'),
code : 'AO'
},
{
name : tn.t('Antarctica'),
code : 'AQ'
},
{
name : tn.t('Argentina'),
code : 'AR'
},
{
name : tn.t('American Samoa'),
code : 'AS'
},
{
name : tn.t('Austria'),
code : 'AT'
},
{
name : tn.t('Australia'),
code : 'AU'
},
{
name : tn.t('Aruba'),
code : 'AW'
},
{
name : tn.t('Åland'),
code : 'AX'
},
{
name : tn.t('Azerbaijan'),
code : 'AZ'
},
{
name : tn.t('Bosnia and Herzegovina'),
code : 'BA'
},
{
name : tn.t('Barbados'),
code : 'BB'
},
{
name : tn.t('Bangladesh'),
code : 'BD'
},
{
name : tn.t('Belgium'),
code : 'BE'
},
{
name : tn.t('Burkina Faso'),
code : 'BF'
},
{
name : tn.t('Bulgaria'),
code : 'BG'
},
{
name : tn.t('Bahrain'),
code : 'BH'
},
{
name : tn.t('Burundi'),
code : 'BI'
},
{
name : tn.t('Benin'),
code : 'BJ'
},
{
name : tn.t('Saint Barthélemy'),
code : 'BL'
},
{
name : tn.t('Bermuda'),
code : 'BM'
},
{
name : tn.t('Brunei'),
code : 'BN'
},
{
name : tn.t('Bolivia'),
code : 'BO'
},
{
name : tn.t('Bonaire'),
code : 'BQ'
},
{
name : tn.t('Brazil'),
code : 'BR'
},
{
name : tn.t('Bahamas'),
code : 'BS'
},
{
name : tn.t('Bhutan'),
code : 'BT'
},
{
name : tn.t('Bouvet Island'),
code : 'BV'
},
{
name : tn.t('Botswana'),
code : 'BW'
},
{
name : tn.t('Belarus'),
code : 'BY'
},
{
name : tn.t('Belize'),
code : 'BZ'
},
{
name : tn.t('Canada'),
code : 'CA'
},
{
name : tn.t('Cocos [Keeling] Islands'),
code : 'CC'
},
{
name : tn.t('Democratic Republic Of Congo'),
code : 'CD'
},
{
name : tn.t('Central African Republic'),
code : 'CF'
},
{
name : tn.t('Republic Of the Congo'),
code : 'CG'
},
{
name : tn.t('Switzerland'),
code : 'CH'
},
{
name : tn.t('Ivory Coast'),
code : 'CI'
},
{
name : tn.t('Cook Islands'),
code : 'CK'
},
{
name : tn.t('Chile'),
code : 'CL'
},
{
name : tn.t('Cameroon'),
code : 'CM'
},
{
name : tn.t('China'),
code : 'CN'
},
{
name : tn.t('Colombia'),
code : 'CO'
},
{
name : tn.t('Costa Rica'),
code : 'CR'
},
{
name : tn.t('Cuba'),
code : 'CU'
},
{
name : tn.t('Cape Verde'),
code : 'CV'
},
{
name : tn.t('Curacao'),
code : 'CW'
},
{
name : tn.t('Christmas Island'),
code : 'CX'
},
{
name : tn.t('Cyprus'),
code : 'CY'
},
{
name : tn.t('Czech Republic'),
code : 'CZ'
},
{
name : tn.t('Germany'),
code : 'DE'
},
{
name : tn.t('Djibouti'),
code : 'DJ'
},
{
name : tn.t('Denmark'),
code : 'DK'
},
{
name : tn.t('Dominica'),
code : 'DM'
},
{
name : tn.t('Dominican Republic'),
code : 'DO'
},
{
name : tn.t('Algeria'),
code : 'DZ'
},
{
name : tn.t('Ecuador'),
code : 'EC'
},
{
name : tn.t('Estonia'),
code : 'EE'
},
{
name : tn.t('Egypt'),
code : 'EG'
},
{
name : tn.t('Western Sahara'),
code : 'EH'
},
{
name : tn.t('Eritrea'),
code : 'ER'
},
{
name : tn.t('Spain'),
code : 'ES'
},
{
name : tn.t('Ethiopia'),
code : 'ET'
},
{
name : tn.t('Finland'),
code : 'FI'
},
{
name : tn.t('Fiji'),
code : 'FJ'
},
{
name : tn.t('Falkland Islands'),
code : 'FK'
},
{
name : tn.t('Micronesia'),
code : 'FM'
},
{
name : tn.t('Faroe Islands'),
code : 'FO'
},
{
name : tn.t('France'),
code : 'FR'
},
{
name : tn.t('Gabon'),
code : 'GA'
},
{
name : tn.t('United Kingdom'),
code : 'GB'
},
{
name : tn.t('Grenada'),
code : 'GD'
},
{
name : tn.t('Georgia'),
code : 'GE'
},
{
name : tn.t('French Guiana'),
code : 'GF'
},
{
name : tn.t('Guernsey'),
code : 'GG'
},
{
name : tn.t('Ghana'),
code : 'GH'
},
{
name : tn.t('Gibraltar'),
code : 'GI'
},
{
name : tn.t('Greenland'),
code : 'GL'
},
{
name : tn.t('Gambia'),
code : 'GM'
},
{
name : tn.t('Guinea'),
code : 'GN'
},
{
name : tn.t('Guadeloupe'),
code : 'GP'
},
{
name : tn.t('Equatorial Guinea'),
code : 'GQ'
},
{
name : tn.t('Greece'),
code : 'GR'
},
{
name : tn.t('South Georgia and The South Sandwich Islands'),
code : 'GS'
},
{
name : tn.t('Guatemala'),
code : 'GT'
},
{
name : tn.t('Guam'),
code : 'GU'
},
{
name : tn.t('Guinea-Bissau'),
code : 'GW'
},
{
name : tn.t('Guyana'),
code : 'GY'
},
{
name : tn.t('Hong Kong'),
code : 'HK'
},
{
name : tn.t('Heard Island And McDonald Islands'),
code : 'HM'
},
{
name : tn.t('Honduras'),
code : 'HN'
},
{
name : tn.t('Croatia'),
code : 'HR'
},
{
name : tn.t('Haiti'),
code : 'HT'
},
{
name : tn.t('Hungary'),
code : 'HU'
},
{
name : tn.t('Indonesia'),
code : 'ID'
},
{
name : tn.t('Ireland'),
code : 'IE'
},
{
name : tn.t('Israel'),
code : 'IL'
},
{
name : tn.t('Isle of Man'),
code : 'IM'
},
{
name : tn.t('India'),
code : 'IN'
},
{
name : tn.t('British Indian Ocean Territory'),
code : 'IO'
},
{
name : tn.t('Iraq'),
code : 'IQ'
},
{
name : tn.t('Iran'),
code : 'IR'
},
{
name : tn.t('Iceland'),
code : 'IS'
},
{
name : tn.t('Italy'),
code : 'IT'
},
{
name : tn.t('Jersey'),
code : 'JE'
},
{
name : tn.t('Jamaica'),
code : 'JM'
},
{
name : tn.t('Jordan'),
code : 'JO'
},
{
name : tn.t('Japan'),
code : 'JP'
},
{
name : tn.t('Kenya'),
code : 'KE'
},
{
name : tn.t('Kyrgyzstan'),
code : 'KG'
},
{
name : tn.t('Cambodia'),
code : 'KH'
},
{
name : tn.t('Kiribati'),
code : 'KI'
},
{
name : tn.t('Comoros'),
code : 'KM'
},
{
name : tn.t('Saint Kitts And Nevis'),
code : 'KN'
},
{
name : tn.t('North Korea'),
code : 'KP'
},
{
name : tn.t('South Korea'),
code : 'KR'
},
{
name : tn.t('Kuwait'),
code : 'KW'
},
{
name : tn.t('Cayman Islands'),
code : 'KY'
},
{
name : tn.t('Kazakhstan'),
code : 'KZ'
},
{
name : tn.t('Laos'),
code : 'LA'
},
{
name : tn.t('Lebanon'),
code : 'LB'
},
{
name : tn.t('Saint Lucia'),
code : 'LC'
},
{
name : tn.t('Liechtenstein'),
code : 'LI'
},
{
name : tn.t('Sri Lanka'),
code : 'LK'
},
{
name : tn.t('Liberia'),
code : 'LR'
},
{
name : tn.t('Lesotho'),
code : 'LS'
},
{
name : tn.t('Lithuania'),
code : 'LT'
},
{
name : tn.t('Luxembourg'),
code : 'LU'
},
{
name : tn.t('Latvia'),
code : 'LV'
},
{
name : tn.t('Libya'),
code : 'LY'
},
{
name : tn.t('Morocco'),
code : 'MA'
},
{
name : tn.t('Monaco'),
code : 'MC'
},
{
name : tn.t('Moldova'),
code : 'MD'
},
{
name : tn.t('Montenegro'),
code : 'ME'
},
{
name : tn.t('Saint Martin'),
code : 'MF'
},
{
name : tn.t('Madagascar'),
code : 'MG'
},
{
name : tn.t('Marshall Islands'),
code : 'MH'
},
{
name : tn.t('North Macedonia'),
code : 'MK'
},
{
name : tn.t('Mali'),
code : 'ML'
},
{
name : tn.t('Myanmar'),
code : 'MM'
},
{
name : tn.t('Mongolia'),
code : 'MN'
},
{
name : tn.t('Macao'),
code : 'MO'
},
{
name : tn.t('Northern Mariana Islands'),
code : 'MP'
},
{
name : tn.t('Martinique'),
code : 'MQ'
},
{
name : tn.t('Mauritania'),
code : 'MR'
},
{
name : tn.t('Montserrat'),
code : 'MS'
},
{
name : tn.t('Malta'),
code : 'MT'
},
{
name : tn.t('Mauritius'),
code : 'MU'
},
{
name : tn.t('Maldives'),
code : 'MV'
},
{
name : tn.t('Malawi'),
code : 'MW'
},
{
name : tn.t('Mexico'),
code : 'MX'
},
{
name : tn.t('Malaysia'),
code : 'MY'
},
{
name : tn.t('Mozambique'),
code : 'MZ'
},
{
name : tn.t('Namibia'),
code : 'NA'
},
{
name : tn.t('New Caledonia'),
code : 'NC'
},
{
name : tn.t('Niger'),
code : 'NE'
},
{
name : tn.t('Norfolk Island'),
code : 'NF'
},
{
name : tn.t('Nigeria'),
code : 'NG'
},
{
name : tn.t('Nicaragua'),
code : 'NI'
},
{
name : tn.t('Netherlands'),
code : 'NL'
},
{
name : tn.t('Norway'),
code : 'NO'
},
{
name : tn.t('Nepal'),
code : 'NP'
},
{
name : tn.t('Nauru'),
code : 'NR'
},
{
name : tn.t('Niue'),
code : 'NU'
},
{
name : tn.t('New Zealand'),
code : 'NZ'
},
{
name : tn.t('Oman'),
code : 'OM'
},
{
name : tn.t('Panama'),
code : 'PA'
},
{
name : tn.t('Peru'),
code : 'PE'
},
{
name : tn.t('French Polynesia'),
code : 'PF'
},
{
name : tn.t('Papua New Guinea'),
code : 'PG'
},
{
name : tn.t('Philippines'),
code : 'PH'
},
{
name : tn.t('Pakistan'),
code : 'PK'
},
{
name : tn.t('Poland'),
code : 'PL'
},
{
name : tn.t('Saint Pierre And Miquelon'),
code : 'PM'
},
{
name : tn.t('Pitcairn Islands'),
code : 'PN'
},
{
name : tn.t('Puerto Rico'),
code : 'PR'
},
{
name : tn.t('Palestinian'),
code : 'PS'
},
{
name : tn.t('Portugal'),
code : 'PT'
},
{
name : tn.t('Palau'),
code : 'PW'
},
{
name : tn.t('Paraguay'),
code : 'PY'
},
{
name : tn.t('Qatar'),
code : 'QA'
},
{
name : tn.t('Reunion'),
code : 'RE'
},
{
name : tn.t('Romania'),
code : 'RO'
},
{
name : tn.t('Serbia'),
code : 'RS'
},
{
name : tn.t('Russian'),
code : 'RU'
},
{
name : tn.t('Rwanda'),
code : 'RW'
},
{
name : tn.t('Saudi Arabia'),
code : 'SA'
},
{
name : tn.t('Solomon Islands'),
code : 'SB'
},
{
name : tn.t('Seychelles'),
code : 'SC'
},
{
name : tn.t('Sudan'),
code : 'SD'
},
{
name : tn.t('Sweden'),
code : 'SE'
},
{
name : tn.t('Singapore'),
code : 'SG'
},
{
name : tn.t('Saint Helena'),
code : 'SH'
},
{
name : tn.t('Slovenia'),
code : 'SI'
},
{
name : tn.t('Svalbard And Jan Mayen'),
code : 'SJ'
},
{
name : tn.t('Slovakia'),
code : 'SK'
},
{
name : tn.t('Sierra Leone'),
code : 'SL'
},
{
name : tn.t('San Marino'),
code : 'SM'
},
{
name : tn.t('Senegal'),
code : 'SN'
},
{
name : tn.t('Somalia'),
code : 'SO'
},
{
name : tn.t('Suriname'),
code : 'SR'
},
{
name : tn.t('South Sudan'),
code : 'SS'
},
{
name : tn.t('Sao Tome and Principe'),
code : 'ST'
},
{
name : tn.t('El Salvador'),
code : 'SV'
},
{
name : tn.t('Sint Maarten'),
code : 'SX'
},
{
name : tn.t('Syria'),
code : 'SY'
},
{
name : tn.t('Swaziland'),
code : 'SZ'
},
{
name : tn.t('Turks And Caicos Islands'),
code : 'TC'
},
{
name : tn.t('Chad'),
code : 'TD'
},
{
name : tn.t('French Southern Territories'),
code : 'TF'
},
{
name : tn.t('Togo'),
code : 'TG'
},
{
name : tn.t('Thailand'),
code : 'TH'
},
{
name : tn.t('Tajikistan'),
code : 'TJ'
},
{
name : tn.t('Tokelau'),
code : 'TK'
},
{
name : tn.t('East Timor'),
code : 'TL'
},
{
name : tn.t('Turkmenistan'),
code : 'TM'
},
{
name : tn.t('Tunisia'),
code : 'TN'
},
{
name : tn.t('Tonga'),
code : 'TO'
},
{
name : tn.t('Turkey'),
code : 'TR'
},
{
name : tn.t('Trinidad And Tobago'),
code : 'TT'
},
{
name : tn.t('Tuvalu'),
code : 'TV'
},
{
name : tn.t('Taiwan'),
code : 'TW'
},
{
name : tn.t('Tanzania'),
code : 'TZ'
},
{
name : tn.t('Ukraine'),
code : 'UA'
},
{
name : tn.t('Uganda'),
code : 'UG'
},
{
name : tn.t('United States Minor Outlying Islands'),
code : 'UM'
},
{
name : tn.t('United States'),
code : 'US'
},
{
name : tn.t('Uruguay'),
code : 'UY'
},
{
name : tn.t('Uzbekistan'),
code : 'UZ'
},
{
name : tn.t('Vatican City'),
code : 'VA'
},
{
name : tn.t('Saint Vincent And The Grenadines'),
code : 'VC'
},
{
name : tn.t('Venezuela'),
code : 'VE'
},
{
name : tn.t('British Virgin Islands'),
code : 'VG'
},
{
name : tn.t('U.S. Virgin Islands'),
code : 'VI'
},
{
name : tn.t('Vietnam'),
code : 'VN'
},
{
name : tn.t('Vanuatu'),
code : 'VU'
},
{
name : tn.t('Wallis And Futuna'),
code : 'WF'
},
{
name : tn.t('Samoa'),
code : 'WS'
},
{
name : tn.t('Kosovo'),
code : 'XK'
},
{
name : tn.t('Yemen'),
code : 'YE'
},
{
name : tn.t('Mayotte'),
code : 'YT'
},
{
name : tn.t('South Africa'),
code : 'ZA'
},
{
name : tn.t('Zambia'),
code : 'ZM'
},
{
name : tn.t('Zimbabwe'),
code : 'ZW'
}
]; | the_stack |
import * as React from 'react';
//import styles from '../../webparts/siteDesigns/components/SiteDesigns.module.scss';
import { ISiteDesignRightsProps } from './ISiteRightsProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { ListView, IViewField, SelectionMode, GroupOrder, IGrouping } from "@pnp/spfx-controls-react/lib/ListView";
import { IListViewItems } from './IListViewItems';
import spservice from '../../services/spservices';
import {
Icon,
IconType,
CommandBar,
Panel,
PanelType,
MessageBar,
MessageBarType,
Label,
Spinner,
SpinnerSize,
Dialog,
DialogType,
DialogFooter,
PrimaryButton,
DefaultButton,
ImageFit,
} from 'office-ui-fabric-react';
import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle";
import * as strings from 'SiteDesignsWebPartStrings';
import { ISiteDesignRightsState } from './ISiteDesignRightsState';
import { SiteDesignInfo, SiteScriptInfo, SiteScriptUpdateInfo, SiteDesignUpdateInfo, SiteDesignPrincipals } from '@pnp/sp';
import { panelMode } from '../../webparts/siteDesigns/components/IEnumPanel';
import styles from './SiteDesignRights.module.scss';
import { PeoplePicker, PrincipalType } from "@pnp/spfx-controls-react/lib/PeoplePicker";
// "https://outlook.office365.com/owa/service.svc/s/Ge…?email=anamendes@sitenanuvem.pt&UA=0&size=HR96x96"
// ListView Columns
const viewFields: IViewField[] = [
{
name: 'Icon',
render: ((item: IListViewItems) => {
// const image = <Icon iconName="UserFollowed" />;
const email = item.PrincipalName.replace('i:0#.f|membership|', "");
const image = <Icon iconType={IconType.image} imageProps={{ imageFit: ImageFit.cover, src: `/_layouts/15/userphoto.aspx?size=s&accountname=${email}`, className: styles.image }} />;
return image;
}),
maxWidth: 70,
},
{
name: 'DisplayName',
displayName: strings.ListViewColumnIdPrincipalNameLabel,
sorting: true,
isResizable: true,
maxWidth: 300,
minWidth: 300
}
];
export default class SiteDesignRights extends React.Component<ISiteDesignRightsProps, ISiteDesignRightsState> {
private spService: spservice;
private items: IListViewItems[] = [];
private refreshParent: boolean = false;
private siteDesignPrincipals: SiteDesignPrincipals[];
private AddPrincipal = React.lazy(() => import('../AddPrincipal/AddPrincipal' /* webpackChunkName: "addprincipal" */));
public constructor(props) {
super(props);
// Initialize state
this.state = ({
items: [],
isLoading: false,
disableCommandOption: true,
showPanel: false,
selectItem: [],
panelMode: panelMode.New,
hasError: false,
errorMessage: '',
showPanelAddScript: false,
showDialogDelete: false,
deleting: false,
disableDeleteButton: false,
showError: false
});
// Init class services
this.spService = new spservice(this.props.context);
// Register event handlers
this.getSelection = this.getSelection.bind(this);
this.onNewItem = this.onNewItem.bind(this);
this.onDeleteItem = this.onDeleteItem.bind(this);
this.onDismissPanel = this.onDismissPanel.bind(this);
this.onRefresh = this.onRefresh.bind(this);
this.onCancel = this.onCancel.bind(this);
this.onDismissAddPrincipalPane = this.onDismissAddPrincipalPane.bind(this);
this.onCloseDialog = this.onCloseDialog.bind(this);
this.onDeleteConfirm = this.onDeleteConfirm.bind(this);
}
/**
*
* @private
* @param {boolean} refresh
* @memberof SiteDesignRights
*/
private onDismissAddPrincipalPane(refresh: boolean) {
this.setState({ showPanel: false });
if (refresh) {
this.refreshParent = true;
this.loadPrincipals();
}
}
// Get Selection Item from List
/**
*
* @private
* @param {IListViewItems[]} items
* @memberof SiteDesignRights
*/
private getSelection(items: IListViewItems[]) {
if (items.length > 0) {
this.setState({
disableCommandOption: false,
selectItem: items
});
} else {
this.setState({
disableCommandOption: true,
selectItem: [],
showPanel: false,
});
}
}
/**
* cancel event option SiteScrips
*
* @private
* @param {React.MouseEvent<HTMLButtonElement>} ev
* @memberof SiteDesignRights
*/
private onCancel(ev: React.MouseEvent<HTMLButtonElement>) {
this.props.onDismiss(this.refreshParent);
}
private onCloseDialog(ev: React.MouseEvent<HTMLButtonElement>) {
ev.preventDefault();
this.setState({
showDialogDelete: false
});
}
/**
*
* @private
* @param {React.MouseEvent<HTMLButtonElement>} ev
* @memberof SiteDesignRights
*/
private async onDeleteConfirm(ev: React.MouseEvent<HTMLButtonElement>) {
ev.preventDefault();
try {
let updateSiteDesignPrincipals: IListViewItems[] = this.items;
for (const item of this.state.selectItem) {
const idx = updateSiteDesignPrincipals.indexOf(item);
if (idx !== -1) {
updateSiteDesignPrincipals.splice(idx, 1);
}
}
this.setState({ deleting: true, disableDeleteButton: true });
const principals: string[] = [];
for (const item of this.state.selectItem) {
principals.push(item.PrincipalName.replace('i:0#.f|membership|', ""));
}
await this.spService.revokeSiteDesignRights(this.props.SiteDesignSelectedItem.Id, principals);
this.refreshParent = true;
this.setState({ deleting: false, disableDeleteButton: false, showDialogDelete: false, showError: false });
this.loadPrincipals();
} catch (error) {
console.log(error.message);
this.setState({ deleting: false, disableDeleteButton: true, showError: true, errorMessage: error.message });
}
}
/**
* Panel Dismiss CallBack
*
* @param {boolean} [refresh]
* @returns
* @memberof SiteDesignRights
*/
public async onDismissPanel(refresh?: boolean) {
this.setState({
showPanel: false
});
if (refresh) {
await this.loadPrincipals();
}
return;
}
// On New Item
/**
*
*
* @private
* @param {React.MouseEvent<HTMLElement>} e
* @memberof SiteDesignRights
*/
private onNewItem(e: React.MouseEvent<HTMLElement>) {
e.preventDefault();
this.setState({
panelMode: panelMode.New,
showPanel: true,
});
}
/**
* On Delete
*
* @private
* @param {React.MouseEvent<HTMLElement>} e
* @memberof SiteDesignRights
*/
private onDeleteItem(e: React.MouseEvent<HTMLElement>) {
e.preventDefault();
this.setState({
panelMode: panelMode.Delete,
showDialogDelete: true,
});
}
/**
* Load SiteDesignRights
*
* @private
* @memberof SiteDesignRights
*/
private async loadPrincipals() {
this.items = [];
this.setState({ isLoading: true });
try {
// check if user is Teanant Global Admin
const isGlobalAdmin = await this.spService.checkUserIsGlobalAdmin();
if (isGlobalAdmin) {
// get SiteDesignRights for SiteDesign
this.siteDesignPrincipals = await this.spService.getSiteDesignRights(this.props.SiteDesignSelectedItem.Id);
if (this.siteDesignPrincipals.length > 0) {
for (const siteDesignPrincipal of this.siteDesignPrincipals) {
this.items.push(
{
key: siteDesignPrincipal.PrincipalName,
DisplayName: siteDesignPrincipal.DisplayName,
PrincipalName: siteDesignPrincipal.PrincipalName
}
);
}
}
this.setState({ items: this.items, isLoading: false, disableCommandOption: true });
} else {
this.setState({
items: this.items,
hasError: true,
errorMessage: strings.ErrorMessageUserNotAdmin,
isLoading: false
});
}
}
catch (error) {
this.setState({
items: this.items,
hasError: true,
errorMessage: error.message,
isLoading: false
});
}
}
/** Refresh
*
* @param {React.MouseEvent<HTMLElement>} ev
* @memberof SiteDesignRights
*/
public onRefresh(ev: React.MouseEvent<HTMLElement>) {
ev.preventDefault();
// loadPrincipals
this.loadPrincipals();
}
/**
* Component Did Mount
*
* @memberof SiteDesignRights
*/
public async componentDidMount() {
// loadPrincipals
await this.loadPrincipals();
}
// On Render
public render(): React.ReactElement<ISiteDesignRightsProps> {
return (
<div>
<Panel isOpen={this.props.showPanel} onDismiss={this.onCancel} type={PanelType.medium} headerText={strings.SiteDesignRightsPanelTitle}>
<div>
<span className={styles.label}>{strings.SiteDesignIdLabel}</span>
<span className={styles.title}>{this.props.SiteDesignSelectedItem.Id}</span>
</div>
<div>
<span className={styles.label}>{strings.SiteDesignRightsPanelTitle}</span>
<span className={styles.title}>{this.props.SiteDesignSelectedItem.Title}</span>
</div>
<div>
<span className={styles.label}>{strings.WebTemplateLabel}</span>
<span className={styles.title}>{this.props.SiteDesignSelectedItem.WebTemplate === '64' ? strings.WebTemplateTeamSite : strings.WebTemplateCommunicationSite}</span>
</div>
<br />
{
this.state.isLoading ?
<Spinner size={SpinnerSize.large} label={strings.LoadingLabel} ariaLive="assertive" />
:
this.state.hasError ?
<MessageBar
messageBarType={MessageBarType.error}>
<span>{this.state.errorMessage}</span>
</MessageBar>
:
<div style={{ marginBottom: 10 }}>
<CommandBar
items={[
{
key: 'newItem',
name: strings.CommandbarNewLabel,
iconProps: {
iconName: 'Add'
},
onClick: this.onNewItem,
},
{
key: 'delete',
name: strings.CommandbarDeleteLabel,
iconProps: {
iconName: 'Delete'
},
onClick: this.onDeleteItem,
disabled: this.state.disableCommandOption,
}
]}
farItems={[
{
key: 'refresh',
name: strings.CommandbarRefreshLabel,
iconProps: {
iconName: 'Refresh'
},
onClick: this.onRefresh,
}
]}
/>
</div>
}
{
!this.state.hasError && !this.state.isLoading &&
<ListView
items={this.state.items}
viewFields={viewFields}
compact={false}
selectionMode={SelectionMode.multiple}
selection={this.getSelection}
showFilter={true}
filterPlaceHolder={strings.SearchPlaceholder}
/>
}
{
this.state.showPanel && this.state.panelMode == panelMode.New &&
<React.Suspense fallback={<div>Loading...</div>}>
<this.AddPrincipal
showPanel={this.state.showPanel}
onDismiss={this.onDismissAddPrincipalPane}
context={this.props.context}
siteDesignInfo={this.props.SiteDesignSelectedItem}
/>
</React.Suspense>
}
<Dialog
hidden={!this.state.showDialogDelete}
onDismiss={this.onCloseDialog}
dialogContentProps={{
type: DialogType.normal,
title: strings.DialogConfirmDeleteTitle,
}}
modalProps={{
isBlocking: true,
}}
>
<p>{strings.DialogConfirmDeleteText}</p>
<br />
{
this.state.showError &&
<div style={{ marginTop: '15px' }}>
<MessageBar messageBarType={MessageBarType.error} >
<span>{this.state.errorMessage}</span>
</MessageBar>
</div>
}
<br />
<DialogFooter>
{
this.state.deleting &&
<div style={{ display: "inline-block", marginRight: '10px', verticalAlign: 'middle' }}>
<Spinner size={SpinnerSize.small} ariaLive="assertive" />
</div>
}
<DefaultButton onClick={this.onDeleteConfirm} text={strings.ButtonDeleteLabel} disabled={this.state.disableDeleteButton} />
<PrimaryButton onClick={this.onCloseDialog} text={strings.ButtonCancelLabel} />
</DialogFooter>
</Dialog>
</Panel>
</div >
);
}
} | the_stack |
jest.mock('inquirer');
import { tortillaBeforeAll, tortillaBeforeEach } from './tests-helper';
import './custom-matchers';
import { Paths } from '../src/paths';
import * as Tmp from 'tmp';
import * as Path from 'path';
import { Release } from '../src/release';
let context: any = {};
// process.env.DEBUG = '1';
process.env.TORTILLA_CACHE_DISABLED = '1';
describe('Release', () => {
beforeAll(tortillaBeforeAll.bind(context));
beforeEach(tortillaBeforeEach.bind(context));
describe('with submodules', () => {
beforeEach(() => {
context.fooModuleDir = Tmp.dirSync({ unsafeCleanup: true }).name;
context.createTortillaProject(context.fooModuleDir);
});
it('one tortilla project as submodule with one version: should point to the correct commit', async () => {
context.setPromptAnswers([
'master@0.1.0'
]);
// Create a sub-project of Tortilla, add an empty commit and release a new version
context.scopeEnv(() => {
context.tortilla(['step', 'push', '-m', 'Create submodule', '--allow-empty']);
context.tortilla(['release', 'bump', 'minor', '-m', 'submodule version test']);
}, { TORTILLA_CWD: context.fooModuleDir });
// Add the sub project as submodule
context.tortilla(['submodule', 'add', Path.basename(context.fooModuleDir), context.fooModuleDir]);
// Release a new version of the root
const out = context.tortilla(['release', 'bump', 'minor', '-m', 'submodule root']);
expect(out).toContain('Checking out "master@0.1.0" in Tortilla submodule ');
expect(out).toContain('Release: 0.1.0');
});
it('two tortilla project as submodule with one version: should point to the correct commit', async () => {
const barModuleDir = Tmp.dirSync({ unsafeCleanup: true }).name;
context.createTortillaProject(barModuleDir);
context.setPromptAnswers([
'master@0.1.0',
'master@1.0.0',
]);
// Create a sub-project of Tortilla, add an empty commit and release a new version
context.scopeEnv(() => {
context.tortilla(['step', 'push', '-m', 'Create submodule', '--allow-empty']);
context.tortilla(['release', 'bump', 'minor', '-m', 'submodule version test']);
}, { TORTILLA_CWD: context.fooModuleDir });
// Create a sub-project of Tortilla, add an empty commit and release a new version
context.scopeEnv(() => {
context.tortilla(['step', 'push', '-m', 'Create submodule', '--allow-empty']);
context.tortilla(['release', 'bump', 'major', '-m', 'submodule version test']);
}, { TORTILLA_CWD: barModuleDir });
// Add the sub project as submodule
context.tortilla(['submodule', 'add', Path.basename(context.fooModuleDir), context.fooModuleDir]);
context.tortilla(['submodule', 'add', Path.basename(barModuleDir), barModuleDir]);
// Release a new version of the root
const out = context.tortilla(['release', 'bump', 'minor', '-m', 'submodule root']);
expect(out).toContain('Checking out "master@0.1.0" in Tortilla submodule ');
expect(out).toContain('Checking out "master@1.0.0" in Tortilla submodule ');
expect(out).toContain('Release: 0.1.0');
});
});
describe('bump()', () => {
it('should bump a major version', () => {
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
let tagExists;
tagExists = context.git.bind(context, ['rev-parse', 'master@root@1.0.0']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@1.0.0']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
});
it('should bump a minor version', () => {
context.tortilla(['release', 'bump', 'minor', '-m', 'minor version test']);
let tagExists;
tagExists = context.git.bind(context, ['rev-parse', 'master@root@0.1.0']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@0.1.0']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
});
it('should bump a patch version', () => {
context.tortilla(['release', 'bump', 'patch', '-m', 'patch version test']);
let tagExists;
tagExists = context.git.bind(context, ['rev-parse', 'master@root@0.0.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@0.0.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
});
it('should bump to next version', () => {
context.tortilla(['release', 'bump', 'next', '-m', 'next version test']);
let tagExists;
tagExists = context.git.bind(context, ['rev-parse', 'master@root@next']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@next']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
});
it('should override next version', () => {
context.tortilla(['release', 'bump', 'next', '-m', 'next version test']);
context.tortilla(['release', 'bump', 'patch', '-m', 'patch version test']);
let tagExists;
tagExists = context.git.bind(context, ['rev-parse', 'master@root@next']);
expect(tagExists).toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@next']);
expect(tagExists).toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@root@0.0.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@0.0.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
})
it('should bump a major, minor and patch versions', () => {
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
context.tortilla(['release', 'bump', 'minor', '-m', 'minor version test']);
context.tortilla(['release', 'bump', 'patch', '-m', 'patch version test']);
let tagExists;
tagExists = context.git.bind(context, ['rev-parse', 'master@root@1.0.0']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@1.0.0']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@root@1.1.0']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@1.1.0']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@root@1.1.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@1.1.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
});
it('should bump a version for all step tags', () => {
context.tortilla(['step', 'tag', '-m', 'dummy']);
context.tortilla(['step', 'tag', '-m', 'dummy']);
context.tortilla(['step', 'tag', '-m', 'dummy']);
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
context.tortilla(['release', 'bump', 'minor', '-m', 'minor version test']);
context.tortilla(['release', 'bump', 'patch', '-m', 'patch version test']);
let tagExists;
tagExists = context.git.bind(context, ['rev-parse', 'master@root@1.1.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@step1@1.1.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@step2@1.1.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@step3@1.1.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@1.1.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
});
it('should change the prefix of the release based on the active branch', () => {
context.git(['checkout', '-b', 'test']);
context.tortilla(['step', 'tag', '-m', 'dummy']);
context.tortilla(['step', 'tag', '-m', 'dummy']);
context.tortilla(['step', 'tag', '-m', 'dummy']);
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
context.tortilla(['release', 'bump', 'minor', '-m', 'minor version test']);
context.tortilla(['release', 'bump', 'patch', '-m', 'patch version test']);
let tagExists;
tagExists = context.git.bind(context, ['rev-parse', 'test@root@1.1.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'test@step1@1.1.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'test@step2@1.1.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'test@step3@1.1.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'test@1.1.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
});
it('should be able to handle multiple bumps for the same version type', () => {
context.tortilla(['release', 'bump', 'patch', '-m', 'patch version test']);
context.tortilla(['release', 'bump', 'minor', '-m', 'minor version test']);
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
context.tortilla(['release', 'bump', 'patch', '-m', 'patch version test']);
let tagExists;
tagExists = context.git.bind(context, ['rev-parse', 'master@root@0.0.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@0.0.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@root@0.1.0']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@0.1.0']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@root@1.0.0']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@1.0.0']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@root@2.0.0']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@2.0.0']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@root@2.0.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
tagExists = context.git.bind(context, ['rev-parse', 'master@2.0.1']);
expect(tagExists).not.toThrowError(/(.|\n)*/);
});
it('should create a diff branch whose commits represent the releases', () => {
context.exec('sh', ['-c', 'echo 1.0.0 > VERSION']);
context.git(['add', 'VERSION']);
context.tortilla(['step', 'push', '-m', 'Create version file']);
context.tortilla(['step', 'tag', '-m', 'First step']);
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
context.tortilla(['step', 'edit', '1.1']);
context.exec('sh', ['-c', 'echo 1.1.0 > VERSION']);
context.git(['add', 'VERSION']);
context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } });
context.git(['rebase', '--continue']);
context.tortilla(['release', 'bump', 'minor', '-m', 'minor version test']);
context.tortilla(['step', 'edit', '1.1']);
context.exec('sh', ['-c', 'echo 1.1.1 > VERSION']);
context.git(['add', 'VERSION']);
context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } });
context.git(['rebase', '--continue']);
context.tortilla(['release', 'bump', 'patch', '-m', 'patch version test']);
context.git(['checkout', 'master-history']);
let commitMessage;
commitMessage = context.git(['log', '-1', '--format=%s']);
expect(commitMessage).toEqual('master@1.1.1: patch version test');
commitMessage = context.git(['log', '-1', '--skip=1', '--format=%s']);
expect(commitMessage).toEqual('master@1.1.0: minor version test');
commitMessage = context.git(['log', '-1', '--skip=2', '--format=%s']);
expect(commitMessage).toEqual('master@1.0.0: major version test');
const releaseDiff = context.git(['diff', 'HEAD', 'HEAD~2'], {
env: {
TORTILLA_STDIO: 'inherit',
GIT_PAGER: 'cat'
}
});
expect(releaseDiff).toContainSameContentAsFile('release-update.diff');
});
it.skip('should remove files which should not be included in the release', () => {
context.exec('touch', ['.travis.yml']);
context.exec('touch', ['renovate.json']);
context.git(['add', '.travis.yml']);
context.git(['add', 'renovate.json']);
context.tortilla(['step', 'push', '-m', 'Add CI configurations']);
context.tortilla(['step', 'tag', '-m', 'First step']);
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
const travisPath = Paths.travis;
const renovatePath = Paths.renovate;
expect(context.exists(travisPath)).toBeTruthy();
expect(context.exists(renovatePath)).toBeTruthy();
context.git(['checkout', 'master@1.0.0']);
expect(context.exists(travisPath)).toBeFalsy();
expect(context.exists(renovatePath)).toBeFalsy();
context.git(['checkout', 'master-history']);
expect(context.exists(travisPath)).toBeFalsy();
expect(context.exists(renovatePath)).toBeFalsy();
});
it('should re-render all manuals using an updated release tag', () => {
context.tortilla(['step', 'edit', '--root']);
const pack = JSON.parse(context.exec('cat', ['package.json']));
pack.repository = {
type: 'git',
url: 'https://github.com/test/repo.git'
};
const packString = JSON.stringify(pack, null, 2).replace(/"/g, '\\"');
context.exec('sh', ['-c', `echo "${packString}" > package.json`]);
context.exec('sh', ['-c', `echo "{{{resolvePath}}}" > .tortilla/manuals/templates/root.tmpl`]);
context.git(['add', '.']);
context.git(['commit', '--amend'], {
env: {
GIT_EDITOR: true
}
});
context.git(['rebase', '--continue']);
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
const manual = context.exec('cat', ['README.md']);
expect(manual).toContainSameContentAsFile('release-path.md');
});
});
describe('revert()', () => {
it('should revert most recent release', () => {
context.tortilla(['release', 'bump', 'major', '-m', 'first release']);
context.tortilla(['release', 'bump', 'major', '-m', 'second release']);
expect(context.tortilla(['release', 'current'])).toContain('2.0.0')
context.tortilla(['release', 'revert']);
expect(context.tortilla(['release', 'current'])).toContain('1.0.0')
});
});
describe('list()', () => {
it('should print all versions of current branch', () => {
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
context.tortilla(['release', 'bump', 'next', '-m', 'next version test']);
context.tortilla(['release', 'bump', 'minor', '-m', 'minor version test']);
context.tortilla(['release', 'bump', 'patch', '-m', 'patch version test']);
const releasesList = context.tortilla(['release', 'list']);
expect(releasesList).toEqual([
'master@1.1.1 -> current release',
'master@1.1.0',
'master@1.0.0'
].join('\n'));
});
it('should print all versions of given branch', () => {
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
context.tortilla(['release', 'bump', 'next', '-m', 'next version test']);
context.tortilla(['release', 'bump', 'minor', '-m', 'minor version test']);
context.tortilla(['release', 'bump', 'patch', '-m', 'patch version test']);
context.git(['checkout', '-b', 'test-branch']);
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
const releasesList = context.tortilla(['release', 'list']);
expect(releasesList).toEqual([
'test-branch@1.0.0 -> current release'
].join('\n'));
});
});
describe('current()', () => {
it('should get the current version', () => {
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
context.tortilla(['release', 'bump', 'next', '-m', 'next version test']);
context.tortilla(['release', 'bump', 'minor', '-m', 'minor version test']);
context.tortilla(['release', 'bump', 'patch', '-m', 'patch version test']);
const currentVersion = context.tortilla(['release', 'current']);
expect(currentVersion).toEqual(['🌟 Release: 1.1.1', '🌟 Branch: master'].join('\n'));
});
});
describe('diff()', () => {
it('should run "git diff" between provided releases', () => {
context.exec('sh', ['-c', 'echo 1.0.0 > VERSION']);
context.git(['add', 'VERSION']);
context.tortilla(['step', 'push', '-m', 'Create version file']);
context.tortilla(['step', 'tag', '-m', 'First step']);
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
context.tortilla(['step', 'edit', '1.1']);
context.exec('sh', ['-c', 'echo 1.1.0 > VERSION']);
context.git(['add', 'VERSION']);
context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } });
context.git(['rebase', '--continue']);
context.tortilla(['release', 'bump', 'minor', '-m', 'minor version test']);
context.tortilla(['step', 'edit', '1.1']);
context.exec('sh', ['-c', 'echo 1.1.1 > VERSION']);
context.git(['add', 'VERSION']);
context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } });
context.git(['rebase', '--continue']);
context.tortilla(['release', 'bump', 'patch', '-m', 'patch version test']);
const releaseDiff = context.tortilla(['release', 'diff', '1.1.1', '1.0.0'], {
env: {
TORTILLA_STDIO: 'inherit',
GIT_PAGER: 'cat'
}
});
expect(releaseDiff).toContainSameContentAsFile('release-update.diff');
});
it('should concat the provided arguments vector', () => {
context.exec('sh', ['-c', 'echo 1.0.0 > VERSION']);
context.git(['add', 'VERSION']);
context.tortilla(['step', 'push', '-m', 'Create version file']);
context.tortilla(['step', 'tag', '-m', 'First step']);
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
context.tortilla(['step', 'edit', '1.1']);
context.exec('sh', ['-c', 'echo 1.1.0 > VERSION']);
context.git(['add', 'VERSION']);
context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } });
context.git(['rebase', '--continue']);
context.tortilla(['release', 'bump', 'minor', '-m', 'minor version test']);
context.tortilla(['step', 'edit', '1.1']);
context.exec('sh', ['-c', 'echo 1.1.1 > VERSION']);
context.git(['add', 'VERSION']);
context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } });
context.git(['rebase', '--continue']);
context.tortilla(['release', 'bump', 'patch', '-m', 'patch version test']);
const releaseDiff = context.tortilla(['release', 'diff', '1.1.1', '1.0.0', '--name-only'], {
env: {
TORTILLA_STDIO: 'inherit',
GIT_PAGER: 'cat'
}
});
expect(releaseDiff).toContainSameContentAsFile('release-update-names.diff');
});
it('should be able to run "git diff" for two releases with different roots', () => {
context.tortilla(['step', 'edit', '--root']);
context.exec('sh', ['-c', 'echo 1.0.0 > VERSION']);
context.git(['add', 'VERSION']);
context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } });
context.git(['rebase', '--continue']);
context.tortilla(['step', 'tag', '-m', 'First step']);
context.tortilla(['release', 'bump', 'major', '-m', 'major version test']);
context.tortilla(['step', 'edit', '--root']);
context.exec('sh', ['-c', 'echo 1.1.0 > VERSION']);
context.git(['add', 'VERSION']);
context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } });
context.git(['rebase', '--continue']);
context.tortilla(['release', 'bump', 'minor', '-m', 'minor version test']);
context.tortilla(['step', 'edit', '--root']);
context.exec('sh', ['-c', 'echo 1.1.1 > VERSION']);
context.git(['add', 'VERSION']);
context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } });
context.git(['rebase', '--continue']);
context.tortilla(['release', 'bump', 'patch', '-m', 'patch version test']);
const releaseDiff = context.tortilla(['release', 'diff', '1.1.1', '1.0.0'], {
env: {
TORTILLA_STDIO: 'inherit',
GIT_PAGER: 'cat'
}
});
expect(releaseDiff).toContainSameContentAsFile('release-update.diff');
});
it('it should be able to run "git diff" for nested submodules', () => {
const submodule = `${context.testDir}/module`;
context.tortilla(['step', 'edit', '--root']);
context.tortilla(['create', submodule], { env: { GIT_EDITOR: true } });
// Create submodule and release initial version
context.scopeEnv(() => {
context.exec('sh', ['-c', 'echo foo > file'], { cwd: submodule });
context.git(['add', 'file'], { cwd: submodule });
context.tortilla(['step', 'push', '-m', 'add file'], { cwd: submodule });
context.tortilla(['step', 'tag', '-m', 'how to add file'], { cwd: submodule });
context.tortilla(['release', 'bump', 'minor', '-m', 'release foo'], { cwd: submodule });
}, {
TORTILLA_CWD: submodule
});
// Amend submodule and release initial version
context.git(['submodule', 'add', './module']);
context.git(['add', '.']);
context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } });
context.git(['rebase', '--continue']);
context.setPromptAnswers(['master@0.1.0']);
context.tortilla(['release', 'bump', 'minor', '-m', 'release foo']);
context.tortilla(['step', 'edit', '--root']);
// Release a second version of the submodule
context.scopeEnv(() => {
context.git(['checkout', 'master']);
context.tortilla(['step', 'edit', '1.1'], { cwd: submodule });
context.exec('sh', ['-c', 'echo bar > file'], { cwd: submodule });
context.git(['add', 'file'], { cwd: submodule });
context.git(['commit', '--amend'], { cwd: submodule, env: { GIT_EDITOR: true } });
context.git(['rebase', '--continue'], { cwd: submodule });
context.tortilla(['release', 'bump', 'major', '-m', 'release bar'], { cwd: submodule });
}, {
TORTILLA_CWD: submodule
});
// Release a second version of the main module
context.git(['add', '.']);
context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } });
context.git(['rebase', '--continue']);
context.setPromptAnswers(['master@1.0.0']);
context.tortilla(['release', 'bump', 'major', '-m', 'release bar']);
const releaseDiff = context.tortilla(['release', 'diff', '0.1.0', '1.0.0'], {
env: {
TORTILLA_STDIO: 'inherit',
GIT_PAGER: 'cat'
}
});
expect(releaseDiff).toContainSameContentAsFile('submodule-releases.diff');
});
it('should handle missing versions of submodules when forming diff', () => {
const submodule = `${context.tempDir}/module`;
context.tortilla(['step', 'edit', '--root']);
context.tortilla(['create', submodule], { env: { GIT_EDITOR: true } });
// Create submodule and release initial version
context.scopeEnv(() => {
context.exec('sh', ['-c', 'echo foo > file'], { cwd: submodule });
context.git(['add', 'file'], { cwd: submodule });
context.tortilla(['step', 'push', '-m', 'add file'], { cwd: submodule });
context.tortilla(['step', 'tag', '-m', 'how to add file'], { cwd: submodule });
context.tortilla(['release', 'bump', 'minor', '-m', 'release foo'], { cwd: submodule });
}, {
TORTILLA_CWD: submodule
});
// Amend submodule and release initial version
context.git(['submodule', 'add', submodule, 'module']);
context.git(['add', '.']);
context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } });
context.git(['rebase', '--continue']);
context.setPromptAnswers(['master@0.1.0']);
context.tortilla(['release', 'bump', 'minor', '-m', 'release foo']);
context.tortilla(['step', 'edit', '--root']);
context.exec('rm', ['-rf', submodule]);
context.tortilla(['create', submodule], { env: { GIT_EDITOR: true } });
// Release a second version of the submodule
context.scopeEnv(() => {
context.exec('sh', ['-c', 'echo foo > file'], { cwd: submodule });
context.git(['add', 'file'], { cwd: submodule });
context.tortilla(['step', 'push', '-m', 'add file'], { cwd: submodule });
context.tortilla(['step', 'tag', '-m', 'how to add file'], { cwd: submodule });
context.tortilla(['release', 'bump', 'major', '-m', 'release foo'], { cwd: submodule });
}, {
TORTILLA_CWD: submodule
});
context.exec('rm', ['-rf', 'module']);
context.git(['clone', submodule, 'module']);
context.git(['add', '.']);
context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } });
context.git(['rebase', '--continue']);
context.setPromptAnswers(['master@1.0.0']);
context.tortilla(['release', 'bump', 'major', '-m', 'release bar']);
const releaseDiff = context.tortilla(['release', 'diff', '0.1.0', '1.0.0'], {
env: {
TORTILLA_STDIO: 'inherit',
GIT_PAGER: 'cat'
}
});
expect(releaseDiff).toEqual('');
});
});
}); | the_stack |
import {JigsawArray} from "./data-collection-utils";
// @dynamic
export class CommonUtils {
// to avoid compodoc generation error
private static _noDataImageSrc = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAAEgBckRAAAAAXNSR0IArs4c6QAAAERlWElmTU0' +
'AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAMKADAAQAAAABAAAAMAAAAADbN2wMAAAGFklEQVRoBe0ZXUibV/TeL4lJNDFGX' +
'adtJ+ta6UTKWFkrs9Y6EGRV2EPpHJS9dRtlP+ynL6N1Y1O3Pmy0dA+DPuyhUIa0fZo/CMKs2Dp1FDrYujJdh7OaqjHRxPwY892d8+n9uPnyRb+4tPUhF/Kde84999x' +
'zzv05594QsqnS3uN5gwkFhVD8+ANLDKHJYiPxWASrRAJGk1KDDycqDZTSOPxk3ogQ8BERT6MuKMR+mwz7sasZPwvBEPnuhh9ls/dqXS6kUa4qImJJsIM3FDjzFDrHD' +
'cGEHm1dUzdAwVptT5e03fbBURpFutqhtfOB4kYknm3cjoAEozK50OdR6vhpadpB1Q6pjFG5oYI2SIvB0NdGmLGjUT5xkK1YV72EyomuFZVFd4q4UodJk8VVJdaxjXd' +
'Qemol84kDRs4HkMVamnbmKMsSqe8fKVAa78+tDP81E60aGg+qNGyAZWtBqHZABMuuYnMVbCfy2j77KkHzldKZPX8gdC3lhtAIVlEJFxSUj1VKigp15BZtagOlkJclb' +
'+CBts6p8191TwXF5bpefWYxtqxdvbpDnOvy7EPGzZaf7vg9sB2Uk1l3ABSOC1f70xv00sCst2N0ZlDLi7hoTdLW0RsZ96F3MRz44Re/JxojpeXbzLdffzEPj+tDevw' +
'iTR0A4szli/0+sS2hbpaY8+1ql3ONmBQLEpgB8UciuwtstnHzQmBpFgJCMfhd4cFglpESi4+Bu1YDz8JSuIXJ8pcZEbwmBI6HSH6ePT/5aF1jAItMC8HwMQhl1YSRl' +
'xglZQDdgNsIY+BL6gOb70iUjFKLqdNptd7NpIJZWVkPPEYP6O6Di93MuiBPrWbLBpSBTTUAycURA6yrLHga4hlv9NjG2IExxNAAmAdhtm1UOOfDfniPWHcQDBYYNHi' +
'ndCFajkFLHESdg9bOyWU4X5T8SmTA+of1JcRhlRLIoEwCLiJi+qjGAxTOEzyRuffP0M0fR+Yr3jpcXCjSsa7Hrz3uE9XSSgC84fncQzOBmPvykFe5N0BmSVD7pkrHs' +
'A57EkmwIKlNJcBNivbeDQ1c6Hu432oh06cOu0sgwkFWunExNACKaajIrW2oUASWQ/K8seQ1DsVFGD8N9zDAiPGds0F+HbpGIH5yQiYgLO83MX2BYgIXsWNcqHYFcPp' +
'mIVwDPWkn/OkMJlF6TnI5cnMwA0inoxFeKkmf5TtyP1V38gJjhWQp3AN+O2hEgB4PKIr3udOgtHrwqQNoOwSi0QoWizfJjBwAphdgrtzwvOCG/CwC2ZSPMjIB8FfAb' +
'7kc9usgPK6VkcWzHsh6IOuBLeCBlOdcKt3O/+wrCIbC43BFS8pgUvUxRKd03pFr3/3RK+60briGDYAIQdu7pjsYYcdzTHT+VN3TbqcNbpcZKIGIzL7vf+hbjrNCSuj' +
'VM42lzXDwG0paDCnQ3j39iSzL34DQ2ImqopVni3L0H//+pzH/eJfDV4a9ZnCWRZKk02eOln67kch1DWjtma4jcbkXhOTU7c2fq9njKN5IYCbaB8eCc/33FnGsZWKSG' +
'lpeLe1PJVfXgLZe7zMkFhmCOdyx6ymr58TBopJUAh4l/cqI13N/NloCSj4gFtvLZxuK/tWOp5tTs1hkgjOigPXuMJwPYfOBIlK+zSqSkup4q+gY9SbRUxAUx6EjwaG' +
'oU5LDdQ3gwvTuRbxNhDGZBi4N+n2gWFnNHiep28uf20QuQvrvBcjgWIBAojrxTk2BG9/mEjn0sfUy8XUN0BeXTLWAIu/Wupx/z8Vv9fwR3AlKliVzwd9qoHhjpXPyu' +
'WJTdTo3Iz1ZnJYRA7gwVAwM4ageRMN0jdNjNkJTrn1GGLcqj2IAnrv4Ggv3zTBeB7eqsqgb6qi8HIPOqKfyDyMQl/EpGQyxbVXluV6oI+qKOuO/oxj1TvJGDu0WSsI' +
'xpvyLzGlPGtpzkk5QSMfYSQoffFPvEB8QnrSyxsan1+Gy3JxgFr7h0BX5cxBwHKfKmKDHwwV5GL5tXGVm6Qv8n4aPmmAAJ4oQ3ytYMFwPM1QPcXA/ZIuVj8o4VBKy3' +
'd/h8ew2BN0+6rD3uSDNFvXJ1rMeyLAH/gPasMvKip60ZAAAAABJRU5ErkJggg==';
public static noDataImageSrc = CommonUtils._noDataImageSrc;
private static copy(source: Object, isDeep: boolean): Object {
if (this.isUndefined(source) || typeof source !== 'object') {
return source;
}
let copy = (source instanceof Array) ? [] : {};
for (let attr in source) {
if (!source.hasOwnProperty(attr)) {
continue;
}
copy[attr] = isDeep ? CommonUtils.copy(source[attr], true) : source[attr];
}
return copy;
}
/**
* 浅拷贝一个对象
* @param source
*/
public static shallowCopy(source: Object): Object {
return CommonUtils.copy(source, false);
}
/**
* 深拷贝一个对象
* @param source
*/
public static deepCopy(source: Object): Object {
return CommonUtils.copy(source, true);
}
public static compareValue(item1: any, item2: any, trackItemBy?: string[] | string): boolean {
// 排除掉非法值和基础类型,如果比对的值是这两种之一的,则采用简单比较方式
if (this.isUndefined(item1) || this.isUndefined(item2)) {
return item1 == item2;
}
const typeOfItem1 = typeof item1, typeOfItem2 = typeof item2;
if (typeOfItem1 == 'string' || typeOfItem1 == 'boolean' || typeOfItem1 == 'number' ||
typeOfItem2 == 'string' || typeOfItem2 == 'boolean' || typeOfItem2 == 'number') {
return item1 == item2;
}
// 对数组类型,认为应该比较各自包含的元素,即不把数组当做对象去比较,因此数组与非数组的比较没有意义
const isArr1 = item1 instanceof Array || item1 instanceof JigsawArray;
const isArr2 = item2 instanceof Array || item2 instanceof JigsawArray;
if ((isArr1 && !isArr2) || (!isArr1 && isArr2)) {
return false;
}
if (isArr1 && isArr2) {
if (item1.length != item2.length) {
// 不等长的数组必然不相等
return false;
}
for (let i = 0, len = item1.length; i < len; i++) {
if (!this.compareValue(item1[i], item2[i], trackItemBy)) {
return false;
}
}
return true;
}
// 到这里说明item1和item2都是非数组的json对象了
if (item1 === item2) {
return true;
}
const trackBy: string[] = typeof trackItemBy == 'string' ? trackItemBy.split(/\s*,\s*/) : trackItemBy;
if (!trackBy || trackBy.length == 0) {
return item1 == item2;
}
for (let i = 0, len = trackBy.length; i < len; i++) {
if (item1[trackBy[i]] != item2[trackBy[i]]) {
return false;
}
}
return true;
}
/**
* 比较两个对象是否相等,如果提供`trackItemBy`参数,则只比较`trackItemBy`数组列出的属性是否相等;
* 如果未提供`trackItemBy`,则按值比较两个对象是否相等。
*
* @param item1 待比较的值1
* @param item2 待比较的值2
* @param trackItemBy 待比较的属性列表
*/
public static compareWithKeyProperty(item1: any, item2: any, trackItemBy: string[]): boolean {
if (trackItemBy && trackItemBy.length > 0) {
for (let i = 0; i < trackItemBy.length; i++) {
if (!item1 || !item2) {
// 过滤掉 typeof null == 'object'
return false;
} else if (typeof item1 === 'object' && typeof item2 === 'object') {
if (item1[trackItemBy[i]] != item2[trackItemBy[i]]) {
return false;
}
} else if (typeof item1 !== 'object' && typeof item2 === 'object') {
if (item1 != item2[trackItemBy[i]]) {
return false;
}
} else if (typeof item1 === 'object' && typeof item2 !== 'object') {
if (item1[trackItemBy[i]] != item2) {
return false;
}
} else {
if (item1 != item2) {
return false;
}
}
}
return true;
} else {
return item1 == item2;
}
}
/**
* 判断一个对象是否不包含任何属性
*
* @param obj
*
*/
public static isEmptyObject(obj): boolean {
for (let i in obj) {
return false;
}
return true;
}
/**
* 负责两个对象的合并,将sourceObject 中的属性添加到targetObject 中
*
* @param targetObject 要合并的源对象
* @param sourceObject 合并的对象信息
* @returns 如果`targetObject`非空,则返回`targetObject`,否则返回一个新对象。
*/
public static extendObject(targetObject: Object, sourceObject: Object): Object {
if (!sourceObject) {
return targetObject;
}
// 目标对象为空,则直接将对象复制给obj
if (this.isUndefined(targetObject)) {
targetObject = {};
}
if (typeof targetObject !== 'object' || typeof sourceObject !== 'object') {
return targetObject;
}
for (let i in sourceObject) {
if (!sourceObject.hasOwnProperty(i)) {
continue;
}
if (typeof sourceObject[i] === "object") {
// 如果原数据为数组, 而目标数据不是同类型,直接覆盖;
if (sourceObject[i] instanceof Array && !(targetObject[i] instanceof Array)) {
targetObject[i] = sourceObject[i];
} else if (this.isUndefined(targetObject[i])) {
// typeof null is object
targetObject[i] = this.isUndefined(sourceObject[i]) ? sourceObject[i] : this.extendObject({}, sourceObject[i]);
} else {
this.extendObject(targetObject[i], sourceObject[i]);
}
} else {
targetObject[i] = sourceObject[i];
}
}
return targetObject;
}
public static extendObjects<T = Object>(targetObject: T, ...sources): T {
sources.forEach(s => {
targetObject = <T>this.extendObject(targetObject, s);
});
return targetObject;
}
/**
* 把一个值转为px或%
* @param value
* @returns string
*/
public static getCssValue(value: string | number): string {
if (CommonUtils.isUndefined(value)) {
return null;
}
value = typeof value === 'string' ? value : value + '';
const match = value ? value.match(/^\s*\d+\.*\d*\s*$/) : null;
return match ? (value + 'px') : value;
}
/**
*
* @param element
* @param selector 支持'.className' '#id' '[attr]' 'tagName'
*
*/
public static getParentNodeBySelector(element: HTMLElement, selector: string): HTMLElement {
if (element instanceof HTMLElement) {
let parent = element.parentElement;
selector = selector.trim();
if (selector.match(/^#.+/)) {
selector = selector.replace("#", '');
while (parent && parent.getAttribute('id') !== selector) {
parent = parent.parentElement;
}
return parent;
} else if (selector.match(/^\..+/)) {
selector = selector.replace(".", '');
while (parent && !parent.classList.contains(selector)) {
parent = parent.parentElement;
}
return parent;
} else if (selector.match(/^\[.+\]$/)) {
selector = selector.replace(/[\[\]]/g, '');
while (parent && !parent.hasAttribute(selector)) {
parent = parent.parentElement;
}
return parent;
} else {
while (parent && parent.tagName.toLowerCase() !== selector) {
parent = parent.parentElement;
}
return parent;
}
} else {
return null;
}
}
/**
* 获取浏览器的语言,例如 `"zh"`
*
* @returns string
*/
public static getBrowserLang(): string {
if (typeof window === 'undefined' || typeof window.navigator === 'undefined') {
return undefined;
}
// to avoid compiler mis-error.
const w: any = window;
let browserLang: any = w.navigator.languages ? w.navigator.languages[0] : null;
browserLang = browserLang || w.navigator.language || w.navigator.browserLanguage || w.navigator.userLanguage;
if (browserLang.indexOf('-') !== -1) {
browserLang = browserLang.split('-')[0];
}
if (browserLang.indexOf('_') !== -1) {
browserLang = browserLang.split('_')[0];
}
return browserLang;
}
/**
* 获取浏览器的语言,例如 `"zh-CN"`
*
* @returns string
*/
public static getBrowserCultureLang(): string {
if (typeof window === 'undefined' || typeof window.navigator === 'undefined') {
return undefined;
}
// to avoid compiler mis-error.
const w: any = window;
let browserCultureLang: any = w.navigator.languages ? w.navigator.languages[0] : null;
browserCultureLang = browserCultureLang || w.navigator.language || w.navigator.browserLanguage || w.navigator.userLanguage;
return browserCultureLang;
}
/**
* 安全的调用一个函数,并返回该函数的返回值。如果该函数执行失败,可以在控制台给出实际的堆栈以协助排查问题
*
* @param context 执行函数的上下文
* @param callback 待执行的回调函数
* @param args 传递给回调函数的参数列表
* @returns 返回该函数的返回值
*/
public static safeInvokeCallback(context: any, callback: Function, args?: any[]): any {
if (CommonUtils.isUndefined(callback)) {
return;
}
try {
return callback.apply(context, args);
} catch (e) {
console.error('invoke callback error: ' + e);
console.error(e.stack);
}
}
/**
* 可靠的判断一个值是否有效,输入 `""` 和 `0` 均返回true,只有`null`或者`undefined`才会返回false
*
* @param value 待测验的值
*
*/
public static isDefined(value): boolean {
return value !== undefined && value !== null;
}
/**
* 参考 `isDefined`
*
* @param value
*
*/
public static isUndefined(value): boolean {
return !this.isDefined(value);
}
/**
* 将url中的参数解析为一个对象
*
* @param rawParam 格式为`var1=value1&var2=value2`
* @returns 返回类似`{var1: "value1", var2: "value2"}`的对象
*/
public static parseUrlParam(rawParam: string): Object {
const result = {};
if (!!rawParam) {
rawParam.split(/&/g).forEach(param => {
const parts = param.split(/=/);
result[this.superDecodeURI(parts[0])] = this.superDecodeURI(parts[1]);
});
}
return result;
}
/**
* 是浏览器内置uri解码`decodeURI()`函数的火力增强版,可以解码任何uri
*
* @param uri
*
*/
public static superDecodeURI(uri: string): string {
if (!uri) {
return uri;
}
return decodeURI(uri).replace(/%([0-9a-f]{2})/gi,
(found, charCode) => String.fromCharCode(parseInt(charCode, 16)));
}
/**
* 判断浏览器是否为IE
*/
public static isIE(): boolean {
return !!navigator.userAgent.match(/MSIE|Trident/g);
}
public static getBrowserType(): string {
if (navigator.userAgent.indexOf("MSIE") != -1) {
return "MSIE";
}
if (navigator.userAgent.indexOf("Firefox") != -1) {
return "Firefox";
}
if (navigator.userAgent.indexOf("Chrome") != -1) {
return "Chrome";
}
if (navigator.userAgent.indexOf("Safari") != -1) {
return "Safari";
}
if (navigator.userAgent.indexOf("Opera") != -1) {
return "Opera";
}
return null;
}
public static toTrackByFunction(trackBy: string | string[]) {
return function (index: number, item: any) {
if (typeof item === 'string') {
return item;
}
if (!trackBy || !item) {
return index;
}
let tracker;
if (trackBy instanceof Array) {
try {
tracker = JSON.stringify(trackBy.map(t => item[t] + ''));
} catch (e) {
console.error('trackBy value must be javascript native object')
}
} else {
tracker = item[trackBy];
}
return tracker;
}
}
/* 文本颜色对比度识别 */
private static _hexTest = /^#([\da-f]{3}){1,2}$/i;
private static _hexATest = /^#([\da-f]{4}){1,2}$/i;
private static _rgbTest =
/^rgb\(((((((1?[1-9]?\d)|10\d|(2[0-4]\d)|25[0-5]),\s?){2}|(((1?[1-9]?\d)|10\d|(2[0-4]\d)|25[0-5])\s){2})((1?[1-9]?\d)|10\d|(2[0-4]\d)|25[0-5]))|((((([1-9]?\d(\.\d+)?)|100|(\.\d+))%,\s?){2}|((([1-9]?\d(\.\d+)?)|100|(\.\d+))%\s){2})(([1-9]?\d(\.\d+)?)|100|(\.\d+))%))\)$/i;
private static _rgbATest =
/^rgba\(((((((1?[1-9]?\d)|10\d|(2[0-4]\d)|25[0-5]),\s?){3})|(((([1-9]?\d(\.\d+)?)|100|(\.\d+))%,\s?){3}))|(((((1?[1-9]?\d)|10\d|(2[0-4]\d)|25[0-5])\s){3})|(((([1-9]?\d(\.\d+)?)|100|(\.\d+))%\s){3}))\/\s)((0?\.\d+)|[01]|(([1-9]?\d(\.\d+)?)|100|(\.\d+))%)\)$/i;
private static _hslTest =
/^hsl\(((((([12]?[1-9]?\d)|[12]0\d|(3[0-5]\d))(\.\d+)?)|(\.\d+))(deg)?|(0|0?\.\d+)turn|(([0-6](\.\d+)?)|(\.\d+))rad)((,\s?(([1-9]?\d(\.\d+)?)|100|(\.\d+))%){2}|(\s(([1-9]?\d(\.\d+)?)|100|(\.\d+))%){2})\)$/i;
private static _hslATest =
/^hsla\(((((([12]?[1-9]?\d)|[12]0\d|(3[0-5]\d))(\.\d+)?)|(\.\d+))(deg)?|(0|0?\.\d+)turn|(([0-6](\.\d+)?)|(\.\d+))rad)(((,\s?(([1-9]?\d(\.\d+)?)|100|(\.\d+))%){2},\s?)|((\s(([1-9]?\d(\.\d+)?)|100|(\.\d+))%){2}\s\/\s))((0?\.\d+)|[01]|(([1-9]?\d(\.\d+)?)|100|(\.\d+))%)\)$/i;
public static adjustFontColor(bg: string): "light" | "dark" {
/*
* sRGB Luma (ITU Rec. 709)标准
* L = (red * 0.2126 + green * 0.7152 + blue * 0.0722) / 255
*/
bg = this.anyToRGB(bg);
const rgbArr = bg.replace(/[^\d,]/g, "").split(",");
const r = +rgbArr[0] * 0.2126;
const g = +rgbArr[1] * 0.7152;
const b = +rgbArr[2] * 0.0722;
return (r + g + b) / 255 - 0.5 >= 0 ? "light" : "dark";
}
public static hexToRGB(h: string): string {
if (this._hexTest.test(h)) {
let r: number | string = 0,
g: number | string = 0,
b: number | string = 0;
if (h.length == 4) {
r = "0x" + h[1] + h[1];
g = "0x" + h[2] + h[2];
b = "0x" + h[3] + h[3];
} else if (h.length == 7) {
r = "0x" + h[1] + h[2];
g = "0x" + h[3] + h[4];
b = "0x" + h[5] + h[6];
}
return `rgb(${+r},${+g},${+b})`;
} else {
return "Invalid input color";
}
}
public static hexAToRGBA(h: string): string {
if (this._hexATest.test(h)) {
let r: number | string = 0,
g: number | string = 0,
b: number | string = 0,
a: any = 1;
if (h.length == 5) {
r = "0x" + h[1] + h[1];
g = "0x" + h[2] + h[2];
b = "0x" + h[3] + h[3];
a = "0x" + h[4] + h[4];
} else if (h.length == 9) {
r = "0x" + h[1] + h[2];
g = "0x" + h[3] + h[4];
b = "0x" + h[5] + h[6];
a = "0x" + h[7] + h[8];
}
a = +(a / 255).toFixed(3);
return `rgba(${+r},${+g},${+b},${+a})`;
} else {
return "Invalid input color";
}
}
private static _toRGB(h: number, s: number, l: number, a: number = NaN): string {
if (h >= 360) {
h %= 360;
}
let c = (1 - Math.abs(2 * l - 1)) * s,
x = c * (1 - Math.abs((h / 60) % 2 - 1)),
m = l - c / 2,
r = 0,
g = 0,
b = 0;
if (0 <= h && h < 60) {
r = c;
g = x;
b = 0;
} else if (60 <= h && h < 120) {
r = x;
g = c;
b = 0;
} else if (120 <= h && h < 180) {
r = 0;
g = c;
b = x;
} else if (180 <= h && h < 240) {
r = 0;
g = x;
b = c;
} else if (240 <= h && h < 300) {
r = x;
g = 0;
b = c;
} else if (300 <= h && h < 360) {
r = c;
g = 0;
b = x;
}
r = Math.round((r + m) * 255);
g = Math.round((g + m) * 255);
b = Math.round((b + m) * 255);
return isNaN(a) ? `rgb(${r},${g},${b})` : `rgba(${r},${g},${b},${a})`;
}
public static hslToRGB(hsl: string): string {
if (this._hslTest.test(hsl)) {
const sep = hsl.indexOf(",") > -1 ? "," : " ";
const hslArr = hsl.substr(4).split(")")[0].split(sep);
const h: number = +hslArr[0],
s: number = +hslArr[1].substr(0, hslArr[1].length - 1) / 100,
l: number = +hslArr[2].substr(0, hslArr[2].length - 1) / 100;
return this._toRGB(h, s, l);
} else {
return "Invalid input color";
}
}
public static hslAToRGBA(hsla: string): string {
if (this._hslATest.test(hsla)) {
const sep = hsla.indexOf(",") > -1 ? "," : " ";
const hslaArr = hsla.substr(5).split(")")[0].split(sep);
if (hslaArr.indexOf("/") > -1) {
hslaArr.splice(3, 1);
}
const h: number = +hslaArr[0],
s: number = +hslaArr[1].substr(0, hslaArr[1].length - 1) / 100,
l: number = +hslaArr[2].substr(0, hslaArr[2].length - 1) / 100,
a: number = +hslaArr[3];
return this._toRGB(h, s, l, a);
} else {
return "Invalid input color";
}
}
public static nameToRGB(name: string): string {
if (name === "") {
return "Invalid input color name";
}
let fakeDiv = document.createElement("div");
fakeDiv.style.color = name;
document.body.appendChild(fakeDiv);
let cs = window.getComputedStyle(fakeDiv),
pv = cs.getPropertyValue("color");
document.body.removeChild(fakeDiv);
return pv;
}
public static anyToRGB(v: string): string {
if (this._hexTest.test(v)) {
v = this.hexToRGB(v);
} else if (this._hexATest.test(v)) {
v = this.hexAToRGBA(v);
} else if (this._hslTest.test(v)) {
v = this.hslToRGB(v);
} else if (this._hslATest.test(v)) {
v = this.hslAToRGBA(v);
}
if (this._rgbATest.test(v)) {
const vArr = v.replace(/[^\d,]/g, "").split(",");
v = "rgb(" + +vArr[0] + "," + +vArr[1] + "," + +vArr[2] + ")";
}
if (!this._rgbTest.test(v)) {
v = this.nameToRGB(v);
}
return v;
}
}
export type CallbackRemoval = () => void; | the_stack |
import { dew as _utf8DewDew } from "./utf8.dew.js";
import { dew as _utilsDewDew } from "./utils.dew.js";
import { dew as _GenericWorkerDewDew } from "./stream/GenericWorker.dew.js";
import { dew as _StreamHelperDewDew } from "./stream/StreamHelper.dew.js";
import { dew as _defaultsDewDew } from "./defaults.dew.js";
import { dew as _compressedObjectDewDew } from "./compressedObject.dew.js";
import { dew as _zipObjectDewDew } from "./zipObject.dew.js";
import { dew as _indexDewDew } from "./generate/index.dew.js";
import { dew as _nodejsUtilsDewDew } from "./nodejsUtils.dew.js";
import { dew as _NodejsStreamInputAdapterDewDew } from "./nodejs/NodejsStreamInputAdapter.dew.js";
var exports = {},
_dewExec = false;
export function dew() {
if (_dewExec) return exports;
_dewExec = true;
var utf8 = _utf8DewDew();
var utils = _utilsDewDew();
var GenericWorker = _GenericWorkerDewDew();
var StreamHelper = _StreamHelperDewDew();
var defaults = _defaultsDewDew();
var CompressedObject = _compressedObjectDewDew();
var ZipObject = _zipObjectDewDew();
var generate = _indexDewDew();
var nodejsUtils = _nodejsUtilsDewDew();
var NodejsStreamInputAdapter = _NodejsStreamInputAdapterDewDew();
/**
* Add a file in the current folder.
* @private
* @param {string} name the name of the file
* @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
* @param {Object} originalOptions the options of the file
* @return {Object} the new file.
*/
var fileAdd = function (name, data, originalOptions) {
// be sure sub folders exist
var dataType = utils.getTypeOf(data),
parent;
/*
* Correct options.
*/
var o = utils.extend(originalOptions || {}, defaults);
o.date = o.date || new Date();
if (o.compression !== null) {
o.compression = o.compression.toUpperCase();
}
if (typeof o.unixPermissions === "string") {
o.unixPermissions = parseInt(o.unixPermissions, 8);
} // UNX_IFDIR 0040000 see zipinfo.c
if (o.unixPermissions && o.unixPermissions & 0x4000) {
o.dir = true;
} // Bit 4 Directory
if (o.dosPermissions && o.dosPermissions & 0x0010) {
o.dir = true;
}
if (o.dir) {
name = forceTrailingSlash(name);
}
if (o.createFolders && (parent = parentFolder(name))) {
folderAdd.call(this, parent, true);
}
var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false;
if (!originalOptions || typeof originalOptions.binary === "undefined") {
o.binary = !isUnicodeString;
}
var isCompressedEmpty = data instanceof CompressedObject && data.uncompressedSize === 0;
if (isCompressedEmpty || o.dir || !data || data.length === 0) {
o.base64 = false;
o.binary = true;
data = "";
o.compression = "STORE";
dataType = "string";
}
/*
* Convert content to fit.
*/
var zipObjectContent = null;
if (data instanceof CompressedObject || data instanceof GenericWorker) {
zipObjectContent = data;
} else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
zipObjectContent = new NodejsStreamInputAdapter(name, data);
} else {
zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);
}
var object = new ZipObject(name, zipObjectContent, o);
this.files[name] = object;
/*
TODO: we can't throw an exception because we have async promises
(we can have a promise of a Date() for example) but returning a
promise is useless because file(name, data) returns the JSZip
object for chaining. Should we break that to allow the user
to catch the error ?
return external.Promise.resolve(zipObjectContent)
.then(function () {
return object;
});
*/
};
/**
* Find the parent folder of the path.
* @private
* @param {string} path the path to use
* @return {string} the parent folder, or ""
*/
var parentFolder = function (path) {
if (path.slice(-1) === '/') {
path = path.substring(0, path.length - 1);
}
var lastSlash = path.lastIndexOf('/');
return lastSlash > 0 ? path.substring(0, lastSlash) : "";
};
/**
* Returns the path with a slash at the end.
* @private
* @param {String} path the path to check.
* @return {String} the path with a trailing slash.
*/
var forceTrailingSlash = function (path) {
// Check the name ends with a /
if (path.slice(-1) !== "/") {
path += "/"; // IE doesn't like substr(-1)
}
return path;
};
/**
* Add a (sub) folder in the current folder.
* @private
* @param {string} name the folder's name
* @param {boolean=} [createFolders] If true, automatically create sub
* folders. Defaults to false.
* @return {Object} the new folder.
*/
var folderAdd = function (name, createFolders) {
createFolders = typeof createFolders !== 'undefined' ? createFolders : defaults.createFolders;
name = forceTrailingSlash(name); // Does this folder already exist?
if (!this.files[name]) {
fileAdd.call(this, name, null, {
dir: true,
createFolders: createFolders
});
}
return this.files[name];
};
/**
* Cross-window, cross-Node-context regular expression detection
* @param {Object} object Anything
* @return {Boolean} true if the object is a regular expression,
* false otherwise
*/
function isRegExp(object) {
return Object.prototype.toString.call(object) === "[object RegExp]";
} // return the actual prototype of JSZip
var out = {
/**
* @see loadAsync
*/
load: function () {
throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
},
/**
* Call a callback function for each entry at this folder level.
* @param {Function} cb the callback function:
* function (relativePath, file) {...}
* It takes 2 arguments : the relative path and the file.
*/
forEach: function (cb) {
var filename, relativePath, file;
for (filename in this.files) {
if (!this.files.hasOwnProperty(filename)) {
continue;
}
file = this.files[filename];
relativePath = filename.slice(this.root.length, filename.length);
if (relativePath && filename.slice(0, this.root.length) === this.root) {
// the file is in the current root
cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...
}
}
},
/**
* Filter nested files/folders with the specified function.
* @param {Function} search the predicate to use :
* function (relativePath, file) {...}
* It takes 2 arguments : the relative path and the file.
* @return {Array} An array of matching elements.
*/
filter: function (search) {
var result = [];
this.forEach(function (relativePath, entry) {
if (search(relativePath, entry)) {
// the file matches the function
result.push(entry);
}
});
return result;
},
/**
* Add a file to the zip file, or search a file.
* @param {string|RegExp} name The name of the file to add (if data is defined),
* the name of the file to find (if no data) or a regex to match files.
* @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
* @param {Object} o File options
* @return {JSZip|Object|Array} this JSZip object (when adding a file),
* a file (when searching by string) or an array of files (when searching by regex).
*/
file: function (name, data, o) {
if (arguments.length === 1) {
if (isRegExp(name)) {
var regexp = name;
return this.filter(function (relativePath, file) {
return !file.dir && regexp.test(relativePath);
});
} else {
// text
var obj = this.files[this.root + name];
if (obj && !obj.dir) {
return obj;
} else {
return null;
}
}
} else {
// more than one argument : we have data !
name = this.root + name;
fileAdd.call(this, name, data, o);
}
return this;
},
/**
* Add a directory to the zip file, or search.
* @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
* @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
*/
folder: function (arg) {
if (!arg) {
return this;
}
if (isRegExp(arg)) {
return this.filter(function (relativePath, file) {
return file.dir && arg.test(relativePath);
});
} // else, name is a new folder
var name = this.root + arg;
var newFolder = folderAdd.call(this, name); // Allow chaining by returning a new object with this folder as the root
var ret = this.clone();
ret.root = newFolder.name;
return ret;
},
/**
* Delete a file, or a directory and all sub-files, from the zip
* @param {string} name the name of the file to delete
* @return {JSZip} this JSZip object
*/
remove: function (name) {
name = this.root + name;
var file = this.files[name];
if (!file) {
// Look for any folders
if (name.slice(-1) !== "/") {
name += "/";
}
file = this.files[name];
}
if (file && !file.dir) {
// file
delete this.files[name];
} else {
// maybe a folder, delete recursively
var kids = this.filter(function (relativePath, file) {
return file.name.slice(0, name.length) === name;
});
for (var i = 0; i < kids.length; i++) {
delete this.files[kids[i].name];
}
}
return this;
},
/**
* Generate the complete zip file
* @param {Object} options the options to generate the zip file :
* - compression, "STORE" by default.
* - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
* @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
*/
generate: function (options) {
throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
},
/**
* Generate the complete zip file as an internal stream.
* @param {Object} options the options to generate the zip file :
* - compression, "STORE" by default.
* - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
* @return {StreamHelper} the streamed zip file.
*/
generateInternalStream: function (options) {
var worker,
opts = {};
try {
opts = utils.extend(options || {}, {
streamFiles: false,
compression: "STORE",
compressionOptions: null,
type: "",
platform: "DOS",
comment: null,
mimeType: 'application/zip',
encodeFileName: utf8.utf8encode
});
opts.type = opts.type.toLowerCase();
opts.compression = opts.compression.toUpperCase(); // "binarystring" is preferred but the internals use "string".
if (opts.type === "binarystring") {
opts.type = "string";
}
if (!opts.type) {
throw new Error("No output type specified.");
}
utils.checkSupport(opts.type); // accept nodejs `process.platform`
if (opts.platform === 'darwin' || opts.platform === 'freebsd' || opts.platform === 'linux' || opts.platform === 'sunos') {
opts.platform = "UNIX";
}
if (opts.platform === 'win32') {
opts.platform = "DOS";
}
var comment = opts.comment || this.comment || "";
worker = generate.generateWorker(this, opts, comment);
} catch (e) {
worker = new GenericWorker("error");
worker.error(e);
}
return new StreamHelper(worker, opts.type || "string", opts.mimeType);
},
/**
* Generate the complete zip file asynchronously.
* @see generateInternalStream
*/
generateAsync: function (options, onUpdate) {
return this.generateInternalStream(options).accumulate(onUpdate);
},
/**
* Generate the complete zip file asynchronously.
* @see generateInternalStream
*/
generateNodeStream: function (options, onUpdate) {
options = options || {};
if (!options.type) {
options.type = "nodebuffer";
}
return this.generateInternalStream(options).toNodejsStream(onUpdate);
}
};
exports = out;
return exports;
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/secretValueOperationsMappers";
import * as Parameters from "../models/parameters";
import { ServiceFabricMeshManagementClientContext } from "../serviceFabricMeshManagementClientContext";
/** Class representing a SecretValueOperations. */
export class SecretValueOperations {
private readonly client: ServiceFabricMeshManagementClientContext;
/**
* Create a SecretValueOperations.
* @param {ServiceFabricMeshManagementClientContext} client Reference to the service client.
*/
constructor(client: ServiceFabricMeshManagementClientContext) {
this.client = client;
}
/**
* Creates a new value of the specified secret resource. The name of the value is typically the
* version identifier. Once created the value cannot be changed.
* @summary Adds the specified value as a new version of the specified secret resource.
* @param resourceGroupName Azure resource group name
* @param secretResourceName The name of the secret resource.
* @param secretValueResourceName The name of the secret resource value which is typically the
* version identifier for the value.
* @param secretValueResourceDescription Description for creating a value of a secret resource.
* @param [options] The optional parameters
* @returns Promise<Models.SecretValueCreateResponse>
*/
create(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, secretValueResourceDescription: Models.SecretValueResourceDescription, options?: msRest.RequestOptionsBase): Promise<Models.SecretValueCreateResponse>;
/**
* @param resourceGroupName Azure resource group name
* @param secretResourceName The name of the secret resource.
* @param secretValueResourceName The name of the secret resource value which is typically the
* version identifier for the value.
* @param secretValueResourceDescription Description for creating a value of a secret resource.
* @param callback The callback
*/
create(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, secretValueResourceDescription: Models.SecretValueResourceDescription, callback: msRest.ServiceCallback<Models.SecretValueResourceDescription>): void;
/**
* @param resourceGroupName Azure resource group name
* @param secretResourceName The name of the secret resource.
* @param secretValueResourceName The name of the secret resource value which is typically the
* version identifier for the value.
* @param secretValueResourceDescription Description for creating a value of a secret resource.
* @param options The optional parameters
* @param callback The callback
*/
create(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, secretValueResourceDescription: Models.SecretValueResourceDescription, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretValueResourceDescription>): void;
create(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, secretValueResourceDescription: Models.SecretValueResourceDescription, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretValueResourceDescription>, callback?: msRest.ServiceCallback<Models.SecretValueResourceDescription>): Promise<Models.SecretValueCreateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
secretResourceName,
secretValueResourceName,
secretValueResourceDescription,
options
},
createOperationSpec,
callback) as Promise<Models.SecretValueCreateResponse>;
}
/**
* Get the information about the specified named secret value resources. The information does not
* include the actual value of the secret.
* @summary Gets the specified secret value resource.
* @param resourceGroupName Azure resource group name
* @param secretResourceName The name of the secret resource.
* @param secretValueResourceName The name of the secret resource value which is typically the
* version identifier for the value.
* @param [options] The optional parameters
* @returns Promise<Models.SecretValueGetResponse>
*/
get(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.SecretValueGetResponse>;
/**
* @param resourceGroupName Azure resource group name
* @param secretResourceName The name of the secret resource.
* @param secretValueResourceName The name of the secret resource value which is typically the
* version identifier for the value.
* @param callback The callback
*/
get(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, callback: msRest.ServiceCallback<Models.SecretValueResourceDescription>): void;
/**
* @param resourceGroupName Azure resource group name
* @param secretResourceName The name of the secret resource.
* @param secretValueResourceName The name of the secret resource value which is typically the
* version identifier for the value.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretValueResourceDescription>): void;
get(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretValueResourceDescription>, callback?: msRest.ServiceCallback<Models.SecretValueResourceDescription>): Promise<Models.SecretValueGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
secretResourceName,
secretValueResourceName,
options
},
getOperationSpec,
callback) as Promise<Models.SecretValueGetResponse>;
}
/**
* Deletes the secret value resource identified by the name. The name of the resource is typically
* the version associated with that value. Deletion will fail if the specified value is in use.
* @summary Deletes the specified value of the named secret resource.
* @param resourceGroupName Azure resource group name
* @param secretResourceName The name of the secret resource.
* @param secretValueResourceName The name of the secret resource value which is typically the
* version identifier for the value.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName Azure resource group name
* @param secretResourceName The name of the secret resource.
* @param secretValueResourceName The name of the secret resource value which is typically the
* version identifier for the value.
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName Azure resource group name
* @param secretResourceName The name of the secret resource.
* @param secretValueResourceName The name of the secret resource value which is typically the
* version identifier for the value.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
secretResourceName,
secretValueResourceName,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* Gets information about all secret value resources of the specified secret resource. The
* information includes the names of the secret value resources, but not the actual values.
* @summary List names of all values of the the specified secret resource.
* @param resourceGroupName Azure resource group name
* @param secretResourceName The name of the secret resource.
* @param [options] The optional parameters
* @returns Promise<Models.SecretValueListResponse>
*/
list(resourceGroupName: string, secretResourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.SecretValueListResponse>;
/**
* @param resourceGroupName Azure resource group name
* @param secretResourceName The name of the secret resource.
* @param callback The callback
*/
list(resourceGroupName: string, secretResourceName: string, callback: msRest.ServiceCallback<Models.SecretValueResourceDescriptionList>): void;
/**
* @param resourceGroupName Azure resource group name
* @param secretResourceName The name of the secret resource.
* @param options The optional parameters
* @param callback The callback
*/
list(resourceGroupName: string, secretResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretValueResourceDescriptionList>): void;
list(resourceGroupName: string, secretResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretValueResourceDescriptionList>, callback?: msRest.ServiceCallback<Models.SecretValueResourceDescriptionList>): Promise<Models.SecretValueListResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
secretResourceName,
options
},
listOperationSpec,
callback) as Promise<Models.SecretValueListResponse>;
}
/**
* Lists the decrypted value of the specified named value of the secret resource. This is a
* privileged operation.
* @summary Lists the specified value of the secret resource.
* @param resourceGroupName Azure resource group name
* @param secretResourceName The name of the secret resource.
* @param secretValueResourceName The name of the secret resource value which is typically the
* version identifier for the value.
* @param [options] The optional parameters
* @returns Promise<Models.SecretValueListValueResponse>
*/
listValue(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.SecretValueListValueResponse>;
/**
* @param resourceGroupName Azure resource group name
* @param secretResourceName The name of the secret resource.
* @param secretValueResourceName The name of the secret resource value which is typically the
* version identifier for the value.
* @param callback The callback
*/
listValue(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, callback: msRest.ServiceCallback<Models.SecretValue>): void;
/**
* @param resourceGroupName Azure resource group name
* @param secretResourceName The name of the secret resource.
* @param secretValueResourceName The name of the secret resource value which is typically the
* version identifier for the value.
* @param options The optional parameters
* @param callback The callback
*/
listValue(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretValue>): void;
listValue(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretValue>, callback?: msRest.ServiceCallback<Models.SecretValue>): Promise<Models.SecretValueListValueResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
secretResourceName,
secretValueResourceName,
options
},
listValueOperationSpec,
callback) as Promise<Models.SecretValueListValueResponse>;
}
/**
* Gets information about all secret value resources of the specified secret resource. The
* information includes the names of the secret value resources, but not the actual values.
* @summary List names of all values of the the specified secret resource.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.SecretValueListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.SecretValueListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.SecretValueResourceDescriptionList>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretValueResourceDescriptionList>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretValueResourceDescriptionList>, callback?: msRest.ServiceCallback<Models.SecretValueResourceDescriptionList>): Promise<Models.SecretValueListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.SecretValueListNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const createOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/secrets/{secretResourceName}/values/{secretValueResourceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.secretResourceName,
Parameters.secretValueResourceName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "secretValueResourceDescription",
mapper: {
...Mappers.SecretValueResourceDescription,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.SecretValueResourceDescription
},
201: {
bodyMapper: Mappers.SecretValueResourceDescription
},
202: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/secrets/{secretResourceName}/values/{secretValueResourceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.secretResourceName,
Parameters.secretValueResourceName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.SecretValueResourceDescription
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/secrets/{secretResourceName}/values/{secretValueResourceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.secretResourceName,
Parameters.secretValueResourceName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/secrets/{secretResourceName}/values",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.secretResourceName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.SecretValueResourceDescriptionList
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const listValueOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/secrets/{secretResourceName}/values/{secretValueResourceName}/list_value",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.secretResourceName,
Parameters.secretValueResourceName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.SecretValue
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.SecretValueResourceDescriptionList
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
}; | the_stack |
import { USBDeviceFound, USBRequestDeviceOptions, ParseUSBDevice, USBConfiguration, USBInterface, USBDirection, USBInTransferResult, USBOutTransferResult, USBTransferStatus, USBControlTransferParameters } from "./USBTypes";
type DotNetReferenceType = {
invokeMethod<T>(methodIdentifier: string, ...args: any[]): T,
invokeMethodAsync<T>(methodIdentifier: string, ...args: any[]): Promise<T>
}
export class USBManager {
private usb: any = (<any>navigator).usb; // The WebUSB API root object
private _usbReference: DotNetReferenceType | undefined = undefined;
// All devices found on the last request
// We keep a list of the most recent object because we can't serialize the "real" USBDevice to send back to C#
// TODO: Find a better way to maintain it and keep consistent with the C# side...
private _foundDevices: any[] = [];
private _eventsRegistered: boolean = false;
public GetDevices = async (): Promise<USBDeviceFound[]> => {
let devices = await this.usb.getDevices();
let found: USBDeviceFound[] = [];
if (devices) {
devices.forEach(d => {
found.push(ParseUSBDevice(d));
this._foundDevices.push(d);
});
}
return found;
}
public RequestDevice = async (options: USBRequestDeviceOptions): Promise<USBDeviceFound> => {
function isEmpty(obj) {
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return true;
}
let filters: any[] = [];
let reqOptions: any = undefined;
if (options && options != null && options.filters && options.filters != null && options.filters.length > 0) {
options.filters.forEach(f => {
let filter: any = {};
Object.keys(f).forEach(key => {
if (f[key] != null) {
filter[key] = f[key];
}
});
if (!isEmpty(filter)) {
filters.push(filter);
}
});
if (filters.length > 0) {
reqOptions = { filters: filters };
}
} else {
reqOptions = { filters: [] };
}
let authorizedDevice = await this.usb.requestDevice(reqOptions);
let usbDevice = ParseUSBDevice(authorizedDevice);
this._foundDevices.push(authorizedDevice);
return usbDevice;
}
public OpenDevice = (device: USBDeviceFound): Promise<USBDeviceFound> => {
let usbDevice = this.GetUSBDevice(device);
return new Promise<USBDeviceFound>((resolve, reject) => {
if (!usbDevice) return reject("Device not connected");
usbDevice.open()
.then(() => {
let parsed = ParseUSBDevice(usbDevice);
console.log(parsed);
resolve(parsed);
})
.catch(err => reject(err));
});
}
public CloseDevice = (device: USBDeviceFound): Promise<USBDeviceFound> => {
let usbDevice = this.GetUSBDevice(device);
return new Promise<USBDeviceFound>((resolve, reject) => {
if (!usbDevice) return reject("Device not connected");
usbDevice.close()
.then(() => {
resolve(ParseUSBDevice(usbDevice));
})
.catch(err => reject(err));
});
}
public ResetDevice = (device: USBDeviceFound): Promise<USBDeviceFound> => {
let usbDevice = this.GetUSBDevice(device);
return new Promise<USBDeviceFound>((resolve, reject) => {
if (!usbDevice) return reject("Device not connected");
usbDevice.reset()
.then(() => {
resolve(ParseUSBDevice(usbDevice));
})
.catch(err => reject(err));
});
}
public SelectConfiguration = (device: USBDeviceFound, configurationValue: number): Promise<USBDeviceFound> => {
let usbDevice = this.GetUSBDevice(device);
return new Promise<USBDeviceFound>((resolve, reject) => {
if (!usbDevice) return reject("Device not connected");
console.log(configurationValue);
usbDevice.selectConfiguration(configurationValue)
.then(() => {
resolve(ParseUSBDevice(usbDevice));
})
.catch(err => reject(err));
});
}
public ClaimInterface = (device: USBDeviceFound, interfaceNumber: number): Promise<USBDeviceFound> => {
let usbDevice = this.GetUSBDevice(device);
return new Promise<USBDeviceFound>((resolve, reject) => {
if (!usbDevice) return reject("Device not connected");
usbDevice.claimInterface(interfaceNumber)
.then(() => {
resolve(ParseUSBDevice(usbDevice));
})
.catch(err => reject(err));
});
}
public ReleaseInterface = (device: USBDeviceFound, interfaceNumber: number): Promise<USBDeviceFound> => {
let usbDevice = this.GetUSBDevice(device);
return new Promise<USBDeviceFound>((resolve, reject) => {
if (!usbDevice) return reject("Device not connected");
usbDevice.releaseInterface(interfaceNumber)
.then(() => {
resolve(ParseUSBDevice(usbDevice));
})
.catch(err => reject(err));
});
}
public SelectAlternateInterface = (device: USBDeviceFound, interfaceNumber: number, alternateSetting: number): Promise<USBDeviceFound> => {
let usbDevice = this.GetUSBDevice(device);
return new Promise<USBDeviceFound>((resolve, reject) => {
if (!usbDevice) return reject("Device not connected");
usbDevice.selectAlternateInterface(interfaceNumber, alternateSetting)
.then(() => {
resolve(ParseUSBDevice(usbDevice));
})
.catch(err => reject(err));
});
}
public ClearHalt = (device: USBDeviceFound, direction: USBDirection, endpointNumber: number): Promise<USBDeviceFound> => {
let usbDevice = this.GetUSBDevice(device);
return new Promise<USBDeviceFound>((resolve, reject) => {
if (!usbDevice) return reject("Device not connected");
usbDevice.clearHalt(direction, endpointNumber)
.then(() => {
resolve(ParseUSBDevice(usbDevice));
})
.catch(err => reject(err));
});
}
public TransferIn = (device: USBDeviceFound, endpointNumber: number, length: number): Promise<USBInTransferResult> => {
let usbDevice = this.GetUSBDevice(device);
return new Promise<USBInTransferResult>((resolve, reject) => {
if (!usbDevice) return reject("Device not connected");
usbDevice.transferIn(endpointNumber, length)
.then(out => {
resolve({
data: this.BufferToBase64(Array.prototype.slice.call(new Uint8Array(out.data.buffer))), // Hack to support Uint8Array to byte[] serialization.
status: out.status
});
})
.catch(err => {
console.error(err);
reject(err);
});
});
}
public TransferOut = (device: USBDeviceFound, endpointNumber: number, data: string): Promise<USBOutTransferResult> => {
let usbDevice = this.GetUSBDevice(device);
return new Promise<USBOutTransferResult>((resolve, reject) => {
if (!usbDevice) return reject("Device not connected");
const buffer = this.Base64ToBuffer(data);
usbDevice.transferOut(endpointNumber, buffer)
.then(out => {
resolve({
bytesWritten: out.bytesWritten,
status: out.status
});
})
.catch(err => {
console.error(err);
reject(err);
});
});
}
public ControlTransferIn = (device: USBDeviceFound, setup: USBControlTransferParameters, length: number): Promise<USBInTransferResult> => {
let usbDevice = this.GetUSBDevice(device);
return new Promise<USBInTransferResult>((resolve, reject) => {
if (!usbDevice) return reject("Device not connected");
usbDevice.ControlTransferIn(setup, length)
.then(out => {
resolve({
data: this.BufferToBase64(Array.prototype.slice.call(new Uint8Array(out.data.buffer))), // Hack to support Uint8Array to byte[] serialization.
status: out.status
});
})
.catch(err => {
console.error(err);
reject(err);
});
});
}
public ControlTransferOut = (device: USBDeviceFound, setup: USBControlTransferParameters, data: string): Promise<USBOutTransferResult> => {
let usbDevice = this.GetUSBDevice(device);
return new Promise<USBOutTransferResult>((resolve, reject) => {
if (!usbDevice) return reject("Device not connected");
const buffer = this.Base64ToBuffer(data);
usbDevice.controlTransferOut(setup, buffer)
.then(out => {
console.log(out);
resolve({
bytesWritten: out.bytesWritten,
status: out.status
});
})
.catch(err => {
console.error(err);
reject(err);
});
});
}
private GetUSBDevice = (device: USBDeviceFound): any => {
return this._foundDevices.find(
d => d.vendorId == device.vendorId &&
d.productId == device.productId &&
d.deviceClass == device.deviceClass &&
d.serialNumber == device.serialNumber);
}
private ConnectionStateChangedCallback = (event: any) => {
if (!this._usbReference) return;
let method: string = "";
let usbDevice = this.GetUSBDevice(event.device);
if (event.type == "disconnect") {
method = "OnDisconnect";
this._foundDevices = this._foundDevices.filter((d, index, arr) => {
return d.vendorId != usbDevice.vendorId &&
d.productId != usbDevice.productId &&
d.deviceClass != usbDevice.deviceClass &&
d.serialNumber != usbDevice.serialNumber;
});
}
else if (event.type == "connect") {
method = "OnConnect";
}
else {
console.warn(event);
return;
}
this._usbReference.invokeMethodAsync(method, ParseUSBDevice(event.device));
}
public RegisterUSBEvents = (usb: DotNetReferenceType) => {
this._usbReference = usb;
//TODO: Check why this event is not consistently being fired.
if (!this._eventsRegistered) {
this.usb.addEventListener("connect", this.ConnectionStateChangedCallback);
this.usb.addEventListener("disconnect", this.ConnectionStateChangedCallback);
this._eventsRegistered = true;
}
}
public RemoveUSBEvents = (usb: DotNetReferenceType) => {
if (this._eventsRegistered) {
this.usb.removeEventListener("connect", this.ConnectionStateChangedCallback);
this.usb.removeEventListener("disconnect", this.ConnectionStateChangedCallback);
}
}
private BufferToBase64 = (buf) => {
var binstr = Array.prototype.map.call(buf, (ch) => {
return String.fromCharCode(ch);
}).join('');
return btoa(binstr);
}
private Base64ToBuffer = (base64: string) => {
var binstr = atob(base64);
var buf = new Uint8Array(binstr.length);
Array.prototype.forEach.call(binstr, (ch, i) => {
buf[i] = ch.charCodeAt(0);
});
return buf;
}
} | the_stack |
import { Tree } from '@angular-devkit/schematics';
import { SchematicTestRunner } from '@angular-devkit/schematics/testing';
import {
Schema as ApplicationOptions,
Style,
} from '@schematics/angular/application/schema';
import { Schema as WorkspaceOptions } from '@schematics/angular/workspace/schema';
import * as path from 'path';
import { SyntaxKind } from 'ts-morph';
import { Schema as SpartacusOptions } from '../add-spartacus/schema';
import { CART_BASE_MODULE } from '../shared/lib-configs/cart-schematics-config';
import { CHECKOUT_BASE_MODULE } from '../shared/lib-configs/checkout-schematics-config';
import {
CART_BASE_FEATURE_NAME,
CHECKOUT_B2B_FEATURE_NAME,
CHECKOUT_BASE_FEATURE_NAME,
CHECKOUT_SCHEDULED_REPLENISHMENT_FEATURE_NAME,
DIGITAL_PAYMENTS_FEATURE_NAME,
SPARTACUS_CHECKOUT_BASE,
SPARTACUS_SCHEMATICS,
} from '../shared/libs-constants';
import { findDynamicImport } from '../shared/utils/import-utils';
import { LibraryOptions } from '../shared/utils/lib-utils';
import { addModuleImport, Import } from '../shared/utils/new-module-utils';
import { createProgram, saveAndFormat } from '../shared/utils/program';
import { getProjectTsConfigPaths } from '../shared/utils/project-tsconfig-paths';
import {
cartBaseFeatureModulePath,
cartWrapperModulePath,
checkoutFeatureModulePath,
checkoutWrapperModulePath,
digitalPaymentsFeatureModulePath,
spartacusFeaturesModulePath,
} from '../shared/utils/test-utils';
import { Schema as SpartacusWrapperOptions } from '../wrapper-module/schema';
import { cleanupConfig } from './index';
const collectionPath = path.join(__dirname, '../collection.json');
describe('Spartacus Wrapper Module Schematics: ng g @spartacus/schematics:wrapper-module', () => {
const schematicRunner = new SchematicTestRunner(
SPARTACUS_SCHEMATICS,
collectionPath
);
let appTree: Tree;
let buildPath: string;
const workspaceOptions: WorkspaceOptions = {
name: 'workspace',
version: '0.5.0',
};
const appOptions: ApplicationOptions = {
name: 'schematics-test',
inlineStyle: false,
inlineTemplate: false,
routing: false,
style: Style.Scss,
skipTests: false,
projectRoot: '',
};
const defaultOptions: SpartacusOptions = {
project: 'schematics-test',
lazy: true,
features: [],
};
const BASE_OPTIONS: LibraryOptions = {
project: 'schematics-test',
lazy: true,
};
beforeEach(async () => {
appTree = await schematicRunner
.runExternalSchematicAsync(
'@schematics/angular',
'workspace',
workspaceOptions
)
.toPromise();
appTree = await schematicRunner
.runExternalSchematicAsync(
'@schematics/angular',
'application',
appOptions,
appTree
)
.toPromise();
buildPath = getProjectTsConfigPaths(appTree, BASE_OPTIONS.project)
.buildPaths[0];
});
describe('One dynamic import in the file', () => {
it('should generate appropriate feature module', async () => {
appTree = await schematicRunner
.runSchematicAsync(
'ng-add',
{
...defaultOptions,
features: [CHECKOUT_B2B_FEATURE_NAME],
name: 'schematics-test',
},
appTree
)
.toPromise();
const { program } = createProgram(appTree, appTree.root.path, buildPath);
const checkoutFeatureModule = program.getSourceFileOrThrow(
checkoutFeatureModulePath
);
const checkoutWrapperModule = program.getSourceFileOrThrow(
checkoutWrapperModulePath
);
expect(checkoutFeatureModule.print()).toMatchSnapshot();
expect(checkoutWrapperModule.print()).toMatchSnapshot();
});
});
describe('Multiple dynamic imports in the file', () => {
it('should generate appropriate feature module', async () => {
appTree = await schematicRunner
.runSchematicAsync(
'ng-add',
{
...defaultOptions,
features: [CART_BASE_FEATURE_NAME],
name: 'schematics-test',
},
appTree
)
.toPromise();
const options: SpartacusWrapperOptions = {
project: 'schematics-test',
markerModuleName: CART_BASE_MODULE,
featureModuleName: CART_BASE_MODULE,
};
appTree = await schematicRunner
.runSchematicAsync('wrapper-module', options, appTree)
.toPromise();
const { program } = createProgram(appTree, appTree.root.path, buildPath);
const cartFeatureModule = program.getSourceFileOrThrow(
cartBaseFeatureModulePath
);
const cartWrapperModule = program.getSourceFileOrThrow(
cartWrapperModulePath
);
expect(cartFeatureModule.print()).toMatchSnapshot();
expect(cartWrapperModule.print()).toMatchSnapshot();
});
});
describe('Double execution', () => {
it('should not change anything', async () => {
// first execution happens under the hood
appTree = await schematicRunner
.runSchematicAsync(
'ng-add',
{
...defaultOptions,
features: [CHECKOUT_BASE_FEATURE_NAME],
name: 'schematics-test',
},
appTree
)
.toPromise();
const options: SpartacusWrapperOptions = {
project: 'schematics-test',
markerModuleName: CHECKOUT_BASE_MODULE,
featureModuleName: CHECKOUT_BASE_MODULE,
};
// the second execution
appTree = await schematicRunner
.runSchematicAsync('wrapper-module', options, appTree)
.toPromise();
const { program } = createProgram(appTree, appTree.root.path, buildPath);
const checkoutFeatureModule = program.getSourceFileOrThrow(
checkoutFeatureModulePath
);
const checkoutWrapperModule = program.getSourceFileOrThrow(
checkoutWrapperModulePath
);
expect(checkoutFeatureModule.print()).toMatchSnapshot();
expect(checkoutWrapperModule.print()).toMatchSnapshot();
});
});
describe('Checkout Scheduled Replenishment', () => {
it('should create the checkout wrapper module and import Checkout features', async () => {
appTree = await schematicRunner
.runSchematicAsync(
'ng-add',
{
...defaultOptions,
name: 'schematics-test',
features: [CHECKOUT_SCHEDULED_REPLENISHMENT_FEATURE_NAME],
},
appTree
)
.toPromise();
const { program } = createProgram(appTree, appTree.root.path, buildPath);
const checkoutFeatureModule = program.getSourceFileOrThrow(
checkoutFeatureModulePath
);
const checkoutWrapperModule = program.getSourceFileOrThrow(
checkoutWrapperModulePath
);
expect(checkoutFeatureModule.print()).toMatchSnapshot();
expect(checkoutWrapperModule.print()).toMatchSnapshot();
});
});
describe('Digital Payments', () => {
it('should create the checkout wrapper module and import Base Checkout and DP', async () => {
appTree = await schematicRunner
.runSchematicAsync(
'ng-add',
{
...defaultOptions,
name: 'schematics-test',
features: [DIGITAL_PAYMENTS_FEATURE_NAME],
},
appTree
)
.toPromise();
const { program } = createProgram(appTree, appTree.root.path, buildPath);
const checkoutWrapperModule = program.getSourceFileOrThrow(
checkoutWrapperModulePath
);
const checkoutFeatureModule = program.getSourceFileOrThrow(
checkoutFeatureModulePath
);
const dpFeaturesModule = program.getSourceFileOrThrow(
digitalPaymentsFeatureModulePath
);
expect(checkoutWrapperModule.print()).toMatchSnapshot();
expect(checkoutFeatureModule.print()).toMatchSnapshot();
expect(dpFeaturesModule.print()).toMatchSnapshot();
});
});
describe('Checkout and DP', () => {
it('Should order the imports in the wrapper and Spartacus features modules', async () => {
appTree = await schematicRunner
.runSchematicAsync(
'ng-add',
{
...defaultOptions,
name: 'schematics-test',
features: [
CHECKOUT_SCHEDULED_REPLENISHMENT_FEATURE_NAME,
DIGITAL_PAYMENTS_FEATURE_NAME,
],
},
appTree
)
.toPromise();
const { program } = createProgram(appTree, appTree.root.path, buildPath);
const spartacusFeaturesModule = program.getSourceFileOrThrow(
spartacusFeaturesModulePath
);
const checkoutFeatureModule = program.getSourceFileOrThrow(
checkoutFeatureModulePath
);
const checkoutWrapperModule = program.getSourceFileOrThrow(
checkoutWrapperModulePath
);
const dpFeaturesModule = program.getSourceFileOrThrow(
digitalPaymentsFeatureModulePath
);
expect(spartacusFeaturesModule.print()).toMatchSnapshot();
expect(checkoutFeatureModule.print()).toMatchSnapshot();
expect(checkoutWrapperModule.print()).toMatchSnapshot();
expect(dpFeaturesModule.print()).toMatchSnapshot();
});
});
describe('wrapper module already exists', () => {
beforeEach(async () => {
appTree = await schematicRunner
.runSchematicAsync(
'ng-add',
{
...defaultOptions,
name: 'schematics-test',
features: [CHECKOUT_BASE_FEATURE_NAME],
},
appTree
)
.toPromise();
const { program } = createProgram(appTree, appTree.root.path, buildPath);
const spartacusFeaturesModule = program.getSourceFileOrThrow(
spartacusFeaturesModulePath
);
const checkoutImport: Import = {
moduleSpecifier: SPARTACUS_CHECKOUT_BASE,
namedImports: [CHECKOUT_BASE_MODULE],
};
// import CheckoutModule statically, making the spartacus-features module a wrapper module
addModuleImport(spartacusFeaturesModule, {
import: checkoutImport,
content: CHECKOUT_BASE_MODULE,
});
saveAndFormat(spartacusFeaturesModule);
const checkoutFeatureModule = program.getSourceFileOrThrow(
checkoutFeatureModulePath
);
const spartacusProvider = findDynamicImport(
checkoutFeatureModule,
checkoutImport
)?.getFirstAncestorByKindOrThrow(SyntaxKind.CallExpression);
if (!spartacusProvider) {
throw new Error('Could not find the spartacus provider');
}
// remove the dynamic import
cleanupConfig(spartacusProvider);
saveAndFormat(checkoutFeatureModule);
appTree = await schematicRunner
.runSchematicAsync(
'ng-add',
{
...defaultOptions,
name: 'schematics-test',
features: [DIGITAL_PAYMENTS_FEATURE_NAME],
},
appTree
)
.toPromise();
});
it('should append the feature module after it, and not add a dynamic import to the feature module', () => {
const { program } = createProgram(appTree, appTree.root.path, buildPath);
const spartacusFeaturesModule = program.getSourceFileOrThrow(
spartacusFeaturesModulePath
);
const checkoutFeatureModule = program.getSourceFileOrThrow(
checkoutFeatureModulePath
);
expect(program.getSourceFile(checkoutWrapperModulePath)).toBeFalsy();
expect(spartacusFeaturesModule.print()).toMatchSnapshot();
expect(checkoutFeatureModule.print()).toMatchSnapshot();
});
});
}); | the_stack |
import { PdfSection, PageSettingsState } from '../../../../src/implementation/pages/pdf-section';
import { PdfDocument } from '../../../../src/implementation/document/pdf-document';
import { PdfPageBase } from '../../../../src/implementation/pages/pdf-page-base';
import { PdfDictionary } from '../../../../src/implementation/primitives/pdf-dictionary';
import { DictionaryProperties } from '../../../../src/implementation/input-output/pdf-dictionary-properties';
import { PdfName } from '../../../../src/implementation/primitives/pdf-name';
import { PdfNumber } from '../../../../src/implementation/primitives/pdf-number';
import { PdfSectionTemplate, PdfPage, PdfSectionPageCollection, PdfPageRotateAngle, PointF, SizeF, PdfFontFamily } from "../../../../src/index";
import { PdfPageSize, PdfPageSettings, PdfWriter, PdfPageOrientation, RectangleF, PdfPageTemplateElement } from "../../../../src/index";
import { PdfFont, PdfStandardFont, PdfSolidBrush, PdfColor } from "../../../../src/index";
describe('PdfSection.ts',()=>{
describe('Constructor initializing',()=>{
// //Create a new PDF document.
// let document2 : PdfDocument = new PdfDocument();
// //Add a page.
// let page1 : PdfPage = document2.pages.add();
// //Create a header and draw the image.
// let bounds2 : RectangleF = new RectangleF({ x : 0, y : 0}, {width : document2.pages.getPageByIndex(0).getClientSize().width, height : 100});
// let header2 : PdfPageTemplateElement = new PdfPageTemplateElement(bounds2);
// //Add the header at the top.
// document2.template.left = header2;
// document2.template.right = header2;
// page1.section.containsTemplates(document2, page1, true);
// page1.section.containsTemplates(document2, page1, false);
// it('-page1.section.drawTemplates(page1, page1.layers.add(), document2, true)- throw Error', () => {
// expect(function (): void {page1.section.drawTemplates(page1, page1.layers.add(), document2, true);}).toThrowError();
// })
// it('-page1.section.drawTemplates(page1, page1.layers.add(), document2, false)- throw Error', () => {
// expect(function (): void {page1.section.drawTemplates(page1, page1.layers.add(), document2, false);}).toThrowError();
// })
let dictionaryProperties : DictionaryProperties = new DictionaryProperties();
let t2 : PdfDocument = new PdfDocument();
let t1 : PdfSection = new PdfSection(t2);
it('-t1.element.Items.getValue(DictionaryProperties.DictionaryProperties.Count) == new Number.PdfNumber(0)', () => {
expect((t1.element as PdfDictionary).items.getValue(dictionaryProperties.count)).toEqual(new PdfNumber(0));
})
it('-t1.element.Items.getValue(DictionaryProperties.DictionaryProperties.Count) == new Name.PdfName(DictionaryProperties.DictionaryProperties.Pages)', () => {
expect((t1.element as PdfDictionary).items.getValue(dictionaryProperties.type)).toEqual(new PdfName(dictionaryProperties.pages));
})
it('-t1.element.Items.getValue(DictionaryProperties.DictionaryProperties.Count) == new Number.PdfNumber(0)', () => {
expect((t1.element as PdfDictionary).items.getValue(dictionaryProperties.kids)).toEqual(t1.pagesReferences);
})
it('-Parent == undefined', () => {
expect(t1.parent).toBeUndefined();
})
it('-ParentDocument != undefined', () => {
expect(t1.parentDocument).not.toBeUndefined();
})
// it('-set PdfPageSettings == null trrow error', () => {
// expect(function (): void {t1.pageSettings == null;}).toThrowError();
// })
it('-PageSettings == undefined', () => {
expect(t1.pageSettings).not.toBeUndefined();
})
it('-element != undefined', () => {
expect(t1.element).not.toBeUndefined();
})
it('-m_pages != undefined', () => {
expect(t1.getPages()).toEqual(new Array<PdfPageBase>());
})
// it('-m_pagesReferences != undefined', () => {
// expect(t1.m_pagesReferences).toEqual(new Array<PdfPageBase>());
// })
// it('-PdfSection.constructor(document,document.PageSettings)', () => {
// expect(t3.constructor(t2 ,t2.PageSettings)).toHaveBeenCalled();
// })
let t4 : PdfSection = new PdfSection(t2 ,t2.pageSettings);
// it('-PdfSection.constructor()', () => {
// expect(t4.constructor()).toHaveBeenCalled();
// })
it('-ParentDocument == document', () => {
expect(t4.parentDocument).toEqual(t2);
})
it('-PageSettings == document.PageSettings.Clone()', () => {
expect(t1.pageSettings).not.toBeUndefined();
// expect(t1.PageSettings).toEqual(t2.PageSettings.Clone());
})
it('-Set Template', () => {
t1.template = new PdfSectionTemplate();
expect(t1.template).not.toBeUndefined();
})
it('-Set Template == null & get Template != Undefined', () => {
t1.template = null;
expect(t1.template).not.toBeUndefined();
})
let page : PdfPage;
// t4.GetActualBounds(page, true);
it('-this.GetLeftIndentWidth(PdfDocument, PdfPage, includeMargins)', () => {
expect(function (): void {t1.getLeftIndentWidth( null, page, true); }).toThrowError();
})
it('-this.GetLeftIndentWidth(PdfDocument, PdfPage, includeMargins)', () => {
expect(function (): void {t1.getLeftIndentWidth( t2, null, true); }).toThrowError();
})
it('-this.GetTopIndentHeight(PdfDocument, PdfPage, includeMargins)', () => {
expect(function (): void {t1.getTopIndentHeight( null, page, true); }).toThrowError();
})
it('-this.GetTopIndentHeight(PdfDocument, PdfPage, includeMargins)', () => {
expect(function (): void {t1.getTopIndentHeight( t2, null, true); }).toThrowError();
})
it('-this.GetRightIndentWidth(PdfDocument, PdfPage, includeMargins)', () => {
expect(function (): void {t1.getRightIndentWidth( null, page, true); }).toThrowError();
})
it('-this.GetRightIndentWidth(PdfDocument, PdfPage, includeMargins)', () => {
expect(function (): void {t1.getRightIndentWidth( t2, null, true); }).toThrowError();
})
it('-this.GetBottomIndentHeight(PdfDocument, PdfPage, includeMargins)', () => {
expect(function (): void {t1.getBottomIndentHeight( null, page, true); }).toThrowError();
})
it('-this.GetBottomIndentHeight(PdfDocument, PdfPage, includeMargins)', () => {
expect(function (): void {t1.getBottomIndentHeight( t2, null, true); }).toThrowError();
})
it('-set PdfPageSettings', () => {
let pageSettings : PdfPageSettings = new PdfPageSettings();
pageSettings.orientation = PdfPageOrientation.Landscape;
t1.pageSettings = pageSettings;
expect(t1.pageSettings).not.toBeUndefined();
expect(function (): void {t1.pageSettings = null;}).toThrowError();
})
let document : PdfDocument = new PdfDocument();
let section : PdfSection = new PdfSection(document);
it('-section.Pages != undefined', () => {
section.pages;
expect(section.pages).not.toBeUndefined();
})
it('-section.Pages.Remove(null) throw Error', () => {
expect(function (): void {section.remove(null);}).toThrowError();
})
// it('-section.Pages.Remove(page) not throw Error', () => {
// let page : PdfPage = section.Add() as PdfPage;
// expect(function (): void {section.Remove(page);}).toThrowError();
// })
let t5 : PdfDocument = new PdfDocument();
t5.pageSettings.size = PdfPageSize.a3;
t5.pageSettings.orientation = PdfPageOrientation.Landscape;
t5.pageSettings.rotate = PdfPageRotateAngle.RotateAngle180;
let page6 : PdfPage = t5.pages.add();
t5.pageSettings.size = PdfPageSize.a4;
t5.pageSettings.orientation = PdfPageOrientation.Landscape;
t5.pageSettings.rotate = PdfPageRotateAngle.RotateAngle180;
let page7 : PdfPage = t5.pages.add();
t5.pageSettings.size = PdfPageSize.a5;
t5.pageSettings.orientation = PdfPageOrientation.Portrait;
t5.pageSettings.rotate = PdfPageRotateAngle.RotateAngle180;
let page8 : PdfPage = t5.pages.add();
let state : PageSettingsState = new PageSettingsState(document);
it('-state.Orientation != undefined', () => {
expect(state.orientation).not.toBeUndefined();
})
let t6 : PdfDocument = new PdfDocument();
let t7 : PdfSection = t6.sections.add() as PdfSection;
let testPage : PdfPage = t7.pages.add();
let bounds1 : RectangleF = new RectangleF(0, 0, 500, 100);
let bounds2 : RectangleF = new RectangleF(0, 0, 500, 100);
let bounds3 : RectangleF = new RectangleF(0, 0, 500, 100);
let bounds4 : RectangleF = new RectangleF(0, 0, 500, 100);
let top : PdfPageTemplateElement = new PdfPageTemplateElement(bounds1);
t6.template.top = top;
t6.template.top.foreground = true;
let left : PdfPageTemplateElement = new PdfPageTemplateElement(bounds2);
t6.template.left = left;
t6.template.left.foreground = true;
let right : PdfPageTemplateElement = new PdfPageTemplateElement(bounds3);
t6.template.right = right;
t6.template.right.foreground = true;
let bottom : PdfPageTemplateElement = new PdfPageTemplateElement(bounds4);
t6.template.bottom = bottom;
t6.template.bottom.foreground = true;
it('template.top.foreground == true', () => {
expect(t6.template.top.foreground).toBeTruthy();
})
t6.save();
let t8 : PdfDocument = new PdfDocument();
let t9 : PdfSection = t8.sections.add() as PdfSection;
let testPage1 : PdfPage = t9.pages.add();
let top1 : PdfPageTemplateElement = new PdfPageTemplateElement(bounds1);
t8.template.top = top1;
t8.template.top.foreground = false;
let left1 : PdfPageTemplateElement = new PdfPageTemplateElement(bounds2);
t8.template.left = left1;
t8.template.left.foreground = false;
let right1 : PdfPageTemplateElement = new PdfPageTemplateElement(bounds3);
t8.template.right = right1;
t8.template.right.foreground = false;
let bottom1 : PdfPageTemplateElement = new PdfPageTemplateElement(bounds4);
t8.template.bottom = bottom1;
t8.template.bottom.foreground = false;
it('template.top.foreground == true', () => {
expect(t8.template.top.foreground).toBeFalsy();
})
t8.save();
// it('-t7.containsTemplates(t6, testPage, true); throw Error', () => {
// expect(function (): void {t7.containsTemplates(t6, testPage, true);}).not.toThrowError();
// })
// it('-t7.containsTemplates(t6, testPage, false); throw Error', () => {
// expect(function (): void {t7.containsTemplates(t6, testPage, false);}).not.toThrowError();
// })
let sampleDocument : PdfDocument = new PdfDocument();
let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 10);
let brush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));
let section1 : PdfSection = sampleDocument.sections.add() as PdfSection;
let settings1 : PdfPageSettings = new PdfPageSettings(40);
settings1.size = PdfPageSize.a3;
settings1.orientation = PdfPageOrientation.Portrait;
settings1.rotate = PdfPageRotateAngle.RotateAngle90;
section1.setPageSettings(settings1);
let page1 : PdfPage = section1.pages.add();
page1.graphics.drawString('Hello World', font, null, brush, 10, 20, null);
let page2 : PdfPage = section1.pages.add();
page2.graphics.drawString('Hello World', font, null, brush, 10, 20, null);
let section2 : PdfSection = sampleDocument.sections.add() as PdfSection;
let settings2 : PdfPageSettings = new PdfPageSettings(30);
settings2.size = new SizeF(500, 750);
settings2.orientation = PdfPageOrientation.Landscape;
settings2.rotate = PdfPageRotateAngle.RotateAngle270;
section2.setPageSettings(settings2);
let page3 : PdfPage = section2.pages.add();
page3.graphics.drawString('Hello World', font, null, brush, 10, 20, null);
})
}) | the_stack |
import * as child_process from 'child_process';
import * as os from 'os';
import { AttachItemsProvider } from './attachToProcess';
import { AttachItem } from './attachQuickPick';
import * as nls from 'vscode-nls';
import { findPowerShell } from '../common';
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
export class Process {
constructor(public name: string, public pid?: string, public commandLine?: string) { }
public toAttachItem(): AttachItem {
return {
label: this.name,
description: this.pid,
detail: this.commandLine,
id: this.pid
};
}
}
export class NativeAttachItemsProviderFactory {
static Get(): AttachItemsProvider {
if (os.platform() === 'win32') {
const pwsh: string | undefined = findPowerShell();
return pwsh ? new CimAttachItemsProvider(pwsh) : new WmicAttachItemsProvider();
} else {
return new PsAttachItemsProvider();
}
}
}
abstract class NativeAttachItemsProvider implements AttachItemsProvider {
protected abstract getInternalProcessEntries(): Promise<Process[]>;
async getAttachItems(): Promise<AttachItem[]> {
const processEntries: Process[] = await this.getInternalProcessEntries();
// localeCompare is significantly slower than < and > (2000 ms vs 80 ms for 10,000 elements)
// We can change to localeCompare if this becomes an issue
processEntries.sort((a, b) => {
if (a.name === undefined) {
if (b.name === undefined) {
return 0;
}
return 1;
}
if (b.name === undefined) {
return -1;
}
const aLower: string = a.name.toLowerCase();
const bLower: string = b.name.toLowerCase();
if (aLower === bLower) {
return 0;
}
return aLower < bLower ? -1 : 1;
});
const attachItems: AttachItem[] = processEntries.map(p => p.toAttachItem());
return attachItems;
}
}
export class PsAttachItemsProvider extends NativeAttachItemsProvider {
// Perf numbers:
// OS X 10.10
// | # of processes | Time (ms) |
// |----------------+-----------|
// | 272 | 52 |
// | 296 | 49 |
// | 384 | 53 |
// | 784 | 116 |
//
// Ubuntu 16.04
// | # of processes | Time (ms) |
// |----------------+-----------|
// | 232 | 26 |
// | 336 | 34 |
// | 736 | 62 |
// | 1039 | 115 |
// | 1239 | 182 |
// ps outputs as a table. With the option "ww", ps will use as much width as necessary.
// However, that only applies to the right-most column. Here we use a hack of setting
// the column header to 50 a's so that the second column will have at least that many
// characters. 50 was chosen because that's the maximum length of a "label" in the
// QuickPick UI in VSCode.
protected async getInternalProcessEntries(): Promise<Process[]> {
let processCmd: string = '';
switch (os.platform()) {
case 'darwin':
processCmd = PsProcessParser.psDarwinCommand;
break;
case 'linux':
processCmd = PsProcessParser.psLinuxCommand;
break;
default:
throw new Error(localize("os.not.supported", 'Operating system "{0}" not supported.', os.platform()));
}
const processes: string = await execChildProcess(processCmd, undefined);
return PsProcessParser.ParseProcessFromPs(processes);
}
}
export class PsProcessParser {
private static get secondColumnCharacters(): number { return 50; }
private static get commColumnTitle(): string { return Array(PsProcessParser.secondColumnCharacters).join("a"); }
// the BSD version of ps uses '-c' to have 'comm' only output the executable name and not
// the full path. The Linux version of ps has 'comm' to only display the name of the executable
// Note that comm on Linux systems is truncated to 16 characters:
// https://bugzilla.redhat.com/show_bug.cgi?id=429565
// Since 'args' contains the full path to the executable, even if truncated, searching will work as desired.
public static get psLinuxCommand(): string { return `ps axww -o pid=,comm=${PsProcessParser.commColumnTitle},args=`; }
public static get psDarwinCommand(): string { return `ps axww -o pid=,comm=${PsProcessParser.commColumnTitle},args= -c`; }
// Only public for tests.
public static ParseProcessFromPs(processes: string): Process[] {
const lines: string[] = processes.split(os.EOL);
return PsProcessParser.ParseProcessFromPsArray(lines);
}
public static ParseProcessFromPsArray(processArray: string[]): Process[] {
const processEntries: Process[] = [];
// lines[0] is the header of the table
for (let i: number = 1; i < processArray.length; i++) {
const line: string = processArray[i];
if (!line) {
continue;
}
const processEntry: Process | undefined = PsProcessParser.parseLineFromPs(line);
if (processEntry) {
processEntries.push(processEntry);
}
}
return processEntries;
}
private static parseLineFromPs(line: string): Process | undefined {
// Explanation of the regex:
// - any leading whitespace
// - PID
// - whitespace
// - executable name --> this is PsAttachItemsProvider.secondColumnCharacters - 1 because ps reserves one character
// for the whitespace separator
// - whitespace
// - args (might be empty)
const psEntry: RegExp = new RegExp(`^\\s*([0-9]+)\\s+(.{${PsProcessParser.secondColumnCharacters - 1}})\\s+(.*)$`);
const matches: RegExpExecArray | null = psEntry.exec(line);
if (matches && matches.length === 4) {
const pid: string = matches[1].trim();
const executable: string = matches[2].trim();
const cmdline: string = matches[3].trim();
return new Process(executable, pid, cmdline);
}
}
}
/**
* Originally from common.ts. Due to test code not having vscode, it was refactored to not have vscode.OutputChannel.
*/
function execChildProcess(process: string, workingDirectory?: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
child_process.exec(process, { cwd: workingDirectory, maxBuffer: 500 * 1024 }, (error: Error | null, stdout: string, stderr: string) => {
if (error) {
reject(error);
return;
}
if (stderr && stderr.length > 0) {
if (stderr.indexOf('screen size is bogus') >= 0) {
// ignore this error silently; see https://github.com/microsoft/vscode/issues/75932
// see similar fix for the Node - Debug (Legacy) Extension at https://github.com/microsoft/vscode-node-debug/commit/5298920
} else {
reject(new Error(stderr));
return;
}
}
resolve(stdout);
});
});
}
export class WmicAttachItemsProvider extends NativeAttachItemsProvider {
// Perf numbers on Win10:
// | # of processes | Time (ms) |
// |----------------+-----------|
// | 309 | 413 |
// | 407 | 463 |
// | 887 | 746 |
// | 1308 | 1132 |
protected async getInternalProcessEntries(): Promise<Process[]> {
const wmicCommand: string = 'wmic process get Name,ProcessId,CommandLine /FORMAT:list';
const processes: string = await execChildProcess(wmicCommand, undefined);
return WmicProcessParser.ParseProcessFromWmic(processes);
}
}
export class WmicProcessParser {
private static get wmicNameTitle(): string { return 'Name'; }
private static get wmicCommandLineTitle(): string { return 'CommandLine'; }
private static get wmicPidTitle(): string { return 'ProcessId'; }
// Only public for tests.
public static ParseProcessFromWmic(processes: string): Process[] {
const lines: string[] = processes.split(os.EOL);
let currentProcess: Process = new Process("current process", undefined, undefined);
const processEntries: Process[] = [];
for (let i: number = 0; i < lines.length; i++) {
const line: string = lines[i];
if (!line) {
continue;
}
WmicProcessParser.parseLineFromWmic(line, currentProcess);
// Each entry of processes has ProcessId as the last line
if (line.lastIndexOf(WmicProcessParser.wmicPidTitle, 0) === 0) {
processEntries.push(currentProcess);
currentProcess = new Process("current process", undefined, undefined);
}
}
return processEntries;
}
private static parseLineFromWmic(line: string, process: Process): void {
const splitter: number = line.indexOf('=');
if (splitter >= 0) {
const key: string = line.slice(0, line.indexOf('=')).trim();
let value: string = line.slice(line.indexOf('=') + 1).trim();
if (key === WmicProcessParser.wmicNameTitle) {
process.name = value;
} else if (key === WmicProcessParser.wmicPidTitle) {
process.pid = value;
} else if (key === WmicProcessParser.wmicCommandLineTitle) {
const extendedLengthPath: string = '\\??\\';
if (value.lastIndexOf(extendedLengthPath, 0) === 0) {
value = value.slice(extendedLengthPath.length);
}
process.commandLine = value;
}
}
}
}
export class CimAttachItemsProvider extends NativeAttachItemsProvider {
constructor(private pwsh: string) { super(); }
// Perf numbers on Win10:
// TODO
protected async getInternalProcessEntries(): Promise<Process[]> {
const pwshCommand: string = `${this.pwsh} -NoProfile -Command`;
const cimCommand: string = 'Get-CimInstance Win32_Process | Select-Object Name,ProcessId,CommandLine | ConvertTo-JSON';
const processes: string = await execChildProcess(`${pwshCommand} "${cimCommand}"`, undefined);
return CimProcessParser.ParseProcessFromCim(processes);
}
}
type CimProcessInfo = {
Name: string;
ProcessId: number;
CommandLine: string | null;
};
export class CimProcessParser {
private static get extendedLengthPathPrefix(): string { return '\\\\?\\'; }
private static get ntObjectManagerPathPrefix(): string { return '\\??\\'; }
// Only public for tests.
public static ParseProcessFromCim(processes: string): Process[] {
const processInfos: CimProcessInfo[] = JSON.parse(processes);
return processInfos.map(info => {
let cmdline: string | undefined = info.CommandLine || undefined;
if (cmdline?.startsWith(this.extendedLengthPathPrefix)) {
cmdline = cmdline.slice(this.extendedLengthPathPrefix.length);
}
if (cmdline?.startsWith(this.ntObjectManagerPathPrefix)) {
cmdline = cmdline.slice(this.ntObjectManagerPathPrefix.length);
}
return new Process(info.Name, `${info.ProcessId}`, cmdline);
});
}
} | the_stack |
import * as DomUtil from '../common/dom_util';
import {AuditoryDescription} from '../audio/auditory_description';
import {Span} from '../audio/span';
import {Debugger} from '../common/debugger';
import {Engine, EngineConst} from '../common/engine';
import SystemExternal from '../common/system_external';
import XpathUtil from '../common/xpath_util';
import {ClearspeakPreferences} from '../speech_rules/clearspeak_preferences';
import {MathMap} from '../speech_rules/math_map';
import SpeechRules from '../speech_rules/speech_rules';
import * as SpeechRuleStores from '../speech_rules/speech_rule_stores';
import {BaseRuleStore} from './base_rule_store';
import {RulesJson} from './base_rule_store';
import {BrailleStore} from './braille_store';
import {Axis, AxisMap, DynamicCstr} from './dynamic_cstr';
import {Grammar, State as GrammarState} from './grammar';
import {MathStore} from './math_store';
import {ActionType, SpeechRule} from './speech_rule';
import {SpeechRuleContext} from './speech_rule_context';
import {Trie} from '../indexing/trie';
export class SpeechRuleEngine {
// TODO (TS): Keeping this as a singleton for the time being.
private static instance: SpeechRuleEngine;
public prune = true;
/**
* Trie for indexing speech rules in this store.
*/
public trie: Trie = null;
/**
* Flag indicating if the engine is ready. Not ready while it is updating!
*/
private ready_: boolean = true;
/**
* Default evaluators collated by locale and modality.
*/
private evaluators_:
{[key: string]: {[key: string]: (p1: Node) => AuditoryDescription[]}} = {};
/**
* @return The Engine object.
*/
public static getInstance(): SpeechRuleEngine {
SpeechRuleEngine.instance = SpeechRuleEngine.instance || new SpeechRuleEngine();
return SpeechRuleEngine.instance;
}
/**
* Test the precondition of a speech rule in debugging mode.
* @param rule A speech rule.
* @param node DOM node to test applicability of the rule.
*/
public static debugSpeechRule(rule: SpeechRule, node: Node) {
let prec = rule.precondition;
let queryResult = rule.context.applyQuery(node, prec.query);
Debugger.getInstance().output(
prec.query, queryResult ? queryResult.toString() : queryResult);
prec.constraints.forEach(cstr =>
Debugger.getInstance().output(
cstr, rule.context.applyConstraint(node, cstr)));
}
/**
* Test the precondition of a speech rule in debugging mode.
* @param name Rule to debug.
* @param node DOM node to test applicability of the rule.
*/
public static debugNamedSpeechRule(name: string, node: Node) {
let rules = SpeechRuleEngine.getInstance().trie.collectRules();
let allRules = rules.filter(rule => rule.name == name);
for (let i = 0, rule; rule = allRules[i]; i++) {
Debugger.getInstance().output(
'Rule', name, 'DynamicCstr:', rule.dynamicCstr.toString(), 'number',
i);
SpeechRuleEngine.debugSpeechRule(rule, node);
}
}
/**
* Updates the evaluator method for the document of the given node. This is
* particular important for XML documents in Firefox that generates a novel
* object (plus evaluate method) for every document.
*
* @param node The target node that is to be evaluated.
*/
private static updateEvaluator(node: Element) {
let parent = node as any as Document;
while(parent && !parent.evaluate) {
parent = parent.parentNode as Document;
}
if (parent.evaluate) {
XpathUtil.currentDocument = /** @type{Document} */(parent);
}
};
// Dispatch functionality.
// The timing function is temporary until the MOSS deliverable is done.
/**
* Computes a speech object for a given node. Returns the empty list if
* no node is given.
* @param node The node to be evaluated.
* @return A list of auditory descriptions
* for that node.
*/
public evaluateNode(node: Element): AuditoryDescription[] {
if (Engine.getInstance().mode === EngineConst.Mode.HTTP) {
SpeechRuleEngine.updateEvaluator(node);
}
let timeIn = (new Date()).getTime();
let result = this.evaluateNode_(node);
let timeOut = (new Date()).getTime();
Debugger.getInstance().output('Time:', timeOut - timeIn);
return result;
}
/**
* Prints the list of all current rules in ChromeVox to the console.
* @return A textual representation of all rules in the speech rule
* engine.
*/
public toString(): string {
let allRules = this.trie.collectRules();
return allRules.map(rule => rule.toString()).join('\n');
}
// TODO (TS): Rewrite engine to use a feature vector and save the settings
// this way. Currently we mess about with a lot of casting!
/**
* Runs a function in the temporary context of the speech rule engine.
* @param settings The temporary settings for the speech rule
* engine. They can contain the usual features.
* @param callback The runnable
* function that computes speech results.
* @return The result of the callback.
*/
public runInSetting(settings: {[feature: string]: string|boolean},
callback: () => AuditoryDescription[]):
AuditoryDescription[] {
let engine = Engine.getInstance() as any;
let save: {[feature: string]: string|boolean} = {};
for (let key in settings) {
save[key] = engine[key];
engine[key] = settings[key];
}
engine.setDynamicCstr();
let result = callback();
for (let key in save) {
engine[key] = save[key];
}
engine.setDynamicCstr();
return result;
}
/**
* Adds a speech rule store to the speech rule engine. This method is called
* when loading a rule set.
* @param set The definition of a speech rule set.
*/
public addStore(set: RulesJson) {
// This line is important to setup the context functions for stores.
// It has to run __before__ the first speech rule store is added.
let store = StoreFactory.get(set);
if (store.kind !== 'abstract') {
store.getSpeechRules().forEach(x => this.trie.addRule(x));
}
this.addEvaluator(store);
}
/**
* Updates adminstrative info in the base Engine.
* During update the engine is not ready!
*/
public updateEngine() {
this.ready_ = true;
let maps = MathMap.getInstance();
if (!Engine.isReady()) {
this.ready_ = false;
setTimeout(this.updateEngine.bind(this), 250);
return;
}
if (this.prune) {
this.prune = false;
this.adjustEngine();
}
// TODO: Rewrite this to use MathCompoundStore
Engine.getInstance().evaluator = maps.lookupString as (p1: string, p2: DynamicCstr) => string;
// maps.store.lookupString.bind(maps.store);
}
/**
* Adjust Engine with local rule files.
*/
public adjustEngine() {
let engine = Engine.getInstance();
if (engine.prune) {
let cstr = engine.prune.split('.');
this.pruneTrie(cstr);
}
if (engine.rules) {
// TODO: This needs to be made more robust.
let path =
SystemExternal.jsonPath.replace('/lib/mathmaps', '/mathmaps');
let parse = (json: string) =>
MathMap.getInstance().parseMaps(`{"${engine.rules}":${json}}`);
MathMap.getInstance().retrieveFiles(path + engine.rules, parse);
}
setTimeout(this.updateEngine.bind(this), 100);
}
/**
* Processes the grammar annotations of a rule.
* @param context The function context in which to
* evaluate the grammar expression.
* @param node The node to which the rule is applied.
* @param grammar The grammar annotations.
*/
public processGrammar(
context: SpeechRuleContext, node: Node, grammar: GrammarState) {
let assignment: GrammarState = {};
for (let key in grammar) {
let value = grammar[key];
assignment[key] = typeof value === 'string' ?
// TODO (TS): This could be a span!
context.constructString(node, value) as string :
value;
}
Grammar.getInstance().pushState(assignment);
}
/**
* Adds an evaluation method by locale and modality.
* @param store The store whose evaluation method is
* added.
*/
public addEvaluator(store: BaseRuleStore) {
let fun = store.evaluateDefault.bind(store);
let loc = this.evaluators_[store.locale];
if (loc) {
loc[store.modality] = fun;
return;
}
let mod: {[key: string]: (p1: Node) => AuditoryDescription[]} = {};
mod[store.modality] = fun;
this.evaluators_[store.locale] = mod;
}
/**
* Selects a default evaluation method by locale and modality. If none exists
* it takes the default evaluation method of the active combined store.
* @param locale The locale.
* @param modality The modality.
* @return The evaluation
* method.
*/
public getEvaluator(locale: string, modality: string):
(p1: Node) => AuditoryDescription[] {
let loc = this.evaluators_[locale];
// TODO: Do we need a fallback here?
return loc[modality];
}
/**
* Collates information on dynamic constraint values of the current state of
* the trie of the engine.
*
* @param opt_info Initial dynamic constraint information.
* @return The collated information.
*/
public enumerate(opt_info?: Object): Object {
return this.trie.enumerate(opt_info);
}
private constructor() {
/**
* Initialised the trie.
*/
this.trie = new Trie();
Engine.registerTest(() => this.ready_);
}
/**
* Computes a speech object for a given node. Returns the empty list if
* no node is given.
* @param node The node to be evaluated.
* @return A list of auditory descriptions
* for that node.
*/
private evaluateNode_(node: Element): AuditoryDescription[] {
if (!node) {
return [];
}
// Update the preferences of the dynamic constraint.
this.updateConstraint_();
return this.evaluateTree_(node);
}
/**
* Applies rules recursively to compute the final speech object.
* @param node Node to apply the speech rule to.
* @return A list of Auditory descriptions.
*/
private evaluateTree_(node: Element): AuditoryDescription[] {
let engine = Engine.getInstance();
let result: AuditoryDescription[];
Debugger.getInstance().output(
engine.mode !== EngineConst.Mode.HTTP ? node.toString() : node);
Grammar.getInstance().setAttribute(node);
let rule = this.lookupRule(node, engine.dynamicCstr);
if (!rule) {
if (engine.strict) {
return [];
}
result = this.getEvaluator(engine.locale, engine.modality)(node);
if (node.attributes) {
this.addPersonality_(result, {}, false, node);
}
return result;
}
Debugger.getInstance().generateOutput(() => [
'Apply Rule:', rule.name, rule.dynamicCstr.toString(),
(engine.mode !== EngineConst.Mode.HTTP ? node : node).toString()
]);
let context = rule.context;
let components = rule.action.components;
result = [];
for (let i = 0, component; component = components[i]; i++) {
let descrs: AuditoryDescription[] = [];
let content = component.content || '';
let attributes = component.attributes || {};
let multi = false;
if (component.grammar) {
this.processGrammar(context, node, component.grammar);
}
let saveEngine = null;
// Retooling the engine
if (attributes.engine) {
saveEngine = Engine.getInstance().dynamicCstr.getComponents();
let features = Grammar.parseInput(attributes.engine);
Engine.getInstance().setDynamicCstr(features as AxisMap);
}
switch (component.type) {
case ActionType.NODE:
let selected = context.applyQuery(node, content) as Element;
if (selected) {
descrs = this.evaluateTree_(selected);
}
break;
case ActionType.MULTI:
multi = true;
let selects = context.applySelector(node, content) as Element[];
if (selects.length > 0) {
descrs = this.evaluateNodeList_(
context, selects, attributes['sepFunc'],
// TODO (span): Sort out those types better.
(context.constructString(node, attributes['separator']) as
string),
attributes['ctxtFunc'],
(context.constructString(node, attributes['context']) as
string));
}
break;
case ActionType.TEXT:
// TODO (span): We need the span concept here as a parameter with
// xpath.
let xpath = attributes['span'];
let attrs: {[key: string]: string} = {};
if (xpath) {
let nodes = XpathUtil.evalXPath(xpath, node);
// TODO: Those could be multiple nodes!
// We need the right xpath expression and combine their
// attributes.
// Generalise the following:
if (nodes.length) {
attrs.extid = (nodes[0] as Element).getAttribute('extid');
}
}
let str = context.constructString(node, content) as string|Span[];
if (str) {
if (Array.isArray(str)) {
descrs = str.map(function(span) {
return AuditoryDescription.create(
{text: span.speech, attributes: span.attributes},
{adjust: true});
});
} else {
descrs = [AuditoryDescription.create(
{text: str, attributes: attrs}, {adjust: true})];
}
}
break;
case ActionType.PERSONALITY:
default:
descrs = [AuditoryDescription.create({text: content})];
}
// Adding overall context and annotation if they exist.
if (descrs[0] && !multi) {
if (attributes['context']) {
descrs[0]['context'] =
context.constructString(node, attributes['context']) +
(descrs[0]['context'] || '');
}
if (attributes['annotation']) {
descrs[0]['annotation'] = attributes['annotation'];
}
}
this.addLayout(descrs, attributes, multi);
if (component.grammar) {
Grammar.getInstance().popState();
}
// Adding personality to the auditory descriptions.
result =
result.concat(this.addPersonality_(descrs, attributes, multi, node));
if (saveEngine) {
Engine.getInstance().setDynamicCstr(saveEngine);
}
}
return result;
}
/**
* Evaluates a list of nodes into a list of auditory descriptions.
* @param context The function context in which to
* evaluate the nodes.
* @param nodes Array of nodes.
* @param sepFunc Name of a function used to compute a separator
* between every element.
* @param sepStr A string that is used as argument to the sepFunc or
* interspersed directly between each node if sepFunc is not supplied.
* @param ctxtFunc Name of a function applied to compute the context
* for every element in the list.
* @param ctxtStr Additional context string that is given to the
* ctxtFunc function or used directly if ctxtFunc is not supplied.
* @return A list of Auditory descriptions.
*/
private evaluateNodeList_(
context: SpeechRuleContext, nodes: Element[], sepFunc: string,
sepStr: string, ctxtFunc: string,
ctxtStr: string): AuditoryDescription[] {
if (nodes === []) {
return [];
}
let sep = sepStr || '';
let cont = ctxtStr || '';
let cFunc = context.contextFunctions.lookup(ctxtFunc);
let ctxtClosure = cFunc ? cFunc(nodes, cont) : function() {
return cont;
};
let sFunc = context.contextFunctions.lookup(sepFunc);
let sepClosure = sFunc ? sFunc(nodes, sep) : function() {
return [AuditoryDescription.create({text: sep}, {translate: true})];
};
let result: AuditoryDescription[] = [];
for (let i = 0, node; node = nodes[i]; i++) {
let descrs = this.evaluateTree_(node);
if (descrs.length > 0) {
descrs[0]['context'] = ctxtClosure() + (descrs[0]['context'] || '');
result = result.concat(descrs);
if (i < nodes.length - 1) {
let text = sepClosure() as AuditoryDescription[];
result = result.concat(text);
}
}
}
return result;
}
/**
* Adds layout annotations to the auditory descriptions
* @param descrs The auditory descriptions.
* @param props The properties.
* @param _multi Is is a multi node component. Currently ignored.
*/
private addLayout(
descrs: AuditoryDescription[], props: {[key: string]: string},
_multi: boolean) {
let layout = props.layout;
if (!layout) {
return;
}
if (layout.match(/^begin/)) {
descrs.unshift(new AuditoryDescription({text: '', layout: layout}));
return;
}
if (layout.match(/^end/)) {
descrs.push(new AuditoryDescription({text: '', layout: layout}));
return;
}
descrs.unshift(new AuditoryDescription(
{text: '', layout: `begin${layout}`}));
descrs.push(new AuditoryDescription({text: '', layout: `end${layout}`}));
}
/**
* Adds personality to every Auditory Descriptions in input list.
* @param descrs A list of Auditory
* descriptions.
* @param props Property dictionary.
* @param multi Multinode flag.
* @param node The original XML node.
* @return The modified array.
*/
private addPersonality_(
descrs: AuditoryDescription[], props: {[key: string]: string},
multi: boolean, node: Node): AuditoryDescription[] {
let personality: {[key: string]: string|number} = {};
let pause = null;
for (let key of EngineConst.personalityPropList) {
let value = props[key];
if (typeof value === 'undefined') {
continue;
}
let numeral = parseFloat(value);
// if (!isNaN(numeral)) {
// personality[sre.Engine.personalityProps[key]] = numeral;
// }
let realValue = isNaN(numeral) ?
value.charAt(0) === '"' ? value.slice(1, -1) : value :
numeral;
if (key === EngineConst.personalityProps.PAUSE) {
pause = realValue;
} else {
personality[key] = realValue;
}
}
// TODO: Deal with non-numeric values for personalities here.
// Possibly use simply an overwrite mechanism without adding.
for (let i = 0, descr; descr = descrs[i]; i++) {
this.addRelativePersonality_(descr, personality as {[key: string]: string});
this.addExternalAttributes_(descr, node as Element);
}
// Removes the last joiner in a multi node element.
if (multi && descrs.length) {
delete descrs[descrs.length - 1]
.personality[EngineConst.personalityProps.JOIN];
}
// Adds pause if there was one.
if (pause && descrs.length) {
let last = descrs[descrs.length - 1];
if (last.text || Object.keys(last.personality).length) {
descrs.push(AuditoryDescription.create(
{text: '', personality: {pause: pause as string}}));
} else {
last.personality[EngineConst.personalityProps.PAUSE] = pause as string;
}
}
return descrs;
}
/**
* Adds external attributes if some are in the node
* @param descr An Auditory descriptions.
* @param node The XML node.
*/
private addExternalAttributes_(descr: AuditoryDescription, node: Element) {
if (node.hasAttributes()) {
let attrs = node.attributes;
for (let i = attrs.length - 1; i >= 0; i--) {
let key = attrs[i].name;
if (!descr.attributes[key] && key.match(/^ext/)) {
descr.attributes[key] = attrs[i].value;
}
}
}
}
/**
* Adds relative personality entries to the personality of a Auditory
* Description.
* @param descr Auditory Description.
* @param personality Dictionary with relative personality entries.
* @return Updated description.
*/
private addRelativePersonality_(
descr: AuditoryDescription, personality: {[key: string]: string}): AuditoryDescription {
if (!descr['personality']) {
descr['personality'] = personality;
return descr;
}
let descrPersonality = descr['personality'];
for (let p in personality) {
// This could be capped by some upper and lower bound.
if (descrPersonality[p] && typeof descrPersonality[p] == 'number' &&
typeof personality[p] == 'number') {
descrPersonality[p] = descrPersonality[p] + personality[p];
} else if (!descrPersonality[p]) {
descrPersonality[p] = personality[p];
}
}
return descr;
}
/**
* Enriches the dynamic constraint with default properties.
*/
// TODO: Exceptions and ordering between locale and modality?
// E.g, missing clearspeak defaults to mathspeak.
// What if there is no default for a particular locale or modality?
// We need a default constraint specification somewhere that defines the
// orders.
// Try to make this dependent on the order of the dynamicCstr.
private updateConstraint_() {
let dynamic = Engine.getInstance().dynamicCstr;
let strict = Engine.getInstance().strict;
let trie = this.trie;
let props: {[key: string]: string[]} = {};
let locale = dynamic.getValue(Axis.LOCALE);
let modality = dynamic.getValue(Axis.MODALITY);
let domain = dynamic.getValue(Axis.DOMAIN);
if (!trie.hasSubtrie([locale, modality, domain])) {
domain = DynamicCstr.DEFAULT_VALUES[Axis.DOMAIN];
if (!trie.hasSubtrie([locale, modality, domain])) {
modality = DynamicCstr.DEFAULT_VALUES[Axis.MODALITY];
if (!trie.hasSubtrie([locale, modality, domain])) {
locale = DynamicCstr.DEFAULT_VALUES[Axis.LOCALE];
}
}
}
props[Axis.LOCALE] = [locale];
// Normally modality cannot be mixed. But summary allows fallback to speech
// if an expression can not be summarised.
props[Axis.MODALITY] =
[modality !== 'summary' ?
modality :
DynamicCstr.DEFAULT_VALUES[Axis.MODALITY]];
// For speech we do not want rule leaking across rule sets.
props[Axis.DOMAIN] =
[modality !== 'speech' ?
DynamicCstr.DEFAULT_VALUES[Axis.DOMAIN] :
domain];
let order = dynamic.getOrder();
for (let i = 0, axis; axis = order[i]; i++) {
if (!props[axis]) {
let value = dynamic.getValue(axis);
let valueSet =
this.makeSet_(value, (dynamic as ClearspeakPreferences).preference);
let def = DynamicCstr.DEFAULT_VALUES[axis];
if (!strict && value !== def) {
valueSet.push(def);
}
props[axis] = valueSet;
}
}
dynamic.updateProperties(props);
}
/**
* Splits preference form style names into set of preference settings.
* @param value The value of the style setting.
* @param preferences Set of Clearspeak preferences or null.
* @return The style settings. Either a single element or a
* pair associating a Clearspeak preference with a value.
*/
private makeSet_(value: string, preferences: {[key: string]: string}|null):
string[] {
if (!preferences || !Object.keys(preferences).length) {
return [value];
}
return value.split(':');
}
/**
* Retrieves a rule for the given node if one exists.
* @param node A node.
* @param dynamic Additional dynamic
* constraints. These are matched against properties of a rule.
* @return The speech rule if an applicable one exists.
*/
public lookupRule(node: Node, dynamic: DynamicCstr) {
if (!node ||
node.nodeType !== DomUtil.NodeType.ELEMENT_NODE &&
node.nodeType !== DomUtil.NodeType.TEXT_NODE) {
return null;
}
let matchingRules = this.lookupRules(node, dynamic);
return matchingRules.length > 0 ?
this.pickMostConstraint_(dynamic, matchingRules) :
null;
}
/**
* Retrieves a list of applicable rule for the given node.
* @param node A node.
* @param dynamic Additional dynamic
* constraints. These are matched against properties of a rule.
* @return All applicable speech rules.
*/
public lookupRules(node: Node, dynamic: DynamicCstr): SpeechRule[] {
return this.trie.lookupRules(node, dynamic.allProperties());
}
/**
* Picks the result of the most constraint rule by prefering those:
* 1) that best match the dynamic constraints.
* 2) with the most additional constraints.
* @param dynamic Dynamic constraints.
* @param rules An array of rules.
* @return The most constraint rule.
*/
private pickMostConstraint_(_dynamic: DynamicCstr, rules: SpeechRule[]):
SpeechRule {
let comparator = Engine.getInstance().comparator;
rules.sort(function(r1, r2) {
return comparator.compare(r1.dynamicCstr, r2.dynamicCstr) ||
// When same number of dynamic constraint attributes matches for
// both rules, compare
// 1. Computed priority value
// 2. length of static constraints,
// 3. Rank in the definition. Note that later rules
// supersede earlier ones.
r2.precondition.priority - r1.precondition.priority ||
r2.precondition.constraints.length -
r1.precondition.constraints.length ||
r2.precondition.rank - r1.precondition.rank;
});
Debugger.getInstance().generateOutput((() => {
return rules.map((x) => x.name + '(' + x.dynamicCstr.toString() + ')');
}).bind(this));
return rules[0];
}
/**
* Prunes the trie of the store for a given constraint.
* @param constraints A list of constraints.
*/
public pruneTrie(constraints: string[]) {
let last = constraints.pop();
let parent = this.trie.byConstraint(constraints);
if (parent) {
parent.removeChild(last);
}
}
}
export namespace StoreFactory {
const stores: Map<string, BaseRuleStore> = new Map();
/**
* Factory method for generating rule stores by modality.
* @param modality The modality.
* @return The generated rule store.
*/
function factory(modality: string): BaseRuleStore {
// TODO (TS): Not sure how to get the constructors directly
// let constructors = {braille: BrailleStore, speech: MathStore};
// return new (constructors[modality] || MathStore)();
if (modality === 'braille') {
return new BrailleStore();
}
return new MathStore();
}
export function get(set: RulesJson) {
let name = `${set.locale}.${set.modality}.${set.domain}`;
if (set.kind === 'actions') {
let store = stores.get(name);
store.parse(set);
return store;
}
SpeechRuleStores.init();
if (set && !set.functions) {
set.functions = SpeechRules.getStore(
set.locale, set.modality, set.domain);
}
let store = factory(set.modality);
stores.set(name, store);
if (set.inherits) {
store.inherits = stores.get(
`${set.inherits}.${set.modality}.${set.domain}`);
}
store.parse(set);
store.initialize();
return store;
}
} | the_stack |
import {CommonUtils} from "../../common/core/utils/common-utils";
declare const $: any;
export class ChartIconPie {
delimiter?: string = null;
fill?: string[] | ((...any) => string) = ["#ff9900", "#fff4dd", "#ffd592"];
height?: number = null;
radius?: number = 8;
width?: number = null;
}
export class ChartIconDonut {
delimiter?: string = null;
fill?: string[] = ["#ff9900", "#fff4dd", "#ffd592"];
height?: number = null;
innerRadius?: number = null;
radius?: number = 8;
width?: number = null;
}
export class ChartIconLine {
delimiter?: string = ",";
fill?: string = "#c6d9fd";
height?: number = 16;
max?: number = null;
min?: number = 0;
stroke?: string = "#4d89f9";
strokeWidth?: number = 1;
width?: number = 32;
}
export class ChartIconBar {
delimiter?: string = ",";
fill?: string[] = ["#4d89f9"];
height?: number = 16;
max?: number = null;
min?: number = 0;
padding?: number = 0.1;
width?: number = 32;
}
export class ChartIconCustomPieLegend {
/**
* orient只有top和right两个值
* - 如果是right,图例的默认宽度是100,用户也可以自定义
* - 如果是top,图例的高度是自动算出来的,所以height属性不需要配置,width也不用配置
*/
orient: string;
data: string[];
width: number;
height?: number;
marginLeft: number;
}
export class ChartIconCustomPie {
delimiter?: string = null;
fill?: string[] | ((...any) => string) = ["#ff9900", "#fff4dd", "#ffd592"];
height?: number = null;
radius?: number = 8;
width?: number = null;
legend?: ChartIconCustomPieLegend;
series?: any;
after?: Function;
link?: Function | string;
/**
* 当没有title,默认使用legend.data
*/
title: string[];
context?: object;
}
export enum ChartType {
pie, donut, line, bar, customPie
}
export type ChartIconOptions = ChartIconPie | ChartIconDonut | ChartIconLine | ChartIconBar | ChartIconCustomPie;
// @dynamic
export class ChartIconFactory {
public static create(selector: string | HTMLElement, chartType: ChartType, options: ChartIconOptions): any {
return $(selector).peity(this._chartTypeMap.get(chartType), options);
}
private static _chartTypeMap = new Map([
[ChartType.pie, 'pie'],
[ChartType.donut, 'donut'],
[ChartType.line, 'line'],
[ChartType.bar, 'bar'],
[ChartType.customPie, 'customPie']
]);
public static registerCustomPie() {
$.fn.peity.register('customPie', {
fill: ['#ff9900', '#fff4dd', '#ffc66e'],
radius: 8,
legend: {
orient: 'top',
width: 100,
height: 100,
data: []
}
},
function (opts) {
if (!opts.delimiter) {
let delimiter = this.$el.text().match(/[^0-9.]/);
opts.delimiter = delimiter ? delimiter[0] : ","
}
let values = $.map(this.values(), function (n) {
return n > 0 ? n : 0
});
if (opts.delimiter == "/") {
let v1 = values[0];
let v2 = values[1];
values = [v1, Math.max(0, v2 - v1)]
}
let i = 0;
let length = values.length;
let sum = 0;
for (; i < length; i++) {
sum += values[i]
}
if (!sum) {
length = 2;
sum = 1;
values = [0, 1];
}
let diameter = opts.radius * 2;
let legendWidth = 0,
legendHeight = 0,
pieOffsetX = 0,
pieOffsetY = 0;
if (opts.legend.orient == 'top') {
legendHeight = 14 * length + 5;
pieOffsetY = legendHeight / 2;
} else if (opts.legend.orient == 'right') {
legendWidth = opts.legend.width + 20;
pieOffsetX = legendWidth / 2;
}
let $svg = this.prepare(
(opts.width || diameter) + legendWidth,
(opts.height || diameter) + legendHeight
);
let width = $svg.width(),
height = $svg.height(),
cx = width / 2 - pieOffsetX,
cy = height / 2 + pieOffsetY;
if (this.$el.text().replace(/\s+/g, '') === '') {
// 没有数据
$svg.remove();
this.$svg = null;
if (!this.$box) {
this.$box = $('<div class="peity-no-data"></div>');
}
this.$el.hide().after(this.$box);
this.$box.empty().append(`<image width="${width}" height="${height}" src="${CommonUtils.noDataImageSrc}">`);
return;
} else {
if (this.$box) {
this.$box.remove();
this.$box = null;
}
}
let radius = Math.min(cx, cy),
innerRadius = opts.innerRadius;
if (this.type == 'donut' && !innerRadius) {
innerRadius = radius * 0.5
}
let pi = Math.PI;
let fill = this.fill();
let scale = this.scale = function (value, radius) {
let radians = value / sum * pi * 2 - pi / 2;
return [
radius * Math.cos(radians) + cx + '',
radius * Math.sin(radians) + cy + ''
]
};
let cumulative = 0;
for (let i = 0; i < length; i++) {
let value = values[i]
, portion = value / sum
, $node;
if (portion == 0) continue;
if (portion == 1) {
if (innerRadius) {
let x2 = cx - 0.01
, y1 = cy - radius
, y2 = cy - innerRadius;
$node = this.svgElement('path', {
d: [
'M', cx, y1,
'A', radius, radius, 0, 1, 1, x2, y1,
'L', x2, y2,
'A', innerRadius, innerRadius, 0, 1, 0, cx, y2
].join(' ')
})
} else {
$node = this.svgElement('circle', {
cx: cx,
cy: cy,
r: radius
})
}
} else {
let cumulativePlusValue = cumulative + value;
let d = ['M'].concat(
scale(cumulative, radius),
'A', radius + '', radius + '', 0 + '', (portion > 0.5 ? 1 : 0) + '', 1 + '',
scale(cumulativePlusValue, radius),
'L'
);
if (innerRadius) {
d = d.concat(
scale(cumulativePlusValue, innerRadius),
'A', innerRadius, innerRadius, 0 + '', (portion > 0.5 ? 1 : 0) + '', 0 + '',
scale(cumulative, innerRadius)
)
} else {
d.push(cx + '', cy + '')
}
cumulative += value;
$node = this.svgElement('path', {
d: d.join(" ")
})
}
$node.attr('fill', fill.call(this, value, i, values));
if (opts.title && !(opts.title instanceof Array)) {
throw('customPie\'s title must be type of array');
}
if (opts.legend && !(opts.legend.data instanceof Array)) {
throw('customPie\'s legend data must be type of array');
}
// 饼图链接
// 图形的title如果没有,使用图例的data
let $title = this.svgElement('title', {})
.text(opts.title ? opts.title[i] : opts.legend.data[i]);
let $link = this.svgElement('a', {'href': 'javascript:;'})
.append($title)
.append($node);
if (opts.link instanceof Function) {
if (opts.context) {
$link.bind('click', () => {
opts.link.call(opts.context, opts.series, i);
});
} else {
$link.bind('click', () => {
opts.link(opts.series, i);
});
}
} else if (typeof opts.link === 'string') {
$link.attr('href', opts.link);
}
// 绘制图例
let $legendTitle = this.svgElement('title', {})
.text(opts.legend.data[i]);
let $legend = this.svgElement('g', {x: '0', y: i * 10});
$legend.append($legendTitle);
let legendPositionX = 0;
if(opts.legend.orient == 'right'){
if(Number.isNaN(Number(opts.legend.marginLeft))){
opts.legend.marginLeft = 20;
}
legendPositionX = diameter + Number(opts.legend.marginLeft);
}
let $rect = this.svgElement('rect', {
x: legendPositionX,
y: 1 + i * 14,
width: 10,
height: 10,
'fill': fill.call(this, value, i, values)
});
let $text = this.svgElement('text', {
x: 12 + legendPositionX,
y: 10 + i * 14,
'font-size': 12
}).text(opts.legend.data[i]);
$legend.append($rect).append($text);
// 等待text渲染
Promise.resolve().then(() => {
const rangeWidth = (opts.legend.orient == 'right' ? opts.legend.width : width) - 12;
if ($text.width() > rangeWidth) {
// 加入省略号
let $ellipsis = this.svgElement('text', {
x: width - 9,
y: 9 + i * 14,
'font-size': 12
}).text('...');
let $ellipsisBg = this.svgElement('rect', {
x: width - 10,
y: i * 14 - 1,
width: 10,
height: 16,
fill: '#fff'
});
$legend.append($ellipsisBg).append($ellipsis);
}
});
$svg.append($link);
$svg.append($legend);
}
}
)
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.