text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { Injectable, EventEmitter } from '@angular/core'; import { Http } from '@angular/http'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import 'rxjs/add/operator/toPromise'; import * as _ from 'lodash'; import { environment } from '../../environments/environment'; import { handleError, parseJson, packageForPost } from './http-helpers'; import { Conference, TimeSlot } from './conference.model'; @Injectable() export class AdminService { baseUrl = environment.production ? '' : 'http://localhost:3000'; allConferences: Conference[] = []; archivedConferences: Conference[] = []; conferences: Conference[] = []; activeConference: BehaviorSubject<Conference> = new BehaviorSubject(null); defaultConference: BehaviorSubject<Conference> = new BehaviorSubject(null); triggerSessionUpdate: EventEmitter<any> = new EventEmitter(); triggerSpeakerUpdate: EventEmitter<any> = new EventEmitter(); constructor(private http: Http) { } createConference(title: string, venueName: string, venueAddress: string, startDate: string, endDate: string) { this.resetActiveConfs(); this.resetDefaultConfs(); let newConf: Conference = { archived: false, lastActive: true, defaultConf: true, title: title, venueName: venueName, venueAddress: venueAddress, uploads: [], dateRange: { start: startDate, end: endDate } }; this.allConferences.push(newConf); this.setFilterAndSort(); this.activeConference.next(newConf); this.defaultConference.next(newConf); let pkg = packageForPost(newConf); return this.http .post(this.baseUrl + '/api/createconference', pkg.body, pkg.opts) .toPromise() .then(parseJson) .catch(handleError); } changeActiveConf(confTitle: string) { let conf = _.find(this.allConferences, conf => conf.title === confTitle); this.resetActiveConfs(); conf.lastActive = true; this.activeConference.next(conf); let pkg = packageForPost(conf); return this.http .post(this.baseUrl + '/api/changeactiveconf', pkg.body, pkg.opts) .toPromise() .then(parseJson) .catch(handleError); } changeDefaultConf(confTitle: string) { let conf = _.find(this.allConferences, conf => conf.title === confTitle); this.resetDefaultConfs(); conf.defaultConf = true; this.defaultConference.next(conf); let pkg = packageForPost(conf); return this.http .post(this.baseUrl + '/api/changedefaultconf', pkg.body, pkg.opts) .toPromise() .then(parseJson) .catch(handleError); } resetActiveConfs() { this.conferences.forEach(conf => { conf.lastActive = false; }); } resetDefaultConfs() { this.conferences.forEach(conf => { conf.defaultConf = false; }); } deleteUpload(uploadToDel: {title: string; url: string;}) { let conf = this.defaultConference.getValue(); let uploadIndex = _.findIndex(conf.uploads, upload => { if (upload.title === uploadToDel.title && upload.url === uploadToDel.url) { return true; } }); conf.uploads.splice(uploadIndex, 1); this.defaultConference.next(conf); return this.http .post(this.baseUrl + '/api/deleteupload', conf) .toPromise() .then(parseJson) .catch(handleError); } archiveConf(confTitle: string, archive: boolean) { let conf = _.find(this.allConferences, conf => conf.title === confTitle); conf.archived = archive; this.setFilterAndSort(); let pkg = packageForPost(conf); return this.http .post(this.baseUrl + '/api/archiveconf', pkg.body, pkg.opts) .toPromise() .then(parseJson) .catch(handleError); } updateConference(currentTitle: string, newTitle: string, newVenueName: string, newVenueAddress: string) { let conference = _.find(this.allConferences, conf => conf.title === currentTitle); conference.title = newTitle; conference.venueName = newVenueName; conference.venueAddress = newVenueAddress; let pkg = packageForPost({currentTitle: currentTitle, conference: conference}); return this.http .post(this.baseUrl + '/api/updateconference', pkg.body, pkg.opts) .toPromise() .then(parseJson) .then(res => { this.triggerSessionUpdate.emit('update'); return res; }) .catch(handleError); } addConfUpload(conf: Conference) { return this.http .post(this.baseUrl + '/api/addconfupload', conf) .toPromise() .then(parseJson) .then(res => { // Uploads go to current defualt conf, update it this.defaultConference.next(res); }); } addTimeslot(startTime: string, endTime: string, conferenceTitle: string, date: string) { let newTimeSlot = {start: startTime, end: endTime}; /* let conference = _.find(this.allConferences, conf => conf.title === conferenceTitle); let confDate = _.find(conference.days, day => day.date === date); // Shallow clone to prevent premature updates let confCopy = _.clone(conference); let confDateCopy = _.find(confCopy.days, day => day.date === date); // If day has no slots yet, make it and add the new slot if (typeof confDateCopy === 'undefined') { if (typeof confCopy.days === 'undefined') confCopy.days = []; let newDay: (any) = { date: date, timeSlots: [newTimeSlot] }; confCopy.days.push(newDay); } else { confDateCopy.timeSlots.push(newTimeSlot); }*/ let pkg = packageForPost({title: conferenceTitle, newSlot: newTimeSlot, date: date }); return this.http .post(this.baseUrl + '/api/addtimeslot', pkg.body, pkg.opts) .toPromise() .then(parseJson) .then(serverConf => { // Need slot ID this.getAllConferences(); return serverConf; }) .catch(handleError); } sortConfSlotsAndDays(conf: Conference) { if (!conf.days) { return; } conf.days.forEach(day => { day.timeSlots = _.sortBy(day.timeSlots, slot => slot.end); }); conf.days = _.sortBy(conf.days, day => day.date); return conf; } /** Find slot within active conference by its id */ findSlotById(slotId): TimeSlot { let slot: TimeSlot; this.defaultConference.getValue().days.forEach(day => { let reqSlot = _.find(day.timeSlots, slot => slot._id === slotId); if (typeof reqSlot !== 'undefined') { slot = reqSlot; } }); return slot; } findDateBySlot(slotId: string) { let date: string; this.defaultConference.getValue().days.forEach(day => { let reqSlot = _.find(day.timeSlots, daySlot => daySlot._id === slotId); if (typeof reqSlot !== 'undefined') { date = day.date; } }); return date; } addRoom(conferenceTitle: string, room: string) { let conf = _.find(this.allConferences, conf => conf.title === conferenceTitle); if (!conf.rooms) { conf.rooms = []; } // Sync front end conf.rooms.push(room); if (conf.title === this.activeConference.getValue().title) { this.activeConference.next(conf); } let pkg = packageForPost(conf); return this.http .post(this.baseUrl + '/api/addRoom', pkg.body, pkg.opts) .toPromise() .then(parseJson) .catch(handleError); } moveRoom(conferenceTitle: string, room: string, direction: string) { let conf = _.find(this.allConferences, conf => conf.title === conferenceTitle); let roomStarti = conf.rooms.indexOf(room); let roomEndi = direction === '+' ? roomStarti + 1 : roomStarti - 1; if (roomEndi > conf.rooms.length - 1 || roomEndi < 0) { return; } let roomsDupe = conf.rooms.slice(); let displacedRoom = roomsDupe[roomEndi]; conf.rooms[roomStarti] = displacedRoom; conf.rooms[roomEndi] = room; let pkg = packageForPost(conf); return this.http .post(this.baseUrl + '/api/updateconfrooms', pkg.body, pkg.opts) .toPromise() .then(parseJson) .catch(handleError); } getAllConferences() { return this.http .get(this.baseUrl + '/api/getallconferences') .toPromise() .then(parseJson) .then(conferences => { this.allConferences = conferences; this.setFilterAndSort(); let activeConf = _.find(this.allConferences, conf => conf.lastActive === true); this.activeConference.next(activeConf); let defaultConf = _.find(this.allConferences, conf => conf.defaultConf === true); this.defaultConference.next(defaultConf); return conferences; }) .catch(handleError); } /** Update conference filters */ setFilterAndSort() { // Sort conferences in reverse order(2017 first, 2016 second...) this.allConferences = _.reverse(_.sortBy(this.allConferences, conf => conf.title)); this.allConferences.forEach(conf => { conf = this.sortConfSlotsAndDays(conf); }); this.archivedConferences = _.filter(this.allConferences, conf => conf.archived); this.conferences = _.filter(this.allConferences, conf => !conf.archived); } }
the_stack
import { StorageTypes } from '@requestnetwork/types'; import { EventEmitter } from 'events'; import * as http from 'http'; import IpfsManager from '../src/ipfs-manager'; const ipfsGatewayConnection: StorageTypes.IIpfsGatewayConnection = { host: 'localhost', port: 5001, protocol: StorageTypes.IpfsGatewayProtocol.HTTP, timeout: 1000, }; const invalidHostIpfsGatewayConnection: StorageTypes.IIpfsGatewayConnection = { host: 'nonexistent', port: 5001, protocol: StorageTypes.IpfsGatewayProtocol.HTTP, timeout: 1000, }; const invalidProtocolIpfsGatewayConnection: StorageTypes.IIpfsGatewayConnection = { host: 'localhost', port: 5001, protocol: 'invalidprotocol' as StorageTypes.IpfsGatewayProtocol, timeout: 1000, }; const testErrorHandling: StorageTypes.IIpfsErrorHandlingConfiguration = { delayBetweenRetries: 0, maxRetries: 0, }; const retryTestErrorHandling: StorageTypes.IIpfsErrorHandlingConfiguration = { delayBetweenRetries: 0, maxRetries: 3, }; let ipfsManager: IpfsManager; const content = 'this is a little test !'; const hash = 'QmNXA5DyFZkdf4XkUT81nmJSo3nS2bL25x7YepxeoDa6tY'; const content2 = 'content\nwith\nspecial\ncharacters\n'; const hash2 = 'QmQj8fQ9T16Ddrxfij5eyRnxXKTVxRXyQuazYnezt9iZpy'; const notAddedHash = 'QmXnnyufdzAWL5CqZ2RnSNgPbvCc1ALT73sNonExisting'; // Content length stored on ipfs is slightly superior to actual content length // because of some stream data stored into ipfs const contentLengthOnIpfs = 29; const contentLengthOnIpfs2 = 38; /* eslint-disable no-magic-numbers */ describe('Ipfs manager', () => { beforeEach(() => { ipfsManager = new IpfsManager(ipfsGatewayConnection, testErrorHandling); }); it('allows to verify repository', async () => { await ipfsManager.getIpfsNodeId(); ipfsManager = new IpfsManager(invalidHostIpfsGatewayConnection, testErrorHandling); await expect(ipfsManager.getIpfsNodeId()).rejects.toThrowError('getaddrinfo ENOTFOUND'); }); it('allows to get the bootstrap list', async () => { const bootstrapList = await ipfsManager.getBootstrapList(); expect(bootstrapList).toHaveProperty('length'); }); it('must throw if the ipfs node is not reachable when using getBootstrapList()', async () => { ipfsManager = new IpfsManager(invalidHostIpfsGatewayConnection, testErrorHandling); await expect(ipfsManager.getBootstrapList()).rejects.toThrowError('getaddrinfo ENOTFOUND'); }); it('allows to add files to ipfs', async () => { let hashReturned = await ipfsManager.add(content); expect(hash).toBe(hashReturned); hashReturned = await ipfsManager.add(content2); expect(hash2).toBe(hashReturned); }); it('allows to pin one file ipfs', async () => { const pinnedHash = await ipfsManager.pin([hash]); expect(hash).toBe(pinnedHash[0]); }); it('allows to pin multiple files to ipfs', async () => { const pinnedHashes = await ipfsManager.pin([hash, hash2]); expect([hash, hash2]).toMatchObject(pinnedHashes); }); it('allows to read files from ipfs', async () => { await ipfsManager.add(content); let contentReturned = await ipfsManager.read(hash, 36); expect(content).toBe(contentReturned.content); await ipfsManager.add(content2); contentReturned = await ipfsManager.read(hash2); expect(content2).toBe(contentReturned.content); }); it('must throw if max size reached', async () => { await ipfsManager.add(content); const maxSize = 10; await expect(ipfsManager.read(hash, maxSize)).rejects.toThrowError( `File size (63) exceeds the declared file size (${maxSize})`, ); }); it('allows to get file size from ipfs', async () => { let hashReturned = await ipfsManager.add(content); let sizeReturned = await ipfsManager.getContentLength(hashReturned); expect(contentLengthOnIpfs).toEqual(sizeReturned); hashReturned = await ipfsManager.add(content2); sizeReturned = await ipfsManager.getContentLength(hashReturned); expect(contentLengthOnIpfs2).toEqual(sizeReturned); }); it('operations with a invalid host network should throw ENOTFOUND errors', async () => { ipfsManager = new IpfsManager(invalidHostIpfsGatewayConnection, testErrorHandling); await expect(ipfsManager.add(content)).rejects.toThrowError('getaddrinfo ENOTFOUND'); await expect(ipfsManager.read(hash)).rejects.toThrowError('getaddrinfo ENOTFOUND'); await expect(ipfsManager.getContentLength(hash)).rejects.toThrowError('getaddrinfo ENOTFOUND'); }, 10000); it('read a non-existent hash on an existent network should throw a timeout error', async () => { await expect(ipfsManager.read(notAddedHash)).rejects.toThrowError('Ipfs read request timeout'); }); it('getContentLength on a non-existent hash on an existent network should throw a timeout error', async () => { await expect(ipfsManager.getContentLength(notAddedHash)).rejects.toThrowError( 'Ipfs stat request timeout', ); }); it('initializing ipfs-manager with default values should not throw an error', async () => { expect(() => new IpfsManager()).not.toThrow(); }); it('initializing ipfs-manager with an invalid protocol should throw an error', async () => { expect( () => new IpfsManager(invalidProtocolIpfsGatewayConnection, testErrorHandling), ).toThrowError('Protocol not implemented for IPFS'); }); it('aborting read request should throw an error', async () => { let hookedRequest: any; // Hook the get function of the protocol module to allow us to send customized event const requestHook = (request: string, _resCallback: any): EventEmitter => { // We filter the response of the request to prevent the promise to resolve // eslint-disable-next-line no-empty,@typescript-eslint/no-empty-function hookedRequest = http.get(request, (_res) => {}); return hookedRequest; }; const hookedIpfsConnectionModule = { get: requestHook }; ipfsManager.ipfsConnectionModule = hookedIpfsConnectionModule; setTimeout(() => hookedRequest.emit('abort'), 1000); await expect(ipfsManager.read(hash)).rejects.toThrowError('Ipfs read request has been aborted'); }); it('aborting read request response should throw an error', async () => { let hookedRequestResponse: any; // Hook the response of the request response to send customized event ot it const requestHook = (request: string, resCallback: any): EventEmitter => { hookedRequestResponse = new EventEmitter(); return http.get(request, (_res) => { resCallback(hookedRequestResponse); }); }; const hookedIpfsConnectionModule = { get: requestHook }; ipfsManager.ipfsConnectionModule = hookedIpfsConnectionModule; setTimeout(() => hookedRequestResponse.emit('aborted'), 1000); await expect(ipfsManager.read(hash)).rejects.toThrowError( 'Ipfs read request response has been aborted', ); }); it('error on read request response should throw an error', async () => { let hookedRequestResponse: any; // Hook the response of the request response to send customized event ot it const requestHook = (request: string, resCallback: any): EventEmitter => { hookedRequestResponse = new EventEmitter(); return http.get(request, (_res) => { resCallback(hookedRequestResponse); }); }; const hookedIpfsConnectionModule = { get: requestHook }; ipfsManager.ipfsConnectionModule = hookedIpfsConnectionModule; setTimeout(() => hookedRequestResponse.emit('error'), 1000); await expect(ipfsManager.read(hash)).rejects.toThrowError('Ipfs read request response error'); }); it('aborting getContentLength request should throw an error', async () => { let hookedRequest: any; // Hook the get function of the protocol module to allow us to send customized event const requestHook = (request: string, _resCallback: any): EventEmitter => { // eslint-disable-next-line no-empty,@typescript-eslint/no-empty-function hookedRequest = http.get(request, (_res) => {}); return hookedRequest; }; const hookedIpfsConnectionModule = { get: requestHook }; ipfsManager.ipfsConnectionModule = hookedIpfsConnectionModule; setTimeout(() => hookedRequest.emit('abort'), 1000); await expect(ipfsManager.getContentLength(hash)).rejects.toThrowError( 'Ipfs stat request has been aborted', ); }); it('aborting getContentLength request response should throw an error', async () => { let hookedRequestResponse: any; // Hook the response of the request response to send customized event ot it const requestHook = (request: string, resCallback: any): EventEmitter => { hookedRequestResponse = new EventEmitter(); return http.get(request, (_res) => { resCallback(hookedRequestResponse); }); }; const hookedIpfsConnectionModule = { get: requestHook }; ipfsManager.ipfsConnectionModule = hookedIpfsConnectionModule; setTimeout(() => hookedRequestResponse.emit('aborted'), 1000); await expect(ipfsManager.getContentLength(hash)).rejects.toThrowError( 'Ipfs stat request response has been aborted', ); }); it('error on getContentLength request response should throw an error', async () => { let hookedRequestResponse: any; // Hook the response of the request response to send customized event ot it const requestHook = (request: string, resCallback: any): EventEmitter => { hookedRequestResponse = new EventEmitter(); return http.get(request, (_res) => { resCallback(hookedRequestResponse); }); }; const hookedIpfsConnectionModule = { get: requestHook }; ipfsManager.ipfsConnectionModule = hookedIpfsConnectionModule; setTimeout(() => hookedRequestResponse.emit('error'), 1000); await expect(ipfsManager.getContentLength(hash)).rejects.toThrowError( 'Ipfs stat request response error', ); }); it('empty getContentLength request response should throw an error', async () => { let hookedRequestResponse: any; // Hook the response of the request response to send customized event ot it const requestHook = (request: string, resCallback: any): EventEmitter => { hookedRequestResponse = new EventEmitter(); return http.get(request, (_res) => { resCallback(hookedRequestResponse); }); }; const hookedIpfsConnectionModule = { get: requestHook }; ipfsManager.ipfsConnectionModule = hookedIpfsConnectionModule; // We emit end event directly, we will call end callball with no response data setTimeout(() => hookedRequestResponse.emit('end'), 1000); await expect(ipfsManager.getContentLength(hash)).rejects.toThrowError( 'Ipfs stat request response cannot be parsed into JSON format', ); }); it('getContentLength request response with no field DataSize should throw an error', async () => { let hookedRequestResponse: any; // Hook the response of the request response to send customized event ot it const requestHook = (request: string, resCallback: any): EventEmitter => { hookedRequestResponse = new EventEmitter(); return http.get(request, (_res) => { resCallback(hookedRequestResponse); }); }; const hookedIpfsConnectionModule = { get: requestHook }; ipfsManager.ipfsConnectionModule = hookedIpfsConnectionModule; // We emit custom json data with no DataSize field setTimeout(() => hookedRequestResponse.emit('data', `{"name":"John"}`), 500); setTimeout(() => hookedRequestResponse.emit('end'), 1000); await expect(ipfsManager.getContentLength(hash)).rejects.toThrowError( 'Ipfs stat request response has no DataSize field', ); }); it('timeout should not retry', async () => { ipfsManager = new IpfsManager(ipfsGatewayConnection, retryTestErrorHandling); await expect(ipfsManager.getContentLength(notAddedHash)).rejects.toThrowError( 'Ipfs stat request timeout', ); }); it.skip('error on read request should retry', async () => { ipfsManager = new IpfsManager(ipfsGatewayConnection, retryTestErrorHandling); let hookedGetResponse: any; const spy = jest.fn(); // Hook the response of the request response to send customized event ot it const getHook = (request: string, resCallback: any): EventEmitter => { hookedGetResponse = new EventEmitter(); return http.get(request, (_res) => { spy(); resCallback(hookedGetResponse); }); }; const hookedIpfsConnectionModule = { get: getHook }; ipfsManager.ipfsConnectionModule = hookedIpfsConnectionModule; // Fails for the original request, the retries and the last one that will fail for (let i = 0; i < retryTestErrorHandling.maxRetries + 2; i++) { setTimeout(() => hookedGetResponse.emit('error'), 100 + 100 * i); } await expect(ipfsManager.read(hash)).rejects.toThrowError('Ipfs read request response error'); expect(spy).toHaveBeenCalledTimes(5); }); it.skip('error on pin request should retry', async () => { ipfsManager = new IpfsManager(ipfsGatewayConnection, retryTestErrorHandling); let hookedGetResponse: any; const spy = jest.fn(); // Hook the response of the request response to send customized event ot it const getHook = (request: string, resCallback: any): EventEmitter => { hookedGetResponse = new EventEmitter(); return http.get(request, (_res) => { spy(); resCallback(hookedGetResponse); }); }; const hookedIpfsConnectionModule = { get: getHook }; ipfsManager.ipfsConnectionModule = hookedIpfsConnectionModule; // Fails for the original request, the retries and the last one that will fail for (let i = 0; i < retryTestErrorHandling.maxRetries + 2; i++) { setTimeout(() => hookedGetResponse.emit('error'), 100 + 100 * i); } await expect(ipfsManager.pin([hash])).rejects.toThrowError('Ipfs pin request response error'); expect(spy).toHaveBeenCalledTimes(5); }); it.skip('error on getContentLength request should retry', async () => { ipfsManager = new IpfsManager(ipfsGatewayConnection, retryTestErrorHandling); let hookedGetResponse: any; const spy = jest.fn(); // Hook the response of the request response to send customized event ot it const getHook = (request: string, resCallback: any): EventEmitter => { hookedGetResponse = new EventEmitter(); return http.get(request, (_res) => { spy(); resCallback(hookedGetResponse); }); }; const hookedIpfsConnectionModule = { get: getHook }; ipfsManager.ipfsConnectionModule = hookedIpfsConnectionModule; for (let i = 0; i < retryTestErrorHandling.maxRetries + 2; i++) { setTimeout(() => hookedGetResponse.emit('error'), 100 + 100 * i); } await expect(ipfsManager.getContentLength(hash)).rejects.toThrowError( 'Ipfs stat request response error', ); expect(spy).toHaveBeenCalledTimes(5); }); });
the_stack
import * as vscode from 'vscode'; import { AuthenticationClient, IBucket, IObject, DataManagementClient, ModelDerivativeClient, DesignAutomationClient, WebhooksClient, BIM360Client, IActivityDetail } from 'forge-server-utils'; import * as dmp from './providers/data-management'; import * as dap from './providers/design-automation'; import * as dmc from './commands/data-management'; import * as mdc from './commands/model-derivative'; import * as dac from './commands/design-automation'; import * as dai from './interfaces/design-automation'; import * as mdi from './interfaces/model-derivative'; import * as hi from './interfaces/hubs'; import { Region } from 'forge-server-utils/dist/common'; import { TemplateEngine, IContext } from './common'; import { WebhooksDataProvider, IWebhook, IWebhookEvent } from './providers/webhooks'; import { viewWebhookDetails, createWebhook, deleteWebhook, updateWebhook } from './commands/webhooks'; import { login, getAccessToken } from './commands/authentication'; import { HubsDataProvider } from './providers/hubs'; import { getEnvironments, setupNewEnvironment, IEnvironment } from './environments'; const DefaultAuthPort = 8123; // TODO: reuse the enum from forge-server-utils enum DesignAutomationRegion { US_WEST = 'us-west', US_EAST = 'us-east' } export function activate(_context: vscode.ExtensionContext) { const environments = getEnvironments(); if (environments.length === 0) { // If no environment is configured, offer a guided process for creating one using vscode UI setupNewEnvironment(); return; } let env = environments[0]; console.log('Extension "vscode-forge-tools" has been loaded.'); let context: IContext = { extensionContext: _context, credentials: { client_id: env.clientId, client_secret: env.clientSecret }, authenticationClient: new AuthenticationClient(env.clientId, env.clientSecret, env.host), dataManagementClient: new DataManagementClient({ client_id: env.clientId, client_secret: env.clientSecret }, env.host, env.region as Region), modelDerivativeClient2L: new ModelDerivativeClient({ client_id: env.clientId, client_secret: env.clientSecret }, env.host, env.region as Region), modelDerivativeClient3L: new ModelDerivativeClient({ token: '' }, env.host, env.region as Region), designAutomationClient: new DesignAutomationClient({ client_id: env.clientId, client_secret: env.clientSecret }, env.host, env.region as Region, env.designAutomationRegion as DesignAutomationRegion), webhookClient: new WebhooksClient({ client_id: env.clientId, client_secret: env.clientSecret }, env.host, env.region as Region), bim360Client: new BIM360Client({ client_id: env.clientId, client_secret: env.clientSecret }, env.host, env.region as Region), templateEngine: new TemplateEngine(), previewSettings: { extensions: vscode.workspace.getConfiguration(undefined, null).get<string[]>('autodesk.forge.viewer.extensions') || [], env: vscode.workspace.getConfiguration(undefined, null).get<string>('autodesk.forge.viewer.env'), api: vscode.workspace.getConfiguration(undefined, null).get<string>('autodesk.forge.viewer.api') } }; // Setup buckets view let simpleStorageDataProvider = new dmp.SimpleStorageDataProvider(context); let dataManagementView = vscode.window.createTreeView('forgeDataManagementView', { treeDataProvider: simpleStorageDataProvider }); context.extensionContext.subscriptions.push(dataManagementView); // Setup hubs view let hubsDataProvider = new HubsDataProvider(context); let hubsView = vscode.window.createTreeView('forgeHubsView', { treeDataProvider: hubsDataProvider }); context.extensionContext.subscriptions.push(hubsView); // Setup design automation view let designAutomationDataProvider = new dap.DesignAutomationDataProvider(context); let designAutomationView = vscode.window.createTreeView('forgeDesignAutomationView', { treeDataProvider: designAutomationDataProvider }); context.extensionContext.subscriptions.push(designAutomationView); // Setup webhooks view let webhooksDataProvider = new WebhooksDataProvider(context); let webhooksView = vscode.window.createTreeView('forgeWebhooksView', { treeDataProvider: webhooksDataProvider }); context.extensionContext.subscriptions.push(webhooksView); registerDataManagementCommands(simpleStorageDataProvider, context); registerModelDerivativeCommands(context, simpleStorageDataProvider, hubsDataProvider); registerDesignAutomationCommands(designAutomationDataProvider, context); registerWebhookCommands(webhooksDataProvider, context); function updateEnvironmentStatus(statusBarItem: vscode.StatusBarItem) { statusBarItem.text = 'Forge Env: ' + env.title; statusBarItem.command = 'forge.switchEnvironment'; statusBarItem.show(); } const envStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); context.extensionContext.subscriptions.push(envStatusBarItem); updateEnvironmentStatus(envStatusBarItem); function updateAuthStatus(statusBarItem: vscode.StatusBarItem) { if (context.threeLeggedToken) { statusBarItem.text = 'Forge Auth: 3-legged'; statusBarItem.command = 'forge.logout'; } else { statusBarItem.text = 'Forge Auth: 2-legged'; statusBarItem.command = 'forge.login'; } statusBarItem.show(); } const authStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); context.extensionContext.subscriptions.push(authStatusBarItem); updateAuthStatus(authStatusBarItem); vscode.commands.registerCommand('forge.login', async () => { try { const port = vscode.workspace.getConfiguration(undefined, null).get<number>('autodesk.forge.authentication.port') || DefaultAuthPort; const data = await login(env.clientId, port, context); const token = data.get('access_token'); const expires = data.get('expires_in'); const tokenType = data.get('token_type'); if (!token || !expires || tokenType !== 'Bearer') { throw new Error('Authentication data missing or incorrect.'); } context.threeLeggedToken = token; context.bim360Client.reset({ token: context.threeLeggedToken }, env.host, env.region as Region); delete (context.bim360Client as any).auth; // TODO: remove 'auth' in the reset method context.modelDerivativeClient3L.reset({ token: context.threeLeggedToken }, env.host, env.region as Region); hubsDataProvider.refresh(); updateAuthStatus(authStatusBarItem); vscode.window.showInformationMessage(`You are now logged in. Autodesk Forge services requiring 3-legged authentication will be available for as long as the generated token is valid (${expires} seconds), or until you manually log out.`); } catch (err) { vscode.window.showWarningMessage(`Could not log in: ${err}`); } }); vscode.commands.registerCommand('forge.logout', async () => { const answer = await vscode.window.showQuickPick(['Yes', 'No'], { placeHolder: 'Would you like to log out?' }); if (answer === 'Yes') { delete context.threeLeggedToken; context.bim360Client.reset(context.credentials, env.host, env.region as Region); delete (context.bim360Client as any).token; // TODO: remove 'token' in the reset method context.modelDerivativeClient3L.reset({ token: '' }, env.host, env.region as Region); hubsDataProvider.refresh(); updateAuthStatus(authStatusBarItem); vscode.window.showInformationMessage(`You are now logged out. Autodesk Forge services requiring 3-legged authentication will no longer be available.`); } }); vscode.commands.registerCommand('forge.switchEnvironment', async () => { const environments = getEnvironments(); const name = await vscode.window.showQuickPick(environments.map(env => env.title), { placeHolder: 'Select Forge environment' }); if (!name) { return; } env = environments.find(environment => environment.title === name) as IEnvironment; delete context.threeLeggedToken; context.credentials = { client_id: env.clientId, client_secret: env.clientSecret }; context.dataManagementClient.reset(context.credentials, env.host, env.region as Region); context.modelDerivativeClient2L.reset(context.credentials, env.host, env.region as Region); context.modelDerivativeClient3L.reset({ token: '' }, env.host, env.region as Region); context.designAutomationClient.reset(context.credentials, env.host, env.region as Region, env.designAutomationRegion as DesignAutomationRegion); context.webhookClient.reset(context.credentials, env.host, env.region as Region); context.bim360Client.reset(context.credentials, env.host, env.region as Region); context.authenticationClient = new AuthenticationClient(env.clientId, env.clientSecret, env.host); simpleStorageDataProvider.refresh(); designAutomationDataProvider.refresh(); hubsDataProvider.refresh(); webhooksDataProvider.refresh(); updateEnvironmentStatus(envStatusBarItem); }); } function registerWebhookCommands(webhooksDataProvider: WebhooksDataProvider, context: IContext) { vscode.commands.registerCommand('forge.refreshWebhooks', () => { webhooksDataProvider.refresh(); }); vscode.commands.registerCommand('forge.createWebhook', async (event: IWebhookEvent) => { // TODO: create webhooks from command palette await createWebhook(event, context, function () { webhooksDataProvider.refresh(event); }); }); vscode.commands.registerCommand('forge.updateWebhook', async (webhook: IWebhook) => { // TODO: update webhooks from command palette await updateWebhook(webhook, context, function () { webhooksDataProvider.refresh(); }); }); vscode.commands.registerCommand('forge.deleteWebhook', async (webhook: IWebhook) => { // TODO: delete webhooks from command palette await deleteWebhook(webhook, context); webhooksDataProvider.refresh(); }); vscode.commands.registerCommand('forge.viewWebhookDetails', async (webhook: IWebhook) => { // TODO: view webhook details from command palette await viewWebhookDetails(webhook, context); }); // Setup the rest vscode.commands.registerCommand('forge.getAccessToken', async () => { await getAccessToken(context); }); } function registerDesignAutomationCommands(designAutomationDataProvider: dap.DesignAutomationDataProvider, context: IContext) { vscode.commands.registerCommand('forge.refreshDesignAutomationTree', () => { designAutomationDataProvider.refresh(); }); vscode.commands.registerCommand('forge.createAppBundle', async () => { await dac.uploadAppBundle(undefined, context); designAutomationDataProvider.refresh(); }); vscode.commands.registerCommand('forge.updateAppBundle', async (entry?: dai.IAppBundleEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } await dac.uploadAppBundle(entry.appbundle, context); designAutomationDataProvider.refresh(); }); vscode.commands.registerCommand('forge.viewAppBundleDetails', async (entry?: dai.IAppBundleAliasEntry | dai.ISharedAppBundleEntry) => { if (entry) { await dac.viewAppBundleDetails('fullid' in entry ? entry.fullid : `${entry.client}.${entry.appbundle}+${entry.alias}`, context); } else { await dac.viewAppBundleDetails(undefined, context); } }); vscode.commands.registerCommand('forge.viewAppBundleVersionDetails', async (entry?: dai.IAppBundleVersionEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } await dac.viewAppBundleDetails({ name: entry.appbundle, version: entry.version }, context); }); vscode.commands.registerCommand('forge.deleteAppBundle', async (entry?: dai.IAppBundleEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } await dac.deleteAppBundle(entry.appbundle, context); designAutomationDataProvider.refresh(); }); vscode.commands.registerCommand('forge.deleteAppBundleAlias', async (entry?: dai.IAppBundleAliasEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } await dac.deleteAppBundleAlias(entry.appbundle, entry.alias, context); designAutomationDataProvider.refresh(); }); vscode.commands.registerCommand('forge.createAppBundleAlias', async (entry?: dai.IAppBundleAliasesEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } await dac.createAppBundleAlias(entry.appbundle, context); designAutomationDataProvider.refresh(); }); vscode.commands.registerCommand('forge.updateAppBundleAlias', async (entry?: dai.IAppBundleAliasEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } await dac.updateAppBundleAlias(entry.appbundle, entry.alias, context); }); vscode.commands.registerCommand('forge.deleteAppBundleVersion', async (entry?: dai.IAppBundleVersionEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } await dac.deleteAppBundleVersion(entry.appbundle, entry.version, context); designAutomationDataProvider.refresh(); }); vscode.commands.registerCommand('forge.viewActivityDetails', async (entry?: dai.IActivityAliasEntry | dai.ISharedActivityEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } const id = 'fullid' in entry ? entry.fullid : `${entry.client}.${entry.activity}+${entry.alias}`; await dac.viewActivityDetails(id, context); }); vscode.commands.registerCommand('forge.viewActivityVersionDetails', async (entry?: dai.IActivityVersionEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } await dac.viewActivityDetails({ name: entry.activity, version: entry.version }, context); }); vscode.commands.registerCommand('forge.deleteActivity', async (entry?: dai.IActivityEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } await dac.deleteActivity(entry.activity, context); designAutomationDataProvider.refresh(); }); vscode.commands.registerCommand('forge.deleteActivityAlias', async (entry?: dai.IActivityAliasEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } await dac.deleteActivityAlias(entry.activity, entry.alias, context); designAutomationDataProvider.refresh(); }); vscode.commands.registerCommand('forge.createActivity', async () => { await dac.createActivity( (activity: IActivityDetail) => { designAutomationDataProvider.refresh(); }, context ); }); vscode.commands.registerCommand('forge.updateActivity', async (entry?: dai.IActivityAliasEntry | dai.IActivityVersionEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } await dac.updateActivity( 'alias' in entry ? `${entry.client}.${entry.activity}+${entry.alias}` : { name: entry.activity, version: entry.version }, (activity: IActivityDetail) => { designAutomationDataProvider.refresh(); }, context ); }); vscode.commands.registerCommand('forge.createActivityAlias', async (entry?: dai.IActivityAliasesEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } await dac.createActivityAlias(entry.activity, context); designAutomationDataProvider.refresh(); }); vscode.commands.registerCommand('forge.updateActivityAlias', async (entry?: dai.IActivityAliasEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } await dac.updateActivityAlias(entry.activity, entry.alias, context); }); vscode.commands.registerCommand('forge.deleteActivityVersion', async (entry?: dai.IActivityVersionEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } await dac.deleteActivityVersion(entry.activity, entry.version, context); designAutomationDataProvider.refresh(); }); vscode.commands.registerCommand('forge.createWorkitem', async (entry?: dai.IActivityAliasEntry | dai.ISharedActivityEntry) => { if (!entry) { vscode.window.showInformationMessage('This command can only be triggered from the tree view.'); return; } await dac.createWorkitem(('fullid' in entry) ? entry.fullid : `${entry.client}.${entry.activity}+${entry.alias}`, context); }); } function registerModelDerivativeCommands(context: IContext, simpleStorageDataProvider: dmp.SimpleStorageDataProvider, hubsDataProvider: HubsDataProvider) { vscode.commands.registerCommand('forge.translateObject', async (object?: IObject | hi.IVersion) => { await mdc.translateObject(object, context); simpleStorageDataProvider.refresh((object as IObject)); hubsDataProvider.refresh((object as hi.IVersion)); }); vscode.commands.registerCommand('forge.translateObjectCustom', async (object?: IObject | hi.IVersion) => { await mdc.translateObjectCustom(object, context, () => { simpleStorageDataProvider.refresh((object as IObject)); hubsDataProvider.refresh((object as hi.IVersion)); }); }); vscode.commands.registerCommand('forge.previewDerivative', async (derivative?: mdi.IDerivative) => { await mdc.previewDerivative(derivative, context); }); vscode.commands.registerCommand('forge.viewDerivativeTree', async (derivative?: mdi.IDerivative) => { await mdc.viewDerivativeTree(derivative, context); }); vscode.commands.registerCommand('forge.viewDerivativeProps', async (derivative?: mdi.IDerivative) => { await mdc.viewDerivativeProps(derivative, context); }); vscode.commands.registerCommand('forge.viewObjectManifest', async (object?: IObject | hi.IVersion) => { await mdc.viewObjectManifest(object, context); }); vscode.commands.registerCommand('forge.deleteObjectManifest', async (object?: IObject) => { await mdc.deleteObjectManifest(object, context); simpleStorageDataProvider.refresh(object); }); vscode.commands.registerCommand('forge.viewObjectThumbnail', async (object?: IObject | hi.IVersion) => { await mdc.viewObjectThumbnail(object, context); }); vscode.commands.registerCommand('forge.downloadDerivativeSvf', async (object?: IObject) => { await mdc.downloadDerivativesSVF(object, context); }); vscode.commands.registerCommand('forge.downloadDerivativeF2d', async (object?: IObject) => { await mdc.downloadDerivativesF2D(object, context); }); vscode.commands.registerCommand('forge.downloadDerivativeOtg', async (object?: IObject) => { await mdc.downloadDerivativesOTG(object, context); }); vscode.commands.registerCommand('forge.downloadDerivativeGltf', async (object?: IObject) => { await mdc.downloadDerivativeGLTF(object, context); }); vscode.commands.registerCommand('forge.copyObjectUrn', async (object?: IObject | hi.IVersion) => { await mdc.copyObjectUrn(object, context); }); } function registerDataManagementCommands(simpleStorageDataProvider: dmp.SimpleStorageDataProvider, context: IContext) { vscode.commands.registerCommand('forge.refreshBuckets', () => { simpleStorageDataProvider.refresh(); }); vscode.commands.registerCommand('forge.createBucket', async () => { await dmc.createBucket(context); simpleStorageDataProvider.refresh(); }); vscode.commands.registerCommand('forge.viewBucketDetails', async (bucket?: IBucket) => { await dmc.viewBucketDetails(bucket, context); }); vscode.commands.registerCommand('forge.deleteBucketObjects', async (bucket?: IBucket) => { await dmc.deleteAllObjects(bucket, context); simpleStorageDataProvider.refresh(); }); vscode.commands.registerCommand('forge.viewObjectDetails', async (object?: IObject) => { await dmc.viewObjectDetails(object, context); }); vscode.commands.registerCommand('forge.uploadObject', async (bucket?: IBucket) => { await dmc.uploadObject(bucket, context); simpleStorageDataProvider.refresh(); }); vscode.commands.registerCommand('forge.createEmptyObject', async (bucket?: IBucket) => { await dmc.createEmptyObject(bucket, context); simpleStorageDataProvider.refresh(); }); vscode.commands.registerCommand('forge.copyObject', async (object?: IObject) => { await dmc.copyObject(object, context); simpleStorageDataProvider.refresh(); }); vscode.commands.registerCommand('forge.renameObject', async (object?: IObject) => { await dmc.renameObject(object, context); simpleStorageDataProvider.refresh(); }); vscode.commands.registerCommand('forge.downloadObject', async (object?: IObject) => { await dmc.downloadObject(object, context); }); vscode.commands.registerCommand('forge.deleteObject', async (object?: IObject) => { await dmc.deleteObject(object, context); simpleStorageDataProvider.refresh(); }); vscode.commands.registerCommand('forge.generateSignedUrl', async (object?: IObject) => { await dmc.generateSignedUrl(object, context); }); vscode.commands.registerCommand('forge.deleteBucket', async (bucket?: IBucket) => { await dmc.deleteBucket(bucket, context); simpleStorageDataProvider.refresh(); }); } export function deactivate() { }
the_stack
import * as fs from "fs"; import * as mkdirp from "mkdirp"; import * as path from "path"; import * as async from "async"; import RemoteProjectClient from "./RemoteProjectClient"; import * as schemas from "./schemas"; import migrateProject from "./migrateProject"; const saveDelay = 60; interface SaveCallback { lastTime: number; timeoutId: NodeJS.Timer; callback: (callback: (err: Error) => any) => any; } export default class ProjectServer { io: SocketIO.Namespace; system: SupCore.System; data: ProjectServerData; buildsPath: string; nextBuildId: number; scheduledSaveCallbacks: { [name: string]: SaveCallback } = {}; nextClientId = 0; clientsBySocketId: { [socketId: string]: RemoteProjectClient } = {}; constructor(globalIO: SocketIO.Server, public projectPath: string, buildsPath: string, callback: (err: Error) => any) { this.data = { manifest: null, entries: null, assets: new SupCore.Data.Assets(this), rooms: new SupCore.Data.Rooms(this), resources: new SupCore.Data.Resources(this) }; this.data.assets.on("itemLoad", this.onAssetLoaded); this.data.rooms.on("itemLoad", this.onRoomLoaded); this.data.resources.on("itemLoad", this.onResourceLoaded); const loadManifest = (callback: (err: Error) => any) => { const done = (data: any) => { try { this.data.manifest = new SupCore.Data.ProjectManifest(data); } catch (err) { callback(err); return; } this.data.manifest.on("change", this.onManifestChanged); if (this.data.manifest.migratedFromFormatVersion != null) this.data.manifest.emit("change"); this.system = SupCore.systems[this.data.manifest.pub.systemId]; if (this.system == null) { callback(new Error(`The system ${this.data.manifest.pub.systemId} is not installed. Run "node server install ${this.data.manifest.pub.systemId}" to install it.`)); } else { this.buildsPath = path.join(buildsPath, this.data.manifest.pub.id); callback(null); } }; fs.readFile(path.join(this.projectPath, "manifest.json"), { encoding: "utf8" }, (err, manifestJSON) => { if (err != null) { callback(err); return; } let manifestData: SupCore.Data.ProjectManifest; try { manifestData = JSON.parse(manifestJSON); } catch (err) { callback(err); return; } try { schemas.validate(manifestData, "projectManifest"); } catch (err) { callback(err); return; } done(manifestData); }); }; const setupNextBuildId = (callback: (err: Error) => any) => { fs.readdir(this.buildsPath, (err, entryIds) => { if (err != null && err.code !== "ENOENT") { callback(err); return; } this.nextBuildId = 0; if (entryIds != null) { for (const entryId of entryIds) { const entryBuildId = parseInt(entryId, 10); if (isNaN(entryBuildId)) continue; this.nextBuildId = Math.max(entryBuildId + 1, this.nextBuildId); } } callback(null); }); }; const ensureRequiredFoldersExist = (callback: (err: Error) => any) => { // These folders might not exist if the project was checked out from source control // But we assume they do when saving resources or rooms, so let's recreate them. const folders = [ "resources", "rooms" ]; async.each(folders, (folder, cb) => { fs.mkdir(path.join(this.projectPath, folder), (err) => { if (err != null && err.code !== "EEXIST") { cb(err); return; } cb(); }); }, callback); }; const loadEntries = (callback: (err: Error) => any) => { fs.readFile(path.join(this.projectPath, "entries.json"), { encoding: "utf8" }, (err, entriesJSON) => { if (err != null) { callback(err); return; } let entriesData: any; try { entriesData = JSON.parse(entriesJSON); } catch (err) { callback(err); return; } if (this.data.manifest.migratedFromFormatVersion != null && this.data.manifest.migratedFromFormatVersion <= 5) { let nextEntryId = 0; let walk = (node: SupCore.Data.EntryNode) => { const intNodeId = parseInt(node.id, 10); nextEntryId = Math.max(nextEntryId, intNodeId); if (node.type == null) for (const childNode of node.children) walk(childNode); }; for (const node of entriesData) walk(node); nextEntryId++; entriesData = { nextEntryId, nodes: entriesData }; } try { schemas.validate(entriesData, "projectEntries"); } catch (err) { callback(err); return; } this.data.entries = new SupCore.Data.Entries(entriesData.nodes, entriesData.nextEntryId, this); this.data.entries.on("change", this.onEntriesChanged); if (this.data.manifest.migratedFromFormatVersion != null && this.data.manifest.migratedFromFormatVersion <= 5) { this.saveEntries(callback); } else { callback(null); } }); }; // migrate() is called after loadEntries() // because some migration code requires the entries to be loaded const migrate = (callback: (err: Error) => any) => { migrateProject(this, callback); }; const serve = (callback: (err: Error) => any) => { // Setup the project's namespace this.io = globalIO.of(`/project:${this.data.manifest.pub.id}`); this.io.on("connection", this.onAddSocket); callback(null); }; // prepareAssets() and prepareResources() is called after serve() // because badges rely on this.io being setup const prepareAssets = (callback: (err: Error) => any) => { async.eachLimit(Object.keys(this.data.entries.byId), 512, (assetId, cb) => { // Ignore folders if (this.data.entries.byId[assetId].type == null) { cb(); return; } this.data.assets.acquire(assetId, null, (err: Error, asset: SupCore.Data.Base.Asset) => { if (err != null) { cb(err); return; } asset.restore(); this.data.assets.release(assetId, null, { skipUnloadDelay: true }); cb(); }); }, callback); }; const prepareResources = (callback: (err: Error) => any) => { async.each(Object.keys(this.system.data.resourceClasses), (resourceId, cb) => { this.data.resources.acquire(resourceId, null, (err: Error, resource: SupCore.Data.Base.Resource) => { if (err != null) { cb(err); return; } resource.restore(); this.data.resources.release(resourceId, null, { skipUnloadDelay: true }); cb(); }); }, callback); }; async.series([ loadManifest, setupNextBuildId, ensureRequiredFoldersExist, loadEntries, migrate, serve, prepareAssets, prepareResources ], callback); } log(message: string) { SupCore.log(`[${this.data.manifest.pub.id} ${this.data.manifest.pub.name}] ${message}`); } save(callback: (err: Error) => any) { const saveCallbacks: Array<(callback: (err: Error) => any) => any> = []; for (const callbackName in this.scheduledSaveCallbacks) { const callbackInfo = this.scheduledSaveCallbacks[callbackName]; if (callbackInfo.timeoutId == null) continue; clearTimeout(callbackInfo.timeoutId); saveCallbacks.push(callbackInfo.callback); } this.scheduledSaveCallbacks = {}; async.parallel(saveCallbacks, callback); } moveAssetFolderToTrash(trashedAssetFolder: string, callback: (err: Error) => any) { const assetsPath = path.join(this.projectPath, "assets"); const folderPath = path.join(assetsPath, trashedAssetFolder); if (!fs.existsSync(folderPath)) { callback(null); return; } const trashedAssetsPath = path.join(this.projectPath, "trashedAssets"); fs.mkdir(trashedAssetsPath, (err) => { if (err != null && err.code !== "EEXIST") throw err; const index = trashedAssetFolder.lastIndexOf("/"); if (index !== -1) trashedAssetFolder = trashedAssetFolder.slice(index); const newFolderPath = path.join(trashedAssetsPath, trashedAssetFolder); fs.rename(folderPath, newFolderPath, callback); }); } removeRemoteClient(socketId: string) { delete this.clientsBySocketId[socketId]; } markMissingDependency(dependentAssetIds: string[], missingAssetId: string) { for (const dependentAssetId of dependentAssetIds) { let missingAssetIds = [ missingAssetId ]; const existingBadge = this.data.entries.badgesByEntryId[dependentAssetId].byId["missingDependencies"]; if (existingBadge != null) { missingAssetIds = missingAssetIds.concat(existingBadge.data.missingAssetIds); } this.setBadge(dependentAssetId, "missingDependencies", "error", { missingAssetIds }); } } scheduleAssetSave = (id: string) => { const item = this.data.assets.byId[id]; if (item == null) { SupCore.log(`Tried to schedule an asset save for item with id ${id} but the asset is not loaded.`); SupCore.log(JSON.stringify(this.data.entries.byId[id], null, 2)); SupCore.log((new Error() as any).stack); return; } const assetPath = path.join(this.projectPath, `assets/${this.data.entries.getStoragePathFromId(id)}`); const saveCallback = item.save.bind(item, assetPath); this.scheduleSave(saveDelay, `assets:${id}`, saveCallback); } private onAssetLoaded = (assetId: string, item: SupCore.Data.Base.Asset) => { item.on("change", () => { this.scheduleAssetSave(assetId); }); item.on("edit", (commandName: string, ...args: any[]) => { this.io.in(`sub:assets:${assetId}`).emit("edit:assets", assetId, commandName, ...args); }); item.on("setBadge", (badgeId: string, type: string, data: any) => { this.setBadge(assetId, badgeId, type, data); }); item.on("clearBadge", (badgeId: string) => { this.clearBadge(assetId, badgeId); }); item.on("addDependencies", (dependencyEntryIds: string[]) => { this.addDependencies(assetId, dependencyEntryIds); }); item.on("removeDependencies", (dependencyEntryIds: string[]) => { this.removeDependencies(assetId, dependencyEntryIds); }); } private onRoomLoaded = (roomId: string, item: SupCore.Data.Room) => { const roomPath = path.join(this.projectPath, `rooms/${roomId}`); const saveCallback = item.save.bind(item, roomPath); item.on("change", () => { this.scheduleSave(saveDelay, `rooms:${roomId}`, saveCallback); }); } private onResourceLoaded = (resourceId: string, item: SupCore.Data.Base.Resource) => { const resourcePath = path.join(this.projectPath, `resources/${resourceId}`); const saveCallback = item.save.bind(item, resourcePath); item.on("change", () => { this.scheduleSave(saveDelay, `resources:${resourceId}`, saveCallback); }); item.on("edit", (commandName: string, ...args: any[]) => { this.io.in(`sub:resources:${resourceId}`).emit("edit:resources", resourceId, commandName, ...args); }); item.on("setAssetBadge", (assetId: string, badgeId: string, type: string, data: any) => { this.setBadge(assetId, badgeId, type, data); }); item.on("clearAssetBadge", (assetId: string, badgeId: string) => { this.clearBadge(assetId, badgeId); }); } private onAddSocket = (socket: SocketIO.Socket) => { const client = new RemoteProjectClient(this, (this.nextClientId++).toString(), socket); this.clientsBySocketId[socket.id] = client; } private scheduleSave = (minimumSecondsElapsed: number, callbackName: string, callback: (callback: (err: Error) => any) => any) => { // this.log(`Scheduling a save: ${callbackName}`); const scheduledCallback = this.scheduledSaveCallbacks[callbackName]; if (scheduledCallback != null && scheduledCallback.timeoutId != null) return; const errorCallback = (err: Error) => { // this.log(`Save done! ${callbackName}`); if (err != null) this.log(`Error in ${callbackName}:\n${err}`); }; if (scheduledCallback == null || scheduledCallback.lastTime <= Date.now() - minimumSecondsElapsed * 1000) { this.scheduledSaveCallbacks[callbackName] = { lastTime: Date.now(), timeoutId: null, callback: null }; callback(errorCallback); } else { const delay = minimumSecondsElapsed * 1000 - (Date.now() - scheduledCallback.lastTime); const timeoutId = setTimeout(() => { callback(errorCallback); scheduledCallback.lastTime = Date.now(); scheduledCallback.timeoutId = null; scheduledCallback.callback = null; }, delay); scheduledCallback.timeoutId = timeoutId; scheduledCallback.callback = callback; } } private onManifestChanged = () => { this.scheduleSave(saveDelay, "manifest", this.saveManifest); }; private onEntriesChanged = () => { this.scheduleSave(saveDelay, "entries", this.saveEntries); }; private saveManifest = (callback: (err: Error) => any) => { const manifestJSON = JSON.stringify(this.data.manifest.pub, null, 2); fs.writeFile(path.join(this.projectPath, "manifest.json"), manifestJSON, callback); } private saveEntries = (callback: (err: Error) => any) => { const entriesJSON = JSON.stringify({ nextEntryId: this.data.entries.nextId, nodes: this.data.entries.getForStorage() }, null, 2); fs.writeFile(path.join(this.projectPath, "newEntries.json"), entriesJSON, () => { fs.rename(path.join(this.projectPath, "newEntries.json"), path.join(this.projectPath, "entries.json"), callback); }); } private setBadge(assetId: string, badgeId: string, type: string, data: any) { // console.log(`setBadge ${assetId} ${badgeId} ${type}`); const badges = this.data.entries.badgesByEntryId[assetId]; const newBadge = { id: badgeId, type, data }; const existingBadge = badges.byId[badgeId]; if (existingBadge != null) { existingBadge.type = type; existingBadge.data = data; this.io.in("sub:entries").emit("set:badges", assetId, newBadge); return; } badges.add(newBadge, null, (err) => { this.io.in("sub:entries").emit("set:badges", assetId, newBadge); }); } private clearBadge(assetId: string, badgeId: string) { // console.log(`clearBadge ${assetId} ${badgeId}`); const badges = this.data.entries.badgesByEntryId[assetId]; badges.remove(badgeId, (err) => { this.io.in("sub:entries").emit("clear:badges", assetId, badgeId); }); } private addDependencies(assetId: string, dependencyEntryIds: string[]) { const addedDependencyEntryIds: string[] = []; let missingAssetIds: string[] = []; let assetDependencies = this.data.entries.dependenciesByAssetId[assetId]; if (assetDependencies == null) assetDependencies = this.data.entries.dependenciesByAssetId[assetId] = []; for (const depId of dependencyEntryIds) { assetDependencies.push(depId); const depEntry = this.data.entries.byId[depId]; if (depEntry == null) { missingAssetIds.push(depId); continue; } const dependentAssetIds = depEntry.dependentAssetIds; if (dependentAssetIds.indexOf(assetId) === -1) { dependentAssetIds.push(assetId); addedDependencyEntryIds.push(depId); } } if (missingAssetIds.length > 0) { const existingBadge = this.data.entries.badgesByEntryId[assetId].byId["missingDependencies"]; if (existingBadge != null) missingAssetIds = missingAssetIds.concat(existingBadge.data.missingAssetIds); this.setBadge(assetId, "missingDependencies", "error", { missingAssetIds }); } if (addedDependencyEntryIds.length > 0) { this.io.in("sub:entries").emit("add:dependencies", assetId, addedDependencyEntryIds); } } private removeDependencies(assetId: string, dependencyEntryIds: string[]) { const removedDependencyEntryIds: string[] = []; const missingAssetIds: string[] = []; let assetDependencies = this.data.entries.dependenciesByAssetId[assetId]; if (assetDependencies == null) assetDependencies = this.data.entries.dependenciesByAssetId[assetId] = []; for (const depId of dependencyEntryIds) { assetDependencies.splice(assetDependencies.indexOf(depId), 1); const depEntry = this.data.entries.byId[depId]; if (depEntry == null) { missingAssetIds.push(depId); continue; } const dependentAssetIds = depEntry.dependentAssetIds; const index = dependentAssetIds.indexOf(assetId); if (index !== -1) { dependentAssetIds.splice(index, 1); removedDependencyEntryIds.push(depId); } } if (missingAssetIds.length > 0) { const existingBadge = this.data.entries.badgesByEntryId[assetId].byId["missingDependencies"]; if (existingBadge != null) { for (const missingAssetId of missingAssetIds) { const index = existingBadge.data.missingAssetIds.indexOf(missingAssetId); if (index !== -1) { existingBadge.data.missingAssetIds.splice(index, 1); } } if (existingBadge.data.missingAssetIds.length === 0) this.clearBadge(assetId, "missingDependencies"); else this.setBadge(assetId, "missingDependencies", "error", existingBadge.data); } } if (removedDependencyEntryIds.length > 0) { this.io.in("sub:entries").emit("remove:dependencies", assetId, removedDependencyEntryIds); } if (assetDependencies.length === 0) { delete this.data.entries.dependenciesByAssetId[assetId]; } } addEntry = (clientSocketId: string, name: string, type: string, options: any, callback: (err: string, newId?: string) => any) => { if (!this.clientsBySocketId[clientSocketId].errorIfCant("editAssets", callback)) return; name = name.trim(); if (name.length === 0) { callback("Entry name cannot be empty"); return; } if (name.indexOf("/") !== -1) { callback("Entry name cannot contain slashes"); return; } const entry: SupCore.Data.EntryNode = { id: null, name, type, badges: [], dependentAssetIds: [] }; if (options == null) options = {}; this.data.entries.add(entry, options.parentId, options.index, (err: string, actualIndex: number) => { if (err != null) { callback(err, null); return; } const onEntryCreated = () => { this.io.in("sub:entries").emit("add:entries", entry, options.parentId, actualIndex); callback(null, entry.id); }; if (entry.type != null) { const assetClass = this.system.data.assetClasses[entry.type]; const asset = new assetClass(entry.id, null, this); asset.init({ name: entry.name }, () => { const assetPath = path.join(this.projectPath, `assets/${this.data.entries.getStoragePathFromId(entry.id)}`); mkdirp(assetPath, () => { asset.save(assetPath, onEntryCreated); }); }); } else { onEntryCreated(); } }); } duplicateEntry = (clientSocketId: string, newName: string, originalEntryId: string, options: any, callback: (err: string, duplicatedId?: string) => any) => { if (!this.clientsBySocketId[clientSocketId].errorIfCant("editAssets", callback)) return; const entryToDuplicate = this.data.entries.byId[originalEntryId]; if (entryToDuplicate == null) { callback(`Entry ${originalEntryId} doesn't exist`); return; } const entry: SupCore.Data.EntryNode = { id: null, name: newName, type: entryToDuplicate.type, badges: [], dependentAssetIds: [] }; if (options == null) options = {}; if (entryToDuplicate.type == null) { this.data.entries.add(entry, options.parentId, options.index, (err: string, actualIndex: number) => { if (err != null) { callback(err, null); return; } this.io.in("sub:entries").emit("add:entries", entry, options.parentId, actualIndex); async.eachSeries(entryToDuplicate.children, (child, cb) => { this.duplicateEntry(clientSocketId, child.name, child.id, { parentId: entry.id, index: entryToDuplicate.children.indexOf(child) }, (err: string, duplicatedId?: string) => { if (err == null) cb(null); else cb(new Error(err)); }); }, (err: Error) => { if (err != null) callback(err.message, null); else callback(null, entry.id); }); }); } else { this.data.entries.add(entry, options.parentId, options.index, (err: string, actualIndex: number) => { if (err != null) { callback(err); return; } const newAssetPath = path.join(this.projectPath, `assets/${this.data.entries.getStoragePathFromId(entry.id)}`); this.data.assets.acquire(originalEntryId, null, (err, referenceAsset) => { mkdirp(newAssetPath, () => { referenceAsset.save(newAssetPath, (err: Error) => { this.data.assets.release(originalEntryId, null); if (err != null) { this.log(`Failed to save duplicated asset at ${newAssetPath} (duplicating ${originalEntryId})`); this.log(err.toString()); this.data.entries.remove(entry.id, (err) => { if (err != null) this.log(err); }); callback("Could not save asset"); return; } this.data.assets.acquire(entry.id, null, (err, newAsset) => { this.data.assets.release(entry.id, null); this.io.in("sub:entries").emit("add:entries", entry, options.parentId, actualIndex); newAsset.restore(); callback(null, entry.id); }); }); }); }); }); } } moveEntry = (clientSocketId: string, entryId: string, parentId: string, index: number, callback: (err: string) => any) => { if (!this.clientsBySocketId[clientSocketId].errorIfCant("editAssets", callback)) return; const oldFullAssetPath = this.data.entries.getStoragePathFromId(entryId); const oldParent = this.data.entries.parentNodesById[entryId]; this.data.entries.move(entryId, parentId, index, (err, actualIndex) => { if (err != null) { callback(err); return; } this.onEntryChangeFullPath(entryId, oldFullAssetPath, () => { if (oldParent == null || oldParent.children.length > 0) return; const oldParentPath = path.join(this.projectPath, `assets/${this.data.entries.getStoragePathFromId(oldParent.id)}`); fs.readdir(oldParentPath, (err, files) => { if (files != null && files.length === 0) fs.rmdirSync(oldParentPath); }); }); this.io.in("sub:entries").emit("move:entries", entryId, parentId, actualIndex); callback(null); }); } trashEntry = (clientSocketId: string, entryId: string, callback: (err: string) => any) => { if (!this.clientsBySocketId[clientSocketId].errorIfCant("editAssets", callback)) return; const trashEntryRecursively = (entry: SupCore.Data.EntryNode, callback: (err: Error) => void) => { const finishTrashEntry = (err: Error) => { if (err != null) { callback(err); return; } // Clear all dependencies for this entry const dependentAssetIds = (entry != null) ? entry.dependentAssetIds : null; const dependencies = this.data.entries.dependenciesByAssetId[entry.id]; if (dependencies != null) { const removedDependencyEntryIds = [] as string[]; for (const depId of dependencies) { const depEntry = this.data.entries.byId[depId]; if (depEntry == null) continue; const dependentAssetIds = depEntry.dependentAssetIds; const index = dependentAssetIds.indexOf(entry.id); if (index !== -1) { dependentAssetIds.splice(index, 1); removedDependencyEntryIds.push(depId); } } if (removedDependencyEntryIds.length > 0) { this.io.in("sub:entries").emit("remove:dependencies", entry.id, dependencies); } delete this.data.entries.dependenciesByAssetId[entry.id]; } let asset: SupCore.Data.Base.Asset; async.series([ (cb) => { if (entry.type != null) { this.data.assets.acquire(entry.id, null, (err, acquiredAsset) => { if (err != null) { cb(err); return; } asset = acquiredAsset; cb(null); }); } else cb(null); }, (cb) => { // Apply and clear any scheduled saved const scheduledSaveCallback = this.scheduledSaveCallbacks[`assets:${entry.id}`]; if (scheduledSaveCallback == null) { cb(); return; } if (scheduledSaveCallback.timeoutId != null) clearTimeout(scheduledSaveCallback.timeoutId); delete this.scheduledSaveCallbacks[`assets:${entry.id}`]; const assetPath = path.join(this.projectPath, `assets/${this.data.entries.getStoragePathFromId(entry.id)}`); asset.save(assetPath, cb); }, (cb) => { // Delete the entry this.data.entries.remove(entry.id, (err) => { if (err != null) { cb(new Error(err)); return; } this.io.in("sub:entries").emit("trash:entries", entry.id); // Notify and clear all asset subscribers const roomName = `sub:assets:${entry.id}`; this.io.in(roomName).emit("trash:assets", entry.id); const room = this.io.adapter.rooms[roomName]; // room is null when the asset isn't open in any client if (room != null) { for (const socketId in room.sockets) { const remoteClient = this.clientsBySocketId[socketId]; remoteClient.socket.leave(roomName); remoteClient.subscriptions.splice(remoteClient.subscriptions.indexOf(roomName), 1); } } // Generate badges for any assets depending on this entry if (dependentAssetIds != null) this.markMissingDependency(dependentAssetIds, entryId); // Skip asset destruction & release if trashing a folder if (asset == null) { cb(null); return; } // NOTE: It is important that we destroy the asset after having removed its entry // from the tree so that nobody can subscribe to it after it's been destroyed asset.destroy(() => { this.data.assets.releaseAll(entry.id); cb(null); }); }); } ], callback); }; if (entry.type == null) { async.each(entry.children, (entry, cb) => { trashEntryRecursively(entry, cb); } , finishTrashEntry); } else finishTrashEntry(null); }; const trashedAssetFolder = this.data.entries.getStoragePathFromId(entryId); const entry = this.data.entries.byId[entryId]; const gotChildren = entry.type == null && entry.children.length > 0; const parentEntry = this.data.entries.parentNodesById[entryId]; trashEntryRecursively(entry, (err: Error) => { if (err != null) { callback(err.message); return; } // After the trash on memory, move folder to trashed assets and clean up empty folders const deleteFolder = (folderPath: string, callback: (error: string) => void) => { fs.readdir(folderPath, (err, files) => { if (err != null) { if (err.code !== "ENOENT") callback(err.message); else callback(null); return; } if (files.length === 0) { fs.rmdir(folderPath, (err) => { if (err != null) { callback(err.message); return; } callback(null); }); } else callback(null); }); }; if (entry.type != null || gotChildren) { this.moveAssetFolderToTrash(trashedAssetFolder, (err) => { if (err != null) { callback(err.message); return; } if (parentEntry != null && parentEntry.children.length === 0) deleteFolder(path.join(this.projectPath, "assets", this.data.entries.getStoragePathFromId(parentEntry.id)), callback); else callback(null); }); } else deleteFolder(path.join(this.projectPath, "assets", trashedAssetFolder), callback); }); } renameEntry = (clientSocketId: string, entryId: string, name: string, callback: (err: string) => any) => { if (!this.clientsBySocketId[clientSocketId].errorIfCant("editAssets", callback)) return; if (name.indexOf("/") !== -1) { callback("Entry name cannot contain slashes"); return; } const oldFullAssetPath = this.data.entries.getStoragePathFromId(entryId); this.data.entries.setProperty(entryId, "name", name, (err: string, actualName: any) => { if (err != null) { callback(err); return; } this.onEntryChangeFullPath(entryId, oldFullAssetPath); this.io.in("sub:entries").emit("setProperty:entries", entryId, "name", actualName); callback(null); }); } private onEntryChangeFullPath = (assetId: string, oldFullAssetPath: string, callback?: Function) => { let mustScheduleSave = false; const scheduledSaveCallback = this.scheduledSaveCallbacks[`assets:${assetId}`]; if (scheduledSaveCallback != null && scheduledSaveCallback.timeoutId != null) { clearTimeout(scheduledSaveCallback.timeoutId); scheduledSaveCallback.timeoutId = null; scheduledSaveCallback.callback = null; mustScheduleSave = true; } const assetPath = this.data.entries.getStoragePathFromId(assetId); async.series([ (cb) => { const index = assetPath.lastIndexOf("/"); if (index !== -1) { const parentPath = assetPath.slice(0, index); mkdirp(path.join(this.projectPath, `assets/${parentPath}`), cb); } else cb(null); }, (cb) => { const oldDirPath = path.join(this.projectPath, `assets/${oldFullAssetPath}`); const dirPath = path.join(this.projectPath, `assets/${assetPath}`); fs.rename(oldDirPath, dirPath, (err) => { if (mustScheduleSave) this.scheduleAssetSave(assetId); if (callback != null) callback(); }); } ]); } saveEntry = (clientSocketId: string, entryId: string, revisionName: string, callback: (err: string) => void) => { if (!this.clientsBySocketId[clientSocketId].errorIfCant("editAssets", callback)) return; if (revisionName.length === 0) { callback("Revision name can't be empty"); return; } this.data.entries.save(entryId, revisionName, (err, revisionId) => { if (err != null) { callback(err); return; } this.data.assets.acquire(entryId, null, (err, asset) => { if (err != null) { callback("Could not acquire asset"); return; } this.data.assets.release(entryId, null); const revisionPath = path.join(this.projectPath, `assetRevisions/${entryId}/${revisionId}-${revisionName}`); mkdirp(revisionPath, (err) => { if (err != null) { callback("Could not write the save"); return; } asset.save(revisionPath, (err: Error) => { if (err != null) { callback("Could not write the save"); console.log(err); return; } this.io.in("sub:entries").emit("save:entries", entryId, revisionId, revisionName); callback(null); }); }); }); }); } }
the_stack
import { IntPretty } from "./int-pretty"; import { Int } from "./int"; import { Dec } from "./decimal"; describe("Test IntPretty", () => { it("Test the precision of IntPretty", () => { const params: { arg: Dec | Int; precision: number; dec: Dec; str: string; }[] = [ { arg: new Int(0), precision: 0, dec: new Dec(0), str: "0", }, { arg: new Dec(0), precision: 0, dec: new Dec(0), str: "0", }, { arg: new Int(100), precision: 0, dec: new Dec(100), str: "100", }, { arg: new Dec(100), precision: 0, dec: new Dec(100), str: "100", }, { arg: new Dec("0.01"), precision: 2, dec: new Dec("0.01"), str: "0.01", }, { arg: new Dec("-0.01"), precision: 2, dec: new Dec("-0.01"), str: "-0.01", }, { arg: new Dec("1.01"), precision: 2, dec: new Dec("1.01"), str: "1.01", }, { arg: new Dec("-1.01"), precision: 2, dec: new Dec("-1.01"), str: "-1.01", }, { arg: new Dec("10.01"), precision: 2, dec: new Dec("10.01"), str: "10.01", }, { arg: new Dec("-10.01"), precision: 2, dec: new Dec("-10.01"), str: "-10.01", }, { arg: new Dec("10.0100"), precision: 2, dec: new Dec("10.01"), str: "10.01", }, { arg: new Dec("-10.0100"), precision: 2, dec: new Dec("-10.01"), str: "-10.01", }, ]; for (const param of params) { const pretty = new IntPretty(param.arg); expect(pretty.options.precision).toBe(param.precision); expect(pretty.toDec().equals(param.dec)).toBeTruthy(); expect(pretty.toString()).toBe(param.str); } }); it("Test modifying the precision of IntPretty", () => { let pretty = new IntPretty(new Dec("10.001")); expect(pretty.options.precision).toBe(3); expect(pretty.toString()).toBe("10.001"); let newPretty = pretty.precision(4); expect(newPretty.options.precision).toBe(4); // Max decimals not changed expect(newPretty.toString()).toBe("1.000"); expect(newPretty.maxDecimals(4).toString()).toBe("1.0001"); newPretty = pretty.increasePrecision(1); expect(newPretty.options.precision).toBe(4); expect(newPretty.toString()).toBe("1.000"); expect(newPretty.maxDecimals(4).toString()).toBe("1.0001"); newPretty = pretty.precision(2); expect(newPretty.options.precision).toBe(2); expect(newPretty.toString()).toBe("100.010"); newPretty = pretty.decreasePrecision(1); expect(newPretty.options.precision).toBe(2); expect(newPretty.toString()).toBe("100.010"); newPretty = pretty.decreasePrecision(6); expect(newPretty.options.precision).toBe(-3); expect(newPretty.toString()).toBe("10,001,000.000"); pretty = new IntPretty(new Int(0)); expect(pretty.decreasePrecision(3).toString()).toBe("0"); expect(pretty.increasePrecision(3).toString()).toBe("0"); expect(() => { pretty.precision(-18); }).not.toThrow(); expect(() => { pretty.precision(18); }).not.toThrow(); expect(() => { pretty.precision(-19); }).toThrow(); expect(() => { pretty.precision(19); }).toThrow(); }); it("Test the add calcutation of IntPretty", () => { const params: { base: Dec | Int; target: Dec | Int; precision: number; dec: Dec; str: string; }[] = [ { base: new Int(0), target: new Int(0), precision: 0, dec: new Dec(0), str: "0", }, { base: new Dec(0), target: new Int(0), precision: 0, dec: new Dec(0), str: "0", }, { base: new Int(0), target: new Dec(0), precision: 0, dec: new Dec(0), str: "0", }, { base: new Int(1), target: new Dec(1), precision: 0, dec: new Dec(2), str: "2", }, { base: new Int(1), target: new Dec(-1), precision: 0, dec: new Dec(0), str: "0", }, { base: new Int(100), target: new Dec(-1), precision: 0, dec: new Dec("99"), str: "99", }, { base: new Dec("100.001"), target: new Dec(-1), precision: 3, dec: new Dec("99.001"), str: "99.001", }, { base: new Dec("100.00100"), target: new Dec("-1.001"), precision: 0, dec: new Dec("99"), // Max decimals should be remain str: "99.000", }, { base: new Dec("100.00100"), target: new Dec("-0.00100"), precision: 0, dec: new Dec("100"), // Max decimals should be remain str: "100.000", }, { base: new Dec("0.00100"), target: new Dec("-1.00100"), precision: 0, dec: new Dec("-1"), // Max decimals should be remain str: "-1.000", }, { base: new Dec("100.00100"), target: new Dec("1.01"), precision: 3, dec: new Dec("101.011"), str: "101.011", }, ]; for (const param of params) { const pretty = new IntPretty(param.base).add(new IntPretty(param.target)); expect(pretty.options.precision).toBe(param.precision); expect(pretty.toDec().equals(param.dec)).toBeTruthy(); expect(pretty.toString()).toBe(param.str); } }); it("Test the sub calcutation of IntPretty", () => { const params: { base: Dec | Int; target: Dec | Int; precision: number; dec: Dec; str: string; }[] = [ { base: new Int(0), target: new Int(0), precision: 0, dec: new Dec(0), str: "0", }, { base: new Dec(0), target: new Int(0), precision: 0, dec: new Dec(0), str: "0", }, { base: new Int(0), target: new Dec(0), precision: 0, dec: new Dec(0), str: "0", }, { base: new Int(1), target: new Dec(1), precision: 0, dec: new Dec(0), str: "0", }, { base: new Int(1), target: new Dec(-1), precision: 0, dec: new Dec(2), str: "2", }, { base: new Int(100), target: new Dec(-1), precision: 0, dec: new Dec("101"), str: "101", }, { base: new Dec("100.001"), target: new Dec(-1), precision: 3, dec: new Dec("101.001"), str: "101.001", }, { base: new Dec("100.00100"), target: new Dec("1.001"), precision: 0, dec: new Dec("99"), // Max decimals should be remain str: "99.000", }, { base: new Dec("100.00100"), target: new Dec("0.00100"), precision: 0, dec: new Dec("100"), // Max decimals should be remain str: "100.000", }, { base: new Dec("0.00100"), target: new Dec("-1.00100"), precision: 3, dec: new Dec("1.002"), str: "1.002", }, { base: new Dec("100.00100"), target: new Dec("-1.01"), precision: 3, dec: new Dec("101.011"), str: "101.011", }, ]; for (const param of params) { const pretty = new IntPretty(param.base).sub(new IntPretty(param.target)); expect(pretty.options.precision).toBe(param.precision); expect(pretty.toDec().equals(param.dec)).toBeTruthy(); expect(pretty.toString()).toBe(param.str); } }); it("Test the mul calcutation of IntPretty", () => { const params: { base: Dec | Int; target: Dec | Int; precision: number; dec: Dec; str: string; }[] = [ { base: new Int(0), target: new Int(0), precision: 0, dec: new Dec(0), str: "0", }, { base: new Dec(0), target: new Int(0), precision: 0, dec: new Dec(0), str: "0", }, { base: new Int(0), target: new Dec(0), precision: 0, dec: new Dec(0), str: "0", }, { base: new Int(1), target: new Dec(1), precision: 0, dec: new Dec(1), str: "1", }, { base: new Int(1), target: new Dec(-1), precision: 0, dec: new Dec(-1), str: "-1", }, { base: new Int(100), target: new Dec(-1), precision: 0, dec: new Dec("-100"), str: "-100", }, { base: new Dec("100.001"), target: new Dec(-1), precision: 3, dec: new Dec("-100.001"), str: "-100.001", }, { base: new Dec("100.00100"), target: new Dec("1.001"), precision: 6, dec: new Dec("100.101001"), // Max decimals should be remain str: "100.101", }, { base: new Dec("100.00100"), target: new Dec("0.00100"), precision: 6, dec: new Dec("0.100001"), // Max decimals should be remain str: "0.100", }, { base: new Dec("100.00100"), target: new Dec("-1.00100"), precision: 6, dec: new Dec("-100.101001"), // Max decimals should be remain str: "-100.101", }, { base: new Dec("100.00100"), target: new Dec("-0.00100"), precision: 6, dec: new Dec("-0.100001"), // Max decimals should be remain str: "-0.100", }, ]; for (const param of params) { const pretty = new IntPretty(param.base).mul(new IntPretty(param.target)); expect(pretty.options.precision).toBe(param.precision); expect(pretty.toDec().equals(param.dec)).toBeTruthy(); expect(pretty.toString()).toBe(param.str); } }); it("Test the quo calcutation of IntPretty", () => { expect(() => { new IntPretty(new Dec("1")).quo(new IntPretty(new Int(0))); }).toThrow(); const params: { base: Dec | Int; target: Dec | Int; precision: number; dec: Dec; str: string; }[] = [ { base: new Int(1), target: new Dec(1), precision: 0, dec: new Dec(1), str: "1", }, { base: new Int(1), target: new Dec(-1), precision: 0, dec: new Dec(-1), str: "-1", }, { base: new Int(100), target: new Dec(-1), precision: 0, dec: new Dec("-100"), str: "-100", }, { base: new Dec("100.001"), target: new Dec(-1), precision: 3, dec: new Dec("-100.001"), str: "-100.001", }, { base: new Dec("300.00300"), target: new Dec("3"), precision: 3, dec: new Dec("100.001"), str: "100.001", }, { base: new Dec("100.00500"), target: new Dec("0.02"), precision: 2, dec: new Dec("5000.25"), // Max decimals should be remain str: "5,000.250", }, { base: new Dec("300.00300"), target: new Dec("4"), precision: 5, dec: new Dec("75.00075"), // Max decimals should be remain str: "75.000", }, ]; for (const param of params) { const pretty = new IntPretty(param.base).quo(new IntPretty(param.target)); expect(pretty.options.precision).toBe(param.precision); expect(pretty.toDec().equals(param.dec)).toBeTruthy(); expect(pretty.toString()).toBe(param.str); } }); it("Test toString() of IntPretty", () => { let pretty = new IntPretty(new Dec("1234.123456")); expect(pretty.toString()).toBe("1,234.123456"); expect(pretty.locale(false).toString()).toBe("1234.123456"); expect(pretty.maxDecimals(3).toString()).toBe("1,234.123"); expect(pretty.maxDecimals(9).toString()).toBe("1,234.123456000"); expect(pretty.maxDecimals(9).trim(true).toString()).toBe("1,234.123456"); expect(pretty.shrink(true).toString()).toBe("1,234.123"); pretty = new IntPretty(new Dec("0.0123456")); expect(pretty.toString()).toBe("0.0123456"); expect(pretty.locale(false).toString()).toBe("0.0123456"); expect(pretty.maxDecimals(3).toString()).toBe("0.012"); expect(pretty.maxDecimals(9).toString()).toBe("0.012345600"); expect(pretty.maxDecimals(9).trim(true).toString()).toBe("0.0123456"); expect(pretty.shrink(true).toString()).toBe("0.0123456"); }); });
the_stack
import { getViewClass, getViewMeta, normalizeElementName, NSVViewMeta, } from './registry' import { ELEMENT_REF } from './runtimeHelpers'; // import { debug } from '../shared'; import { Component, NodeObject, NodeWidget, QObjectSignals, QWidgetSignals } from '@nodegui/nodegui' import type { RNComponent } from "../../react-nodegui/src/components/config"; import { warn, error, log } from '../../shared/Logger'; import { EventWidget } from '@nodegui/nodegui/dist/lib/core/EventWidget'; import { QVariantType } from '@nodegui/nodegui/dist/lib/QtCore/QVariant'; import { RNWindow } from '../../react-nodegui/src/components/Window/RNWindow'; import SvelteNodeGUIDocument from '../../svelte/SvelteNodeGUIDocument'; // import { default as set } from "set-value"; // import unset from 'unset-value' // import {isContentView, isLayout} from "./index"; declare var __DEV__: boolean declare var __TEST__: boolean export const enum NSVNodeTypes { TEXT = 'text', ELEMENT = 'element', COMMENT = 'comment', ROOT = 'root', } // View Flags indicate the kind of view the element is // this avoids extra checks during runtime to determine // the method to use for adding/removing child nodes // export const enum NSVViewFlags { NONE = 0, SKIP_ADD_TO_DOM = 1 << 0, /* NativeScript-specific. TODO: determine NodeGUI-specific ones. */ // CONTENT_VIEW = 1 << 1, // LAYOUT_VIEW = 1 << 2, NO_CHILDREN = 1 << 3, } type EventListener = (args: unknown) => void; export function componentIsEventWidget<Signals extends {} = {}>(component: Component): component is EventWidget<Signals> { if(!component){ return false; } if(typeof (component as EventWidget<Signals>).addEventListener === "function"){ return true; } return false; } export function componentIsStyleable<Signals extends QWidgetSignals = QWidgetSignals>(component: Component): component is NodeWidget<Signals> { if(!component){ return false; } if(typeof (component as NodeWidget<Signals>)._rawInlineStyle === "string"){ return true; } return false; } export function componentHasPropertyAccessor<Signals extends QObjectSignals = QObjectSignals>(component: Component): component is NodeObject<Signals> { if(!component){ return false; } if(typeof (component as NodeObject<Signals>).property === "function"){ return true; } return false; } export function componentSupportsId<Signals extends QWidgetSignals = QWidgetSignals>(component: Component): component is NodeWidget<Signals> { if(typeof (component as NodeWidget<Signals>).setObjectName === "function"){ return true; } return false; } export function* elementIterator(el: NSVNode): Iterable<NSVNode> { yield el; for (let child of el.childNodes) { yield* elementIterator(child) } } export type NativeView<T extends Component = Component> = T & RNComponent; interface IStyleProxy { setProperty(propertyName: string, value: string, priority?: string): void; removeProperty(property: string): void; // animation: string; cssText: string; } let nodeId: number = 0 export abstract class NSVNode { protected constructor(nodeType: NSVNodeTypes) { this.nodeType = nodeType this.nodeId = nodeId++ } nodeRole?: string nodeId: number nodeType: NSVNodeTypes get textContent(): string|null { if(this.nodeType === NSVNodeTypes.TEXT){ return (this as NSVNode as NSVText).data; } if(this.nodeType === NSVNodeTypes.ELEMENT){ return this.childNodes.map(childNode => childNode.textContent).join(""); } return null; } set textContent(value: string){ if(this.nodeType === NSVNodeTypes.TEXT){ (this as NSVNode as NSVText).data = (value ?? ""); return; } if(this.nodeType === NSVNodeTypes.ELEMENT){ this.childNodes.forEach(c => (this as NSVNode as NSVElement).removeChild(c as NSVNode)); (this as NSVNode as NSVElement).appendChild(new NSVText(value)); return; } } parentNode: NSVNode | null = null parentElement: NSVElement | null = null childNodes: NSVNode[] = [] nextSibling: NSVNode | null = null previousSibling: NSVNode | null = null get firstChild() { return this.childNodes.length ? this.childNodes[0] : null } get lastChild() { return this.childNodes.length ? this.childNodes[this.childNodes.length - 1] : null } appendChild(child: NSVNode): NSVNode { if(child === this || ![NSVNodeTypes.ELEMENT, NSVNodeTypes.ROOT].includes(this.nodeType)){ throw new Error("HierarchyRequestError: The operation would yield an incorrect node tree."); } if(child instanceof NSVNode === false){ throw new Error("TypeError: Argument 1 ('child') to Node.appendChild must be an instance of NSVNode"); } if(child.parentNode === this){ return child; } child.previousSibling = this.childNodes[this.childNodes.length - 1] ?? null; child.nextSibling = null; // If the child is already a child of this, remove it from our childNodes array before adding it to the end. if(child.parentNode === this){ const childIndex = this.childNodes.findIndex(c => c === child); if(childIndex === -1){ throw new Error("NotFoundError: the object can not be found here."); } this.childNodes.splice(childIndex, 0); } this.childNodes.push(child); child.parentNode = this as NSVNode; if(this.nodeType === NSVNodeTypes.ELEMENT){ child.parentElement = this as NSVNode as NSVElement; if(child.nodeType === NSVNodeTypes.TEXT){ (this as NSVNode as NSVElement).updateNativeText(); } } return child; } insertBefore(newNode: NSVNode, referenceNode: NSVNode): NSVNode { if(newNode === this || ![NSVNodeTypes.ELEMENT, NSVNodeTypes.ROOT].includes(this.nodeType)){ throw new Error("HierarchyRequestError: The operation would yield an incorrect node tree."); } if(newNode instanceof NSVNode === false){ throw new Error("TypeError: Argument 1 ('newNode') to Node.insertBefore must be an instance of NSVNode"); } // console.log(`[Node.insertBefore] ${newNode}, ${referenceNode}`); const referenceIndex = referenceNode == null ? -1 : this.childNodes.findIndex(node => node === referenceNode); if(referenceIndex === -1){ this.appendChild(newNode); } else { newNode.previousSibling = this.childNodes[referenceIndex - 1] ?? null; newNode.nextSibling = this.childNodes[referenceIndex]; // If the child is already a child of this, remove it from our childNodes array before adding it to the end. if(newNode.parentNode === this){ const newNodeIndex = this.childNodes.findIndex(c => c === newNode); if(newNodeIndex === -1){ throw new Error("NotFoundError: the object can not be found here."); } this.childNodes.splice(newNodeIndex, 0); } this.childNodes.splice(referenceIndex, 0, newNode); newNode.parentNode = this as NSVNode; if(this.nodeType === NSVNodeTypes.ELEMENT){ newNode.parentElement = this as NSVNode as NSVElement; if(newNode.nodeType === NSVNodeTypes.TEXT){ (this as NSVNode as NSVElement).updateNativeText(); } } } return newNode; } removeChild(child: NSVNode): NSVNode { if(child === this){ throw new Error("HierarchyRequestError: The operation would yield an incorrect node tree."); } if(child instanceof NSVNode === false){ throw new Error("TypeError: Argument 1 ('child') to Node.removeChild must be an instance of NSVNode"); } const childIndex = this.childNodes.findIndex(c => c === child); if(childIndex === -1){ throw new Error("NotFoundError: the object can not be found here."); } if(childIndex !== -1){ child.previousSibling = null; child.nextSibling = null; this.childNodes.splice(childIndex, 1); child.parentNode = null; if(this.nodeType === NSVNodeTypes.ELEMENT){ child.parentElement = null; if(child.nodeType === NSVNodeTypes.TEXT){ (this as NSVNode as NSVElement).updateNativeText(); } } } return child; } } export class NSVElement<T extends NativeView = NativeView> extends NSVNode { private readonly _tagName: string private readonly _nativeView: T; private _meta: NSVViewMeta<T> | undefined private readonly recycledNewProps: Record<string, any> = {}; private readonly recycledOldProps: Record<string, any> = {}; private readonly propsSetter: Record<string, (value: any) => void> = {}; public ownerDocument: SvelteNodeGUIDocument|null = null; constructor(tagName: string){ super(NSVNodeTypes.ELEMENT); this._tagName = normalizeElementName(tagName); const viewClass = getViewClass(tagName); if(viewClass){ // this._nativeView = new viewClass(); this._nativeView = viewClass; // We're now calling new in the resolver itself // console.log(`!! [${tagName}] nativeView was instantiated!`, this._nativeView); (this._nativeView as any)[ELEMENT_REF] = this; } } get tagName(): string { return this._tagName } get nativeView() { return this._nativeView } private readonly stylesMap = new Map<string, string|number>(); get id(): string { if(componentSupportsId(this.nativeView)){ return this.nativeView.objectName(); } else { console.warn(`<${this._tagName}> is a virtual element (i.e. has no corresponding Qt Widget) and so the attribute "id" cannot be accessed.`); return ""; } } set id(value: string){ if(componentSupportsId(this.nativeView)){ this.nativeView.setObjectName(value); } else { console.warn(`<${this._tagName}> is a virtual element (i.e. has no corresponding Qt Widget) and so the attribute "id" cannot be set on it.`); } } /* istanbul ignore next */ setStyle(property: string, value: string | number | null, priority: "important"|""): void { // console.log(`[NSVElement] this.setStyle("${property}", "${value}")`); // log.debug(() => `setStyle ${this} ${property} ${value}`) if(!(value = value.toString().trim()).length){ return; } if(!componentIsStyleable(this.nativeView)){ return; } const currentValue = this.stylesMap.get(property); if(currentValue === value || typeof value === "undefined"){ return; } if(value === null){ this.stylesMap.delete(property); } this.stylesMap.set(property, `${value}${priority ? " !important" : ""}`); /* NodeGUI doesn't seem to give property-by-property access into the styles, so for now, we'll just inefficiently rewrite the whole inline style upon any update. */ let updatedRawInlineStyle: string = ""; let i = 0; for (const [property, value] of this.stylesMap) { updatedRawInlineStyle += `${i > 0 ? "\n" : ""}${property}:${value};`; i++; } // console.log(`[NSVElement.setStyle] this.nativeView.setInlineStyle("${updatedRawInlineStyle}");`); this.nativeView.setInlineStyle(updatedRawInlineStyle); // const rawInlineStyle: string = this.nativeView._rawInlineStyle; // const styleDeclarations: string[] = rawInlineStyle.trim().split(";").map(styleDeclaration => styleDeclaration.trim()); // const styleMaps: [property: string, value: string][] = styleDeclarations.map((styleDeclaration) => styleDeclaration.split(":", 2) as [string, string]); // const stylesMap: Map<string, string> = new Map(); // styleMaps.forEach(([property, value]) => { // stylesMap.set(property, value); // }); // stylesMap.set(property, value); // const updatedRawInlineStyle: string = styleMaps.reduce((acc: string, [property, value]) => `${acc}\n${property}:${value};`, "").slice("\n".length); // this.nativeView.setInlineStyle(updatedRawInlineStyle); } /** * Accessed by Svelte's set_style() function. * Expected to return an object that provides setters for each style. * @example node.style.setProperty(key, value, important ? 'important' : ''); */ public readonly style = { setProperty: (propertyName: string, value: string, priority: "important"|"") => { // console.log(`[NSVElement] style.setProperty("${propertyName}", "${value}${priority ? " important" : ""}")`); this.setStyle(propertyName, value, priority); }, removeProperty: (propertyName: string) => { // console.log(`[NSVElement] style.removeProperty("${propertyName}")`); this.setStyle(propertyName, null, ""); }, get animation(): string { console.warn(`[NSVElement] Animation support not yet implemented.`); // return [...animations.keys()].join(", ") return ""; }, set animation(value: string) { console.warn(`[NSVElement] Animation support not yet implemented.`); // log.debug(() => `setting animation ${value}`) // let new_animations = value.trim() == "" ? [] : value.split(',').map(a => a.trim()); // //add new ones // for (let anim of new_animations) { // if (!animations.has(anim)) { // addAnimation(anim); // } // } // //remove old ones // for (let anim of animations.keys()) { // if (new_animations.indexOf(anim) < 0) { // removeAnimation(anim); // } // } }, get cssText(): string { console.warn(`[NSVElement.getCssText] (not yet implemented)`); return ""; // log.debug(() => "got css text"); // return getStyleAttribute(); }, set cssText(value: string) { console.warn(`[NSVElement.setCssText] (not yet implemented)`); // log.debug(() => "set css text"); // setStyleAttribute(value); } } updateNativeText(): void { if(componentHasPropertyAccessor(this.nativeView)){ this.nativeView.setProperty("text", this.textContent); return; } error(`updateNativeText() called on element that does not implement it.`, this); } get meta(): NSVViewMeta<T> { if (this._meta) { return this._meta } return (this._meta = getViewMeta(this.tagName)) } /** * We keep references to the event listeners so that the Svelte NodeGUI HostConfig can remove any attached event listener if it needs to replace it. */ private _eventListeners?: Map<string, any>; get eventListeners() { if(!this._eventListeners){ this._eventListeners = new Map(); } return this._eventListeners!; } addEventListener<Signals extends {}, SignalType extends keyof Signals>( event: SignalType, handler: Signals[SignalType], options: AddEventListenerOptions = {} ) { if(!componentIsEventWidget<Signals>(this.nativeView)){ return; } // log(`add event listener ${this} ${event}`); const { capture, once } = options if (capture) { warn('Bubble propagation is not supported') return } if (once) { const oldHandler = handler const self = this handler = ((...args: any) => { const res = (oldHandler as unknown as EventListener).call(null, ...args) if (res !== null) { self.removeEventListener(event, handler) } }) as unknown as Signals[SignalType] } //svelte compatibility wrapper (handler as any).__wrapper = (handler as any).__wrapper || ((args: unknown) => { /* I don't see any evidence that Qt events include the event name, so not sure what to do here. */ (args as any).type = event; (handler as unknown as EventListener)(args) }); this.nativeView.addEventListener<SignalType>(event, handler) this.eventListeners.set(event as string, handler); } removeEventListener<Signals extends {}, SignalType extends keyof Signals>(event: SignalType, handler?: Signals[SignalType]) { if(!componentIsEventWidget<Signals>(this.nativeView)){ return; } this.eventListeners.delete(event as string); this.nativeView.removeEventListener(event, handler) } dispatchEvent(event: string) { if (this.nativeView) { /** * I don't see that NodeGUI has implemented QCoreApplication::sendEvent, so I think we can only no-op here. * @see https://doc.qt.io/qt-5/eventsandfilters.html#sending-events * @see https://doc.qt.io/qt-5/qcoreapplication.html#sendEvent * * I don't see any evidence that Qt events include the event name, so not sure whether to pass * on an event name (which was for NativeScript purposes anyway) at all here. */ // this.nativeView.notify({ eventName: event, object: this.nativeView }) } } getAttribute(name: string): unknown { if(!this.nativeView){ return void 0; } if(componentHasPropertyAccessor(this.nativeView)){ /** * @see https://doc.qt.io/archives/qt-5.8/qobject.html#property */ return this.nativeView.property(name); } return (this.nativeView as any)[name]; } private static readonly recycledOldProps: Record<string, any> = Object.freeze({}); setAttribute(name: string, value: unknown) { /* * A note to myself after following this rabbit hole several times before: * Users may intuitively try to set the "text" property on an element such as <text>, simply because * it's a likely property name to expect, and because it appears to be corroborated by Intellisense, * due to our default of typing any unrecognised JSX key as a string value. * * In fact, RNText doesn't implement a text property in its setProps() method, so it (correctly) no-ops. * To set text, we expect users to write it as: * * <text>hello</text> * * ... This creates an NSVText node with the text "hello", which Svelte reads using the .data accessor. */ ["style", "styleSheet", // TODO: implement "class", "className"].forEach(n => { if(name.startsWith(n)){ // console.log(`[NSVElement.setAttribute("${name}", "${value}")]`); } }) if(name === "style"){ /* * e.g. <view style={`align-items: center; justify-content: center; height: 100%;`}> * c.f. <view style="align-items: center; justify-content: center; height: 100%;"> * * We have three options here. We can either: * 1) Parse the AST and set the styles one-by-one (neat, but inefficient), or; * 2) Serialise this.stylesMap and merge it with this incoming value. * 3) Clear this.stylesMap and replace _rawInlineStyle with this incoming value. * * The easiest to do is number 3..! */ this.stylesMap.clear(); if(componentIsStyleable(this._nativeView)){ // console.log(`[NSVElement.setAttribute("${name}", value)] – Setting _rawInlineStyle!`); this._nativeView.setInlineStyle(value as string); } return; } if(name === "stylesheet"){ console.warn(`[NSVElement.setAttribute("${name}", value)] – TODO: implement stylesheet.`); return; } if(name === "nodeRole" && typeof value === "string"){ this.nodeRole = value; return; } if(name === "id"){ // console.log(`[NSVElement.setAttribute("${name}", "${value}")]`); /** * setProps would also do the trick, but we want our wrapping element to set the very * same id on itself, too. */ this.id = value as string; return; } if(name === "class"){ // console.log(`[NSVElement.setAttribute("${name}", "${value}")] on <${this.tagName}>`); /** * The "class" property isn't handled by setProps for some reason. * It's probably special-cased by the React Host Config. */ if(componentHasPropertyAccessor(this.nativeView)){ /** * @see https://doc.qt.io/archives/qt-5.8/qobject.html#property */ this.nativeView.setProperty(name, value as string); return; } } // /** // * The 'ios' and 'android' properties (e.g. on ActionItem) // * are readonly, so we need to assign one level lower. // */ // if(name === "ios" && value){ // Object.keys(value).forEach((key: string) => { // set(this.nativeView.ios, key, value); // }); // return; // } // if(name === "android" && value){ // Object.keys(value).forEach((key: string) => { // set(this.nativeView.android, key, value); // }); // return; // } // set(this.nativeView, name, value) if(!this.nativeView){ return; } /** * React NodeGUI's API for setting props expects an object of props. * We only set props one-at-a-time, so we'll avoid reallocations by re-using and cleaning up the same static object. */ this.recycledNewProps[name] = value; this.nativeView.setProps(this.recycledNewProps, this.recycledOldProps); delete this.recycledNewProps[name]; /** * No way to tell whether a setter existed for the given attribute name, unfortunately. * So we can't fall back to this.nativeView.setProperty() (though arguably that would be dangerous anyway). */ } removeAttribute(name: string) { if(name === "nodeRole"){ this.nodeRole = void 0; return; } // potential issue: unsetValue is an empty object // not all properties/attributes may know/check for this // set(this.nativeView, name, unsetValue) // originally we deleted the property, but in case of built-in properties // this would break them. For example, deleting the padding property // will prevent us from changing the padding once we deleted it // that's not the expected behaviour. // unset(this.nativeView, name) console.warn( `[NSVElement.removeAttribute] React NodeGUI hasn't implemented removeAttribute, so it's unclear how to implement ` + `removeAttribute() in Svelte NodeGUI. You may want to try passing null or undefined instead of removing the attribute.` ); } removeChild(child: NSVNode): NSVNode { const node = super.removeChild(child); if (this.meta.viewFlags & NSVViewFlags.NO_CHILDREN) { // debug('NO_CHILDREN') return } if (this.meta?.viewFlags & NSVViewFlags.NO_CHILDREN) { // debug('NO_CHILDREN') return } if(child.nodeType === NSVNodeTypes.ELEMENT){ const childElement = child as NSVElement; if(this.nativeView){ if(childElement.nativeView){ // console.log(`Successful native remove: ${this.toString()} X ${childElement.toString()}`); this.nativeView.removeChild(childElement.nativeView); } else { // console.warn(`No native child to remove: ${this.toString()} X ${childElement.toString()}`); } } else { // console.warn(`Skipping native remove: ${this.toString()} X ${childElement.toString()}`); // It's probably a virtual element like Head, Style, etc; there is no native view to remove from. } } return node; } appendChild(child: NSVNode): NSVNode { const node = super.appendChild(child); if(child.nodeType === NSVNodeTypes.ELEMENT){ const childElement = child as NSVElement; if(this.meta?.nodeOps?.insert){ const defer: boolean = this.meta.nodeOps.insert(childElement, this, -1) === "defer"; if(!defer){ return node; } } if(this.nativeView){ if(childElement.nativeView){ // console.log(`Successful native append: ${this.toString()} > ${childElement.toString()}`); this.nativeView.appendChild(childElement.nativeView); } else { // console.warn(`No native child to append: ${this.toString()} > ${childElement.toString()}`); } } else { // console.warn(`Skipping native append: ${this.toString()} > ${childElement.toString()}`); // It's probably a virtual element like Head, Style, etc; there is no native view to append into. } } return node; } insertBefore(newNode: NSVNode, referenceNode?: NSVNode | null): NSVNode { const node = super.insertBefore(newNode, referenceNode); if(newNode.nodeType === NSVNodeTypes.ELEMENT){ const newElement = newNode as NSVElement; const referenceIndex = referenceNode == null ? -1 : this.childNodes.findIndex(node => node === referenceNode); if(this.meta?.nodeOps?.insert){ const defer: boolean = this.meta.nodeOps.insert(newElement, this, referenceIndex) === "defer"; if(!defer){ return node; } } if(this.nativeView){ if(newElement.nativeView){ if(referenceNode){ if((referenceNode as NSVElement).nativeView){ // console.log(`Successful native insertBefore: > ${newElement.toString()}, ${referenceNode.toString()}`); this.nativeView.insertBefore(newElement.nativeView, (referenceNode as NSVElement).nativeView); } else { // We're at the mercy of the underlying React NodeGUI and NodeGUI implementations. function findClosestNonVirtualPreviousElementSibling(node: NSVNode): NSVElement|null { let haul: NSVElement|null = null; while(node = node.previousSibling){ if(node.nodeType === NSVNodeTypes.ELEMENT && (node as NSVElement).nativeView){ haul = node as NSVElement; break; } } return haul; } const closest: NSVElement|null = findClosestNonVirtualPreviousElementSibling(referenceNode); if(closest){ // console.warn(`No native referenceNode to insertBefore (was given ${referenceNode.toString()}), so will try inserting before the closest eligible previousSibling instead: ${this.toString()} > ${newElement.toString()}, ${closest.toString()}`); this.nativeView.insertBefore(newElement.nativeView, closest.nativeView); } else { // console.warn(`No native referenceNode to insertBefore (was given ${referenceNode.toString()}), and no eligible previousSiblings, so will try appendChild instead: ${this.toString()} > ${newElement.toString()}`); this.nativeView.appendChild(newElement.nativeView); } } } else { // console.warn(`No referenceNode to insertBefore, so will try appendChild instead: ${this.toString()} > ${newElement.toString()}, ${referenceNode?.toString() ?? "NONE"}`); this.nativeView.appendChild(newElement.nativeView); } } else { console.warn(`No native newNode to insertBefore: ${this.toString()} > ${newElement.toString()}, ${referenceNode?.toString() ?? "NONE"}`); } } else { // It's probably a virtual element like Head, Style, etc; there is no native view to insert into. } } return node; } toString(): string { if(this.tagName === NSVNodeTypes.TEXT){ const textContent = this.textContent; return `<${this.tagName}(${this.nodeId}) id="${this.id}">${textContent.slice(0, 15)}${textContent.length > 15 ? "..." : ""}</text>`; } return `<${this.tagName}(${this.nodeId}) id="${this.id}">`; } } export class NSVComment extends NSVNode { constructor(public data: string = "") { super(NSVNodeTypes.COMMENT); } toString(): string { return "NSVComment:" + `"` + this.data + `"`; } } /** * This is a text node. It's a virtual element (is non-visual), and serves only as a data structure. * Whenever its data changes, we tell its parentNode to update its "text" property. */ export class NSVText extends NSVNode { private _data: string; constructor(data: string = ""){ super(NSVNodeTypes.TEXT); // console.log(`[NSVText] constructor "${this._text}"`); this.data = data; } get data(): string | undefined { return this._data; } set data(t: string | undefined) { // console.log(`NSVText text setter was called!`); this._data = t; // Tell any parent node to update its "text" property because this text node has just updated its contents. if(this.parentNode?.nodeType === NSVNodeTypes.ELEMENT){ (this.parentNode as NSVElement).updateNativeText(); } } /** * The Svelte runtime calls this upon the text node. * @see set_data() */ get wholeText(): string|undefined { // console.log(`NSVText get wholeText was called!`); let _wholeText = ""; if(this.previousSibling?.nodeType === NSVNodeTypes.TEXT){ _wholeText += (this.previousSibling as NSVText).data; } if(this.nextSibling?.nodeType === NSVNodeTypes.TEXT){ _wholeText += (this.nextSibling as NSVText).wholeText; // recurses } else { _wholeText += this.data; } // console.log(`get wholeText: ${_wholeText}`); return _wholeText; } replaceWholeText(wholeText: string): null | NSVText { console.log(`NSVText replaceWholeText was called!`); let recipient: NSVText = this; if(this.previousSibling?.nodeType === NSVNodeTypes.TEXT){ recipient = this.previousSibling as NSVText; } let nextSibling: NSVNode = recipient; while(nextSibling = recipient.nextSibling){ if(nextSibling.nodeType !== NSVNodeTypes.TEXT){ break; } nextSibling.parentNode.removeChild(nextSibling); } recipient.data = wholeText; return wholeText === "" ? null : recipient; } toString(): string { const textContent = this.textContent; return `<#text(${this.nodeId})>${this.data.slice(0, 15)}${this.data.length > 15 ? "..." : ""}</#text>`; } } export class NSVRoot<T extends NativeView = NativeView> extends NSVNode { baseRef?: NSVElement<T> constructor() { super(NSVNodeTypes.ROOT) } get text(): string | undefined { error(`text() getter called on element that does not implement it.`, this); return void 0; } set text(t: string | undefined) { error(`text() setter called on element that does not implement it.`, this); } setBaseRef(el: NSVNode|null): void { // console.log(`NSVRoot->appendChild(${el.nodeType})`) if (el instanceof NSVElement) { this.baseRef = el } // no-op } toString(): string { if(this.baseRef){ return "NSVRoot:" + this.baseRef.toString(); } else { return "NSVRoot:" + "null"; } } }
the_stack
import * as assert from "assert"; import * as ts from "typescript"; import {TypeChecker} from "../../type-checker"; import {CodeGenerationContext} from "../code-generation-context"; import {isMaybeObjectType} from "../util/types"; import {PerFileSourceFileRewirter} from "./per-file-source-file-rewriter"; import {MODULE_LOADER_FACTORY_NAME, PerFileWasmLoaderEmitHelper} from "./per-file-wasm-loader-emit-helper"; import {WastMetaData} from "./wast-meta-data"; interface Types { [name: string]: { primitive: boolean, fields: Array<{ name: string, type: string }>, constructor?: ts.Identifier; typeArguments: string[]; }; } /** * Inserts a wasm module loader function, the wasm byte code and rewrites the entry functions to call the wasm module. */ export class PerFileCodeGeneratorSourceFileRewriter implements PerFileSourceFileRewirter { private loadWasmFunctionIdentifier: ts.Identifier | undefined; private wasmUrl: string | undefined; private wastMetaData: Partial<WastMetaData> = {}; constructor(private context: CodeGenerationContext) {} setWastMetaData(metadata: WastMetaData): void { this.wastMetaData = metadata; } setWasmUrl(wasmUrl: string): void { this.wasmUrl = wasmUrl; } /** * Generates a new function declaration with an equal signature but replaced body. The body looks like * @code * const instance = await loadWasmModule(); * const result = instance.exports.fn.apply(undefined, arguments); // arguments are potentially cased * * speedyJsGc(); // only if not disableHeapNukeOnExit is set * * return result; // result is potentially casted * * fn is replaced with the passed in name * @param name the name of the function in the compilation * @param functionDeclaration the function declaration to transform * @return the new function declaration that acts as proxy / facade for a wasm function */ rewriteEntryFunction(name: string, functionDeclaration: ts.FunctionDeclaration): ts.FunctionDeclaration { this.loadWasmFunctionIdentifier = this.loadWasmFunctionIdentifier || ts.createUniqueName("loadWasmModule"); const signature = this.context.typeChecker.getSignatureFromDeclaration(functionDeclaration); const bodyStatements: ts.Statement[] = []; // types = { ... } const argumentTypes = signature.declaration.parameters.map(parameter => this.context.typeChecker.getTypeAtLocation(parameter)); const serializedTypes = this.serializeArgumentAndReturnTypes(argumentTypes, signature.getReturnType()); const typesIdentifier = ts.createUniqueName("types"); const typesDeclaration = ts.createVariableStatement(undefined , [ts.createVariableDeclaration(typesIdentifier, undefined, serializedTypes)]); let argumentObjects: ts.Identifier; // argumentObjects = new Map(); if (argumentTypes.findIndex(argumentType => (argumentType.flags & ts.TypeFlags.Object) !== 0 || isMaybeObjectType(argumentType)) !== -1) { argumentObjects = ts.createUniqueName("argumentObjects"); const argumentObjectsMap = ts.createNew(ts.createIdentifier("Map"), undefined, []); bodyStatements.push(ts.createVariableStatement(undefined, [ts.createVariableDeclaration(argumentObjects, undefined, argumentObjectsMap)])); } else { argumentObjects = ts.createIdentifier("undefined"); } // const result = instance.exports.fn(args) const instanceIdentifier = ts.createUniqueName("instance"); const wasmExports = ts.createPropertyAccess(instanceIdentifier, "exports"); const targetFunction = ts.createPropertyAccess(wasmExports, name); const args = signature.declaration.parameters.map(parameter => this.castToWasm( parameter, this.loadWasmFunctionIdentifier!, typesIdentifier, argumentObjects) ); const functionCall = ts.createCall(targetFunction, [], args); const castedResult = this.castToJs(functionCall, signature.getReturnType(), this.loadWasmFunctionIdentifier!, typesIdentifier); const resultIdentifier = ts.createUniqueName("result"); const resultVariable = ts.createVariableDeclaration(resultIdentifier, undefined, castedResult); bodyStatements.push(ts.createVariableStatement(undefined, [resultVariable])); if (!this.context.compilationContext.compilerOptions.disableHeapNukeOnExit) { // speedyJsGc(); bodyStatements.push(ts.createStatement(ts.createCall(ts.createPropertyAccess(this.loadWasmFunctionIdentifier, "gc"), [], []))); } bodyStatements.push(ts.createReturn(resultIdentifier)); // function (instance) { ... } const instanceParameter = ts.createParameter(undefined, undefined, undefined, instanceIdentifier); const loadHandlerBody = ts.createBlock(bodyStatements); const loadedHandler = ts.createFunctionExpression(undefined, undefined, "instanceLoaded", undefined, [ instanceParameter ], undefined, loadHandlerBody); // loadWasmModule().then(instance => ); const loadInstance = ts.createCall(this.loadWasmFunctionIdentifier, [], []); const instanceLoaded = ts.createCall(ts.createPropertyAccess(loadInstance, "then"), [], [ loadedHandler ]); return ts.updateFunctionDeclaration( functionDeclaration, functionDeclaration.decorators, (functionDeclaration.modifiers || [] as ts.Modifier[]).filter(modifier => modifier.kind !== ts.SyntaxKind.AsyncKeyword), functionDeclaration.asteriskToken, functionDeclaration.name, functionDeclaration.typeParameters, functionDeclaration.parameters, functionDeclaration.type, ts.createBlock([typesDeclaration, ts.createReturn(instanceLoaded)]) ); } rewriteSourceFile(sourceFile: ts.SourceFile, requestEmitHelper: (emitHelper: ts.EmitHelper) => void): ts.SourceFile { assert (this.wasmUrl, `No wasm fetch expression set but requested to transform the source file`); if (!this.loadWasmFunctionIdentifier) { return sourceFile; } requestEmitHelper(new PerFileWasmLoaderEmitHelper()); const compilerOptions = this.context.compilationContext.compilerOptions; let staticBump = this.wastMetaData.staticBump || 0; if (staticBump % 16 !== 0) { staticBump += 16 - staticBump % 16; } const options = toLiteral({ totalStack: compilerOptions.totalStack, initialMemory: compilerOptions.initialMemory, globalBase: compilerOptions.globalBase, staticBump, exposeGc: compilerOptions.exportGc || compilerOptions.exposeGc }); const initializer = ts.createCall(ts.createIdentifier(MODULE_LOADER_FACTORY_NAME), [], [ ts.createLiteral(this.wasmUrl!), options ]); const statements = sourceFile.statements; const statementsToInsert = []; // var loadWasmModule = _moduleLoader(...); const loaderDeclaration = ts.createVariableDeclarationList([ts.createVariableDeclaration(this.loadWasmFunctionIdentifier, undefined, initializer)]); statementsToInsert.push(ts.createVariableStatement([], loaderDeclaration)); // export let speedyJsGc = loadWasmModule_1.gc; or without export if only expose if (compilerOptions.exposeGc || compilerOptions.exportGc) { const speedyJsGcVariable = ts.createVariableDeclaration("speedyJsGc", undefined, ts.createPropertyAccess(this.loadWasmFunctionIdentifier, "gc")); const speedyJsGcDeclaration = ts.createVariableDeclarationList([speedyJsGcVariable], ts.NodeFlags.Const); const modifiers = compilerOptions.exportGc ? [ ts.createToken(ts.SyntaxKind.ExportKeyword) ] : []; statementsToInsert.push(ts.createVariableStatement(modifiers, speedyJsGcDeclaration)); } return ts.updateSourceFileNode(sourceFile, [...statementsToInsert, ...statements]); } private castToJs(returnValue: ts.Expression, type: ts.Type, loadWasmFunctionIdentifier: ts.Identifier, typesIdentifier: ts.Identifier): ts.Expression { // wasm code returns 1 for true and zero for false. Cast it to a boolean if (type.flags & ts.TypeFlags.BooleanLike) { return ts.createBinary(returnValue, ts.SyntaxKind.EqualsEqualsEqualsToken, ts.createNumericLiteral("1")); } if (type.flags & ts.TypeFlags.Object || isMaybeObjectType(type)) { return ts.createCall(ts.createPropertyAccess(loadWasmFunctionIdentifier, "toJSObject"), undefined, [ returnValue, ts.createLiteral(serializedTypeName(type, this.context.typeChecker)), typesIdentifier ]); } return returnValue; } private castToWasm(parameterDeclaration: ts.ParameterDeclaration, loadWasmFunctionIdentifier: ts.Identifier, typesIdentifier: ts.Identifier, argumentObjects: ts.Identifier): ts.Expression { const parameterType = this.context.typeChecker.getTypeAtLocation(parameterDeclaration); const symbol = this.context.typeChecker.getSymbolAtLocation(parameterDeclaration.name); if (parameterType.flags & ts.TypeFlags.Object || isMaybeObjectType(parameterType)) { return ts.createCall(ts.createPropertyAccess(loadWasmFunctionIdentifier, "toWASM"), undefined, [ ts.createIdentifier(symbol.name), ts.createLiteral(serializedTypeName(parameterType, this.context.typeChecker)), typesIdentifier, argumentObjects ]); } return ts.createIdentifier(symbol.name); } private serializeArgumentAndReturnTypes(argumentTypes: ts.Type[], returnType: ts.Type) { const types: Types = {}; const typesToProcess = Array.from(new Set([...argumentTypes, returnType])); while (typesToProcess.length > 0) { let type = typesToProcess.pop()!; if (type.flags & ts.TypeFlags.Void) { continue; } const name = serializedTypeName(type, this.context.typeChecker); if (name in types) { continue; } const primitive = !!(type.flags & ts.TypeFlags.BooleanLike || type.flags & ts.TypeFlags.IntLike || type.flags & ts.TypeFlags.NumberLike); let fields: Array<{ name: string, type: string }> = []; const typeArguments: string[] = []; let constructor: ts.Identifier | undefined; if (isMaybeObjectType(type)) { type = type.getNonNullableType(); } if (type.flags & ts.TypeFlags.Object) { const objectType = type as ts.ObjectType; const classReference = this.context.resolveClass(type); assert(classReference, "Class Reference for argument or return type " + this.context.typeChecker.typeToString(type) + " not found."); fields = classReference!.getFields(objectType, this.context).map(field => { typesToProcess.push(field.type); return { name: field.name, type: serializedTypeName(field.type, this.context.typeChecker) }; }); if (objectType.objectFlags & ts.ObjectFlags.Reference && (objectType as ts.TypeReference).typeArguments) { const typeReference = objectType as ts.TypeReference; typesToProcess.push(...typeReference.typeArguments); typeArguments.push(...typeReference.typeArguments.map(typeArgument => serializedTypeName(typeArgument, this.context.typeChecker))); } constructor = ts.createIdentifier(type.getSymbol().getName()); } types[name] = { primitive, fields, constructor, typeArguments }; } return toLiteral(types); } } function serializedTypeName(type: ts.Type, typeChecker: TypeChecker): string { if (isMaybeObjectType(type)) { type = type.getNonNullableType(); } if (type.flags & ts.TypeFlags.BooleanLike) { return "i1"; } else if (type.flags & ts.TypeFlags.IntLike) { return "i32"; } else if (type.flags & ts.TypeFlags.NumberLike) { return "double"; } else if (type.flags & ts.TypeFlags.Object) { const objectType = type as ts.ObjectType; let className = typeChecker.getFullyQualifiedName(type.getSymbol()); if (objectType.objectFlags & ts.ObjectFlags.Reference && (objectType as ts.TypeReference).typeArguments) { const typeArguments = (objectType as ts.TypeReference).typeArguments.map(typeArgument => serializedTypeName(typeArgument, typeChecker)); className += `<${typeArguments}>`; } return className; } else { throw new Error("Unsupported type " + typeChecker.typeToString(type)); } } function toLiteral(value: any): ts.Expression { if (Array.isArray(value)) { return ts.createArrayLiteral(value.map(element => toLiteral(element))); } else if (typeof value === "object") { if (value.kind && value.flags) { // ts node return value as ts.Expression; } return ts.createObjectLiteral( Object.keys(value).map(property => { const propertyValue = value[property]; return ts.createPropertyAssignment(ts.createLiteral(property), toLiteral(propertyValue)); }) ); } else if (typeof value === "undefined") { return ts.createIdentifier("undefined"); } else if (typeof value === "number" || typeof value === "boolean" || typeof(value) === "string") { return ts.createLiteral(value); } throw new Error("Unsupported value of type " + typeof(value)); }
the_stack
import gql from 'graphql-tag'; import * as ApolloReactCommon from '@apollo/react-common'; import * as ApolloReactHooks from '@apollo/react-hooks'; export type Maybe<T> = T | null; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string, String: string, Boolean: boolean, Int: number, Float: number, DateTime: any, }; export type Account = { __typename?: 'Account', id: Scalars['Int'], sortCode: Scalars['String'], iban: Scalars['String'], bic: Scalars['String'], currency: Scalars['String'], balance: Scalars['Float'], }; export type AccountResponse = { __typename?: 'AccountResponse', account: Account, message: Scalars['String'], }; export type Card = { __typename?: 'Card', id: Scalars['Int'], cardNumber: Scalars['String'], pin: Scalars['Float'], expiresIn: Scalars['DateTime'], cvv: Scalars['Float'], monthlySpendingLimit: Scalars['Float'], }; export type LoginResponse = { __typename?: 'LoginResponse', accessToken: Scalars['String'], user: User, }; export type Mutation = { __typename?: 'Mutation', logout: Scalars['Boolean'], revokeRefreshTokensForUser: Scalars['Boolean'], login: LoginResponse, register: Scalars['Boolean'], updatePassword: Scalars['Boolean'], destroyAccount: Scalars['Boolean'], addMoney: AccountResponse, exchange: AccountResponse, createAccount: Scalars['Boolean'], deleteAccount: Scalars['Boolean'], createTransaction: Scalars['Float'], createCard: Scalars['Boolean'], }; export type MutationRevokeRefreshTokensForUserArgs = { userId: Scalars['Int'] }; export type MutationLoginArgs = { password: Scalars['String'], email: Scalars['String'] }; export type MutationRegisterArgs = { country: Scalars['String'], city: Scalars['String'], postCode: Scalars['String'], streetAddress: Scalars['String'], dateOfBirth: Scalars['String'], lastName: Scalars['String'], firsName: Scalars['String'], password: Scalars['String'], email: Scalars['String'] }; export type MutationUpdatePasswordArgs = { newPassword: Scalars['String'], oldPassword: Scalars['String'] }; export type MutationAddMoneyArgs = { currency: Scalars['String'], amount: Scalars['Float'] }; export type MutationExchangeArgs = { amount: Scalars['Float'], toAccountCurrency: Scalars['String'], selectedAccountCurrency: Scalars['String'] }; export type MutationCreateAccountArgs = { currency: Scalars['String'] }; export type MutationDeleteAccountArgs = { currency: Scalars['String'] }; export type MutationCreateTransactionArgs = { currency: Scalars['String'] }; export type Query = { __typename?: 'Query', me?: Maybe<User>, accounts: Array<Account>, account: Account, transactions: Array<Transaction>, cards: Array<Card>, }; export type QueryAccountArgs = { currency: Scalars['String'] }; export type QueryTransactionsArgs = { currency: Scalars['String'] }; export type Transaction = { __typename?: 'Transaction', id: Scalars['Int'], transactionType: Scalars['String'], date: Scalars['DateTime'], amount: Scalars['String'], }; export type User = { __typename?: 'User', id: Scalars['Int'], email: Scalars['String'], firstName: Scalars['String'], lastName: Scalars['String'], dateOfBirth: Scalars['String'], streetAddress: Scalars['String'], postCode: Scalars['String'], city: Scalars['String'], country: Scalars['String'], }; export type AccountQueryVariables = { currency: Scalars['String'] }; export type AccountQuery = ( { __typename?: 'Query' } & { account: ( { __typename?: 'Account' } & Pick<Account, 'id' | 'balance'> ) } ); export type AccountsQueryVariables = {}; export type AccountsQuery = ( { __typename?: 'Query' } & { accounts: Array<( { __typename?: 'Account' } & Pick<Account, 'id' | 'balance' | 'currency' | 'sortCode' | 'iban' | 'bic'> )> } ); export type AddMoneyMutationVariables = { amount: Scalars['Float'], currency: Scalars['String'] }; export type AddMoneyMutation = ( { __typename?: 'Mutation' } & { addMoney: ( { __typename?: 'AccountResponse' } & Pick<AccountResponse, 'message'> & { account: ( { __typename?: 'Account' } & Pick<Account, 'id' | 'balance'> ) } ) } ); export type CardsQueryVariables = {}; export type CardsQuery = ( { __typename?: 'Query' } & { cards: Array<( { __typename?: 'Card' } & Pick<Card, 'id' | 'cardNumber' | 'pin' | 'expiresIn' | 'cvv' | 'monthlySpendingLimit'> )> } ); export type CreateAccountMutationVariables = { currency: Scalars['String'] }; export type CreateAccountMutation = ( { __typename?: 'Mutation' } & Pick<Mutation, 'createAccount'> ); export type CreateCardMutationVariables = {}; export type CreateCardMutation = ( { __typename?: 'Mutation' } & Pick<Mutation, 'createCard'> ); export type CreateTransactionMutationVariables = { currency: Scalars['String'] }; export type CreateTransactionMutation = ( { __typename?: 'Mutation' } & Pick<Mutation, 'createTransaction'> ); export type DeleteAccountMutationVariables = { currency: Scalars['String'] }; export type DeleteAccountMutation = ( { __typename?: 'Mutation' } & Pick<Mutation, 'deleteAccount'> ); export type DestroyAccountMutationVariables = {}; export type DestroyAccountMutation = ( { __typename?: 'Mutation' } & Pick<Mutation, 'destroyAccount'> ); export type ExchangeMutationVariables = { selectedAccountCurrency: Scalars['String'], toAccountCurrency: Scalars['String'], amount: Scalars['Float'] }; export type ExchangeMutation = ( { __typename?: 'Mutation' } & { exchange: ( { __typename?: 'AccountResponse' } & Pick<AccountResponse, 'message'> & { account: ( { __typename?: 'Account' } & Pick<Account, 'id' | 'balance'> ) } ) } ); export type LoginMutationVariables = { email: Scalars['String'], password: Scalars['String'] }; export type LoginMutation = ( { __typename?: 'Mutation' } & { login: ( { __typename?: 'LoginResponse' } & Pick<LoginResponse, 'accessToken'> & { user: ( { __typename?: 'User' } & Pick<User, 'id' | 'email' | 'firstName' | 'lastName' | 'dateOfBirth' | 'streetAddress' | 'postCode' | 'city' | 'country'> ) } ) } ); export type LogoutMutationVariables = {}; export type LogoutMutation = ( { __typename?: 'Mutation' } & Pick<Mutation, 'logout'> ); export type MeQueryVariables = {}; export type MeQuery = ( { __typename?: 'Query' } & { me: Maybe<( { __typename?: 'User' } & Pick<User, 'id' | 'email' | 'firstName' | 'lastName' | 'dateOfBirth' | 'streetAddress' | 'postCode' | 'city' | 'country'> )> } ); export type RegisterMutationVariables = { email: Scalars['String'], password: Scalars['String'], firstName: Scalars['String'], lastName: Scalars['String'], dateOfBirth: Scalars['String'], streetAddress: Scalars['String'], postCode: Scalars['String'], city: Scalars['String'], country: Scalars['String'] }; export type RegisterMutation = ( { __typename?: 'Mutation' } & Pick<Mutation, 'register'> ); export type TransactionsQueryVariables = { currency: Scalars['String'] }; export type TransactionsQuery = ( { __typename?: 'Query' } & { transactions: Array<( { __typename?: 'Transaction' } & Pick<Transaction, 'id' | 'transactionType' | 'date' | 'amount'> )> } ); export type UpdatePasswordMutationVariables = { oldPassword: Scalars['String'], newPassword: Scalars['String'] }; export type UpdatePasswordMutation = ( { __typename?: 'Mutation' } & Pick<Mutation, 'updatePassword'> ); export const AccountDocument = gql` query Account($currency: String!) { account(currency: $currency) { id balance } } `; /** * __useAccountQuery__ * * To run a query within a React component, call `useAccountQuery` and pass it any options that fit your needs. * When your component renders, `useAccountQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useAccountQuery({ * variables: { * currency: // value for 'currency' * }, * }); */ export function useAccountQuery(baseOptions?: ApolloReactHooks.QueryHookOptions<AccountQuery, AccountQueryVariables>) { return ApolloReactHooks.useQuery<AccountQuery, AccountQueryVariables>(AccountDocument, baseOptions); } export function useAccountLazyQuery(baseOptions?: ApolloReactHooks.LazyQueryHookOptions<AccountQuery, AccountQueryVariables>) { return ApolloReactHooks.useLazyQuery<AccountQuery, AccountQueryVariables>(AccountDocument, baseOptions); } export type AccountQueryHookResult = ReturnType<typeof useAccountQuery>; export type AccountLazyQueryHookResult = ReturnType<typeof useAccountLazyQuery>; export type AccountQueryResult = ApolloReactCommon.QueryResult<AccountQuery, AccountQueryVariables>; export const AccountsDocument = gql` query Accounts { accounts { id balance currency sortCode iban bic } } `; /** * __useAccountsQuery__ * * To run a query within a React component, call `useAccountsQuery` and pass it any options that fit your needs. * When your component renders, `useAccountsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useAccountsQuery({ * variables: { * }, * }); */ export function useAccountsQuery(baseOptions?: ApolloReactHooks.QueryHookOptions<AccountsQuery, AccountsQueryVariables>) { return ApolloReactHooks.useQuery<AccountsQuery, AccountsQueryVariables>(AccountsDocument, baseOptions); } export function useAccountsLazyQuery(baseOptions?: ApolloReactHooks.LazyQueryHookOptions<AccountsQuery, AccountsQueryVariables>) { return ApolloReactHooks.useLazyQuery<AccountsQuery, AccountsQueryVariables>(AccountsDocument, baseOptions); } export type AccountsQueryHookResult = ReturnType<typeof useAccountsQuery>; export type AccountsLazyQueryHookResult = ReturnType<typeof useAccountsLazyQuery>; export type AccountsQueryResult = ApolloReactCommon.QueryResult<AccountsQuery, AccountsQueryVariables>; export const AddMoneyDocument = gql` mutation AddMoney($amount: Float!, $currency: String!) { addMoney(amount: $amount, currency: $currency) { account { id balance } message } } `; export type AddMoneyMutationFn = ApolloReactCommon.MutationFunction<AddMoneyMutation, AddMoneyMutationVariables>; /** * __useAddMoneyMutation__ * * To run a mutation, you first call `useAddMoneyMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useAddMoneyMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [addMoneyMutation, { data, loading, error }] = useAddMoneyMutation({ * variables: { * amount: // value for 'amount' * currency: // value for 'currency' * }, * }); */ export function useAddMoneyMutation(baseOptions?: ApolloReactHooks.MutationHookOptions<AddMoneyMutation, AddMoneyMutationVariables>) { return ApolloReactHooks.useMutation<AddMoneyMutation, AddMoneyMutationVariables>(AddMoneyDocument, baseOptions); } export type AddMoneyMutationHookResult = ReturnType<typeof useAddMoneyMutation>; export type AddMoneyMutationResult = ApolloReactCommon.MutationResult<AddMoneyMutation>; export type AddMoneyMutationOptions = ApolloReactCommon.BaseMutationOptions<AddMoneyMutation, AddMoneyMutationVariables>; export const CardsDocument = gql` query Cards { cards { id cardNumber pin expiresIn cvv monthlySpendingLimit } } `; /** * __useCardsQuery__ * * To run a query within a React component, call `useCardsQuery` and pass it any options that fit your needs. * When your component renders, `useCardsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useCardsQuery({ * variables: { * }, * }); */ export function useCardsQuery(baseOptions?: ApolloReactHooks.QueryHookOptions<CardsQuery, CardsQueryVariables>) { return ApolloReactHooks.useQuery<CardsQuery, CardsQueryVariables>(CardsDocument, baseOptions); } export function useCardsLazyQuery(baseOptions?: ApolloReactHooks.LazyQueryHookOptions<CardsQuery, CardsQueryVariables>) { return ApolloReactHooks.useLazyQuery<CardsQuery, CardsQueryVariables>(CardsDocument, baseOptions); } export type CardsQueryHookResult = ReturnType<typeof useCardsQuery>; export type CardsLazyQueryHookResult = ReturnType<typeof useCardsLazyQuery>; export type CardsQueryResult = ApolloReactCommon.QueryResult<CardsQuery, CardsQueryVariables>; export const CreateAccountDocument = gql` mutation CreateAccount($currency: String!) { createAccount(currency: $currency) } `; export type CreateAccountMutationFn = ApolloReactCommon.MutationFunction<CreateAccountMutation, CreateAccountMutationVariables>; /** * __useCreateAccountMutation__ * * To run a mutation, you first call `useCreateAccountMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useCreateAccountMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [createAccountMutation, { data, loading, error }] = useCreateAccountMutation({ * variables: { * currency: // value for 'currency' * }, * }); */ export function useCreateAccountMutation(baseOptions?: ApolloReactHooks.MutationHookOptions<CreateAccountMutation, CreateAccountMutationVariables>) { return ApolloReactHooks.useMutation<CreateAccountMutation, CreateAccountMutationVariables>(CreateAccountDocument, baseOptions); } export type CreateAccountMutationHookResult = ReturnType<typeof useCreateAccountMutation>; export type CreateAccountMutationResult = ApolloReactCommon.MutationResult<CreateAccountMutation>; export type CreateAccountMutationOptions = ApolloReactCommon.BaseMutationOptions<CreateAccountMutation, CreateAccountMutationVariables>; export const CreateCardDocument = gql` mutation createCard { createCard } `; export type CreateCardMutationFn = ApolloReactCommon.MutationFunction<CreateCardMutation, CreateCardMutationVariables>; /** * __useCreateCardMutation__ * * To run a mutation, you first call `useCreateCardMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useCreateCardMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [createCardMutation, { data, loading, error }] = useCreateCardMutation({ * variables: { * }, * }); */ export function useCreateCardMutation(baseOptions?: ApolloReactHooks.MutationHookOptions<CreateCardMutation, CreateCardMutationVariables>) { return ApolloReactHooks.useMutation<CreateCardMutation, CreateCardMutationVariables>(CreateCardDocument, baseOptions); } export type CreateCardMutationHookResult = ReturnType<typeof useCreateCardMutation>; export type CreateCardMutationResult = ApolloReactCommon.MutationResult<CreateCardMutation>; export type CreateCardMutationOptions = ApolloReactCommon.BaseMutationOptions<CreateCardMutation, CreateCardMutationVariables>; export const CreateTransactionDocument = gql` mutation CreateTransaction($currency: String!) { createTransaction(currency: $currency) } `; export type CreateTransactionMutationFn = ApolloReactCommon.MutationFunction<CreateTransactionMutation, CreateTransactionMutationVariables>; /** * __useCreateTransactionMutation__ * * To run a mutation, you first call `useCreateTransactionMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useCreateTransactionMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [createTransactionMutation, { data, loading, error }] = useCreateTransactionMutation({ * variables: { * currency: // value for 'currency' * }, * }); */ export function useCreateTransactionMutation(baseOptions?: ApolloReactHooks.MutationHookOptions<CreateTransactionMutation, CreateTransactionMutationVariables>) { return ApolloReactHooks.useMutation<CreateTransactionMutation, CreateTransactionMutationVariables>(CreateTransactionDocument, baseOptions); } export type CreateTransactionMutationHookResult = ReturnType<typeof useCreateTransactionMutation>; export type CreateTransactionMutationResult = ApolloReactCommon.MutationResult<CreateTransactionMutation>; export type CreateTransactionMutationOptions = ApolloReactCommon.BaseMutationOptions<CreateTransactionMutation, CreateTransactionMutationVariables>; export const DeleteAccountDocument = gql` mutation DeleteAccount($currency: String!) { deleteAccount(currency: $currency) } `; export type DeleteAccountMutationFn = ApolloReactCommon.MutationFunction<DeleteAccountMutation, DeleteAccountMutationVariables>; /** * __useDeleteAccountMutation__ * * To run a mutation, you first call `useDeleteAccountMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useDeleteAccountMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [deleteAccountMutation, { data, loading, error }] = useDeleteAccountMutation({ * variables: { * currency: // value for 'currency' * }, * }); */ export function useDeleteAccountMutation(baseOptions?: ApolloReactHooks.MutationHookOptions<DeleteAccountMutation, DeleteAccountMutationVariables>) { return ApolloReactHooks.useMutation<DeleteAccountMutation, DeleteAccountMutationVariables>(DeleteAccountDocument, baseOptions); } export type DeleteAccountMutationHookResult = ReturnType<typeof useDeleteAccountMutation>; export type DeleteAccountMutationResult = ApolloReactCommon.MutationResult<DeleteAccountMutation>; export type DeleteAccountMutationOptions = ApolloReactCommon.BaseMutationOptions<DeleteAccountMutation, DeleteAccountMutationVariables>; export const DestroyAccountDocument = gql` mutation DestroyAccount { destroyAccount } `; export type DestroyAccountMutationFn = ApolloReactCommon.MutationFunction<DestroyAccountMutation, DestroyAccountMutationVariables>; /** * __useDestroyAccountMutation__ * * To run a mutation, you first call `useDestroyAccountMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useDestroyAccountMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [destroyAccountMutation, { data, loading, error }] = useDestroyAccountMutation({ * variables: { * }, * }); */ export function useDestroyAccountMutation(baseOptions?: ApolloReactHooks.MutationHookOptions<DestroyAccountMutation, DestroyAccountMutationVariables>) { return ApolloReactHooks.useMutation<DestroyAccountMutation, DestroyAccountMutationVariables>(DestroyAccountDocument, baseOptions); } export type DestroyAccountMutationHookResult = ReturnType<typeof useDestroyAccountMutation>; export type DestroyAccountMutationResult = ApolloReactCommon.MutationResult<DestroyAccountMutation>; export type DestroyAccountMutationOptions = ApolloReactCommon.BaseMutationOptions<DestroyAccountMutation, DestroyAccountMutationVariables>; export const ExchangeDocument = gql` mutation Exchange($selectedAccountCurrency: String!, $toAccountCurrency: String!, $amount: Float!) { exchange(selectedAccountCurrency: $selectedAccountCurrency, toAccountCurrency: $toAccountCurrency, amount: $amount) { account { id balance } message } } `; export type ExchangeMutationFn = ApolloReactCommon.MutationFunction<ExchangeMutation, ExchangeMutationVariables>; /** * __useExchangeMutation__ * * To run a mutation, you first call `useExchangeMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useExchangeMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [exchangeMutation, { data, loading, error }] = useExchangeMutation({ * variables: { * selectedAccountCurrency: // value for 'selectedAccountCurrency' * toAccountCurrency: // value for 'toAccountCurrency' * amount: // value for 'amount' * }, * }); */ export function useExchangeMutation(baseOptions?: ApolloReactHooks.MutationHookOptions<ExchangeMutation, ExchangeMutationVariables>) { return ApolloReactHooks.useMutation<ExchangeMutation, ExchangeMutationVariables>(ExchangeDocument, baseOptions); } export type ExchangeMutationHookResult = ReturnType<typeof useExchangeMutation>; export type ExchangeMutationResult = ApolloReactCommon.MutationResult<ExchangeMutation>; export type ExchangeMutationOptions = ApolloReactCommon.BaseMutationOptions<ExchangeMutation, ExchangeMutationVariables>; export const LoginDocument = gql` mutation Login($email: String!, $password: String!) { login(email: $email, password: $password) { accessToken user { id email firstName lastName dateOfBirth streetAddress postCode city country } } } `; export type LoginMutationFn = ApolloReactCommon.MutationFunction<LoginMutation, LoginMutationVariables>; /** * __useLoginMutation__ * * To run a mutation, you first call `useLoginMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useLoginMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [loginMutation, { data, loading, error }] = useLoginMutation({ * variables: { * email: // value for 'email' * password: // value for 'password' * }, * }); */ export function useLoginMutation(baseOptions?: ApolloReactHooks.MutationHookOptions<LoginMutation, LoginMutationVariables>) { return ApolloReactHooks.useMutation<LoginMutation, LoginMutationVariables>(LoginDocument, baseOptions); } export type LoginMutationHookResult = ReturnType<typeof useLoginMutation>; export type LoginMutationResult = ApolloReactCommon.MutationResult<LoginMutation>; export type LoginMutationOptions = ApolloReactCommon.BaseMutationOptions<LoginMutation, LoginMutationVariables>; export const LogoutDocument = gql` mutation Logout { logout } `; export type LogoutMutationFn = ApolloReactCommon.MutationFunction<LogoutMutation, LogoutMutationVariables>; /** * __useLogoutMutation__ * * To run a mutation, you first call `useLogoutMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useLogoutMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [logoutMutation, { data, loading, error }] = useLogoutMutation({ * variables: { * }, * }); */ export function useLogoutMutation(baseOptions?: ApolloReactHooks.MutationHookOptions<LogoutMutation, LogoutMutationVariables>) { return ApolloReactHooks.useMutation<LogoutMutation, LogoutMutationVariables>(LogoutDocument, baseOptions); } export type LogoutMutationHookResult = ReturnType<typeof useLogoutMutation>; export type LogoutMutationResult = ApolloReactCommon.MutationResult<LogoutMutation>; export type LogoutMutationOptions = ApolloReactCommon.BaseMutationOptions<LogoutMutation, LogoutMutationVariables>; export const MeDocument = gql` query Me { me { id email firstName lastName dateOfBirth streetAddress postCode city country } } `; /** * __useMeQuery__ * * To run a query within a React component, call `useMeQuery` and pass it any options that fit your needs. * When your component renders, `useMeQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useMeQuery({ * variables: { * }, * }); */ export function useMeQuery(baseOptions?: ApolloReactHooks.QueryHookOptions<MeQuery, MeQueryVariables>) { return ApolloReactHooks.useQuery<MeQuery, MeQueryVariables>(MeDocument, baseOptions); } export function useMeLazyQuery(baseOptions?: ApolloReactHooks.LazyQueryHookOptions<MeQuery, MeQueryVariables>) { return ApolloReactHooks.useLazyQuery<MeQuery, MeQueryVariables>(MeDocument, baseOptions); } export type MeQueryHookResult = ReturnType<typeof useMeQuery>; export type MeLazyQueryHookResult = ReturnType<typeof useMeLazyQuery>; export type MeQueryResult = ApolloReactCommon.QueryResult<MeQuery, MeQueryVariables>; export const RegisterDocument = gql` mutation Register($email: String!, $password: String!, $firstName: String!, $lastName: String!, $dateOfBirth: String!, $streetAddress: String!, $postCode: String!, $city: String!, $country: String!) { register(email: $email, password: $password, firsName: $firstName, lastName: $lastName, dateOfBirth: $dateOfBirth, streetAddress: $streetAddress, postCode: $postCode, city: $city, country: $country) } `; export type RegisterMutationFn = ApolloReactCommon.MutationFunction<RegisterMutation, RegisterMutationVariables>; /** * __useRegisterMutation__ * * To run a mutation, you first call `useRegisterMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useRegisterMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [registerMutation, { data, loading, error }] = useRegisterMutation({ * variables: { * email: // value for 'email' * password: // value for 'password' * firstName: // value for 'firstName' * lastName: // value for 'lastName' * dateOfBirth: // value for 'dateOfBirth' * streetAddress: // value for 'streetAddress' * postCode: // value for 'postCode' * city: // value for 'city' * country: // value for 'country' * }, * }); */ export function useRegisterMutation(baseOptions?: ApolloReactHooks.MutationHookOptions<RegisterMutation, RegisterMutationVariables>) { return ApolloReactHooks.useMutation<RegisterMutation, RegisterMutationVariables>(RegisterDocument, baseOptions); } export type RegisterMutationHookResult = ReturnType<typeof useRegisterMutation>; export type RegisterMutationResult = ApolloReactCommon.MutationResult<RegisterMutation>; export type RegisterMutationOptions = ApolloReactCommon.BaseMutationOptions<RegisterMutation, RegisterMutationVariables>; export const TransactionsDocument = gql` query Transactions($currency: String!) { transactions(currency: $currency) { id transactionType date amount } } `; /** * __useTransactionsQuery__ * * To run a query within a React component, call `useTransactionsQuery` and pass it any options that fit your needs. * When your component renders, `useTransactionsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useTransactionsQuery({ * variables: { * currency: // value for 'currency' * }, * }); */ export function useTransactionsQuery(baseOptions?: ApolloReactHooks.QueryHookOptions<TransactionsQuery, TransactionsQueryVariables>) { return ApolloReactHooks.useQuery<TransactionsQuery, TransactionsQueryVariables>(TransactionsDocument, baseOptions); } export function useTransactionsLazyQuery(baseOptions?: ApolloReactHooks.LazyQueryHookOptions<TransactionsQuery, TransactionsQueryVariables>) { return ApolloReactHooks.useLazyQuery<TransactionsQuery, TransactionsQueryVariables>(TransactionsDocument, baseOptions); } export type TransactionsQueryHookResult = ReturnType<typeof useTransactionsQuery>; export type TransactionsLazyQueryHookResult = ReturnType<typeof useTransactionsLazyQuery>; export type TransactionsQueryResult = ApolloReactCommon.QueryResult<TransactionsQuery, TransactionsQueryVariables>; export const UpdatePasswordDocument = gql` mutation UpdatePassword($oldPassword: String!, $newPassword: String!) { updatePassword(oldPassword: $oldPassword, newPassword: $newPassword) } `; export type UpdatePasswordMutationFn = ApolloReactCommon.MutationFunction<UpdatePasswordMutation, UpdatePasswordMutationVariables>; /** * __useUpdatePasswordMutation__ * * To run a mutation, you first call `useUpdatePasswordMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useUpdatePasswordMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [updatePasswordMutation, { data, loading, error }] = useUpdatePasswordMutation({ * variables: { * oldPassword: // value for 'oldPassword' * newPassword: // value for 'newPassword' * }, * }); */ export function useUpdatePasswordMutation(baseOptions?: ApolloReactHooks.MutationHookOptions<UpdatePasswordMutation, UpdatePasswordMutationVariables>) { return ApolloReactHooks.useMutation<UpdatePasswordMutation, UpdatePasswordMutationVariables>(UpdatePasswordDocument, baseOptions); } export type UpdatePasswordMutationHookResult = ReturnType<typeof useUpdatePasswordMutation>; export type UpdatePasswordMutationResult = ApolloReactCommon.MutationResult<UpdatePasswordMutation>; export type UpdatePasswordMutationOptions = ApolloReactCommon.BaseMutationOptions<UpdatePasswordMutation, UpdatePasswordMutationVariables>;
the_stack
import BigNumber from "bignumber.js/bignumber"; enum ChainId { MAINNET = 1, ROPSTEN = 3, RINKEBY = 4, GÖRLI = 5, KOVAN = 42, BSC_MAINNET = 56, BSC_TESTNET = 97 } // mint token export const MINTTOKEN = Object.freeze({ ALLNEW: 'ALLNEW', ENDED: 'ENDED', BAKE: 'BAKE', PET: 'PET', BPET: 'BPET', WEAPON: 'WEAPON', BEST: 'BEST', WEAPONNFT: 'WEAPONNFT', PETNFT: 'PETNFT', HELMETNFT: 'HELMETNFT', HATNFT: 'HATNFT', ETH2MASTER: 'ETH2MASTER', AETHANDETH2: 'AETHANDETH2', AETHMASTER: 'AETHMASTER', TEN: 'TEN', TENNFT: 'TENNFT', WSOTE: 'WSOTE', SHIELD: 'SHIELD', BRY: 'BRY', BAKESTAKING: 'BAKESTAKING', DEFI100: 'DEFI100', DEFI100OLD: 'DEFI100OLD', BANANA: 'BANANA', PCWS: 'PCWS', SEASCAPENFT: 'SEASCAPENFT', WAR: 'WAR', TKONFT: 'TKONFT', WAR2: 'WAR2', DIESEL: 'DIESEL', MX: 'MX' }) export const SUBTRACT_GAS_LIMIT = 100000 const ONE_MINUTE_IN_SECONDS = new BigNumber(60) const ONE_HOUR_IN_SECONDS = ONE_MINUTE_IN_SECONDS.times(60) const ONE_DAY_IN_SECONDS = ONE_HOUR_IN_SECONDS.times(24) const ONE_YEAR_IN_SECONDS = ONE_DAY_IN_SECONDS.times(365) export const INTEGERS = { ONE_MINUTE_IN_SECONDS, ONE_HOUR_IN_SECONDS, ONE_DAY_IN_SECONDS, ONE_YEAR_IN_SECONDS, ZERO: new BigNumber(0), ONE: new BigNumber(1), ONES_31: new BigNumber('4294967295'), // 2**32-1 ONES_127: new BigNumber('340282366920938463463374607431768211455'), // 2**128-1 ONES_255: new BigNumber('115792089237316195423570985008687907853269984665640564039457584007913129639935'), // 2**256-1 INTEREST_RATE_BASE: new BigNumber('1e18') } export const deadAddress = '0x000000000000000000000000000000000000dead' export const contractAddresses = { bakeBatBlp: { [ChainId.BSC_TESTNET]: '0xF1785c979E822134b6D5A9B23Bd75126388B23Df', [ChainId.BSC_MAINNET]: '0x675Ec26cF1c99A5cD227658f5d0e2fAcbbf3Dcf7' }, oneInchBakeNFT: { [ChainId.BSC_TESTNET]: '0xb4484CACd4cdA038B7d7b261502E5cdFBab9eb5B', [ChainId.BSC_MAINNET]: '0x2B843942EdF0040012b12bE2b3C197Ef53cab7F9' }, exchangeOneInchBakeNFT: { [ChainId.BSC_TESTNET]: '0x1753091b502B797B8b545aE890AD2936A7588696', [ChainId.BSC_MAINNET]: '0x961985030bC6cB35a8bf2bfeFf32FF0512f4D3b0' }, bidOneInchBakeNFT: { [ChainId.BSC_TESTNET]: '0xEF8806D4Ff16Cc555E2C693a1795CdC0d00B7727', [ChainId.BSC_MAINNET]: '0xea8683ed461ED504F08078903C2C89ee5F40A8A7' }, busd: { [ChainId.BSC_TESTNET]: '0xed24fc36d5ee211ea25a80239fb8c4cfd80f12ee', [ChainId.BSC_MAINNET]: '0xe9e7cea3dedca5984780bafc599bd69add087d56' }, busdUsdcBlp: { [ChainId.BSC_TESTNET]: '0xA29122631a683EeFe5696F678e9DDbFA5415a537', [ChainId.BSC_MAINNET]: '0x56CDE265aaD310e623C8f8994a5143582659aBfC' }, mx: { [ChainId.BSC_TESTNET]: '0x54991a494a05C2435E73C34782b8cCF954c77099', [ChainId.BSC_MAINNET]: '0x9F882567A62a5560d147d64871776EeA72Df41D3' }, bakeMxBlp: { [ChainId.BSC_TESTNET]: '0x22ca1a9ac0c9393b86f4097b7bd9d003cb12acf2', [ChainId.BSC_MAINNET]: '0x0af49D51E2136af95646527263bACbA004eb4884' }, mxMaster: { [ChainId.BSC_TESTNET]: '0x7469A0B95FF8649bCcfa9d10F8D7e01DbEF9791f', [ChainId.BSC_MAINNET]: '0xBF94CC0BbE177C6E0d2d581cA20dcF7CBd50B8f4' }, diesel: { [ChainId.BSC_TESTNET]: '0x398F3AC457a965493C7D9E35158Ab716A40Edd76', [ChainId.BSC_MAINNET]: '0xe1eA2E1907d93F154234CE3b5A7418faf175fE11' }, dieselMaster: { [ChainId.BSC_TESTNET]: '0x5f44f198115E0e856440473620c44E5Ceb267306', [ChainId.BSC_MAINNET]: '0xA3138cF6AA7ac5F6D27adFf863D92d5717a47402' }, bnbDieselBlp: { [ChainId.BSC_TESTNET]: '0xc09D61E531Acbc58c66F22Cf8265bD5061A0cEd8', [ChainId.BSC_MAINNET]: '0x2077bB2BAbf6e78dE2825143a1C03AbFe974DbeA' }, voteForNFT: { [ChainId.BSC_TESTNET]: '0x87CAdb6185EcFb54E6bd46541581D727d497E0F5', [ChainId.BSC_MAINNET]: '0xdCb42F9b544312aBdC9c6145a9F0Af590e4b535E' }, tokocryptoNft: { [ChainId.BSC_TESTNET]: '0x3A1c331Bb2cBA92F3F623068947bAbAE3ed99A36', [ChainId.BSC_MAINNET]: '0x3A1c331Bb2cBA92F3F623068947bAbAE3ed99A36' }, tokocryptoCommonNftMaster: { [ChainId.BSC_TESTNET]: '0x9E5aB10f4d9Fac4fA8B4306C7d115fBcaC3869da', [ChainId.BSC_MAINNET]: '0x5466Bbb3c6280943C8A9b0c39e3ad7D31b2bB78D' }, exchangeTokocryptoNFT: { [ChainId.BSC_TESTNET]: '0xA2734393C1b8880aEF94026699F4eCcCc8dC89AC', [ChainId.BSC_MAINNET]: '0xcfb27c7F778780178e95feA84c45e5D79F0a0a4E' }, bidTokocryptoNFT: { [ChainId.BSC_TESTNET]: '0xCA8e8E83856758b01488d904e5aBE85d21d743EF', [ChainId.BSC_MAINNET]: '0xE4D3299B1a3C268814C57394c2a729FecA3b2B00' }, war: { [ChainId.BSC_TESTNET]: '0x9f0D3d71a1C58a1025701929Be99D23B3eA7e607', [ChainId.BSC_MAINNET]: '0x42dbD44a8883D4363B395F77547812DC7dB806d5' }, bakeWarBlp: { [ChainId.BSC_TESTNET]: '0x2759a262108Ca345e1F40F13774040ec8Be9Eeb6', [ChainId.BSC_MAINNET]: '0x8B4Fa3e7F29924b6A60C4abaC0db9dEA0DF594ba' }, warMaster: { [ChainId.BSC_TESTNET]: '0x7bf4bed035a54589082b73a5d6e41413da981f09', [ChainId.BSC_MAINNET]: '0x52c26308fe70fd188c7efaad11663e5b3ead42c9' }, busdWarBlp: { [ChainId.BSC_TESTNET]: '0xf08957d003208a23508fe9054fafd7217c789825', [ChainId.BSC_MAINNET]: '0x083593735495EE0EB7D8716470D7683c1b852ca5' }, warMaster2: { [ChainId.BSC_TESTNET]: '0x35750aFd872FB6fFCD5c7DCe8904f8edD9a129Ce', [ChainId.BSC_MAINNET]: '0x77Bfd5d645010F5d798a3a481E122eC8F291eDCE' }, seascapeNFT: { [ChainId.BSC_TESTNET]: '0x66638f4970c2ae63773946906922c07a583b6069', [ChainId.BSC_MAINNET]: '0xc54b96b04AA8828b63Cf250408E1084E9F6Ac6c8' }, seascapeCommonNftMaster: { [ChainId.BSC_TESTNET]: '0xd7292499CC94016c4265Af49034e58018399151E', [ChainId.BSC_MAINNET]: '0xA491395865cA3Ef828E4a879D3d2de7C7eC94689' }, pCWSBakeBlp: { [ChainId.BSC_TESTNET]: '0x8c72CbDaCb26f15e1a73D78dE1265C963ACed502', [ChainId.BSC_MAINNET]: '0x14BC29C27899E33fdD7169407216C86Fa947c537' }, exchangeSeascapeNFT: { [ChainId.BSC_TESTNET]: '0x196a6D38b0048aC41c3819476177fCC22d3ec081', [ChainId.BSC_MAINNET]: '0x773028cD87f93dfA67E2F5FeC01DB4EA82Cc4b07' }, bidSeascapeNFT: { [ChainId.BSC_TESTNET]: '0xb8737421ab10EeDB01F1d7c30c5ad5F0ebB6Afb5', [ChainId.BSC_MAINNET]: '0x498a5E8A34A85845DeD8869d5638B2E2ff91D979' }, pCWSBnbBlp: { [ChainId.BSC_TESTNET]: '0x4353A4E7eC5836Fc798308555e153765fA7Ee1B5', [ChainId.BSC_MAINNET]: '0xe67B96a9456E6e623463d022Fbb949a3fdD9Ed4C' }, pCWS: { [ChainId.BSC_TESTNET]: '0xE17626fC6C189640057Aa4b7fFb272CB7E3A4ea7', [ChainId.BSC_MAINNET]: '0xbcf39F0EDDa668C58371E519AF37CA705f2bFcbd' }, pCWSMaster: { [ChainId.BSC_TESTNET]: '0xdC2df521fBe550446F0C0e8d98f2C01eb781b0cd', [ChainId.BSC_MAINNET]: '0x540360fF1B002aFEd972cFFcB05B6ff478Ca05C2' }, BANANA: { [ChainId.BSC_TESTNET]: '0x3D66334d92A00e5Ca199682C67d166Ffee1DB928', [ChainId.BSC_MAINNET]: '0x603c7f932ED1fc6575303D8Fb018fDCBb0f39a95' }, bakeBananaBlp: { [ChainId.BSC_TESTNET]: '0xA0acf95c4A3a89A6e0b219eb895DF065c48983B5', [ChainId.BSC_MAINNET]: '0x61890bd5AF37A44f15a697f9db9BfcCeAbF4e322' }, BANANAMaster: { [ChainId.BSC_TESTNET]: '0x5b588A2061441832fF654b513Dd3a3fDc5dbB685', [ChainId.BSC_MAINNET]: '0x35dafafE18B65cEBA36350DCf4EeB618Ad2B8387' }, crudeoilBakeBaseIDO: { [ChainId.BSC_TESTNET]: '0x3deB2265C986d34532C699abb911AD0c3e837E49', [ChainId.BSC_MAINNET]: '0xD2dbbE23baa58e3D56eBd388CfF6791B560F2347' }, spartanBakeBaseIDO: { [ChainId.BSC_TESTNET]: '0x09C9177EAe955ccFC9dED783C5886086D30621c0', [ChainId.BSC_MAINNET]: '0x67F633FfBB430551893EB2B8e63D211c2B386CC9' }, bidBakeryArtwork3NFT: { [ChainId.BSC_TESTNET]: '0x0CE4128c061708718c1a519c11d31d80F297cf9b', [ChainId.BSC_MAINNET]: '0xe98631Ce5ccf1e9eF1638a76C78702a384A79E29' }, bakeryArtwork3NFT: { [ChainId.BSC_TESTNET]: '0x241DDDC8fa9628923761D94779778288E69C9209', [ChainId.BSC_MAINNET]: '0x84d7FE5D949eA5fec5D84617bAdD7590275bFa72' }, exchangeBakeryArtwork3NFT: { [ChainId.BSC_TESTNET]: '0x73BD5E9FD21b53BDb455689feA4b03cba0Ffa2E6', [ChainId.BSC_MAINNET]: '0x8fb398BE7ACb7110436749A394e3D672b8Ddb2ff' }, DEFI100: { [ChainId.BSC_TESTNET]: '0x34EE4d1dDD4DE53958BfC562EB7D9b7B4c8fedAb', [ChainId.BSC_MAINNET]: '0x9d8AAC497A4b8fe697dd63101d793F0C6A6EEbB6' }, DEFI100Master: { [ChainId.BSC_TESTNET]: '0xA71024785a10786D45ab3F82062ef704aD763355', [ChainId.BSC_MAINNET]: '0xf5Df2D28309095c5212F395A4B571cAcE5C2058C' }, DEFI100OldMaster: { [ChainId.BSC_TESTNET]: '0xA71024785a10786D45ab3F82062ef704aD763355', [ChainId.BSC_MAINNET]: '0x4302b66b1b923171FBF44AeA0ee5a21e687409eC' }, DEFI100BakeBLP: { [ChainId.BSC_TESTNET]: '0x05864D0bda90113Bb300355c6726a96d8f97Be0a', [ChainId.BSC_MAINNET]: '0x237E5251371A9Ce542829a8888B9C3BF05F68522' }, DEFI100BnbBLP: { [ChainId.BSC_TESTNET]: '0x9872624A2b6B7c6444AAa1681146A700d4Fc00a7', [ChainId.BSC_MAINNET]: '0x6ba40C79C2Da5d6faF29B1eDac8C15e1fb8f7aB1' }, aeth: { [ChainId.BSC_TESTNET]: '0xe82ec65D01E3866c906B608234dd6873C7bbCf73', [ChainId.BSC_MAINNET]: '0x973616ff3b9d8F88411C5b4E6F928EE541e4d01f' }, ankr: { [ChainId.BSC_TESTNET]: '0x0C3393DB8B57aF9AE636E502C728E5b3c24c1Ab8', [ChainId.BSC_MAINNET]: '0xf307910A4c7bbc79691fD374889b36d8531B08e3' }, onx: { [ChainId.BSC_TESTNET]: '0xcD73CcDE7d66768d0f64528762CdebE72d198f36', [ChainId.BSC_MAINNET]: '0x50dfd52c9f6961Bf94D1d5489AE4B3e37D2F1fe7' }, aethMaster: { [ChainId.BSC_TESTNET]: '0x15559497E14E2BB948dE402Fd75627fab3CE88e0', [ChainId.BSC_MAINNET]: '0xed8732d98ADb5591e9FC9a15BbA7a345B78B3e0E' }, BRYBakeBLP: { [ChainId.BSC_TESTNET]: '0x7508a0Cb9F432B2Fd4ffCD5a2632144A990935b2', [ChainId.BSC_MAINNET]: '0x79249E6b65030902671c5Fa85d79E3ec28e4b1b9' }, BRY: { [ChainId.BSC_TESTNET]: '0x205E58A7b8B2D37e153b5217feB754967586E91e', [ChainId.BSC_MAINNET]: '0xf859Bf77cBe8699013d6Dbc7C2b926Aaf307F830' }, BRYMaster: { [ChainId.BSC_TESTNET]: '0xe29B3775425F8EC90db14dA9c53a08BC0235ce7A', [ChainId.BSC_MAINNET]: '0xA9E34CB291B64d3ad56B365ADDE369f3Ec04F7a8' }, SHIELD: { [ChainId.BSC_TESTNET]: '0x5Bae754F693af19aCfAcf6cb2F4b8F592b68f8AA', [ChainId.BSC_MAINNET]: '0x60b3BC37593853c04410c4F07fE4D6748245BF77' }, SHIELDMaster: { [ChainId.BSC_TESTNET]: '0xc86c91C0120cd1cFDb4513A9b49F34F0dD4d4A2e', [ChainId.BSC_MAINNET]: '0x9C94E850DB4371B38c00F60F9cE111694b212C30' }, wSOTE: { [ChainId.BSC_TESTNET]: '0xB939376da0b3C7f47f320580CbB6B2608DB20F58', [ChainId.BSC_MAINNET]: '0x541e619858737031a1244a5d0cd47e5ef480342c' }, wSOTEMaster: { [ChainId.BSC_TESTNET]: '0x63A535209D8A6c01D5e382f982aFa062a45b233d', [ChainId.BSC_MAINNET]: '0x99638fD577C22fc752B3734103933CF9835C5e02' }, wSoteBakeBLP: { [ChainId.BSC_TESTNET]: '0x511b69183ee7e983afdc0a48e33310008ee88d20', [ChainId.BSC_MAINNET]: '0x7dbc5d1f167b476e7c8866d6e8221d210547ab88' }, ten: { [ChainId.BSC_TESTNET]: '0x81fe632De52041d1c7E6C23a42B215a601a7D716', [ChainId.BSC_MAINNET]: '0xdFF8cb622790b7F92686c722b02CaB55592f152C' }, tenMaster: { [ChainId.BSC_TESTNET]: '0xCB3491E145f78C1d8350B50AA4298a16e310D90A', [ChainId.BSC_MAINNET]: '0x4D6D2e3B419D324b77dDCAf3Ff17A66C7D16e9f5' }, tenPetNftMaster: { [ChainId.BSC_TESTNET]: '0x99fe3638286499cf0e35Cea3abd83b7677cE2c55', [ChainId.BSC_MAINNET]: '0x7c9378d17534a476d8741f26a46cbae1a0788bd5' }, tenBakeBLP: { [ChainId.BSC_TESTNET]: '0x6276658502bB1660BCd815B7e1004C041547963D', [ChainId.BSC_MAINNET]: '0x101E83700c5dE0Bc4F5a65471A26DA6B141EA478' }, beth: { [ChainId.BSC_TESTNET]: '0x747c58A36Fe414032072d671ccdf38720aDDb1a9', [ChainId.BSC_MAINNET]: '0x250632378E573c6Be1AC2f97Fcdf00515d0Aa91B' }, bethBakeBLP: { [ChainId.BSC_TESTNET]: '0xfef3ec19d4b48c9d75684c2ca7527b9ddbae53fe', [ChainId.BSC_MAINNET]: '0x53920d115CeC3E94dFeae52CA515093e84858109' }, eth2Master: { [ChainId.BSC_TESTNET]: '0x377C901Dc5f752C110dB33A526cAA327454F5Cf0', [ChainId.BSC_MAINNET]: '0xe627f00D5a5bfcE0640E771Af573C41e9a278A20' }, helmetNftCommonMaster: { [ChainId.BSC_TESTNET]: '0x1B16aF670b0017ffD5E026008078599c322c50CF', [ChainId.BSC_MAINNET]: '0x163454D6313DC09eD376da6760cBEeA1efE2acF5' }, helmetNft: { [ChainId.BSC_TESTNET]: '0xd97B0aDaFf4C8bd19a2587ce07f8416ad0860C90', [ChainId.BSC_MAINNET]: '0x2f0f57BADc77701E9e6384b9335cB9AA4900b08A' }, petNFTCommonMaster: { [ChainId.BSC_TESTNET]: '0x68cA8D5Bf0aDA9f7dA0530bdbdcC324e37622d75', [ChainId.BSC_MAINNET]: '0x68cA8D5Bf0aDA9f7dA0530bdbdcC324e37622d75' // TODO }, weaponNFTCommonMaster: { [ChainId.BSC_TESTNET]: '0x7fF8C60852834937BAb6ec3adb4403fE669628Cc', [ChainId.BSC_MAINNET]: '0x7fF8C60852834937BAb6ec3adb4403fE669628Cc' // TODO }, petNft: { [ChainId.BSC_TESTNET]: '0xAa4cDa1838Ab17F6554EB2F1b3a65214083dF3f7', [ChainId.BSC_MAINNET]: '0x90E88d4c8E8f19af15DfEabD516d80666F06A2F5' }, exchangePetNft: { [ChainId.BSC_TESTNET]: '0xc51Eadfb14e13b0071464a504167bc6868Fe6eEa', [ChainId.BSC_MAINNET]: '0xa3514F8ee39Ba80cD36B4aecfa2Fe2eb5fD6b326' }, // bid pet nft bidPetNFT: { [ChainId.BSC_TESTNET]: '0xf6D05A90337596F3273a8A1914A1b4E94303767f', [ChainId.BSC_MAINNET]: '0x3bD857648Da97f3c395546E4F7F9fAD3aF29da33' }, bestToken: { [ChainId.BSC_TESTNET]: '0xAE8044eF4264E672e142cA4d9fcD92135e8d2592', [ChainId.BSC_MAINNET]: '0x10747e2045a0ef884a0586AC81558F43285ea3c7' }, bestMaster: { [ChainId.BSC_TESTNET]: '0x31f9B1f691884a8A744DCf29714d6B37bfB5E909', [ChainId.BSC_MAINNET]: '0x62Da74a42de360f1B5882d63e1E480fb80F0956f' }, busdToken: { [ChainId.BSC_TESTNET]: '0xed24fc36d5ee211ea25a80239fb8c4cfd80f12ee', [ChainId.BSC_MAINNET]: '0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56' }, usdtToken: { [ChainId.BSC_TESTNET]: '0x337610d27c682E347C9cD60BD4b3b107C9d34dDd', [ChainId.BSC_MAINNET]: '0x55d398326f99059ff775485246999027b3197955' }, transfer: { [ChainId.BSC_TESTNET]: '0x626d260DaAf60D0c1C52E9eB8F166055d3Ee59CC', [ChainId.BSC_MAINNET]: '0xf8177Cda1b5B5B022F7a87546Dcb646C5562E952' }, weapon: { [ChainId.BSC_TESTNET]: '0x84525cE72f4f10C1Daa471C17f0DE14F96cd3132', [ChainId.BSC_MAINNET]: '0x3664d30A612824617e3Cf6935d6c762c8B476eDA' }, weaponMaster: { [ChainId.BSC_TESTNET]: '0x5D036Eae933Bb2c7a00b97387D95eB74E6A8b24a', [ChainId.BSC_MAINNET]: '0x0c2fC172c822B923f92A17aD9EA5c15aD7332624' }, weaponNFT: { [ChainId.BSC_TESTNET]: '0x2F2d38bC4C9d7b2A57432d8a7AB2093a432885Ca', [ChainId.BSC_MAINNET]: '0xBe7095dBBe04E8374ea5F9f5B3f30A48D57cb004' }, exchangeWeaponNFT: { [ChainId.BSC_TESTNET]: '0xf9128Cd6D8B63106Da4058491A495b3Eb96afC5C', [ChainId.BSC_MAINNET]: '0xA4C3a8F8465FdDdE98A440f8cF5E180e6e33f644' }, // bid weapon nft bidWeaponNFT: { [ChainId.BSC_TESTNET]: '0xE8931c2a02c75e547FA3b9aE8D2324c544bEF2C6', [ChainId.BSC_MAINNET]: '0x61E9181E7Fece6e2a79e1abfF71ACB99bd98E3E3' }, binanceNft: { [ChainId.BSC_TESTNET]: '0x9D540ff9Af51178cB285Dc19629f9a7b2F9408Be', [ChainId.BSC_MAINNET]: '0xc014B45D680B5a4bf51cCdA778A68d5251C14b5E' }, exchangeBinanceNft: { [ChainId.BSC_TESTNET]: '0xb40d08e866693E4A4AC6556A533D996DED5e7458', [ChainId.BSC_MAINNET]: '0x58e6E6e16A8fd619b6DE1dA4F614dfB31dcC07b2' }, // bid binance nft bidBinanceNFT: { [ChainId.BSC_TESTNET]: '0x8A9b166E8cc39815B7D0D96F1D9f88EeFC774012', [ChainId.BSC_MAINNET]: '0xEF44A8D2830DFaC64A7493Ae60850cfb950567e1' }, bakeryArtwork2NFT: { [ChainId.BSC_TESTNET]: '0xFfe09E64396d1b717DeF289A3aCB9F55d0A523A0', [ChainId.BSC_MAINNET]: '0x1233B9f706cB9028a03B61AF125cf1Fe840CDBD3' }, exchangeBakeryArtwork2NFT: { [ChainId.BSC_TESTNET]: '0xC9DaA8877e21eF6Df3B9F25C4FE8F65B790E3329', [ChainId.BSC_MAINNET]: '0xC921239C1b5deaD79C889af1D9E006ef560FfFeA' }, bidBakeryArtwork2NFT: { [ChainId.BSC_TESTNET]: '0x864BdcAd8dd09394711c28256a136D2a248fc8A5', [ChainId.BSC_MAINNET]: '0x616Ea437dFBf929ef49116614F6B2b610F48b0ae' }, dogeMemeNFT: { [ChainId.BSC_TESTNET]: '0x241DDDC8fa9628923761D94779778288E69C9209', [ChainId.BSC_MAINNET]: '0x84d7FE5D949eA5fec5D84617bAdD7590275bFa72' }, exchangeDogeMemeNFT: { [ChainId.BSC_TESTNET]: '0x73BD5E9FD21b53BDb455689feA4b03cba0Ffa2E6', [ChainId.BSC_MAINNET]: '0x8fb398BE7ACb7110436749A394e3D672b8Ddb2ff' }, bidDogeMemeNFT: { [ChainId.BSC_TESTNET]: '0x0CE4128c061708718c1a519c11d31d80F297cf9b', [ChainId.BSC_MAINNET]: '0xe98631Ce5ccf1e9eF1638a76C78702a384A79E29' }, reviewAddress: { [ChainId.BSC_TESTNET]: [ '0x4627a245f31A325F986FbB0528B04bF56977fD8A', '0x626d260DaAf60D0c1C52E9eB8F166055d3Ee59CC', '0x2dDcee78258006FB332c748848AF6913455aCb1A', '0x5e03bE5F99D3fE5b771711ac874344b41f4f1eD4', '0xd9066cc6717210c586A50333B12359f7c90a7cDc' ], [ChainId.BSC_MAINNET]: [ '0x4627a245f31A325F986FbB0528B04bF56977fD8A', '0x626d260DaAf60D0c1C52E9eB8F166055d3Ee59CC', '0x2dDcee78258006FB332c748848AF6913455aCb1A', '0x18920B8772249ed26390016ECd5Ad23CcE839C54', '0x54D272626aA031F30bDBB2f8009883ca1D487055', '0xf1465311E37BdBDE75d0231C7307C4f09b1d1200', '0x274Adf173DFA779a4684a5Febacaf6bc25121953', '0xEC02adD2E53ac17Cb9e8Af1Cf68F6Dc319E23304', '0x3A9e7266EF2c5F37AE906a4D4f4d9c96F32C2C0C', '0x92Ce0850222f9eF7271b2fb64f62F705daA4b064', '0xf3Ab6f5ccBb9C46e6ba6602cea91a4851Df4Fe29' ] // TODO }, bakeryArtworkNFT: { [ChainId.BSC_TESTNET]: '0xC6911A6E1824b626dB9562df9A4634aE7BeE3621', [ChainId.BSC_MAINNET]: '0x5Bc94e9347F3b9Be8415bDfd24af16666704E44f' }, exchangeBakeryArtworkNFT: { [ChainId.BSC_TESTNET]: '0x44Eb2059D03a189776f4A9F9f36dddB51FC6d582', [ChainId.BSC_MAINNET]: '0x26b82AB8269B2aD48FBDbbC9a08c78df7D68E814' }, // bid bakery artwork nft bidBakeryArtworkNFT: { [ChainId.BSC_TESTNET]: '0x865D9379d9b2D20ECe1Bf0aEA1D933D75A81C7CD', [ChainId.BSC_MAINNET]: '0xE84E73889CDF43dbB57fFee42DC0615eb244891E' }, bakeryArtworkRouter: { [ChainId.BSC_TESTNET]: '0x4090B62C9098731C4d9C03A0d9a0A99F0D3Ed30E', [ChainId.BSC_MAINNET]: '0x4A2a35D0D259ecd344FaB05adEb9c72389ADF2D8' // **没有发主网,主网没用这个合约 }, digitalArtworkNft: { [ChainId.BSC_TESTNET]: '0xe5f1ac1971f28cf8cbea5fee6fe61b1dd8908141', [ChainId.BSC_MAINNET]: '0xbc9535ceb418a27027f5cc560440f4a8823cb8bf' }, exchangeArtworkNFT: { [ChainId.BSC_TESTNET]: '0x1BcD5753f219B776c668f3942a1b5436103482f6', [ChainId.BSC_MAINNET]: '0x59dC5A288dA642beAcA7bD0016065609fC06DF61' }, // bid digital artwork nft bidDigitalArtworkNFT: { [ChainId.BSC_TESTNET]: '0x6A5aEDF1e54B9Ac41F6fEe5D3363d3970773f511', [ChainId.BSC_MAINNET]: '0x0c7Ab53232DA9a525ee93d20FD0BE256F512Cf8e' }, petMaster2: { [ChainId.BSC_TESTNET]: '0xdB4d137261bA793d67d2A375d4aaA55F2eE1E396', [ChainId.BSC_MAINNET]: '0x5d2FE774032596D2C69Dc441fD137A1F43725E08' }, exchangeEggNFT: { [ChainId.BSC_TESTNET]: '0x09B3B152E20ABACd0C67C8784bA8A25063D985CB', [ChainId.BSC_MAINNET]: '0x8443BE845c3D03Ac723411861025d0e8F453950f' }, // bid pet egg nft bidPetEggNFT: { [ChainId.BSC_TESTNET]: '0x1a70E2a27E18adAdeD9015Bec58605A583Ef105b', [ChainId.BSC_MAINNET]: '0x437bf818Ae0b62C0E1Ad823877e2e5C25d07682B' }, petEggNft: { [ChainId.BSC_TESTNET]: '0x0B619B394cA844576E571E43b6A120882Eb8C59a', [ChainId.BSC_MAINNET]: '0x8A3ACae3CD954fEdE1B46a6cc79f9189a6C79c56' }, pet: { [ChainId.BSC_TESTNET]: '0xe59af933b309aFF12f323111B2B1648fF45D5dc0', [ChainId.BSC_MAINNET]: '0x4d4e595d643dc61EA7FCbF12e4b1AAA39f9975B8' }, petMaster: { [ChainId.BSC_TESTNET]: '0xfe292e44fE33579b3690dE57302263B3d6B59739', [ChainId.BSC_MAINNET]: '0x4A2a35D0D259ecd344FaB05adEb9c72389ADF2D8' }, dish: { [ChainId.BSC_TESTNET]: '0xC3a7736b284cE163c45D92b75da4d4A34847be63', [ChainId.BSC_MAINNET]: '0xa7463C3163962b12AEB623147c2043Bb54834962', 42: '0x43a7903E3a839a67192151eE300e11198985E54b', 1: '0x6b3595068778dd592e39a122f4f5a5cf09c90fe2' }, dishMaster: { [ChainId.BSC_TESTNET]: '0x22CbdB1Da36B35725d1D75A7784271EE3f869b30', [ChainId.BSC_MAINNET]: '0x7145319189629AFcF31754D8AC459265FCa4cF91', 42: '0x43a7903E3a839a67192151eE300e11198985E54b', 1: '0x6b3595068778dd592e39a122f4f5a5cf09c90fe2' }, exchangeNFT: { [ChainId.BSC_TESTNET]: '0x6ebF7b9F11a81101d4a929e19FCefba72e8AE5cc', [ChainId.BSC_MAINNET]: '0x05D189D22D9916837A82438D74F3837Ac70b2831' }, // bid dish nft bidDishNFT: { [ChainId.BSC_TESTNET]: '0x7D055aB74Cf65fb1a3C62A3F7c74172F19a39086', [ChainId.BSC_MAINNET]: '0x2D01300340bF6bFad0D7f830102188D6291dDc15' }, sushi: { [ChainId.BSC_TESTNET]: '0xe02df9e3e622debdd69fb838bb799e3f168902c5', [ChainId.BSC_MAINNET]: '0xe02df9e3e622debdd69fb838bb799e3f168902c5', // [ChainId.BSC_MAINNET]: '0x918DE02364E0b63CE83e3741d254D19D8FE8f914', // 主网预生产合约 42: '0x43a7903E3a839a67192151eE300e11198985E54b', 1: '0x6b3595068778dd592e39a122f4f5a5cf09c90fe2' }, masterChef: { [ChainId.BSC_TESTNET]: '0x20eC291bB8459b6145317E7126532CE7EcE5056f', [ChainId.BSC_MAINNET]: '0x20eC291bB8459b6145317E7126532CE7EcE5056f', // [ChainId.BSC_MAINNET]: '0xBd9695B0F5fBC902cb55e2F2F5d2cf0A7002c834', // 主网预生产合约 1: '0xc2edad668740f1aa35e4d8f227fb8e17dca888cd' }, weth: { [ChainId.BSC_TESTNET]: '0x094616f0bdfb0b526bd735bf66eca0ad254ca81f', // WBNB [ChainId.BSC_MAINNET]: '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c', 1: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2' }, bakeDestroyed: { [ChainId.BSC_TESTNET]: '0x3aDa268097c7d9973A2D4cCD1ca939c386AbCFb7', [ChainId.BSC_MAINNET]: '0x732B6620D3469204BCC6F44c0b40cD8C4bAfC747' // 主网生产 // [ChainId.BSC_MAINNET]: '0x8d01c3d91A22ca77A4B33e5e82b9e1eE48e78542' // 主网预生产合约 }, bakeDestroyedManager: { [ChainId.BSC_TESTNET]: '0x337E3Cee9c3e892F84c76B0Ec2C06fd4Ab06A734', [ChainId.BSC_MAINNET]: '0x2dab7D9A2A8c5a4e085377043619D2e7f2914700' // 主网生产 // [ChainId.BSC_MAINNET]: '0x03FFFEF727C4e85468130aA0513e0428c6CFeFB1' // 主网预生产合约 } } // mint bake pools export const supportedPools = [ { pid: 7, lpAddresses: { [ChainId.BSC_TESTNET]: '0xe02df9e3e622debdd69fb838bb799e3f168902c5', [ChainId.BSC_MAINNET]: '0xe02df9e3e622debdd69fb838bb799e3f168902c5', // 主网生产 // [ChainId.BSC_MAINNET]: '0x918DE02364E0b63CE83e3741d254D19D8FE8f914', // 主网预生产合约ODO 1: '0xce84867c3c02b05dc570d0135103d3fb9cc19433' }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'Bread', symbol: 'BAKE', tokenSymbol: MINTTOKEN.BAKE, icon: 'bread' }, { pid: 23, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.bakeBatBlp[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.bakeBatBlp[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAT', symbol: 'BAKE-BAT BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'bat', stakeIcon: 'bakeBat' }, { pid: 21, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.bakeMxBlp[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.bakeMxBlp[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'MX', symbol: 'BAKE-MX BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'mx', stakeIcon: 'bakeMx' }, { pid: 20, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.bakeWarBlp[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.bakeWarBlp[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'WAR', symbol: 'BAKE-WAR BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'war' }, { pid: 19, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pCWSBnbBlp[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pCWSBnbBlp[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pCWS[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pCWS[ChainId.BSC_MAINNET] }, name: 'pCWS', symbol: 'BNB-pCWS BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'pcws' }, { pid: 18, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.DEFI100BakeBLP[ChainId.BSC_TESTNET], // use bake bnb [ChainId.BSC_MAINNET]: contractAddresses.DEFI100BakeBLP[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'D100', symbol: 'BAKE-D100 BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'defi100' }, { pid: 17, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.BRYBakeBLP[ChainId.BSC_TESTNET], // use bake bnb [ChainId.BSC_MAINNET]: contractAddresses.BRYBakeBLP[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BRY', symbol: 'BAKE-BRY BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'bry' }, { pid: 16, lpAddresses: { [ChainId.BSC_TESTNET]: '0x8170b95AaCe8F494090Db7A4a17ba9EB73C2413C', // use bake bnb [ChainId.BSC_MAINNET]: '0x8F30114846012e5C1Fa33F32Cf93b0250C90E05a' }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'SHIELD', symbol: 'BAKE-SHIELD BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'shield' }, { pid: 14, lpAddresses: { [ChainId.BSC_TESTNET]: '0x8170b95AaCe8F494090Db7A4a17ba9EB73C2413C', // use bake bnb [ChainId.BSC_MAINNET]: '0xdb2d83eD108E68cc1C9689081d54673Bd9402A54' }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'DOGE', symbol: 'BAKE-DOGE BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'doge.png' }, { pid: 12, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pet[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pet[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pet[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pet[ChainId.BSC_MAINNET] }, name: 'PET Staking', symbol: 'PET', tokenSymbol: MINTTOKEN.BAKE, icon: 'pets', activityTime: 'Start from Oct. 23 10:00 UTC to Oct. 26 10:00 UTC', ended: true }, { pid: 13, lpAddresses: { [ChainId.BSC_TESTNET]: '0x1699bCe1AE94fE00226329dcbBe5FE006CAF3D59', [ChainId.BSC_MAINNET]: '0x6F72943c807BdFaC19bAE25E84B8E99Fee0305FC' }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pet[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pet[ChainId.BSC_MAINNET] }, name: 'Pet Food', symbol: 'PET-BAKE BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'petfood' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: '0x47d34Fd4f095767E718F110AfEf030bb18E8C48F', [ChainId.BSC_MAINNET]: '0xc2Eed0F5a0dc28cfa895084bC0a9B8B8279aE492', 1: '0xce84867c3c02b05dc570d0135103d3fb9cc19433' }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'Doughnut', symbol: 'BAKE-BNB BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'doughnut' }, { pid: 8, lpAddresses: { [ChainId.BSC_TESTNET]: '0x8170b95AaCe8F494090Db7A4a17ba9EB73C2413C', // use bake bnb [ChainId.BSC_MAINNET]: '0x6E218EA042BeF40a8baF706b00d0f0A7b4fCE50a' }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'Waffle', symbol: 'BAKE-BUSD BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'waffle' }, { pid: 9, lpAddresses: { [ChainId.BSC_TESTNET]: '0x8170b95AaCe8F494090Db7A4a17ba9EB73C2413C', // use bake bnb [ChainId.BSC_MAINNET]: '0x5B294814Ca563E81085a858c0e53B9F2c7a3927f' }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'Rolls', symbol: 'BAKE-DOT BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'rolls', ended: true }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: '0xAf5e8AA68dd1b61376aC4F6fa4D06A5A4AB6cafD', [ChainId.BSC_MAINNET]: '0x559e3D9611E9cB8a77c11335Bdac49621382188B', 1: '0xa5904961f61bae7c4dd8478077556c91bf291cfd' }, tokenAddresses: { [ChainId.BSC_TESTNET]: '0xed24fc36d5ee211ea25a80239fb8c4cfd80f12ee', [ChainId.BSC_MAINNET]: '0xe9e7cea3dedca5984780bafc599bd69add087d56', 1: '0xaba8cac6866b83ae4eec97dd07ed254282f6ad8a' }, name: 'Croissant', symbol: 'BUSD-BNB BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'croissant' }, { pid: 10, lpAddresses: { [ChainId.BSC_TESTNET]: '0x95D619e70160D289933c7E6A98E7dFD3a2C75e27', [ChainId.BSC_MAINNET]: '0xbcF3278098417E23d941613ce36a7cE9428724A5', // 主网生产 1: '0xce84867c3c02b05dc570d0135103d3fb9cc19433' }, tokenAddresses: { [ChainId.BSC_TESTNET]: '0x95d619e70160d289933c7e6a98e7dfd3a2c75e27', [ChainId.BSC_MAINNET]: '0xe9e7cea3dedca5984780bafc599bd69add087d56', // 主网生产 1: '0x6b3595068778dd592e39a122f4f5a5cf09c90fe2' }, name: 'Latte', symbol: 'USDT-BUSD BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'latte' }, { pid: 22, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.busdUsdcBlp[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.busdUsdcBlp[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.busd[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.busd[ChainId.BSC_MAINNET] }, name: 'BUSD-USDC BLP', symbol: 'BUSD-USDC BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'busdUsdc' }, { pid: 3, lpAddresses: { [ChainId.BSC_TESTNET]: '0x6f469DAE7F333EdfC98c6057F12E2A7521a9861c', [ChainId.BSC_MAINNET]: '0xa50b9c5DB61C855D5939aa1a66B26Df77745809b', 1: '0xa5904961f61bae7c4dd8478077556c91bf291cfd' }, tokenAddresses: { [ChainId.BSC_TESTNET]: '0xd66c6b4f0be8ce5b39d52e0fd1344c389929b378', [ChainId.BSC_MAINNET]: '0x2170ed0880ac9a755fd29b2688956bd959f933f8', 1: '0xaba8cac6866b83ae4eec97dd07ed254282f6ad8a' }, name: 'Toast', symbol: 'ETH-BNB BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'toast' }, { pid: 4, lpAddresses: { [ChainId.BSC_TESTNET]: '0xf6fD8961F129955A51ba3B392B40594B499dEF3a', [ChainId.BSC_MAINNET]: '0x58521373474810915b02FE968D1BCBe35Fc61E09', 1: '0xa5904961f61bae7c4dd8478077556c91bf291cfd' }, tokenAddresses: { [ChainId.BSC_TESTNET]: '0x6ce8da28e2f864420840cf74474eff5fd80e65b8', [ChainId.BSC_MAINNET]: '0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c', 1: '0xaba8cac6866b83ae4eec97dd07ed254282f6ad8a' }, name: 'Cake', symbol: 'BTC-BNB BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'cake' }, { pid: 5, lpAddresses: { [ChainId.BSC_TESTNET]: '0x937c36B10F0a0B3aeA8a3EF0Ef9eB56E74692A84', // use btc [ChainId.BSC_MAINNET]: '0x56D68e3645c9A010c7fD5313530b9194Ff66C725', 1: '0xa5904961f61bae7c4dd8478077556c91bf291cfd' }, tokenAddresses: { [ChainId.BSC_TESTNET]: '0x6ce8da28e2f864420840cf74474eff5fd80e65b8', // use btc [ChainId.BSC_MAINNET]: '0x7083609fce4d1d8dc0c979aab8c869ea2c873402', 1: '0xaba8cac6866b83ae4eec97dd07ed254282f6ad8a' }, name: 'Cookies', symbol: 'DOT-BNB BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'cookies', ended: true }, { pid: 6, lpAddresses: { [ChainId.BSC_TESTNET]: '0x5B85218b6079524867ed3D99Bd345B873278CA4F', // use btc [ChainId.BSC_MAINNET]: '0x52AaEF46c9F02dBC45Ce3a55ff2B7057f5aB6275', 1: '0xa5904961f61bae7c4dd8478077556c91bf291cfd' }, tokenAddresses: { [ChainId.BSC_TESTNET]: '0x6ce8da28e2f864420840cf74474eff5fd80e65b8', // use btc [ChainId.BSC_MAINNET]: '0xf8a0bf9cf54bb92f17374d9e9a321e6a111a51bd', 1: '0xaba8cac6866b83ae4eec97dd07ed254282f6ad8a' }, name: 'Pineapple bun', symbol: 'LINK-BNB BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'pineapple_bun', ended: true } ] // new Pools下的矿池必须在pet/bake矿池中有 export const supportedNewPools = [ { pid: 23, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.bakeBatBlp[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.bakeBatBlp[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAT', symbol: 'BAKE-BAT BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'bat' }, { pid: 21, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.bakeMxBlp[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.bakeMxBlp[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'MX', symbol: 'BAKE-MX BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'mx' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to MX', symbol: 'BAKE', tokenSymbol: MINTTOKEN.MX, icon: 'mx', stakeIcon: 'bake', otherName: 'MX' }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.bnbDieselBlp[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.bnbDieselBlp[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.diesel[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.diesel[ChainId.BSC_MAINNET] }, name: 'BNB-DIESEL BLP', symbol: 'BNB-DIESEL BLP', tokenSymbol: MINTTOKEN.DIESEL, icon: 'diesel', stakeIcon: 'bnb_diesel', otherName: 'DIESEL' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to DIESEL', symbol: 'BAKE', tokenSymbol: MINTTOKEN.DIESEL, icon: 'diesel', stakeIcon: 'bake', otherName: 'DIESEL' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'TKO NFT Pool', symbol: 'BAKE', tokenSymbol: MINTTOKEN.TKONFT, icon: 'tkonft', stakeIcon: 'bake', otherName: 'TKO NFT' }, { pid: 20, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.bakeWarBlp[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.bakeWarBlp[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'WAR', symbol: 'BAKE-WAR BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'war' }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to WAR', symbol: 'BAKE', tokenSymbol: MINTTOKEN.WAR, icon: 'war', stakeIcon: 'bake', otherName: 'WAR' }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to pCWS', symbol: 'BAKE', tokenSymbol: MINTTOKEN.PCWS, icon: 'pcws', stakeIcon: 'bake', otherName: 'pCWS' }, { pid: 19, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pCWSBnbBlp[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pCWSBnbBlp[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pCWS[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pCWS[ChainId.BSC_MAINNET] }, name: 'pCWS', symbol: 'BNB-pCWS BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'pcws' }, { pid: 18, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.DEFI100BakeBLP[ChainId.BSC_TESTNET], // use bake bnb [ChainId.BSC_MAINNET]: contractAddresses.DEFI100BakeBLP[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'D100', symbol: 'BAKE-D100 BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'defi100' }, { pid: 17, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.BRYBakeBLP[ChainId.BSC_TESTNET], // use bake bnb [ChainId.BSC_MAINNET]: contractAddresses.BRYBakeBLP[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BRY', symbol: 'BAKE-BRY BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'bry' }, { pid: 16, lpAddresses: { [ChainId.BSC_TESTNET]: '0x8170b95AaCe8F494090Db7A4a17ba9EB73C2413C', // use bake bnb [ChainId.BSC_MAINNET]: '0x8F30114846012e5C1Fa33F32Cf93b0250C90E05a' }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'SHIELD', symbol: 'BAKE-SHIELD BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'shield' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to SHIELD', symbol: 'BAKE', tokenSymbol: MINTTOKEN.SHIELD, icon: 'shield', stakeIcon: 'bake', otherName: 'SHIELD', ended: true }, { pid: 14, lpAddresses: { [ChainId.BSC_TESTNET]: '0x8170b95AaCe8F494090Db7A4a17ba9EB73C2413C', // use bake bnb [ChainId.BSC_MAINNET]: '0xdb2d83eD108E68cc1C9689081d54673Bd9402A54' }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'DOGE', symbol: 'BAKE-DOGE BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'doge.png' }, { pid: 13, lpAddresses: { [ChainId.BSC_TESTNET]: '0x1699bCe1AE94fE00226329dcbBe5FE006CAF3D59', [ChainId.BSC_MAINNET]: '0x6F72943c807BdFaC19bAE25E84B8E99Fee0305FC' }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pet[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pet[ChainId.BSC_MAINNET] }, name: 'Pet Food', symbol: 'PET-BAKE BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'petfood' }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to Weapon', symbol: 'BAKE', tokenSymbol: MINTTOKEN.WEAPON, icon: 'bake_weapon', stakeIcon: 'bake' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pet[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pet[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pet[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pet[ChainId.BSC_MAINNET] }, name: 'PET to Weapon', symbol: 'PET', tokenSymbol: MINTTOKEN.WEAPON, icon: 'pet_weapon', stakeIcon: 'pet' } ] export const supportedPetPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'Pet Airdrop', symbol: 'BAKE', tokenSymbol: MINTTOKEN.PET, icon: 'pets', activityTime: '5000 PET/hour from Oct. 20 07:00 UTC to Oct. 20 19:00 UTC', amountDay: 5000, amountUnit: 'PET/Hour', stakeIcon: 'bake' } ] export const endedPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BUSD-WAR BLP', symbol: 'BUSD-WAR BLP', tokenSymbol: MINTTOKEN.WAR2, icon: 'war', stakeIcon: 'bake', otherName: 'WAR' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pCWS[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pCWS[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pCWS[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pCWS[ChainId.BSC_MAINNET] }, name: 'CWS NFT Pool', symbol: 'pCWS', tokenSymbol: MINTTOKEN.SEASCAPENFT, icon: 'seascapenft', stakeIcon: 'helmetnft', otherName: 'SEASCAPE NFT' }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.bakeBananaBlp[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.bakeBananaBlp[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.BANANA[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.BANANA[ChainId.BSC_MAINNET] }, name: 'BANANA', symbol: 'BAKE BANANA BLP', tokenSymbol: MINTTOKEN.BANANA, icon: 'banana', stakeIcon: 'banana', otherName: 'BANANA' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to BRY', symbol: 'BAKE', tokenSymbol: MINTTOKEN.BRY, icon: 'bry', stakeIcon: 'bake', otherName: 'BRY' }, { pid: 100, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'D100(not used) ', symbol: 'BAKE', tokenSymbol: MINTTOKEN.DEFI100, icon: 'defi100', stakeIcon: 'bake', otherName: 'D100' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'D100(not used)', symbol: 'BAKE', tokenSymbol: MINTTOKEN.DEFI100OLD, icon: 'defi100', stakeIcon: 'bake', otherName: 'D100' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to SHIELD', symbol: 'BAKE', tokenSymbol: MINTTOKEN.SHIELD, icon: 'shield', stakeIcon: 'bake', otherName: 'SHIELD' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to wSOTE', symbol: 'BAKE', tokenSymbol: MINTTOKEN.WSOTE, icon: 'wsote', stakeIcon: 'bake', otherName: 'wSOTE' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.tenBakeBLP[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.tenBakeBLP[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.ten[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.ten[ChainId.BSC_MAINNET] }, name: 'Bake to Ten', symbol: 'TEN-BAKE BLP', tokenSymbol: MINTTOKEN.TEN, icon: 'ten1', stakeIcon: 'staketen', otherName: 'TEN' }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.ten[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.ten[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.ten[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.ten[ChainId.BSC_MAINNET] }, name: 'Ten to PET NFT', symbol: 'TEN', tokenSymbol: MINTTOKEN.TEN, icon: 'ten2', stakeIcon: 'helmetnft', otherName: 'PET NFT', amountUnit: 'PET NFT', amountDay: '100' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'NFT Christmas Hat', symbol: 'BAKE', tokenSymbol: MINTTOKEN.HATNFT, icon: 'helmetnft', stakeIcon: 'helmetnft', otherName: 'NFT Xmas Hat' }, { pid: 12, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pet[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pet[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pet[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pet[ChainId.BSC_MAINNET] }, name: 'PET Staking', symbol: 'PET', tokenSymbol: MINTTOKEN.BAKE, icon: 'pets', activityTime: 'Start from Oct. 23 10:00 UTC to Oct. 26 10:00 UTC' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'Pet Airdrop', symbol: 'BAKE', tokenSymbol: MINTTOKEN.PET, icon: 'pets', activityTime: '5000 PET/hour from Oct. 20 07:00 UTC to Oct. 20 19:00 UTC', amountDay: 5000, amountUnit: 'PET/Hour', stakeIcon: 'bake' }, { pid: 5, lpAddresses: { [ChainId.BSC_TESTNET]: '0x937c36B10F0a0B3aeA8a3EF0Ef9eB56E74692A84', // use btc [ChainId.BSC_MAINNET]: '0x56D68e3645c9A010c7fD5313530b9194Ff66C725', 1: '0xa5904961f61bae7c4dd8478077556c91bf291cfd' }, tokenAddresses: { [ChainId.BSC_TESTNET]: '0x6ce8da28e2f864420840cf74474eff5fd80e65b8', // use btc [ChainId.BSC_MAINNET]: '0x7083609fce4d1d8dc0c979aab8c869ea2c873402', 1: '0xaba8cac6866b83ae4eec97dd07ed254282f6ad8a' }, name: 'Cookies', symbol: 'DOT-BNB BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'cookies' }, { pid: 6, lpAddresses: { [ChainId.BSC_TESTNET]: '0x5B85218b6079524867ed3D99Bd345B873278CA4F', // use btc [ChainId.BSC_MAINNET]: '0x52AaEF46c9F02dBC45Ce3a55ff2B7057f5aB6275', 1: '0xa5904961f61bae7c4dd8478077556c91bf291cfd' }, tokenAddresses: { [ChainId.BSC_TESTNET]: '0x6ce8da28e2f864420840cf74474eff5fd80e65b8', // use btc [ChainId.BSC_MAINNET]: '0xf8a0bf9cf54bb92f17374d9e9a321e6a111a51bd', 1: '0xaba8cac6866b83ae4eec97dd07ed254282f6ad8a' }, name: 'Pineapple bun', symbol: 'LINK-BNB BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'pineapple_bun' }, { pid: 9, lpAddresses: { [ChainId.BSC_TESTNET]: '0x8170b95AaCe8F494090Db7A4a17ba9EB73C2413C', // use bake bnb [ChainId.BSC_MAINNET]: '0x5B294814Ca563E81085a858c0e53B9F2c7a3927f' }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'Rolls', symbol: 'BAKE-DOT BLP', tokenSymbol: MINTTOKEN.BAKE, icon: 'rolls' }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to BEST', symbol: 'BAKE', tokenSymbol: MINTTOKEN.BEST, icon: 'bake_best', amountDay: 5000, amountUnit: 'BEST', stakeIcon: 'bake' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: '0x7499b895F98E4B6FEab59c51322527f9Dec80794', [ChainId.BSC_MAINNET]: '0x229E9F691ed34cf4cb706Fae7bF65AeB9020E329' }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pet[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pet[ChainId.BSC_MAINNET] }, name: 'Earn PET', symbol: 'PET-BNB BLP', tokenSymbol: MINTTOKEN.BPET, icon: 'pets', // activityTime: '5000 PET/hour from Oct. 20 07:00 UTC to Oct. 20 19:00 UTC', stakeIcon: 'pets', otherName: 'PET' } ] export const bPetPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: '0x7499b895F98E4B6FEab59c51322527f9Dec80794', [ChainId.BSC_MAINNET]: '0x229E9F691ed34cf4cb706Fae7bF65AeB9020E329' }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pet[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pet[ChainId.BSC_MAINNET] }, name: 'Earn PET', symbol: 'PET-BNB BLP', tokenSymbol: MINTTOKEN.BPET, icon: 'pets', // activityTime: '5000 PET/hour from Oct. 20 07:00 UTC to Oct. 20 19:00 UTC', stakeIcon: 'pets', otherName: 'PET' } ] export const weaponPools = [ { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to Weapon', symbol: 'BAKE', tokenSymbol: MINTTOKEN.WEAPON, icon: 'bake_weapon', stakeIcon: 'bake' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pet[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pet[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pet[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pet[ChainId.BSC_MAINNET] }, name: 'PET to Weapon', symbol: 'PET', tokenSymbol: MINTTOKEN.WEAPON, icon: 'pet_weapon', stakeIcon: 'pet' } ] export const bestPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to BEST', symbol: 'BAKE', tokenSymbol: MINTTOKEN.BEST, icon: 'bake_best', amountDay: 5000, amountUnit: 'BEST', stakeIcon: 'bake' } ] export const weaponnftPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'Weapon NFT', symbol: 'BAKE', tokenSymbol: MINTTOKEN.WEAPONNFT, icon: 'weaponnft', stakeIcon: 'weaponnft', otherName: 'Weapon NFT' } ] export const petNftPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to Pet NFT', symbol: 'BAKE', tokenSymbol: MINTTOKEN.PETNFT, icon: 'weaponnft', stakeIcon: 'weaponnft', otherName: 'Pet NFT' }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pet[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pet[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pet[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pet[ChainId.BSC_MAINNET] }, name: 'PET to Pet NFT', symbol: 'PET', tokenSymbol: MINTTOKEN.PETNFT, icon: 'weaponnft', stakeIcon: 'pet', otherName: 'Pet NFT' } ] export const helmetNftPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'TKO NFT Pool', symbol: 'BAKE', tokenSymbol: MINTTOKEN.TKONFT, icon: 'tkonft', stakeIcon: 'bake', otherName: 'TKO NFT' } // { // pid: 1, // lpAddresses: { // [ChainId.BSC_TESTNET]: contractAddresses.pCWS[ChainId.BSC_TESTNET], // [ChainId.BSC_MAINNET]: contractAddresses.pCWS[ChainId.BSC_MAINNET] // }, // tokenAddresses: { // [ChainId.BSC_TESTNET]: contractAddresses.pCWS[ChainId.BSC_TESTNET], // [ChainId.BSC_MAINNET]: contractAddresses.pCWS[ChainId.BSC_MAINNET] // }, // name: 'CWS NFT Pool', // symbol: 'pCWS', // tokenSymbol: MINTTOKEN.SEASCAPENFT, // icon: 'seascapenft', // stakeIcon: 'helmetnft', // otherName: 'SEASCAPE NFT' // }, // { // pid: 1, // lpAddresses: { // [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], // [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] // }, // tokenAddresses: { // [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], // [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] // }, // name: 'NFT Christmas Hat', // symbol: 'BAKE', // tokenSymbol: MINTTOKEN.HATNFT, // icon: 'helmetnft', // stakeIcon: 'helmetnft', // otherName: 'Xmas hats NFT' // }, // { // pid: 2, // lpAddresses: { // [ChainId.BSC_TESTNET]: contractAddresses.ten[ChainId.BSC_TESTNET], // [ChainId.BSC_MAINNET]: contractAddresses.ten[ChainId.BSC_MAINNET] // }, // tokenAddresses: { // [ChainId.BSC_TESTNET]: contractAddresses.ten[ChainId.BSC_TESTNET], // [ChainId.BSC_MAINNET]: contractAddresses.ten[ChainId.BSC_MAINNET] // }, // name: 'Ten to PET NFT', // symbol: 'TEN', // tokenSymbol: MINTTOKEN.TEN, // icon: 'ten2', // stakeIcon: 'helmetnft', // otherName: 'PET NFT', // amountUnit: 'PET NFT', // amountDay: '100' // } ] export const hatNftPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'NFT Christmas Hat', symbol: 'BAKE', tokenSymbol: MINTTOKEN.HATNFT, icon: 'helmetnft', stakeIcon: 'helmetnft', otherName: 'Xmas hats NFT' } ] export const eth2MasterPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: '0x07b5a883c74a844232533ee8b713f5210fe15b5b', [ChainId.BSC_MAINNET]: '0xFb72D7C0f1643c96c197A98E5f36eBcf7597d0E3' }, tokenAddresses: [ { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, { [ChainId.BSC_TESTNET]: '0x747c58A36Fe414032072d671ccdf38720aDDb1a9', [ChainId.BSC_MAINNET]: '0x250632378E573c6Be1AC2f97Fcdf00515d0Aa91B' } ], name: 'Hamburger', symbol: 'BETH-ETH BLP', tokenSymbol: MINTTOKEN.ETH2MASTER, icon: 'hamburger', stakeIcon: 'eth', otherName: 'BETH + BAKE', bethRoi: 15, bakeRoi: 15 }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: '0x392a2cfd11f5933fc48f6d132567bf0d8816443e', [ChainId.BSC_MAINNET]: '0x2fC2aD3c28560C97CAcA6D2DcF9B38614F48769A' }, tokenAddresses: [ { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, { [ChainId.BSC_TESTNET]: '0x747c58A36Fe414032072d671ccdf38720aDDb1a9', [ChainId.BSC_MAINNET]: '0x250632378E573c6Be1AC2f97Fcdf00515d0Aa91B' } ], name: 'Macaroon', symbol: 'BETH-BNB BLP', tokenSymbol: MINTTOKEN.ETH2MASTER, icon: 'macaroon', stakeIcon: 'eth', otherName: 'BETH + BAKE', bethRoi: 15, bakeRoi: 15 }, { pid: 3, lpAddresses: { [ChainId.BSC_TESTNET]: '0xa759f0fd9918bba2c03687492d5b7dc37ebd9ac9', [ChainId.BSC_MAINNET]: '0x5FeF671Df9718934FDa164da289374f675745D86' }, tokenAddresses: [ { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, { [ChainId.BSC_TESTNET]: '0x747c58A36Fe414032072d671ccdf38720aDDb1a9', [ChainId.BSC_MAINNET]: '0x250632378E573c6Be1AC2f97Fcdf00515d0Aa91B' } ], name: 'Macaroon2', symbol: 'BETH-BUSD BLP', tokenSymbol: MINTTOKEN.ETH2MASTER, icon: 'macaroon2', stakeIcon: 'eth', otherName: 'BETH + BAKE', bethRoi: 15, bakeRoi: 15 } ] export const aethMasterPools = [ { pid: 4, lpAddresses: { [ChainId.BSC_TESTNET]: '0x29A96ac9949C1de0Ac9896Ae2A2229570dFd867E', [ChainId.BSC_MAINNET]: '0x8c7e17ebe49943109F04c85dF540609c660E2a27' }, tokenAddresses: [ { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, { [ChainId.BSC_TESTNET]: contractAddresses.ankr[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.ankr[ChainId.BSC_MAINNET] }, { [ChainId.BSC_TESTNET]: contractAddresses.onx[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.onx[ChainId.BSC_MAINNET] } ], name: 'Macaroon3', symbol: 'AETH-BETH BLP', tokenSymbol: MINTTOKEN.AETHMASTER, icon: 'macaroon3', stakeIcon: 'aeth', otherName: 'ANKR + ONX + BAKE', bethRoi: 15, bakeRoi: 15 }, { pid: 5, lpAddresses: { [ChainId.BSC_TESTNET]: '0x21B712E0A15DE4b0DB343F958aDA7d6Dbc31ba59', [ChainId.BSC_MAINNET]: '0xcCFe31Dd6B74b2695a5163a6648d28766323EbC3' }, tokenAddresses: [ { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, { [ChainId.BSC_TESTNET]: contractAddresses.ankr[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.ankr[ChainId.BSC_MAINNET] }, { [ChainId.BSC_TESTNET]: contractAddresses.onx[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.onx[ChainId.BSC_MAINNET] } ], name: 'Macaroon4', symbol: 'AETH-ETH BLP', tokenSymbol: MINTTOKEN.AETHMASTER, icon: 'macaroon4', stakeIcon: 'aeth', otherName: 'ANKR + ONX + BAKE', bethRoi: 15, bakeRoi: 15 } ] export const aethAndEth2Pools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: '0x07b5a883c74a844232533ee8b713f5210fe15b5b', [ChainId.BSC_MAINNET]: '0xFb72D7C0f1643c96c197A98E5f36eBcf7597d0E3' }, tokenAddresses: [ { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, { [ChainId.BSC_TESTNET]: '0x747c58A36Fe414032072d671ccdf38720aDDb1a9', [ChainId.BSC_MAINNET]: '0x250632378E573c6Be1AC2f97Fcdf00515d0Aa91B' } ], name: 'Hamburger', symbol: 'BETH-ETH BLP', tokenSymbol: MINTTOKEN.ETH2MASTER, icon: 'hamburger', stakeIcon: 'eth', otherName: 'BETH + BAKE', bethRoi: 15, bakeRoi: 15 }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: '0x392a2cfd11f5933fc48f6d132567bf0d8816443e', [ChainId.BSC_MAINNET]: '0x2fC2aD3c28560C97CAcA6D2DcF9B38614F48769A' }, tokenAddresses: [ { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, { [ChainId.BSC_TESTNET]: '0x747c58A36Fe414032072d671ccdf38720aDDb1a9', [ChainId.BSC_MAINNET]: '0x250632378E573c6Be1AC2f97Fcdf00515d0Aa91B' } ], name: 'Macaroon', symbol: 'BETH-BNB BLP', tokenSymbol: MINTTOKEN.ETH2MASTER, icon: 'macaroon', stakeIcon: 'eth', otherName: 'BETH + BAKE', bethRoi: 15, bakeRoi: 15 }, { pid: 3, lpAddresses: { [ChainId.BSC_TESTNET]: '0xa759f0fd9918bba2c03687492d5b7dc37ebd9ac9', [ChainId.BSC_MAINNET]: '0x5FeF671Df9718934FDa164da289374f675745D86' }, tokenAddresses: [ { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, { [ChainId.BSC_TESTNET]: '0x747c58A36Fe414032072d671ccdf38720aDDb1a9', [ChainId.BSC_MAINNET]: '0x250632378E573c6Be1AC2f97Fcdf00515d0Aa91B' } ], name: 'Macaroon2', symbol: 'BETH-BUSD BLP', tokenSymbol: MINTTOKEN.ETH2MASTER, icon: 'macaroon2', stakeIcon: 'eth', otherName: 'BETH + BAKE', bethRoi: 15, bakeRoi: 15 }, { pid: 4, lpAddresses: { [ChainId.BSC_TESTNET]: '0x29A96ac9949C1de0Ac9896Ae2A2229570dFd867E', [ChainId.BSC_MAINNET]: '0x8c7e17ebe49943109F04c85dF540609c660E2a27' }, tokenAddresses: [ { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, { [ChainId.BSC_TESTNET]: contractAddresses.ankr[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.ankr[ChainId.BSC_MAINNET] }, { [ChainId.BSC_TESTNET]: contractAddresses.onx[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.onx[ChainId.BSC_MAINNET] } ], name: 'Macaroon3', symbol: 'AETH-BETH BLP', tokenSymbol: MINTTOKEN.AETHMASTER, icon: 'macaroon3', stakeIcon: 'aeth', otherName: 'ANKR + ONX + BAKE', bethRoi: 15, bakeRoi: 15 }, { pid: 5, lpAddresses: { [ChainId.BSC_TESTNET]: '0x21B712E0A15DE4b0DB343F958aDA7d6Dbc31ba59', [ChainId.BSC_MAINNET]: '0xcCFe31Dd6B74b2695a5163a6648d28766323EbC3' }, tokenAddresses: [ { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, { [ChainId.BSC_TESTNET]: contractAddresses.ankr[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.ankr[ChainId.BSC_MAINNET] }, { [ChainId.BSC_TESTNET]: contractAddresses.onx[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.onx[ChainId.BSC_MAINNET] } ], name: 'Macaroon4', symbol: 'AETH-ETH BLP', tokenSymbol: MINTTOKEN.AETHMASTER, icon: 'macaroon4', stakeIcon: 'aeth', otherName: 'ANKR + ONX + BAKE', bethRoi: 15, bakeRoi: 15 } ] export const springMasterPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.tenBakeBLP[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.tenBakeBLP[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.ten[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.ten[ChainId.BSC_MAINNET] }, name: 'Bake to Ten', symbol: 'TEN-BAKE BLP', tokenSymbol: MINTTOKEN.TEN, icon: 'ten1', stakeIcon: 'staketen', otherName: 'TEN' // amountDay: '5000', // amountUnit: MINTTOKEN.TEN, }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.ten[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.ten[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.ten[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.ten[ChainId.BSC_MAINNET] }, name: 'Ten to PET NFT', symbol: 'TEN', tokenSymbol: MINTTOKEN.TEN, icon: 'ten2', stakeIcon: 'helmetnft', otherName: 'PET NFT', amountUnit: 'PET NFT', amountDay: '100' } ] export const wSOTEMasterPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to wSOTE', symbol: 'BAKE', tokenSymbol: MINTTOKEN.WSOTE, icon: 'wsote', stakeIcon: 'bake', otherName: 'wSOTE' } ] export const SHIELDMasterPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to SHIELD', symbol: 'BAKE', tokenSymbol: MINTTOKEN.SHIELD, icon: 'shield', stakeIcon: 'bake', otherName: 'SHIELD' } ] export const BRYMasterPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to BRY', symbol: 'BAKE', tokenSymbol: MINTTOKEN.BRY, icon: 'bry', stakeIcon: 'bake', otherName: 'BRY' } ] // bake staking export const supportedBakeStakingPools = [ // { // pid: 1, // lpAddresses: { // [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], // [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] // }, // tokenAddresses: { // [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], // [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] // }, // name: 'BAKE to D100', // symbol: 'BAKE', // tokenSymbol: MINTTOKEN.DEFI100, // icon: 'defi100', // stakeIcon: 'bake', // otherName: 'D100' // }, // stake bake earn bake一直放在第一个 { pid: 7, lpAddresses: { [ChainId.BSC_TESTNET]: '0xe02df9e3e622debdd69fb838bb799e3f168902c5', [ChainId.BSC_MAINNET]: '0xe02df9e3e622debdd69fb838bb799e3f168902c5', // 主网生产 // [ChainId.BSC_MAINNET]: '0x918DE02364E0b63CE83e3741d254D19D8FE8f914', // 主网预生产合约ODO 1: '0xce84867c3c02b05dc570d0135103d3fb9cc19433' }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'Bread', symbol: 'BAKE', tokenSymbol: MINTTOKEN.BAKE, icon: 'bread' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to MX', symbol: 'BAKE', tokenSymbol: MINTTOKEN.MX, icon: 'mx', stakeIcon: 'bake', otherName: 'MX' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to DIESEL', symbol: 'BAKE', tokenSymbol: MINTTOKEN.DIESEL, icon: 'diesel', stakeIcon: 'bake', otherName: 'DIESEL' }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to WAR', symbol: 'BAKE', tokenSymbol: MINTTOKEN.WAR, icon: 'war', stakeIcon: 'bake', otherName: 'WAR' }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to pCWS', symbol: 'BAKE', tokenSymbol: MINTTOKEN.PCWS, icon: 'pcws', stakeIcon: 'bake', otherName: 'pCWS' }, { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to SHIELD', symbol: 'BAKE', tokenSymbol: MINTTOKEN.SHIELD, icon: 'shield', stakeIcon: 'bake', otherName: 'SHIELD', ended: true }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to Weapon', symbol: 'BAKE', tokenSymbol: MINTTOKEN.WEAPON, icon: 'bake_weapon', stakeIcon: 'bake' } ] export const DEFI100MasterPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to D100', symbol: 'BAKE', tokenSymbol: MINTTOKEN.DEFI100, icon: 'defi100', stakeIcon: 'bake', otherName: 'D100' } ] export const DEFI100OLDMasterPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'D100(not used)', symbol: 'BAKE', tokenSymbol: MINTTOKEN.DEFI100OLD, icon: 'defi100', stakeIcon: 'bake', otherName: 'D100' } ] export const BananaMasterPools = [ { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.bakeBananaBlp[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.bakeBananaBlp[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.BANANA[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.BANANA[ChainId.BSC_MAINNET] }, name: 'BANANA', symbol: 'BAKE BANANA BLP', tokenSymbol: MINTTOKEN.BANANA, icon: 'banana', stakeIcon: 'banana', otherName: 'BANANA' } ] export const seascapeNftPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pCWS[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pCWS[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.pCWS[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.pCWS[ChainId.BSC_MAINNET] }, name: 'CWS NFT Pool', symbol: 'pCWS', tokenSymbol: MINTTOKEN.SEASCAPENFT, icon: 'seascapenft', stakeIcon: 'seascapenft', otherName: 'SEASCAPE NFT' } ] export const pCWSMasterPools = [ { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to pCWS', symbol: 'BAKE', tokenSymbol: MINTTOKEN.PCWS, icon: 'pcws', stakeIcon: 'bake', otherName: 'pCWS' } ] export const warMasterPools = [ { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to WAR', symbol: 'BAKE', tokenSymbol: MINTTOKEN.WAR, icon: 'war', stakeIcon: 'bake', otherName: 'WAR' } ] export const war2MasterPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.busdWarBlp[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.busdWarBlp[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.war[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.war[ChainId.BSC_MAINNET] }, name: 'BUSD-WAR BLP', symbol: 'BUSD-WAR BLP', tokenSymbol: MINTTOKEN.WAR2, icon: 'war', stakeIcon: 'bake', otherName: 'WAR' } ] export const tokocryptoNftPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'TKO NFT Pool', symbol: 'BAKE', tokenSymbol: MINTTOKEN.TKONFT, icon: 'tkonft', stakeIcon: 'bake', otherName: 'TKO NFT' } ] export const dieselPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to DIESEL', symbol: 'BAKE', tokenSymbol: MINTTOKEN.DIESEL, icon: 'diesel', stakeIcon: 'bake', otherName: 'DIESEL' }, { pid: 2, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.bnbDieselBlp[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.bnbDieselBlp[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.diesel[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.diesel[ChainId.BSC_MAINNET] }, name: 'BNB-DIESEL BLP', symbol: 'BNB-DIESEL BLP', tokenSymbol: MINTTOKEN.DIESEL, icon: 'diesel', stakeIcon: 'bnb_diesel', otherName: 'DIESEL' } ] export const mxMasterPools = [ { pid: 1, lpAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, tokenAddresses: { [ChainId.BSC_TESTNET]: contractAddresses.sushi[ChainId.BSC_TESTNET], [ChainId.BSC_MAINNET]: contractAddresses.sushi[ChainId.BSC_MAINNET] }, name: 'BAKE to MX', symbol: 'BAKE', tokenSymbol: MINTTOKEN.MX, icon: 'mx', stakeIcon: 'bake', otherName: 'MX' } ]
the_stack
import {fakeAsync, TestBed, tick} from '@angular/core/testing'; import {Component, Type} from '@angular/core'; import {By} from '@angular/platform-browser'; import {CdkListbox, CdkListboxModule, CdkOption, ListboxValueChangeEvent} from './index'; import {dispatchKeyboardEvent, dispatchMouseEvent} from '../../cdk/testing/private'; import {B, DOWN_ARROW, END, HOME, SPACE, UP_ARROW} from '@angular/cdk/keycodes'; import {FormControl, ReactiveFormsModule} from '@angular/forms'; import {CommonModule} from '@angular/common'; async function setupComponent<T, O = string>(component: Type<T>, imports: any[] = []) { await TestBed.configureTestingModule({ imports: [CdkListboxModule, ...imports], declarations: [component], }).compileComponents(); const fixture = TestBed.createComponent(component); fixture.detectChanges(); const listboxDebugEl = fixture.debugElement.query(By.directive(CdkListbox)); const optionDebugEls = fixture.debugElement.queryAll(By.directive(CdkOption)); return { fixture, testComponent: fixture.componentInstance, listbox: listboxDebugEl.injector.get<CdkListbox<O>>(CdkListbox), listboxEl: listboxDebugEl.nativeElement as HTMLElement, options: optionDebugEls.map(el => el.injector.get<CdkOption<O>>(CdkOption)), optionEls: optionDebugEls.map(el => el.nativeElement as HTMLElement), }; } describe('CdkOption and CdkListbox', () => { describe('id', () => { it('should generate unique ids', async () => { const {listbox, listboxEl, options, optionEls} = await setupComponent(ListboxWithOptions); const optionIds = new Set(optionEls.map(option => option.id)); expect(optionIds.size).toBe(options.length); for (let i = 0; i < options.length; i++) { expect(options[i].id).toBe(optionEls[i].id); expect(options[i].id).toMatch(/cdk-option-\d+/); } expect(listbox.id).toEqual(listboxEl.id); expect(listbox.id).toMatch(/cdk-listbox-\d+/); }); it('should not overwrite user given ids', async () => { const {testComponent, fixture, listboxEl, optionEls} = await setupComponent( ListboxWithOptions, ); testComponent.listboxId = 'my-listbox'; testComponent.appleId = 'my-apple'; fixture.detectChanges(); expect(listboxEl.id).toBe('my-listbox'); expect(optionEls[0].id).toBe('my-apple'); }); }); describe('tabindex', () => { it('should use tabindex=0 for focusable elements, tabindex=-1 for non-focusable elements', async () => { const {fixture, listbox, listboxEl, optionEls} = await setupComponent(ListboxWithOptions); expect(listboxEl.getAttribute('tabindex')).toBe('0'); expect(optionEls[0].getAttribute('tabindex')).toBe('-1'); listbox.focus(); fixture.detectChanges(); expect(listboxEl.getAttribute('tabindex')).toBe('-1'); expect(optionEls[0].getAttribute('tabindex')).toBe('0'); }); it('should respect user given tabindex for focusable elements', async () => { const {testComponent, fixture, listbox, listboxEl, optionEls} = await setupComponent( ListboxWithOptions, ); testComponent.listboxTabindex = 10; testComponent.appleTabindex = 20; fixture.detectChanges(); expect(listboxEl.getAttribute('tabindex')).toBe('10'); expect(optionEls[0].getAttribute('tabindex')).toBe('-1'); listbox.focus(); fixture.detectChanges(); expect(listboxEl.getAttribute('tabindex')).toBe('-1'); expect(optionEls[0].getAttribute('tabindex')).toBe('20'); }); it('should use listbox tabindex for focusable options', async () => { const {testComponent, fixture, listbox, optionEls} = await setupComponent(ListboxWithOptions); testComponent.listboxTabindex = 10; fixture.detectChanges(); expect(optionEls[0].getAttribute('tabindex')).toBe('-1'); listbox.focus(); fixture.detectChanges(); expect(optionEls[0].getAttribute('tabindex')).toBe('10'); }); }); describe('selection', () => { it('should be empty initially', async () => { const {fixture, listbox, options, optionEls} = await setupComponent(ListboxWithOptions); expect(listbox.value).toEqual([]); for (let i = 0; i < options.length; i++) { expect(options[i].isSelected()).toBeFalse(); expect(optionEls[i].hasAttribute('aria-selected')).toBeFalse(); } expect(fixture.componentInstance.changedOption).toBeUndefined(); }); it('should update when selection is changed programmatically', async () => { const {fixture, listbox, options, optionEls} = await setupComponent(ListboxWithOptions); options[1].select(); fixture.detectChanges(); expect(listbox.value).toEqual(['orange']); expect(options[1].isSelected()).toBeTrue(); expect(optionEls[1].getAttribute('aria-selected')).toBe('true'); expect(fixture.componentInstance.changedOption).toBeUndefined(); }); it('should update on option clicked', async () => { const {fixture, listbox, options, optionEls} = await setupComponent(ListboxWithOptions); optionEls[0].click(); fixture.detectChanges(); expect(listbox.value).toEqual(['apple']); expect(options[0].isSelected()).toBeTrue(); expect(optionEls[0].getAttribute('aria-selected')).toBe('true'); expect(fixture.componentInstance.changedOption?.id).toBe(options[0].id); }); it('should update on option activated via keyboard', async () => { const {fixture, listbox, listboxEl, options, optionEls} = await setupComponent( ListboxWithOptions, ); listbox.focus(); dispatchKeyboardEvent(listboxEl, 'keydown', SPACE); fixture.detectChanges(); expect(listbox.value).toEqual(['apple']); expect(options[0].isSelected()).toBeTrue(); expect(optionEls[0].getAttribute('aria-selected')).toBe('true'); expect(fixture.componentInstance.changedOption?.id).toBe(options[0].id); }); it('should deselect previously selected option in single-select listbox', async () => { const {fixture, listbox, options, optionEls} = await setupComponent(ListboxWithOptions); dispatchMouseEvent(optionEls[0], 'click'); fixture.detectChanges(); expect(listbox.value).toEqual(['apple']); expect(options[0].isSelected()).toBeTrue(); dispatchMouseEvent(optionEls[2], 'click'); fixture.detectChanges(); expect(listbox.value).toEqual(['banana']); expect(options[0].isSelected()).toBeFalse(); }); it('should select all options programmatically in multi-select listbox', async () => { const {testComponent, fixture, listbox} = await setupComponent(ListboxWithOptions); testComponent.isMultiselectable = true; fixture.detectChanges(); listbox.setAllSelected(true); fixture.detectChanges(); expect(listbox.value).toEqual(['apple', 'orange', 'banana', 'peach']); }); it('should add to selection in multi-select listbox', async () => { const {testComponent, fixture, listbox, options, optionEls} = await setupComponent( ListboxWithOptions, ); testComponent.isMultiselectable = true; optionEls[0].click(); fixture.detectChanges(); expect(listbox.value).toEqual(['apple']); expect(options[0].isSelected()).toBeTrue(); optionEls[2].click(); fixture.detectChanges(); expect(listbox.value).toEqual(['apple', 'banana']); expect(options[0].isSelected()).toBeTrue(); }); it('should deselect all options when switching to single-selection with invalid selection', async () => { const {testComponent, fixture, listbox} = await setupComponent(ListboxWithOptions); testComponent.isMultiselectable = true; fixture.detectChanges(); listbox.setAllSelected(true); fixture.detectChanges(); expect(listbox.value).toEqual(['apple', 'orange', 'banana', 'peach']); testComponent.isMultiselectable = false; fixture.detectChanges(); expect(listbox.value).toEqual([]); }); it('should preserve selection when switching to single-selection with valid selection', async () => { const {testComponent, fixture, listbox, optionEls} = await setupComponent(ListboxWithOptions); testComponent.isMultiselectable = true; fixture.detectChanges(); optionEls[0].click(); fixture.detectChanges(); expect(listbox.value).toEqual(['apple']); testComponent.isMultiselectable = false; fixture.detectChanges(); expect(listbox.value).toEqual(['apple']); }); it('should allow programmatically toggling options', async () => { const {testComponent, fixture, listbox, options} = await setupComponent(ListboxWithOptions); testComponent.isMultiselectable = true; fixture.detectChanges(); options[0].toggle(); listbox.toggle(options[1]); fixture.detectChanges(); expect(options[0].isSelected()).toBeTrue(); expect(options[1].isSelected()).toBeTrue(); options[0].toggle(); listbox.toggle(options[1]); fixture.detectChanges(); expect(options[0].isSelected()).toBeFalse(); expect(options[1].isSelected()).toBeFalse(); }); it('should allow programmatically selecting and deselecting options', async () => { const {testComponent, fixture, listbox, options} = await setupComponent(ListboxWithOptions); testComponent.isMultiselectable = true; fixture.detectChanges(); options[0].select(); listbox.select(options[1]); fixture.detectChanges(); expect(options[0].isSelected()).toBeTrue(); expect(options[1].isSelected()).toBeTrue(); options[0].deselect(); listbox.deselect(options[1]); fixture.detectChanges(); expect(options[0].isSelected()).toBeFalse(); expect(options[1].isSelected()).toBeFalse(); }); // TODO(mmalerba): Fix this case. // Currently banana gets booted because the option isn't loaded yet, // but then when the option loads the value is already lost. // it('should allow binding to listbox value', async () => { // const {testComponent, fixture, listbox, options} = await setupComponent(ListboxWithBoundValue); // expect(listbox.value).toEqual(['banana']); // expect(options[2].isSelected()).toBeTrue(); // // testComponent.value = ['orange']; // fixture.detectChanges(); // // expect(listbox.value).toEqual(['orange']); // expect(options[1].isSelected()).toBeTrue(); // }); }); describe('disabled state', () => { it('should be able to toggle listbox disabled state', async () => { const {fixture, testComponent, listbox, listboxEl, options, optionEls} = await setupComponent( ListboxWithOptions, ); testComponent.isListboxDisabled = true; fixture.detectChanges(); expect(listbox.disabled).toBeTrue(); expect(listboxEl.getAttribute('aria-disabled')).toBe('true'); for (let i = 0; i < options.length; i++) { expect(options[i].disabled).toBeTrue(); expect(optionEls[i].getAttribute('aria-disabled')).toBe('true'); } }); it('should toggle option disabled state', async () => { const {fixture, testComponent, options, optionEls} = await setupComponent(ListboxWithOptions); testComponent.isAppleDisabled = true; fixture.detectChanges(); expect(options[0].disabled).toBeTrue(); expect(optionEls[0].getAttribute('aria-disabled')).toBe('true'); }); it('should not change selection on click of a disabled option', async () => { const {fixture, testComponent, listbox, optionEls} = await setupComponent(ListboxWithOptions); testComponent.isAppleDisabled = true; fixture.detectChanges(); optionEls[0].click(); fixture.detectChanges(); expect(listbox.value).toEqual([]); expect(fixture.componentInstance.changedOption).toBeUndefined(); }); it('should not change selection on click in a disabled listbox', async () => { const {fixture, testComponent, listbox, optionEls} = await setupComponent(ListboxWithOptions); testComponent.isListboxDisabled = true; fixture.detectChanges(); optionEls[0].click(); fixture.detectChanges(); expect(listbox.value).toEqual([]); expect(fixture.componentInstance.changedOption).toBeUndefined(); }); it('should not change selection on keyboard activation in a disabled listbox', async () => { const {fixture, testComponent, listbox, listboxEl} = await setupComponent(ListboxWithOptions); listbox.focus(); fixture.detectChanges(); testComponent.isListboxDisabled = true; fixture.detectChanges(); dispatchKeyboardEvent(listboxEl, 'keydown', SPACE); fixture.detectChanges(); expect(listbox.value).toEqual([]); expect(fixture.componentInstance.changedOption).toBeUndefined(); }); it('should not change selection on click of a disabled option', async () => { const {fixture, testComponent, listbox, listboxEl} = await setupComponent(ListboxWithOptions); listbox.focus(); fixture.detectChanges(); testComponent.isAppleDisabled = true; fixture.detectChanges(); dispatchKeyboardEvent(listboxEl, 'keydown', SPACE); fixture.detectChanges(); expect(listbox.value).toEqual([]); expect(fixture.componentInstance.changedOption).toBeUndefined(); }); it('should not handle type ahead on a disabled listbox', async (...args: unknown[]) => { const {fixture, testComponent, listboxEl, options} = await setupComponent(ListboxWithOptions); await fakeAsync(() => { testComponent.isListboxDisabled = true; fixture.detectChanges(); dispatchKeyboardEvent(listboxEl, 'keydown', B); fixture.detectChanges(); tick(200); for (let option of options) { expect(option.isActive()).toBeFalse(); } })(args); }); it('should skip disabled options when navigating with arrow keys', async () => { const {testComponent, fixture, listbox, listboxEl, options} = await setupComponent( ListboxWithOptions, ); testComponent.isOrangeDisabled = true; listbox.focus(); fixture.detectChanges(); expect(options[0].isActive()).toBeTrue(); dispatchKeyboardEvent(listboxEl, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(options[2].isActive()).toBeTrue(); }); }); describe('compare with', () => { it('should allow custom function to compare option values', async () => { const {fixture, listbox, options} = await setupComponent< ListboxWithObjectValues, {name: string} >(ListboxWithObjectValues, [CommonModule]); listbox.value = [{name: 'Banana'}]; fixture.detectChanges(); expect(options[2].isSelected()).toBeTrue(); listbox.value = [{name: 'Orange', extraStuff: true} as any]; fixture.detectChanges(); expect(options[1].isSelected()).toBeTrue(); }); }); describe('keyboard navigation', () => { it('should update active item on arrow key presses', async () => { const {fixture, listbox, listboxEl, options} = await setupComponent(ListboxWithOptions); listbox.focus(); dispatchKeyboardEvent(listboxEl, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(options[1].isActive()).toBeTrue(); dispatchKeyboardEvent(listboxEl, 'keydown', UP_ARROW); fixture.detectChanges(); expect(options[0].isActive()).toBeTrue(); }); it('should update active option on home and end key press', async () => { const {fixture, listbox, listboxEl, options, optionEls} = await setupComponent( ListboxWithOptions, ); listbox.focus(); dispatchKeyboardEvent(listboxEl, 'keydown', END); fixture.detectChanges(); expect(options[options.length - 1].isActive()).toBeTrue(); expect(optionEls[options.length - 1].classList).toContain('cdk-option-active'); dispatchKeyboardEvent(listboxEl, 'keydown', HOME); fixture.detectChanges(); expect(options[0].isActive()).toBeTrue(); expect(optionEls[0].classList).toContain('cdk-option-active'); }); it('should change active item using type ahead', async (...args: unknown[]) => { const {fixture, listbox, listboxEl, options} = await setupComponent(ListboxWithOptions); await fakeAsync(() => { listbox.focus(); fixture.detectChanges(); dispatchKeyboardEvent(listboxEl, 'keydown', B); fixture.detectChanges(); tick(200); expect(options[2].isActive()).toBeTrue(); })(args); }); it('should allow custom type ahead label', async (...args: unknown[]) => { const {fixture, listbox, listboxEl, options} = await setupComponent( ListboxWithCustomTypeahead, ); await fakeAsync(() => { listbox.focus(); fixture.detectChanges(); dispatchKeyboardEvent(listboxEl, 'keydown', B); fixture.detectChanges(); tick(200); expect(options[2].isActive()).toBeTrue(); })(args); }); it('should focus and toggle the next item when pressing SHIFT + DOWN_ARROW', async () => { const {fixture, listbox, listboxEl, options} = await setupComponent(ListboxWithOptions); listbox.focus(); fixture.detectChanges(); dispatchKeyboardEvent(listboxEl, 'keydown', DOWN_ARROW, undefined, {shift: true}); fixture.detectChanges(); expect(listbox.value).toEqual(['orange']); expect(fixture.componentInstance.changedOption?.id).toBe(options[1].id); }); // TODO(mmalerba): ensure all keys covered }); describe('with roving tabindex', () => { it('should shift focus on keyboard navigation', async () => { const {fixture, listbox, listboxEl, optionEls} = await setupComponent(ListboxWithOptions); listbox.focus(); fixture.detectChanges(); expect(document.activeElement).toBe(optionEls[0]); expect(listboxEl.hasAttribute('aria-activedescendant')).toBeFalse(); dispatchKeyboardEvent(listboxEl, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(document.activeElement).toBe(optionEls[1]); expect(listboxEl.hasAttribute('aria-activedescendant')).toBeFalse(); }); it('should focus first option on listbox focus', async () => { const {fixture, listbox, optionEls} = await setupComponent(ListboxWithOptions); listbox.focus(); fixture.detectChanges(); expect(document.activeElement).toBe(optionEls[0]); }); it('should focus listbox if no focusable options available', async () => { const {fixture, listbox, listboxEl} = await setupComponent(ListboxWithNoOptions); listbox.focus(); fixture.detectChanges(); expect(document.activeElement).toBe(listboxEl); }); }); describe('with aria-activedescendant', () => { it('should update active descendant on keyboard navigation', async () => { const {testComponent, fixture, listbox, listboxEl, optionEls} = await setupComponent( ListboxWithOptions, ); testComponent.isActiveDescendant = true; fixture.detectChanges(); listbox.focus(); dispatchKeyboardEvent(listboxEl, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(listboxEl.getAttribute('aria-activedescendant')).toBe(optionEls[0].id); expect(document.activeElement).toBe(listboxEl); dispatchKeyboardEvent(listboxEl, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(listboxEl.getAttribute('aria-activedescendant')).toBe(optionEls[1].id); expect(document.activeElement).toBe(listboxEl); }); it('should not activate an option on listbox focus', async () => { const {testComponent, fixture, listbox, options} = await setupComponent(ListboxWithOptions); testComponent.isActiveDescendant = true; fixture.detectChanges(); listbox.focus(); fixture.detectChanges(); for (let option of options) { expect(option.isActive()).toBeFalse(); } }); it('should focus listbox and make option active on option focus', async () => { const {testComponent, fixture, listboxEl, options, optionEls} = await setupComponent( ListboxWithOptions, ); testComponent.isActiveDescendant = true; fixture.detectChanges(); optionEls[2].focus(); fixture.detectChanges(); expect(document.activeElement).toBe(listboxEl); expect(options[2].isActive()).toBeTrue(); }); }); describe('with FormControl', () => { it('should reflect disabled state of the FormControl', async () => { const {testComponent, fixture, listbox} = await setupComponent(ListboxWithFormControl, [ ReactiveFormsModule, ]); testComponent.formControl.disable(); fixture.detectChanges(); expect(listbox.disabled).toBeTrue(); }); it('should update when FormControl value changes', async () => { const {testComponent, fixture, options} = await setupComponent(ListboxWithFormControl, [ ReactiveFormsModule, ]); testComponent.formControl.setValue(['banana']); fixture.detectChanges(); expect(options[2].isSelected()).toBeTrue(); }); it('should update FormControl when selection changes', async () => { const {testComponent, fixture, optionEls} = await setupComponent(ListboxWithFormControl, [ ReactiveFormsModule, ]); const spy = jasmine.createSpy(); const subscription = testComponent.formControl.valueChanges.subscribe(spy); fixture.detectChanges(); expect(spy).not.toHaveBeenCalled(); optionEls[1].click(); fixture.detectChanges(); expect(spy).toHaveBeenCalledWith(['orange']); subscription.unsubscribe(); }); it('should update multi-select listbox when FormControl value changes', async () => { const {testComponent, fixture, options} = await setupComponent(ListboxWithFormControl, [ ReactiveFormsModule, ]); testComponent.isMultiselectable = true; fixture.detectChanges(); testComponent.formControl.setValue(['orange', 'banana']); fixture.detectChanges(); expect(options[1].isSelected()).toBeTrue(); expect(options[2].isSelected()).toBeTrue(); }); it('should update FormControl when multi-selection listbox changes', async () => { const {testComponent, fixture, optionEls} = await setupComponent(ListboxWithFormControl, [ ReactiveFormsModule, ]); testComponent.isMultiselectable = true; fixture.detectChanges(); const spy = jasmine.createSpy(); const subscription = testComponent.formControl.valueChanges.subscribe(spy); fixture.detectChanges(); expect(spy).not.toHaveBeenCalled(); optionEls[1].click(); fixture.detectChanges(); expect(spy).toHaveBeenCalledWith(['orange']); optionEls[2].click(); fixture.detectChanges(); expect(spy).toHaveBeenCalledWith(['orange', 'banana']); subscription.unsubscribe(); }); it('should have FormControl error multiple values selected in single-select listbox', async () => { const {testComponent, fixture} = await setupComponent(ListboxWithFormControl, [ ReactiveFormsModule, ]); testComponent.formControl.setValue(['orange', 'banana']); fixture.detectChanges(); expect(testComponent.formControl.hasError('cdkListboxMultipleValues')).toBeTrue(); expect(testComponent.formControl.hasError('cdkListboxInvalidValues')).toBeFalse(); }); it('should have FormControl error when non-option value selected', async () => { const {testComponent, fixture} = await setupComponent(ListboxWithFormControl, [ ReactiveFormsModule, ]); testComponent.isMultiselectable = true; testComponent.formControl.setValue(['orange', 'dragonfruit', 'mango']); fixture.detectChanges(); expect(testComponent.formControl.hasError('cdkListboxInvalidValues')).toBeTrue(); expect(testComponent.formControl.hasError('cdkListboxMultipleValues')).toBeFalse(); expect(testComponent.formControl.errors?.['cdkListboxInvalidValues']).toEqual({ 'values': ['dragonfruit', 'mango'], }); }); it('should have multiple FormControl errors when multiple non-option values selected in single-select listbox', async () => { const {testComponent, fixture} = await setupComponent(ListboxWithFormControl, [ ReactiveFormsModule, ]); testComponent.formControl.setValue(['dragonfruit', 'mango']); fixture.detectChanges(); expect(testComponent.formControl.hasError('cdkListboxInvalidValues')).toBeTrue(); expect(testComponent.formControl.hasError('cdkListboxMultipleValues')).toBeTrue(); expect(testComponent.formControl.errors?.['cdkListboxInvalidValues']).toEqual({ 'values': ['dragonfruit', 'mango'], }); }); }); }); @Component({ template: ` <div cdkListbox [id]="listboxId" [tabindex]="listboxTabindex" [cdkListboxMultiple]="isMultiselectable" [cdkListboxDisabled]="isListboxDisabled" [cdkListboxUseActiveDescendant]="isActiveDescendant" (cdkListboxValueChange)="onSelectionChange($event)"> <div cdkOption="apple" [cdkOptionDisabled]="isAppleDisabled" [id]="appleId" [tabindex]="appleTabindex"> Apple </div> <div cdkOption="orange" [cdkOptionDisabled]="isOrangeDisabled">Orange</div> <div cdkOption="banana">Banana</div> <div cdkOption="peach">Peach</div> </div> `, }) class ListboxWithOptions { changedOption: CdkOption; isListboxDisabled = false; isAppleDisabled = false; isOrangeDisabled = false; isMultiselectable = false; isActiveDescendant = false; listboxId: string; listboxTabindex: number; appleId: string; appleTabindex: number; onSelectionChange(event: ListboxValueChangeEvent<unknown>) { this.changedOption = event.option; } } @Component({ template: `<div cdkListbox></div>`, }) class ListboxWithNoOptions {} @Component({ template: ` <div cdkListbox [formControl]="formControl" [cdkListboxMultiple]="isMultiselectable" [cdkListboxUseActiveDescendant]="isActiveDescendant"> <div cdkOption="apple">Apple</div> <div cdkOption="orange">Orange</div> <div cdkOption="banana">Banana</div> <div cdkOption="peach">Peach</div> </div> `, }) class ListboxWithFormControl { formControl = new FormControl(); isMultiselectable = false; isActiveDescendant = false; } @Component({ template: ` <ul cdkListbox> <li cdkOption="apple" cdkOptionTypeaheadLabel="apple">🍎</li> <li cdkOption="orange" cdkOptionTypeaheadLabel="orange">🍊</li> <li cdkOption="banana" cdkOptionTypeaheadLabel="banana">🍌</li> <li cdkOption="peach" cdkOptionTypeaheadLabel="peach">🍑</li> </ul> `, }) class ListboxWithCustomTypeahead {} // @Component({ // template: ` // <div cdkListbox // [cdkListboxValue]="value"> // <div cdkOption="apple">Apple</div> // <div cdkOption="orange">Orange</div> // <div cdkOption="banana">Banana</div> // <div cdkOption="peach">Peach</div> // </div> // `, // }) // class ListboxWithBoundValue { // value = ['banana']; // } @Component({ template: ` <div cdkListbox [cdkListboxCompareWith]="fruitCompare"> <div *ngFor="let fruit of fruits" [cdkOption]="fruit">{{fruit.name}}</div> </div> `, }) class ListboxWithObjectValues { fruits = [{name: 'Apple'}, {name: 'Orange'}, {name: 'Banana'}, {name: 'Peach'}]; fruitCompare = (a: {name: string}, b: {name: string}) => a.name === b.name; }
the_stack
module formFor { /** * SelectField $scope. */ interface TypeAheadFieldScope extends ng.IScope { /** * Name of the attribute within the parent form-for directive's model object. * This attributes specifies the data-binding target for the input. * Dot notation (ex "address.street") is supported. */ attribute:string; /** * Views must call this callback to notify of the <select> menu having been closed. */ close:Function; /** * Debounce duration (in ms) before filter text is applied to options. */ debounce?:number; /** * Disable input element. * Note the name is disable and not disabled to avoid collisions with the HTML5 disabled attribute. * This attribute defaults to 'auto' which means that the menu will drop up or down based on its position within the viewport. */ disable:boolean; /** * Two-way bindable filter string. * $watch this property to load remote options based on filter text. * (Refer to the documentation for coding examples.) */ filter?:string; /** * Visible options, shown after filtering. */ filteredOptions:Array<any>; /** * Optional function to be invoked when the filter text has changed. * Use this function to implement server-side filtering. */ filterTextChanged?:(data:{[text:string]:string}) => void; /** * Callback to apply filtered text. */ filterTextClick:Function; /** * Optional help tooltip to display on hover. * By default this makes use of the Angular Bootstrap tooltip directive and the Font Awesome icon set. */ help?:string; /** * Select menu is currently open. */ isOpen:boolean; /** * Key-down event handler to be called by view template. */ keyDown:(event:any) => void; /** * Optional field label displayed before the drop-down. * (Although not required, it is strongly suggested that you specify a value for this attribute.) HTML is allowed for this attribute. */ label?:string; /** * Optional override for label key in options array. * Defaults to "label". */ labelAttribute?:string; /** * Optional class-name for field <label>. */ labelClass?:string; /** * Shared between formFor and TypeAheadField directives. */ model:BindableFieldWrapper; /** * Updates mouse-over index. * Called in response to arrow-key navigation of select menu options. */ mouseOver:(index:number) => void; /** * Moused-over option. */ mouseOverOption:any; /** * Index of moused-over option. */ mouseOverIndex:number; /** * Views must call this callback to notify of the <select> menu having been opened. */ open:Function; /** * Set of options, each containing a label and value key. * The label is displayed to the user and the value is assigned to the corresponding model attribute on selection. */ options:Array<Object>; /** * Optional placeholder text to display if no value has been selected and no filter text has been entered. */ placeholder?:string; /** * Used to share data between main select-field template and ngIncluded templates. */ scopeBuster:any; searchTextChange?:(text:string) => void; /** * Selects the specified option. */ selectOption:(option:any) => void; /** * Sets focus on filter field after a small delay. * Can be used to auto-focus on filter field when select menu has been opened. */ setFilterFocus:Function; /** * Optional custom tab index for input; by default this is 0 (tab order chosen by the browser) */ tabIndex?:number; /** * Optional ID to assign to the inner <input type="checkbox"> element; * A unique ID will be auto-generated if no value is provided. */ uid?:string; /** * Optional override for value key in options array. * Defaults to "value". */ valueAttribute:string; } var MIN_TIMEOUT_INTERVAL:number = 10; var $document_:ng.IAugmentedJQuery; var $log_:ng.ILogService; var $timeout_:ng.ITimeoutService; var fieldHelper_:FieldHelper; /** * Renders an &lt;input type="text"&gt; component with type-ahead functionality. * This type of component works with a large set of options that can be loaded asynchronously if needed. * * @example * // To use this component you'll first need to define a set of options. For instance: * $scope.genders = [ * { value: 'f', label: 'Female' }, * { value: 'm', label: 'Male' } * ]; * * // To render a drop-down input using the above options: * <type-ahead-field attribute="gender" * label="Gender" * options="genders"> * </type-ahead-field> * * @param $document $injector-supplied $document service * @param $log $injector-supplied $log service * @param $timeout $injector-supplied $timeout service * @param fieldHelper */ export class TypeAheadFieldDirective implements ng.IDirective { require:string = '^formFor'; restrict:string = 'EA'; templateUrl:string = ($element, $attributes) => { return $attributes['template'] || 'form-for/templates/type-ahead-field.html'; }; scope:any = { attribute: '@', debounce: '@?', disable: '=', filterDebounce: '@?', filterTextChanged: '&?', help: '@?', options: '=' }; /* @ngInject */ constructor($document:ng.IAugmentedJQuery, $log:ng.ILogService, $timeout:ng.ITimeoutService, fieldHelper:FieldHelper) { $document_ = $document; $log_ = $log; $timeout_ = $timeout; fieldHelper_ = fieldHelper; } /* @ngInject */ link($scope:TypeAheadFieldScope, $element:ng.IAugmentedJQuery, $attributes:ng.IAttributes, formForController:FormForController):void { if (!$scope.attribute) { $log_.error('Missing required field "attribute"'); return; } // Read from $attributes to avoid getting any interference from $scope. $scope.labelAttribute = $attributes['labelAttribute'] || 'label'; $scope.valueAttribute = $attributes['valueAttribute'] || 'value'; $scope.placeholder = $attributes.hasOwnProperty('placeholder') ? $attributes['placeholder'] : 'Select'; $scope.tabIndex = $attributes['tabIndex'] || 0; $scope.scopeBuster = { filter: '' }; fieldHelper_.manageLabel($scope, $attributes, false); fieldHelper_.manageFieldRegistration($scope, $attributes, formForController); /***************************************************************************************** * The following code pertains to opening and closing the filter. *****************************************************************************************/ var filterText:HTMLElement; // Helper method for setting focus on an item after a delay var setDelayedFilterTextFocus:Function = () => { if (!filterText) { // Null when link is first run because of ng-include var filterTextSelector:ng.IAugmentedJQuery = $element.find('input'); if (filterTextSelector.length) { filterText = filterTextSelector[0]; } } if (filterText) { $timeout_(filterText.focus.bind(filterText)); } }; $scope.close = () => { $timeout_(() => { $scope.isOpen = false; }); }; $scope.open = () => { if ($scope.disable || $scope.model.disabled) { return; } $timeout_(() => { $scope.isOpen = true; }); }; /***************************************************************************************** * The following code pertains to filtering visible options. *****************************************************************************************/ $scope.filteredOptions = []; // Sanitizes option and filter-text values for comparison var sanitize:(value:string) => string = (value) => { return typeof value === "string" ? value.toLowerCase() : ''; }; // Updates visible <option>s based on current filter text var calculateFilteredOptions = () => { var options:Array<any> = $scope.options || []; $scope.filteredOptions.splice(0); if (!$scope.scopeBuster.filter) { angular.copy(options, $scope.filteredOptions); } else { var filter:string = sanitize($scope.scopeBuster.filter); angular.forEach(options, (option) => { var index:number = sanitize(option[$scope.labelAttribute]).indexOf(filter); if (index >= 0) { $scope.filteredOptions.push(option); } }); } }; $scope.searchTextChange = (text:string) => { // No-op required by Angular Material }; $scope.$watch('scopeBuster.filter', calculateFilteredOptions); $scope.$watch('options.length', calculateFilteredOptions); /***************************************************************************************** * The following code deals with toggling/collapsing the drop-down and selecting values. *****************************************************************************************/ var documentClick = (event) => { // See filterTextClick() for why we check this property. if (event.ignoreFor === $scope.model.uid) { return; } $scope.close(); }; $scope.filterTextClick = (event) => { // We can't stop the event from propagating or we might prevent other inputs from closing on blur. // But we can't let it proceed as normal or it may result in the $document click handler closing a newly-opened input. // Instead we tag it for this particular instance of <select-field> to ignore. if ($scope.isOpen) { event.ignoreFor = $scope.model.uid; } }; var pendingTimeoutId:ng.IPromise<any>; $scope.$watch('isOpen', () => { if (pendingTimeoutId) { $timeout_.cancel(pendingTimeoutId); } pendingTimeoutId = $timeout_(() => { pendingTimeoutId = null; if ($scope.isOpen) { $document_.on('click', documentClick); } else { $document_.off('click', documentClick); } }, MIN_TIMEOUT_INTERVAL); }); $scope.$on('$destroy', () => { $document_.off('click', documentClick); }); /***************************************************************************************** * The following code responds to keyboard events when the drop-down is visible *****************************************************************************************/ $scope.setFilterFocus = () => { setDelayedFilterTextFocus(); }; $scope.mouseOver = (index:number) => { $scope.mouseOverIndex = index; $scope.mouseOverOption = index >= 0 ? $scope.filteredOptions[index] : null; }; $scope.selectOption = (option:any) => { $scope.model.bindable = option && option[$scope.valueAttribute]; $scope.scopeBuster.filter = option && option[$scope.labelAttribute]; }; var syncFilterText = function() { if ($scope.model.bindable && $scope.options) { $scope.options.forEach((option:any) => { if ($scope.model.bindable === option[$scope.valueAttribute]) { $scope.scopeBuster.filter = option[$scope.labelAttribute]; } }); } }; $scope.$watch('model.bindable', syncFilterText); $scope.$watch('options.length', syncFilterText); // Listen to key down, not up, because ENTER key sometimes gets converted into a click event. $scope.keyDown = (event:KeyboardEvent) => { switch (event.keyCode) { case 27: // Escape key $scope.close(); break; case 13: // Enter key if ($scope.isOpen) { $scope.selectOption($scope.mouseOverOption); $scope.close(); } else { $scope.open(); } event.preventDefault(); break; case 38: // Up arrow if ($scope.isOpen) { $scope.mouseOver( $scope.mouseOverIndex > 0 ? $scope.mouseOverIndex - 1 : $scope.filteredOptions.length - 1 ); } else { $scope.open(); } break; case 40: // Down arrow if ($scope.isOpen) { $scope.mouseOver( $scope.mouseOverIndex < $scope.filteredOptions.length - 1 ? $scope.mouseOverIndex + 1 : 0 ); } else { $scope.open(); } break; case 9: // Tabbing (in or out) should close the menu. case 16: $scope.close(); break; default: // But all other key events should (they potentially indicate a changed type-ahead filter value). $scope.open(); break; } }; $scope.$watchCollection('[isOpen, filteredOptions.length]', () => { // Reset hover anytime our list opens/closes or our collection is refreshed. $scope.mouseOver(-1); // Pass focus through to filter field when the type-ahead is opened if ($scope.isOpen) { setDelayedFilterTextFocus(); } }); if ($scope.filterTextChanged instanceof Function) { $scope.$watch('scopeBuster.filter', (text) => { $scope.filterTextChanged({text: text}); }); } } } angular.module('formFor').directive('typeAheadField', ($document, $log, $timeout, FieldHelper) => { return new TypeAheadFieldDirective($document, $log, $timeout, FieldHelper); }); }
the_stack
import React, { useRef, useEffect, forwardRef, useCallback } from 'react'; import { Tree } from './Tree'; import { melodies } from '../melodies'; import { toNote } from './utils/midiHelpers'; import debounce from 'lodash.debounce'; import * as Tone from 'tone'; import throttle from 'lodash.debounce'; import { persistKeys, dbSelectionEvent, dbKeyPress } from '../firebase/persistKeys'; import { ShareAndAbout } from './ShareAndAbout'; import { ProductHuntBadge } from './ProductHuntBadge'; import styled from '@emotion/styled'; const allNotes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']; const scale = ['C', 'D', 'E', 'F', 'G', 'A', 'B']; const silentKeys: Record<string, boolean> = { Shift: false, Escape: false, Enter: false, Meta: false, Control: false, Alt: false, Tab: false, ' ': false, ArrowUp: false, ArrowDown: false, ArrowLeft: false, ArrowRight: false, }; /** Don't persist these keys, we don't use them: */ const ignoreKeysForPersist = new Set([ 'Shift', 'ArrowLeft', 'ArrowUp', 'ArrowRight', 'ArrowDown', 'Meta', 'Escape', 'Control', 'Alt', 'Tab', 'CapsLock', 'Home', 'End', ]); type chord = string[]; const chords: Record<string, chord> = { Am: ['A2', 'E3', 'C3'], Am7: ['A2', 'E3', 'C4', 'G4'], Amaj9: ['A2', 'E3', 'B3'], C: ['C2', 'E3', 'G3'], Cmaj7: ['C3', 'E3', 'G4', 'B4'], Cmaj9: ['C2', 'E3', 'B3', 'D4'], Cmaj7NoRoot: ['E3', 'G4', 'B4'], }; const chordKeys: Record<string, Array<chord>> = { '.': [chords.C, chords.Am, chords.Cmaj7], '!': [chords.Cmaj9, chords.Am7], '?': [chords.Cmaj7NoRoot], }; const JournalTextArea = styled.textarea({ position: 'relative', zIndex: 3, boxSizing: 'border-box', height: 'calc(100vh - 180px)', width: '100%', maxWidth: '700px', fontSize: '33px', border: 0, resize: 'none', outline: 'none', color: '#333', paddingTop: '60px', paddingBottom: '60px', paddingLeft: '20px', paddingRight: '20px', backgroundColor: 'rgba(255, 255, 255, 0.5)', '@media (min-width: 768px)': { height: 'calc(100vh - 110px)', paddingTop: '60px', paddingBottom: '60px', paddingLeft: '60px', paddingRight: '30px', }, }); type Props = { readonly?: boolean; sampler: Tone.Sampler; }; const JournalScreen = ({ readonly = false, sampler }: Props) => { const noteIndex = useRef(0); const treeIndex = useRef(0); const treeCoverOpacityChange = useRef('0'); const lastNotePlayed = useRef('C3'); const unsavedPersists = useRef<Array<dbKeyPress | dbSelectionEvent>>([]); const lastSelectionWasAtLength = useRef(true); const firstKeyPressTime = useRef(0); const currentSentiment = useRef(0.5); /** Throttled save to the DB to persist any unpersisted key presses */ const persist = useCallback( debounce( () => { const urlPieces = window.location.pathname.split('/'); const entryId = urlPieces[2]; if (entryId) { persistKeys(entryId, unsavedPersists.current); unsavedPersists.current = []; } }, 1000, { leading: true, trailing: true } ), [] ); const readSentiment = useCallback( throttle( (sample: string) => // Score the text fetch('/api/sentiment', { method: 'post', body: JSON.stringify({ sample }), }).then((res) => { if (res.status === 200) { try { res.json().then((result) => { // Assign the new sentiment score as a 0-1 scale currentSentiment.current = Number.isFinite(result.sentiment) ? Math.min(Math.max((result.sentiment + 1) / 2, 0), 1) : 0.5; console.log('new sentiment ' + currentSentiment.current); }); } catch (e) { console.log(e); } } }), 1000, { leading: true, trailing: true } ), [] ); return ( <> <JournalTextArea spellCheck="false" autoFocus={true} readOnly={readonly} disabled={readonly} onSelect={(e) => { if (!readonly) { const textarea = e.currentTarget; const selectionStart = textarea.selectionStart; const selectionEnd = textarea.selectionEnd; if (selectionStart === selectionEnd && selectionStart === textarea.textLength) { // Bail if the selection is at the end, and the previous selection was at the end // We don't need this info as it will happen automatically and we can save some space if (lastSelectionWasAtLength.current === true) { return; } lastSelectionWasAtLength.current = true; } else { lastSelectionWasAtLength.current = false; } // Add this key press to the list to be persisted at the next save event unsavedPersists.current.push({ type: 'selection', selectionStart, selectionEnd, timeFromBegin: Date.now() - firstKeyPressTime.current, }); persist(); } }} placeholder="How are you feeling? &#10;Start typing" onChange={(e) => { if (!readonly) { persist(); } const newValue = e.currentTarget.value; const lastCharacter = newValue[newValue.length - 1]; if (lastCharacter === ' ' || lastCharacter === '.' || lastCharacter === '!' || lastCharacter === '?') { const totalEntry = e.currentTarget.value; // Move the sentiment with the most recent writing: const recentWriting = totalEntry.substring(totalEntry.length - 65); readSentiment(recentWriting); } }} onKeyDown={(e) => { if (firstKeyPressTime.current === 0) { firstKeyPressTime.current = Date.now(); } // Bail early for OS key combos if (e.metaKey || e.ctrlKey) { return; } const dbKey: dbKeyPress = { type: 'key', key: e.key, timeFromBegin: Date.now() - firstKeyPressTime.current, notes: [], }; if (ignoreKeysForPersist.has(e.key) === false) { // Add this key press to the list to be persisted at the next save event // The notes will get filled in before the persist happens unsavedPersists.current.push(dbKey); } // If it's a silent key, bail out: const shouldBeSilent = silentKeys[e.key]; if (shouldBeSilent === false) { return; } // If it's a chord key, play the chord: let chord = null; if (chordKeys[e.key]) { const chordToPlayIndex = Math.floor(Math.random() * chordKeys[e.key].length); chord = chordKeys[e.key][chordToPlayIndex]; // Play a chord for this key let delay = 0; let velocity = 0.25; const chordToUse = Math.random() > 0.7 ? chord.reverse() : chord; const duration = 4; for (const note of chordToUse) { setTimeout(() => { sampler.triggerAttackRelease([note], duration, undefined, velocity); }, delay); // Add it to the DB copy: dbKey.notes.push({ note: note, duration, velocity, delayFromKeyPress: delay }); // Play the chord slower and lighter as it goes: if (delay === 0) { delay = 65; } else { delay *= 2; } velocity = velocity - 0.175 * velocity; } return; } // If it's backspace or delete, descend the scale if (e.key === 'Backspace' || e.key === 'Delete') { if (e.currentTarget.value.length === 0) { // Bail out if there's nothing to delete return; } const note = lastNotePlayed.current.replace(/[^a-z#+]/gi, ''); const octave = parseInt(lastNotePlayed.current.replace(/[^0-9+]/gi, '')); const noteIndex = allNotes.indexOf(note); if (noteIndex !== -1) { let descendingNote; let descendingNoteOctave; if (noteIndex === 0) { // Reached the root, lower the octave and grab the max child descendingNoteOctave = octave - 1; descendingNote = allNotes[allNotes.length - 1]; } else { descendingNoteOctave = octave; descendingNote = allNotes[noteIndex - 1]; } if (descendingNoteOctave === 0) { // If we reach 0, start up high again descendingNoteOctave = 5; } const noteWithOctave = `${descendingNote}${descendingNoteOctave}`; const velocity = 0.15; const duration = 3; sampler.triggerAttackRelease([noteWithOctave], duration, undefined, velocity); // Add it to the DB copy: dbKey.notes.push({ note: noteWithOctave, duration, velocity, delayFromKeyPress: 0 }); lastNotePlayed.current = noteWithOctave; } return; } // Play the next note in the sequence // console.log('sentiment score: ' + currentSentiment.current); const melodyIndex = Math.round(melodies.length * currentSentiment.current); console.log({ melodyIndex }); const melody = melodies[melodyIndex] ?? melodies[0]; let nextKey; if (noteIndex.current > melody.notes.length - 1) { // If we're above this melody's last note, use the last note: nextKey = melody.notes[melody.notes.length - 1]; } else { // Otherwise, use the key at this index: nextKey = melody.notes[noteIndex.current]; } const nextNote = toNote(nextKey.pitch!); // Randomize velocity between 0.1 and 0.2, but mostly hit 0.2 const velocity = Math.max(Math.min(Math.random() / 2, 0.2), 0.1); const duration = 3; sampler.triggerAttackRelease([nextNote], duration, undefined, velocity); // Add it to the DB copy: dbKey.notes.push({ note: nextNote, duration, velocity, delayFromKeyPress: 0 }); // Remember the last note we played: lastNotePlayed.current = nextNote; // Hide a new svg cover every N keystrokes: const coverCount = Math.floor(treeIndex.current / 6); const treeBranch = document.querySelector('#cover-' + coverCount) as SVGElement; if (treeBranch) { treeBranch.style.transition = 'opacity 0.5s ease-in'; treeBranch.style.opacity = treeCoverOpacityChange.current; } // Hard coding magic numberz for JAM spririt... update this if we want multiple graphics later if (coverCount === 21) { // We've hit the end of the tree, start over treeIndex.current = 0; treeCoverOpacityChange.current = treeCoverOpacityChange.current === '1' ? '0' : '1'; } // +/- 1 to the tree index treeIndex.current += 1; // +1 to the note index noteIndex.current += 1; if (noteIndex.current === melodies[1].notes!.length) { // Restart the melody if we've run out of notes noteIndex.current = 0; } }} ></JournalTextArea> <Tree /> <ShareAndAbout readonly={readonly} /> {/* <ProductHuntBadge /> */} </> ); }; export default JournalScreen;
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "./types"; import * as utilities from "./utilities"; /** * Provides a [DigitalOcean Monitoring](https://docs.digitalocean.com/reference/api/api-reference/#tag/Monitoring) resource. * Monitor alerts can be configured to alert about, e.g., disk or memory usage exceeding certain threshold, or traffic at certain * limits. Notifications can be sent to either an email address or a Slack channel. * * ## Import * * Monitor alerts can be imported using the monitor alert `uuid`, e.g. * * ```sh * $ pulumi import digitalocean:index/monitorAlert:MonitorAlert cpu_alert b8ecd2ab-2267-4a5e-8692-cbf1d32583e3 * ``` */ export class MonitorAlert extends pulumi.CustomResource { /** * Get an existing MonitorAlert resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: MonitorAlertState, opts?: pulumi.CustomResourceOptions): MonitorAlert { return new MonitorAlert(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'digitalocean:index/monitorAlert:MonitorAlert'; /** * Returns true if the given object is an instance of MonitorAlert. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is MonitorAlert { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === MonitorAlert.__pulumiType; } /** * How to send notifications about the alerts. This is a list with one element, . * Note that for Slack, the DigitalOcean app needs to have permissions for your workspace. You can * read more in [Slack's documentation](https://slack.com/intl/en-dk/help/articles/222386767-Manage-app-installation-settings-for-your-workspace) */ public readonly alerts!: pulumi.Output<outputs.MonitorAlertAlerts>; /** * The comparison for `value`. * This may be either `GreaterThan` or `LessThan`. */ public readonly compare!: pulumi.Output<string>; /** * The description of the alert. */ public readonly description!: pulumi.Output<string>; /** * The status of the alert. */ public readonly enabled!: pulumi.Output<boolean | undefined>; /** * The resources to which the alert policy applies. */ public readonly entities!: pulumi.Output<string[] | undefined>; /** * Tags for the alert. */ public readonly tags!: pulumi.Output<string[] | undefined>; /** * The type of the alert. * This may be either `v1/insights/droplet/load_1`, `v1/insights/droplet/load_5`, `v1/insights/droplet/load_15`, * `v1/insights/droplet/memory_utilization_percent`, `v1/insights/droplet/disk_utilization_percent`, * `v1/insights/droplet/cpu`, `v1/insights/droplet/disk_read`, `v1/insights/droplet/disk_write`, * `v1/insights/droplet/public_outbound_bandwidth`, `v1/insights/droplet/public_inbound_bandwidth`, * `v1/insights/droplet/private_outbound_bandwidth`, `v1/insights/droplet/private_inbound_bandwidth`. */ public readonly type!: pulumi.Output<string>; /** * The uuid of the alert. */ public /*out*/ readonly uuid!: pulumi.Output<string>; /** * The value to start alerting at, e.g., 90% or 85Mbps. This is a floating-point number. * DigitalOcean will show the correct unit in the web panel. */ public readonly value!: pulumi.Output<number>; /** * The time frame of the alert. Either `5m`, `10m`, `30m`, or `1h`. */ public readonly window!: pulumi.Output<string>; /** * Create a MonitorAlert resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: MonitorAlertArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: MonitorAlertArgs | MonitorAlertState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as MonitorAlertState | undefined; inputs["alerts"] = state ? state.alerts : undefined; inputs["compare"] = state ? state.compare : undefined; inputs["description"] = state ? state.description : undefined; inputs["enabled"] = state ? state.enabled : undefined; inputs["entities"] = state ? state.entities : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["type"] = state ? state.type : undefined; inputs["uuid"] = state ? state.uuid : undefined; inputs["value"] = state ? state.value : undefined; inputs["window"] = state ? state.window : undefined; } else { const args = argsOrState as MonitorAlertArgs | undefined; if ((!args || args.alerts === undefined) && !opts.urn) { throw new Error("Missing required property 'alerts'"); } if ((!args || args.compare === undefined) && !opts.urn) { throw new Error("Missing required property 'compare'"); } if ((!args || args.description === undefined) && !opts.urn) { throw new Error("Missing required property 'description'"); } if ((!args || args.type === undefined) && !opts.urn) { throw new Error("Missing required property 'type'"); } if ((!args || args.value === undefined) && !opts.urn) { throw new Error("Missing required property 'value'"); } if ((!args || args.window === undefined) && !opts.urn) { throw new Error("Missing required property 'window'"); } inputs["alerts"] = args ? args.alerts : undefined; inputs["compare"] = args ? args.compare : undefined; inputs["description"] = args ? args.description : undefined; inputs["enabled"] = args ? args.enabled : undefined; inputs["entities"] = args ? args.entities : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["type"] = args ? args.type : undefined; inputs["value"] = args ? args.value : undefined; inputs["window"] = args ? args.window : undefined; inputs["uuid"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(MonitorAlert.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering MonitorAlert resources. */ export interface MonitorAlertState { /** * How to send notifications about the alerts. This is a list with one element, . * Note that for Slack, the DigitalOcean app needs to have permissions for your workspace. You can * read more in [Slack's documentation](https://slack.com/intl/en-dk/help/articles/222386767-Manage-app-installation-settings-for-your-workspace) */ alerts?: pulumi.Input<inputs.MonitorAlertAlerts>; /** * The comparison for `value`. * This may be either `GreaterThan` or `LessThan`. */ compare?: pulumi.Input<string>; /** * The description of the alert. */ description?: pulumi.Input<string>; /** * The status of the alert. */ enabled?: pulumi.Input<boolean>; /** * The resources to which the alert policy applies. */ entities?: pulumi.Input<pulumi.Input<string>[]>; /** * Tags for the alert. */ tags?: pulumi.Input<pulumi.Input<string>[]>; /** * The type of the alert. * This may be either `v1/insights/droplet/load_1`, `v1/insights/droplet/load_5`, `v1/insights/droplet/load_15`, * `v1/insights/droplet/memory_utilization_percent`, `v1/insights/droplet/disk_utilization_percent`, * `v1/insights/droplet/cpu`, `v1/insights/droplet/disk_read`, `v1/insights/droplet/disk_write`, * `v1/insights/droplet/public_outbound_bandwidth`, `v1/insights/droplet/public_inbound_bandwidth`, * `v1/insights/droplet/private_outbound_bandwidth`, `v1/insights/droplet/private_inbound_bandwidth`. */ type?: pulumi.Input<string>; /** * The uuid of the alert. */ uuid?: pulumi.Input<string>; /** * The value to start alerting at, e.g., 90% or 85Mbps. This is a floating-point number. * DigitalOcean will show the correct unit in the web panel. */ value?: pulumi.Input<number>; /** * The time frame of the alert. Either `5m`, `10m`, `30m`, or `1h`. */ window?: pulumi.Input<string>; } /** * The set of arguments for constructing a MonitorAlert resource. */ export interface MonitorAlertArgs { /** * How to send notifications about the alerts. This is a list with one element, . * Note that for Slack, the DigitalOcean app needs to have permissions for your workspace. You can * read more in [Slack's documentation](https://slack.com/intl/en-dk/help/articles/222386767-Manage-app-installation-settings-for-your-workspace) */ alerts: pulumi.Input<inputs.MonitorAlertAlerts>; /** * The comparison for `value`. * This may be either `GreaterThan` or `LessThan`. */ compare: pulumi.Input<string>; /** * The description of the alert. */ description: pulumi.Input<string>; /** * The status of the alert. */ enabled?: pulumi.Input<boolean>; /** * The resources to which the alert policy applies. */ entities?: pulumi.Input<pulumi.Input<string>[]>; /** * Tags for the alert. */ tags?: pulumi.Input<pulumi.Input<string>[]>; /** * The type of the alert. * This may be either `v1/insights/droplet/load_1`, `v1/insights/droplet/load_5`, `v1/insights/droplet/load_15`, * `v1/insights/droplet/memory_utilization_percent`, `v1/insights/droplet/disk_utilization_percent`, * `v1/insights/droplet/cpu`, `v1/insights/droplet/disk_read`, `v1/insights/droplet/disk_write`, * `v1/insights/droplet/public_outbound_bandwidth`, `v1/insights/droplet/public_inbound_bandwidth`, * `v1/insights/droplet/private_outbound_bandwidth`, `v1/insights/droplet/private_inbound_bandwidth`. */ type: pulumi.Input<string>; /** * The value to start alerting at, e.g., 90% or 85Mbps. This is a floating-point number. * DigitalOcean will show the correct unit in the web panel. */ value: pulumi.Input<number>; /** * The time frame of the alert. Either `5m`, `10m`, `30m`, or `1h`. */ window: pulumi.Input<string>; }
the_stack
import { chainAsync, uuid, objectsEqual } from "./utilities"; import { InanoSQLAdapter, InanoSQLAdapterConstructor, InanoSQLInstance, InanoSQLTable } from "./interfaces"; import { nanoSQL } from "."; export const myConsole = Object.create(console, { assert: { value: function assert(assertion, message, ...args) { if (typeof window === "undefined") { try { console.assert(assertion, message, ...args); } catch (err) { console.error(err.stack); } } else { console.assert(assertion, message, ...args); } }, configurable: true, enumerable: true, writable: true, }, }); export class nanoSQLAdapterTest { constructor( public adapter: InanoSQLAdapterConstructor, public args: any[] ) { } public test() { return this.PrimaryKeys().then(() => { console.log("✓ Primary Key Tests Passed"); return this.Writes(); }).then(() => { console.log("✓ Write Tests Passed"); return this.RangeReads(); }).then(() => { console.log("✓ Range Read Tests Passed (number)"); return this.RangeReadsUUID(); }).then(() => { console.log("✓ Range Read Tests Passed (uuid)"); return this.Deletes(); }).then(() => { console.log("✓ Delete Tests Passed"); return this.SecondayIndexes(); }).then(() => { console.log("✓ Secondary Index Passed"); console.log("✓ All Tests Passed!******"); }) } public static newTable(adapter: InanoSQLAdapter, nSQL: InanoSQLInstance, tableName: string, tableConfig: InanoSQLTable, complete: () => void, error: () => void) { adapter.nSQL = nSQL; adapter.createTable(tableName, tableConfig, () => { if (!nSQL.dbs["123"]) { nSQL.dbs["123"] = { adapter: adapter, _tables: {}, _tableIds: {}, } as any; } nSQL.getDB("123")._tables[tableName] = tableConfig; complete(); }, error); } public Deletes() { const adapter: InanoSQLAdapter = new this.adapter(...this.args); const nSQL: InanoSQLInstance = new nanoSQL(); let allRows: any[] = []; return new Promise((res, rej) => { adapter.nSQL = nSQL; adapter.connect("123", () => { nanoSQLAdapterTest.newTable(adapter, nSQL, "test", { id: uuid(), name: "test", count: 0, rowLocks: {}, model: { "id:int": {ai: true, pk: true}, "name:string": {} }, columns: [ { key: "id", type: "int", immutable: false }, { key: "name", type: "string", immutable: false } ], indexes: {}, actions: [], queries: {}, views: [], pkType: "int", pkCol: ["id"], isPkNum: true, ai: true }, res, rej); }, rej); }).then(() => { return new Promise((res, rej) => { let titles: any[] = []; for (let i = 0; i < 500; i++) { allRows.push({id: i + 1, name: "Title " + (i + 1)}); titles.push("Title " + (i + 1)); } chainAsync(titles, (title, i, done) => { adapter.write("test", null, {name: title}, done, rej); }).then(res); }); }).then(() => { return new Promise((res, rej) => { // single rows can be deleted. adapter.delete("test", 3 as any, () => { let rows: any[] = []; adapter.readMulti("test", "all", undefined, undefined, false, (row, idx) => { rows.push(row); }, () => { const condition = objectsEqual(rows, allRows.filter(r => r.id !== 3)); myConsole.assert(condition, "Delete Test"); condition ? res() : rej({e: allRows.filter(r => r.id !== 3), g: rows }); }, rej); }, rej); }); }).then(() => { return new Promise((res, rej) => { adapter.dropTable("test", () => { adapter.disconnect(res, rej); }, rej); }); }); } public SecondayIndexes() { const adapter: InanoSQLAdapter = new this.adapter(...this.args); const nSQL: InanoSQLInstance = new nanoSQL(); let allRows: any[] = []; return new Promise((res, rej) => { adapter.nSQL = nSQL; adapter.connect("123", () => { nanoSQLAdapterTest.newTable(adapter, nSQL, "test", { id: uuid(), name: "test", count: 0, rowLocks: {}, model: { "id:int": {ai: true, pk: true}, "name:string": {} }, columns: [ { key: "id", type: "int", immutable: false }, { key: "name", type: "string", immutable: false } ], indexes: { "name": { id: "name", isArray: false, type: "string", path: ["name"], props: {}, isDate: false } }, actions: [], queries: {}, views: [], pkType: "int", pkCol: ["id"], isPkNum: true, ai: true }, res, rej); }, rej); }).then(() => { return new Promise((res, rej) => { let titles: any[] = []; for (let i = 0; i < 500; i++) { let num: any = (i + 1); if (num <= 9) { num = "00" + num; } else if (num <= 99) { num = "0" + num; } allRows.push({id: i + 1, name: "Title " + num}); } adapter.createIndex("test", "name", "string", () => { chainAsync(allRows, (row, i, done) => { adapter.write("test", null, row, () => { adapter.addIndexValue("test", "name", row.id, row.name, done, rej); }, rej); }).then(res); }, rej); }); }).then(() => { return new Promise((res, rej) => { // read secondary index let pks: any[] = []; adapter.readIndexKey("test", "name", "Title 005", (pk) => { pks.push(pk); }, () => { const condition = objectsEqual(pks, [5]); myConsole.assert(condition, "Secondary Index Single Read"); condition ? res() : rej({e: [5], g: pks}); }, rej); }); }).then(() => { return new Promise((res, rej) => { // read range secondary index let pks: any[] = []; adapter.readIndexKeys("test", "name", "range", "Title 004", "Title 020", false, (pk, value) => { pks.push(pk); }, () => { const filterRows = allRows.filter(r => r.name >= "Title 004" && r.name <= "Title 020").map(r => r.id); const condition = objectsEqual(pks, filterRows); myConsole.assert(condition, "Secondary Index Range Read"); condition ? res() : rej({e: filterRows, g: pks}); }, rej); }); }).then(() => { return new Promise((res, rej) => { // read offset secondary index let pks: any[] = []; adapter.readIndexKeys("test", "name", "offset", 10, 20, false, (pk) => { pks.push(pk); }, () => { const filterRows = allRows.filter((r, i) => i >= 10 && i < 30).map(r => r.id); const condition = objectsEqual(pks, filterRows); myConsole.assert(condition, "Secondary Index Offset Read"); condition ? res() : rej({e: filterRows, g: pks}); }, rej); }); }).then(() => { return new Promise((res, rej) => { // read range secondary index let pks: any[] = []; adapter.readIndexKeys("test", "name", "range", "Title 010", "~", true, (pk, value) => { pks.push(pk); }, () => { const filterRows = allRows.filter(r => r.name >= "Title 010").map(r => r.id).reverse(); const condition = objectsEqual(pks, filterRows); myConsole.assert(condition, "Secondary Index Range Read Reverse"); condition ? res() : rej({e: filterRows, g: pks}); }, rej); }); }).then(() => { return new Promise((res, rej) => { // read offset secondary index let pks: any[] = []; adapter.readIndexKeys("test", "name", "offset", 10, 20, true, (pk) => { pks.push(pk); }, () => { const filterRows = allRows.filter((r, i) => i >= 469 && i < 489).map(r => r.id).reverse(); const condition = objectsEqual(pks, filterRows); myConsole.assert(condition, "Secondary Index Offset Read Reverse"); condition ? res() : rej({e: filterRows, g: pks}); }, rej); }); }).then(() => { return new Promise((res, rej) => { // read offset secondary index let pks: any[] = []; adapter.deleteIndexValue("test", "name", 10, "Title 010", () => { adapter.readIndexKeys("test", "name", "all", undefined, undefined, false, (pk) => { pks.push(pk); }, () => { const filterRows = allRows.filter(r => r.id !== 10).map(r => r.id); const condition = objectsEqual(pks, filterRows); myConsole.assert(condition, "Secondary Index Remove Value"); condition ? res() : rej({e: filterRows, g: pks}); }, rej); }, rej); }); }); } public RangeReads() { const adapter: InanoSQLAdapter = new this.adapter(...this.args); const nSQL: InanoSQLInstance = new nanoSQL(); let allRows: any[] = []; let index: any[] = []; return new Promise((res, rej) => { adapter.nSQL = nSQL; adapter.connect("123", () => { nanoSQLAdapterTest.newTable(adapter, nSQL, "test", { id: uuid(), name: "test", count: 0, rowLocks: {}, model: { "id:int": {ai: true, pk: true}, "name:string": {} }, columns: [ { key: "id", type: "int", immutable: false }, { key: "name", type: "string", immutable: false } ], indexes: {}, actions: [], views: [], queries: {}, pkType: "int", pkCol: ["id"], isPkNum: true, ai: true }, res, rej); }, rej); }).then(() => { return new Promise((res, rej) => { let titles: any[] = []; for (let i = 0; i < 500; i++) { allRows.push({id: i + 1, name: "Title " + (i + 1)}); titles.push("Title " + (i + 1)); index.push(i + 1); } chainAsync(titles, (title, i, done) => { adapter.write("test", null, {name: title}, done, rej); }).then(res); }); }).then(() => { // Select entire table return new Promise((res, rej) => { let rows: any[] = []; adapter.readMulti("test", "all", undefined, undefined, false, (row, idx) => { rows.push(row); }, () => { const condition = objectsEqual(rows, allRows); myConsole.assert(condition, "Select Entire Table"); condition ? res() : rej({e: allRows, g: rows}); }, rej); }); }).then(() => { // Select a range of rows using a range of the index with reverse return new Promise((res, rej) => { let rows: any[] = []; adapter.readMulti("test", "all", undefined, undefined, true, (row, idx) => { rows.push(row); }, () => { const filterRows = allRows.slice().reverse(); const condition = objectsEqual(rows, filterRows); myConsole.assert(condition, "Select All Rows Test (reverse)"); condition ? res() : rej({e: filterRows, g: rows}); }, rej); }); }).then(() => { // Select a range of rows using a range of the index with reverse return new Promise((res, rej) => { let rows: any[] = []; adapter.readMulti("test", "range", 10, 20, true, (row, idx) => { rows.push(row); }, () => { const filterRows = allRows.filter(r => r.id >= 10 && r.id <= 20).reverse(); const condition = objectsEqual(rows, filterRows); myConsole.assert(condition, "Select Range Test (Reverse)"); condition ? res() : rej({e: filterRows, g: rows}); }, rej); }); }).then(() => { // Select a range of rows using a range of the index with reverse return new Promise((res, rej) => { let rows: any[] = []; adapter.readMulti("test", "offset", 10, 20, true, (row, idx) => { rows.push(row); }, () => { const filterRows = allRows.filter((r, i) => i >= 499 - 30 && i < 499 - 10).reverse(); const condition = objectsEqual(rows, filterRows); myConsole.assert(condition, "Select Offset Test (Reverse)"); condition ? res() : rej({e: filterRows, g: rows}); }, rej); }); }).then(() => { // Select a range of rows using a range of the index return new Promise((res, rej) => { let rows: any[] = []; adapter.readMulti("test", "range", 10, 20, false, (row, idx) => { rows.push(row); }, () => { const filterRows = allRows.filter(r => r.id >= 10 && r.id <= 20); const condition = objectsEqual(rows, filterRows); myConsole.assert(condition, "Select Range Test 2"); condition ? res() : rej({e: filterRows, g: rows}); }, rej); }); }).then(() => { // Select a range of rows given a lower and upper limit primary key return new Promise((res, rej) => { let rows: any[] = []; adapter.readMulti("test", "offset", 10, 20, false, (row, idx) => { rows.push(row); }, () => { const condition = objectsEqual(rows, allRows.filter(r => r.id > 10 && r.id <= 30)); myConsole.assert(condition, "Select Offset / Limit Test"); condition ? res() : rej({g: rows, e: allRows.filter(r => r.id > 10 && r.id <= 30)}); }, rej); }); }).then(() => { // Select index return new Promise((res, rej) => { adapter.getTableIndex("test", (idx) => { const condition = objectsEqual(idx, index); myConsole.assert(condition, "Select Index Test"); condition ? res() : rej({ e: index, g: idx }); }, rej); }); }).then(() => { // Select index length return new Promise((res, rej) => { adapter.getTableIndexLength("test", (idx) => { const condition = idx === 500; myConsole.assert(condition, "Select Index Length Test"); condition ? res() : rej({e: 500, g: idx}); }, rej); }); }).then(() => { return new Promise((res, rej) => { adapter.dropTable("test", () => { adapter.disconnect(res, rej); }, rej); }); }); } public RangeReadsUUID() { const adapter: InanoSQLAdapter = new this.adapter(...this.args); const nSQL: InanoSQLInstance = new nanoSQL(); let allRows: any[] = []; let index: any[] = []; return new Promise((res, rej) => { adapter.nSQL = nSQL; adapter.connect("123", () => { nanoSQLAdapterTest.newTable(adapter, nSQL, "test", { id: uuid(), name: "test", count: 0, rowLocks: {}, model: { "id:uuid": {pk: true}, "name:string": {} }, columns: [ { key: "id", type: "uuid", immutable: false }, { key: "name", type: "string", immutable: false } ], indexes: {}, actions: [], views: [], queries: {}, pkType: "uuid", pkCol: ["id"], isPkNum: false, ai: false }, res, rej); }, rej); }).then(() => { return new Promise((res, rej) => { let titles: any[] = []; for (let i = 0; i < 500; i++) { const id = uuid(); allRows.push({id: id, name: "Title " + i}); titles.push("Title " + i); index.push(id); } index.sort((a, b) => a > b ? 1 : -1); allRows.sort((a, b) => a.id > b.id ? 1 : -1); chainAsync(allRows, (row, i, done) => { adapter.write("test", row.id, row, done, rej); }).then(res); }); }).then(() => { // Select a range of rows using a range of the index return new Promise((res, rej) => { let rows: any[] = []; adapter.readMulti("test", "offset", 10, 20, false, (row, idx) => { rows.push(row); }, () => { const condition = objectsEqual(rows, allRows.filter((r, i) => i >= 10 && i < 30)); myConsole.assert(condition, "Select Range Test 2"); condition ? res() : rej({g: rows, e: allRows.filter((r, i) => i >= 10 && i < 30)}); }, rej); }); }).then(() => { // Select a range of rows given a lower and upper limit primary key return new Promise((res, rej) => { let rows: any[] = []; adapter.readMulti("test", "range", allRows[10].id, allRows[20].id, false, (row, idx) => { rows.push(row); }, () => { const condition = objectsEqual(rows, allRows.filter(r => r.id >= allRows[10].id && r.id <= allRows[20].id)); myConsole.assert(condition, "Select Range Test (Primary Key)"); condition ? res() : rej({ g: rows, e: allRows.filter(r => r.id >= allRows[10].id && r.id <= allRows[20].id) }); }, rej); }); }).then(() => { // Select entire table return new Promise((res, rej) => { let rows: any[] = []; // console.time("READ"); adapter.readMulti("test", "all", undefined, undefined, false, (row, idx) => { rows.push(row); }, () => { // console.timeEnd("READ"); const condition = objectsEqual(rows, allRows); myConsole.assert(condition, "Select Entire Table Test"); condition ? res() : rej({e: allRows, g: rows}); }, rej); }); }).then(() => { // Select index return new Promise((res, rej) => { adapter.getTableIndex("test", (idx) => { const condition = objectsEqual(idx, index); myConsole.assert(condition, "Select Index Test"); condition ? res() : rej({ e: index, g: idx }); }, rej); }); }).then(() => { // Select index length return new Promise((res, rej) => { adapter.getTableIndexLength("test", (len) => { const condition = len === 500; myConsole.assert(condition, "Select Index Length Test"); condition ? res() : rej({e: 500, g: len}); }, rej); }); }).then(() => { return new Promise((res, rej) => { adapter.dropTable("test", () => { adapter.disconnect(res, rej); }, rej); }); }); } public Writes() { const adapter: InanoSQLAdapter = new this.adapter(...this.args); const nSQL: InanoSQLInstance = new nanoSQL(); return new Promise((res, rej) => { adapter.nSQL = nSQL; adapter.connect("123", () => { nanoSQLAdapterTest.newTable(adapter, nSQL, "test", { id: uuid(), name: "test", count: 0, rowLocks: {}, model: { "id:int": {pk: true, ai: true}, "name:string": {}, "posts:string[]": {} }, columns: [ { key: "id", type: "int", immutable: false }, { key: "name", type: "string", immutable: false }, { key: "posts", type: "string[]", immutable: false } ], indexes: {}, actions: [], views: [], queries: {}, pkType: "int", pkCol: ["id"], isPkNum: true, ai: true }, res, rej); }, rej); }).then(() => { // make sure new rows are added correctly return new Promise((res, rej) => { adapter.write("test", null, { name: "Test", count: 0, rowLocks: {}, posts: [1, 2] }, (pk) => { adapter.read("test", pk, (row) => { const expectRow = {name: "Test", count: 0, rowLocks: {}, id: 1, posts: [1, 2]}; const condition = objectsEqual(row, expectRow); myConsole.assert(condition, "Insert Test"); condition ? res() : rej({e: expectRow, g: row}); }, rej); }, rej); }); }).then(() => { // Make sure existing rows are updated correctly return new Promise((res, rej) => { adapter.write("test", 1, {id: 1, name: "Testing", posts: [1, 2]}, (pk) => { adapter.read("test", pk, (row) => { const expectRow = {name: "Testing", id: 1, posts: [1, 2]}; const condition = objectsEqual(row, expectRow); myConsole.assert(condition, "Update Test"); condition ? res() : rej({e: expectRow, g: row}); }, rej); }, rej); }); }).then(() => { // Make sure existing rows are replaced correctly return new Promise((res, rej) => { adapter.write("test", 1, {id: 1, name: "Testing"}, (pk) => { adapter.read("test", pk, (row) => { const expectRow = {name: "Testing", id: 1}; const condition = objectsEqual(row, expectRow); myConsole.assert(condition, "Replace Test"); condition ? res() : rej({e: expectRow, g: row}); }, rej); }, rej); }); }).then(() => { return new Promise((res, rej) => { adapter.dropTable("test", () => { adapter.disconnect(res, rej); }, rej); }); }); } public PrimaryKeys() { const adapter: InanoSQLAdapter = new this.adapter(...this.args); const nSQL: InanoSQLInstance = new nanoSQL(); return new Promise((res, rej) => { adapter.nSQL = nSQL; adapter.connect("123", () => { Promise.all([ "test", "test2", "test3", "test4", "test5", "test6", "test7", "test8" ].map(t => { return new Promise((res2, rej2) => { nanoSQLAdapterTest.newTable(adapter, nSQL, t, { id: uuid(), name: "test", count: 0, rowLocks: {}, model: { "test": { "id:int": {pk: true, ai: true}, "name:string": {} }, "test2": { "id:uuid": {pk: true}, "name:string": {} }, "test3": { "id:timeId": {pk: true}, "name:string": {} }, "test4": { "id:timeIdms": {pk: true}, "name:string": {} }, "test5": { "id:uuid": {pk: true}, "name:string": {} }, "test6": { "id:float": {pk: true}, "name:string": {} }, "test7": { "nested:obj": { model: {"id:int": {pk: true}} }, "name:string": {} }, "test8": { "id:string": {pk: true}, "name:string": {} }, }[t], columns: [ { "test": { key: "id", type: "int" }, "test2": { key: "id", type: "uuid" }, "test3": { key: "id", type: "timeId" }, "test4": { key: "id", type: "timeIdms" }, "test5": { key: "id", type: "uuid" }, "test6": { key: "id", type: "float" }, "test7": { key: "nested", model: [ {key: "id", type: "int"} ] }, "test8": { key: "id", type: "string" } }[t], { key: "name", type: "string" } ], indexes: {}, actions: [], queries: {}, views: [], pkType: { test: "int", test2: "uuid", test3: "timeId", test4: "timeIdms", test5: "uuid", test6: "float", test7: "int", test8: "string" }[t], pkCol: t === "test7" ? ["nested", "id"] : ["id"], isPkNum: { test: true, test2: false, test3: false, test4: false, test5: false, test6: true, test7: true, test8: false }[t], ai: { test: true, test2: false, test3: false, test4: false, test5: false, test6: false, test7: false, test8: false }[t] }, res2, rej2); }); })).then(res).catch(rej); }, rej); }).then(() => { // Auto incriment test return new Promise((res, rej) => { adapter.write("test", null, {name: "Test"}, (pk) => { const condition = objectsEqual(pk, 1); myConsole.assert(condition, "Test Auto Incriment Integer."); condition ? (() => { adapter.read("test", 1, (row: any) => { const condition2 = objectsEqual(row.id, 1); myConsole.assert(condition2, "Select Integer Primary Key."); condition2 ? res() : rej({e: 1, g: row.id}); }, rej); })() : rej(pk); }, rej); }); }).then(() => { // UUID test return new Promise((res, rej) => { adapter.write("test2", null, { name: "Test" }, (pk) => { const condition = pk.match(/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/); myConsole.assert(condition, "Test UUID."); condition ? (() => { adapter.read("test2", pk, (row: any) => { const condition2 = objectsEqual(row.id, pk); myConsole.assert(condition2, "Select UUID Primary Key."); condition2 ? res() : rej({e: pk, g: row.id}); }, rej); })() : rej({e: "valid uuid", g: pk}); }, rej); }); }).then(() => { // TimeID Test return new Promise((res, rej) => { adapter.write("test3", null, { name: "Test" }, (pk) => { const condition = pk.match(/^\w{10}-\w{1,5}$/); myConsole.assert(condition, "Test timeId."); condition ? (() => { adapter.read("test3", pk, (row: any) => { const condition2 = objectsEqual(row.id, pk); myConsole.assert(condition2, "Select timeId Primary Key."); condition2 ? res() : rej({e: pk, g: row.id}); }, rej); })() : rej({e: "valid timeid", g: pk}); }, rej); }); }).then(() => { // TimeIDMS test return new Promise((res, rej) => { adapter.write("test4", null, { name: "Test" }, (pk) => { const condition = pk.match(/^\w{13}-\w{1,5}$/); myConsole.assert(condition, "Test timeIdms."); condition ? (() => { adapter.read("test4", pk, (row: any) => { const condition2 = objectsEqual(row.id, pk); myConsole.assert(condition2, "Select timeIdms Primary Key."); condition2 ? res() : rej({e: pk, g: row.id}); }, rej); })() : rej({e: "valid timeidms", g: pk}); }, rej); }); }).then(() => { // Ordered String Primary Key Test return new Promise((res, rej) => { let UUIDs: any[] = []; for (let i = 0; i < 20; i ++) { UUIDs.push(uuid()); } chainAsync(UUIDs, (uuid, i, done) => { adapter.write("test5", uuid, {id: uuid, name: "Test " + i }, done, rej); }).then(() => { UUIDs.sort(); let keys: any[] = []; adapter.readMulti("test5", "all", undefined, undefined, false, (row, idx) => { keys.push(row.id); }, () => { const condition = objectsEqual(keys, UUIDs); myConsole.assert(condition, "Test Sorted Primary Keys."); condition ? res() : rej({e: UUIDs, g: keys}); }, rej); }); }); }).then(() => { // Ordered Float PK Test return new Promise((res, rej) => { let floats: any[] = []; for (let i = 0; i < 20; i++) { floats.push({id: Math.random(), name: "Test " + i}); } chainAsync(floats, (row, i, next) => { adapter.write("test6", row.id, row, next, rej); }).then(() => { let rows: any[] = []; adapter.readMulti("test6", "all", undefined, undefined, false, (row) => { rows.push(row); }, () => { const condition = objectsEqual(rows, floats.sort((a, b) => a.id > b.id ? 1 : -1)); myConsole.assert(condition, "Test float primary keys."); condition ? (() => { adapter.read("test6", floats[0].id, (row: any) => { const condition2 = objectsEqual(row.id, floats[0].id); myConsole.assert(condition2, "Select Float Primary Key."); condition2 ? res() : rej({e: floats[0].id, g: row.id}); }, rej); })() : rej({ e: floats.sort((a, b) => a.id > b.id ? 1 : -1), g: rows }); }, rej); }).catch(rej); }); }).then(() => { // Nested PK Test return new Promise((res, rej) => { let nestedPKRows: any[] = []; for (let i = 1; i < 20; i++) { nestedPKRows.push({nested: {id: i}, name: "Test " + i}); } chainAsync(nestedPKRows, (row, i, next) => { adapter.write("test7", row.nested.id, row, next, rej); }).then(() => { let rows: any[] = []; adapter.readMulti("test7", "all", undefined, undefined, false, (row) => { rows.push(row); }, () => { const condition = objectsEqual(rows, nestedPKRows); myConsole.assert(condition, "Test Nested primary keys."); condition ? (() => { adapter.read("test7", nestedPKRows[2].nested.id, (row: any) => { const condition2 = objectsEqual(row.nested.id, nestedPKRows[2].nested.id); myConsole.assert(condition2, "Select Nested Primary Key."); condition2 ? res() : rej({e: nestedPKRows[0].nested.id, g: row.id}); }, rej); })() : rej({ e: nestedPKRows.sort((a, b) => a.id > b.id ? 1 : -1), g: rows }); }, rej); }).catch(rej); }); }).then(() => { // Sorted string test return new Promise((res, rej) => { let nestedPKRows: any[] = []; let stringValues = " !#$%&'()*+,-./0123456789;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~".split(""); for (let i = 0; i < stringValues.length; i++) { nestedPKRows.push({id: stringValues[i], name: "Test " + i}); } chainAsync(nestedPKRows, (row, i, next) => { adapter.write("test8", row.id, row, next, rej); }).then(() => { let rows: any[] = []; adapter.readMulti("test8", "all", undefined, undefined, false, (row) => { rows.push(row); }, () => { const condition = objectsEqual(rows, nestedPKRows); myConsole.assert(condition, "Test strings sort properly."); condition ? res() : rej({e: nestedPKRows, g: rows}); }, rej); }).catch(rej); }); }).then(() => { return Promise.all([ "test", "test2", "test3", "test4", "test5", "test6", "test7", "test8" ].map(table => new Promise((res, rej) => { adapter.dropTable(table, res, rej); }))).then(() => { return new Promise((res, rej) => { adapter.disconnect(res, rej); }); }); }); } }
the_stack
import { AwaitTransactionSuccessOpts, ContractFunctionObj, ContractTxFunctionObj, SendTransactionOpts, BaseContract, SubscriptionManager, PromiseWithTransactionHash, methodAbiToFunctionSignature, linkLibrariesInBytecode, } from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, BlockParamLiteral, BlockRange, CallData, ContractAbi, ContractArtifact, DecodedLogArgs, LogWithDecodedArgs, MethodAbi, TransactionReceiptWithDecodedLogs, TxData, TxDataPayable, SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, hexUtils, logUtils, providerUtils } from '@0x/utils'; import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; // tslint:enable:no-unused-variable export type ForwarderEventArgs = ForwarderOwnershipTransferredEventArgs; export enum ForwarderEvents { OwnershipTransferred = 'OwnershipTransferred', } export interface ForwarderOwnershipTransferredEventArgs extends DecodedLogArgs { previousOwner: string; newOwner: string; } /* istanbul ignore next */ // tslint:disable:array-type // tslint:disable:no-parameter-reassignment // tslint:disable-next-line:class-name export class ForwarderContract extends BaseContract { /** * @ignore */ public static deployedBytecode: string | undefined; public static contractName = 'Forwarder'; private readonly _methodABIIndex: { [name: string]: number } = {}; private readonly _subscriptionManager: SubscriptionManager<ForwarderEventArgs, ForwarderEvents>; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, supportedProvider: SupportedProvider, txDefaults: Partial<TxData>, logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, _exchange: string, _exchangeV2: string, _weth: string, ): Promise<ForwarderContract> { assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ schemas.addressSchema, schemas.numberSchema, schemas.jsNumber, ]); if (artifact.compilerOutput === undefined) { throw new Error('Compiler output not found in the artifact file'); } const provider = providerUtils.standardizeOrThrow(supportedProvider); const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; if (Object.keys(logDecodeDependencies) !== undefined) { for (const key of Object.keys(logDecodeDependencies)) { logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; } } return ForwarderContract.deployAsync( bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly, _exchange, _exchangeV2, _weth, ); } public static async deployWithLibrariesFrom0xArtifactAsync( artifact: ContractArtifact, libraryArtifacts: { [libraryName: string]: ContractArtifact }, supportedProvider: SupportedProvider, txDefaults: Partial<TxData>, logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, _exchange: string, _exchangeV2: string, _weth: string, ): Promise<ForwarderContract> { assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ schemas.addressSchema, schemas.numberSchema, schemas.jsNumber, ]); if (artifact.compilerOutput === undefined) { throw new Error('Compiler output not found in the artifact file'); } const provider = providerUtils.standardizeOrThrow(supportedProvider); const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; if (Object.keys(logDecodeDependencies) !== undefined) { for (const key of Object.keys(logDecodeDependencies)) { logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; } } const libraryAddresses = await ForwarderContract._deployLibrariesAsync( artifact, libraryArtifacts, new Web3Wrapper(provider), txDefaults, ); const bytecode = linkLibrariesInBytecode(artifact, libraryAddresses); return ForwarderContract.deployAsync( bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly, _exchange, _exchangeV2, _weth, ); } public static async deployAsync( bytecode: string, abi: ContractAbi, supportedProvider: SupportedProvider, txDefaults: Partial<TxData>, logDecodeDependencies: { [contractName: string]: ContractAbi }, _exchange: string, _exchangeV2: string, _weth: string, ): Promise<ForwarderContract> { assert.isHexString('bytecode', bytecode); assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ schemas.addressSchema, schemas.numberSchema, schemas.jsNumber, ]); const provider = providerUtils.standardizeOrThrow(supportedProvider); const constructorAbi = BaseContract._lookupConstructorAbi(abi); [_exchange, _exchangeV2, _weth] = BaseContract._formatABIDataItemList( constructorAbi.inputs, [_exchange, _exchangeV2, _weth], BaseContract._bigNumberToString, ); const iface = new ethers.utils.Interface(abi); const deployInfo = iface.deployFunction; const txData = deployInfo.encode(bytecode, [_exchange, _exchangeV2, _weth]); const web3Wrapper = new Web3Wrapper(provider); const txDataWithDefaults = await BaseContract._applyDefaultsToContractTxDataAsync( { data: txData, ...txDefaults, }, web3Wrapper.estimateGasAsync.bind(web3Wrapper), ); const txHash = await web3Wrapper.sendTransactionAsync(txDataWithDefaults); logUtils.log(`transactionHash: ${txHash}`); const txReceipt = await web3Wrapper.awaitTransactionSuccessAsync(txHash); logUtils.log(`Forwarder successfully deployed at ${txReceipt.contractAddress}`); const contractInstance = new ForwarderContract( txReceipt.contractAddress as string, provider, txDefaults, logDecodeDependencies, ); contractInstance.constructorArgs = [_exchange, _exchangeV2, _weth]; return contractInstance; } /** * @returns The contract ABI */ public static ABI(): ContractAbi { const abi = [ { inputs: [ { name: '_exchange', type: 'address', }, { name: '_exchangeV2', type: 'address', }, { name: '_weth', type: 'address', }, ], outputs: [], payable: false, stateMutability: 'nonpayable', type: 'constructor', }, { anonymous: false, inputs: [ { name: 'previousOwner', type: 'address', indexed: true, }, { name: 'newOwner', type: 'address', indexed: true, }, ], name: 'OwnershipTransferred', outputs: [], type: 'event', }, { inputs: [], outputs: [], payable: true, stateMutability: 'payable', type: 'fallback', }, { constant: true, inputs: [], name: 'ERC1155_BATCH_RECEIVED', outputs: [ { name: '', type: 'bytes4', }, ], payable: false, stateMutability: 'view', type: 'function', }, { constant: true, inputs: [], name: 'ERC1155_RECEIVED', outputs: [ { name: '', type: 'bytes4', }, ], payable: false, stateMutability: 'view', type: 'function', }, { constant: true, inputs: [], name: 'EXCHANGE_V2_ORDER_ID', outputs: [ { name: '', type: 'bytes4', }, ], payable: false, stateMutability: 'view', type: 'function', }, { constant: false, inputs: [ { name: 'assetData', type: 'bytes', }, ], name: 'approveMakerAssetProxy', outputs: [], payable: false, stateMutability: 'nonpayable', type: 'function', }, { constant: false, inputs: [ { name: 'orders', type: 'tuple[]', components: [ { name: 'makerAddress', type: 'address', }, { name: 'takerAddress', type: 'address', }, { name: 'feeRecipientAddress', type: 'address', }, { name: 'senderAddress', type: 'address', }, { name: 'makerAssetAmount', type: 'uint256', }, { name: 'takerAssetAmount', type: 'uint256', }, { name: 'makerFee', type: 'uint256', }, { name: 'takerFee', type: 'uint256', }, { name: 'expirationTimeSeconds', type: 'uint256', }, { name: 'salt', type: 'uint256', }, { name: 'makerAssetData', type: 'bytes', }, { name: 'takerAssetData', type: 'bytes', }, { name: 'makerFeeAssetData', type: 'bytes', }, { name: 'takerFeeAssetData', type: 'bytes', }, ], }, { name: 'makerAssetBuyAmount', type: 'uint256', }, { name: 'signatures', type: 'bytes[]', }, { name: 'ethFeeAmounts', type: 'uint256[]', }, { name: 'feeRecipients', type: 'address[]', }, ], name: 'marketBuyOrdersWithEth', outputs: [ { name: 'wethSpentAmount', type: 'uint256', }, { name: 'makerAssetAcquiredAmount', type: 'uint256', }, ], payable: true, stateMutability: 'payable', type: 'function', }, { constant: false, inputs: [ { name: 'orders', type: 'tuple[]', components: [ { name: 'makerAddress', type: 'address', }, { name: 'takerAddress', type: 'address', }, { name: 'feeRecipientAddress', type: 'address', }, { name: 'senderAddress', type: 'address', }, { name: 'makerAssetAmount', type: 'uint256', }, { name: 'takerAssetAmount', type: 'uint256', }, { name: 'makerFee', type: 'uint256', }, { name: 'takerFee', type: 'uint256', }, { name: 'expirationTimeSeconds', type: 'uint256', }, { name: 'salt', type: 'uint256', }, { name: 'makerAssetData', type: 'bytes', }, { name: 'takerAssetData', type: 'bytes', }, { name: 'makerFeeAssetData', type: 'bytes', }, { name: 'takerFeeAssetData', type: 'bytes', }, ], }, { name: 'ethSellAmount', type: 'uint256', }, { name: 'signatures', type: 'bytes[]', }, { name: 'ethFeeAmounts', type: 'uint256[]', }, { name: 'feeRecipients', type: 'address[]', }, ], name: 'marketSellAmountWithEth', outputs: [ { name: 'wethSpentAmount', type: 'uint256', }, { name: 'makerAssetAcquiredAmount', type: 'uint256', }, ], payable: true, stateMutability: 'payable', type: 'function', }, { constant: false, inputs: [ { name: 'orders', type: 'tuple[]', components: [ { name: 'makerAddress', type: 'address', }, { name: 'takerAddress', type: 'address', }, { name: 'feeRecipientAddress', type: 'address', }, { name: 'senderAddress', type: 'address', }, { name: 'makerAssetAmount', type: 'uint256', }, { name: 'takerAssetAmount', type: 'uint256', }, { name: 'makerFee', type: 'uint256', }, { name: 'takerFee', type: 'uint256', }, { name: 'expirationTimeSeconds', type: 'uint256', }, { name: 'salt', type: 'uint256', }, { name: 'makerAssetData', type: 'bytes', }, { name: 'takerAssetData', type: 'bytes', }, { name: 'makerFeeAssetData', type: 'bytes', }, { name: 'takerFeeAssetData', type: 'bytes', }, ], }, { name: 'signatures', type: 'bytes[]', }, { name: 'ethFeeAmounts', type: 'uint256[]', }, { name: 'feeRecipients', type: 'address[]', }, ], name: 'marketSellOrdersWithEth', outputs: [ { name: 'wethSpentAmount', type: 'uint256', }, { name: 'makerAssetAcquiredAmount', type: 'uint256', }, ], payable: true, stateMutability: 'payable', type: 'function', }, { constant: false, inputs: [ { name: 'operator', type: 'address', }, { name: 'from', type: 'address', }, { name: 'ids', type: 'uint256[]', }, { name: 'values', type: 'uint256[]', }, { name: 'data', type: 'bytes', }, ], name: 'onERC1155BatchReceived', outputs: [ { name: '', type: 'bytes4', }, ], payable: false, stateMutability: 'nonpayable', type: 'function', }, { constant: false, inputs: [ { name: 'operator', type: 'address', }, { name: 'from', type: 'address', }, { name: 'id', type: 'uint256', }, { name: 'value', type: 'uint256', }, { name: 'data', type: 'bytes', }, ], name: 'onERC1155Received', outputs: [ { name: '', type: 'bytes4', }, ], payable: false, stateMutability: 'nonpayable', type: 'function', }, { constant: true, inputs: [], name: 'owner', outputs: [ { name: '', type: 'address', }, ], payable: false, stateMutability: 'view', type: 'function', }, { constant: false, inputs: [ { name: 'newOwner', type: 'address', }, ], name: 'transferOwnership', outputs: [], payable: false, stateMutability: 'nonpayable', type: 'function', }, { constant: false, inputs: [ { name: 'assetData', type: 'bytes', }, { name: 'amount', type: 'uint256', }, ], name: 'withdrawAsset', outputs: [], payable: false, stateMutability: 'nonpayable', type: 'function', }, ] as ContractAbi; return abi; } protected static async _deployLibrariesAsync( artifact: ContractArtifact, libraryArtifacts: { [libraryName: string]: ContractArtifact }, web3Wrapper: Web3Wrapper, txDefaults: Partial<TxData>, libraryAddresses: { [libraryName: string]: string } = {}, ): Promise<{ [libraryName: string]: string }> { const links = artifact.compilerOutput.evm.bytecode.linkReferences; // Go through all linked libraries, recursively deploying them if necessary. for (const link of Object.values(links)) { for (const libraryName of Object.keys(link)) { if (!libraryAddresses[libraryName]) { // Library not yet deployed. const libraryArtifact = libraryArtifacts[libraryName]; if (!libraryArtifact) { throw new Error(`Missing artifact for linked library "${libraryName}"`); } // Deploy any dependent libraries used by this library. await ForwarderContract._deployLibrariesAsync( libraryArtifact, libraryArtifacts, web3Wrapper, txDefaults, libraryAddresses, ); // Deploy this library. const linkedLibraryBytecode = linkLibrariesInBytecode(libraryArtifact, libraryAddresses); const txDataWithDefaults = await BaseContract._applyDefaultsToContractTxDataAsync( { data: linkedLibraryBytecode, ...txDefaults, }, web3Wrapper.estimateGasAsync.bind(web3Wrapper), ); const txHash = await web3Wrapper.sendTransactionAsync(txDataWithDefaults); logUtils.log(`transactionHash: ${txHash}`); const { contractAddress } = await web3Wrapper.awaitTransactionSuccessAsync(txHash); logUtils.log(`${libraryArtifact.contractName} successfully deployed at ${contractAddress}`); libraryAddresses[libraryArtifact.contractName] = contractAddress as string; } } } return libraryAddresses; } public getFunctionSignature(methodName: string): string { const index = this._methodABIIndex[methodName]; const methodAbi = ForwarderContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion const functionSignature = methodAbiToFunctionSignature(methodAbi); return functionSignature; } public getABIDecodedTransactionData<T>(methodName: string, callData: string): T { const functionSignature = this.getFunctionSignature(methodName); const self = (this as any) as ForwarderContract; const abiEncoder = self._lookupAbiEncoder(functionSignature); const abiDecodedCallData = abiEncoder.strictDecode<T>(callData); return abiDecodedCallData; } public getABIDecodedReturnData<T>(methodName: string, callData: string): T { const functionSignature = this.getFunctionSignature(methodName); const self = (this as any) as ForwarderContract; const abiEncoder = self._lookupAbiEncoder(functionSignature); const abiDecodedCallData = abiEncoder.strictDecodeReturnValue<T>(callData); return abiDecodedCallData; } public getSelector(methodName: string): string { const functionSignature = this.getFunctionSignature(methodName); const self = (this as any) as ForwarderContract; const abiEncoder = self._lookupAbiEncoder(functionSignature); return abiEncoder.getSelector(); } public ERC1155_BATCH_RECEIVED(): ContractFunctionObj<string> { const self = (this as any) as ForwarderContract; const functionSignature = 'ERC1155_BATCH_RECEIVED()'; return { async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<string> { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); return abiEncoder.strictDecodeReturnValue<string>(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, []); }, }; } public ERC1155_RECEIVED(): ContractFunctionObj<string> { const self = (this as any) as ForwarderContract; const functionSignature = 'ERC1155_RECEIVED()'; return { async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<string> { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); return abiEncoder.strictDecodeReturnValue<string>(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, []); }, }; } public EXCHANGE_V2_ORDER_ID(): ContractFunctionObj<string> { const self = (this as any) as ForwarderContract; const functionSignature = 'EXCHANGE_V2_ORDER_ID()'; return { async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<string> { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); return abiEncoder.strictDecodeReturnValue<string>(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, []); }, }; } /** * Approves the respective proxy for a given asset to transfer tokens on the Forwarder contract's behalf. * This is necessary because an order fee denominated in the maker asset (i.e. a percentage fee) is sent by the * Forwarder contract to the fee recipient. * This method needs to be called before forwarding orders of a maker asset that hasn't * previously been approved. * @param assetData Byte array encoded for the respective asset proxy. */ public approveMakerAssetProxy(assetData: string): ContractTxFunctionObj<void> { const self = (this as any) as ForwarderContract; assert.isString('assetData', assetData); const functionSignature = 'approveMakerAssetProxy(bytes)'; return { async sendTransactionAsync( txData?: Partial<TxData> | undefined, opts: SendTransactionOpts = { shouldValidate: true }, ): Promise<string> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( { data: this.getABIEncodedTransactionData(), ...txData }, this.estimateGasAsync.bind(this), ); if (opts.shouldValidate !== false) { await this.callAsync(txDataWithDefaults); } return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); }, awaitTransactionSuccessAsync( txData?: Partial<TxData>, opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, ): PromiseWithTransactionHash<TransactionReceiptWithDecodedLogs> { return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); }, async estimateGasAsync(txData?: Partial<TxData> | undefined): Promise<number> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ data: this.getABIEncodedTransactionData(), ...txData, }); return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); }, async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<void> { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); return abiEncoder.strictDecodeReturnValue<void>(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [assetData]); }, }; } /** * Attempt to buy makerAssetBuyAmount of makerAsset by selling ETH provided with transaction. * The Forwarder may *fill* more than makerAssetBuyAmount of the makerAsset so that it can * pay takerFees where takerFeeAssetData == makerAssetData (i.e. percentage fees). * Any ETH not spent will be refunded to sender. * @param orders Array of order specifications used containing desired * makerAsset and WETH as takerAsset. * @param makerAssetBuyAmount Desired amount of makerAsset to purchase. * @param signatures Proofs that orders have been created by makers. * @param ethFeeAmounts Amounts of ETH, denominated in Wei, that are paid to * corresponding feeRecipients. * @param feeRecipients Addresses that will receive ETH when orders are filled. * @returns wethSpentAmount Amount of WETH spent on the given set of orders.makerAssetAcquiredAmount Amount of maker asset acquired from the given set of orders. */ public marketBuyOrdersWithEth( orders: Array<{ makerAddress: string; takerAddress: string; feeRecipientAddress: string; senderAddress: string; makerAssetAmount: BigNumber; takerAssetAmount: BigNumber; makerFee: BigNumber; takerFee: BigNumber; expirationTimeSeconds: BigNumber; salt: BigNumber; makerAssetData: string; takerAssetData: string; makerFeeAssetData: string; takerFeeAssetData: string; }>, makerAssetBuyAmount: BigNumber, signatures: string[], ethFeeAmounts: BigNumber[], feeRecipients: string[], ): ContractTxFunctionObj<[BigNumber, BigNumber]> { const self = (this as any) as ForwarderContract; assert.isArray('orders', orders); assert.isBigNumber('makerAssetBuyAmount', makerAssetBuyAmount); assert.isArray('signatures', signatures); assert.isArray('ethFeeAmounts', ethFeeAmounts); assert.isArray('feeRecipients', feeRecipients); const functionSignature = 'marketBuyOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[],uint256[],address[])'; return { async sendTransactionAsync( txData?: Partial<TxData> | undefined, opts: SendTransactionOpts = { shouldValidate: true }, ): Promise<string> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( { data: this.getABIEncodedTransactionData(), ...txData }, this.estimateGasAsync.bind(this), ); if (opts.shouldValidate !== false) { await this.callAsync(txDataWithDefaults); } return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); }, awaitTransactionSuccessAsync( txData?: Partial<TxData>, opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, ): PromiseWithTransactionHash<TransactionReceiptWithDecodedLogs> { return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); }, async estimateGasAsync(txData?: Partial<TxData> | undefined): Promise<number> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ data: this.getABIEncodedTransactionData(), ...txData, }); return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); }, async callAsync( callData: Partial<CallData> = {}, defaultBlock?: BlockParam, ): Promise<[BigNumber, BigNumber]> { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); return abiEncoder.strictDecodeReturnValue<[BigNumber, BigNumber]>(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [ orders, makerAssetBuyAmount, signatures, ethFeeAmounts, feeRecipients, ]); }, }; } /** * Purchases as much of orders' makerAssets as possible by selling the specified amount of ETH * accounting for order and forwarder fees. This functions throws if ethSellAmount was not reached. * @param orders Array of order specifications used containing desired * makerAsset and WETH as takerAsset. * @param ethSellAmount Desired amount of ETH to sell. * @param signatures Proofs that orders have been created by makers. * @param ethFeeAmounts Amounts of ETH, denominated in Wei, that are paid to * corresponding feeRecipients. * @param feeRecipients Addresses that will receive ETH when orders are filled. * @returns wethSpentAmount Amount of WETH spent on the given set of orders.makerAssetAcquiredAmount Amount of maker asset acquired from the given set of orders. */ public marketSellAmountWithEth( orders: Array<{ makerAddress: string; takerAddress: string; feeRecipientAddress: string; senderAddress: string; makerAssetAmount: BigNumber; takerAssetAmount: BigNumber; makerFee: BigNumber; takerFee: BigNumber; expirationTimeSeconds: BigNumber; salt: BigNumber; makerAssetData: string; takerAssetData: string; makerFeeAssetData: string; takerFeeAssetData: string; }>, ethSellAmount: BigNumber, signatures: string[], ethFeeAmounts: BigNumber[], feeRecipients: string[], ): ContractTxFunctionObj<[BigNumber, BigNumber]> { const self = (this as any) as ForwarderContract; assert.isArray('orders', orders); assert.isBigNumber('ethSellAmount', ethSellAmount); assert.isArray('signatures', signatures); assert.isArray('ethFeeAmounts', ethFeeAmounts); assert.isArray('feeRecipients', feeRecipients); const functionSignature = 'marketSellAmountWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[],uint256[],address[])'; return { async sendTransactionAsync( txData?: Partial<TxData> | undefined, opts: SendTransactionOpts = { shouldValidate: true }, ): Promise<string> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( { data: this.getABIEncodedTransactionData(), ...txData }, this.estimateGasAsync.bind(this), ); if (opts.shouldValidate !== false) { await this.callAsync(txDataWithDefaults); } return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); }, awaitTransactionSuccessAsync( txData?: Partial<TxData>, opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, ): PromiseWithTransactionHash<TransactionReceiptWithDecodedLogs> { return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); }, async estimateGasAsync(txData?: Partial<TxData> | undefined): Promise<number> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ data: this.getABIEncodedTransactionData(), ...txData, }); return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); }, async callAsync( callData: Partial<CallData> = {}, defaultBlock?: BlockParam, ): Promise<[BigNumber, BigNumber]> { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); return abiEncoder.strictDecodeReturnValue<[BigNumber, BigNumber]>(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [ orders, ethSellAmount, signatures, ethFeeAmounts, feeRecipients, ]); }, }; } /** * Purchases as much of orders' makerAssets as possible by selling as much of the ETH value sent * as possible, accounting for order and forwarder fees. * @param orders Array of order specifications used containing desired * makerAsset and WETH as takerAsset. * @param signatures Proofs that orders have been created by makers. * @param ethFeeAmounts Amounts of ETH, denominated in Wei, that are paid to * corresponding feeRecipients. * @param feeRecipients Addresses that will receive ETH when orders are filled. * @returns wethSpentAmount Amount of WETH spent on the given set of orders.makerAssetAcquiredAmount Amount of maker asset acquired from the given set of orders. */ public marketSellOrdersWithEth( orders: Array<{ makerAddress: string; takerAddress: string; feeRecipientAddress: string; senderAddress: string; makerAssetAmount: BigNumber; takerAssetAmount: BigNumber; makerFee: BigNumber; takerFee: BigNumber; expirationTimeSeconds: BigNumber; salt: BigNumber; makerAssetData: string; takerAssetData: string; makerFeeAssetData: string; takerFeeAssetData: string; }>, signatures: string[], ethFeeAmounts: BigNumber[], feeRecipients: string[], ): ContractTxFunctionObj<[BigNumber, BigNumber]> { const self = (this as any) as ForwarderContract; assert.isArray('orders', orders); assert.isArray('signatures', signatures); assert.isArray('ethFeeAmounts', ethFeeAmounts); assert.isArray('feeRecipients', feeRecipients); const functionSignature = 'marketSellOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],uint256[],address[])'; return { async sendTransactionAsync( txData?: Partial<TxData> | undefined, opts: SendTransactionOpts = { shouldValidate: true }, ): Promise<string> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( { data: this.getABIEncodedTransactionData(), ...txData }, this.estimateGasAsync.bind(this), ); if (opts.shouldValidate !== false) { await this.callAsync(txDataWithDefaults); } return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); }, awaitTransactionSuccessAsync( txData?: Partial<TxData>, opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, ): PromiseWithTransactionHash<TransactionReceiptWithDecodedLogs> { return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); }, async estimateGasAsync(txData?: Partial<TxData> | undefined): Promise<number> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ data: this.getABIEncodedTransactionData(), ...txData, }); return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); }, async callAsync( callData: Partial<CallData> = {}, defaultBlock?: BlockParam, ): Promise<[BigNumber, BigNumber]> { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); return abiEncoder.strictDecodeReturnValue<[BigNumber, BigNumber]>(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [ orders, signatures, ethFeeAmounts, feeRecipients, ]); }, }; } /** * The smart contract calls this function on the recipient after a `safeTransferFrom`. This function MAY throw to revert and reject the transfer. Return of other than the magic value MUST result in the transaction being reverted Note: the contract address is always the message sender * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred * @param values An array containing amounts of each token being transferred * @param data Additional data with no specified format * @returns &#x60;bytes4(keccak256(&quot;onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)&quot;))&#x60; */ public onERC1155BatchReceived( operator: string, from: string, ids: BigNumber[], values: BigNumber[], data: string, ): ContractTxFunctionObj<string> { const self = (this as any) as ForwarderContract; assert.isString('operator', operator); assert.isString('from', from); assert.isArray('ids', ids); assert.isArray('values', values); assert.isString('data', data); const functionSignature = 'onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)'; return { async sendTransactionAsync( txData?: Partial<TxData> | undefined, opts: SendTransactionOpts = { shouldValidate: true }, ): Promise<string> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( { data: this.getABIEncodedTransactionData(), ...txData }, this.estimateGasAsync.bind(this), ); if (opts.shouldValidate !== false) { await this.callAsync(txDataWithDefaults); } return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); }, awaitTransactionSuccessAsync( txData?: Partial<TxData>, opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, ): PromiseWithTransactionHash<TransactionReceiptWithDecodedLogs> { return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); }, async estimateGasAsync(txData?: Partial<TxData> | undefined): Promise<number> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ data: this.getABIEncodedTransactionData(), ...txData, }); return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); }, async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<string> { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); return abiEncoder.strictDecodeReturnValue<string>(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [ operator.toLowerCase(), from.toLowerCase(), ids, values, data, ]); }, }; } /** * The smart contract calls this function on the recipient after a `safeTransferFrom`. This function MAY throw to revert and reject the transfer. Return of other than the magic value MUST result in the transaction being reverted Note: the contract address is always the message sender * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param id An array containing the ids of the token being transferred * @param value An array containing the amount of tokens being transferred * @param data Additional data with no specified format * @returns &#x60;bytes4(keccak256(&quot;onERC1155Received(address,address,uint256,uint256,bytes)&quot;))&#x60; */ public onERC1155Received( operator: string, from: string, id: BigNumber, value: BigNumber, data: string, ): ContractTxFunctionObj<string> { const self = (this as any) as ForwarderContract; assert.isString('operator', operator); assert.isString('from', from); assert.isBigNumber('id', id); assert.isBigNumber('value', value); assert.isString('data', data); const functionSignature = 'onERC1155Received(address,address,uint256,uint256,bytes)'; return { async sendTransactionAsync( txData?: Partial<TxData> | undefined, opts: SendTransactionOpts = { shouldValidate: true }, ): Promise<string> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( { data: this.getABIEncodedTransactionData(), ...txData }, this.estimateGasAsync.bind(this), ); if (opts.shouldValidate !== false) { await this.callAsync(txDataWithDefaults); } return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); }, awaitTransactionSuccessAsync( txData?: Partial<TxData>, opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, ): PromiseWithTransactionHash<TransactionReceiptWithDecodedLogs> { return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); }, async estimateGasAsync(txData?: Partial<TxData> | undefined): Promise<number> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ data: this.getABIEncodedTransactionData(), ...txData, }); return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); }, async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<string> { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); return abiEncoder.strictDecodeReturnValue<string>(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [ operator.toLowerCase(), from.toLowerCase(), id, value, data, ]); }, }; } public owner(): ContractFunctionObj<string> { const self = (this as any) as ForwarderContract; const functionSignature = 'owner()'; return { async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<string> { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); return abiEncoder.strictDecodeReturnValue<string>(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, []); }, }; } /** * Change the owner of this contract. * @param newOwner New owner address. */ public transferOwnership(newOwner: string): ContractTxFunctionObj<void> { const self = (this as any) as ForwarderContract; assert.isString('newOwner', newOwner); const functionSignature = 'transferOwnership(address)'; return { async sendTransactionAsync( txData?: Partial<TxData> | undefined, opts: SendTransactionOpts = { shouldValidate: true }, ): Promise<string> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( { data: this.getABIEncodedTransactionData(), ...txData }, this.estimateGasAsync.bind(this), ); if (opts.shouldValidate !== false) { await this.callAsync(txDataWithDefaults); } return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); }, awaitTransactionSuccessAsync( txData?: Partial<TxData>, opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, ): PromiseWithTransactionHash<TransactionReceiptWithDecodedLogs> { return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); }, async estimateGasAsync(txData?: Partial<TxData> | undefined): Promise<number> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ data: this.getABIEncodedTransactionData(), ...txData, }); return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); }, async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<void> { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); return abiEncoder.strictDecodeReturnValue<void>(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [newOwner.toLowerCase()]); }, }; } /** * Withdraws assets from this contract. It may be used by the owner to withdraw assets * that were accidentally sent to this contract. * @param assetData Byte array encoded for the respective asset proxy. * @param amount Amount of the asset to withdraw. */ public withdrawAsset(assetData: string, amount: BigNumber): ContractTxFunctionObj<void> { const self = (this as any) as ForwarderContract; assert.isString('assetData', assetData); assert.isBigNumber('amount', amount); const functionSignature = 'withdrawAsset(bytes,uint256)'; return { async sendTransactionAsync( txData?: Partial<TxData> | undefined, opts: SendTransactionOpts = { shouldValidate: true }, ): Promise<string> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( { data: this.getABIEncodedTransactionData(), ...txData }, this.estimateGasAsync.bind(this), ); if (opts.shouldValidate !== false) { await this.callAsync(txDataWithDefaults); } return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); }, awaitTransactionSuccessAsync( txData?: Partial<TxData>, opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, ): PromiseWithTransactionHash<TransactionReceiptWithDecodedLogs> { return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); }, async estimateGasAsync(txData?: Partial<TxData> | undefined): Promise<number> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ data: this.getABIEncodedTransactionData(), ...txData, }); return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); }, async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<void> { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); return abiEncoder.strictDecodeReturnValue<void>(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [assetData, amount]); }, }; } /** * Subscribe to an event type emitted by the Forwarder contract. * @param eventName The Forwarder contract event you would like to subscribe to. * @param indexFilterValues An object where the keys are indexed args returned by the event and * the value is the value you are interested in. E.g `{maker: aUserAddressHex}` * @param callback Callback that gets called when a log is added/removed * @param isVerbose Enable verbose subscription warnings (e.g recoverable network issues encountered) * @return Subscription token used later to unsubscribe */ public subscribe<ArgsType extends ForwarderEventArgs>( eventName: ForwarderEvents, indexFilterValues: IndexedFilterValues, callback: EventCallback<ArgsType>, isVerbose: boolean = false, blockPollingIntervalMs?: number, ): string { assert.doesBelongToStringEnum('eventName', eventName, ForwarderEvents); assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); assert.isFunction('callback', callback); const subscriptionToken = this._subscriptionManager.subscribe<ArgsType>( this.address, eventName, indexFilterValues, ForwarderContract.ABI(), callback, isVerbose, blockPollingIntervalMs, ); return subscriptionToken; } /** * Cancel a subscription * @param subscriptionToken Subscription token returned by `subscribe()` */ public unsubscribe(subscriptionToken: string): void { this._subscriptionManager.unsubscribe(subscriptionToken); } /** * Cancels all existing subscriptions */ public unsubscribeAll(): void { this._subscriptionManager.unsubscribeAll(); } /** * Gets historical logs without creating a subscription * @param eventName The Forwarder contract event you would like to subscribe to. * @param blockRange Block range to get logs from. * @param indexFilterValues An object where the keys are indexed args returned by the event and * the value is the value you are interested in. E.g `{_from: aUserAddressHex}` * @return Array of logs that match the parameters */ public async getLogsAsync<ArgsType extends ForwarderEventArgs>( eventName: ForwarderEvents, blockRange: BlockRange, indexFilterValues: IndexedFilterValues, ): Promise<Array<LogWithDecodedArgs<ArgsType>>> { assert.doesBelongToStringEnum('eventName', eventName, ForwarderEvents); assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); const logs = await this._subscriptionManager.getLogsAsync<ArgsType>( this.address, eventName, blockRange, indexFilterValues, ForwarderContract.ABI(), ); return logs; } constructor( address: string, supportedProvider: SupportedProvider, txDefaults?: Partial<TxData>, logDecodeDependencies?: { [contractName: string]: ContractAbi }, deployedBytecode: string | undefined = ForwarderContract.deployedBytecode, ) { super( 'Forwarder', ForwarderContract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies, deployedBytecode, ); classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); this._subscriptionManager = new SubscriptionManager<ForwarderEventArgs, ForwarderEvents>( ForwarderContract.ABI(), this._web3Wrapper, ); ForwarderContract.ABI().forEach((item, index) => { if (item.type === 'function') { const methodAbi = item as MethodAbi; this._methodABIIndex[methodAbi.name] = index; } }); } } // tslint:disable:max-file-line-count // tslint:enable:no-unbound-method no-parameter-reassignment no-consecutive-blank-lines ordered-imports align // tslint:enable:trailing-comma whitespace no-trailing-whitespace
the_stack
import { css } from '@emotion/react'; import styled from '@emotion/styled'; import FocusTrap from 'focus-trap-react'; import { motion } from 'framer-motion'; import Link from 'next/link'; import { useRouter } from 'next/router'; import React from 'react'; import ReactDOM from 'react-dom'; import useDebouncedValue from '../../hooks/useDebouncedValue'; import { useTheme } from '../../context/ThemeContext'; import { EnterIcon } from '../Icons'; import { CommandCenterStatic } from './CommandCenterStatic'; import { HEIGHT, MAX_HEIGHT } from './constants'; const toggleLockScroll = () => { document.documentElement.classList.toggle('lock-scroll'); return; }; type Result = { type: 'snippet' | 'blogPost'; slug: string; title: string; }; interface Props { onClose: () => void; } export type IndexOperator = (nudge?: number) => void; const clamp = (value: number, min: number, max: number) => { return Math.min(Math.max(value, min), max); }; const wrap = (value: number, min: number, max: number) => { const range = max - min; return ((((value - min) % range) + range) % range) + min; }; function useIndexItem<T>( items: T[], initial = 0 ): [ T, IndexOperator, IndexOperator, React.Dispatch<React.SetStateAction<number>> ] { const [index, setIndex] = React.useState(initial); const itemsRef = React.useRef(items); React.useEffect(() => { itemsRef.current = items; setIndex((index) => clamp(index, 0, Math.max(items.length - 1, 0))); }, [items]); const previousItem = React.useCallback((nudge: number = 1) => { setIndex((index) => wrap(index - nudge, 0, Math.max(itemsRef.current.length, 0)) ); }, []); const nextItem = React.useCallback((nudge: number = 1) => { setIndex((index) => wrap(index + nudge, 0, Math.max(itemsRef.current.length, 0)) ); }, []); return [items[index], previousItem, nextItem, setIndex]; } const Search = (props: Props) => { const { onClose } = props; const router = useRouter(); const [loading, setLoading] = React.useState(true); const [results, setResults] = React.useState<Result[]>([]); const [searchQuery, setSearchQuery] = React.useState(''); const debouncedSearchQuery = useDebouncedValue(searchQuery, 250); const inputRef = React.useRef<HTMLInputElement>(null); const SearchRef = React.useRef<HTMLDivElement>(null); const [ selectedResult, previousResult, nextResult, setSelectedResult, ] = useIndexItem(results); const clickOutside = (e: React.BaseSyntheticEvent) => { if ( SearchRef && SearchRef.current && SearchRef.current.contains(e.target) ) { return null; } return onClose(); }; const handlePointer = (index: number) => setSelectedResult(index); const handleKey = React.useCallback( (event: KeyboardEvent) => { if (debouncedSearchQuery !== '') { switch (event.key) { case 'Enter': const href = `/${ selectedResult.type === 'snippet' ? 'snippets' : 'posts' }/${selectedResult.slug}/`; router.push(href).then(() => window.scrollTo(0, 0)); setTimeout(onClose, 600); break; case 'ArrowUp': event.preventDefault(); previousResult(); break; case 'ArrowDown': event.preventDefault(); nextResult(); break; default: } } }, [ debouncedSearchQuery, selectedResult, router, onClose, previousResult, nextResult, ] ); React.useEffect(() => { if (inputRef && inputRef.current) { inputRef.current.focus(); } toggleLockScroll(); return () => toggleLockScroll(); }, []); React.useEffect(() => { setLoading(true); if (debouncedSearchQuery && debouncedSearchQuery !== '') { const searchEndpoint = `/api/search?q=${debouncedSearchQuery.toLowerCase()}`; fetch(searchEndpoint) .then((res) => res.json()) .then((res) => { setResults(res.results); setLoading(false); }); } if (debouncedSearchQuery === '') { setResults([]); setLoading(false); } }, [debouncedSearchQuery]); React.useEffect(() => { window.addEventListener('keydown', handleKey); return () => { window.removeEventListener('keydown', handleKey); }; }, [handleKey]); React.useEffect(() => { if (selectedResult) { document .getElementById(selectedResult.slug) ?.scrollIntoView({ block: 'nearest' }); } }, [selectedResult]); const { dark } = useTheme(); return ReactDOM.createPortal( <FocusTrap> <aside> <Overlay initial={{ backgroundColor: dark ? 'rgba(0,0,0,0)' : 'rgba(241, 243, 247, 0)', }} animate={{ backgroundColor: dark ? 'rgba(0,0,0,0.8)' : 'rgba(241, 243, 247, 0.8)', }} exit={{ backgroundColor: dark ? 'rgba(0,0,0,0)' : 'rgba(241, 243, 247, 0)', }} // transition={{ duration: 0.4 }} onClick={clickOutside} data-testid="search-overlay" aria-label="search" // The dialog container element has aria-modal set to true. aria-modal="true" tabIndex={-1} // All elements required to operate the dialog are descendants of the element that has role dialog. role="dialog" > <SearchBox initial={{ scale: 0.8, opacity: 0, x: '-50%' }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.5, opacity: 0, transition: { duration: 0.15, delay: 0.1 }, }} transition={{ ease: 'easeOut', duration: 0.2, }} > <FormWrapper data-testid="search" ref={SearchRef}> <form onSubmit={(e) => e.preventDefault()}> <input ref={inputRef} autoComplete="off" type="search" placeholder="Type keywords to search blog posts..." data-testid="search-input" id="search-input" name="search" onChange={(e) => { setSearchQuery(e.target.value); }} value={searchQuery} /> <div css={css` width: 120px; color: var(--maximeheckel-colors-typeface-tertiary); font-size: 14px; font-weight: 500; opacity: 0.8; `} > {debouncedSearchQuery !== '' && !loading ? `${results.length} results` : null} </div> </form> </FormWrapper> {debouncedSearchQuery !== '' ? ( <SearchResults height={ results.length * HEIGHT >= MAX_HEIGHT ? MAX_HEIGHT : results.length * HEIGHT } > {results.map((result, index) => ( <Result data-testid="search-result" key={result.slug} id={result.slug} selected={selectedResult === result} onPointerEnter={() => handlePointer(index)} > <Link href={`/${ result.type === 'snippet' ? 'snippets' : 'posts' }/${result.slug}`} > <a onClick={() => setTimeout(onClose, 600)}> {result.title} </a> </Link> <div css={css` display: flex; align-items: center; justify-content: center; margin-left: 16px; height: 35px; width: 35px; background-color: var(--maximeheckel-colors-emphasis); border-radius: var(--border-radius-1); path { stroke: var(--maximeheckel-colors-brand); } `} > <EnterIcon /> </div> </Result> ))} </SearchResults> ) : ( <CommandCenterStatic /> )} </SearchBox> </Overlay> </aside> </FocusTrap>, document.body ); }; export { Search }; const Result = styled(motion.li)<{ selected: boolean }>` display: flex; align-items: center; margin-bottom: 0px; list-style: none; font-size: 0.875rem; line-height: 24px; color: var(--maximeheckel-colors-typeface-secondary); padding: 10px 25px; height: ${HEIGHT}px; a { color: unset; display: block; width: 500px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-decoration: none; } > div { opacity: 0; } ${(p) => p.selected ? ` background-color: var(--maximeheckel-colors-foreground); a { color: var(--maximeheckel-colors-brand); } > div { opacity: 1; } ` : ''} `; const SearchResults = styled('ul')<{ height?: number }>` @media (max-width: 700px) { max-height: 450px; } background: var(--maximeheckel-colors-body); max-height: ${MAX_HEIGHT}px; height: ${(p) => p.height || 0}px; overflow-y: scroll; margin: 0px; transition: height 0.4s ease-out; will-change: height; `; const SearchBox = styled(motion.div)` position: fixed; overflow: hidden; width: 600px; top: 20%; left: 50%; transform: translateX(-50%); border-radius: var(--border-radius-2); box-shadow: var(--maximeheckel-shadow-1); border: 1px solid var(--maximeheckel-border-color); @media (max-width: 700px) { width: 100%; top: 0; border-radius: 0px; } `; const FormWrapper = styled('div')` background: var(--maximeheckel-colors-body); form { margin: 0px; position: relative; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--maximeheckel-border-color); } input { background: transparent; border: none; font-size: 0.875rem; font-weight: 400; height: 55px; padding: 0px 25px; width: 100%; outline: none; color: var(--maximeheckel-colors-typeface-primary); ::placeholder, ::-webkit-input-placeholder { color: var(--maximeheckel-colors-typeface-secondary); } :-ms-input-placeholder { color: var(--maximeheckel-colors-typeface-secondary); } -webkit-appearance: textfield; outline-offset: -2px; ::-webkit-search-cancel-button, ::-webkit-search-decoration { -webkit-appearance: none; } ::-webkit-input-placeholder { color: inherit; opacity: 0.54; } ::-webkit-file-upload-button { -webkit-appearance: button; font: inherit; } ::-webkit-autofill { background: transparent; color: var(--maximeheckel-colors-typeface-primary); font-size: 14px; } } `; const Overlay = styled(motion.div)` position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 999; outline: none; `;
the_stack
* ERR_MANIFEST_ASSERT_INTEGRITY * ERR_QUICSESSION_VERSION_NEGOTIATION * ERR_REQUIRE_ESM * ERR_TLS_CERT_ALTNAME_INVALID * ERR_UNHANDLED_ERROR * ERR_WORKER_INVALID_EXEC_ARGV * ERR_WORKER_PATH * ERR_QUIC_ERROR * ERR_SOCKET_BUFFER_SIZE //System error, shouldn't ever happen inside Deno * ERR_SYSTEM_ERROR //System error, shouldn't ever happen inside Deno * ERR_TTY_INIT_FAILED //System error, shouldn't ever happen inside Deno * ERR_INVALID_PACKAGE_CONFIG // package.json stuff, probably useless * *********** */ import { getSystemErrorName, inspect } from "./util.ts"; import { codeMap, errorMap } from "./internal_binding/uv.ts"; import { assert } from "../_util/assert.ts"; import { fileURLToPath } from "./url.ts"; export { errorMap }; /** * @see https://github.com/nodejs/node/blob/f3eb224/lib/internal/errors.js */ const classRegExp = /^([A-Z][a-z0-9]*)+$/; /** * @see https://github.com/nodejs/node/blob/f3eb224/lib/internal/errors.js * @description Sorted by a rough estimate on most frequently used entries. */ const kTypes = [ "string", "function", "number", "object", // Accept 'Function' and 'Object' as alternative to the lower cased version. "Function", "Object", "boolean", "bigint", "symbol", ]; const nodeInternalPrefix = "__node_internal_"; // deno-lint-ignore no-explicit-any type GenericFunction = (...args: any[]) => any; /** This function removes unnecessary frames from Node.js core errors. */ export function hideStackFrames(fn: GenericFunction) { // We rename the functions that will be hidden to cut off the stacktrace // at the outermost one. const hidden = nodeInternalPrefix + fn.name; Object.defineProperty(fn, "name", { value: hidden }); return fn; } const captureLargerStackTrace = hideStackFrames( function captureLargerStackTrace(err) { Error.captureStackTrace(err); return err; }, ); export interface ErrnoException extends Error { errno?: number; code?: string; path?: string; syscall?: string; } /** * This creates an error compatible with errors produced in the C++ * This function should replace the deprecated * `exceptionWithHostPort()` function. * * @param err A libuv error number * @param syscall * @param address * @param port * @return The error. */ export const uvExceptionWithHostPort = hideStackFrames( function uvExceptionWithHostPort( err: number, syscall: string, address: string, port?: number, ) { const { 0: code, 1: uvmsg } = uvErrmapGet(err) || uvUnmappedError; const message = `${syscall} ${code}: ${uvmsg}`; let details = ""; if (port && port > 0) { details = ` ${address}:${port}`; } else if (address) { details = ` ${address}`; } // deno-lint-ignore no-explicit-any const ex: any = new Error(`${message}${details}`); ex.code = code; ex.errno = err; ex.syscall = syscall; ex.address = address; if (port) { ex.port = port; } return captureLargerStackTrace(ex); }, ); /** * This used to be `util._errnoException()`. * * @param err A libuv error number * @param syscall * @param original * @return A `ErrnoException` */ export const errnoException = hideStackFrames( function errnoException(err, syscall, original): ErrnoException { const code = getSystemErrorName(err); const message = original ? `${syscall} ${code} ${original}` : `${syscall} ${code}`; // deno-lint-ignore no-explicit-any const ex: any = new Error(message); ex.errno = err; ex.code = code; ex.syscall = syscall; return captureLargerStackTrace(ex); }, ); function uvErrmapGet(name: number) { return errorMap.get(name); } const uvUnmappedError = ["UNKNOWN", "unknown error"]; /** * This creates an error compatible with errors produced in the C++ * function UVException using a context object with data assembled in C++. * The goal is to migrate them to ERR_* errors later when compatibility is * not a concern. * * @param ctx * @return The error. */ export const uvException = hideStackFrames(function uvException(ctx) { const { 0: code, 1: uvmsg } = uvErrmapGet(ctx.errno) || uvUnmappedError; let message = `${code}: ${ctx.message || uvmsg}, ${ctx.syscall}`; let path; let dest; if (ctx.path) { path = ctx.path.toString(); message += ` '${path}'`; } if (ctx.dest) { dest = ctx.dest.toString(); message += ` -> '${dest}'`; } // deno-lint-ignore no-explicit-any const err: any = new Error(message); for (const prop of Object.keys(ctx)) { if (prop === "message" || prop === "path" || prop === "dest") { continue; } err[prop] = ctx[prop]; } err.code = code; if (path) { err.path = path; } if (dest) { err.dest = dest; } return captureLargerStackTrace(err); }); /** * Deprecated, new function is `uvExceptionWithHostPort()` * New function added the error description directly * from C++. this method for backwards compatibility * @param err A libuv error number * @param syscall * @param address * @param port * @param additional */ export const exceptionWithHostPort = hideStackFrames( function exceptionWithHostPort( err: number, syscall: string, address: string, port: number, additional: string, ) { const code = getSystemErrorName(err); let details = ""; if (port && port > 0) { details = ` ${address}:${port}`; } else if (address) { details = ` ${address}`; } if (additional) { details += ` - Local (${additional})`; } // deno-lint-ignore no-explicit-any const ex: any = new Error(`${syscall} ${code}${details}`); ex.errno = err; ex.code = code; ex.syscall = syscall; ex.address = address; if (port) { ex.port = port; } return captureLargerStackTrace(ex); }, ); /** * @param code A libuv error number or a c-ares error code * @param syscall * @param hostname */ export const dnsException = hideStackFrames(function (code, syscall, hostname) { let errno; // If `code` is of type number, it is a libuv error number, else it is a // c-ares error code. if (typeof code === "number") { errno = code; // ENOTFOUND is not a proper POSIX error, but this error has been in place // long enough that it's not practical to remove it. if ( code === codeMap.get("EAI_NODATA") || code === codeMap.get("EAI_NONAME") ) { code = "ENOTFOUND"; // Fabricated error name. } else { code = getSystemErrorName(code); } } const message = `${syscall} ${code}${hostname ? ` ${hostname}` : ""}`; // deno-lint-ignore no-explicit-any const ex: any = new Error(message); ex.errno = errno; ex.code = code; ex.syscall = syscall; if (hostname) { ex.hostname = hostname; } return captureLargerStackTrace(ex); }); /** * All error instances in Node have additional methods and properties * This export class is meant to be extended by these instances abstracting native JS error instances */ export class NodeErrorAbstraction extends Error { code: string; constructor(name: string, code: string, message: string) { super(message); this.code = code; this.name = name; //This number changes depending on the name of this class //20 characters as of now this.stack = this.stack && `${name} [${this.code}]${this.stack.slice(20)}`; } toString() { return `${this.name} [${this.code}]: ${this.message}`; } } export class NodeError extends NodeErrorAbstraction { constructor(code: string, message: string) { super(Error.prototype.name, code, message); } } export class NodeSyntaxError extends NodeErrorAbstraction implements SyntaxError { constructor(code: string, message: string) { super(SyntaxError.prototype.name, code, message); Object.setPrototypeOf(this, SyntaxError.prototype); this.toString = function () { return `${this.name} [${this.code}]: ${this.message}`; }; } } export class NodeRangeError extends NodeErrorAbstraction { constructor(code: string, message: string) { super(RangeError.prototype.name, code, message); Object.setPrototypeOf(this, RangeError.prototype); this.toString = function () { return `${this.name} [${this.code}]: ${this.message}`; }; } } export class NodeTypeError extends NodeErrorAbstraction implements TypeError { constructor(code: string, message: string) { super(TypeError.prototype.name, code, message); Object.setPrototypeOf(this, TypeError.prototype); this.toString = function () { return `${this.name} [${this.code}]: ${this.message}`; }; } } export class NodeURIError extends NodeErrorAbstraction implements URIError { constructor(code: string, message: string) { super(URIError.prototype.name, code, message); Object.setPrototypeOf(this, URIError.prototype); this.toString = function () { return `${this.name} [${this.code}]: ${this.message}`; }; } } export class ERR_INVALID_ARG_TYPE extends NodeTypeError { constructor(name: string, expected: string | string[], actual: unknown) { // https://github.com/nodejs/node/blob/f3eb224/lib/internal/errors.js#L1037-L1087 expected = Array.isArray(expected) ? expected : [expected]; let msg = "The "; if (name.endsWith(" argument")) { // For cases like 'first argument' msg += `${name} `; } else { const type = name.includes(".") ? "property" : "argument"; msg += `"${name}" ${type} `; } msg += "must be "; const types = []; const instances = []; const other = []; for (const value of expected) { if (kTypes.includes(value)) { types.push(value.toLocaleLowerCase()); } else if (classRegExp.test(value)) { instances.push(value); } else { other.push(value); } } // Special handle `object` in case other instances are allowed to outline // the differences between each other. if (instances.length > 0) { const pos = types.indexOf("object"); if (pos !== -1) { types.splice(pos, 1); instances.push("Object"); } } if (types.length > 0) { if (types.length > 2) { const last = types.pop(); msg += `one of type ${types.join(", ")}, or ${last}`; } else if (types.length === 2) { msg += `one of type ${types[0]} or ${types[1]}`; } else { msg += `of type ${types[0]}`; } if (instances.length > 0 || other.length > 0) { msg += " or "; } } if (instances.length > 0) { if (instances.length > 2) { const last = instances.pop(); msg += `an instance of ${instances.join(", ")}, or ${last}`; } else { msg += `an instance of ${instances[0]}`; if (instances.length === 2) { msg += ` or ${instances[1]}`; } } if (other.length > 0) { msg += " or "; } } if (other.length > 0) { if (other.length > 2) { const last = other.pop(); msg += `one of ${other.join(", ")}, or ${last}`; } else if (other.length === 2) { msg += `one of ${other[0]} or ${other[1]}`; } else { if (other[0].toLowerCase() !== other[0]) { msg += "an "; } msg += `${other[0]}`; } } super( "ERR_INVALID_ARG_TYPE", `${msg}.${invalidArgTypeHelper(actual)}`, ); } } export class ERR_INVALID_ARG_VALUE extends NodeTypeError { constructor(name: string, value: unknown, reason: string = "is invalid") { const type = name.includes(".") ? "property" : "argument"; const inspected = inspect(value); super( "ERR_INVALID_ARG_VALUE", `The ${type} '${name}' ${reason}. Received ${inspected}`, ); } } // A helper function to simplify checking for ERR_INVALID_ARG_TYPE output. // deno-lint-ignore no-explicit-any function invalidArgTypeHelper(input: any) { if (input == null) { return ` Received ${input}`; } if (typeof input === "function" && input.name) { return ` Received function ${input.name}`; } if (typeof input === "object") { if (input.constructor && input.constructor.name) { return ` Received an instance of ${input.constructor.name}`; } return ` Received ${inspect(input, { depth: -1 })}`; } let inspected = inspect(input, { colors: false }); if (inspected.length > 25) { inspected = `${inspected.slice(0, 25)}...`; } return ` Received type ${typeof input} (${inspected})`; } export class ERR_OUT_OF_RANGE extends RangeError { code = "ERR_OUT_OF_RANGE"; constructor(str: string, range: string, received: unknown) { super( `The value of "${str}" is out of range. It must be ${range}. Received ${received}`, ); const { name } = this; // Add the error code to the name to include it in the stack trace. this.name = `${name} [${this.code}]`; // Access the stack to generate the error message including the error code from the name. this.stack; // Reset the name to the actual name. this.name = name; } } export class ERR_AMBIGUOUS_ARGUMENT extends NodeTypeError { constructor(x: string, y: string) { super("ERR_AMBIGUOUS_ARGUMENT", `The "${x}" argument is ambiguous. ${y}`); } } export class ERR_ARG_NOT_ITERABLE extends NodeTypeError { constructor(x: string) { super("ERR_ARG_NOT_ITERABLE", `${x} must be iterable`); } } export class ERR_ASSERTION extends NodeError { constructor(x: string) { super("ERR_ASSERTION", `${x}`); } } export class ERR_ASYNC_CALLBACK extends NodeTypeError { constructor(x: string) { super("ERR_ASYNC_CALLBACK", `${x} must be a function`); } } export class ERR_ASYNC_TYPE extends NodeTypeError { constructor(x: string) { super("ERR_ASYNC_TYPE", `Invalid name for async "type": ${x}`); } } export class ERR_BROTLI_INVALID_PARAM extends NodeRangeError { constructor(x: string) { super("ERR_BROTLI_INVALID_PARAM", `${x} is not a valid Brotli parameter`); } } export class ERR_BUFFER_OUT_OF_BOUNDS extends NodeRangeError { constructor(name?: string) { super( "ERR_BUFFER_OUT_OF_BOUNDS", name ? `"${name}" is outside of buffer bounds` : "Attempt to access memory outside buffer bounds", ); } } export class ERR_BUFFER_TOO_LARGE extends NodeRangeError { constructor(x: string) { super( "ERR_BUFFER_TOO_LARGE", `Cannot create a Buffer larger than ${x} bytes`, ); } } export class ERR_CANNOT_WATCH_SIGINT extends NodeError { constructor() { super( "ERR_CANNOT_WATCH_SIGINT", "Cannot watch for SIGINT signals", ); } } export class ERR_CHILD_CLOSED_BEFORE_REPLY extends NodeError { constructor() { super( "ERR_CHILD_CLOSED_BEFORE_REPLY", "Child closed before reply received", ); } } export class ERR_CHILD_PROCESS_IPC_REQUIRED extends NodeError { constructor(x: string) { super( "ERR_CHILD_PROCESS_IPC_REQUIRED", `Forked processes must have an IPC channel, missing value 'ipc' in ${x}`, ); } } export class ERR_CHILD_PROCESS_STDIO_MAXBUFFER extends NodeRangeError { constructor(x: string) { super( "ERR_CHILD_PROCESS_STDIO_MAXBUFFER", `${x} maxBuffer length exceeded`, ); } } export class ERR_CONSOLE_WRITABLE_STREAM extends NodeTypeError { constructor(x: string) { super( "ERR_CONSOLE_WRITABLE_STREAM", `Console expects a writable stream instance for ${x}`, ); } } export class ERR_CONTEXT_NOT_INITIALIZED extends NodeError { constructor() { super( "ERR_CONTEXT_NOT_INITIALIZED", "context used is not initialized", ); } } export class ERR_CPU_USAGE extends NodeError { constructor(x: string) { super( "ERR_CPU_USAGE", `Unable to obtain cpu usage ${x}`, ); } } export class ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED extends NodeError { constructor() { super( "ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED", "Custom engines not supported by this OpenSSL", ); } } export class ERR_CRYPTO_ECDH_INVALID_FORMAT extends NodeTypeError { constructor(x: string) { super( "ERR_CRYPTO_ECDH_INVALID_FORMAT", `Invalid ECDH format: ${x}`, ); } } export class ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY extends NodeError { constructor() { super( "ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY", "Public key is not valid for specified curve", ); } } export class ERR_CRYPTO_ENGINE_UNKNOWN extends NodeError { constructor(x: string) { super( "ERR_CRYPTO_ENGINE_UNKNOWN", `Engine "${x}" was not found`, ); } } export class ERR_CRYPTO_FIPS_FORCED extends NodeError { constructor() { super( "ERR_CRYPTO_FIPS_FORCED", "Cannot set FIPS mode, it was forced with --force-fips at startup.", ); } } export class ERR_CRYPTO_FIPS_UNAVAILABLE extends NodeError { constructor() { super( "ERR_CRYPTO_FIPS_UNAVAILABLE", "Cannot set FIPS mode in a non-FIPS build.", ); } } export class ERR_CRYPTO_HASH_FINALIZED extends NodeError { constructor() { super( "ERR_CRYPTO_HASH_FINALIZED", "Digest already called", ); } } export class ERR_CRYPTO_HASH_UPDATE_FAILED extends NodeError { constructor() { super( "ERR_CRYPTO_HASH_UPDATE_FAILED", "Hash update failed", ); } } export class ERR_CRYPTO_INCOMPATIBLE_KEY extends NodeError { constructor(x: string, y: string) { super( "ERR_CRYPTO_INCOMPATIBLE_KEY", `Incompatible ${x}: ${y}`, ); } } export class ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS extends NodeError { constructor(x: string, y: string) { super( "ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS", `The selected key encoding ${x} ${y}.`, ); } } export class ERR_CRYPTO_INVALID_DIGEST extends NodeTypeError { constructor(x: string) { super( "ERR_CRYPTO_INVALID_DIGEST", `Invalid digest: ${x}`, ); } } export class ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE extends NodeTypeError { constructor(x: string, y: string) { super( "ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE", `Invalid key object type ${x}, expected ${y}.`, ); } } export class ERR_CRYPTO_INVALID_STATE extends NodeError { constructor(x: string) { super( "ERR_CRYPTO_INVALID_STATE", `Invalid state for operation ${x}`, ); } } export class ERR_CRYPTO_PBKDF2_ERROR extends NodeError { constructor() { super( "ERR_CRYPTO_PBKDF2_ERROR", "PBKDF2 error", ); } } export class ERR_CRYPTO_SCRYPT_INVALID_PARAMETER extends NodeError { constructor() { super( "ERR_CRYPTO_SCRYPT_INVALID_PARAMETER", "Invalid scrypt parameter", ); } } export class ERR_CRYPTO_SCRYPT_NOT_SUPPORTED extends NodeError { constructor() { super( "ERR_CRYPTO_SCRYPT_NOT_SUPPORTED", "Scrypt algorithm not supported", ); } } export class ERR_CRYPTO_SIGN_KEY_REQUIRED extends NodeError { constructor() { super( "ERR_CRYPTO_SIGN_KEY_REQUIRED", "No key provided to sign", ); } } export class ERR_DIR_CLOSED extends NodeError { constructor() { super( "ERR_DIR_CLOSED", "Directory handle was closed", ); } } export class ERR_DIR_CONCURRENT_OPERATION extends NodeError { constructor() { super( "ERR_DIR_CONCURRENT_OPERATION", "Cannot do synchronous work on directory handle with concurrent asynchronous operations", ); } } export class ERR_DNS_SET_SERVERS_FAILED extends NodeError { constructor(x: string, y: string) { super( "ERR_DNS_SET_SERVERS_FAILED", `c-ares failed to set servers: "${x}" [${y}]`, ); } } export class ERR_DOMAIN_CALLBACK_NOT_AVAILABLE extends NodeError { constructor() { super( "ERR_DOMAIN_CALLBACK_NOT_AVAILABLE", "A callback was registered through " + "process.setUncaughtExceptionCaptureCallback(), which is mutually " + "exclusive with using the `domain` module", ); } } export class ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE extends NodeError { constructor() { super( "ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE", "The `domain` module is in use, which is mutually exclusive with calling " + "process.setUncaughtExceptionCaptureCallback()", ); } } export class ERR_ENCODING_INVALID_ENCODED_DATA extends NodeErrorAbstraction implements TypeError { errno: number; constructor(encoding: string, ret: number) { super( TypeError.prototype.name, "ERR_ENCODING_INVALID_ENCODED_DATA", `The encoded data was not valid for encoding ${encoding}`, ); Object.setPrototypeOf(this, TypeError.prototype); this.errno = ret; } } export class ERR_ENCODING_NOT_SUPPORTED extends NodeRangeError { constructor(x: string) { super( "ERR_ENCODING_NOT_SUPPORTED", `The "${x}" encoding is not supported`, ); } } export class ERR_EVAL_ESM_CANNOT_PRINT extends NodeError { constructor() { super( "ERR_EVAL_ESM_CANNOT_PRINT", `--print cannot be used with ESM input`, ); } } export class ERR_EVENT_RECURSION extends NodeError { constructor(x: string) { super( "ERR_EVENT_RECURSION", `The event "${x}" is already being dispatched`, ); } } export class ERR_FEATURE_UNAVAILABLE_ON_PLATFORM extends NodeTypeError { constructor(x: string) { super( "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM", `The feature ${x} is unavailable on the current platform, which is being used to run Node.js`, ); } } export class ERR_FS_FILE_TOO_LARGE extends NodeRangeError { constructor(x: string) { super( "ERR_FS_FILE_TOO_LARGE", `File size (${x}) is greater than 2 GB`, ); } } export class ERR_FS_INVALID_SYMLINK_TYPE extends NodeError { constructor(x: string) { super( "ERR_FS_INVALID_SYMLINK_TYPE", `Symlink type must be one of "dir", "file", or "junction". Received "${x}"`, ); } } export class ERR_HTTP2_ALTSVC_INVALID_ORIGIN extends NodeTypeError { constructor() { super( "ERR_HTTP2_ALTSVC_INVALID_ORIGIN", `HTTP/2 ALTSVC frames require a valid origin`, ); } } export class ERR_HTTP2_ALTSVC_LENGTH extends NodeTypeError { constructor() { super( "ERR_HTTP2_ALTSVC_LENGTH", `HTTP/2 ALTSVC frames are limited to 16382 bytes`, ); } } export class ERR_HTTP2_CONNECT_AUTHORITY extends NodeError { constructor() { super( "ERR_HTTP2_CONNECT_AUTHORITY", `:authority header is required for CONNECT requests`, ); } } export class ERR_HTTP2_CONNECT_PATH extends NodeError { constructor() { super( "ERR_HTTP2_CONNECT_PATH", `The :path header is forbidden for CONNECT requests`, ); } } export class ERR_HTTP2_CONNECT_SCHEME extends NodeError { constructor() { super( "ERR_HTTP2_CONNECT_SCHEME", `The :scheme header is forbidden for CONNECT requests`, ); } } export class ERR_HTTP2_GOAWAY_SESSION extends NodeError { constructor() { super( "ERR_HTTP2_GOAWAY_SESSION", `New streams cannot be created after receiving a GOAWAY`, ); } } export class ERR_HTTP2_HEADERS_AFTER_RESPOND extends NodeError { constructor() { super( "ERR_HTTP2_HEADERS_AFTER_RESPOND", `Cannot specify additional headers after response initiated`, ); } } export class ERR_HTTP2_HEADERS_SENT extends NodeError { constructor() { super( "ERR_HTTP2_HEADERS_SENT", `Response has already been initiated.`, ); } } export class ERR_HTTP2_HEADER_SINGLE_VALUE extends NodeTypeError { constructor(x: string) { super( "ERR_HTTP2_HEADER_SINGLE_VALUE", `Header field "${x}" must only have a single value`, ); } } export class ERR_HTTP2_INFO_STATUS_NOT_ALLOWED extends NodeRangeError { constructor() { super( "ERR_HTTP2_INFO_STATUS_NOT_ALLOWED", `Informational status codes cannot be used`, ); } } export class ERR_HTTP2_INVALID_CONNECTION_HEADERS extends NodeTypeError { constructor(x: string) { super( "ERR_HTTP2_INVALID_CONNECTION_HEADERS", `HTTP/1 Connection specific headers are forbidden: "${x}"`, ); } } export class ERR_HTTP2_INVALID_HEADER_VALUE extends NodeTypeError { constructor(x: string, y: string) { super( "ERR_HTTP2_INVALID_HEADER_VALUE", `Invalid value "${x}" for header "${y}"`, ); } } export class ERR_HTTP2_INVALID_INFO_STATUS extends NodeRangeError { constructor(x: string) { super( "ERR_HTTP2_INVALID_INFO_STATUS", `Invalid informational status code: ${x}`, ); } } export class ERR_HTTP2_INVALID_ORIGIN extends NodeTypeError { constructor() { super( "ERR_HTTP2_INVALID_ORIGIN", `HTTP/2 ORIGIN frames require a valid origin`, ); } } export class ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH extends NodeRangeError { constructor() { super( "ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH", `Packed settings length must be a multiple of six`, ); } } export class ERR_HTTP2_INVALID_PSEUDOHEADER extends NodeTypeError { constructor(x: string) { super( "ERR_HTTP2_INVALID_PSEUDOHEADER", `"${x}" is an invalid pseudoheader or is used incorrectly`, ); } } export class ERR_HTTP2_INVALID_SESSION extends NodeError { constructor() { super( "ERR_HTTP2_INVALID_SESSION", `The session has been destroyed`, ); } } export class ERR_HTTP2_INVALID_STREAM extends NodeError { constructor() { super( "ERR_HTTP2_INVALID_STREAM", `The stream has been destroyed`, ); } } export class ERR_HTTP2_MAX_PENDING_SETTINGS_ACK extends NodeError { constructor() { super( "ERR_HTTP2_MAX_PENDING_SETTINGS_ACK", `Maximum number of pending settings acknowledgements`, ); } } export class ERR_HTTP2_NESTED_PUSH extends NodeError { constructor() { super( "ERR_HTTP2_NESTED_PUSH", `A push stream cannot initiate another push stream.`, ); } } export class ERR_HTTP2_NO_SOCKET_MANIPULATION extends NodeError { constructor() { super( "ERR_HTTP2_NO_SOCKET_MANIPULATION", `HTTP/2 sockets should not be directly manipulated (e.g. read and written)`, ); } } export class ERR_HTTP2_ORIGIN_LENGTH extends NodeTypeError { constructor() { super( "ERR_HTTP2_ORIGIN_LENGTH", `HTTP/2 ORIGIN frames are limited to 16382 bytes`, ); } } export class ERR_HTTP2_OUT_OF_STREAMS extends NodeError { constructor() { super( "ERR_HTTP2_OUT_OF_STREAMS", `No stream ID is available because maximum stream ID has been reached`, ); } } export class ERR_HTTP2_PAYLOAD_FORBIDDEN extends NodeError { constructor(x: string) { super( "ERR_HTTP2_PAYLOAD_FORBIDDEN", `Responses with ${x} status must not have a payload`, ); } } export class ERR_HTTP2_PING_CANCEL extends NodeError { constructor() { super( "ERR_HTTP2_PING_CANCEL", `HTTP2 ping cancelled`, ); } } export class ERR_HTTP2_PING_LENGTH extends NodeRangeError { constructor() { super( "ERR_HTTP2_PING_LENGTH", `HTTP2 ping payload must be 8 bytes`, ); } } export class ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED extends NodeTypeError { constructor() { super( "ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED", `Cannot set HTTP/2 pseudo-headers`, ); } } export class ERR_HTTP2_PUSH_DISABLED extends NodeError { constructor() { super( "ERR_HTTP2_PUSH_DISABLED", `HTTP/2 client has disabled push streams`, ); } } export class ERR_HTTP2_SEND_FILE extends NodeError { constructor() { super( "ERR_HTTP2_SEND_FILE", `Directories cannot be sent`, ); } } export class ERR_HTTP2_SEND_FILE_NOSEEK extends NodeError { constructor() { super( "ERR_HTTP2_SEND_FILE_NOSEEK", `Offset or length can only be specified for regular files`, ); } } export class ERR_HTTP2_SESSION_ERROR extends NodeError { constructor(x: string) { super( "ERR_HTTP2_SESSION_ERROR", `Session closed with error code ${x}`, ); } } export class ERR_HTTP2_SETTINGS_CANCEL extends NodeError { constructor() { super( "ERR_HTTP2_SETTINGS_CANCEL", `HTTP2 session settings canceled`, ); } } export class ERR_HTTP2_SOCKET_BOUND extends NodeError { constructor() { super( "ERR_HTTP2_SOCKET_BOUND", `The socket is already bound to an Http2Session`, ); } } export class ERR_HTTP2_SOCKET_UNBOUND extends NodeError { constructor() { super( "ERR_HTTP2_SOCKET_UNBOUND", `The socket has been disconnected from the Http2Session`, ); } } export class ERR_HTTP2_STATUS_101 extends NodeError { constructor() { super( "ERR_HTTP2_STATUS_101", `HTTP status code 101 (Switching Protocols) is forbidden in HTTP/2`, ); } } export class ERR_HTTP2_STATUS_INVALID extends NodeRangeError { constructor(x: string) { super( "ERR_HTTP2_STATUS_INVALID", `Invalid status code: ${x}`, ); } } export class ERR_HTTP2_STREAM_ERROR extends NodeError { constructor(x: string) { super( "ERR_HTTP2_STREAM_ERROR", `Stream closed with error code ${x}`, ); } } export class ERR_HTTP2_STREAM_SELF_DEPENDENCY extends NodeError { constructor() { super( "ERR_HTTP2_STREAM_SELF_DEPENDENCY", `A stream cannot depend on itself`, ); } } export class ERR_HTTP2_TRAILERS_ALREADY_SENT extends NodeError { constructor() { super( "ERR_HTTP2_TRAILERS_ALREADY_SENT", `Trailing headers have already been sent`, ); } } export class ERR_HTTP2_TRAILERS_NOT_READY extends NodeError { constructor() { super( "ERR_HTTP2_TRAILERS_NOT_READY", `Trailing headers cannot be sent until after the wantTrailers event is emitted`, ); } } export class ERR_HTTP2_UNSUPPORTED_PROTOCOL extends NodeError { constructor(x: string) { super( "ERR_HTTP2_UNSUPPORTED_PROTOCOL", `protocol "${x}" is unsupported.`, ); } } export class ERR_HTTP_HEADERS_SENT extends NodeError { constructor(x: string) { super( "ERR_HTTP_HEADERS_SENT", `Cannot ${x} headers after they are sent to the client`, ); } } export class ERR_HTTP_INVALID_HEADER_VALUE extends NodeTypeError { constructor(x: string, y: string) { super( "ERR_HTTP_INVALID_HEADER_VALUE", `Invalid value "${x}" for header "${y}"`, ); } } export class ERR_HTTP_INVALID_STATUS_CODE extends NodeRangeError { constructor(x: string) { super( "ERR_HTTP_INVALID_STATUS_CODE", `Invalid status code: ${x}`, ); } } export class ERR_HTTP_SOCKET_ENCODING extends NodeError { constructor() { super( "ERR_HTTP_SOCKET_ENCODING", `Changing the socket encoding is not allowed per RFC7230 Section 3.`, ); } } export class ERR_HTTP_TRAILER_INVALID extends NodeError { constructor() { super( "ERR_HTTP_TRAILER_INVALID", `Trailers are invalid with this transfer encoding`, ); } } export class ERR_INCOMPATIBLE_OPTION_PAIR extends NodeTypeError { constructor(x: string, y: string) { super( "ERR_INCOMPATIBLE_OPTION_PAIR", `Option "${x}" cannot be used in combination with option "${y}"`, ); } } export class ERR_INPUT_TYPE_NOT_ALLOWED extends NodeError { constructor() { super( "ERR_INPUT_TYPE_NOT_ALLOWED", `--input-type can only be used with string input via --eval, --print, or STDIN`, ); } } export class ERR_INSPECTOR_ALREADY_ACTIVATED extends NodeError { constructor() { super( "ERR_INSPECTOR_ALREADY_ACTIVATED", `Inspector is already activated. Close it with inspector.close() before activating it again.`, ); } } export class ERR_INSPECTOR_ALREADY_CONNECTED extends NodeError { constructor(x: string) { super( "ERR_INSPECTOR_ALREADY_CONNECTED", `${x} is already connected`, ); } } export class ERR_INSPECTOR_CLOSED extends NodeError { constructor() { super( "ERR_INSPECTOR_CLOSED", `Session was closed`, ); } } export class ERR_INSPECTOR_COMMAND extends NodeError { constructor(x: number, y: string) { super( "ERR_INSPECTOR_COMMAND", `Inspector error ${x}: ${y}`, ); } } export class ERR_INSPECTOR_NOT_ACTIVE extends NodeError { constructor() { super( "ERR_INSPECTOR_NOT_ACTIVE", `Inspector is not active`, ); } } export class ERR_INSPECTOR_NOT_AVAILABLE extends NodeError { constructor() { super( "ERR_INSPECTOR_NOT_AVAILABLE", `Inspector is not available`, ); } } export class ERR_INSPECTOR_NOT_CONNECTED extends NodeError { constructor() { super( "ERR_INSPECTOR_NOT_CONNECTED", `Session is not connected`, ); } } export class ERR_INSPECTOR_NOT_WORKER extends NodeError { constructor() { super( "ERR_INSPECTOR_NOT_WORKER", `Current thread is not a worker`, ); } } export class ERR_INVALID_ASYNC_ID extends NodeRangeError { constructor(x: string, y: string) { super( "ERR_INVALID_ASYNC_ID", `Invalid ${x} value: ${y}`, ); } } export class ERR_INVALID_BUFFER_SIZE extends NodeRangeError { constructor(x: string) { super( "ERR_INVALID_BUFFER_SIZE", `Buffer size must be a multiple of ${x}`, ); } } export class ERR_INVALID_CALLBACK extends NodeTypeError { constructor(object: unknown) { super( "ERR_INVALID_CALLBACK", `Callback must be a function. Received ${inspect(object)}`, ); } } export class ERR_INVALID_CURSOR_POS extends NodeTypeError { constructor() { super( "ERR_INVALID_CURSOR_POS", `Cannot set cursor row without setting its column`, ); } } export class ERR_INVALID_FD extends NodeRangeError { constructor(x: string) { super( "ERR_INVALID_FD", `"fd" must be a positive integer: ${x}`, ); } } export class ERR_INVALID_FD_TYPE extends NodeTypeError { constructor(x: string) { super( "ERR_INVALID_FD_TYPE", `Unsupported fd type: ${x}`, ); } } export class ERR_INVALID_FILE_URL_HOST extends NodeTypeError { constructor(x: string) { super( "ERR_INVALID_FILE_URL_HOST", `File URL host must be "localhost" or empty on ${x}`, ); } } export class ERR_INVALID_FILE_URL_PATH extends NodeTypeError { constructor(x: string) { super( "ERR_INVALID_FILE_URL_PATH", `File URL path ${x}`, ); } } export class ERR_INVALID_HANDLE_TYPE extends NodeTypeError { constructor() { super( "ERR_INVALID_HANDLE_TYPE", `This handle type cannot be sent`, ); } } export class ERR_INVALID_HTTP_TOKEN extends NodeTypeError { constructor(x: string, y: string) { super( "ERR_INVALID_HTTP_TOKEN", `${x} must be a valid HTTP token ["${y}"]`, ); } } export class ERR_INVALID_IP_ADDRESS extends NodeTypeError { constructor(x: string) { super( "ERR_INVALID_IP_ADDRESS", `Invalid IP address: ${x}`, ); } } export class ERR_INVALID_OPT_VALUE_ENCODING extends NodeTypeError { constructor(x: string) { super( "ERR_INVALID_OPT_VALUE_ENCODING", `The value "${x}" is invalid for option "encoding"`, ); } } export class ERR_INVALID_PERFORMANCE_MARK extends NodeError { constructor(x: string) { super( "ERR_INVALID_PERFORMANCE_MARK", `The "${x}" performance mark has not been set`, ); } } export class ERR_INVALID_PROTOCOL extends NodeTypeError { constructor(x: string, y: string) { super( "ERR_INVALID_PROTOCOL", `Protocol "${x}" not supported. Expected "${y}"`, ); } } export class ERR_INVALID_REPL_EVAL_CONFIG extends NodeTypeError { constructor() { super( "ERR_INVALID_REPL_EVAL_CONFIG", `Cannot specify both "breakEvalOnSigint" and "eval" for REPL`, ); } } export class ERR_INVALID_REPL_INPUT extends NodeTypeError { constructor(x: string) { super( "ERR_INVALID_REPL_INPUT", `${x}`, ); } } export class ERR_INVALID_SYNC_FORK_INPUT extends NodeTypeError { constructor(x: string) { super( "ERR_INVALID_SYNC_FORK_INPUT", `Asynchronous forks do not support Buffer, TypedArray, DataView or string input: ${x}`, ); } } export class ERR_INVALID_THIS extends NodeTypeError { constructor(x: string) { super( "ERR_INVALID_THIS", `Value of "this" must be of type ${x}`, ); } } export class ERR_INVALID_TUPLE extends NodeTypeError { constructor(x: string, y: string) { super( "ERR_INVALID_TUPLE", `${x} must be an iterable ${y} tuple`, ); } } export class ERR_INVALID_URI extends NodeURIError { constructor() { super( "ERR_INVALID_URI", `URI malformed`, ); } } export class ERR_IPC_CHANNEL_CLOSED extends NodeError { constructor() { super( "ERR_IPC_CHANNEL_CLOSED", `Channel closed`, ); } } export class ERR_IPC_DISCONNECTED extends NodeError { constructor() { super( "ERR_IPC_DISCONNECTED", `IPC channel is already disconnected`, ); } } export class ERR_IPC_ONE_PIPE extends NodeError { constructor() { super( "ERR_IPC_ONE_PIPE", `Child process can have only one IPC pipe`, ); } } export class ERR_IPC_SYNC_FORK extends NodeError { constructor() { super( "ERR_IPC_SYNC_FORK", `IPC cannot be used with synchronous forks`, ); } } export class ERR_MANIFEST_DEPENDENCY_MISSING extends NodeError { constructor(x: string, y: string) { super( "ERR_MANIFEST_DEPENDENCY_MISSING", `Manifest resource ${x} does not list ${y} as a dependency specifier`, ); } } export class ERR_MANIFEST_INTEGRITY_MISMATCH extends NodeSyntaxError { constructor(x: string) { super( "ERR_MANIFEST_INTEGRITY_MISMATCH", `Manifest resource ${x} has multiple entries but integrity lists do not match`, ); } } export class ERR_MANIFEST_INVALID_RESOURCE_FIELD extends NodeTypeError { constructor(x: string, y: string) { super( "ERR_MANIFEST_INVALID_RESOURCE_FIELD", `Manifest resource ${x} has invalid property value for ${y}`, ); } } export class ERR_MANIFEST_TDZ extends NodeError { constructor() { super( "ERR_MANIFEST_TDZ", `Manifest initialization has not yet run`, ); } } export class ERR_MANIFEST_UNKNOWN_ONERROR extends NodeSyntaxError { constructor(x: string) { super( "ERR_MANIFEST_UNKNOWN_ONERROR", `Manifest specified unknown error behavior "${x}".`, ); } } export class ERR_METHOD_NOT_IMPLEMENTED extends NodeError { constructor(x: string) { super( "ERR_METHOD_NOT_IMPLEMENTED", `The ${x} method is not implemented`, ); } } export class ERR_MISSING_ARGS extends NodeTypeError { constructor(...args: (string | string[])[]) { let msg = "The "; const len = args.length; const wrap = (a: unknown) => `"${a}"`; args = args.map( (a) => (Array.isArray(a) ? a.map(wrap).join(" or ") : wrap(a)), ); switch (len) { case 1: msg += `${args[0]} argument`; break; case 2: msg += `${args[0]} and ${args[1]} arguments`; break; default: msg += args.slice(0, len - 1).join(", "); msg += `, and ${args[len - 1]} arguments`; break; } super( "ERR_MISSING_ARGS", `${msg} must be specified`, ); } } export class ERR_MISSING_OPTION extends NodeTypeError { constructor(x: string) { super( "ERR_MISSING_OPTION", `${x} is required`, ); } } export class ERR_MULTIPLE_CALLBACK extends NodeError { constructor() { super( "ERR_MULTIPLE_CALLBACK", `Callback called multiple times`, ); } } export class ERR_NAPI_CONS_FUNCTION extends NodeTypeError { constructor() { super( "ERR_NAPI_CONS_FUNCTION", `Constructor must be a function`, ); } } export class ERR_NAPI_INVALID_DATAVIEW_ARGS extends NodeRangeError { constructor() { super( "ERR_NAPI_INVALID_DATAVIEW_ARGS", `byte_offset + byte_length should be less than or equal to the size in bytes of the array passed in`, ); } } export class ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT extends NodeRangeError { constructor(x: string, y: string) { super( "ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT", `start offset of ${x} should be a multiple of ${y}`, ); } } export class ERR_NAPI_INVALID_TYPEDARRAY_LENGTH extends NodeRangeError { constructor() { super( "ERR_NAPI_INVALID_TYPEDARRAY_LENGTH", `Invalid typed array length`, ); } } export class ERR_NO_CRYPTO extends NodeError { constructor() { super( "ERR_NO_CRYPTO", `Node.js is not compiled with OpenSSL crypto support`, ); } } export class ERR_NO_ICU extends NodeTypeError { constructor(x: string) { super( "ERR_NO_ICU", `${x} is not supported on Node.js compiled without ICU`, ); } } export class ERR_QUICCLIENTSESSION_FAILED extends NodeError { constructor(x: string) { super( "ERR_QUICCLIENTSESSION_FAILED", `Failed to create a new QuicClientSession: ${x}`, ); } } export class ERR_QUICCLIENTSESSION_FAILED_SETSOCKET extends NodeError { constructor() { super( "ERR_QUICCLIENTSESSION_FAILED_SETSOCKET", `Failed to set the QuicSocket`, ); } } export class ERR_QUICSESSION_DESTROYED extends NodeError { constructor(x: string) { super( "ERR_QUICSESSION_DESTROYED", `Cannot call ${x} after a QuicSession has been destroyed`, ); } } export class ERR_QUICSESSION_INVALID_DCID extends NodeError { constructor(x: string) { super( "ERR_QUICSESSION_INVALID_DCID", `Invalid DCID value: ${x}`, ); } } export class ERR_QUICSESSION_UPDATEKEY extends NodeError { constructor() { super( "ERR_QUICSESSION_UPDATEKEY", `Unable to update QuicSession keys`, ); } } export class ERR_QUICSOCKET_DESTROYED extends NodeError { constructor(x: string) { super( "ERR_QUICSOCKET_DESTROYED", `Cannot call ${x} after a QuicSocket has been destroyed`, ); } } export class ERR_QUICSOCKET_INVALID_STATELESS_RESET_SECRET_LENGTH extends NodeError { constructor() { super( "ERR_QUICSOCKET_INVALID_STATELESS_RESET_SECRET_LENGTH", `The stateResetToken must be exactly 16-bytes in length`, ); } } export class ERR_QUICSOCKET_LISTENING extends NodeError { constructor() { super( "ERR_QUICSOCKET_LISTENING", `This QuicSocket is already listening`, ); } } export class ERR_QUICSOCKET_UNBOUND extends NodeError { constructor(x: string) { super( "ERR_QUICSOCKET_UNBOUND", `Cannot call ${x} before a QuicSocket has been bound`, ); } } export class ERR_QUICSTREAM_DESTROYED extends NodeError { constructor(x: string) { super( "ERR_QUICSTREAM_DESTROYED", `Cannot call ${x} after a QuicStream has been destroyed`, ); } } export class ERR_QUICSTREAM_INVALID_PUSH extends NodeError { constructor() { super( "ERR_QUICSTREAM_INVALID_PUSH", `Push streams are only supported on client-initiated, bidirectional streams`, ); } } export class ERR_QUICSTREAM_OPEN_FAILED extends NodeError { constructor() { super( "ERR_QUICSTREAM_OPEN_FAILED", `Opening a new QuicStream failed`, ); } } export class ERR_QUICSTREAM_UNSUPPORTED_PUSH extends NodeError { constructor() { super( "ERR_QUICSTREAM_UNSUPPORTED_PUSH", `Push streams are not supported on this QuicSession`, ); } } export class ERR_QUIC_TLS13_REQUIRED extends NodeError { constructor() { super( "ERR_QUIC_TLS13_REQUIRED", `QUIC requires TLS version 1.3`, ); } } export class ERR_SCRIPT_EXECUTION_INTERRUPTED extends NodeError { constructor() { super( "ERR_SCRIPT_EXECUTION_INTERRUPTED", "Script execution was interrupted by `SIGINT`", ); } } export class ERR_SERVER_ALREADY_LISTEN extends NodeError { constructor() { super( "ERR_SERVER_ALREADY_LISTEN", `Listen method has been called more than once without closing.`, ); } } export class ERR_SERVER_NOT_RUNNING extends NodeError { constructor() { super( "ERR_SERVER_NOT_RUNNING", `Server is not running.`, ); } } export class ERR_SOCKET_ALREADY_BOUND extends NodeError { constructor() { super( "ERR_SOCKET_ALREADY_BOUND", `Socket is already bound`, ); } } export class ERR_SOCKET_BAD_BUFFER_SIZE extends NodeTypeError { constructor() { super( "ERR_SOCKET_BAD_BUFFER_SIZE", `Buffer size must be a positive integer`, ); } } export class ERR_SOCKET_BAD_PORT extends NodeRangeError { constructor(name: string, port: unknown, allowZero = true) { assert( typeof allowZero === "boolean", "The 'allowZero' argument must be of type boolean.", ); const operator = allowZero ? ">=" : ">"; super( "ERR_SOCKET_BAD_PORT", `${name} should be ${operator} 0 and < 65536. Received ${port}.`, ); } } export class ERR_SOCKET_BAD_TYPE extends NodeTypeError { constructor() { super( "ERR_SOCKET_BAD_TYPE", `Bad socket type specified. Valid types are: udp4, udp6`, ); } } export class ERR_SOCKET_CLOSED extends NodeError { constructor() { super( "ERR_SOCKET_CLOSED", `Socket is closed`, ); } } export class ERR_SOCKET_DGRAM_IS_CONNECTED extends NodeError { constructor() { super( "ERR_SOCKET_DGRAM_IS_CONNECTED", `Already connected`, ); } } export class ERR_SOCKET_DGRAM_NOT_CONNECTED extends NodeError { constructor() { super( "ERR_SOCKET_DGRAM_NOT_CONNECTED", `Not connected`, ); } } export class ERR_SOCKET_DGRAM_NOT_RUNNING extends NodeError { constructor() { super( "ERR_SOCKET_DGRAM_NOT_RUNNING", `Not running`, ); } } export class ERR_SRI_PARSE extends NodeSyntaxError { constructor(name: string, char: string, position: number) { super( "ERR_SRI_PARSE", `Subresource Integrity string ${name} had an unexpected ${char} at position ${position}`, ); } } export class ERR_STREAM_ALREADY_FINISHED extends NodeError { constructor(x: string) { super( "ERR_STREAM_ALREADY_FINISHED", `Cannot call ${x} after a stream was finished`, ); } } export class ERR_STREAM_CANNOT_PIPE extends NodeError { constructor() { super( "ERR_STREAM_CANNOT_PIPE", `Cannot pipe, not readable`, ); } } export class ERR_STREAM_DESTROYED extends NodeError { constructor(x: string) { super( "ERR_STREAM_DESTROYED", `Cannot call ${x} after a stream was destroyed`, ); } } export class ERR_STREAM_NULL_VALUES extends NodeTypeError { constructor() { super( "ERR_STREAM_NULL_VALUES", `May not write null values to stream`, ); } } export class ERR_STREAM_PREMATURE_CLOSE extends NodeError { constructor() { super( "ERR_STREAM_PREMATURE_CLOSE", `Premature close`, ); } } export class ERR_STREAM_PUSH_AFTER_EOF extends NodeError { constructor() { super( "ERR_STREAM_PUSH_AFTER_EOF", `stream.push() after EOF`, ); } } export class ERR_STREAM_UNSHIFT_AFTER_END_EVENT extends NodeError { constructor() { super( "ERR_STREAM_UNSHIFT_AFTER_END_EVENT", `stream.unshift() after end event`, ); } } export class ERR_STREAM_WRAP extends NodeError { constructor() { super( "ERR_STREAM_WRAP", `Stream has StringDecoder set or is in objectMode`, ); } } export class ERR_STREAM_WRITE_AFTER_END extends NodeError { constructor() { super( "ERR_STREAM_WRITE_AFTER_END", `write after end`, ); } } export class ERR_SYNTHETIC extends NodeError { constructor() { super( "ERR_SYNTHETIC", `JavaScript Callstack`, ); } } export class ERR_TLS_DH_PARAM_SIZE extends NodeError { constructor(x: string) { super( "ERR_TLS_DH_PARAM_SIZE", `DH parameter size ${x} is less than 2048`, ); } } export class ERR_TLS_HANDSHAKE_TIMEOUT extends NodeError { constructor() { super( "ERR_TLS_HANDSHAKE_TIMEOUT", `TLS handshake timeout`, ); } } export class ERR_TLS_INVALID_CONTEXT extends NodeTypeError { constructor(x: string) { super( "ERR_TLS_INVALID_CONTEXT", `${x} must be a SecureContext`, ); } } export class ERR_TLS_INVALID_STATE extends NodeError { constructor() { super( "ERR_TLS_INVALID_STATE", `TLS socket connection must be securely established`, ); } } export class ERR_TLS_INVALID_PROTOCOL_VERSION extends NodeTypeError { constructor(protocol: string, x: string) { super( "ERR_TLS_INVALID_PROTOCOL_VERSION", `${protocol} is not a valid ${x} TLS protocol version`, ); } } export class ERR_TLS_PROTOCOL_VERSION_CONFLICT extends NodeTypeError { constructor(prevProtocol: string, protocol: string) { super( "ERR_TLS_PROTOCOL_VERSION_CONFLICT", `TLS protocol version ${prevProtocol} conflicts with secureProtocol ${protocol}`, ); } } export class ERR_TLS_RENEGOTIATION_DISABLED extends NodeError { constructor() { super( "ERR_TLS_RENEGOTIATION_DISABLED", `TLS session renegotiation disabled for this socket`, ); } } export class ERR_TLS_REQUIRED_SERVER_NAME extends NodeError { constructor() { super( "ERR_TLS_REQUIRED_SERVER_NAME", `"servername" is required parameter for Server.addContext`, ); } } export class ERR_TLS_SESSION_ATTACK extends NodeError { constructor() { super( "ERR_TLS_SESSION_ATTACK", `TLS session renegotiation attack detected`, ); } } export class ERR_TLS_SNI_FROM_SERVER extends NodeError { constructor() { super( "ERR_TLS_SNI_FROM_SERVER", `Cannot issue SNI from a TLS server-side socket`, ); } } export class ERR_TRACE_EVENTS_CATEGORY_REQUIRED extends NodeTypeError { constructor() { super( "ERR_TRACE_EVENTS_CATEGORY_REQUIRED", `At least one category is required`, ); } } export class ERR_TRACE_EVENTS_UNAVAILABLE extends NodeError { constructor() { super( "ERR_TRACE_EVENTS_UNAVAILABLE", `Trace events are unavailable`, ); } } export class ERR_UNAVAILABLE_DURING_EXIT extends NodeError { constructor() { super( "ERR_UNAVAILABLE_DURING_EXIT", `Cannot call function in process exit handler`, ); } } export class ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET extends NodeError { constructor() { super( "ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET", "`process.setupUncaughtExceptionCapture()` was called while a capture callback was already active", ); } } export class ERR_UNESCAPED_CHARACTERS extends NodeTypeError { constructor(x: string) { super( "ERR_UNESCAPED_CHARACTERS", `${x} contains unescaped characters`, ); } } export class ERR_UNKNOWN_BUILTIN_MODULE extends NodeError { constructor(x: string) { super( "ERR_UNKNOWN_BUILTIN_MODULE", `No such built-in module: ${x}`, ); } } export class ERR_UNKNOWN_CREDENTIAL extends NodeError { constructor(x: string, y: string) { super( "ERR_UNKNOWN_CREDENTIAL", `${x} identifier does not exist: ${y}`, ); } } export class ERR_UNKNOWN_ENCODING extends NodeTypeError { constructor(x: string) { super( "ERR_UNKNOWN_ENCODING", `Unknown encoding: ${x}`, ); } } export class ERR_UNKNOWN_FILE_EXTENSION extends NodeTypeError { constructor(x: string, y: string) { super( "ERR_UNKNOWN_FILE_EXTENSION", `Unknown file extension "${x}" for ${y}`, ); } } export class ERR_UNKNOWN_MODULE_FORMAT extends NodeRangeError { constructor(x: string) { super( "ERR_UNKNOWN_MODULE_FORMAT", `Unknown module format: ${x}`, ); } } export class ERR_UNKNOWN_SIGNAL extends NodeTypeError { constructor(x: string) { super( "ERR_UNKNOWN_SIGNAL", `Unknown signal: ${x}`, ); } } export class ERR_UNSUPPORTED_DIR_IMPORT extends NodeError { constructor(x: string, y: string) { super( "ERR_UNSUPPORTED_DIR_IMPORT", `Directory import '${x}' is not supported resolving ES modules, imported from ${y}`, ); } } export class ERR_UNSUPPORTED_ESM_URL_SCHEME extends NodeError { constructor() { super( "ERR_UNSUPPORTED_ESM_URL_SCHEME", `Only file and data URLs are supported by the default ESM loader`, ); } } export class ERR_V8BREAKITERATOR extends NodeError { constructor() { super( "ERR_V8BREAKITERATOR", `Full ICU data not installed. See https://github.com/nodejs/node/wiki/Intl`, ); } } export class ERR_VALID_PERFORMANCE_ENTRY_TYPE extends NodeError { constructor() { super( "ERR_VALID_PERFORMANCE_ENTRY_TYPE", `At least one valid performance entry type is required`, ); } } export class ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING extends NodeTypeError { constructor() { super( "ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING", `A dynamic import callback was not specified.`, ); } } export class ERR_VM_MODULE_ALREADY_LINKED extends NodeError { constructor() { super( "ERR_VM_MODULE_ALREADY_LINKED", `Module has already been linked`, ); } } export class ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA extends NodeError { constructor() { super( "ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA", `Cached data cannot be created for a module which has been evaluated`, ); } } export class ERR_VM_MODULE_DIFFERENT_CONTEXT extends NodeError { constructor() { super( "ERR_VM_MODULE_DIFFERENT_CONTEXT", `Linked modules must use the same context`, ); } } export class ERR_VM_MODULE_LINKING_ERRORED extends NodeError { constructor() { super( "ERR_VM_MODULE_LINKING_ERRORED", `Linking has already failed for the provided module`, ); } } export class ERR_VM_MODULE_NOT_MODULE extends NodeError { constructor() { super( "ERR_VM_MODULE_NOT_MODULE", `Provided module is not an instance of Module`, ); } } export class ERR_VM_MODULE_STATUS extends NodeError { constructor(x: string) { super( "ERR_VM_MODULE_STATUS", `Module status ${x}`, ); } } export class ERR_WASI_ALREADY_STARTED extends NodeError { constructor() { super( "ERR_WASI_ALREADY_STARTED", `WASI instance has already started`, ); } } export class ERR_WORKER_INIT_FAILED extends NodeError { constructor(x: string) { super( "ERR_WORKER_INIT_FAILED", `Worker initialization failure: ${x}`, ); } } export class ERR_WORKER_NOT_RUNNING extends NodeError { constructor() { super( "ERR_WORKER_NOT_RUNNING", `Worker instance not running`, ); } } export class ERR_WORKER_OUT_OF_MEMORY extends NodeError { constructor(x: string) { super( "ERR_WORKER_OUT_OF_MEMORY", `Worker terminated due to reaching memory limit: ${x}`, ); } } export class ERR_WORKER_UNSERIALIZABLE_ERROR extends NodeError { constructor() { super( "ERR_WORKER_UNSERIALIZABLE_ERROR", `Serializing an uncaught exception failed`, ); } } export class ERR_WORKER_UNSUPPORTED_EXTENSION extends NodeTypeError { constructor(x: string) { super( "ERR_WORKER_UNSUPPORTED_EXTENSION", `The worker script extension must be ".js", ".mjs", or ".cjs". Received "${x}"`, ); } } export class ERR_WORKER_UNSUPPORTED_OPERATION extends NodeTypeError { constructor(x: string) { super( "ERR_WORKER_UNSUPPORTED_OPERATION", `${x} is not supported in workers`, ); } } export class ERR_ZLIB_INITIALIZATION_FAILED extends NodeError { constructor() { super( "ERR_ZLIB_INITIALIZATION_FAILED", `Initialization failed`, ); } } export class ERR_FALSY_VALUE_REJECTION extends NodeError { reason: string; constructor(reason: string) { super( "ERR_FALSY_VALUE_REJECTION", "Promise was rejected with falsy value", ); this.reason = reason; } } export class ERR_HTTP2_INVALID_SETTING_VALUE extends NodeRangeError { actual: unknown; min?: number; max?: number; constructor(name: string, actual: unknown, min?: number, max?: number) { super( "ERR_HTTP2_INVALID_SETTING_VALUE", `Invalid value for setting "${name}": ${actual}`, ); this.actual = actual; if (min !== undefined) { this.min = min; this.max = max; } } } export class ERR_HTTP2_STREAM_CANCEL extends NodeError { cause?: Error; constructor(error: Error) { super( "ERR_HTTP2_STREAM_CANCEL", typeof error.message === "string" ? `The pending stream has been canceled (caused by: ${error.message})` : "The pending stream has been canceled", ); if (error) { this.cause = error; } } } export class ERR_INVALID_ADDRESS_FAMILY extends NodeRangeError { host: string; port: number; constructor(addressType: string, host: string, port: number) { super( "ERR_INVALID_ADDRESS_FAMILY", `Invalid address family: ${addressType} ${host}:${port}`, ); this.host = host; this.port = port; } } export class ERR_INVALID_CHAR extends NodeTypeError { constructor(name: string, field?: string) { super( "ERR_INVALID_CHAR", field ? `Invalid character in ${name}` : `Invalid character in ${name} ["${field}"]`, ); } } export class ERR_INVALID_OPT_VALUE extends NodeTypeError { constructor(name: string, value: unknown) { super( "ERR_INVALID_OPT_VALUE", `The value "${value}" is invalid for option "${name}"`, ); } } export class ERR_INVALID_RETURN_PROPERTY extends NodeTypeError { constructor(input: string, name: string, prop: string, value: string) { super( "ERR_INVALID_RETURN_PROPERTY", `Expected a valid ${input} to be returned for the "${prop}" from the "${name}" function but got ${value}.`, ); } } // deno-lint-ignore no-explicit-any function buildReturnPropertyType(value: any) { if (value && value.constructor && value.constructor.name) { return `instance of ${value.constructor.name}`; } else { return `type ${typeof value}`; } } export class ERR_INVALID_RETURN_PROPERTY_VALUE extends NodeTypeError { constructor(input: string, name: string, prop: string, value: unknown) { super( "ERR_INVALID_RETURN_PROPERTY_VALUE", `Expected ${input} to be returned for the "${prop}" from the "${name}" function but got ${ buildReturnPropertyType(value) }.`, ); } } export class ERR_INVALID_RETURN_VALUE extends NodeTypeError { constructor(input: string, name: string, value: unknown) { super( "ERR_INVALID_RETURN_VALUE", `Expected ${input} to be returned from the "${name}" function but got ${ buildReturnPropertyType(value) }.`, ); } } export class ERR_INVALID_URL extends NodeTypeError { input: string; constructor(input: string) { super( "ERR_INVALID_URL", `Invalid URL: ${input}`, ); this.input = input; } } export class ERR_INVALID_URL_SCHEME extends NodeTypeError { constructor(expected: string | [string] | [string, string]) { expected = Array.isArray(expected) ? expected : [expected]; const res = expected.length === 2 ? `one of scheme ${expected[0]} or ${expected[1]}` : `of scheme ${expected[0]}`; super( "ERR_INVALID_URL_SCHEME", `The URL must be ${res}`, ); } } export class ERR_MODULE_NOT_FOUND extends NodeError { constructor(path: string, base: string, type: string = "package") { super( "ERR_MODULE_NOT_FOUND", `Cannot find ${type} '${path}' imported from ${base}`, ); } } export class ERR_INVALID_PACKAGE_CONFIG extends NodeError { constructor(path: string, base?: string, message?: string) { const msg = `Invalid package config ${path}${ base ? ` while importing ${base}` : "" }${message ? `. ${message}` : ""}`; super("ERR_INVALID_PACKAGE_CONFIG", msg); } } export class ERR_INVALID_MODULE_SPECIFIER extends NodeTypeError { constructor(request: string, reason: string, base?: string) { super( "ERR_INVALID_MODULE_SPECIFIER", `Invalid module "${request}" ${reason}${ base ? ` imported from ${base}` : "" }`, ); } } export class ERR_INVALID_PACKAGE_TARGET extends NodeError { // deno-lint-ignore no-explicit-any constructor( pkgPath: string, key: string, target: any, isImport?: boolean, base?: string, ) { let msg: string; const relError = typeof target === "string" && !isImport && target.length && !target.startsWith("./"); if (key === ".") { assert(isImport === false); msg = `Invalid "exports" main target ${JSON.stringify(target)} defined ` + `in the package config ${pkgPath}package.json${ base ? ` imported from ${base}` : "" }${relError ? '; targets must start with "./"' : ""}`; } else { msg = `Invalid "${isImport ? "imports" : "exports"}" target ${ JSON.stringify(target) } defined for '${key}' in the package config ${pkgPath}package.json${ base ? ` imported from ${base}` : "" }${relError ? '; targets must start with "./"' : ""}`; } super("ERR_INVALID_PACKAGE_TARGET", msg); } } export class ERR_PACKAGE_IMPORT_NOT_DEFINED extends NodeTypeError { constructor( specifier: string, packageJSONUrl: URL | undefined, base: string | URL, ) { const packagePath = packageJSONUrl && fileURLToPath(new URL(".", packageJSONUrl)); const msg = `Package import specifier "${specifier}" is not defined${ packagePath ? ` in package ${packagePath}package.json` : "" } imported from ${fileURLToPath(base)}`; super("ERR_PACKAGE_IMPORT_NOT_DEFINED", msg); } } export class ERR_PACKAGE_PATH_NOT_EXPORTED extends NodeError { constructor( subpath: string, packageJSONUrl: string, base?: string, ) { const pkgPath = fileURLToPath(new URL(".", packageJSONUrl)); const basePath = base && fileURLToPath(base); let msg: string; if (subpath === ".") { msg = `No "exports" main defined in ${pkgPath}package.json${ basePath ? ` imported from ${basePath}` : "" }`; } else { msg = `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${ basePath ? ` imported from ${basePath}` : "" }`; } super("ERR_PACKAGE_PATH_NOT_EXPORTED", msg); } }
the_stack
import { localize } from 'vs/nls'; import { distinct, coalesce } from 'vs/base/common/arrays'; import * as strings from 'vs/base/common/strings'; import { OperatingSystem, Language } from 'vs/base/common/platform'; import { IMatch, IFilter, or, matchesContiguousSubString, matchesPrefix, matchesCamelCase, matchesWords } from 'vs/base/common/filters'; import { Registry } from 'vs/platform/registry/common/platform'; import { ResolvedKeybinding, ResolvedKeybindingPart } from 'vs/base/common/keybindings'; import { AriaLabelProvider, UserSettingsLabelProvider, UILabelProvider, ModifierLabels as ModLabels } from 'vs/base/common/keybindingLabels'; import { MenuRegistry, ILocalizedString, ICommandAction } from 'vs/platform/actions/common/actions'; import { IWorkbenchActionRegistry, Extensions as ActionExtensions } from 'vs/workbench/common/actions'; import { EditorModel } from 'vs/workbench/common/editor/editorModel'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { ResolvedKeybindingItem } from 'vs/platform/keybinding/common/resolvedKeybindingItem'; import { getAllUnboundCommands } from 'vs/workbench/services/keybinding/browser/unboundCommands'; import { IKeybindingItemEntry, KeybindingMatches, KeybindingMatch, IKeybindingItem } from 'vs/workbench/services/preferences/common/preferences'; export const KEYBINDING_ENTRY_TEMPLATE_ID = 'keybinding.entry.template'; const SOURCE_DEFAULT = localize('default', "Default"); const SOURCE_EXTENSION = localize('extension', "Extension"); const SOURCE_USER = localize('user', "User"); interface ModifierLabels { ui: ModLabels; aria: ModLabels; user: ModLabels; } const wordFilter = or(matchesPrefix, matchesWords, matchesContiguousSubString); export class KeybindingsEditorModel extends EditorModel { private _keybindingItems: IKeybindingItem[]; private _keybindingItemsSortedByPrecedence: IKeybindingItem[]; private modifierLabels: ModifierLabels; constructor( os: OperatingSystem, @IKeybindingService private readonly keybindingsService: IKeybindingService ) { super(); this._keybindingItems = []; this._keybindingItemsSortedByPrecedence = []; this.modifierLabels = { ui: UILabelProvider.modifierLabels[os], aria: AriaLabelProvider.modifierLabels[os], user: UserSettingsLabelProvider.modifierLabels[os] }; } fetch(searchValue: string, sortByPrecedence: boolean = false): IKeybindingItemEntry[] { let keybindingItems = sortByPrecedence ? this._keybindingItemsSortedByPrecedence : this._keybindingItems; const commandIdMatches = /@command:\s*(.+)/i.exec(searchValue); if (commandIdMatches && commandIdMatches[1]) { return keybindingItems.filter(k => k.command === commandIdMatches[1]) .map(keybindingItem => (<IKeybindingItemEntry>{ id: KeybindingsEditorModel.getId(keybindingItem), keybindingItem, templateId: KEYBINDING_ENTRY_TEMPLATE_ID })); } if (/@source:\s*(user|default|extension)/i.test(searchValue)) { keybindingItems = this.filterBySource(keybindingItems, searchValue); searchValue = searchValue.replace(/@source:\s*(user|default|extension)/i, ''); } else { const keybindingMatches = /@keybinding:\s*((\".+\")|(\S+))/i.exec(searchValue); if (keybindingMatches && (keybindingMatches[2] || keybindingMatches[3])) { searchValue = keybindingMatches[2] || `"${keybindingMatches[3]}"`; } } searchValue = searchValue.trim(); if (!searchValue) { return keybindingItems.map(keybindingItem => (<IKeybindingItemEntry>{ id: KeybindingsEditorModel.getId(keybindingItem), keybindingItem, templateId: KEYBINDING_ENTRY_TEMPLATE_ID })); } return this.filterByText(keybindingItems, searchValue); } private filterBySource(keybindingItems: IKeybindingItem[], searchValue: string): IKeybindingItem[] { if (/@source:\s*default/i.test(searchValue)) { return keybindingItems.filter(k => k.source === SOURCE_DEFAULT); } if (/@source:\s*user/i.test(searchValue)) { return keybindingItems.filter(k => k.source === SOURCE_USER); } if (/@source:\s*extension/i.test(searchValue)) { return keybindingItems.filter(k => k.source === SOURCE_EXTENSION); } return keybindingItems; } private filterByText(keybindingItems: IKeybindingItem[], searchValue: string): IKeybindingItemEntry[] { const quoteAtFirstChar = searchValue.charAt(0) === '"'; const quoteAtLastChar = searchValue.charAt(searchValue.length - 1) === '"'; const completeMatch = quoteAtFirstChar && quoteAtLastChar; if (quoteAtFirstChar) { searchValue = searchValue.substring(1); } if (quoteAtLastChar) { searchValue = searchValue.substring(0, searchValue.length - 1); } searchValue = searchValue.trim(); const result: IKeybindingItemEntry[] = []; const words = searchValue.split(' '); const keybindingWords = this.splitKeybindingWords(words); for (const keybindingItem of keybindingItems) { const keybindingMatches = new KeybindingItemMatches(this.modifierLabels, keybindingItem, searchValue, words, keybindingWords, completeMatch); if (keybindingMatches.commandIdMatches || keybindingMatches.commandLabelMatches || keybindingMatches.commandDefaultLabelMatches || keybindingMatches.sourceMatches || keybindingMatches.whenMatches || keybindingMatches.keybindingMatches) { result.push({ id: KeybindingsEditorModel.getId(keybindingItem), templateId: KEYBINDING_ENTRY_TEMPLATE_ID, commandLabelMatches: keybindingMatches.commandLabelMatches || undefined, commandDefaultLabelMatches: keybindingMatches.commandDefaultLabelMatches || undefined, keybindingItem, keybindingMatches: keybindingMatches.keybindingMatches || undefined, commandIdMatches: keybindingMatches.commandIdMatches || undefined, sourceMatches: keybindingMatches.sourceMatches || undefined, whenMatches: keybindingMatches.whenMatches || undefined }); } } return result; } private splitKeybindingWords(wordsSeparatedBySpaces: string[]): string[] { const result: string[] = []; for (const word of wordsSeparatedBySpaces) { result.push(...coalesce(word.split('+'))); } return result; } override async resolve(actionLabels = new Map<string, string>()): Promise<void> { const workbenchActionsRegistry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); this._keybindingItemsSortedByPrecedence = []; const boundCommands: Map<string, boolean> = new Map<string, boolean>(); for (const keybinding of this.keybindingsService.getKeybindings()) { if (keybinding.command) { // Skip keybindings without commands this._keybindingItemsSortedByPrecedence.push(KeybindingsEditorModel.toKeybindingEntry(keybinding.command, keybinding, workbenchActionsRegistry, actionLabels)); boundCommands.set(keybinding.command, true); } } const commandsWithDefaultKeybindings = this.keybindingsService.getDefaultKeybindings().map(keybinding => keybinding.command); for (const command of getAllUnboundCommands(boundCommands)) { const keybindingItem = new ResolvedKeybindingItem(undefined, command, null, undefined, commandsWithDefaultKeybindings.indexOf(command) === -1, null, false); this._keybindingItemsSortedByPrecedence.push(KeybindingsEditorModel.toKeybindingEntry(command, keybindingItem, workbenchActionsRegistry, actionLabels)); } this._keybindingItems = this._keybindingItemsSortedByPrecedence.slice(0).sort((a, b) => KeybindingsEditorModel.compareKeybindingData(a, b)); return super.resolve(); } private static getId(keybindingItem: IKeybindingItem): string { return keybindingItem.command + (keybindingItem.keybinding ? keybindingItem.keybinding.getAriaLabel() : '') + keybindingItem.source + keybindingItem.when; } private static compareKeybindingData(a: IKeybindingItem, b: IKeybindingItem): number { if (a.keybinding && !b.keybinding) { return -1; } if (b.keybinding && !a.keybinding) { return 1; } if (a.commandLabel && !b.commandLabel) { return -1; } if (b.commandLabel && !a.commandLabel) { return 1; } if (a.commandLabel && b.commandLabel) { if (a.commandLabel !== b.commandLabel) { return a.commandLabel.localeCompare(b.commandLabel); } } if (a.command === b.command) { return a.keybindingItem.isDefault ? 1 : -1; } return a.command.localeCompare(b.command); } private static toKeybindingEntry(command: string, keybindingItem: ResolvedKeybindingItem, workbenchActionsRegistry: IWorkbenchActionRegistry, actions: Map<string, string>): IKeybindingItem { const menuCommand = MenuRegistry.getCommand(command)!; const editorActionLabel = actions.get(command)!; return <IKeybindingItem>{ keybinding: keybindingItem.resolvedKeybinding, keybindingItem, command, commandLabel: KeybindingsEditorModel.getCommandLabel(menuCommand, editorActionLabel), commandDefaultLabel: KeybindingsEditorModel.getCommandDefaultLabel(menuCommand, workbenchActionsRegistry), when: keybindingItem.when ? keybindingItem.when.serialize() : '', source: ( keybindingItem.extensionId ? (keybindingItem.isBuiltinExtension ? SOURCE_DEFAULT : SOURCE_EXTENSION) : (keybindingItem.isDefault ? SOURCE_DEFAULT : SOURCE_USER) ) }; } private static getCommandDefaultLabel(menuCommand: ICommandAction, workbenchActionsRegistry: IWorkbenchActionRegistry): string | null { if (!Language.isDefaultVariant()) { if (menuCommand && menuCommand.title && (<ILocalizedString>menuCommand.title).original) { const category: string | undefined = menuCommand.category ? (<ILocalizedString>menuCommand.category).original : undefined; const title = (<ILocalizedString>menuCommand.title).original; return category ? localize('cat.title', "{0}: {1}", category, title) : title; } } return null; } private static getCommandLabel(menuCommand: ICommandAction, editorActionLabel: string): string { if (menuCommand) { const category: string | undefined = menuCommand.category ? typeof menuCommand.category === 'string' ? menuCommand.category : menuCommand.category.value : undefined; const title = typeof menuCommand.title === 'string' ? menuCommand.title : menuCommand.title.value; return category ? localize('cat.title', "{0}: {1}", category, title) : title; } if (editorActionLabel) { return editorActionLabel; } return ''; } } class KeybindingItemMatches { readonly commandIdMatches: IMatch[] | null = null; readonly commandLabelMatches: IMatch[] | null = null; readonly commandDefaultLabelMatches: IMatch[] | null = null; readonly sourceMatches: IMatch[] | null = null; readonly whenMatches: IMatch[] | null = null; readonly keybindingMatches: KeybindingMatches | null = null; constructor(private modifierLabels: ModifierLabels, keybindingItem: IKeybindingItem, searchValue: string, words: string[], keybindingWords: string[], completeMatch: boolean) { if (!completeMatch) { this.commandIdMatches = this.matches(searchValue, keybindingItem.command, or(matchesWords, matchesCamelCase), words); this.commandLabelMatches = keybindingItem.commandLabel ? this.matches(searchValue, keybindingItem.commandLabel, (word, wordToMatchAgainst) => matchesWords(word, keybindingItem.commandLabel, true), words) : null; this.commandDefaultLabelMatches = keybindingItem.commandDefaultLabel ? this.matches(searchValue, keybindingItem.commandDefaultLabel, (word, wordToMatchAgainst) => matchesWords(word, keybindingItem.commandDefaultLabel, true), words) : null; this.sourceMatches = this.matches(searchValue, keybindingItem.source, (word, wordToMatchAgainst) => matchesWords(word, keybindingItem.source, true), words); this.whenMatches = keybindingItem.when ? this.matches(null, keybindingItem.when, or(matchesWords, matchesCamelCase), words) : null; } this.keybindingMatches = keybindingItem.keybinding ? this.matchesKeybinding(keybindingItem.keybinding, searchValue, keybindingWords, completeMatch) : null; } private matches(searchValue: string | null, wordToMatchAgainst: string, wordMatchesFilter: IFilter, words: string[]): IMatch[] | null { let matches = searchValue ? wordFilter(searchValue, wordToMatchAgainst) : null; if (!matches) { matches = this.matchesWords(words, wordToMatchAgainst, wordMatchesFilter); } if (matches) { matches = this.filterAndSort(matches); } return matches; } private matchesWords(words: string[], wordToMatchAgainst: string, wordMatchesFilter: IFilter): IMatch[] | null { let matches: IMatch[] | null = []; for (const word of words) { const wordMatches = wordMatchesFilter(word, wordToMatchAgainst); if (wordMatches) { matches = [...(matches || []), ...wordMatches]; } else { matches = null; break; } } return matches; } private filterAndSort(matches: IMatch[]): IMatch[] { return distinct(matches, (a => a.start + '.' + a.end)).filter(match => !matches.some(m => !(m.start === match.start && m.end === match.end) && (m.start <= match.start && m.end >= match.end))).sort((a, b) => a.start - b.start); } private matchesKeybinding(keybinding: ResolvedKeybinding, searchValue: string, words: string[], completeMatch: boolean): KeybindingMatches | null { const [firstPart, chordPart] = keybinding.getParts(); const userSettingsLabel = keybinding.getUserSettingsLabel(); const ariaLabel = keybinding.getAriaLabel(); const label = keybinding.getLabel(); if ((userSettingsLabel && strings.compareIgnoreCase(searchValue, userSettingsLabel) === 0) || (ariaLabel && strings.compareIgnoreCase(searchValue, ariaLabel) === 0) || (label && strings.compareIgnoreCase(searchValue, label) === 0)) { return { firstPart: this.createCompleteMatch(firstPart), chordPart: this.createCompleteMatch(chordPart) }; } const firstPartMatch: KeybindingMatch = {}; let chordPartMatch: KeybindingMatch = {}; const matchedWords: number[] = []; const firstPartMatchedWords: number[] = []; let chordPartMatchedWords: number[] = []; let matchFirstPart = true; for (let index = 0; index < words.length; index++) { const word = words[index]; let firstPartMatched = false; let chordPartMatched = false; matchFirstPart = matchFirstPart && !firstPartMatch.keyCode; let matchChordPart = !chordPartMatch.keyCode; if (matchFirstPart) { firstPartMatched = this.matchPart(firstPart, firstPartMatch, word, completeMatch); if (firstPartMatch.keyCode) { for (const cordPartMatchedWordIndex of chordPartMatchedWords) { if (firstPartMatchedWords.indexOf(cordPartMatchedWordIndex) === -1) { matchedWords.splice(matchedWords.indexOf(cordPartMatchedWordIndex), 1); } } chordPartMatch = {}; chordPartMatchedWords = []; matchChordPart = false; } } if (matchChordPart) { chordPartMatched = this.matchPart(chordPart, chordPartMatch, word, completeMatch); } if (firstPartMatched) { firstPartMatchedWords.push(index); } if (chordPartMatched) { chordPartMatchedWords.push(index); } if (firstPartMatched || chordPartMatched) { matchedWords.push(index); } matchFirstPart = matchFirstPart && this.isModifier(word); } if (matchedWords.length !== words.length) { return null; } if (completeMatch && (!this.isCompleteMatch(firstPart, firstPartMatch) || !this.isCompleteMatch(chordPart, chordPartMatch))) { return null; } return this.hasAnyMatch(firstPartMatch) || this.hasAnyMatch(chordPartMatch) ? { firstPart: firstPartMatch, chordPart: chordPartMatch } : null; } private matchPart(part: ResolvedKeybindingPart | null, match: KeybindingMatch, word: string, completeMatch: boolean): boolean { let matched = false; if (this.matchesMetaModifier(part, word)) { matched = true; match.metaKey = true; } if (this.matchesCtrlModifier(part, word)) { matched = true; match.ctrlKey = true; } if (this.matchesShiftModifier(part, word)) { matched = true; match.shiftKey = true; } if (this.matchesAltModifier(part, word)) { matched = true; match.altKey = true; } if (this.matchesKeyCode(part, word, completeMatch)) { match.keyCode = true; matched = true; } return matched; } private matchesKeyCode(keybinding: ResolvedKeybindingPart | null, word: string, completeMatch: boolean): boolean { if (!keybinding) { return false; } const ariaLabel: string = keybinding.keyAriaLabel || ''; if (completeMatch || ariaLabel.length === 1 || word.length === 1) { if (strings.compareIgnoreCase(ariaLabel, word) === 0) { return true; } } else { if (matchesContiguousSubString(word, ariaLabel)) { return true; } } return false; } private matchesMetaModifier(keybinding: ResolvedKeybindingPart | null, word: string): boolean { if (!keybinding) { return false; } if (!keybinding.metaKey) { return false; } return this.wordMatchesMetaModifier(word); } private matchesCtrlModifier(keybinding: ResolvedKeybindingPart | null, word: string): boolean { if (!keybinding) { return false; } if (!keybinding.ctrlKey) { return false; } return this.wordMatchesCtrlModifier(word); } private matchesShiftModifier(keybinding: ResolvedKeybindingPart | null, word: string): boolean { if (!keybinding) { return false; } if (!keybinding.shiftKey) { return false; } return this.wordMatchesShiftModifier(word); } private matchesAltModifier(keybinding: ResolvedKeybindingPart | null, word: string): boolean { if (!keybinding) { return false; } if (!keybinding.altKey) { return false; } return this.wordMatchesAltModifier(word); } private hasAnyMatch(keybindingMatch: KeybindingMatch): boolean { return !!keybindingMatch.altKey || !!keybindingMatch.ctrlKey || !!keybindingMatch.metaKey || !!keybindingMatch.shiftKey || !!keybindingMatch.keyCode; } private isCompleteMatch(part: ResolvedKeybindingPart | null, match: KeybindingMatch): boolean { if (!part) { return true; } if (!match.keyCode) { return false; } if (part.metaKey && !match.metaKey) { return false; } if (part.altKey && !match.altKey) { return false; } if (part.ctrlKey && !match.ctrlKey) { return false; } if (part.shiftKey && !match.shiftKey) { return false; } return true; } private createCompleteMatch(part: ResolvedKeybindingPart | null): KeybindingMatch { const match: KeybindingMatch = {}; if (part) { match.keyCode = true; if (part.metaKey) { match.metaKey = true; } if (part.altKey) { match.altKey = true; } if (part.ctrlKey) { match.ctrlKey = true; } if (part.shiftKey) { match.shiftKey = true; } } return match; } private isModifier(word: string): boolean { if (this.wordMatchesAltModifier(word)) { return true; } if (this.wordMatchesCtrlModifier(word)) { return true; } if (this.wordMatchesMetaModifier(word)) { return true; } if (this.wordMatchesShiftModifier(word)) { return true; } return false; } private wordMatchesAltModifier(word: string): boolean { if (strings.equalsIgnoreCase(this.modifierLabels.ui.altKey, word)) { return true; } if (strings.equalsIgnoreCase(this.modifierLabels.aria.altKey, word)) { return true; } if (strings.equalsIgnoreCase(this.modifierLabels.user.altKey, word)) { return true; } if (strings.equalsIgnoreCase(localize('option', "option"), word)) { return true; } return false; } private wordMatchesCtrlModifier(word: string): boolean { if (strings.equalsIgnoreCase(this.modifierLabels.ui.ctrlKey, word)) { return true; } if (strings.equalsIgnoreCase(this.modifierLabels.aria.ctrlKey, word)) { return true; } if (strings.equalsIgnoreCase(this.modifierLabels.user.ctrlKey, word)) { return true; } return false; } private wordMatchesMetaModifier(word: string): boolean { if (strings.equalsIgnoreCase(this.modifierLabels.ui.metaKey, word)) { return true; } if (strings.equalsIgnoreCase(this.modifierLabels.aria.metaKey, word)) { return true; } if (strings.equalsIgnoreCase(this.modifierLabels.user.metaKey, word)) { return true; } if (strings.equalsIgnoreCase(localize('meta', "meta"), word)) { return true; } return false; } private wordMatchesShiftModifier(word: string): boolean { if (strings.equalsIgnoreCase(this.modifierLabels.ui.shiftKey, word)) { return true; } if (strings.equalsIgnoreCase(this.modifierLabels.aria.shiftKey, word)) { return true; } if (strings.equalsIgnoreCase(this.modifierLabels.user.shiftKey, word)) { return true; } return false; } }
the_stack
import {Application} from "../../../support/application.config"; import {toolbar, createEditStepDialog} from "../../../support/components/common"; import curatePage from "../../../support/pages/curate"; import LoginPage from "../../../support/pages/login"; import {advancedSettings} from "../../../support/components/merging/index"; import mergeRuleModal from "../../../support/components/merging/merge-rule-modal"; import mergeStrategyModal from "../../../support/components/merging/merge-strategy-modal"; import "cypress-wait-until"; const mergeStep = "merge-test"; const mergeStep1 = "merge-person"; describe("Validate Merge warnings", () => { before(() => { cy.visit("/"); cy.contains(Application.title); cy.loginAsDeveloper().withRequest(); LoginPage.postLogin(); cy.waitForAsyncRequest(); }); beforeEach(() => { cy.loginAsDeveloper().withRequest(); cy.waitForAsyncRequest(); }); afterEach(() => { cy.resetTestUser(); cy.waitForAsyncRequest(); }); after(() => { cy.loginAsDeveloper().withRequest(); cy.deleteSteps("merging", "merge-test"); cy.resetTestUser(); cy.waitForAsyncRequest(); }); it("Navigate to curate tab and Open Person entity", () => { cy.waitUntil(() => toolbar.getCurateToolbarIcon()).click(); cy.waitUntil(() => curatePage.getEntityTypePanel("Customer").should("be.visible")); curatePage.toggleEntityTypeId("Person"); curatePage.selectMergeTab("Person"); cy.waitUntil(() => curatePage.addNewStep()); }); it("Creating a new merge step ", () => { curatePage.addNewStep().should("be.visible").click(); createEditStepDialog.stepNameInput().type(mergeStep, {timeout: 2000}); createEditStepDialog.setSourceRadio("Query"); createEditStepDialog.setQueryInput(`cts.collectionQuery(['match-person'])`); createEditStepDialog.saveButton("merging").click(); cy.waitForAsyncRequest(); curatePage.verifyStepNameIsVisible(mergeStep); }); it("Navigate to merge step and validate warning messages", () => { cy.waitUntil(() => curatePage.editStep(mergeStep).click({force: true})); curatePage.switchEditAdvanced().click(); advancedSettings.setTargetCollection("onMerge", "match-person"); advancedSettings.keepTargetCollection("onMerge"); curatePage.saveSettings(mergeStep).click(); curatePage.alertMessage().eq(0).should("have.text", "Warning: Target Collections includes the source collection match-person"); curatePage.alertDescription().eq(0).should("have.text", "Please remove source collection from target collections"); cy.wait(1000); advancedSettings.setTargetCollection("onMerge", "Person"); advancedSettings.keepTargetCollection("onMerge"); curatePage.switchEditAdvanced().click(); curatePage.saveSettings(mergeStep).click(); curatePage.alertMessage().eq(0).should("have.text", "Warning: Target Collections includes the target entity type Person"); curatePage.alertDescription().eq(0).should("have.text", "Please remove target entity type from target collections"); curatePage.alertMessage().eq(1).should("have.text", "Warning: Target Collections includes the source collection match-person"); curatePage.alertDescription().eq(1).should("have.text", "Please remove source collection from target collections"); }); it("Click on cancel and reopen the merge step ", () => { curatePage.cancelSettings(mergeStep).click(); cy.wait(1000); cy.waitUntil(() => curatePage.editStep(mergeStep).click({force: true})); curatePage.alertMessage().should("not.exist"); curatePage.switchEditAdvanced().click(); curatePage.mergeTargetCollection("onMerge").eq(1).should("have.text", "match-person\nPerson"); curatePage.alertMessage().should("not.exist"); curatePage.saveSettings(mergeStep).click(); curatePage.alertMessage().eq(0).should("have.text", "Warning: Target Collections includes the target entity type Person"); curatePage.alertDescription().eq(0).should("have.text", "Please remove target entity type from target collections"); curatePage.alertMessage().eq(1).should("have.text", "Warning: Target Collections includes the source collection match-person"); curatePage.alertDescription().eq(1).should("have.text", "Please remove source collection from target collections"); }); it("Remove the warnings one by one", () => { cy.findByTestId("onMerge-edit").click(); curatePage.removeTargetCollection("Person"); advancedSettings.keepTargetCollection("onMerge"); curatePage.saveSettings(mergeStep).click(); curatePage.alertMessage().eq(0).should("have.text", "Warning: Target Collections includes the source collection match-person"); curatePage.alertDescription().eq(0).should("have.text", "Please remove source collection from target collections"); cy.findByTestId("onMerge-edit").click(); curatePage.removeTargetCollection("match-person"); advancedSettings.keepTargetCollection("onMerge"); curatePage.saveSettings(mergeStep).click(); cy.wait(1000); }); it("Reopen the merge settings", () => { cy.waitUntil(() => toolbar.getCurateToolbarIcon()).click(); cy.waitUntil(() => curatePage.getEntityTypePanel("Customer").should("be.visible")); curatePage.toggleEntityTypeId("Person"); curatePage.selectMergeTab("Person"); cy.waitUntil(() => curatePage.addNewStep()); cy.waitUntil(() => curatePage.editStep(mergeStep).should("be.visible")).click({force: true}); curatePage.alertMessage().should("not.exist"); curatePage.switchEditAdvanced().click(); curatePage.alertMessage().should("not.exist"); curatePage.mergeTargetCollection("onMerge").eq(1).should("have.text", ""); curatePage.cancelSettings(mergeStep).click(); }); it("Open merging step details ", () => { curatePage.openStepDetails(mergeStep1); cy.contains(mergeStep1); }); it("Click on merge rule Address and validate warnings", () => { cy.findAllByText("Address").first().click(); cy.get("[name=\"maxValues\"]").first().check(); mergeRuleModal.saveButton(); mergeRuleModal.alertMessage().should("have.text", "Warning: The current merge settings might produce merged documents that are inconsistent with the entity type\nIn the entity type Person, the property or properties Address allows only a single value.\nIn every merge rule for the property Address set Max Values or Max Sources to 1."); mergeRuleModal.alertDescription().should("have.text", "Please set max values for property to 1 on merge to avoid an invalid entity instance."); mergeRuleModal.ruleMaxValuesInput("1"); mergeRuleModal.saveButton(); curatePage.alertMessage().should("not.exist"); cy.findAllByText("Address").first().click(); cy.get("[name=\"maxValues\"]").first().check(); mergeRuleModal.ruleMaxValuesInput("0"); mergeRuleModal.ruleMaxScoreInput("1"); mergeRuleModal.saveButton(); curatePage.alertMessage().should("not.exist"); cy.findAllByText("Address").first().click(); cy.get("[name=\"maxValues\"]").first().check(); mergeRuleModal.ruleMaxScoreInput("0"); mergeRuleModal.saveButton(); mergeRuleModal.alertMessage().should("have.text", "Warning: The current merge settings might produce merged documents that are inconsistent with the entity type\nIn the entity type Person, the property or properties Address allows only a single value.\nIn every merge rule for the property Address set Max Values or Max Sources to 1."); mergeRuleModal.alertDescription().should("have.text", "Please set max values for property to 1 on merge to avoid an invalid entity instance."); mergeRuleModal.ruleMaxValuesInput("1"); mergeRuleModal.ruleMaxScoreInput("2"); mergeRuleModal.saveButton(); curatePage.alertMessage().should("not.exist"); cy.findAllByText("Address").first().click(); cy.get("[name=\"maxValues\"]").first().check(); mergeRuleModal.ruleMaxValuesInput("2"); mergeRuleModal.ruleMaxScoreInput("2"); mergeRuleModal.saveButton(); mergeRuleModal.alertMessage().should("have.text", "Warning: The current merge settings might produce merged documents that are inconsistent with the entity type\nIn the entity type Person, the property or properties Address allows only a single value.\nIn every merge rule for the property Address set Max Values or Max Sources to 1."); mergeRuleModal.alertDescription().should("have.text", "Please set max values for property to 1 on merge to avoid an invalid entity instance."); //Will uncomment once DHFPROD-7452 is fixed /* mergeRuleModal.selectMergeTypeDropdown("Strategy"); mergeRuleModal.selectStrategyName("retain-single-value"); mergeRuleModal.saveButton(); mergeRuleModal.alertMessage().should("have.text", "Warning: The current merge settings might produce merged documents that are inconsistent with the entity type\nIn the entity type Person, the property or properties DateOfBirth, ZipCode, id, SSN, lname, desc, fname allows only a single value.\nIn every merge rule for the property DateOfBirth, ZipCode, id, SSN, lname, desc, fname set Max Values or Max Sources to 1."); mergeRuleModal.alertDescription().should("have.text", "Please set max values for property to 1 on merge to avoid an invalid entity instance.");*/ mergeRuleModal.cancelButton().click(); toolbar.getCurateToolbarIcon().click(); cy.waitUntil(() => curatePage.getEntityTypePanel("Customer").should("be.visible")); curatePage.toggleEntityTypeId("Person"); curatePage.selectMergeTab("Person"); curatePage.openStepDetails(mergeStep1); cy.contains(mergeStep1); }); it("Click on merge Strategy and validate warnings", () => { cy.findAllByText("retain-single-value").eq(0).click(); mergeStrategyModal.strategyMaxScoreInput("1"); mergeStrategyModal.saveButton().click(); cy.findByText("Address").click(); mergeRuleModal.alertMessage().should("not.exist"); mergeRuleModal.saveButton(); mergeRuleModal.alertMessage().should("have.text", "Warning: The current merge settings might produce merged documents that are inconsistent with the entity type\nIn the entity type Person, the property or properties Address allows only a single value.\nIn every merge rule for the property Address set Max Values or Max Sources to 1."); mergeRuleModal.alertDescription().should("have.text", "Please set max values for property to 1 on merge to avoid an invalid entity instance."); mergeRuleModal.cancelButton().click(); cy.findAllByText("retain-single-value").eq(0).click(); mergeStrategyModal.maxValue("2"); mergeStrategyModal.strategyMaxScoreInput("2"); mergeStrategyModal.saveButton().click(); cy.wait(1000); cy.findByText("Address").click(); mergeRuleModal.saveButton(); mergeRuleModal.alertMessage().should("have.text", "Warning: The current merge settings might produce merged documents that are inconsistent with the entity type\nIn the entity type Person, the property or properties Address allows only a single value.\nIn every merge rule for the property Address set Max Values or Max Sources to 1."); mergeRuleModal.alertDescription().should("have.text", "Please set max values for property to 1 on merge to avoid an invalid entity instance."); mergeRuleModal.cancelButton().click(); }); it("Reset values ", () => { cy.findAllByText("retain-single-value").eq(0).click(); mergeStrategyModal.maxValue("1"); mergeStrategyModal.strategyMaxScoreInput("0"); mergeStrategyModal.saveButton().click(); cy.findByText("Address").click(); mergeRuleModal.selectMergeTypeDropdown("Property-specific"); mergeRuleModal.ruleMaxValuesInput("1"); mergeRuleModal.ruleMaxScoreInput("0"); mergeRuleModal.saveButton(); }); });
the_stack
import { T, Val, EmptyArray, IterType, FalseyValues, isTruthy } from "./common"; import { Option, Some, None } from "./option"; export type Ok<T> = ResultType<T, never>; export type Err<E> = ResultType<never, E>; export type Result<T, E> = ResultType<T, E>; type From<T> = Exclude<T, Error | FalseyValues>; type ResultTypes<R> = { [K in keyof R]: R[K] extends Result<infer T, any> ? T : never; }; type ResultErrors<R> = { [K in keyof R]: R[K] extends Result<any, infer U> ? U : never; }; export class ResultType<T, E> { readonly [T]: boolean; readonly [Val]: T | E; constructor(val: T | E, ok: boolean) { this[Val] = val; this[T] = ok; } [Symbol.iterator](this: Result<T, E>): IterType<T> { return this[T] ? (this[Val] as any)[Symbol.iterator]() : EmptyArray[Symbol.iterator](); } /** * Returns the contained `T`, or `err` if the result is `Err`. The `err` * value must be falsey and defaults to `undefined`. * * ``` * const x = Ok(1); * assert.equal(x.into(), 1); * * const x = Err(1); * assert.equal(x.into(), undefined); * * const x = Err(1); * assert.equal(x.into(null), null); * ``` */ into(this: Result<T, E>): T | undefined; into<U extends FalseyValues>(this: Result<T, E>, err: U): T | U; into(this: Result<T, E>, err?: FalseyValues): T | FalseyValues { return this[T] ? (this[Val] as T) : err; } /** * Compares the Result to `cmp`, returns true if both are `Ok` or both * are `Err` and acts as a type guard. * * ``` * const o = Ok(1); * const e = Err(1); * * assert.equal(o.isLike(Ok(1))), true); * assert.equal(e.isLike(Err(1)), true); * assert.equal(o.isLike(e), false); * ``` */ isLike(this: Result<T, E>, cmp: unknown): cmp is Result<unknown, unknown> { return cmp instanceof ResultType && this[T] === cmp[T]; } /** * Returns true if the Result is `Ok` and acts as a type guard. * * ``` * const x = Ok(10); * assert.equal(x.isOk(), true); * * const x = Err(10); * assert.equal(x.isOk(), false); * ``` */ isOk(this: Result<T, E>): this is Ok<T> { return this[T]; } /** * Returns true if the Result is `Err` and acts as a type guard. * * ``` * const x = Ok(10); * assert.equal(x.isErr(), false); * * const x = Err(10); * assert.equal(x.isErr(), true); * ``` */ isErr(this: Result<T, E>): this is Err<E> { return !this[T]; } /** * Creates an `Option<T>` by calling `f` with the contained `Ok` value. * Converts `Ok` to `Some` if the filter returns true, or `None` otherwise. * * For more advanced filtering, consider `match`. * * ``` * const x = Ok(1); * assert.equal(x.filter((v) => v < 5).isLike(Some(1)), true); * assert.equal(x.filter((v) => v < 5).unwrap(), 1); * * const x = Ok(10); * assert.equal(x.filter((v) => v < 5).isNone(), true); * * const x = Err(1); * assert.equal(x.filter((v) => v < 5).isNone(), true); * ``` */ filter(this: Result<T, E>, f: (val: T) => boolean): Option<T> { return this[T] && f(this[Val] as T) ? Some(this[Val] as T) : None; } /** * Returns the contained `Ok` value and throws `Error(msg)` if `Err`. * * To avoid throwing, consider `isOk`, `unwrapOr`, `unwrapOrElse` or * `match` to handle the `Err` case. * * ``` * const x = Ok(1); * assert.equal(x.expect("Was Err"), 1); * * const x = Err(1); * const y = x.expect("Was Err"); // throws * ``` */ expect(this: Result<T, E>, msg: string): T { if (this[T]) { return this[Val] as T; } else { throw new Error(msg); } } /** * Returns the contained `Err` value and throws `Error(msg)` if `Ok`. * * To avoid throwing, consider `isErr` or `match` to handle the `Ok` case. * * ``` * const x = Ok(1); * const y = x.expectErr("Was Ok"); // throws * * const x = Err(1); * assert.equal(x.expectErr("Was Ok"), 1); * ``` */ expectErr(this: Result<T, E>, msg: string): E { if (this[T]) { throw new Error(msg); } else { return this[Val] as E; } } /** * Returns the contained `Ok` value and throws if `Err`. * * To avoid throwing, consider `isOk`, `unwrapOr`, `unwrapOrElse` or * `match` to handle the `Err` case. To throw a more informative error use * `expect`. * * ``` * const x = Ok(1); * assert.equal(x.unwrap(), 1); * * const x = Err(1); * const y = x.unwrap(); // throws * ``` */ unwrap(this: Result<T, E>): T { return this.expect("Failed to unwrap Result (found Err)"); } /** * Returns the contained `Err` value and throws if `Ok`. * * To avoid throwing, consider `isErr` or `match` to handle the `Ok` case. * To throw a more informative error use `expectErr`. * * ``` * const x = Ok(1); * const y = x.unwrap(); // throws * * const x = Err(1); * assert.equal(x.unwrap(), 1); * ``` */ unwrapErr(this: Result<T, E>): E { return this.expectErr("Failed to unwrapErr Result (found Ok)"); } /** * Returns the contained `Ok` value or a provided default. * * The provided default is eagerly evaluated. If you are passing the result * of a function call, consider `unwrapOrElse`, which is lazily evaluated. * * ``` * const x = Ok(10); * assert.equal(x.unwrapOr(1), 10); * * const x = Err(10); * assert.equal(x.unwrapOr(1), 1); * ``` */ unwrapOr(this: Result<T, E>, def: T): T { return this[T] ? (this[Val] as T) : def; } /** * Returns the contained `Ok` value or computes it from a function. * * ``` * const x = Ok(10); * assert.equal(x.unwrapOrElse(() => 1 + 1), 10); * * const x = Err(10); * assert.equal(x.unwrapOrElse(() => 1 + 1), 2); * ``` */ unwrapOrElse(this: Result<T, E>, f: () => T): T { return this[T] ? (this[Val] as T) : f(); } /** * Returns the contained `Ok` or `Err` value. * * Most problems are better solved using one of the other `unwrap_` methods. * This method should only be used when you are certain that you need it. * * ``` * const x = Ok(10); * assert.equal(x.unwrapUnchecked(), 10); * * const x = Err(20); * assert.equal(x.unwrapUnchecked(), 20); * ``` */ unwrapUnchecked(this: Result<T, E>): T | E { return this[Val]; } /** * Returns the Option if it is `Ok`, otherwise returns `resb`. * * `resb` is eagerly evaluated. If you are passing the result of a function * call, consider `orElse`, which is lazily evaluated. * * ``` * const x = Ok(10); * const xor = x.or(Ok(1)); * assert.equal(xor.unwrap(), 10); * * const x = Err(10); * const xor = x.or(Ok(1)); * assert.equal(xor.unwrap(), 1); * ``` */ or(this: Result<T, E>, resb: Result<T, E>): Result<T, E> { return this[T] ? (this as any) : resb; } /** * Returns the Result if it is `Ok`, otherwise returns the value of `f()` * mapping `Result<T, E>` to `Result<T, F>`. * * ``` * const x = Ok(10); * const xor = x.orElse(() => Ok(1)); * assert.equal(xor.unwrap(), 10); * * const x = Err(10); * const xor = x.orElse(() => Ok(1)); * assert.equal(xor.unwrap(), 1); * * const x = Err(10); * const xor = x.orElse((e) => Err(`val ${e}`)); * assert.equal(xor.unwrapErr(), "val 10"); * ``` */ orElse<F>(this: Result<T, E>, f: (err: E) => Result<T, F>): Result<T, F> { return this[T] ? (this as unknown as Result<T, F>) : f(this[Val] as E); } /** * Returns itself if the Result is `Err`, otherwise returns `resb`. * * ``` * const x = Ok(10); * const xand = x.and(Ok(1)); * assert.equal(xand.unwrap(), 1); * * const x = Err(10); * const xand = x.and(Ok(1)); * assert.equal(xand.unwrapErr(), 10); * * const x = Ok(10); * const xand = x.and(Err(1)); * assert.equal(xand.unwrapErr(), 1); * ``` */ and<U>(this: Result<T, E>, resb: Result<U, E>): Result<U, E> { return this[T] ? resb : (this as any); } /** * Returns itself if the Result is `Err`, otherwise calls `f` with the `Ok` * value and returns the result. * * ``` * const x = Ok(10); * const xand = x.andThen((n) => n + 1); * assert.equal(xand.unwrap(), 11); * * const x = Err(10); * const xand = x.andThen((n) => n + 1); * assert.equal(xand.unwrapErr(), 10); * * const x = Ok(10); * const xand = x.and(Err(1)); * assert.equal(xand.unwrapErr(), 1); * ``` */ andThen<U>(this: Result<T, E>, f: (val: T) => Result<U, E>): Result<U, E> { return this[T] ? f(this[Val] as T) : (this as any); } /** * Maps a `Result<T, E>` to `Result<U, E>` by applying a function to the * `Ok` value. * * ``` * const x = Ok(10); * const xmap = x.map((n) => `number ${n}`); * assert.equal(xmap.unwrap(), "number 10"); * ``` */ map<U>(this: Result<T, E>, f: (val: T) => U): Result<U, E> { return new ResultType( this[T] ? f(this[Val] as T) : (this[Val] as E), this[T] ) as Result<U, E>; } /** * Maps a `Result<T, E>` to `Result<T, F>` by applying a function to the * `Err` value. * * ``` * const x = Err(10); * const xmap = x.mapErr((n) => `number ${n}`); * assert.equal(xmap.unwrapErr(), "number 10"); * ``` */ mapErr<F>(this: Result<T, E>, op: (err: E) => F): Result<T, F> { return new ResultType( this[T] ? (this[Val] as T) : op(this[Val] as E), this[T] ) as Result<T, F>; } /** * Returns the provided default if `Err`, otherwise calls `f` with the * `Ok` value and returns the result. * * The provided default is eagerly evaluated. If you are passing the result * of a function call, consider `mapOrElse`, which is lazily evaluated. * * ``` * const x = Ok(10); * const xmap = x.mapOr(1, (n) => n + 1); * assert.equal(xmap.unwrap(), 11); * * const x = Err(10); * const xmap = x.mapOr(1, (n) => n + 1); * assert.equal(xmap.unwrap(), 1); * ``` */ mapOr<U>(this: Result<T, E>, def: U, f: (val: T) => U): U { return this[T] ? f(this[Val] as T) : def; } /** * Computes a default return value if `Err`, otherwise calls `f` with the * `Ok` value and returns the result. * * ``` * const x = Ok(10); * const xmap = x.mapOrElse(() => 1 + 1, (n) => n + 1); * assert.equal(xmap.unwrap(), 11); * * const x = Err(10); * const xmap = x.mapOrElse(() => 1 + 1, (n) => n + 1); * assert.equal(xmap.unwrap(), 2); * ``` */ mapOrElse<U>(this: Result<T, E>, def: (err: E) => U, f: (val: T) => U): U { return this[T] ? f(this[Val] as T) : def(this[Val] as E); } /** * Transforms the `Result<T, E>` into an `Option<T>`, mapping `Ok(v)` to * `Some(v)`, discarding any `Err` value and mapping to None. * * ``` * const x = Ok(10); * const opt = x.ok(); * assert.equal(x.isSome(), true); * assert.equal(x.unwrap(), 10); * * const x = Err(10); * const opt = x.ok(); * assert.equal(x.isNone(), true); * const y = x.unwrap(); // throws * ``` */ ok(this: Result<T, E>): Option<T> { return this[T] ? Some(this[Val] as T) : None; } } /** * Tests the provided `val` is an Result and acts as a type guard. * * ``` * assert.equal(Result.is(Ok(1), true); * assert.equal(Result.is(Err(1), true)); * assert.equal(Result.is(Some(1), false)); * ``` */ function is(val: unknown): val is Result<unknown, unknown> { return val instanceof ResultType; } /** * A Result represents success, or failure. If we hold a value * of type `Result<T, E>`, we know it is either `Ok<T>` or `Err<E>`. * * As a function, `Result` is an alias for `Result.from`. * * ``` * const users = ["Fry", "Bender"]; * function fetch_user(username: string): Result<string, string> { * return users.includes(username) ? Ok(username) : Err("Wha?"); * } * * function greet(username: string): string { * return fetch_user(username).mapOrElse( * (err) => `Error: ${err}`, * (user) => `Good news everyone, ${user} is here!` * ); * } * * assert.equal(greet("Bender"), "Good news everyone, Bender is here!"); * assert.equal(greet("SuperKing"), "Error: Wha?"); * ``` */ export function Result<T>( val: T ): Result< From<T>, | (T extends Error ? T : never) | (Extract<FalseyValues, T> extends never ? never : null) > { return from(val) as any; } Result.is = is; Result.from = from; Result.nonNull = nonNull; Result.qty = qty; Result.safe = safe; Result.all = all; Result.any = any; /** * Creates an `Ok<T>` value, which can be used where a `Result<T, E>` is * required. See Result for more examples. * * Note that the counterpart `Err` type `E` is set to the same type as `T` * by default. TypeScript will usually infer the correct `E` type from the * context (e.g. a function which accepts or returns a Result). * * ``` * const x = Ok(10); * assert.equal(x.isSome(), true); * assert.equal(x.unwrap(), 10); * ``` */ export function Ok<T>(val: T): Ok<T> { return new ResultType<T, never>(val, true); } /** * Creates an `Err<E>` value, which can be used where a `Result<T, E>` is * required. See Result for more examples. * * Note that the counterpart `Ok` type `T` is set to the same type as `E` * by default. TypeScript will usually infer the correct `T` type from the * context (e.g. a function which accepts or returns a Result). * * ``` * const x = Err(10); * assert.equal(x.isErr(), true); * assert.equal(x.unwrapErr(), 10); * ``` */ export function Err<E>(val: E): Err<E> { return new ResultType<never, E>(val, false); } /** * Creates a new `Result<T, E>` which is `Ok<T>` unless the provided `val` is * falsey, an instance of `Error` or an invalid `Date`. * * The `T` is narrowed to exclude any falsey values or Errors. * * The `E` type includes: * - `null` (if `val` could have been falsey or an invalid date) * - `Error` types excluded from `T` (if there are any) * * **Note:** `null` is not a useful value. Consider `Option.from` or `mapErr`. * * ``` * assert.equal(Result.from(1).unwrap(), 1); * assert.equal(Result(0).isErr(), true); * * const err = Result.from(new Error("msg")); * assert.equal(err.unwrapErr().message, "msg"); * * // Create a Result<number, string> * const x = Option.from(1).okOr("Falsey Value"); * ``` */ function from<T>( val: T ): Result< From<T>, | (T extends Error ? T : never) | (Extract<FalseyValues, T> extends never ? never : null) > { return isTruthy(val) ? new ResultType(val as any, !(val instanceof Error)) : Err(null); } /** * Creates a new `Result<T, null>` which is `Ok` unless the provided `val` is * `undefined`, `null` or `NaN`. * * **Note:** `null` is not a useful value. Consider `Option.nonNull` or * `mapErr`. * * ``` * assert.equal(Result.nonNull(1).unwrap(), 1); * assert.equal(Result.nonNull(0).unwrap(), 0); * assert.equal(Result.nonNull(null).isErr(), true); * * // Create a Result<number, string> * const x = Option.nonNull(1).okOr("Nullish Value"); * ``` */ function nonNull<T>(val: T): Result<NonNullable<T>, null> { return val === undefined || val === null || val !== val ? Err(null) : Ok(val as NonNullable<T>); } /** * Creates a new Result<number, null> which is `Ok` when the provided `val` is * a finite integer greater than or equal to 0. * * **Note:** `null` is not a useful value. Consider `Option.qty` or `mapErr`. * * ``` * const x = Result.qty("test".indexOf("s")); * assert.equal(x.unwrap(), 2); * * const x = Result.qty("test".indexOf("z")); * assert.equal(x.unwrapErr(), null); * * // Create a Result<number, string> * const x = Result.qty("test".indexOf("s")).mapErr(() => "Not Found"); * ``` */ function qty<T extends number>(val: T): Result<number, null> { return val >= 0 && Number.isInteger(val) ? Ok(val) : Err(null); } /** * Capture the outcome of a function or Promise as a `Result<T, Error>`, * preventing throwing (function) or rejection (Promise). * * **Note:** If the function throws (or the Promise rejects with) a value that * is not an instance of `Error`, the value is converted to a string and used * as the message text for a new Error instance. * * ### Usage for functions * * Calls `fn` with the provided `args` and returns a `Result<T, Error>`. The * Result is `Ok` if the provided function returned, or `Err` if it threw. * * **Note:** Any function which returns a Promise (or PromiseLike) value is * rejected by the type signature. `Result<Promise<T>, Error>` is not a useful * type, and using it in this way is likely to be a mistake. * * ``` * function mightThrow(throws: boolean) { * if (throws) { * throw new Error("Throw"); * } * return "Hello World"; * } * * const x: Result<string, Error> = Result.safe(mightThrow, true); * assert.equal(x.unwrapErr() instanceof Error, true); * assert.equal(x.unwrapErr().message, "Throw"); * * const x = Result.safe(() => mightThrow(false)); * assert.equal(x.unwrap(), "Hello World"); * ``` * * ### Usage for Promises * * Accepts `promise` and returns a new Promise which always resolves to * `Result<T, Error>`. The Result is `Ok` if the original promise * resolved, or `Err` if it rejected. * * ``` * async function mightThrow(throws: boolean) { * if (throws) { * throw new Error("Throw") * } * return "Hello World"; * } * * const x = await Result.safe(mightThrow(true)); * assert.equal(x.unwrapErr() instanceof Error, true); * assert.equal(x.unwrapErr().message, "Throw"); * * const x = await Result.safe(mightThrow(false)); * assert.equal(x.unwrap(), "Hello World"); * ``` */ function safe<T, A extends any[]>( fn: (...args: A) => T extends PromiseLike<any> ? never : T, ...args: A ): Result<T, Error>; function safe<T>(promise: Promise<T>): Promise<Result<T, Error>>; function safe<T, A extends any[]>( fn: ((...args: A) => T) | Promise<T>, ...args: A ): Result<T, Error> | Promise<Result<T, Error>> { if (fn instanceof Promise) { return fn.then((val) => Ok(val), toError); } try { return Ok(fn(...args)); } catch (err) { return toError(err); } } function toError(err: unknown): Err<Error> { return err instanceof Error ? Err(err) : Err(new Error(String(err))); } /** * Converts a number of `Result`s into a single Result. The first `Err` found * (if any) is returned, otherwise the new Result is `Ok` and contains an array * of all the unwrapped values. * * ``` * function num(val: number): Result<number, string> { * return val > 10 ? Ok(val) : Err(`Value ${val} is too low.`); * } * * const xyz = Result.all(num(20), num(30), num(40)); * const [x, y, z] = xyz.unwrap(); * assert.equal(x, 20); * assert.equal(y, 30); * assert.equal(z, 40); * * const err = Result.all(num(20), num(5), num(40)); * assert.equal(err.isErr(), true); * assert.equal(err.unwrapErr(), "Value 5 is too low."); * ``` */ function all<R extends Result<any, any>[]>( ...results: R ): Result<ResultTypes<R>, ResultErrors<R>[number]> { const ok = []; for (const result of results) { if (result.isOk()) { ok.push(result.unwrapUnchecked()); } else { return result; } } return Ok(ok) as Ok<ResultTypes<R>>; } /** * Converts a number of `Result`s into a single Result. The first `Ok` found * (if any) is returned, otherwise the new Result is an `Err` containing an * array of all the unwrapped errors. * * ``` * function num(val: number): Result<number, string> { * return val > 10 ? Ok(val) : Err(`Value ${val} is too low.`); * } * * const x = Result.any(num(5), num(20), num(2)); * assert.equal(x.unwrap(), 20); * * const efg = Result.any(num(2), num(5), num(8)); * const [e, f, g] = efg.unwrapErr(); * assert.equal(e, "Value 2 is too low."); * assert.equal(f, "Value 5 is too low."); * assert.equal(g, "Value 8 is too low."); * ``` */ function any<R extends Result<any, any>[]>( ...results: R ): Result<ResultTypes<R>[number], ResultErrors<R>> { const err = []; for (const result of results) { if (result.isOk()) { return result; } else { err.push(result.unwrapUnchecked()); } } return Err(err) as Err<ResultErrors<R>>; }
the_stack
import test, { Test } from "tape-promise/tape"; import HelloWorldContractJson from "../../../../solidity/hello-world-contract/HelloWorld.json"; import Web3 from "web3"; import Web3JsQuorum, { IPrivateTransactionReceipt } from "web3js-quorum"; import { BesuMpTestLedger } from "@hyperledger/cactus-test-tooling"; import { AbiItem } from "web3-utils"; import { LogLevelDesc } from "@hyperledger/cactus-common"; const testCase = "Executes private transactions on Hyperledger Besu"; const logLevel: LogLevelDesc = "TRACE"; // WARNING: the keys here are demo purposes ONLY. Please use a tool like Orchestrate or EthSigner for production, rather than hard coding private keys const keysStatic = { tessera: { member1: { publicKey: "BULeR8JyUWhiuuCMU/HLA0Q5pzkYT+cHII3ZKBey3Bo=", }, member2: { publicKey: "QfeDAys9MPDs2XHExtc84jKGHxZg/aj52DTh0vtA3Xc=", }, member3: { publicKey: "1iTZde/ndBHvzhcl7V68x44Vx7pl8nwx9LqnM/AfJUg=", }, }, besu: { member1: { url: "http://127.0.0.1:20000", wsUrl: "ws://127.0.0.1:20001", privateKey: "8f2a55949038a9610f50fb23b5883af3b4ecb3c3bb792cbcefbd1542c692be63", }, member2: { url: "http://127.0.0.1:20002", wsUrl: "ws://127.0.0.1:20003", privateKey: "c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3", }, member3: { url: "http://127.0.0.1:20004", wsUrl: "ws://127.0.0.1:20005", privateKey: "ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f", }, ethsignerProxy: { url: "http://127.0.0.1:18545", accountAddress: "9b790656b9ec0db1936ed84b3bea605873558198", }, }, }; test(testCase, async (t: Test) => { // At development time one can specify this environment variable if there is // a multi-party network already running, which is doable with something like // this on the terminal: // docker run --rm --privileged --publish 2222:22 --publish 3000:3000 --publish 8545:8545 --publish 8546:8546 --publish 9001:9001 --publish 9081:9081 --publish 9082:9082 --publish 9083:9083 --publish 9090:9090 --publish 18545:18545 --publish 20000:20000 --publish 20001:20001 --publish 20002:20002 --publish 20003:20003 --publish 20004:20004 --publish 20005:20005 --publish 25000:25000 petermetz/cactus-besu-multi-party-all-in-one:0.1.2 // // The upside of this approach is that a new container is not launched from // scratch for every test execution which enables faster iteration. const preWarmedLedger = process.env.CACTUS_TEST_PRE_WARMED_LEDGER === "true"; let keys: any; if (preWarmedLedger) { keys = keysStatic; } else { const ledger = new BesuMpTestLedger({ logLevel }); test.onFinish(() => ledger.stop()); await ledger.start(); keys = await ledger.getKeys(); } const rpcApiHttpHostMember1 = keys.besu.member1.url; const rpcApiHttpHostMember2 = keys.besu.member2.url; const rpcApiHttpHostMember3 = keys.besu.member3.url; const web3Member1 = new Web3(rpcApiHttpHostMember1); const web3Member2 = new Web3(rpcApiHttpHostMember2); const web3Member3 = new Web3(rpcApiHttpHostMember3); const chainIdMember1 = await web3Member1.eth.getChainId(); t.comment(`chainIdMember1=${chainIdMember1}`); const chainIdMember2 = await web3Member2.eth.getChainId(); t.comment(`chainIdMember2=${chainIdMember2}`); const chainIdMember3 = await web3Member3.eth.getChainId(); t.comment(`chainIdMember3=${chainIdMember3}`); const web3QuorumMember1 = Web3JsQuorum(web3Member1); t.ok(web3QuorumMember1, "web3QuorumMember1 truthy OK"); const web3QuorumMember2 = Web3JsQuorum(web3Member2); t.ok(web3QuorumMember2, "web3QuorumMember2 truthy OK"); const web3QuorumMember3 = Web3JsQuorum(web3Member3); t.ok(web3QuorumMember3, "web3QuorumMember3 truthy OK"); const commitmentHash = await web3QuorumMember1.priv.generateAndSendRawTransaction( { data: "0x" + HelloWorldContractJson.bytecode, privateFrom: keys.tessera.member1.publicKey, privateFor: [ keys.tessera.member1.publicKey, keys.tessera.member2.publicKey, ], privateKey: keys.besu.member1.privateKey, gasLimit: "3000000", }, ); t.ok(commitmentHash, "commitmentHash truthy OK"); const contractDeployReceipt = (await web3QuorumMember1.priv.waitForTransactionReceipt( commitmentHash, )) as IPrivateTransactionReceipt; t.ok(contractDeployReceipt, "contractDeployReceipt truthy OK"); const receipt = contractDeployReceipt as IPrivateTransactionReceipt; const { contractAddress } = receipt; t.comment(`Private contract address: ${contractAddress}`); t.ok(contractAddress, "contractAddress truthy OK"); // Check that the third node does not see the transaction of the contract // deployment that was sent to node 1 and 2 only, not 3. const txReceiptNever = await web3QuorumMember3.priv.waitForTransactionReceipt( commitmentHash, ); t.notok(txReceiptNever, "txReceiptNever falsy OK"); // Check that node 1 and 2 can indeed see the transaction for the contract // deployment that was sent to them and them only (node 3 was left out) // Note that changing this to use web3QuorumMember3 breaks it and I'm suspecting // that this is what's plaguing the tests that are based on the connector // which is instantiated with a single web3+web3 Quorum client. // What I will try next is to have 3 connectors each with a web3 Quorum client // that points to one of the 3 nodes and see if that makes it work. const txReceiptAlways1 = await web3QuorumMember1.priv.waitForTransactionReceipt( commitmentHash, ); t.ok(txReceiptAlways1, "txReceiptAlways1 truthy OK"); const txReceiptAlways2 = await web3QuorumMember2.priv.waitForTransactionReceipt( commitmentHash, ); t.ok(txReceiptAlways2, "txReceiptAlways2 truthy OK"); const contract = new web3Member1.eth.Contract( HelloWorldContractJson.abi as never, ); const setNameAbi = contract["_jsonInterface"].find( (e) => e.name === "setName", ) as AbiItem & { signature: string; inputs: AbiItem[] }; t.ok(setNameAbi, "setNameAbi truthy OK"); t.ok(setNameAbi.inputs, "setNameAbi.inputs truthy OK"); t.ok(setNameAbi.signature, "setNameAbi.signature truthy OK"); const getNameAbi = contract["_jsonInterface"].find( (e) => e.name === "getName", ) as AbiItem & { signature: string; inputs: AbiItem[] }; t.ok(getNameAbi, "getNameAbi truthy OK"); t.ok(getNameAbi.inputs, "getNameAbi.inputs truthy OK"); t.ok(getNameAbi.signature, "getNameAbi.signature truthy OK"); { t.comment("Checking if member1 can call setName()"); const functionArgs = web3Member1.eth.abi .encodeParameters(setNameAbi.inputs, ["ProfessorCactus - #1"]) .slice(2); const functionParams = { to: contractDeployReceipt.contractAddress, data: setNameAbi.signature + functionArgs, privateFrom: keys.tessera.member1.publicKey, privateFor: [keys.tessera.member2.publicKey], privateKey: keys.besu.member1.privateKey, }; const transactionHash = await web3QuorumMember1.priv.generateAndSendRawTransaction( functionParams, ); t.comment(`Transaction hash: ${transactionHash}`); t.ok(transactionHash, "transactionHash truthy OK"); const result = await web3QuorumMember1.priv.waitForTransactionReceipt( transactionHash, ); t.comment(`Transaction receipt for set() call: ${JSON.stringify(result)}`); t.ok(result, "set() result member 1 truthy OK"); } { t.comment("Checking if member1 can see new name via getName()"); const functionArgs = web3Member1.eth.abi .encodeParameters(getNameAbi.inputs, []) .slice(2); const fnParams = { to: contractDeployReceipt.contractAddress, data: getNameAbi.signature + functionArgs, privateFrom: keys.tessera.member1.publicKey, privateFor: [keys.tessera.member2.publicKey], privateKey: keys.besu.member1.privateKey, }; const privacyGroupId = web3QuorumMember1.utils.generatePrivacyGroup( fnParams, ); const callOutput = await web3QuorumMember1.priv.call(privacyGroupId, { to: contractDeployReceipt.contractAddress, data: contract.methods.getName().encodeABI(), }); t.comment(`getName Call output: ${JSON.stringify(callOutput)}`); t.ok(callOutput, "callOutput truthy OK"); const name = web3QuorumMember1.eth.abi.decodeParameter( "string", callOutput, ); t.equal(name, "ProfessorCactus - #1", "getName() member 1 equals #1"); } { // Member 3 cannot see into the privacy group of 1 and 2 so the getName // will not return the value that was set earlier in that privacy group. t.comment("Checking if member3 can see new name via getName()"); const fnParams = { to: contractDeployReceipt.contractAddress, data: contract.methods.getName().encodeABI(), privateFrom: keys.tessera.member1.publicKey, privateFor: [keys.tessera.member2.publicKey], privateKey: keys.besu.member3.privateKey, }; const privacyGroupId = web3QuorumMember3.utils.generatePrivacyGroup( fnParams, ); const callOutput = await web3QuorumMember3.priv.call(privacyGroupId, { to: contractDeployReceipt.contractAddress, data: getNameAbi.signature, }); t.comment(`getName member3 output: ${JSON.stringify(callOutput)}`); t.equal(callOutput, "0x", "member3 getName callOutput === 0x OK"); } { t.comment("Checking if member2 can call setName()"); const functionArgs = web3Member2.eth.abi .encodeParameters(setNameAbi.inputs, ["ProfessorCactus - #2"]) .slice(2); const functionParams = { to: contractDeployReceipt.contractAddress, data: setNameAbi.signature + functionArgs, privateFrom: keys.tessera.member2.publicKey, privateFor: [keys.tessera.member2.publicKey], privateKey: keys.besu.member2.privateKey, }; const transactionHash = await web3QuorumMember2.priv.generateAndSendRawTransaction( functionParams, ); t.comment(`Transaction hash: ${transactionHash}`); t.ok(transactionHash, "transactionHash truthy OK"); const result = await web3QuorumMember2.priv.waitForTransactionReceipt( transactionHash, ); t.comment(`Transaction receipt for set() call: ${JSON.stringify(result)}`); t.ok(result, "set() result member 2 truthy OK"); } { t.comment("Checking if member3 can call setName()"); const functionArgs = web3Member3.eth.abi .encodeParameters(setNameAbi.inputs, ["ProfessorCactus - #3"]) .slice(2); const functionParams = { to: contractDeployReceipt.contractAddress, data: setNameAbi.signature + functionArgs, privateFrom: keys.tessera.member3.publicKey, privateKey: keys.besu.member3.privateKey, privateFor: [keys.tessera.member2.publicKey], }; const transactionHash = await web3QuorumMember3.priv.generateAndSendRawTransaction( functionParams, ); t.comment(`setName tx hash for member 3: ${transactionHash}`); t.ok(transactionHash, "setName tx hash for member 3 truthy OK"); const result = await web3QuorumMember3.priv.waitForTransactionReceipt( transactionHash, ); t.comment(`Transaction receipt for set() call: ${JSON.stringify(result)}`); t.ok(result, "set() result for member 3 truthy OK"); } t.end(); });
the_stack
import React from 'react'; import { render, waitFor } from '@testing-library/react'; import gql from 'graphql-tag'; // @ts-ignore import { withState } from './recomposeWithState.js'; import { DocumentNode } from 'graphql'; import { ApolloClient } from '../../../../core'; import { ApolloProvider } from '../../../context'; import { InMemoryCache as Cache } from '../../../../cache'; import { QueryResult } from '../../../types/types'; import { itAsync, mockSingleLink } from '../../../../testing'; import { Query } from '../../../components/Query'; import { graphql } from '../../graphql'; import { ChildProps, DataValue } from '../../types'; describe('[queries] errors', () => { let error: typeof console.error; beforeEach(() => { error = console.error; console.error = jest.fn(() => {}); }); afterEach(() => { console.error = error; }); // errors itAsync('does not swallow children errors', (resolve, reject) => { let done = false; const query: DocumentNode = gql` query people { allPeople(first: 1) { people { name } } } `; const data = { allPeople: { people: [{ name: 'Luke Skywalker' }] } }; const link = mockSingleLink({ request: { query }, result: { data } }); const client = new ApolloClient({ link, cache: new Cache({ addTypename: false }) }); class ErrorBoundary extends React.Component { componentDidCatch(e: Error) { expect(e.message).toMatch(/bar is not a function/); done = true; } render() { return this.props.children; } } let bar: any; const ContainerWithData = graphql(query)(() => { bar(); // this will throw return null; }); render( <ApolloProvider client={client}> <ErrorBoundary> <ContainerWithData /> </ErrorBoundary> </ApolloProvider> ); waitFor(() => { expect(done).toBe(true); }).then(resolve, reject); }); it('can unmount without error', () => { const query: DocumentNode = gql` query people { allPeople(first: 1) { people { name } } } `; const data = { allPeople: { people: [{ name: 'Luke Skywalker' }] } }; const link = mockSingleLink({ request: { query }, result: { data } }); const client = new ApolloClient({ link, cache: new Cache({ addTypename: false }) }); const ContainerWithData = graphql(query)(() => null); const { unmount } = render( <ApolloProvider client={client}> <ContainerWithData /> </ApolloProvider> ) as any; try { unmount(); } catch (e) { throw new Error(e); } }); itAsync('passes any GraphQL errors in props', (resolve, reject) => { let done = false const query: DocumentNode = gql` query people { allPeople(first: 1) { people { name } } } `; const link = mockSingleLink({ request: { query }, error: new Error('boo') }); const client = new ApolloClient({ link, cache: new Cache({ addTypename: false }) }); const ErrorContainer = graphql(query)( class extends React.Component<ChildProps> { componentDidUpdate() { const { data } = this.props; expect(data!.error).toBeTruthy(); expect(data!.error!.networkError).toBeTruthy(); done = true } render() { return null; } } ); render( <ApolloProvider client={client}> <ErrorContainer /> </ApolloProvider> ); waitFor(() => { expect(done).toBe(true); }).then(resolve, reject); }); describe('uncaught exceptions', () => { const consoleWarn = console.warn; beforeAll(() => { console.warn = () => null; }); afterAll(() => { console.warn = consoleWarn; }); let unhandled: any[] = []; function handle(reason: any) { unhandled.push(reason); } beforeEach(() => { unhandled = []; process.on('unhandledRejection', handle); }); afterEach(() => { process.removeListener('unhandledRejection', handle); }); itAsync('does not log when you change variables resulting in an error', (resolve, reject) => { const query: DocumentNode = gql` query people($var: Int) { allPeople(first: $var) { people { name } } } `; const var1 = { var: 1 }; const data = { allPeople: { people: { name: 'Luke Skywalker' } } }; const var2 = { var: 2 }; const link = mockSingleLink( { request: { query, variables: var1 }, result: { data } }, { request: { query, variables: var2 }, error: new Error('boo') } ); const client = new ApolloClient({ link, cache: new Cache({ addTypename: false }) }); type Data = typeof data; type Vars = typeof var1; interface Props extends Vars { var: number; setVar: (val: number) => number; } let iteration = 0; let done = false; const ErrorContainer = withState('var', 'setVar', 1)( graphql<Props, Data, Vars>(query)( class extends React.Component<ChildProps<Props, Data, Vars>> { componentDidUpdate() { const { props } = this; iteration += 1; try { if (iteration === 1) { // initial loading state is done, we have data expect(props.data!.allPeople).toEqual( data.allPeople ); props.setVar(2); } else if (iteration === 2) { expect(props.data!.allPeople).toEqual( data.allPeople ); } else if (iteration === 3) { // variables have changed, wee are loading again but also have data expect(props.data!.loading).toBeTruthy(); } else if (iteration === 4) { // the second request had an error! expect(props.data!.error).toBeTruthy(); expect(props.data!.error!.networkError).toBeTruthy(); // // We need to set a timeout to ensure the unhandled rejection is swept up setTimeout(() => { try { expect(unhandled.length).toEqual(0); } catch (err) { reject(err); } done = true; }); } } catch (err) { reject(err); } } render() { return null; } } ) ); render( <ApolloProvider client={client}> <ErrorContainer /> </ApolloProvider> ); waitFor(() => expect(done).toBeTruthy()).then(resolve, reject); }); }); it('will not log a warning when there is an error that is not caught in the render method when using query', () => new Promise<void>((resolve, reject) => { const query: DocumentNode = gql` query people { allPeople(first: 1) { people { name } } } `; interface Data { allPeople: { people: { name: string }[]; }; } const link = mockSingleLink({ request: { query }, error: new Error('oops') }); const client = new ApolloClient({ link, cache: new Cache({ addTypename: false }) }); const origError = console.error; const errorMock = jest.fn(); console.error = errorMock; let renderCount = 0; @graphql<{}, Data>(query) class UnhandledErrorComponent extends React.Component< ChildProps<{}, Data> > { render(): React.ReactNode { try { switch (renderCount++) { case 0: expect(this.props.data!.loading).toEqual(true); break; case 1: // Noop. Don’t handle the error so a warning will be logged to the console. expect(renderCount).toBe(2); expect(errorMock.mock.calls.length).toBe(0); break; default: throw new Error('Too many renders.'); } } catch (error) { reject(error); } finally { console.error = origError; } return null; } } render( <ApolloProvider client={client}> <UnhandledErrorComponent /> </ApolloProvider> ); waitFor(() => { expect(renderCount).toBe(2); }).then(resolve, reject); })); itAsync('passes any cached data when there is a GraphQL error', (resolve, reject) => { const query: DocumentNode = gql` query people { allPeople(first: 1) { people { name } } } `; const data = { allPeople: { people: [{ name: 'Luke Skywalker' }] } }; type Data = typeof data; const link = mockSingleLink( { request: { query }, result: { data } }, { request: { query }, error: new Error('No Network Connection') } ); const client = new ApolloClient({ link, cache: new Cache({ addTypename: false }) }); let count = 0; const Container = graphql<{}, Data>(query, { options: { notifyOnNetworkStatusChange: true } })( class extends React.Component<ChildProps<{}, Data>> { componentDidUpdate() { const { props } = this; try { switch (count++) { case 0: expect(props.data!.allPeople).toEqual( data.allPeople ); setTimeout(() => { props.data!.refetch().catch(() => null); }); break; case 1: expect(props.data!.loading).toBeTruthy(); expect(props.data!.allPeople).toEqual( data.allPeople ); break; case 2: expect(props.data!.loading).toBeFalsy(); expect(props.data!.error).toBeTruthy(); expect(props.data!.allPeople).toEqual( data.allPeople ); break; default: throw new Error('Unexpected fall through'); } } catch (e) { reject(e); } } render() { return null; } } ); render( <ApolloProvider client={client}> <Container /> </ApolloProvider> ); waitFor(() => expect(count).toBe(3)).then(resolve, reject); }); itAsync('can refetch after there was a network error', (resolve, reject) => { const query: DocumentNode = gql` query somethingelse { allPeople(first: 1) { people { name } } } `; const data = { allPeople: { people: [{ name: 'Luke Skywalker' }] } }; const dataTwo = { allPeople: { people: [{ name: 'Princess Leia' }] } }; type Data = typeof data; const link = mockSingleLink( { request: { query }, result: { data } }, { request: { query }, error: new Error('This is an error!') }, { request: { query }, result: { data: dataTwo } } ); const client = new ApolloClient({ link, cache: new Cache({ addTypename: false }) }); let count = 0; const noop = () => null; const Container = graphql<{}, Data>(query, { options: { notifyOnNetworkStatusChange: true } })( class extends React.Component<ChildProps<{}, Data>> { componentDidUpdate() { const { props } = this; try { switch (count++) { case 0: props .data!.refetch() .then(() => { reject('Expected error value on first refetch.'); }) .catch(noop); break; case 1: expect(props.data!.loading).toBeTruthy(); break; case 2: expect(props.data!.loading).toBeFalsy(); expect(props.data!.error).toBeTruthy(); props .data!.refetch() .then(noop) .catch(() => { reject('Expected good data on second refetch.'); }); break; case 3: expect(props.data!.loading).toBeTruthy(); break; case 4: expect(props.data!.loading).toBeFalsy(); expect(props.data!.error).toBeFalsy(); expect(props.data!.allPeople).toEqual( dataTwo.allPeople ); break; default: throw new Error('Unexpected fall through'); } } catch (e) { reject(e); } } render() { return null; } } ); render( <ApolloProvider client={client}> <Container /> </ApolloProvider> ); waitFor(() => expect(count).toBe(5)).then(resolve, reject); }); itAsync('does not throw/console.err an error after a component that received a network error is unmounted', (resolve, reject) => { const query: DocumentNode = gql` query somethingelse { allPeople(first: 1) { people { name } } } `; const data = { allPeople: { people: [{ name: 'Luke Skywalker' }] } }; type Data = typeof data; const link = mockSingleLink( { request: { query }, result: { data } }, { request: { query }, error: new Error('This is an error!') } ); const client = new ApolloClient({ link, cache: new Cache({ addTypename: false }) }); let count = 0; const noop = () => null; interface ContainerOwnProps { hideContainer: Function; } interface QueryChildProps { data: DataValue<Data>; hideContainer: Function; } let done = false; const Container = graphql<ContainerOwnProps, Data, {}, QueryChildProps>( query, { options: { notifyOnNetworkStatusChange: true }, props: something => { return { data: something.data!, hideContainer: something!.ownProps.hideContainer }; } } )( class extends React.Component<ChildProps<QueryChildProps, Data>> { componentDidUpdate() { const { props } = this; try { switch (count++) { case 0: props .data!.refetch() .then(() => { reject('Expected error value on first refetch.'); }) .catch(noop); break; case 2: expect(props.data!.loading).toBeFalsy(); expect(props.data!.error).toBeTruthy(); const origError = console.error; const errorMock = jest.fn(); console.error = errorMock; props.hideContainer(); setTimeout(() => { expect(errorMock.mock.calls.length).toEqual(0); console.error = origError; done = true; }, 100); break; default: if (count < 2) { throw new Error('Unexpected fall through'); } } } catch (err) { reject(err); } } render() { return null; } } ); class Switcher extends React.Component<any, any> { constructor(props: any) { super(props); this.state = { showContainer: true }; } render() { const { state: { showContainer } } = this; if (showContainer) { return ( <Container hideContainer={() => this.setState({ showContainer: false })} /> ); } return null; } } render( <ApolloProvider client={client}> <Switcher /> </ApolloProvider> ); waitFor(() => expect(done).toBeTruthy()).then(resolve, reject); }); itAsync('correctly sets loading state on remount after a network error', (resolve, reject) => { const query: DocumentNode = gql` query somethingelse { allPeople(first: 1) { people { name } } } `; const data = { allPeople: { people: [{ name: 'Luke Skywalker' }] } }; const dataTwo = { allPeople: { people: [{ name: 'Princess Leia' }] } }; type Data = typeof data; const link = mockSingleLink( { request: { query }, error: new Error('This is an error!') }, { request: { query }, result: { data: dataTwo } } ); const client = new ApolloClient({ link, cache: new Cache({ addTypename: false }) }); let count = 0; type ContainerOwnProps = { toggle: () => void }; const Container = graphql<ContainerOwnProps, Data>(query, { options: { notifyOnNetworkStatusChange: true } })( class extends React.Component<ChildProps<ContainerOwnProps, Data>> { render() { switch (count) { case 0: expect(this.props.data!.loading).toBe(true); break; case 1: expect(this.props.data!.loading).toBe(false); expect(this.props.data!.error!.networkError!.message).toMatch( /This is an error/ ); // unmount this component setTimeout(() => { this.props.toggle(); }, 0); setTimeout(() => { // remount after 50 ms this.props.toggle(); }, 50); break; case 2: expect(this.props.data!.loading).toBe(true); break; case 3: expect(this.props.data!.loading).toBe(false); expect(this.props.data!.allPeople).toEqual(dataTwo.allPeople); break; default: throw new Error('Too many renders.'); } count += 1; return null; } } ); type Toggle = () => void; type OwnProps = { children: (toggle: Toggle) => any }; class Manager extends React.Component<OwnProps, { show: boolean }> { constructor(props: any) { super(props); this.state = { show: true }; } render() { if (!this.state.show) return null; return this.props.children(() => this.setState(({ show }) => ({ show: !show })) ); } } render( <ApolloProvider client={client}> <Manager>{(toggle: Toggle) => <Container toggle={toggle} />}</Manager> </ApolloProvider> ); waitFor(() => expect(count).toBe(4)).then(resolve, reject); }); describe('errorPolicy', () => { itAsync('passes any GraphQL errors in props along with data', (resolve, reject) => { let done = false; const query: DocumentNode = gql` query people { allPeople(first: 1) { people { name } } } `; const link = mockSingleLink({ request: { query }, result: { data: { allPeople: { people: null } }, errors: [new Error('this is an error')] } }); const client = new ApolloClient({ link, cache: new Cache({ addTypename: false }) }); const ErrorContainer = graphql(query, { options: { errorPolicy: 'all' } })( class extends React.Component<ChildProps> { componentDidUpdate() { const { data } = this.props; expect(data!.error).toBeTruthy(); expect(data!.error!.graphQLErrors[0].message).toEqual( 'this is an error' ); expect(data).toMatchObject({ allPeople: { people: null } }); done = true; } render() { return null; } } ); render( <ApolloProvider client={client}> <ErrorContainer /> </ApolloProvider> ); waitFor(() => { expect(done).toBe(true); }).then(resolve, reject); }); itAsync('passes any GraphQL errors in props along with data [component]', (resolve, reject) => { let done = false; const query: DocumentNode = gql` query people { allPeople(first: 1) { people { name } } } `; const link = mockSingleLink({ request: { query }, result: { data: { allPeople: { people: null } }, errors: [new Error('this is an error')] } }); const client = new ApolloClient({ link, cache: new Cache({ addTypename: false }) }); class ErrorContainer extends React.Component<QueryResult> { componentDidUpdate() { const { props } = this; expect(props.error).toBeTruthy(); expect(props.error!.graphQLErrors[0].message).toEqual( 'this is an error' ); expect(props.data!.allPeople!).toMatchObject({ people: null }); done = true; } render() { return null; } } render( <ApolloProvider client={client}> <Query query={query} errorPolicy="all"> {(props: any) => <ErrorContainer {...props} />} </Query> </ApolloProvider> ); waitFor(() => { expect(done).toBe(true); }).then(resolve, reject); }); }); });
the_stack
import { Application, expect, isFreePort, Router, RouterContext, } from "./deps.ts"; import { getFreePort, Test } from "../deps.ts"; import { describe, it } from "./utils.ts"; import { superoak } from "../mod.ts"; describe("superoak(url)", () => { it("superoak(url): should support `superoak(url)` if consumer wants to handle server themselves", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hello"; }); app.use(router.routes()); app.use(router.allowedMethods()); const controller = new AbortController(); const { signal } = controller; app.addEventListener("listen", async ({ hostname, port, secure }) => { const protocol = secure ? "https" : "http"; const url = `${protocol}://${hostname}:${port}`; (await superoak(url)) .get("/") .expect("hello", () => { controller.abort(); done(); }); }); await app.listen( { hostname: "localhost", port: await getFreePort(1024), signal }, ); }); describe(".end(cb)", () => { it("Oak: superoak(url): .end(cb): should set `this` to the test object when calling the `cb` in `.end(cb)`", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hello"; }); app.use(router.routes()); app.use(router.allowedMethods()); const controller = new AbortController(); const { signal } = controller; app.addEventListener( "listen", async ({ hostname, port, secure }) => { const protocol = secure ? "https" : "http"; const url = `${protocol}://${hostname}:${port}`; const test = (await superoak(url)).get("/"); test.end(function (this: Test) { expect(test).toEqual(this); controller.abort(); done(); }); }, ); await app.listen( { hostname: "localhost", port: await getFreePort(1024), signal }, ); }); it("superoak(url): .end(cb): should handle error returned when server goes down", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = ""; }); app.use(router.routes()); app.use(router.allowedMethods()); const controller = new AbortController(); const { signal } = controller; app.addEventListener( "listen", async ({ hostname, port, secure }) => { const protocol = secure ? "https" : "http"; const url = `${protocol}://${hostname}:${port}`; controller.abort(); (await superoak(url)) .get("/") .expect(200, (err) => { expect(err).toBeInstanceOf(Error); done(); }); }, ); await app.listen( { hostname: "localhost", port: await getFreePort(1024), signal }, ); }); }); }); describe("superoak(app)", () => { it("superoak(app): should fire up the app on an ephemeral port", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hey"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .end((_err, res) => { expect(res.status).toEqual(200); expect(res.text).toEqual("hey"); done(); }); }); it("superoak(app): should not follow redirects by default", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hey"; }); router.get("/redirect", (ctx: RouterContext) => { ctx.response.redirect("/"); }); app.use(router.routes()); app.use(router.allowedMethods()); const redirects: string[] = []; (await superoak(app)) .get("/redirect") .on("redirect", (res) => { redirects.push(res.headers.location); }) .then((res) => { expect(redirects).toEqual([]); expect(res.status).toEqual(302); done(); }); }); it("superoak(app): should follow redirects when instructed", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "Smudgie"; }); router.get("/redirect", (ctx: RouterContext) => { ctx.response.redirect("/"); }); app.use(router.routes()); app.use(router.allowedMethods()); const redirects: string[] = []; (await superoak(app)) .get("/redirect") .redirects(1) .on("redirect", (res) => { redirects.push(res.headers.location); }) .then((res) => { expect(redirects).toEqual(["/"]); expect(res.status).toEqual(200); expect(res.text).toEqual("Smudgie"); done(); }); }); // TODO: https test. // it("superoak(app, true): should work with a https server", (done) => {}); it("superoak(app): should work with .send() etc", async (done) => { const router = new Router(); const app = new Application(); router.post("/", async (ctx: RouterContext) => { if (ctx.request.hasBody) { ctx.response.body = await ctx.request.body(); } }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .post("/") .send({ name: "john" }) .expect("john", () => { done(); }); }); describe(".end(fn)", () => { it("superoak(app): .end(fn): should close server", async (done) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "superoak FTW!"; }); app.use(router.routes()); app.use(router.allowedMethods()); const portPromise: Promise<number> = new Promise((resolve) => { app.addEventListener("listen", ({ port }) => resolve(port)); }); (await superoak(app)).get("/") .end(async (_err, _res) => { const port: number = await portPromise; const isClosed = await isFreePort(port); expect(isClosed).toBeTruthy(); done(); }); }); // TODO: support nested requests using the same `superoak` instance. // it("superoak(app): .end(fn): should support nested requests", async ( // done, // ) => { // const router = new Router(); // const app = new Application(); // router.get("/", (ctx: RouterContext) => { // ctx.response.body = "superoak FTW!"; // }); // app.use(router.routes()); // app.use(router.allowedMethods()); // const test = await superoak(app); // test // .get("/") // .end(() => { // test // .get("/") // .end((err, res) => { // expect(err).toBeNull(); // expect(res.status).toEqual(200); // expect(res.text).toEqual("superoak FTW!"); // done(); // }); // }); // }); it("superoak(app): .end(fn): should support nested requests if create a new superoak instance", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "superoak FTW!"; }); app.use(router.routes()); app.use(router.allowedMethods()); let test = await superoak(app); test .get("/") .end(async () => { test = await superoak(app); test .get("/") .end((err, res) => { expect(err).toBeNull(); expect(res.status).toEqual(200); expect(res.text).toEqual("superoak FTW!"); done(); }); }); }); it("superoak(app): .end(fn): should include the response in the error callback", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "whatever"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect(() => { throw new Error("Some error"); }) .end((err, res) => { expect(err).toBeDefined(); expect(res).toBeDefined(); // Duck-typing response, just in case. expect(res.status).toEqual(200); done(); }); }); it("superoak(app): .end(fn): should set `this` to the test object when calling the error callback", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "whatever"; }); app.use(router.routes()); app.use(router.allowedMethods()); const test = (await superoak(app)).get("/"); test.expect(() => { throw new Error("Some error"); }).end(function (this: Test, err, _res) { expect(err).toBeDefined(); expect(this).toEqual(test); done(); }); }); it("superoak(app): .end(fn): should handle an undefined Response", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", async (ctx: RouterContext) => { await new Promise((resolve) => { setTimeout(() => { ctx.response.body = ""; resolve(true); }, 20); }); }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)).get("/").timeout(1) .expect(200, (err, _res) => { expect(err).toBeInstanceOf(Error); done(); }); }); // TODO: determine if _can_ test a server going down? }); describe(".expect(status[, fn])", () => { it("superoak(app): .expect(status[, fn]): should assert the response status", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hey"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect(404) .end((err, _res) => { expect(err.message).toEqual('expected 404 "Not Found", got 200 "OK"'); done(); }); }); }); describe(".expect(status)", () => { it("superoak(app): .expect(status): should assert only status", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hey"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect(200) .end(done); }); }); describe(".expect(status, body[, fn])", () => { it("superoak(app): .expect(status, body[, fn]): should assert the response body and status", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "foo"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect(200, "foo", done); }); describe("when the body argument is an empty string", () => { it("superoak(app): .expect(status, body[, fn]): should not quietly pass on failure", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "foo"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect(200, "") .end((err, _res) => { expect(err.message).toEqual('expected "" response body, got "foo"'); done(); }); }); }); }); describe(".expect(body[, fn])", () => { it("superoak(app): .expect(body[, fn]): should assert the response body", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = { foo: "bar" }; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect("hey") .end((err, _res) => { expect(err.message).toEqual( 'expected "hey" response body, got \'{"foo":"bar"}\'', ); done(); }); }); it("superoak(app): .expect(body[, fn]): should assert the status before the body", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.status = 500; ctx.response.body = { message: "something went wrong" }; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect(200) .expect("hey") .end((err, _res) => { expect(err.message).toEqual( 'expected 200 "OK", got 500 "Internal Server Error"', ); done(); }); }); it("superoak(app): .expect(body[, fn]): should assert the response text", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = { foo: "bar" }; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect('{"foo":"bar"}', done); }); it("superoak(app): .expect(body[, fn]): should assert the parsed response body", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = { foo: "bar" }; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect({ foo: "baz" }) .end(async (err, _res) => { expect(err.message).toEqual( 'expected { foo: "baz" } response body, got { foo: "bar" }', ); (await superoak(app)) .get("/") .expect({ foo: "bar" }) .end(done); }); }); it("superoak(app): .expect(body[, fn]): should test response object types", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.status = 200; ctx.response.body = { stringValue: "foo", numberValue: 3 }; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect({ stringValue: "foo", numberValue: 3 }, done); }); it("superoak(app): .expect(body[, fn]): should deep test response object types", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.status = 200; ctx.response.body = { stringValue: "foo", numberValue: 3, nestedObject: { innerString: "5" }, }; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect( { stringValue: "foo", numberValue: 3, nestedObject: { innerString: 5 }, }, ) .end(async (err, _res) => { expect(err.message).toEqual( 'expected { stringValue: "foo", numberValue: 3, nestedObject: { innerString: 5 } } response body, got { stringValue: "foo", numberValue: 3, nestedObject: { innerString: "5" } }', ); // eslint-disable-line max-len (await superoak(app)) .get("/") .expect( { stringValue: "foo", numberValue: 3, nestedObject: { innerString: "5" }, }, ) .end(done); }); }); it("superoak(app): .expect(body[, fn]): should support regular expressions", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "foobar"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect(/^bar/) .end((err, _res) => { expect(err.message).toEqual('expected body "foobar" to match /^bar/'); done(); }); }); }); it("superoak(app): .expect(body[, fn]): should assert response body multiple times", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hey deno"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect(/deno/) .expect("hey") .expect("hey deno") .end((err, _res) => { expect(err.message).toEqual( 'expected "hey" response body, got "hey deno"', ); done(); }); it("superoak(app): .expect(body[, fn]): should assert response body multiple times with no exception", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hey deno"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect(/deno/) .expect(/^hey/) .expect("hey deno", done); }); }); describe(".expect(field, value[, fn])", () => { it("superoak(app): .expect(field, value[, fn]): should assert the header field presence", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = { foo: "bar" }; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect("Content-Foo", "bar") .end((err, _res) => { expect(err.message).toEqual('expected "Content-Foo" header field'); done(); }); }); it("superoak(app): .expect(field, value[, fn]): should assert the header field value", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = { foo: "bar" }; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect("Content-Type", "text/plain") .end((err, _res) => { expect(err.message).toEqual( 'expected "Content-Type" of "text/plain", got "application/json; charset=utf-8"', ); done(); }); }); it("superoak(app): .expect(field, value[, fn]): should assert multiple fields", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hey"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect("Content-Type", "text/plain; charset=utf-8") .expect("Content-Length", "3") .end(done); }); it("superoak(app): .expect(field, value[, fn]): should support regular expressions", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hey"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect("Content-Type", /^application/) .end((err) => { expect(err.message).toEqual( 'expected "Content-Type" matching /^application/, got "text/plain; charset=utf-8"', ); done(); }); }); it("superoak(app): .expect(field, value[, fn]): should support numbers", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hey"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect("Content-Length", 4) .end((err) => { expect(err.message).toEqual( 'expected "Content-Length" of "4", got "3"', ); done(); }); }); describe("handling arbitrary expect functions", () => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hey"; }); app.use(router.routes()); app.use(router.allowedMethods()); it("superoak(app): .expect(field, value[, fn]): reports errors", async ( done, ) => { (await superoak(app)).get("/") .expect((_res) => { throw new Error("failed"); }) .end((err) => { expect(err.message).toEqual("failed"); done(); }); }); it( "superoak(app): .expect(field, value[, fn]): ensures truthy non-errors returned from asserts are not promoted to errors", async (done) => { (await superoak(app)).get("/") .expect((_res) => { return "some descriptive error"; }) .end((err) => { expect(err).toBeNull(); done(); }); }, ); it("superoak(app): .expect(field, value[, fn]): ensures truthy errors returned from asserts are throw to end", async ( done, ) => { (await superoak(app)).get("/") .expect((_res) => { return new Error("some descriptive error"); }) .end((err) => { expect(err.message).toEqual("some descriptive error"); expect(err).toBeInstanceOf(Error); done(); }); }); it("superoak(app): .expect(field, value[, fn]): doesn't create false negatives", async ( done, ) => { (await superoak(app)).get("/") .expect((_res) => { }) .end(done); }); it("superoak(app): .expect(field, value[, fn]): handles multiple asserts", async ( done, ) => { const calls: number[] = []; (await superoak(app)).get("/") .expect((_res) => { calls[0] = 1; }) .expect((_res) => { calls[1] = 1; }) .expect((_res) => { calls[2] = 1; }) .end(() => { const callCount = [0, 1, 2].reduce((count, i) => { return count + calls[i]; }, 0); expect(callCount).toEqual(3); done(); }); }); it("superoak(app): .expect(field, value[, fn]): plays well with normal assertions - no false positives", async ( done, ) => { (await superoak(app)).get("/") .expect((_res) => { }) .expect("Content-Type", /json/) .end((err) => { expect(err.message).toMatch(/Content-Type/); done(); }); }); it("superoak(app): .expect(field, value[, fn]): plays well with normal assertions - no false negatives", async ( done, ) => { (await superoak(app)).get("/") .expect((_res) => { }) .expect("Content-Type", /plain/) .expect((_res) => { }) .expect("Content-Type", /text/) .end(done); }); }); describe("handling multiple assertions per field", () => { it("superoak(app): .expect(field, value[, fn]): should work", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hey"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect("Content-Type", /text/) .expect("Content-Type", /plain/) .end(done); }); it("superoak(app): .expect(field, value[, fn]): should return an error if the first one fails", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hey"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect("Content-Type", /bloop/) .expect("Content-Type", /plain/) .end((err) => { expect(err.message).toEqual( 'expected "Content-Type" matching /bloop/, ' + 'got "text/plain; charset=utf-8"', ); done(); }); }); it("superoak(app): .expect(field, value[, fn]): should return an error if a middle one fails", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hey"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect("Content-Type", /text/) .expect("Content-Type", /bloop/) .expect("Content-Type", /plain/) .end((err) => { expect(err.message).toEqual( 'expected "Content-Type" matching /bloop/, ' + 'got "text/plain; charset=utf-8"', ); done(); }); }); it("superoak(app): .expect(field, value[, fn]): should return an error if the last one fails", async ( done, ) => { const router = new Router(); const app = new Application(); router.get("/", (ctx: RouterContext) => { ctx.response.body = "hey"; }); app.use(router.routes()); app.use(router.allowedMethods()); (await superoak(app)) .get("/") .expect("Content-Type", /text/) .expect("Content-Type", /plain/) .expect("Content-Type", /bloop/) .end((err) => { expect(err.message).toEqual( 'expected "Content-Type" matching /bloop/, ' + 'got "text/plain; charset=utf-8"', ); done(); }); }); }); }); });
the_stack
import {OAuth2Client} from 'google-auth-library'; import {google, script_v1 as scriptV1} from 'googleapis'; import {createServer} from 'http'; import open from 'open'; import readline from 'readline'; import enableDestroy from 'server-destroy'; import type {Credentials, GenerateAuthUrlOpts, OAuth2ClientOptions} from 'google-auth-library'; import type {IncomingMessage, Server, ServerResponse} from 'http'; import type {AddressInfo} from 'net'; import type {ReadonlyDeep} from 'type-fest'; import {ClaspError} from './clasp-error.js'; import {DOTFILE} from './dotfile.js'; import {ERROR, LOG} from './messages.js'; import {checkIfOnlineOrDie, getOAuthSettings} from './utils.js'; import type {ClaspToken} from './dotfile'; import type {ClaspCredentials} from './utils'; /** * Authentication with Google's APIs. */ // Auth is complicated. Consider yourself warned. // GLOBAL: clasp login will store this (~/.clasprc.json): // { // "access_token": "XXX", // "refresh_token": "1/k4rt_hgxbeGdaRag2TSVgnXgUrWcXwerPpvlzGG1peHVfzI58EZH0P25c7ykiRYd", // "scope": "https://www.googleapis.com/auth/script.projects https://www.googleapis.com/auth/script ...", // "token_type": "Bearer", // "expiry_date": 1539130731398 // } // LOCAL: clasp login will store this (./.clasprc.json): // { // "token": { // "access_token": "XXX", // "refresh_token": "1/k4rw_hgxbeGdaRag2TSVgnXgUrWcXwerPpvlzGG1peHVfzI58EZH0P25c7ykiRYd", // "scope": "https://www.googleapis.com/auth/script.projects https://www.googleapis.com/auth/script ...", // "token_type": "Bearer", // "expiry_date": 1539130731398 // }, // // Settings // "oauth2ClientSettings": { // "clientId": "807925367021-infvb16rd7lasqi22q2npeahkeodfrq5.apps.googleusercontent.com", // "clientSecret": "9dbdeOCRHUyriewCoDrLHtPg", // "redirectUri": "http://localhost" // }, // "isLocalCreds": true // } // API settings // @see https://developers.google.com/oauthplayground/ const REDIRECT_URI_OOB = 'urn:ietf:wg:oauth:2.0:oob'; const globalOauth2ClientSettings: OAuth2ClientOptions = { clientId: '1072944905499-vm2v2i5dvn0a0d2o4ca36i1vge8cvbn0.apps.googleusercontent.com', clientSecret: 'v6V3fKV_zWU7iw1DrpO1rknX', redirectUri: 'http://localhost', }; const globalOAuth2Client = new OAuth2Client(globalOauth2ClientSettings); let localOAuth2Client: OAuth2Client; // Must be set up after authorize. // *Global* Google API clients export const discovery = google.discovery({version: 'v1'}); export const drive = google.drive({version: 'v3', auth: globalOAuth2Client}); export const logger = google.logging({version: 'v2', auth: globalOAuth2Client}); export const script = google.script({version: 'v1', auth: globalOAuth2Client}); export const serviceUsage = google.serviceusage({version: 'v1', auth: globalOAuth2Client}); /** * Gets the local OAuth client for the Google Apps Script API. * Only the Apps Script API needs to use local credential for the Execution API (script.run). * @see https://developers.google.com/apps-script/api/how-tos/execute */ export const getLocalScript = async (): Promise<scriptV1.Script> => google.script({version: 'v1', auth: localOAuth2Client}); export const scopeWebAppDeploy = 'https://www.googleapis.com/auth/script.webapp.deploy'; // Scope needed for script.run export const defaultScopes = [ // Default to clasp scopes 'https://www.googleapis.com/auth/script.deployments', // Apps Script deployments 'https://www.googleapis.com/auth/script.projects', // Apps Script management scopeWebAppDeploy, // Apps Script Web Apps 'https://www.googleapis.com/auth/drive.metadata.readonly', // Drive metadata 'https://www.googleapis.com/auth/drive.file', // Create Drive files 'https://www.googleapis.com/auth/service.management', // Cloud Project Service Management API 'https://www.googleapis.com/auth/logging.read', // StackDriver logs 'https://www.googleapis.com/auth/userinfo.email', // User email address 'https://www.googleapis.com/auth/userinfo.profile', // Extra scope since service.management doesn't work alone 'https://www.googleapis.com/auth/cloud-platform', ]; /** * Requests authorization to manage Apps Script projects. * @param {boolean} useLocalhost Uses a local HTTP server if true. Manual entry o.w. * @param {ClaspCredentials?} creds An optional credentials object. * @param {string[]} [scopes=[]] List of OAuth scopes to authorize. */ export const authorize = async (options: { readonly creds?: Readonly<ClaspCredentials>; readonly scopes: readonly string[]; // Only used with custom creds. readonly useLocalhost: boolean; }) => { try { // Set OAuth2 Client Options let oAuth2ClientOptions: OAuth2ClientOptions; if (options.creds) { // If we passed our own creds // Use local credentials const { client_id: clientId, client_secret: clientSecret, project_id, redirect_uris: redirectUris, } = options.creds.installed; console.log(LOG.CREDS_FROM_PROJECT(project_id)); oAuth2ClientOptions = {clientId, clientSecret, redirectUri: redirectUris[0]}; } else { // Use global credentials const globalOauth2ClientOptions: OAuth2ClientOptions = { clientId: '1072944905499-vm2v2i5dvn0a0d2o4ca36i1vge8cvbn0.apps.googleusercontent.com', clientSecret: 'v6V3fKV_zWU7iw1DrpO1rknX', redirectUri: 'http://localhost', }; oAuth2ClientOptions = globalOauth2ClientOptions; } // Set scopes let scope = ( options.creds ? // Set scopes to custom scopes options.scopes : defaultScopes ) as string[]; if (options.creds && scope.length === 0) { scope = defaultScopes; // TODO formal error // throw new ClaspError('You need to specify scopes in the manifest.' + // 'View appsscript.json. Add a list of scopes in "oauthScopes"' + // 'Tip:' + // '1. clasp open' + // '2. File > Project Properties > Scopes'); } const oAuth2ClientAuthUrlOptions: GenerateAuthUrlOpts = {access_type: 'offline', scope}; // Grab a token from the credentials. const token = await (options.useLocalhost ? authorizeWithLocalhost : authorizeWithoutLocalhost)( oAuth2ClientOptions, oAuth2ClientAuthUrlOptions ); console.log(`${LOG.AUTH_SUCCESSFUL}\n`); // Save the token and own creds together. let claspToken: ClaspToken; if (options.creds) { const {client_id: clientId, client_secret: clientSecret, redirect_uris: redirectUri} = options.creds.installed; // Save local ClaspCredentials. claspToken = { token, oauth2ClientSettings: {clientId, clientSecret, redirectUri: redirectUri[0]}, isLocalCreds: true, }; } else { // Save global ClaspCredentials. claspToken = { token, oauth2ClientSettings: globalOauth2ClientSettings, isLocalCreds: false, }; } await DOTFILE.AUTH(claspToken.isLocalCreds).write(claspToken); console.log(LOG.SAVED_CREDS(Boolean(options.creds))); } catch (error) { if (error instanceof ClaspError) { throw error; } throw new ClaspError(`${ERROR.ACCESS_TOKEN}${error}`); } }; export const getLoggedInEmail = async () => { await loadAPICredentials(); try { return (await google.oauth2('v2').userinfo.get({auth: globalOAuth2Client})).data.email; } catch { return; } }; /** * Loads the Apps Script API credentials for the CLI. * * Required before every API call. */ export const loadAPICredentials = async (local = false): Promise<ClaspToken> => { // Gets the OAuth settings. May be local or global. const rc: ClaspToken = await getOAuthSettings(local); await setOauthClientCredentials(rc); return rc; }; /** * Requests authorization to manage Apps Script projects. Spins up * a temporary HTTP server to handle the auth redirect. * @param {OAuth2ClientOptions} oAuth2ClientOptions The required client options for auth * @param {GenerateAuthUrlOpts} oAuth2ClientAuthUrlOptions Auth URL options * Used for local/global testing. */ const authorizeWithLocalhost = async ( oAuth2ClientOptions: Readonly<OAuth2ClientOptions>, oAuth2ClientAuthUrlOptions: Readonly<GenerateAuthUrlOpts> ): Promise<Credentials> => { // Wait until the server is listening, otherwise we don't have // the server port needed to set up the Oauth2Client. const server = await new Promise<Server>(resolve => { const s = createServer(); enableDestroy(s); s.listen(0, () => resolve(s)); }); const {port} = server.address() as AddressInfo; const client = new OAuth2Client({...oAuth2ClientOptions, redirectUri: `http://localhost:${port}`}); // TODO Add spinner const authCode = await new Promise<string>((resolve, reject) => { server.on('request', (request: ReadonlyDeep<IncomingMessage>, response: ReadonlyDeep<ServerResponse>) => { const urlParts = new URL(request.url ?? '', 'http://localhost').searchParams; const code = urlParts.get('code'); const error = urlParts.get('error'); if (code) { resolve(code); } else { reject(error); } response.end(LOG.AUTH_PAGE_SUCCESSFUL); }); const authUrl = client.generateAuthUrl(oAuth2ClientAuthUrlOptions); console.log(LOG.AUTHORIZE(authUrl)); (async () => open(authUrl))(); }); server.destroy(); return (await client.getToken(authCode)).tokens; }; /** * Requests authorization to manage Apps Script projects. Requires the user to * manually copy/paste the authorization code. No HTTP server is used. * @param {OAuth2ClientOptions} oAuth2ClientOptions The required client options for auth. * @param {GenerateAuthUrlOpts} oAuth2ClientAuthUrlOptions Auth URL options */ const authorizeWithoutLocalhost = async ( oAuth2ClientOptions: Readonly<OAuth2ClientOptions>, oAuth2ClientAuthUrlOptions: Readonly<GenerateAuthUrlOpts> ): Promise<Credentials> => { const client = new OAuth2Client({...oAuth2ClientOptions, redirectUri: REDIRECT_URI_OOB}); console.log(LOG.AUTHORIZE(client.generateAuthUrl(oAuth2ClientAuthUrlOptions))); // TODO Add spinner const authCode = await new Promise<string>((resolve, reject) => { const rl = readline.createInterface({input: process.stdin, output: process.stdout}); rl.question(LOG.AUTH_CODE, (code: string) => { rl.close(); if (code && code.length > 0) { resolve(code); } else { reject(new ClaspError('No authorization code entered.')); } }); }); return (await client.getToken(authCode)).tokens; }; /** * Set OAuth client credentails from rc. * Can be global or local. * Saves new credentials if access token refreshed. * @param {ClaspToken} rc OAuth client settings from rc file. */ // Because of mutation: const setOauthClientCredentials = async (rc: ClaspToken) => { /** * Refreshes the credentials and saves them. */ const refreshCredentials = async (oAuthClient: ReadonlyDeep<OAuth2Client>) => { await oAuthClient.getAccessToken(); // Refreshes expiry date if required rc.token = oAuthClient.credentials; }; // Set credentials and refresh them. try { await checkIfOnlineOrDie(); if (rc.isLocalCreds) { const {clientId, clientSecret, redirectUri} = rc.oauth2ClientSettings; localOAuth2Client = new OAuth2Client({clientId, clientSecret, redirectUri}); localOAuth2Client.setCredentials(rc.token); await refreshCredentials(localOAuth2Client); } else { globalOAuth2Client.setCredentials(rc.token); await refreshCredentials(globalOAuth2Client); } // Save the credentials. await DOTFILE.AUTH(rc.isLocalCreds).write(rc); } catch (error) { if (error instanceof ClaspError) { throw error; } throw new ClaspError(`${ERROR.ACCESS_TOKEN}${error}`); } }; // /** // * Compare global OAuth client scopes against manifest and prompt user to // * authorize if new scopes found (local OAuth credentails only). // * @param {ClaspToken} rc OAuth client settings from rc file. // */ // // TODO: currently unused. Check relevancy // export async function checkOauthScopes(rc: ReadonlyDeep<ClaspToken>) { // try { // await checkIfOnline(); // await setOauthClientCredentials(rc); // const {scopes} = await globalOAuth2Client.getTokenInfo(globalOAuth2Client.credentials.access_token as string); // const {oauthScopes} = await readManifest(); // const newScopes = oauthScopes && oauthScopes.length > 1 ? oauthScopes.filter(x => !scopes.includes(x)) : []; // if (newScopes.length === 0) return; // console.log('New authorization scopes detected in manifest:\n', newScopes); // const answers = await oauthScopesPrompt(); // if (answers.doAuth) { // if (!rc.isLocalCreds) throw new ClaspError(ERROR.NO_LOCAL_CREDENTIALS); // await authorize({useLocalhost: answers.localhost, scopes: newScopes}); // } // } catch (error) { // if (error instanceof ClaspError) throw error; // throw new ClaspError(ERROR.BAD_REQUEST((error as {message: string}).message)); // } // }
the_stack
import { ILifecycleEvents, IPuppetFrame, IPuppetFrameEvents, } from '@secret-agent/interfaces/IPuppetFrame'; import { URL } from 'url'; import Protocol from 'devtools-protocol'; import { CanceledPromiseError } from '@secret-agent/commons/interfaces/IPendingWaitEvent'; import { TypedEventEmitter } from '@secret-agent/commons/eventUtils'; import { NavigationReason } from '@secret-agent/interfaces/INavigation'; import { IBoundLog } from '@secret-agent/interfaces/ILog'; import Resolvable from '@secret-agent/commons/Resolvable'; import ProtocolError from './ProtocolError'; import { DevtoolsSession } from './DevtoolsSession'; import ConsoleMessage from './ConsoleMessage'; import { DEFAULT_PAGE, ISOLATED_WORLD } from './FramesManager'; import { NavigationLoader } from './NavigationLoader'; import PageFrame = Protocol.Page.Frame; const ContextNotFoundCode = -32000; const InPageNavigationLoaderPrefix = 'inpage'; export default class Frame extends TypedEventEmitter<IPuppetFrameEvents> implements IPuppetFrame { public get id(): string { return this.internalFrame.id; } public get name(): string { return this.internalFrame.name ?? ''; } public get parentId(): string { return this.internalFrame.parentId; } public url: string; public get isDefaultUrl(): boolean { return !this.url || this.url === ':' || this.url === DEFAULT_PAGE; } public get securityOrigin(): string { if (!this.activeLoader?.isNavigationComplete || this.isDefaultUrl) return ''; let origin = this.internalFrame.securityOrigin; if (!origin || origin === '://') { this.internalFrame.securityOrigin = new URL(this.url).origin; origin = this.internalFrame.securityOrigin; } return origin; } public navigationReason?: string; public disposition?: string; public get isAttached(): boolean { return this.checkIfAttached(); } public get activeLoader(): NavigationLoader { return this.navigationLoadersById[this.activeLoaderId]; } public activeLoaderId: string; public navigationLoadersById: { [loaderId: string]: NavigationLoader } = {}; protected readonly logger: IBoundLog; private isolatedWorldElementObjectId?: string; private readonly parentFrame: Frame | null; private readonly devtoolsSession: DevtoolsSession; private defaultLoaderId: string; private startedLoaderId: string; private defaultContextId: number; private isolatedContextId: number; private readonly activeContextIds: Set<number>; private internalFrame: PageFrame; private closedWithError: Error; private defaultContextCreated: Resolvable<void>; private readonly checkIfAttached: () => boolean; private inPageCounter = 0; constructor( internalFrame: PageFrame, activeContextIds: Set<number>, devtoolsSession: DevtoolsSession, logger: IBoundLog, checkIfAttached: () => boolean, parentFrame: Frame | null, ) { super(); this.activeContextIds = activeContextIds; this.devtoolsSession = devtoolsSession; this.logger = logger.createChild(module); this.parentFrame = parentFrame; this.checkIfAttached = checkIfAttached; this.setEventsToLog(['frame-requested-navigation', 'frame-navigated', 'frame-lifecycle']); this.storeEventsWithoutListeners = true; this.onAttached(internalFrame); } public close(error: Error) { this.cancelPendingEvents('Frame closed'); error ??= new CanceledPromiseError('Frame closed'); this.activeLoader.setNavigationResult(error); this.defaultContextCreated?.reject(error); this.closedWithError = error; } public async evaluate<T>( expression: string, isolateFromWebPageEnvironment?: boolean, options?: { shouldAwaitExpression?: boolean; retriesWaitingForLoad?: number }, ): Promise<T> { if (this.closedWithError) throw this.closedWithError; const startUrl = this.url; const startOrigin = this.securityOrigin; const contextId = await this.waitForActiveContextId(isolateFromWebPageEnvironment); try { const result: Protocol.Runtime.EvaluateResponse = await this.devtoolsSession.send( 'Runtime.evaluate', { expression, contextId, returnByValue: true, awaitPromise: options?.shouldAwaitExpression ?? true, }, this, ); if (result.exceptionDetails) { throw ConsoleMessage.exceptionToError(result.exceptionDetails); } const remote = result.result; if (remote.objectId) this.devtoolsSession.disposeRemoteObject(remote); return remote.value as T; } catch (err) { let retries = options?.retriesWaitingForLoad ?? 0; // if we had a context id from a blank page, try again if ( (!startOrigin || this.url !== startUrl) && this.getActiveContextId(isolateFromWebPageEnvironment) !== contextId ) { retries += 1; } const isNotFoundError = err.code === ContextNotFoundCode || (err as ProtocolError).remoteError?.code === ContextNotFoundCode; if (isNotFoundError) { if (retries > 0) { // Cannot find context with specified id (ie, could be reloading or unloading) return this.evaluate(expression, isolateFromWebPageEnvironment, { shouldAwaitExpression: options?.shouldAwaitExpression, retriesWaitingForLoad: retries - 1, }); } throw new CanceledPromiseError('The page context to evaluate javascript was not found'); } throw err; } } public async waitForLifecycleEvent( event: keyof ILifecycleEvents = 'load', loaderId?: string, timeoutMs = 30e3, ): Promise<void> { event ??= 'load'; timeoutMs ??= 30e3; await this.waitForLoader(loaderId, timeoutMs); const loader = this.navigationLoadersById[loaderId ?? this.activeLoaderId]; if (loader.lifecycle[event]) return; await this.waitOn( 'frame-lifecycle', x => { if (loaderId && x.loader.id !== loaderId) return false; return x.name === event; }, timeoutMs, ); } public async setFileInputFiles(objectId: string, files: string[]): Promise<void> { await this.devtoolsSession.send('DOM.setFileInputFiles', { objectId, files, }); } public async evaluateOnNode<T>(nodeId: string, expression: string): Promise<T> { if (this.closedWithError) throw this.closedWithError; try { const result = await this.devtoolsSession.send('Runtime.callFunctionOn', { functionDeclaration: `function executeRemoteFn() { return ${expression}; }`, returnByValue: true, objectId: nodeId, }); if (result.exceptionDetails) { throw ConsoleMessage.exceptionToError(result.exceptionDetails); } const remote = result.result; if (remote.objectId) this.devtoolsSession.disposeRemoteObject(remote); return remote.value as T; } catch (err) { if (err instanceof CanceledPromiseError) return; throw err; } } public async getFrameElementNodeId(): Promise<string> { try { if (!this.parentFrame || this.isolatedWorldElementObjectId) return this.isolatedWorldElementObjectId; const owner = await this.devtoolsSession.send('DOM.getFrameOwner', { frameId: this.id }); this.isolatedWorldElementObjectId = await this.parentFrame.resolveNodeId(owner.backendNodeId); // don't dispose... will cleanup frame return this.isolatedWorldElementObjectId; } catch (error) { // ignore errors looking this up this.logger.info('Failed to lookup isolated node', { frameId: this.id, error, }); } } public async resolveNodeId(backendNodeId: number): Promise<string> { const result = await this.devtoolsSession.send('DOM.resolveNode', { backendNodeId, executionContextId: this.getActiveContextId(true), }); return result.object.objectId; } /////// NAVIGATION /////////////////////////////////////////////////////////////////////////////////////////////////// public initiateNavigation(url: string, loaderId: string): void { // chain current listeners to new promise this.setLoader(loaderId, url); } public requestedNavigation(url: string, reason: NavigationReason, disposition: string): void { this.navigationReason = reason; this.disposition = disposition; this.emit('frame-requested-navigation', { frame: this, url, reason }); } public onAttached(internalFrame: PageFrame): void { this.internalFrame = internalFrame; this.updateUrl(); if (!internalFrame.loaderId) return; // if we this is the first loader and url is default, this is the first loader if ( this.isDefaultUrl && !this.defaultLoaderId && Object.keys(this.navigationLoadersById).length === 0 ) { this.defaultLoaderId = internalFrame.loaderId; } this.setLoader(internalFrame.loaderId); if (this.url || internalFrame.unreachableUrl) { // if this is a loaded frame, just count it as loaded. it shouldn't fail this.navigationLoadersById[internalFrame.loaderId].setNavigationResult(internalFrame.url); } } public onNavigated(frame: PageFrame): void { this.internalFrame = frame; this.updateUrl(); const loader = this.navigationLoadersById[frame.loaderId] ?? this.activeLoader; if (frame.unreachableUrl) { loader.setNavigationResult( new Error(`Unreachable url for navigation "${frame.unreachableUrl}"`), ); } else { loader.setNavigationResult(frame.url); } this.emit('frame-navigated', { frame: this, loaderId: frame.loaderId }); } public onNavigatedWithinDocument(url: string): void { if (this.url === url) return; // we're using params on about:blank, so make sure to strip for url if (url.startsWith(DEFAULT_PAGE)) url = DEFAULT_PAGE; this.url = url; const isDomLoaded = this.activeLoader?.lifecycle?.DOMContentLoaded; const loaderId = `${InPageNavigationLoaderPrefix}${(this.inPageCounter += 1)}`; this.setLoader(loaderId, url); if (isDomLoaded) { this.activeLoader.markLoaded(); } this.emit('frame-navigated', { frame: this, navigatedInDocument: true, loaderId }); } /////// LIFECYCLE //////////////////////////////////////////////////////////////////////////////////////////////////// public onStoppedLoading(): void { if (!this.startedLoaderId) return; const loader = this.navigationLoadersById[this.startedLoaderId]; loader?.onStoppedLoading(); } public async waitForLoader(loaderId?: string, timeoutMs?: number): Promise<Error | null> { if (!loaderId) { loaderId = this.activeLoaderId; if (loaderId === this.defaultLoaderId) { // wait for an actual frame to load const frameLoader = await this.waitOn('frame-loader-created', null, timeoutMs ?? 60e3); loaderId = frameLoader.loaderId; } } const hasLoaderError = await this.navigationLoadersById[loaderId]?.navigationResolver; if (hasLoaderError instanceof Error) return hasLoaderError; if (!this.getActiveContextId(false)) { await this.waitForDefaultContext(); } } public onLifecycleEvent(name: string, pageLoaderId?: string): void { const loaderId = pageLoaderId ?? this.activeLoaderId; if (name === 'init' && pageLoaderId) { // if the active loader never initiates before this new one, we should notify if ( this.activeLoaderId && this.activeLoaderId !== pageLoaderId && !this.activeLoader.lifecycle.init && !this.activeLoader.isNavigationComplete ) { this.activeLoader.setNavigationResult(new CanceledPromiseError('Navigation canceled')); } this.startedLoaderId = pageLoaderId; } if (!this.navigationLoadersById[loaderId]) { this.setLoader(loaderId); } this.navigationLoadersById[loaderId].onLifecycleEvent(name); if (loaderId !== this.activeLoaderId) { let checkLoaderForInPage = false; for (const [historicalLoaderId, loader] of Object.entries(this.navigationLoadersById)) { if (loaderId === historicalLoaderId) { checkLoaderForInPage = true; } if (checkLoaderForInPage && historicalLoaderId.startsWith(InPageNavigationLoaderPrefix)) { loader.onLifecycleEvent(name); this.emit('frame-lifecycle', { frame: this, name, loader }); } } } if (loaderId !== this.defaultLoaderId) { this.emit('frame-lifecycle', { frame: this, name, loader: this.navigationLoadersById[loaderId], }); } } /////// CONTEXT ID ////////////////////////////////////////////////////////////////////////////////////////////////// public hasContextId(executionContextId: number): boolean { return ( this.defaultContextId === executionContextId || this.isolatedContextId === executionContextId ); } public removeContextId(executionContextId: number): void { if (this.defaultContextId === executionContextId) this.defaultContextId = null; if (this.isolatedContextId === executionContextId) this.isolatedContextId = null; } public clearContextIds(): void { this.defaultContextId = null; this.isolatedContextId = null; } public addContextId(executionContextId: number, isDefault: boolean): void { if (isDefault) { this.defaultContextId = executionContextId; this.defaultContextCreated?.resolve(); } else { this.isolatedContextId = executionContextId; } } public getActiveContextId(isolatedContext: boolean): number | undefined { let id: number; if (isolatedContext) { id = this.isolatedContextId; } else { id = this.defaultContextId; } if (id && this.activeContextIds.has(id)) return id; } public async waitForActiveContextId(isolatedContext = true): Promise<number> { if (!this.isAttached) throw new Error('Execution Context is not available in detached frame'); const existing = this.getActiveContextId(isolatedContext); if (existing) return existing; if (isolatedContext) { const context = await this.createIsolatedWorld(); // give one task to set up await new Promise(setImmediate); return context; } await this.waitForDefaultContext(); return this.getActiveContextId(isolatedContext); } public canEvaluate(isolatedFromWebPageEnvironment: boolean): boolean { return this.getActiveContextId(isolatedFromWebPageEnvironment) !== undefined; } public toJSON() { return { id: this.id, parentId: this.parentId, name: this.name, url: this.url, navigationReason: this.navigationReason, disposition: this.disposition, activeLoader: this.activeLoader, }; } private setLoader(loaderId: string, url?: string): void { if (!loaderId) return; if (loaderId === this.activeLoaderId) return; if (this.navigationLoadersById[loaderId]) return; this.activeLoaderId = loaderId; this.logger.info('Queuing new navigation loader', { loaderId, frameId: this.id, }); this.navigationLoadersById[loaderId] = new NavigationLoader(loaderId, this.logger); if (url) this.navigationLoadersById[loaderId].url = url; this.emit('frame-loader-created', { frame: this, loaderId, }); } private async createIsolatedWorld(): Promise<number> { try { if (!this.isAttached) return; const isolatedWorld = await this.devtoolsSession.send( 'Page.createIsolatedWorld', { frameId: this.id, worldName: ISOLATED_WORLD, // param is misspelled in protocol grantUniveralAccess: true, }, this, ); const { executionContextId } = isolatedWorld; if (!this.activeContextIds.has(executionContextId)) { this.activeContextIds.add(executionContextId); this.addContextId(executionContextId, false); this.getFrameElementNodeId().catch(() => null); } return executionContextId; } catch (error) { if (error instanceof CanceledPromiseError) { return; } if (error instanceof ProtocolError) { // 32000 code means frame doesn't exist, see if we just missed timing if (error.remoteError?.code === ContextNotFoundCode) { if (!this.isAttached) return; } } this.logger.warn('Failed to create isolated world.', { frameId: this.id, error, }); } } private async waitForDefaultContext(): Promise<void> { if (this.getActiveContextId(false)) return; this.defaultContextCreated = new Resolvable<void>(); // don't time out this event, we'll just wait for the page to shut down await this.defaultContextCreated.promise.catch(err => { if (err instanceof CanceledPromiseError) return; throw err; }); } private updateUrl(): void { if (this.internalFrame.url) { this.url = this.internalFrame.url + (this.internalFrame.urlFragment ?? ''); } else { this.url = undefined; } } }
the_stack
import assert = require("assert"); import { CrossValidator } from "../../../../src/model/evaluation/cross_validation/CrossValidator"; import { AppSoftmaxRegressionSparse } from "../../../../src/model/supervised/classifier/neural_network/learner/AppSoftmaxRegressionSparse"; import { ColumnarContentEmail } from "../../../data/ColumnarDataWithSubwordFeaturizer.test"; import { LuContentEmail } from "../../../data/LuDataWithSubwordFeaturizer.test"; import { ConfusionMatrix } from "../../../../src/mathematics/confusion_matrix/ConfusionMatrix"; import { ThresholdReporter } from "../../../../src/model/evaluation/report/ThresholdReporter"; import { ColumnarDataWithSubwordFeaturizer } from "../../../../src/data/ColumnarDataWithSubwordFeaturizer"; import { LuDataWithSubwordFeaturizer } from "../../../../src/data/LuDataWithSubwordFeaturizer"; import { NgramSubwordFeaturizer } from "../../../../src/model/language_understanding/featurizer/NgramSubwordFeaturizer"; import { Utility } from "../../../../src/utility/Utility"; import { UnitTestHelper } from "../../../utility/Utility.test"; describe("Test Suite - model/evaluation/cross_validator/CrossValidator", async () => { it("Test.0000 crossValidate() - LuContentEmail", async function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const luContent: string = LuContentEmail; const numberOfCrossValidationFolds: number = CrossValidator.defaultNumberOfCrossValidationFolds; const learnerParameterEpochs: number = AppSoftmaxRegressionSparse.defaultEpochs; const learnerParameterMiniBatchSize: number = AppSoftmaxRegressionSparse.defaultMiniBatchSize; const learnerParameterL1Regularization: number = AppSoftmaxRegressionSparse.defaultL1Regularization; const learnerParameterL2Regularization: number = AppSoftmaxRegressionSparse.defaultL2Regularization; const learnerParameterLossEarlyStopRatio: number = AppSoftmaxRegressionSparse.defaultLossEarlyStopRatio; const learnerParameterLearningRate: number = AppSoftmaxRegressionSparse.defaultLearningRate; const learnerParameterToCalculateOverallLossAfterEpoch: boolean = true; const luDataWithSubwordFeaturizer: LuDataWithSubwordFeaturizer = await LuDataWithSubwordFeaturizer.createLuDataWithSubwordFeaturizer( luContent, new NgramSubwordFeaturizer(), true); const intentLabelIndexArray: number[] = luDataWithSubwordFeaturizer.getIntentLabelIndexArray(); const utteranceFeatureIndexArrays: number[][] = luDataWithSubwordFeaturizer.getUtteranceFeatureIndexArrays(); assert(intentLabelIndexArray, "intentLabelIndexArray is undefined."); assert(utteranceFeatureIndexArrays, "utteranceFeatureIndexArrays is undefined."); const crossValidator: CrossValidator = new CrossValidator( numberOfCrossValidationFolds, learnerParameterEpochs, learnerParameterMiniBatchSize, learnerParameterL1Regularization, learnerParameterL2Regularization, learnerParameterLossEarlyStopRatio, learnerParameterLearningRate, learnerParameterToCalculateOverallLossAfterEpoch); crossValidator.crossValidate( luDataWithSubwordFeaturizer.getFeaturizerLabels(), luDataWithSubwordFeaturizer.getFeaturizerLabelMap(), luDataWithSubwordFeaturizer.getFeaturizer().getNumberLabels(), luDataWithSubwordFeaturizer.getFeaturizer().getNumberFeatures(), luDataWithSubwordFeaturizer.getIntents(), luDataWithSubwordFeaturizer.getUtterances(), luDataWithSubwordFeaturizer.getIntentLabelIndexArray(), luDataWithSubwordFeaturizer.getUtteranceFeatureIndexArrays(), luDataWithSubwordFeaturizer.getIntentInstanceIndexMapArray()); const crossValidationResult: { "confusionMatrixCrossValidation": ConfusionMatrix "thresholdReporterCrossValidation": ThresholdReporter, "predictionLabels": string[], "predictionLabelIndexes": number[], "groundTruthLabels": string[], "groundTruthLabelIndexes": number[], "predictions": number[][] } = crossValidator.getCrossValidationResult(); Utility.debuggingLog( `crossValidationResult.confusionMatrixCrossValidation.getMicroQuantileMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getMicroQuantileMetrics()}` + `crossValidationResult.confusionMatrixCrossValidation.getMacroQuantileMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getMacroQuantileMetrics()}` + `crossValidationResult.confusionMatrixCrossValidation.getMicroAverageMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getMicroAverageMetrics()}` + `,crossValidationResult.confusionMatrixCrossValidation.getSummationMicroAverageMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getSummationMicroAverageMetrics()}` + `,crossValidationResult.confusionMatrixCrossValidation.getMacroAverageMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getMacroAverageMetrics()}` + `,crossValidationResult.confusionMatrixCrossValidation.getSummationMacroAverageMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getSummationMacroAverageMetrics()}` + `,crossValidationResult.confusionMatrixCrossValidation.getPositiveSupportLabelMacroAverageMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getPositiveSupportLabelMacroAverageMetrics()}` + `,crossValidationResult.confusionMatrixCrossValidation.getPositiveSupportLabelSummationMacroAverageMetrics()=` + // tslint:disable-next-line: max-line-length `${crossValidationResult.confusionMatrixCrossValidation.getPositiveSupportLabelSummationMacroAverageMetrics()}` + `,crossValidationResult.confusionMatrixCrossValidation.getWeightedMacroAverageMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getWeightedMacroAverageMetrics()}` + `,crossValidationResult.confusionMatrixCrossValidation.getSummationWeightedMacroAverageMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getSummationWeightedMacroAverageMetrics()}`); }); it("Test.0001 crossValidate() - ColumnarContentEmail", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const columnarContent: string = ColumnarContentEmail; const labelColumnIndex: number = 0; const textColumnIndex: number = 2; const weightColumnIndex: number = 1; const linesToSkip: number = 1; const numberOfCrossValidationFolds: number = CrossValidator.defaultNumberOfCrossValidationFolds; const learnerParameterEpochs: number = AppSoftmaxRegressionSparse.defaultEpochs; const learnerParameterMiniBatchSize: number = AppSoftmaxRegressionSparse.defaultMiniBatchSize; const learnerParameterL1Regularization: number = AppSoftmaxRegressionSparse.defaultL1Regularization; const learnerParameterL2Regularization: number = AppSoftmaxRegressionSparse.defaultL2Regularization; const learnerParameterLossEarlyStopRatio: number = AppSoftmaxRegressionSparse.defaultLossEarlyStopRatio; const learnerParameterLearningRate: number = AppSoftmaxRegressionSparse.defaultLearningRate; const learnerParameterToCalculateOverallLossAfterEpoch: boolean = true; const columnarDataWithSubwordFeaturizer: ColumnarDataWithSubwordFeaturizer = ColumnarDataWithSubwordFeaturizer.createColumnarDataWithSubwordFeaturizer( columnarContent, new NgramSubwordFeaturizer(), labelColumnIndex, textColumnIndex, weightColumnIndex, linesToSkip, true); const intentLabelIndexArray: number[] = columnarDataWithSubwordFeaturizer.getIntentLabelIndexArray(); const utteranceFeatureIndexArrays: number[][] = columnarDataWithSubwordFeaturizer.getUtteranceFeatureIndexArrays(); assert(intentLabelIndexArray, "intentLabelIndexArray is undefined."); assert(utteranceFeatureIndexArrays, "utteranceFeatureIndexArrays is undefined."); const crossValidator: CrossValidator = new CrossValidator( numberOfCrossValidationFolds, learnerParameterEpochs, learnerParameterMiniBatchSize, learnerParameterL1Regularization, learnerParameterL2Regularization, learnerParameterLossEarlyStopRatio, learnerParameterLearningRate, learnerParameterToCalculateOverallLossAfterEpoch); crossValidator.crossValidate( columnarDataWithSubwordFeaturizer.getFeaturizerLabels(), columnarDataWithSubwordFeaturizer.getFeaturizerLabelMap(), columnarDataWithSubwordFeaturizer.getFeaturizer().getNumberLabels(), columnarDataWithSubwordFeaturizer.getFeaturizer().getNumberFeatures(), columnarDataWithSubwordFeaturizer.getIntents(), columnarDataWithSubwordFeaturizer.getUtterances(), columnarDataWithSubwordFeaturizer.getIntentLabelIndexArray(), columnarDataWithSubwordFeaturizer.getUtteranceFeatureIndexArrays(), columnarDataWithSubwordFeaturizer.getIntentInstanceIndexMapArray()); const crossValidationResult: { "confusionMatrixCrossValidation": ConfusionMatrix "thresholdReporterCrossValidation": ThresholdReporter, "predictionLabels": string[], "predictionLabelIndexes": number[], "groundTruthLabels": string[], "groundTruthLabelIndexes": number[], "predictions": number[][] } = crossValidator.getCrossValidationResult(); Utility.debuggingLog( `crossValidationResult.confusionMatrixCrossValidation.getMicroQuantileMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getMicroQuantileMetrics()}` + `crossValidationResult.confusionMatrixCrossValidation.getMacroQuantileMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getMacroQuantileMetrics()}` + `crossValidationResult.confusionMatrixCrossValidation.getMicroAverageMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getMicroAverageMetrics()}` + `,crossValidationResult.confusionMatrixCrossValidation.getSummationMicroAverageMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getSummationMicroAverageMetrics()}` + `,crossValidationResult.confusionMatrixCrossValidation.getMacroAverageMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getMacroAverageMetrics()}` + `,crossValidationResult.confusionMatrixCrossValidation.getSummationMacroAverageMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getSummationMacroAverageMetrics()}` + `,crossValidationResult.confusionMatrixCrossValidation.getPositiveSupportLabelMacroAverageMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getPositiveSupportLabelMacroAverageMetrics()}` + `,crossValidationResult.confusionMatrixCrossValidation.getPositiveSupportLabelSummationMacroAverageMetrics()=` + // tslint:disable-next-line: max-line-length `${crossValidationResult.confusionMatrixCrossValidation.getPositiveSupportLabelSummationMacroAverageMetrics()}` + `,crossValidationResult.confusionMatrixCrossValidation.getWeightedMacroAverageMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getWeightedMacroAverageMetrics()}` + `,crossValidationResult.confusionMatrixCrossValidation.getSummationWeightedMacroAverageMetrics()=` + `${crossValidationResult.confusionMatrixCrossValidation.getSummationWeightedMacroAverageMetrics()}`); }); });
the_stack
import { GlobalProps } from 'ojs/ojvcomponent'; import { ComponentChildren } from 'preact'; import { editableValue, editableValueEventMap, editableValueSettableProperties } from '../ojeditablevalue'; import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..'; export interface ojRangeSlider extends editableValue<Object | null, ojRangeSliderSettableProperties> { disabled: boolean; displayOptions?: { converterHint?: 'display' | 'none'; helpInstruction?: Array<'notewindow' | 'none'> | 'notewindow' | 'none'; messages?: 'display' | 'none'; validatorHint?: 'display' | 'none'; }; labelledBy: string | null; max: number | null; min: number | null; orientation: 'horizontal' | 'vertical'; step: number | null; readonly transientValue: { end: number | null; start: number | null; }; value: { end: number | null; start: number | null; }; translations: { higherValueThumb?: string; lowerValueThumb?: string; startEnd?: string; }; addEventListener<T extends keyof ojRangeSliderEventMap>(type: T, listener: (this: HTMLElement, ev: ojRangeSliderEventMap[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojRangeSliderSettableProperties>(property: T): ojRangeSlider[T]; getProperty(property: string): any; setProperty<T extends keyof ojRangeSliderSettableProperties>(property: T, value: ojRangeSliderSettableProperties[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojRangeSliderSettableProperties>): void; setProperties(properties: ojRangeSliderSettablePropertiesLenient): void; } export namespace ojRangeSlider { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type disabledChanged = JetElementCustomEvent<ojRangeSlider["disabled"]>; // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged = JetElementCustomEvent<ojRangeSlider["displayOptions"]>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged = JetElementCustomEvent<ojRangeSlider["labelledBy"]>; // tslint:disable-next-line interface-over-type-literal type maxChanged = JetElementCustomEvent<ojRangeSlider["max"]>; // tslint:disable-next-line interface-over-type-literal type minChanged = JetElementCustomEvent<ojRangeSlider["min"]>; // tslint:disable-next-line interface-over-type-literal type orientationChanged = JetElementCustomEvent<ojRangeSlider["orientation"]>; // tslint:disable-next-line interface-over-type-literal type stepChanged = JetElementCustomEvent<ojRangeSlider["step"]>; // tslint:disable-next-line interface-over-type-literal type transientValueChanged = JetElementCustomEvent<ojRangeSlider["transientValue"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged = JetElementCustomEvent<ojRangeSlider["value"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type describedByChanged = editableValue.describedByChanged<Object | null, ojRangeSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpChanged = editableValue.helpChanged<Object | null, ojRangeSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged = editableValue.helpHintsChanged<Object | null, ojRangeSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged = editableValue.labelEdgeChanged<Object | null, ojRangeSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged = editableValue.labelHintChanged<Object | null, ojRangeSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged = editableValue.messagesCustomChanged<Object | null, ojRangeSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged = editableValue.userAssistanceDensityChanged<Object | null, ojRangeSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type validChanged = editableValue.validChanged<Object | null, ojRangeSliderSettableProperties>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export interface ojRangeSliderEventMap extends editableValueEventMap<Object | null, ojRangeSliderSettableProperties> { 'ojAnimateEnd': ojRangeSlider.ojAnimateEnd; 'ojAnimateStart': ojRangeSlider.ojAnimateStart; 'disabledChanged': JetElementCustomEvent<ojRangeSlider["disabled"]>; 'displayOptionsChanged': JetElementCustomEvent<ojRangeSlider["displayOptions"]>; 'labelledByChanged': JetElementCustomEvent<ojRangeSlider["labelledBy"]>; 'maxChanged': JetElementCustomEvent<ojRangeSlider["max"]>; 'minChanged': JetElementCustomEvent<ojRangeSlider["min"]>; 'orientationChanged': JetElementCustomEvent<ojRangeSlider["orientation"]>; 'stepChanged': JetElementCustomEvent<ojRangeSlider["step"]>; 'transientValueChanged': JetElementCustomEvent<ojRangeSlider["transientValue"]>; 'valueChanged': JetElementCustomEvent<ojRangeSlider["value"]>; 'describedByChanged': JetElementCustomEvent<ojRangeSlider["describedBy"]>; 'helpChanged': JetElementCustomEvent<ojRangeSlider["help"]>; 'helpHintsChanged': JetElementCustomEvent<ojRangeSlider["helpHints"]>; 'labelEdgeChanged': JetElementCustomEvent<ojRangeSlider["labelEdge"]>; 'labelHintChanged': JetElementCustomEvent<ojRangeSlider["labelHint"]>; 'messagesCustomChanged': JetElementCustomEvent<ojRangeSlider["messagesCustom"]>; 'userAssistanceDensityChanged': JetElementCustomEvent<ojRangeSlider["userAssistanceDensity"]>; 'validChanged': JetElementCustomEvent<ojRangeSlider["valid"]>; } export interface ojRangeSliderSettableProperties extends editableValueSettableProperties<Object | null> { disabled: boolean; displayOptions?: { converterHint?: 'display' | 'none'; helpInstruction?: Array<'notewindow' | 'none'> | 'notewindow' | 'none'; messages?: 'display' | 'none'; validatorHint?: 'display' | 'none'; }; labelledBy: string | null; max: number | null; min: number | null; orientation: 'horizontal' | 'vertical'; step: number | null; readonly transientValue: { end: number | null; start: number | null; }; value: { end: number | null; start: number | null; }; translations: { higherValueThumb?: string; lowerValueThumb?: string; startEnd?: string; }; } export interface ojRangeSliderSettablePropertiesLenient extends Partial<ojRangeSliderSettableProperties> { [key: string]: any; } export interface ojSlider extends editableValue<number | null, ojSliderSettableProperties> { displayOptions?: { converterHint?: 'display' | 'none'; helpInstruction?: Array<'notewindow' | 'none'> | 'notewindow' | 'none'; messages?: 'display' | 'none'; validatorHint?: 'display' | 'none'; }; labelledBy: string | null; max: number | null; min: number | null; orientation: 'horizontal' | 'vertical'; step: number | null; readonly transientValue: number; type: 'fromMin' | 'fromMax' | 'single'; value: number | null; translations: { invalidStep?: string; maxMin?: string; noValue?: string; optionNum?: string; valueRange?: string; }; addEventListener<T extends keyof ojSliderEventMap>(type: T, listener: (this: HTMLElement, ev: ojSliderEventMap[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojSliderSettableProperties>(property: T): ojSlider[T]; getProperty(property: string): any; setProperty<T extends keyof ojSliderSettableProperties>(property: T, value: ojSliderSettableProperties[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojSliderSettableProperties>): void; setProperties(properties: ojSliderSettablePropertiesLenient): void; } export namespace ojSlider { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged = JetElementCustomEvent<ojSlider["displayOptions"]>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged = JetElementCustomEvent<ojSlider["labelledBy"]>; // tslint:disable-next-line interface-over-type-literal type maxChanged = JetElementCustomEvent<ojSlider["max"]>; // tslint:disable-next-line interface-over-type-literal type minChanged = JetElementCustomEvent<ojSlider["min"]>; // tslint:disable-next-line interface-over-type-literal type orientationChanged = JetElementCustomEvent<ojSlider["orientation"]>; // tslint:disable-next-line interface-over-type-literal type stepChanged = JetElementCustomEvent<ojSlider["step"]>; // tslint:disable-next-line interface-over-type-literal type transientValueChanged = JetElementCustomEvent<ojSlider["transientValue"]>; // tslint:disable-next-line interface-over-type-literal type typeChanged = JetElementCustomEvent<ojSlider["type"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged = JetElementCustomEvent<ojSlider["value"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type describedByChanged = editableValue.describedByChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type disabledChanged = editableValue.disabledChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpChanged = editableValue.helpChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged = editableValue.helpHintsChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged = editableValue.labelEdgeChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged = editableValue.labelHintChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged = editableValue.messagesCustomChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged = editableValue.userAssistanceDensityChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type validChanged = editableValue.validChanged<number | null, ojSliderSettableProperties>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export interface ojSliderEventMap extends editableValueEventMap<number | null, ojSliderSettableProperties> { 'ojAnimateEnd': ojSlider.ojAnimateEnd; 'ojAnimateStart': ojSlider.ojAnimateStart; 'displayOptionsChanged': JetElementCustomEvent<ojSlider["displayOptions"]>; 'labelledByChanged': JetElementCustomEvent<ojSlider["labelledBy"]>; 'maxChanged': JetElementCustomEvent<ojSlider["max"]>; 'minChanged': JetElementCustomEvent<ojSlider["min"]>; 'orientationChanged': JetElementCustomEvent<ojSlider["orientation"]>; 'stepChanged': JetElementCustomEvent<ojSlider["step"]>; 'transientValueChanged': JetElementCustomEvent<ojSlider["transientValue"]>; 'typeChanged': JetElementCustomEvent<ojSlider["type"]>; 'valueChanged': JetElementCustomEvent<ojSlider["value"]>; 'describedByChanged': JetElementCustomEvent<ojSlider["describedBy"]>; 'disabledChanged': JetElementCustomEvent<ojSlider["disabled"]>; 'helpChanged': JetElementCustomEvent<ojSlider["help"]>; 'helpHintsChanged': JetElementCustomEvent<ojSlider["helpHints"]>; 'labelEdgeChanged': JetElementCustomEvent<ojSlider["labelEdge"]>; 'labelHintChanged': JetElementCustomEvent<ojSlider["labelHint"]>; 'messagesCustomChanged': JetElementCustomEvent<ojSlider["messagesCustom"]>; 'userAssistanceDensityChanged': JetElementCustomEvent<ojSlider["userAssistanceDensity"]>; 'validChanged': JetElementCustomEvent<ojSlider["valid"]>; } export interface ojSliderSettableProperties extends editableValueSettableProperties<number | null> { displayOptions?: { converterHint?: 'display' | 'none'; helpInstruction?: Array<'notewindow' | 'none'> | 'notewindow' | 'none'; messages?: 'display' | 'none'; validatorHint?: 'display' | 'none'; }; labelledBy: string | null; max: number | null; min: number | null; orientation: 'horizontal' | 'vertical'; step: number | null; readonly transientValue: number; type: 'fromMin' | 'fromMax' | 'single'; value: number | null; translations: { invalidStep?: string; maxMin?: string; noValue?: string; optionNum?: string; valueRange?: string; }; } export interface ojSliderSettablePropertiesLenient extends Partial<ojSliderSettableProperties> { [key: string]: any; } export type RangeSliderElement = ojRangeSlider; export type SliderElement = ojSlider; export namespace RangeSliderElement { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type disabledChanged = JetElementCustomEvent<ojRangeSlider["disabled"]>; // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged = JetElementCustomEvent<ojRangeSlider["displayOptions"]>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged = JetElementCustomEvent<ojRangeSlider["labelledBy"]>; // tslint:disable-next-line interface-over-type-literal type maxChanged = JetElementCustomEvent<ojRangeSlider["max"]>; // tslint:disable-next-line interface-over-type-literal type minChanged = JetElementCustomEvent<ojRangeSlider["min"]>; // tslint:disable-next-line interface-over-type-literal type orientationChanged = JetElementCustomEvent<ojRangeSlider["orientation"]>; // tslint:disable-next-line interface-over-type-literal type stepChanged = JetElementCustomEvent<ojRangeSlider["step"]>; // tslint:disable-next-line interface-over-type-literal type transientValueChanged = JetElementCustomEvent<ojRangeSlider["transientValue"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged = JetElementCustomEvent<ojRangeSlider["value"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type describedByChanged = editableValue.describedByChanged<Object | null, ojRangeSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpChanged = editableValue.helpChanged<Object | null, ojRangeSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged = editableValue.helpHintsChanged<Object | null, ojRangeSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged = editableValue.labelEdgeChanged<Object | null, ojRangeSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged = editableValue.labelHintChanged<Object | null, ojRangeSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged = editableValue.messagesCustomChanged<Object | null, ojRangeSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged = editableValue.userAssistanceDensityChanged<Object | null, ojRangeSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type validChanged = editableValue.validChanged<Object | null, ojRangeSliderSettableProperties>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export namespace SliderElement { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged = JetElementCustomEvent<ojSlider["displayOptions"]>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged = JetElementCustomEvent<ojSlider["labelledBy"]>; // tslint:disable-next-line interface-over-type-literal type maxChanged = JetElementCustomEvent<ojSlider["max"]>; // tslint:disable-next-line interface-over-type-literal type minChanged = JetElementCustomEvent<ojSlider["min"]>; // tslint:disable-next-line interface-over-type-literal type orientationChanged = JetElementCustomEvent<ojSlider["orientation"]>; // tslint:disable-next-line interface-over-type-literal type stepChanged = JetElementCustomEvent<ojSlider["step"]>; // tslint:disable-next-line interface-over-type-literal type transientValueChanged = JetElementCustomEvent<ojSlider["transientValue"]>; // tslint:disable-next-line interface-over-type-literal type typeChanged = JetElementCustomEvent<ojSlider["type"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged = JetElementCustomEvent<ojSlider["value"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type describedByChanged = editableValue.describedByChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type disabledChanged = editableValue.disabledChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpChanged = editableValue.helpChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged = editableValue.helpHintsChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged = editableValue.labelEdgeChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged = editableValue.labelHintChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged = editableValue.messagesCustomChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged = editableValue.userAssistanceDensityChanged<number | null, ojSliderSettableProperties>; // tslint:disable-next-line interface-over-type-literal type validChanged = editableValue.validChanged<number | null, ojSliderSettableProperties>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export interface RangeSliderIntrinsicProps extends Partial<Readonly<ojRangeSliderSettableProperties>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { onojAnimateEnd?: (value: ojRangeSliderEventMap['ojAnimateEnd']) => void; onojAnimateStart?: (value: ojRangeSliderEventMap['ojAnimateStart']) => void; ondisabledChanged?: (value: ojRangeSliderEventMap['disabledChanged']) => void; ondisplayOptionsChanged?: (value: ojRangeSliderEventMap['displayOptionsChanged']) => void; onlabelledByChanged?: (value: ojRangeSliderEventMap['labelledByChanged']) => void; onmaxChanged?: (value: ojRangeSliderEventMap['maxChanged']) => void; onminChanged?: (value: ojRangeSliderEventMap['minChanged']) => void; onorientationChanged?: (value: ojRangeSliderEventMap['orientationChanged']) => void; onstepChanged?: (value: ojRangeSliderEventMap['stepChanged']) => void; ontransientValueChanged?: (value: ojRangeSliderEventMap['transientValueChanged']) => void; onvalueChanged?: (value: ojRangeSliderEventMap['valueChanged']) => void; ondescribedByChanged?: (value: ojRangeSliderEventMap['describedByChanged']) => void; onhelpChanged?: (value: ojRangeSliderEventMap['helpChanged']) => void; onhelpHintsChanged?: (value: ojRangeSliderEventMap['helpHintsChanged']) => void; onlabelEdgeChanged?: (value: ojRangeSliderEventMap['labelEdgeChanged']) => void; onlabelHintChanged?: (value: ojRangeSliderEventMap['labelHintChanged']) => void; onmessagesCustomChanged?: (value: ojRangeSliderEventMap['messagesCustomChanged']) => void; onuserAssistanceDensityChanged?: (value: ojRangeSliderEventMap['userAssistanceDensityChanged']) => void; onvalidChanged?: (value: ojRangeSliderEventMap['validChanged']) => void; children?: ComponentChildren; } export interface SliderIntrinsicProps extends Partial<Readonly<ojSliderSettableProperties>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { onojAnimateEnd?: (value: ojSliderEventMap['ojAnimateEnd']) => void; onojAnimateStart?: (value: ojSliderEventMap['ojAnimateStart']) => void; ondisplayOptionsChanged?: (value: ojSliderEventMap['displayOptionsChanged']) => void; onlabelledByChanged?: (value: ojSliderEventMap['labelledByChanged']) => void; onmaxChanged?: (value: ojSliderEventMap['maxChanged']) => void; onminChanged?: (value: ojSliderEventMap['minChanged']) => void; onorientationChanged?: (value: ojSliderEventMap['orientationChanged']) => void; onstepChanged?: (value: ojSliderEventMap['stepChanged']) => void; ontransientValueChanged?: (value: ojSliderEventMap['transientValueChanged']) => void; ontypeChanged?: (value: ojSliderEventMap['typeChanged']) => void; onvalueChanged?: (value: ojSliderEventMap['valueChanged']) => void; ondescribedByChanged?: (value: ojSliderEventMap['describedByChanged']) => void; ondisabledChanged?: (value: ojSliderEventMap['disabledChanged']) => void; onhelpChanged?: (value: ojSliderEventMap['helpChanged']) => void; onhelpHintsChanged?: (value: ojSliderEventMap['helpHintsChanged']) => void; onlabelEdgeChanged?: (value: ojSliderEventMap['labelEdgeChanged']) => void; onlabelHintChanged?: (value: ojSliderEventMap['labelHintChanged']) => void; onmessagesCustomChanged?: (value: ojSliderEventMap['messagesCustomChanged']) => void; onuserAssistanceDensityChanged?: (value: ojSliderEventMap['userAssistanceDensityChanged']) => void; onvalidChanged?: (value: ojSliderEventMap['validChanged']) => void; children?: ComponentChildren; } declare global { namespace preact.JSX { interface IntrinsicElements { "oj-range-slider": RangeSliderIntrinsicProps; "oj-slider": SliderIntrinsicProps; } } }
the_stack
import { Stopwatch } from 'ts-stopwatch'; import { azureCloudEndpoint } from '../../Enums/azureCloudEndpoint'; import { CdmCorpusDefinition, CdmDocumentDefinition, CdmManifestDefinition, cdmStatusLevel, StorageAdapterCacheContext } from '../../internal'; import { ADLSAdapter } from '../../Storage'; import { TokenProvider } from '../../Utilities/Network'; import { adlsTestHelper } from '../adlsTestHelper'; import { testHelper } from '../testHelper'; import { MockADLSAdapter } from './MockADLSAdapter'; class FakeTokenProvider implements TokenProvider { public getToken(): string { return 'TOKEN'; } } const adlsTest = { async runWriteReadTest(adapter: ADLSAdapter): Promise<void> { const filename: string = `WriteReadTest/${process.env['USERNAME']}_${process.env['COMPUTERNAME']}_TypeScript.txt`; const writeContents: string = `${new Date().toString()}\n${filename}`; await adapter.writeAsync(filename, writeContents); const readContents: string = await adapter.readAsync(filename); expect(writeContents) .toEqual(readContents); }, async runCheckFileTimeTests(adapter: ADLSAdapter): Promise<void> { const filename: string = `WriteReadTest/${process.env['USERNAME']}_${process.env['COMPUTERNAME']}_TypeScript.txt`; const writeContents: string = `${new Date().toString()}\n${filename}`; await adapter.writeAsync(filename, writeContents); const readContents: string = await adapter.readAsync(filename); expect(writeContents) .toEqual(readContents); const offset1: Date = await adapter.computeLastModifiedTimeAsync('/FileTimeTest/CheckFileTime.txt'); const offset2: Date = await adapter.computeLastModifiedTimeAsync('FileTimeTest/CheckFileTime.txt'); expect(offset1) .not .toBeNull(); expect(offset2) .not .toBeNull(); expect(offset1.getTime() === offset2.getTime()) .toBe(true); expect(offset1 < new Date()) .toBe(true); }, async runFileEnumTest(adapter: ADLSAdapter): Promise<void> { const context: StorageAdapterCacheContext = adapter.createFileQueryCacheContext(); try { const files1: string[] = await adapter.fetchAllFilesAsync('/FileEnumTest/'); const files2: string[] = await adapter.fetchAllFilesAsync('/FileEnumTest'); const files3: string[] = await adapter.fetchAllFilesAsync('FileEnumTest/'); const files4: string[] = await adapter.fetchAllFilesAsync('FileEnumTest'); // expect 100 files to be enumerated expect(files1.length === 100 && files2.length === 100 && files3.length === 100 && files4.length === 100) .toBe(true); // these calls should be fast due to cache const watch: Stopwatch = new Stopwatch(); watch.start(); for (let i = 0; i < files1.length; i++) { expect(files1[i] === files2[i] && files1[i] === files3[i] && files1[i] === files4[i]) .toBe(true); await adapter.computeLastModifiedTimeAsync(files1[i]); } watch.stop(); expect(watch.getTime()) .toBeLessThan(100); } finally { context.dispose(); } }, async runSpecialCharactersTest(adapter: ADLSAdapter): Promise<void> { const corpus: CdmCorpusDefinition = new CdmCorpusDefinition(); corpus.storage.mount('adls', adapter); corpus.storage.defaultNamespace = 'adls'; try { const manifest: CdmManifestDefinition = await corpus.fetchObjectAsync<CdmManifestDefinition>('default.manifest.cdm.json'); await manifest.fileStatusCheckAsync(); expect(manifest.entities.length) .toBe(1); expect(manifest.entities.allItems[0].dataPartitions.length) .toBe(2); expect(manifest.entities.allItems[0].dataPartitions.allItems[0].location) .toBe('TestEntity-With=Special Characters/year=2020/TestEntity-partition-With=Special Characters-0.csv'); expect(manifest.entities.allItems[0].dataPartitions.allItems[1].location) .toBe('TestEntity-With=Special Characters/year=2020/TestEntity-partition-With=Special Characters-1.csv'); } catch (ex) { fail(ex); } } }; describe('Cdm.Storage.AdlsAdapter', () => { const testSubpath: string = 'Storage'; const adlsIt: jest.It = process.env['ADLS_RUNTESTS'] === '1' ? it : it.skip; /** * The tests declared with "adlsIt" will run only if the ADLS environment variables are setup. * In order to run and debug these tests via Test Explorer in Visual Studio Code you must * temporarily replace "adlsIt" with "it" */ adlsIt('ADLSWriteReadSharedKey', async () => { await adlsTest.runWriteReadTest(adlsTestHelper.createAdapterWithSharedKey()); }); adlsIt('ADLSWriteReadClientId', async () => { await adlsTest.runWriteReadTest(adlsTestHelper.createAdapterWithClientId()); }); adlsIt('ADLSWriteReadClientIdWithEndpoint', async () => { await adlsTest.runWriteReadTest(adlsTestHelper.createAdapterWithClientId(undefined, true)); }); adlsIt('ADLSWriteReadWithBlobHostname', async () => { await adlsTest.runWriteReadTest(adlsTestHelper.createAdapterWithSharedKey(undefined, true)); await adlsTest.runWriteReadTest(adlsTestHelper.createAdapterWithClientId(undefined, false, true)); }); adlsIt('ADLSCheckFileTimeSharedKey', async () => { await adlsTest.runCheckFileTimeTests(adlsTestHelper.createAdapterWithSharedKey()); }); adlsIt('ADLSCheckFileTimeClientId', async () => { await adlsTest.runCheckFileTimeTests(adlsTestHelper.createAdapterWithClientId()); }); adlsIt('ADLSFileEnumSharedKey', async () => { await adlsTest.runFileEnumTest(adlsTestHelper.createAdapterWithSharedKey()); }); adlsIt('ADLSFileEnumClientId', async () => { await adlsTest.runFileEnumTest(adlsTestHelper.createAdapterWithClientId()); }); adlsIt('ADLSSpecialCharactersTest', async () => { await adlsTest.runSpecialCharactersTest(adlsTestHelper.createAdapterWithClientId('PathWithSpecialCharactersAndUnescapedStringTest/Root-With=Special Characters:')); }); /** * Tests if the adapter won't retry if a HttpStatusCode response with a code in AvoidRetryCodes is received. */ adlsIt('testAvoidRetryCodes', async () => { const adlsAdapter = adlsTestHelper.createAdapterWithSharedKey(); adlsAdapter.numberOfRetries = 3; const corpus = new CdmCorpusDefinition(); corpus.storage.mount('adls', adlsAdapter); let count = 0; corpus.setEventCallback((status, message) => { if (message.indexOf('Response for request ') !== -1) { count++; } }, cdmStatusLevel.progress); await corpus.fetchObjectAsync<CdmDocumentDefinition>('adls:/inexistentFile.cdm.json'); expect(count) .toEqual(1); }); /** * Checks if the endpoint of the adls adapter is set to default if not present in the config parameters. * This is necessary to support old config files that do not include an "endpoint". */ test('TestEndpointMissingOnConfig', () => { const config = { 'hostname': 'hostname.dfs.core.windows.net', 'root': 'root', 'tenant': 'tenant', 'clientId': 'clientId' }; const adlsAdapter = new ADLSAdapter(); adlsAdapter.updateConfig(JSON.stringify(config)); expect(adlsAdapter.endpoint) .toEqual(azureCloudEndpoint.AzurePublic); }); /** * Test if formattedHostname is properly set when loading from config. */ it('TestFormattedHostnameFromConfig', () => { const config = { 'hostname': 'hostname.dfs.core.windows.net', 'root': 'root', 'tenant': 'tenant', 'clientId': 'clientId' }; const adlsAdapter = new ADLSAdapter(); adlsAdapter.updateConfig(JSON.stringify(config)); const corpusPath: string = adlsAdapter.createCorpusPath('https://hostname.dfs.core.windows.net/root/partitions/data.csv'); expect(corpusPath) .toEqual('/partitions/data.csv'); }); /** * Tests to create corpus paths and adapter paths in AdlsAdapter */ it('TestCreateCorpusAndAdapterPathInAdlsAdapter', () => { const host1: string = 'storageaccount.dfs.core.windows.net'; const root: string = '/fs'; let adlsAdapter: MockADLSAdapter = new MockADLSAdapter(host1, root, 'test'); const adapterPath1: string = 'https://storageaccount.dfs.core.windows.net/fs/a/1.csv'; const adapterPath2: string = 'https://storageaccount.dfs.core.windows.net:443/fs/a/2.csv'; const adapterPath3: string = 'https://storageaccount.blob.core.windows.net/fs/a/3.csv'; const adapterPath4: string = 'https://storageaccount.blob.core.windows.net:443/fs/a/4.csv'; const corpusPath1: string = adlsAdapter.createCorpusPath(adapterPath1); const corpusPath2: string = adlsAdapter.createCorpusPath(adapterPath2); const corpusPath3: string = adlsAdapter.createCorpusPath(adapterPath3); const corpusPath4: string = adlsAdapter.createCorpusPath(adapterPath4); expect(corpusPath1) .toBe('/a/1.csv'); expect(corpusPath2) .toBe('/a/2.csv'); expect(corpusPath3) .toBe('/a/3.csv'); expect(corpusPath4) .toBe('/a/4.csv'); expect(adlsAdapter.createAdapterPath(corpusPath1)) .toBe(adapterPath1); expect(adlsAdapter.createAdapterPath(corpusPath2)) .toBe(adapterPath2); expect(adlsAdapter.createAdapterPath(corpusPath3)) .toBe(adapterPath3); expect(adlsAdapter.createAdapterPath(corpusPath4)) .toBe(adapterPath4); // Check that an adapter path is correctly created from a corpus path with any namespace const corpusPathWithNamespace1: string = 'adls:/test.json'; const corpusPathWithNamespace2: string = 'mylake:/test.json'; const expectedAdapterPath: string = 'https://storageaccount.dfs.core.windows.net/fs/test.json'; expect(adlsAdapter.createAdapterPath(corpusPathWithNamespace1)) .toBe(expectedAdapterPath); expect(adlsAdapter.createAdapterPath(corpusPathWithNamespace2)) .toBe(expectedAdapterPath); // Check that an adapter path is correctly created from a corpus path with colons const corpusPathWithColons: string = 'namespace:/a/path:with:colons/some-file.json'; expect(adlsAdapter.createAdapterPath(corpusPathWithColons)) .toBe('https://storageaccount.dfs.core.windows.net/fs/a/path%3Awith%3Acolons/some-file.json'); expect(adlsAdapter.createCorpusPath('https://storageaccount.dfs.core.windows.net/fs/a/path%3Awith%3Acolons/some-file.json')) .toBe('/a/path:with:colons/some-file.json'); expect(adlsAdapter.createCorpusPath('https://storageaccount.dfs.core.windows.net/fs/a/path%3awith%3acolons/some-file.json')) .toBe('/a/path:with:colons/some-file.json'); // Check other special characters expect(adlsAdapter.createAdapterPath('namespace:/a/path with=special=characters/some-file.json')) .toBe('https://storageaccount.dfs.core.windows.net/fs/a/path%20with%3Dspecial%3Dcharacters/some-file.json'); expect(adlsAdapter.createCorpusPath('https://storageaccount.dfs.core.windows.net/fs/a/path%20with%3dspecial%3dcharacters/some-file.json')) .toBe('/a/path with=special=characters/some-file.json'); expect(adlsAdapter.createCorpusPath('https://storageaccount.dfs.core.windows.net/fs/a/path%20with%3dspecial%3Dcharacters/some-file.json')) .toBe('/a/path with=special=characters/some-file.json'); // Check that an adapter path is null if the corpus path provided is null expect(adlsAdapter.createAdapterPath(undefined)) .toBeUndefined(); const host2: string = 'storageaccount.blob.core.windows.net:8888'; adlsAdapter = new MockADLSAdapter(host2, root, 'test'); const adapterPath5: string = 'https://storageaccount.blob.core.windows.net:8888/fs/a/5.csv'; const adapterPath6: string = 'https://storageaccount.dfs.core.windows.net:8888/fs/a/6.csv'; const adapterPath7: string = 'https://storageaccount.blob.core.windows.net/fs/a/7.csv'; expect(adlsAdapter.createCorpusPath(adapterPath5)) .toBe('/a/5.csv'); expect(adlsAdapter.createCorpusPath(adapterPath6)) .toBe('/a/6.csv'); expect(adlsAdapter.createCorpusPath(adapterPath7)) .toBeUndefined(); }); /** * The secret property is not saved to the config.json file for security reasons. * When constructing and ADLS adapter from config, the user should be able to set the secret after the adapter is constructed. */ it('TestConfigAndUpdateConfigWithoutSecret', () => { const config = { root: 'root', hostname: 'hostname', tenant: 'tenant', clientId: 'clientId' }; try { const adlsAdapter1: MockADLSAdapter = new MockADLSAdapter(); adlsAdapter1.updateConfig(JSON.stringify(config)); adlsAdapter1.clientId = 'clientId2' adlsAdapter1.secret = 'secret'; adlsAdapter1.sharedKey = 'sharedKey'; adlsAdapter1.tokenProvider = new FakeTokenProvider(); } catch { fail('adlsAdapter initialized without secret shouldn\'t throw exception when updating config.') } try { const adlsAdapter2: MockADLSAdapter = new MockADLSAdapter(); adlsAdapter2.clientId = 'clientId2' adlsAdapter2.secret = 'secret'; adlsAdapter2.sharedKey = 'sharedKey'; adlsAdapter2.tokenProvider = new FakeTokenProvider(); adlsAdapter2.updateConfig(JSON.stringify(config)); } catch { fail('adlsAdapter initialized without secret shouldn\'t throw exception when updating config.') } }); /** * Tests to initialize hostname and root in AdlsAdapter */ it('TestInitializeHostnameAndRoot', () => { const host1: string = 'storageaccount.dfs.core.windows.net'; const adlsAdapter1: MockADLSAdapter = new MockADLSAdapter(host1, 'root-without-slash', 'test'); expect(adlsAdapter1.hostname) .toBe('storageaccount.dfs.core.windows.net'); expect(adlsAdapter1.root) .toBe('/root-without-slash'); const adapterPath1: string = 'https://storageaccount.dfs.core.windows.net/root-without-slash/a/1.csv'; const corpusPath1: string = adlsAdapter1.createCorpusPath(adapterPath1); expect(corpusPath1) .toBe('/a/1.csv'); expect(adlsAdapter1.createAdapterPath(corpusPath1)) .toBe(adapterPath1); const adlsAdapter1WithFolders: MockADLSAdapter = new MockADLSAdapter(host1, 'root-without-slash/folder1/folder2', 'test'); expect(adlsAdapter1WithFolders.root) .toBe('/root-without-slash/folder1/folder2'); const adapterPath2: string = 'https://storageaccount.dfs.core.windows.net/root-without-slash/folder1/folder2/a/1.csv'; const corpusPath2: string = adlsAdapter1WithFolders.createCorpusPath(adapterPath2); expect(corpusPath2) .toBe('/a/1.csv'); expect(adlsAdapter1WithFolders.createAdapterPath(corpusPath2)) .toBe(adapterPath2); const adlsAdapter2: MockADLSAdapter = new MockADLSAdapter(host1, '/root-starts-with-slash', 'test'); expect(adlsAdapter2.root) .toBe('/root-starts-with-slash'); const adlsAdapter2WithFolders: MockADLSAdapter = new MockADLSAdapter(host1, '/root-starts-with-slash/folder1/folder2', 'test'); expect(adlsAdapter2WithFolders.root) .toBe('/root-starts-with-slash/folder1/folder2'); const adlsAdapter3: MockADLSAdapter = new MockADLSAdapter(host1, 'root-ends-with-slash/', 'test'); expect(adlsAdapter3.root) .toBe('/root-ends-with-slash'); const adlsAdapter3WithFolders: MockADLSAdapter = new MockADLSAdapter(host1, 'root-ends-with-slash/folder1/folder2/', 'test'); expect(adlsAdapter3WithFolders.root) .toBe('/root-ends-with-slash/folder1/folder2'); const adlsAdapter4: MockADLSAdapter = new MockADLSAdapter(host1, '/root-with-slashes/', 'test'); expect(adlsAdapter4.root) .toBe('/root-with-slashes'); const adlsAdapter4WithFolders: MockADLSAdapter = new MockADLSAdapter(host1, '/root-with-slashes/folder1/folder2/', 'test'); expect(adlsAdapter4WithFolders.root) .toBe('/root-with-slashes/folder1/folder2'); // Mount from config const config: string = testHelper.getInputFileContent(testSubpath, 'TestInitializeHostnameAndRoot', 'config.json'); const corpus: CdmCorpusDefinition = new CdmCorpusDefinition(); corpus.storage.mountFromConfig(config); expect((corpus.storage.fetchAdapter('adlsadapter1') as ADLSAdapter).root) .toBe('/root-without-slash'); expect((corpus.storage.fetchAdapter('adlsadapter2') as ADLSAdapter).root) .toBe('/root-without-slash/folder1/folder2'); expect((corpus.storage.fetchAdapter('adlsadapter3') as ADLSAdapter).root) .toBe('/root-starts-with-slash/folder1/folder2'); expect((corpus.storage.fetchAdapter('adlsadapter4') as ADLSAdapter).root) .toBe('/root-ends-with-slash/folder1/folder2'); expect((corpus.storage.fetchAdapter('adlsadapter5') as ADLSAdapter).root) .toBe('/root-with-slashes/folder1/folder2'); }); /** * Test hostname with leading protocol. */ it('TestHostnameWithLeadingProtocol', () => { const host1: string = 'https://storageaccount.dfs.core.windows.net'; const adlsAdapter1: MockADLSAdapter = new MockADLSAdapter(host1, 'root-without-slash', 'test'); const adapterPath: string = 'https://storageaccount.dfs.core.windows.net/root-without-slash/a/1.csv'; const corpusPath1: string = adlsAdapter1.createCorpusPath(adapterPath); expect(adlsAdapter1.hostname) .toBe('https://storageaccount.dfs.core.windows.net'); expect(adlsAdapter1.root) .toBe('/root-without-slash'); expect(corpusPath1) .toBe('/a/1.csv'); expect(adlsAdapter1.createAdapterPath(corpusPath1)) .toBe(adapterPath); const host2: string = 'HttPs://storageaccount.dfs.core.windows.net'; const adlsAdapter2: MockADLSAdapter = new MockADLSAdapter(host2, 'root-without-slash', 'test'); const corpusPath2: string = adlsAdapter2.createCorpusPath(adapterPath); expect(adlsAdapter2.hostname) .toBe('HttPs://storageaccount.dfs.core.windows.net'); expect(adlsAdapter2.root) .toBe('/root-without-slash'); expect(corpusPath2) .toBe('/a/1.csv'); expect(adlsAdapter2.createAdapterPath(corpusPath2)) .toBe(adapterPath); try { const host3: string = 'http://storageaccount.dfs.core.windows.net'; const adlsAdapter3: MockADLSAdapter = new MockADLSAdapter(host3, 'root-without-slash', 'test'); fail('Expected Exception for using a http:// hostname.') } catch(ex) { expect(ex instanceof URIError) .toBeTruthy(); } try { const host4: string = 'https://bar:baz::]/foo/'; const adlsAdapter4: MockADLSAdapter = new MockADLSAdapter(host4, 'root-without-slash', 'test'); fail('Expected Exception for using an invalid hostname.') } catch(ex) { expect(ex instanceof URIError) .toBeTruthy(); } }); /** * Test azure cloud endpoint in config. */ it('TestLoadingAndSavingEndpointInConfig', () => { // Mount from config const config: string = testHelper.getInputFileContent(testSubpath, 'TestLoadingAndSavingEndpointInConfig', 'config.json'); const corpus: CdmCorpusDefinition = new CdmCorpusDefinition(); corpus.storage.mountFromConfig(config); expect((corpus.storage.fetchAdapter('adlsadapter1') as ADLSAdapter).endpoint) .toBeUndefined; expect((corpus.storage.fetchAdapter('adlsadapter2') as ADLSAdapter).endpoint) .toBe(azureCloudEndpoint.AzurePublic); expect((corpus.storage.fetchAdapter('adlsadapter3') as ADLSAdapter).endpoint) .toBe(azureCloudEndpoint.AzureChina); expect((corpus.storage.fetchAdapter('adlsadapter4') as ADLSAdapter).endpoint) .toBe(azureCloudEndpoint.AzureGermany); expect((corpus.storage.fetchAdapter('adlsadapter5') as ADLSAdapter).endpoint) .toBe(azureCloudEndpoint.AzureUsGovernment); try { const configSnakeCase: string = testHelper.getInputFileContent(testSubpath, 'TestLoadingAndSavingEndpointInConfig', 'config-SnakeCase.json'); const corpusSnakeCase: CdmCorpusDefinition = new CdmCorpusDefinition(); corpusSnakeCase.storage.mountFromConfig(configSnakeCase); fail('Expected RuntimeException for config.json using endpoint value in snake case.') } catch (ex) { const message: string = "Endpoint value should be a string of an enumeration value from the class AzureCloudEndpoint in Pascal case."; expect(ex.message) .toBe(message); } }); });
the_stack
import {EventEmitter} from 'events'; import * as uuid from 'uuid'; import {cls, RootContext} from './cls'; import {OpenCensusPropagation, TracePolicy} from './config'; import {Constants, SpanType} from './constants'; import {Logger} from './logger'; import { Func, Propagation, RootSpan, RootSpanOptions, Span, SpanOptions, Tracer, } from './plugin-types'; import { RootSpanData, UNCORRELATED_CHILD_SPAN, UNCORRELATED_ROOT_SPAN, DISABLED_CHILD_SPAN, DISABLED_ROOT_SPAN, UntracedRootSpanData, } from './span-data'; import {TraceLabels} from './trace-labels'; import {traceWriter} from './trace-writer'; import {neverTrace} from './tracing-policy'; import * as util from './util'; /** * An interface describing configuration fields read by the StackdriverTracer * object. This includes fields read by the trace policy. */ export interface StackdriverTracerConfig { enhancedDatabaseReporting: boolean; rootSpanNameOverride: (path: string) => string; spansPerTraceSoftLimit: number; spansPerTraceHardLimit: number; } /** * A collection of externally-instantiated objects used by StackdriverTracer. */ export interface StackdriverTracerComponents { logger: Logger; tracePolicy: TracePolicy; propagation: OpenCensusPropagation; } /** * StackdriverTracer exposes a number of methods to create trace spans and * propagate trace context across asynchronous boundaries. */ export class StackdriverTracer implements Tracer { readonly constants = Constants; readonly labels = TraceLabels; readonly spanTypes = SpanType; readonly traceContextUtils = { encodeAsByteArray: util.serializeTraceContext, decodeFromByteArray: util.deserializeTraceContext, }; readonly propagation: Propagation = { extract: getHeader => { // If enabled, this.propagationMechanism is non-null. if (!this.enabled) { return null; } // OpenCensus propagation libraries expect span IDs to be size-16 hex // strings. In the future it might be worthwhile to change how span IDs // are stored in this library to avoid excessive base 10<->16 conversions. const result = this.headerPropagation!.extract({ getHeader: (...args) => { const result = getHeader(...args); if (result === null) { return; // undefined } return result; }, }); if (result) { result.spanId = util.hexToDec(result.spanId); } return result; }, inject: (setHeader, value) => { // If enabled, this.propagationMechanism is non-null. // Also, don't inject a falsey value. if (!this.enabled || !value) { return; } // Convert back to base-10 span IDs. See the wrapper for `extract` // for more details. value = Object.assign({}, value, { spanId: `0000000000000000${util.decToHex(value.spanId).slice(2)}`.slice( -16 ), }); this.headerPropagation!.inject({setHeader}, value); }, }; private enabled = false; private pluginName: string; private pluginNameToLog: string; private logger: Logger | null = null; private config: StackdriverTracerConfig | null = null; private policy: TracePolicy | null = null; // The underlying propagation mechanism used by this.propagation. private headerPropagation: OpenCensusPropagation | null = null; /** * Constructs a new StackdriverTracer instance. * @param name A string identifying this StackdriverTracer instance in logs. */ constructor(name: string) { this.pluginName = name; this.pluginNameToLog = this.pluginName ? this.pluginName : 'no-plugin-name'; this.disable(); // disable immediately } /** * Enables this instance. This function is only for internal use and * unit tests. A separate TraceWriter instance should be initialized * beforehand. * @param config An object specifying how this instance should * be configured. * @param components An collection of externally-instantiated objects used * by this instance. * @private */ enable( config: StackdriverTracerConfig, components: StackdriverTracerComponents ) { this.config = config; this.logger = components.logger; this.policy = components.tracePolicy; this.headerPropagation = components.propagation; this.enabled = true; } /** * Disable this instance. This function is only for internal use and * unit tests. * @private */ disable() { // Even though plugins should be unpatched, setting a new policy that // never generates traces allows persisting wrapped methods (either because // they are already instantiated or the plugin doesn't unpatch them) to // short-circuit out of trace generation logic. this.policy = neverTrace(); this.enabled = false; } /** * Returns whether the StackdriverTracer instance is active. This function is * only for internal use and unit tests; under normal circumstances it will * always return true. * @private */ isActive(): boolean { return this.enabled; } enhancedDatabaseReportingEnabled(): boolean { return !!this.config && this.config.enhancedDatabaseReporting; } getConfig(): StackdriverTracerConfig { if (!this.config) { throw new Error('Configuration is not available.'); } return this.config; } runInRootSpan<T>(options: RootSpanOptions, fn: (span: RootSpan) => T): T { if (!this.isActive()) { return fn(DISABLED_ROOT_SPAN); } options = options || {name: ''}; // Don't create a root span if we are already in a root span const rootSpan = cls.get().getContext(); if (rootSpan.type === SpanType.ROOT && !rootSpan.span.endTime) { this.logger!.warn( `TraceApi#runInRootSpan: [${this.pluginNameToLog}] Cannot create nested root spans.` ); return fn(UNCORRELATED_ROOT_SPAN); } // Ensure that the trace context, if it exists, has an options field. const canonicalizeTraceContext = ( traceContext?: util.TraceContext | null ) => { if (!traceContext) { return null; } if (traceContext.options !== undefined) { return traceContext as Required<util.TraceContext>; } return { traceId: traceContext.traceId, spanId: traceContext.spanId, options: 1, }; }; const traceContext = canonicalizeTraceContext(options.traceContext); // Consult the trace policy. const shouldTrace = this.policy!.shouldTrace({ timestamp: Date.now(), url: options.url || '', method: options.method || '', traceContext, options, }); const traceId = traceContext ? traceContext.traceId : uuid.v4().split('-').join(''); let rootContext: RootSpan & RootContext; // Create an "untraced" root span (one that won't be published) if the // trace policy disallows it. if (!shouldTrace) { rootContext = new UntracedRootSpanData(traceId); } else { // Create a new root span, and invoke fn with it. rootContext = new RootSpanData( // Trace object { projectId: '', traceId, spans: [], }, // Span name this.config!.rootSpanNameOverride(options.name), // Parent span ID traceContext ? traceContext.spanId : '0', // Number of stack frames to skip options.skipFrames || 0 ); } return cls.get().runWithContext(() => { return fn(rootContext); }, rootContext); } getCurrentRootSpan(): RootSpan { if (!this.isActive()) { return DISABLED_ROOT_SPAN; } return cls.get().getContext(); } getCurrentContextId(): string | null { // In v3, this will be deprecated for getCurrentRootSpan. const traceContext = this.getCurrentRootSpan().getTraceContext(); return traceContext ? traceContext.traceId : null; } getProjectId(): Promise<string> { if (traceWriter.exists() && traceWriter.get().isActive) { return traceWriter.get().getProjectId(); } else { return Promise.reject( new Error('The Project ID could not be retrieved.') ); } } getWriterProjectId(): string | null { // In v3, this will be deprecated for getProjectId. if (traceWriter.exists() && traceWriter.get().isActive) { return traceWriter.get().projectId; } else { return null; } } createChildSpan(options?: SpanOptions): Span { if (!this.isActive()) { return DISABLED_CHILD_SPAN; } options = options || {name: ''}; const rootSpan = cls.get().getContext(); if (rootSpan.type === SpanType.ROOT) { if (rootSpan.span.endTime) { // A closed root span suggests that we either have context confusion or // some work is being done after the root request has been completed. // The first case could lead to a memory leak, if somehow all spans end // up getting misattributed to the same root span – we get a root span // with continuously growing number of child spans. The second case // seems to have some value, but isn't representable. The user probably // needs a custom outer span that encompasses the entirety of work. this.logger!.warn( `TraceApi#createChildSpan: [${this.pluginNameToLog}] Creating phantom child span [${options.name}] because root span [${rootSpan.span.name}] was already closed.` ); return UNCORRELATED_CHILD_SPAN; } if (rootSpan.trace.spans.length >= this.config!.spansPerTraceHardLimit) { // As in the previous case, a root span with a large number of child // spans suggests a memory leak stemming from context confusion. This // is likely due to userspace task queues or Promise implementations. this.logger!.warn( `TraceApi#createChildSpan: [${ this.pluginNameToLog }] Creating phantom child span [${ options.name }] because the trace with root span [${ rootSpan.span.name }] has reached a limit of ${ this.config!.spansPerTraceHardLimit } spans. This is likely a memory leak.` ); this.logger!.warn( [ 'TraceApi#createChildSpan: Please see', 'https://github.com/googleapis/cloud-trace-nodejs/wiki', 'for details and suggested actions.', ].join(' ') ); return UNCORRELATED_CHILD_SPAN; } if (rootSpan.trace.spans.length === this.config!.spansPerTraceSoftLimit) { // As in the previous case, a root span with a large number of child // spans suggests a memory leak stemming from context confusion. This // is likely due to userspace task queues or Promise implementations. // Note that since child spans can be created by users directly on a // RootSpanData instance, this block might be skipped because it only // checks equality -- this is OK because no automatic tracing plugin // uses the RootSpanData API directly. this.logger!.warn( `TraceApi#createChildSpan: [${ this.pluginNameToLog }] Adding child span [${ options.name }] will cause the trace with root span [${ rootSpan.span.name }] to contain more than ${ this.config!.spansPerTraceSoftLimit } spans. This is likely a memory leak.` ); this.logger!.warn( [ 'TraceApi#createChildSpan: Please see', 'https://github.com/googleapis/cloud-trace-nodejs/wiki', 'for details and suggested actions.', ].join(' ') ); } // Create a new child span and return it. const childContext = rootSpan.createChildSpan({ name: options.name, skipFrames: options.skipFrames ? options.skipFrames + 1 : 1, }); this.logger!.info( `TraceApi#createChildSpan: [${this.pluginNameToLog}] Created child span [${options.name}]` ); return childContext; } else if (rootSpan.type === SpanType.UNSAMPLED) { // "Untraced" child spans don't incur a memory penalty. return rootSpan.createChildSpan(); } else if (rootSpan.type === SpanType.DISABLED) { return DISABLED_CHILD_SPAN; } else { // Context was lost. this.logger!.warn( `TraceApi#createChildSpan: [${this.pluginNameToLog}] Creating phantom child span [${options.name}] because there is no root span.` ); return UNCORRELATED_CHILD_SPAN; } } isRealSpan(span: Span): boolean { return span.type === SpanType.ROOT || span.type === SpanType.CHILD; } getResponseTraceContext( incomingTraceContext: util.TraceContext | null, isTraced: boolean ) { if (!this.isActive() || !incomingTraceContext) { return null; } return { traceId: incomingTraceContext.traceId, spanId: incomingTraceContext.spanId, options: (incomingTraceContext.options || 0) & (isTraced ? 1 : 0), }; } wrap<T>(fn: Func<T>): Func<T> { if (!this.isActive()) { return fn; } return cls.get().bindWithCurrentContext(fn); } wrapEmitter(emitter: EventEmitter): void { if (!this.isActive()) { return; } cls.get().patchEmitterToPropagateContext(emitter); } }
the_stack
import { keywordFor, assocBang, MalError, symbolFor as S, MalNode, MalNodeMap, isMap, MalMap, MalVal, M_OUTER, isNode, M_ELMSTRS, M_DELIMITERS, M_ISSUGAR, M_ISLIST, M_OUTER_INDEX, isSeq, getName, createList as L, MalSeq, isSymbol, } from './types' import printExp from './printer' const S_QUOTE = S('quote') const S_QUASIQUOTE = S('quasiquote') const S_UNQUOTE = S('unquote') const S_SPLICE_UNQUOTE = S('splice-unquote') const S_FN_SUGAR = S('fn-sugar') const S_WITH_META_SUGAR = S('with-meta-sugar') const S_UI_ANNOTATE = S('ui-annotate') const S_DEREF = S('deref') class Reader { private tokens: string[] | [string, number][] private str: string private strlen: number private _index: number constructor(tokens: string[], str: string) { this.tokens = [...tokens] this.str = str this.strlen = str.length this._index = 0 } public next() { const token = this.tokens[this._index++] return Array.isArray(token) ? token[0] : token } public peek(pos = this._index) { const token = this.tokens[pos] return Array.isArray(token) ? token[0] : token } public get index() { return this._index } public getStr(start: number, end: number) { return this.str.slice(start, end) } public offset(pos = this._index): number { const token = this.tokens[pos] return (token !== undefined ? token[1] : this.strlen) as number } public endOffset(pos = this._index): number { const token = this.tokens[pos] return (token !== undefined ? (token[1] as number) + token[0].length : this.strlen) as number } public prevEndOffset(): number { return this.endOffset(this._index - 1) } } function tokenize(str: string, saveStr = false) { // eslint-disable-next-line no-useless-escape const re = /[\s,]*(~@|[\[\]{}()'`~^@#]|"(?:\\.|[^\\"])*"|;.*|[^\s\[\]{}('"`,;)]*)/g let match = null const spaceRe = /^[\s,]*/ let spaceMatch = null, spaceOffset = null const results = [] while ((match = re.exec(str)) && match[1] != '') { if (match[1][0] === ';') { continue } if (saveStr) { spaceMatch = spaceRe.exec(match[0]) spaceOffset = spaceMatch ? spaceMatch[0].length : 0 results.push([match[1], match.index + spaceOffset] as [string, number]) } else { results.push(match[1]) } } return results } function readAtom(reader: Reader) { const token = reader.next() if (typeof token === 'string') { if (token.match(/^[-+]?[0-9]+$/)) { // integer return parseInt(token, 10) } else if (token.match(/^[-+]?([0-9]*\.[0-9]+|[0-9]+)$/)) { // float return parseFloat(token) } else if (token.match(/^"(?:\\.|[^\\"])*"$/)) { // string return token .slice(1, token.length - 1) .replace(/\\(.)/g, (_: any, c: string) => (c === 'n' ? '\n' : c)) // handle new line } else if (token[0] === '"') { throw new MalError("Expected '\"', got EOF") } else if (token[0] === ':') { return keywordFor(token.slice(1)) } else if (token === 'nil') { return null } else if (token === 'true') { return true } else if (token === 'false') { return false } else if (/^NaN$|^-?Infinity$/.test(token)) { return parseFloat(token) } else { // symbol return S(token as string) } } else { return token } } // read list of tokens function readVector(reader: Reader, saveStr: boolean, start = '[', end = ']') { const exp: any = [] let elmStrs: any = null, delimiters: string[] | null = null let token = reader.next() if (token !== start) { throw new MalError(`Expected '${start}'`) } if (saveStr) { elmStrs = [] delimiters = [] } let elmStart = 0 while ((token = reader.peek()) !== end) { if (!token) { throw new MalError(`Expected '${end}', got EOF`) } if (saveStr) { // Save delimiter const delimiter = reader.getStr(reader.prevEndOffset(), reader.offset()) delimiters?.push(delimiter) elmStart = reader.offset() } // eslint-disable-next-line @typescript-eslint/no-use-before-define exp.push(readForm(reader, saveStr)) if (saveStr) { const elm = reader.getStr(elmStart, reader.prevEndOffset()) elmStrs?.push(elm) } } if (saveStr) { // Save a delimiter between a last element and a end tag const delimiter = reader.getStr(reader.prevEndOffset(), reader.offset()) delimiters?.push(delimiter) // Save string information exp[M_DELIMITERS] = delimiters exp[M_ELMSTRS] = elmStrs } reader.next() return exp } // read vector of tokens function readList(reader: Reader, saveStr: boolean) { const exp = readVector(reader, saveStr, '(', ')') ;(exp as MalSeq)[M_ISLIST] = true return exp } // read hash-map key/value pairs function readHashMap(reader: Reader, saveStr: boolean) { const lst = readVector(reader, saveStr, '{', '}') const map = assocBang({}, ...lst) as MalNodeMap if (saveStr) { const elmStrs = [] for (let i = 0; i < lst.length; i += 2) { elmStrs.push(lst[M_ELMSTRS][i], lst[M_ELMSTRS][i + 1]) } map[M_ELMSTRS] = elmStrs map[M_DELIMITERS] = lst[M_DELIMITERS] } return map } function readForm(reader: Reader, saveStr: boolean): any { let val // For syntaxtic sugars const startIdx = reader.index // Set offset array value if the form is syntaxic sugar. // the offset array is like [<end of arg0>, <start of arg1>] let sugar: number[] | null = null switch (reader.peek()) { // reader macros/transforms case ';': val = null break case "'": reader.next() if (saveStr) sugar = [reader.prevEndOffset(), reader.offset()] val = L(S_QUOTE, readForm(reader, saveStr)) break case '`': reader.next() if (saveStr) sugar = [reader.prevEndOffset(), reader.offset()] val = L(S_QUASIQUOTE, readForm(reader, saveStr)) break case '~': reader.next() if (saveStr) sugar = [reader.prevEndOffset(), reader.offset()] val = L(S_UNQUOTE, readForm(reader, saveStr)) break case '~@': reader.next() if (saveStr) sugar = [reader.prevEndOffset(), reader.offset()] val = L(S_SPLICE_UNQUOTE, readForm(reader, saveStr)) break case '#': { reader.next() const type = reader.peek() if (type === '(') { // Syntactic sugar for anonymous function: #( ) if (saveStr) sugar = [reader.prevEndOffset(), reader.offset()] val = L(S_FN_SUGAR, readForm(reader, saveStr)) } else if (type === '@') { // Syntactic sugar for ui-annotation #@ reader.next() if (saveStr) sugar = [reader.prevEndOffset(), reader.offset()] const annotation = readForm(reader, saveStr) if (sugar) sugar.push(reader.prevEndOffset(), reader.offset()) const expr = readForm(reader, saveStr) val = L(S_UI_ANNOTATE, annotation, expr) } else if (type[0] === '"') { // Syntactic sugar for set-id if (saveStr) sugar = [reader.prevEndOffset(), reader.offset()] const meta = readForm(reader, saveStr) if (sugar) sugar.push(reader.prevEndOffset(), reader.offset()) const expr = readForm(reader, saveStr) val = L(S('set-id'), meta, expr) } break } case '^': { // Syntactic sugar for with-meta reader.next() if (saveStr) sugar = [reader.prevEndOffset(), reader.offset()] const meta = readForm(reader, saveStr) if (sugar) sugar.push(reader.prevEndOffset(), reader.offset()) const expr = readForm(reader, saveStr) val = L(S_WITH_META_SUGAR, meta, expr) break } case '@': // Syntactic sugar for deref reader.next() if (saveStr) sugar = [reader.prevEndOffset(), reader.offset()] val = L(S_DEREF, readForm(reader, saveStr)) break // list case ')': throw new MalError("unexpected ')'") case '(': val = readList(reader, saveStr) break // vector case ']': throw new Error("unexpected ']'") case '[': val = readVector(reader, saveStr) break // hash-map case '}': throw new Error("unexpected '}'") case '{': val = readHashMap(reader, saveStr) break // atom default: val = readAtom(reader) } if (sugar) { // Save str info const annotator = reader.peek(startIdx) const formEnd = reader.prevEndOffset() val[M_ISSUGAR] = true const delimiters = [''] const elmStrs = [annotator] sugar.push(formEnd) for (let i = 0; i < sugar.length - 1; i += 2) { delimiters.push(reader.getStr(sugar[i], sugar[i + 1])) elmStrs.push(reader.getStr(sugar[i + 1], sugar[i + 2])) } delimiters.push('') val[M_DELIMITERS] = delimiters val[M_ELMSTRS] = elmStrs } return val } export function getRangeOfExp( exp: MalNode, root?: MalNode ): [number, number] | null { function isParent(parent: MalNode, child: MalNode): boolean { if (parent === child) { return true } const outer = child[M_OUTER] if (!outer) { return false } else if (outer === parent) { return true } else { return isParent(parent, outer) } } function calcOffset(exp: MalNode): number { if (!exp[M_OUTER] || exp === root) { return 0 } const outer = exp[M_OUTER] let offset = calcOffset(outer) // Creates a delimiter cache printExp(outer) if (isSeq(outer)) { const index = exp[M_OUTER_INDEX] offset += (outer[M_ISSUGAR] ? 0 : 1) + outer[M_DELIMITERS].slice(0, index + 1).join('').length + outer[M_ELMSTRS].slice(0, index).join('').length } else if (isMap(outer)) { const index = exp[M_OUTER_INDEX] offset += 1 /* '{'. length */ + outer[M_DELIMITERS].slice(0, (index + 1) * 2).join('').length + outer[M_ELMSTRS].slice(0, index * 2 + 1).join('').length } return offset } const isExpOutsideOfParent = root && !isParent(root, exp) if (!isNode(exp) || isExpOutsideOfParent) { return null } const expLength = printExp(exp, true).length const offset = calcOffset(exp) return [offset, offset + expLength] } export function findExpByRange( exp: MalVal, start: number, end: number ): MalNode | null { if (!isNode(exp)) { // If Atom return null } // Creates a caches of children at the same time calculating length of exp const expLen = printExp(exp, true).length if (!(0 <= start && end <= expLen)) { // Does not fit within the exp return null } if (isSeq(exp)) { // Sequential // Add the length of open-paren let offset = exp[M_ISSUGAR] ? 0 : 1 // Search Children for (let i = 0; i < exp.length; i++) { const child = exp[i] offset += exp[M_DELIMITERS][i].length const ret = findExpByRange(child, start - offset, end - offset) if (ret !== null) { return ret } // For #() syntaxtic sugar if (i < exp[M_ELMSTRS].length) { offset += exp[M_ELMSTRS][i].length } } } else if (isMap(exp)) { // Hash Map let offset = 1 // length of '{' const keys = Object.keys(exp) const elmStrs = exp[M_ELMSTRS] const delimiters = exp[M_DELIMITERS] // Search Children for (let i = 0; i < keys.length; i++) { const child = exp[keys[i]] // Offsets offset += delimiters[i * 2].length + // delimiter before key elmStrs[i * 2].length + // key delimiters[i * 2 + 1].length // delimiter between key and value const ret = findExpByRange(child, start - offset, end - offset) if (ret !== null) { return ret } offset += elmStrs[i * 2 + 1].length } } return exp } export function convertJSObjectToMalMap(obj: any): MalVal { if (Array.isArray(obj)) { const ret = obj.map(v => convertJSObjectToMalMap(v)) return ret } else if (isSymbol(obj) || obj instanceof Function) { return obj } else if (obj instanceof Object) { const ret: MalMap = {} for (const [key, value] of Object.entries(obj)) { ret[keywordFor(key)] = convertJSObjectToMalMap(value) } return ret } else { return obj } } export function convertMalNodeToJSObject(exp: MalVal): any { if (isMap(exp)) { const ret: {[Key: string]: MalVal} = {} for (const [key, value] of Object.entries(exp)) { const jsKey = getName(key) ret[jsKey] = convertMalNodeToJSObject(value) } return ret } else if (isSeq(exp)) { return (exp as MalVal[]).map(e => convertMalNodeToJSObject(e)) } else { return exp } } export class BlankException extends Error {} export function reconstructTree(exp: MalVal) { if (!isNode(exp)) { return } else { if (isMap(exp)) { const keys = Object.keys(exp) keys.forEach((key, i) => { const e = exp[key] if (isNode(e)) { e[M_OUTER] = exp e[M_OUTER_INDEX] = i reconstructTree(e) } }) } else { exp.forEach((e, i) => { if (isNode(e)) { e[M_OUTER] = exp e[M_OUTER_INDEX] = i reconstructTree(e) } }) } } } export default function readStr(str: string, saveStr = true): MalVal { const tokens = tokenize(str, saveStr) as string[] if (tokens.length === 0) { throw new BlankException() } const reader = new Reader(tokens, str) const exp = readForm(reader, saveStr) if (reader.index < tokens.length - 1) { throw new MalError('Invalid end of file') } if (saveStr) { saveOuter(exp, null) } return exp function saveOuter(exp: MalVal, outer: MalVal, index?: number) { if (isNode(exp) && !(M_OUTER in exp)) { if (isNode(outer) && index !== undefined) { exp[M_OUTER] = outer exp[M_OUTER_INDEX] = index } const children: MalVal[] | null = Array.isArray(exp) ? exp : isMap(exp) ? Object.keys(exp).map(k => exp[k]) : null if (children) { children.forEach((child, index) => saveOuter(child, exp, index)) } } } }
the_stack
import * as React from 'react'; import { Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, Grid, Divider, Typography, IconButton, CircularProgress, Zoom, } from '@material-ui/core'; import AddIcon from '@material-ui/icons/Add'; import Help from '@material-ui/icons/Help'; import DeleteIcon from '@material-ui/icons/Delete'; import { IKatibMetadata, IKatibParameter } from './LeftPanel'; import { NotebookPanel } from '@jupyterlab/notebook'; import { executeRpc, RPC_CALL_STATUS, RPCError } from '../lib/RPCUtils'; import { Kernel } from '@jupyterlab/services'; import { useTheme } from '@material-ui/core/styles'; import { Input } from '../components/Input'; import { Select } from '../components/Select'; import { LightTooltip } from '../components/LightTooltip'; // python to katib types const katibTypeMapper: { [id: string]: string } = { int: 'int', float: 'double', str: 'categorical', }; const algorithmOptions = [ { value: 'random', label: 'Random Search' }, { value: 'grid', label: 'Grid Search' }, { value: 'bayesianoptimization', label: 'Bayesian Optimization' }, // Temporarely disable the following algorithms // due to bad configuration. // { value: 'hyperband', label: 'Hyperband' }, // { value: 'tpe', label: 'Hyperopt TPE' }, ]; // https://github.com/scikit-optimize/scikit-optimize/blob/master/skopt/optimizer/optimizer.py#L55 const estimatorOptions = [ { value: 'GP', label: 'Gaussian Process Regressor (GP)' }, { value: 'RF', label: 'Random Forest Regressor (RF)' }, { value: 'ET', label: 'Extra Trees Regressor (ET)' }, { value: 'GBRT', label: 'Gradient Boosting Regressor (GBRT)' }, ]; // https://github.com/scikit-optimize/scikit-optimize/blob/master/skopt/optimizer/optimizer.py#L84 const acqFuncOptions = [ { value: 'LCB', label: 'Lower Confidence Bound (LCB)' }, { value: 'EI', label: 'Negative Expected Improvement (EI)' }, { value: 'PI', label: 'Negative Probability of Improvement (PI)' }, { value: 'gp_hedge', label: 'Choose Probabilistically (gp_hedge)' }, { value: 'EIps', label: 'EI + Function Compute Time (EIps)' }, { value: 'PIps', label: 'PI + Function Compute Time (PIps)' }, ]; interface KabitDialog { open: boolean; nbFilePath: string; toggleDialog: Function; katibMetadata: IKatibMetadata; updateKatibMetadata: Function; kernel: Kernel.IKernelConnection; } export const KatibDialog: React.FunctionComponent<KabitDialog> = props => { const [loading, setLoading] = React.useState(true); const [error, setError] = React.useState(''); const [pipelineParameters, setPipelineParameters] = React.useState([]); const [pipelineMetrics, setPipelineMetrics] = React.useState([]); const theme = useTheme(); React.useEffect(() => { // this is called when `open` changes value. // We are interested in the case when `open` becomes true. if (props.open) { // send RPC to retrieve current pipeline parameters and // update the state onKatibShowPanel(); } }, [props.open]); const onKatibShowPanel = async () => { // Send an RPC to Kale to get the pipeline parameters // that are currently defined in the notebook const args = { source_notebook_path: props.nbFilePath }; let rpcPipelineParameters = []; try { rpcPipelineParameters = await executeRpc( props.kernel, 'nb.get_pipeline_parameters', args, ); } catch (error) { if ( error instanceof RPCError && error.error.code === RPC_CALL_STATUS.InternalError ) { console.warn( 'InternalError while parsing the notebook for' + ' pipeline parameters', error.error, ); setError(error.error.err_details); setLoading(false); return; } else { // close Katib dialog before showing the error dialog props.toggleDialog(); throw error; } } // Send an RPC to Kale to get the pipeline metrics // that are currently defined in the notebook let rpcPipelineMetrics: any = []; try { rpcPipelineMetrics = await executeRpc( props.kernel, 'nb.get_pipeline_metrics', args, ); } catch (error) { if ( error instanceof RPCError && error.error.code === RPC_CALL_STATUS.InternalError ) { console.warn( 'InternalError while parsing the notebook for' + ' pipeline metrics', error.error, ); setError(error.error.err_details); setLoading(false); return; } else { // close Katib dialog before showing the error dialog props.toggleDialog(); throw error; } } setPipelineMetrics( Object.keys(rpcPipelineMetrics).map((x: string) => { return { label: rpcPipelineMetrics[x], value: x }; }), ); // now that we have new parameters from the RPC, check what are the // parameters currently stored in the notebook metadata. In case the // objectiveMetricName matches one of the RPC parameters, then keep it. // Otherwise we empty the field from the Notebook metadata. let newObjectiveMetricName = ''; let newAdditionalMetricNames: string[] = []; if ( Object.keys(rpcPipelineMetrics).includes( props.katibMetadata.objective.objectiveMetricName, ) ) { newObjectiveMetricName = props.katibMetadata.objective.objectiveMetricName; newAdditionalMetricNames = Object.keys(rpcPipelineMetrics).filter( x => x !== props.katibMetadata.objective.objectiveMetricName, ); } type IParameter = [boolean, string, string, string]; const paramsWithRequired: IParameter[] = rpcPipelineParameters.map( (x: IParameter) => [false, ...x], ); // a pipeline parameter is in the format: [<required>, <name>, <type>, <value>] // merge existing notebook parameters (tagged by `pipeline-parameters`) // with the parameters already present in the notebook's Katib Metadata // @ts-ignore const katibParameters: IKatibParameter[] = paramsWithRequired // first filter out all pipeline parameters that have types not // supported by Katib .filter(param => katibTypeMapper[param[2]] !== undefined) // keep only the parameter that have a corresponding entry in the // notebook's katib metadata .filter(param => { const new_param_name = param[1]; const new_param_type = katibTypeMapper[param[2]]; // check if this parameter is already part of the notebook's // Katib metadata const existing_param = props.katibMetadata.parameters.filter( x => x.name === new_param_name, ); return ( existing_param.length > 0 && // in case the new parameter is numeric, don't validate its type // because it could have been set to categorical by the user in a // previous Dialog interaction (['int', 'double'].includes(new_param_type) && existing_param[0].parameterType == 'categorical' ? true : existing_param[0].parameterType === new_param_type) ); }) // get the matching entries of the notebook's metadata (there might be // others that we don't need) .map( param => props.katibMetadata.parameters.filter(x => x.name === param[1])[0], ); // set the detected parameters as required, because they are already present // in the notebook metadata setPipelineParameters( paramsWithRequired.map(p => // check if the parameter is present inside the katibParameters list of // objects katibParameters.filter(kp => kp.name === p[1]).length > 0 ? [true, ...p.slice(1)] : p, ), ); // Now, with the result, update the state to save these parameters // to katib metadata props.updateKatibMetadata({ ...props.katibMetadata, parameters: katibParameters, objective: { ...props.katibMetadata.objective, objectiveMetricName: newObjectiveMetricName, additionalMetricNames: newAdditionalMetricNames, }, }); setLoading(false); }; const handleClose = () => { props.toggleDialog(); // next time the user open this dialog it will need // to call onKatibShowPanel again setError(''); setLoading(true); }; /** * TODO: Add docs */ const updateParameter = (parameter: string, action: Function) => ( value?: string, ) => { // update the metadata field of a specific parameter (e.g. min, max values) const currentParameterIndex = props.katibMetadata.parameters.findIndex( x => x.name === parameter, ); // now get elements with shallow copies let currentParameters = [...props.katibMetadata.parameters]; // get parameter and update field (`min`, `max`) let updatedParameter = { ...currentParameters[currentParameterIndex] }; action(updatedParameter, value); // replace old parameter at position idx with the updated one. // currentParameters.splice(currentParameterIndex, 1, updatedParameter); currentParameters[currentParameterIndex] = updatedParameter; props.updateKatibMetadata({ ...props.katibMetadata, parameters: currentParameters, }); }; const updateParameterFeasibleSpaceRange = (field: 'min' | 'max' | 'step') => ( parameter: IKatibParameter, value: string, ) => { // either min, max or step parameter.feasibleSpace = { ...parameter.feasibleSpace, [field]: value }; }; const updateParameterFeasibleSpaceList = (idx: number) => ( parameter: IKatibParameter, value: string, ) => { // update a categorical parameter, idx is the index of the value in the list // get the current parameter categorical list let newParameterList = [...parameter.feasibleSpace.list]; newParameterList[idx] = value; parameter.feasibleSpace = { ...parameter.feasibleSpace, list: newParameterList, }; }; const updateParameterList = (operation: 'add' | 'delete', idx: number) => ( parameter: IKatibParameter, ) => { let parameterList = parameter.feasibleSpace.list === undefined ? [] : [...parameter.feasibleSpace.list]; operation === 'add' ? // add a new category at the end of the list parameterList.push('') : // else operation=`delete`: remove 1 element at position idx parameterList.splice(idx, 1); parameter.feasibleSpace = { ...parameter.feasibleSpace, list: parameterList, }; }; const updateNumericParameterType = ( parameterName: string, parameterOriginalType: 'int' | 'double', ) => (parameter: IKatibParameter, value: string) => { if (value === 'list') { parameter.parameterType = 'categorical'; delete parameter.feasibleSpace.max; delete parameter.feasibleSpace.min; delete parameter.feasibleSpace.step; } else { // value === "range" parameter.parameterType = parameterOriginalType; delete parameter.feasibleSpace.list; } }; const updateObjectiveMetricName = (value: string) => { props.updateKatibMetadata({ ...props.katibMetadata, objective: { ...props.katibMetadata.objective, objectiveMetricName: value, // add all the other metrics to the additionalMetricsNames // pipeline metrics is of type {label: string, value: string}[] additionalMetricNames: pipelineMetrics .filter(x => x.value !== value) .map(x => x.value), }, }); }; const updateParameterRequired = ( parameterName: string, parameterType: string, ) => (event: React.ChangeEvent<HTMLInputElement>) => { const checked = event.target.checked; if (checked) { // add a new parameter entry in the notebook metadata props.updateKatibMetadata({ ...props.katibMetadata, parameters: [ ...props.katibMetadata.parameters, { name: parameterName, parameterType: parameterType, feasibleSpace: {}, }, ], }); } else { // remove the parameter entry from metadata const paramsWithoutUnchecked = props.katibMetadata.parameters.filter( x => x.name !== parameterName, ); props.updateKatibMetadata({ ...props.katibMetadata, parameters: paramsWithoutUnchecked, }); } // Assign the new check parameter to the pipeline parameter setPipelineParameters( pipelineParameters.map(x => x[1] == parameterName ? [checked, ...x.slice(1)] : x, ), ); }; const updateObjective = (field: 'type' | 'goal') => (value: string) => { // this callback is used by the text fields and select with katib objective // parameters. // update one of the fields of the katib objective props.updateKatibMetadata({ ...props.katibMetadata, objective: { ...props.katibMetadata.objective, [field]: field === 'goal' ? Number(value) : value, }, }); }; const updateAlgorithmName = (value: string) => { props.updateKatibMetadata({ ...props.katibMetadata, algorithm: { ...props.katibMetadata.algorithm, algorithmName: value }, }); }; const updateAlgorithmSetting = ( field: | 'random_state' | 'base_estimator' | 'n_initial_points' | 'acq_func' | 'acq_optimizer', ) => (value: string) => { let newSettings = ( props.katibMetadata.algorithm.algorithmSettings || [] ).filter(x => x.name !== field); newSettings.push({ name: field, value: value }); props.updateKatibMetadata({ ...props.katibMetadata, algorithm: { ...props.katibMetadata.algorithm, algorithmSettings: newSettings, }, }); return value; }; const updateCounts = ( field: 'maxTrialCount' | 'maxFailedTrialCount' | 'parallelTrialCount', ) => (value: string) => { props.updateKatibMetadata({ ...props.katibMetadata, [field]: Number(value), }); }; const getAlgorithmSetting = (settingName: string) => { const setting = ( props.katibMetadata.algorithm.algorithmSettings || [] ).filter(x => x.name === settingName); return setting.length > 0 ? setting[0].value : undefined; }; const getDialogHeader = (headerName: string, helpContent: any) => { return ( <React.Fragment> <Grid container direction="row" justify="flex-start" alignItems="center" > <div style={{ color: theme.kale.headers.main }} className="katib-dialog-header kale-header" > {headerName} </div> <LightTooltip title={helpContent} placement="top-start" interactive={true} TransitionComponent={Zoom} > <Help style={{ color: theme.kale.headers.main }} className="kale-header katib-headers-tooltip katib-dialog-header" /> </LightTooltip> </Grid> </React.Fragment> ); }; const katibParameters = props.katibMetadata.parameters || []; const parametersControls = loading ? '' : pipelineParameters.map((parameter, idx) => { const [ parameterRequired, parameterName, pyParameterType, parameterValue, ] = parameter; const katibParameterType = katibTypeMapper[pyParameterType]; // check if this pipeline parameter is required or not. // if it is not, don't crete any input field and if it is then get the // metadata parameter const metadataParameter = katibParameters.filter(x => x.name === parameterName)[0] || null; // ignored will hide the checkbox from pipeline parameters that cannot // become katib parameter // (e.g. boolean params) const ignored = katibParameterType === undefined; const searchSpace = !parameterRequired ? ( '' ) : metadataParameter.parameterType === 'categorical' ? ( // control to add a list to a feasible space <Grid container direction="column" justify="flex-end" alignItems="center" > {(metadataParameter.feasibleSpace.list || []).map((value, idx) => { return ( <Grid container direction="row" justify="flex-end" alignItems="center" > <Input validation={ pyParameterType === 'int' ? 'int' : pyParameterType === 'float' ? 'double' : null } variant={'outlined'} label={'Value'} value={value} updateValue={updateParameter( metadataParameter.name, updateParameterFeasibleSpaceList(idx), )} style={{ marginLeft: '4px', marginRight: '4px', width: 'auto', }} /> <IconButton aria-label="delete" onClick={() => { updateParameter( metadataParameter.name, updateParameterList('delete', idx), )(); }} > <DeleteIcon /> </IconButton> </Grid> ); })} <Grid container direction="row" justify="flex-end" alignItems="center" > <div className="add-button" style={{ padding: 0 }}> <Button variant="contained" size="small" title="Add Value" color="primary" style={{ marginRight: '52px' }} onClick={() => { updateParameter( metadataParameter.name, updateParameterList('add', idx), )(); }} > <AddIcon /> Add Value </Button> </div> </Grid> </Grid> ) : metadataParameter.parameterType === 'int' || metadataParameter.parameterType === 'double' ? ( // controls to add mix max feasible space <Grid container direction="row" justify="flex-end" alignItems="center" > <Grid item xs={3}> <Input validation={metadataParameter.parameterType} variant={'outlined'} label={'Min'} value={metadataParameter.feasibleSpace.min || ''} updateValue={updateParameter( metadataParameter.name, updateParameterFeasibleSpaceRange('min'), )} style={{ marginLeft: '4px', marginRight: '4px', width: 'auto' }} /> </Grid> <Grid item xs={3}> <Input validation={metadataParameter.parameterType} variant={'outlined'} label={'Max'} value={metadataParameter.feasibleSpace.max || ''} updateValue={updateParameter( metadataParameter.name, updateParameterFeasibleSpaceRange('max'), )} style={{ marginLeft: '4px', marginRight: '4px', width: 'auto' }} /> </Grid> <Grid item xs={3}> <Input validation={metadataParameter.parameterType} variant={'outlined'} label={'Step'} value={metadataParameter.feasibleSpace.step || ''} updateValue={updateParameter( metadataParameter.name, updateParameterFeasibleSpaceRange('step'), )} style={{ marginLeft: '4px', marginRight: '4px', width: 'auto' }} /> </Grid> </Grid> ) : ( '' ); return ( <React.Fragment> <Grid container direction="row" justify="flex-start" alignItems="center" > <Grid item xs={1}> <Checkbox disabled={ignored} checked={parameterRequired} onChange={updateParameterRequired( parameterName, katibParameterType, )} value="secondary" color="primary" // Here it is important to set the width to 100% because // jupyter is overriding the width to auto. This makes the // checkbox input to be misplaced wrt to the material checkbox // and results in the onChange to not work. inputProps={{ style: { height: '100%', }, }} /> </Grid> <Grid item xs={3}> <Typography variant="body2" style={parameterRequired ? {} : { opacity: '0.5' }} > Name: <b>{parameterName}</b> </Typography> {katibParameterType ? ( <Typography variant="body2" style={parameterRequired ? {} : { opacity: '0.5' }} > Type: <b>{katibParameterType}</b> </Typography> ) : ( '' )} {metadataParameter && ['int', 'float'].includes(pyParameterType) ? ( <Select variant={'outlined'} updateValue={updateParameter( parameterName, updateNumericParameterType( parameterName, pyParameterType, ), )} values={[ { label: 'Range', value: 'range' }, { label: 'List', value: 'list', tooltip: 'Depending on the implementation of your chosen' + ' algorithm, a list might be treated differently' + ' from a range.', }, ]} value={ metadataParameter.parameterType === 'categorical' ? 'list' : 'range' } label={''} index={0} /> ) : null} </Grid> <Grid item xs={8}> {katibParameterType ? ( searchSpace ) : ( <Typography variant="body2" style={{ opacity: '0.5' }}> Katib does not support this parameter's type </Typography> )} </Grid> </Grid> {/* Skip the last divider after the last parameter */} {/*{idx < pipelineParameters.length - 1 ? (*/} <Divider variant="middle" style={{ margin: '10px' }} /> {/*) : (*/} {/* ''*/} {/*)}*/} </React.Fragment> ); }); const body = loading ? ( <React.Fragment> <Grid container direction="column" justify="center" alignItems="center" style={{ marginTop: '20px' }} > <CircularProgress /> <Typography variant="body2">Loading pipeline parameters...</Typography> </Grid> </React.Fragment> ) : error !== '' ? ( <React.Fragment> <Grid container direction="column" justify="center" alignItems="flex-start" > <p style={{ marginTop: '10px' }}> An error has occurred while parsing the notebook: </p> <p style={{ fontWeight: 700 }}>{error}</p> </Grid> </React.Fragment> ) : ( <React.Fragment> {getDialogHeader( 'Search Space Parameters', <a target="_blank" href="https://www.kubeflow.org/docs/components/hyperparameter-tuning/experiment/#configuration-spec" > More Info... </a>, )} {parametersControls} {getDialogHeader( 'Search Algorithm', <a target="_blank" href="https://www.kubeflow.org/docs/components/hyperparameter-tuning/experiment/#search-algorithms" > More Info... </a>, )} <Select variant="outlined" label={'Algorithm'} values={algorithmOptions} value={props.katibMetadata.algorithm.algorithmName || ''} index={-1} updateValue={updateAlgorithmName} style={{ width: 'auto' }} /> {props.katibMetadata.algorithm.algorithmName === 'random' ? ( <React.Fragment> <Divider variant="middle" style={{ margin: '10px' }} /> <Grid container direction="row" justify="flex-start" alignItems="center" > <Input type="number" variant={'outlined'} label={'Random State'} value={ getAlgorithmSetting('random_state') || updateAlgorithmSetting('random_state')('10') } updateValue={updateAlgorithmSetting('random_state')} style={{ marginLeft: '4px', marginRight: '4px', width: 'auto' }} /> </Grid> </React.Fragment> ) : props.katibMetadata.algorithm.algorithmName == 'bayesianoptimization' ? ( <React.Fragment> <Divider variant="middle" style={{ margin: '10px' }} /> <Grid container direction="row" justify="center" alignItems="center"> <Grid item xs={9}> <Select variant="outlined" label={'Base Estimator'} values={estimatorOptions} value={ getAlgorithmSetting('base_estimator') || updateAlgorithmSetting('base_estimator')('GP') } index={-1} updateValue={updateAlgorithmSetting('base_estimator')} style={{ width: '97%' }} /> </Grid> <Grid item xs={3}> <Input type="number" variant={'outlined'} label={'N Initial Points'} value={ getAlgorithmSetting('random_state') || updateAlgorithmSetting('random_state')('10') } updateValue={updateAlgorithmSetting('n_initial_points')} style={{ marginLeft: '4px', marginRight: '4px', width: '95%' }} /> </Grid> </Grid> <Grid container direction="row" justify="center" alignItems="center"> <Grid item xs={5}> <Select variant="outlined" label={'Acquisition Function'} values={acqFuncOptions} value={ getAlgorithmSetting('acq_func') || updateAlgorithmSetting('acq_func')('gp_hedge') } index={-1} updateValue={updateAlgorithmSetting('acq_func')} style={{ width: '95%' }} /> </Grid> <Grid item xs={4}> <Input variant={'outlined'} label={'Acq. Fun. Optimizer'} value={ getAlgorithmSetting('acq_optimizer') || updateAlgorithmSetting('acq_optimizer')('auto') } updateValue={updateAlgorithmSetting('acq_optimizer')} style={{ marginLeft: '4px', marginRight: '4px', width: 'auto' }} /> </Grid> <Grid item xs={3}> <Input type="number" variant={'outlined'} label={'Random State'} value={ getAlgorithmSetting('random_state') || updateAlgorithmSetting('random_state')('10') } updateValue={updateAlgorithmSetting('random_state')} style={{ marginLeft: '4px', marginRight: '4px', width: 'auto' }} /> </Grid> </Grid> </React.Fragment> ) : ( '' )} {getDialogHeader( 'Search Objective', <a target="_blank" href="https://www.kubeflow.org/docs/components/hyperparameter-tuning/experiment/#configuration-spec" > More Info... </a>, )} <Grid container direction="row" justify="center" alignItems="center"> <Grid item xs={4}> <Select variant="outlined" label={'Reference Metric'} values={pipelineMetrics} value={props.katibMetadata.objective.objectiveMetricName || ''} index={-1} updateValue={updateObjectiveMetricName} style={{ width: '95%' }} /> </Grid> <Grid item xs={4}> <Select variant="outlined" label={'Type'} values={[ { label: 'Minimize', value: 'minimize' }, { label: 'Maximize', value: 'maximize' }, ]} value={props.katibMetadata.objective.type || 'minimize'} index={-1} updateValue={updateObjective('type')} style={{ width: '95%' }} /> </Grid> <Grid item xs={4}> <Input validation="double" variant={'outlined'} label={'Goal'} value={props.katibMetadata.objective.goal || ''} updateValue={updateObjective('goal')} style={{ marginLeft: '4px', marginRight: '4px', width: 'auto' }} /> </Grid> </Grid> {getDialogHeader( 'Run Parameters', <a target="_blank" href="https://www.kubeflow.org/docs/components/hyperparameter-tuning/experiment/#configuration-spec" > More Info... </a>, )} <Grid container direction="row" justify="center" alignItems="center"> <Grid item xs={4}> <Input validation="int" variant={'outlined'} label={'Parallel Trial Count'} value={props.katibMetadata.parallelTrialCount} updateValue={updateCounts('parallelTrialCount')} style={{ marginLeft: '4px', marginRight: '4px', width: 'auto' }} /> </Grid> <Grid item xs={4}> <Input validation="int" variant={'outlined'} label={'Max Trial Count'} value={props.katibMetadata.maxTrialCount} updateValue={updateCounts('maxTrialCount')} style={{ marginLeft: '4px', marginRight: '4px', width: 'auto' }} /> </Grid> <Grid item xs={4}> <Input validation="int" variant={'outlined'} label={'max Failed Trial Count'} value={props.katibMetadata.maxFailedTrialCount} updateValue={updateCounts('maxFailedTrialCount')} style={{ marginLeft: '4px', marginRight: '4px', width: 'auto' }} /> </Grid> </Grid> </React.Fragment> ); return ( <Dialog open={props.open} onClose={handleClose} fullWidth={true} maxWidth={'sm'} scroll="paper" aria-labelledby="scroll-dialog-title" aria-describedby="scroll-dialog-description" > <DialogTitle id="scroll-dialog-title"> <p style={{ padding: '0', color: theme.kale.headers.main }} className="kale-header" > Katib Job </p> </DialogTitle> <DialogContent dividers={true} style={{ paddingTop: 0 }}> {body} </DialogContent> <DialogActions> <Button onClick={handleClose} color="primary"> Close </Button> </DialogActions> </Dialog> ); };
the_stack
import type { Signer, TypedDataSigner } from '@ethersproject/abstract-signer'; import type { BaseProvider, TransactionReceipt, } from '@ethersproject/providers'; import { BigNumber, BigNumberish, ContractTransaction } from 'ethers'; import { Interface } from '@ethersproject/abi'; import invariant from 'tiny-invariant'; import warning from 'tiny-warning'; import { ERC1155__factory, ERC721__factory, ERC20__factory, IZeroEx, IZeroEx__factory, } from '../../contracts'; import type { ApprovalStatus, BaseNftSwap, PayableOverrides, TransactionOverrides, } from '../common/types'; import { UnexpectedAssetTypeError } from '../error'; import { approveAsset, DEFAULT_APP_ID, generateErc1155Order, generateErc721Order, getApprovalStatus, parseRawSignature, signOrderWithEoaWallet, verifyAppIdOrThrow, } from './pure'; import type { AddressesForChainV4, ApprovalOverrides, ERC721OrderStruct, FillOrderOverrides, NftOrderV4, NftOrderV4Serialized, OrderStructOptionsCommonStrict, SignedERC1155OrderStruct, SignedERC1155OrderStructSerialized, SignedERC721OrderStruct, SignedERC721OrderStructSerialized, SignedNftOrderV4, SigningOptionsV4, SwappableAssetV4, UserFacingERC1155AssetDataSerializedV4, UserFacingERC20AssetDataSerializedV4, UserFacingERC721AssetDataSerializedV4, } from './types'; import { ERC1155_TRANSFER_FROM_DATA, ERC721_TRANSFER_FROM_DATA, } from './nft-safe-transfer-from-data'; import addresses from './addresses.json'; import { searchOrderbook, postOrderToOrderbook, PostOrderResponsePayload, SearchOrdersParams, ORDERBOOK_API_ROOT_URL_PRODUCTION, SearchOrdersResponsePayload, } from './orderbook'; import { getWrappedNativeToken } from '../../utils/addresses'; import { DIRECTION_MAPPING, OrderStatusV4, TradeDirection } from './enums'; import { CONTRACT_ORDER_VALIDATOR } from './properties'; import { ETH_ADDRESS_AS_ERC20 } from './constants'; import { ZERO_AMOUNT } from '../../utils/eth'; import { arrayify } from '@ethersproject/bytes'; export enum SupportedChainIdsV4 { Mainnet = 1, Ropsten = 3, Ganache = 1337, Polygon = 137, PolygonMumbai = 80001, BSC = 56, Optimism = 10, Fantom = 250, Celo = 42220, Avalance = 43114, // Arbitrum = 42161, // soon } export const SupportedChainsForV4OrderbookStatusMonitoring = [ SupportedChainIdsV4.Ropsten, SupportedChainIdsV4.Polygon, SupportedChainIdsV4.PolygonMumbai, SupportedChainIdsV4.Mainnet, SupportedChainIdsV4.Optimism, ]; export interface INftSwapV4 extends BaseNftSwap { signOrder: ( order: NftOrderV4, signerAddress: string, signer: Signer, signingOptions?: Partial<SigningOptionsV4> ) => Promise<SignedNftOrderV4>; buildNftAndErc20Order: ( nft: | UserFacingERC721AssetDataSerializedV4 | UserFacingERC1155AssetDataSerializedV4, erc20: UserFacingERC20AssetDataSerializedV4, sellOrBuyNft: 'sell' | 'buy', makerAddress: string, userConfig?: Partial<OrderStructOptionsCommonStrict> ) => NftOrderV4Serialized; loadApprovalStatus: ( asset: SwappableAssetV4, walletAddress: string, approvalOverrides?: Partial<ApprovalOverrides> ) => Promise<ApprovalStatus>; approveTokenOrNftByAsset: ( asset: SwappableAssetV4, walletAddress: string, approvalTransactionOverrides?: Partial<TransactionOverrides>, approvalOverrides?: Partial<ApprovalOverrides> ) => Promise<ContractTransaction>; fillSignedOrder: ( signedOrder: SignedNftOrderV4, fillOrderOverrides?: Partial<FillOrderOverrides>, transactionOverrides?: Partial<PayableOverrides> ) => Promise<ContractTransaction>; awaitTransactionHash: (txHash: string) => Promise<TransactionReceipt>; cancelOrder: ( nonce: BigNumberish, orderType: 'ERC721' | 'ERC1155' // Can we make this optional ) => Promise<ContractTransaction>; matchOrders: ( sellOrder: SignedNftOrderV4, buyOrder: SignedNftOrderV4, transactionOverrides?: Partial<PayableOverrides> ) => Promise<ContractTransaction>; // waitUntilOrderFilledOrCancelled: ( // order: NftOrderV4, // timeoutInMs?: number, // pollOrderStatusFrequencyInMs?: number, // throwIfStatusOtherThanFillableOrFilled?: boolean // ) => Promise<OrderStatus | null>; getOrderStatus: (order: NftOrderV4) => Promise<OrderStatusV4>; // getOrderHash: (order: NftOrderV4) => string; // getTypedData: ( // chainId: number, // exchangeContractAddress: string, // order: NftOrderV4 // ) => TypedData; // normalizeSignedOrder: (order: SignedNftOrderV4) => SignedNftOrderV4; // normalizeOrder: (order: NftOrderV4) => NftOrderV4; // verifyOrderSignature: ( // order: NftOrderV4, // signature: string, // chainId: number, // exchangeContractAddress: string // ) => boolean; // checkIfOrderCanBeFilledWithNativeToken: (order: NftOrderV4) => boolean; // getAssetsFromOrder: (order: NftOrderV4) => { // makerAssets: SwappableAsset[]; // takerAssets: SwappableAsset[]; // }; } export interface AdditionalSdkConfig { // Identify your app fills with distinct integer appId: string; // Custom zeroex proxy contract address (defaults to the canonical contracts deployed by 0x Labs core team) zeroExExchangeProxyContractAddress: string; // Custom orderbook url. Defaults to using Trader.xyz's multi-chain open orderbook orderbookRootUrl: string; } class NftSwapV4 implements INftSwapV4 { // RPC provider public provider: BaseProvider; // Wallet signer public signer: Signer | undefined; // Chain Id for this instance of NftSwapV4. // To switch chains, instantiate a new version of NftSWapV4 with the updated chain id. public chainId: number; // ZeroEx ExchangeProxy contract address to reference public exchangeProxyContractAddress: string; // Generated ZeroEx ExchangeProxy contracts public exchangeProxy: IZeroEx; // Unique identifier for app. Must be a positive integer between 1 and 2**128 public appId: string; // Orderbook URL public orderbookRootUrl: string; constructor( provider: BaseProvider, signer: Signer, chainId?: number | string, additionalConfig?: Partial<AdditionalSdkConfig> ) { this.provider = provider; this.signer = signer; this.chainId = chainId ? parseInt(chainId.toString(10), 10) : (this.provider._network.chainId as SupportedChainIdsV4); const defaultAddressesForChain: AddressesForChainV4 | undefined = addresses[this.chainId as SupportedChainIdsV4]; const zeroExExchangeContractAddress = additionalConfig?.zeroExExchangeProxyContractAddress ?? defaultAddressesForChain?.exchange; invariant( zeroExExchangeContractAddress, '0x V4 Exchange Contract Address not set. Exchange Contract is required to load NftSwap' ); this.exchangeProxyContractAddress = zeroExExchangeContractAddress; this.orderbookRootUrl = additionalConfig?.orderbookRootUrl ?? ORDERBOOK_API_ROOT_URL_PRODUCTION; this.appId = additionalConfig?.appId ?? DEFAULT_APP_ID; verifyAppIdOrThrow(this.appId); this.exchangeProxy = IZeroEx__factory.connect( zeroExExchangeContractAddress, signer ?? provider ); } /** * Checks if an asset is approved for trading with 0x v4 * If an asset is not approved, call approveTokenOrNftByAsset to approve. * @param asset A tradeable asset (ERC20, ERC721, or ERC1155) * @param walletAddress The wallet address that owns the asset * @param approvalOverrides Optional config options for approving * @returns */ loadApprovalStatus = ( asset: SwappableAssetV4, walletAddress: string, approvalOverrides?: Partial<ApprovalOverrides> | undefined ): Promise<ApprovalStatus> => { // TODO(johnrjj) - Fix to pass thru more args... return getApprovalStatus( walletAddress, approvalOverrides?.exchangeContractAddress ?? this.exchangeProxy.address, asset, this.provider ); }; /** * Convenience function to await a transaction hash. * During a fill order call, you can get the pending transaction hash and await it manually via this method. * @param txHash Transaction hash to await * @returns */ awaitTransactionHash = async (txHash: string) => { return this.provider.waitForTransaction(txHash); }; /** * Cancels an 0x v4 order. Once cancelled, the order no longer fillable. * Requires a signer * @param nonce * @param orderType * @returns Transaciton Receipt */ cancelOrder = ( nonce: BigNumberish, orderType: 'ERC721' | 'ERC1155' ): Promise<ContractTransaction> => { if (orderType === 'ERC721') { return this.exchangeProxy.cancelERC721Order(nonce); } if (orderType === 'ERC1155') { return this.exchangeProxy.cancelERC1155Order(nonce); } console.log('unsupported order', orderType); throw new Error('unsupport order'); }; /** * Batch fill NFT sell orders * Can be used by taker to fill multiple NFT sell orders atomically. * E.g. A taker has a shopping cart full of NFTs to buy, can call this method to fill them all. * Requires a valid signer to execute transaction * @param signedOrders Signed 0x NFT sell orders * @param revertIfIncomplete Revert if we don't fill _all_ orders (defaults to false) * @param transactionOverrides Ethers transaciton overrides * @returns */ batchBuyNfts = ( signedOrders: Array<SignedNftOrderV4>, revertIfIncomplete: boolean = false, transactionOverrides?: PayableOverrides ) => { const allSellOrders = signedOrders.every((signedOrder) => { if (signedOrder.direction === 0) { return true; } return false; }); invariant( allSellOrders, `batchBuyNfts: All orders must be of type sell order (order direction == 0)` ); const allErc721 = signedOrders.every((signedOrder) => { if ('erc721Token' in signedOrder) { return true; } return false; }); const allErc1155 = signedOrders.every((signedOrder) => { if ('erc1155Token' in signedOrder) { return true; } return false; }); const eitherAllErc721OrErc1155Orders = allErc721 || allErc1155; invariant( eitherAllErc721OrErc1155Orders, `Batch buy is only available for tokens of the same ERC type.` ); if (allErc721) { const erc721SignedOrders: SignedERC721OrderStruct[] = signedOrders as SignedERC721OrderStruct[]; return this.exchangeProxy.batchBuyERC721s( erc721SignedOrders, erc721SignedOrders.map((so) => so.signature), erc721SignedOrders.map((_) => '0x'), revertIfIncomplete, { ...transactionOverrides, } ); } else if (allErc1155) { const erc1155SignedOrders: SignedERC1155OrderStruct[] = signedOrders as SignedERC1155OrderStruct[]; return this.exchangeProxy.batchBuyERC1155s( erc1155SignedOrders, erc1155SignedOrders.map((so) => so.signature), erc1155SignedOrders.map((so) => so.erc1155TokenAmount), erc1155SignedOrders.map((_) => '0x'), revertIfIncomplete, { ...transactionOverrides, } ); } else { throw Error('batchBuyNfts: Incompatible state'); } }; /** * Derives order hash from order (currently requires a provider to derive) * @param order A 0x v4 order (signed or unsigned) * @returns Order hash */ getOrderHash = (order: NftOrderV4Serialized): Promise<string> => { if ('erc721Token' in order) { return this.exchangeProxy.getERC721OrderHash(order); } if ('erc1155Token' in order) { return this.exchangeProxy.getERC1155OrderHash(order); } throw new Error('unsupport order'); }; /** * Looks up the order status for a given 0x v4 order. * (Available states for an order are 'filled', 'expired', ) * @param order An 0x v4 NFT order * @returns A number the corresponds to the enum OrderStatusV4 * Valid order states: * Invalid = 0 * Fillable = 1, * Unfillable = 2, * Expired = 3, */ getOrderStatus = async (order: NftOrderV4): Promise<number> => { if ('erc721Token' in order) { const erc721OrderStatus = await this.exchangeProxy.getERC721OrderStatus( order ); return erc721OrderStatus; } if ('erc1155Token' in order) { const [ _erc1155OrderHash, erc1155OrderStatus, _erc1155OrderAmount, _erc1155OrderAmountReminaing, ] = await this.exchangeProxy.getERC1155OrderInfo(order); return erc1155OrderStatus; } console.log('unsupported order', order); throw new Error('unsupport order'); }; /** * Convenience function to approve an asset (ERC20, ERC721, or ERC1155) for trading with 0x v4 * @param asset * @param _walletAddress * @param approvalTransactionOverrides * @param otherOverrides * @returns An ethers contract transaction */ approveTokenOrNftByAsset = ( asset: SwappableAssetV4, _walletAddress: string, // Remove in next release approvalTransactionOverrides?: Partial<TransactionOverrides>, otherOverrides?: Partial<ApprovalOverrides> ): Promise<ContractTransaction> => { const signedToUse = otherOverrides?.signer ?? this.signer; if (!signedToUse) { throw new Error('Signed not defined'); } return approveAsset( this.exchangeProxy.address, asset, signedToUse, { ...approvalTransactionOverrides, }, otherOverrides ); }; // // TyPeSaFeTy: Order types supported: // // ERC721<>ERC20 // // ERC1155<>ERC20 // // Below ensures type-safe for those specific combinations /** * Builds a 0x order given two assets (either NFT<>ERC20 or ERC20<>NFT) * @param makerAsset An asset (ERC20, ERC721, or ERC1155) the user has * @param takerAsset An asset (ERC20, ERC721, or ERC1155) the user wants * @param makerAddress The address of the wallet creating the order * @param orderConfig Various order configuration options (e.g. expiration, nonce) */ buildOrder( makerAsset: UserFacingERC1155AssetDataSerializedV4, takerAsset: UserFacingERC20AssetDataSerializedV4, makerAddress: string, orderConfig?: Partial<OrderStructOptionsCommonStrict> ): NftOrderV4Serialized; buildOrder( makerAsset: UserFacingERC20AssetDataSerializedV4, takerAsset: UserFacingERC1155AssetDataSerializedV4, makerAddress: string, orderConfig?: Partial<OrderStructOptionsCommonStrict> ): NftOrderV4Serialized; buildOrder( makerAsset: UserFacingERC721AssetDataSerializedV4, takerAsset: UserFacingERC20AssetDataSerializedV4, makerAddress: string, orderConfig?: Partial<OrderStructOptionsCommonStrict> ): NftOrderV4Serialized; buildOrder( makerAsset: UserFacingERC20AssetDataSerializedV4, takerAsset: UserFacingERC721AssetDataSerializedV4, makerAddress: string, orderConfig?: Partial<OrderStructOptionsCommonStrict> ): NftOrderV4Serialized; buildOrder( makerAsset: SwappableAssetV4, takerAsset: SwappableAssetV4, makerAddress: string, orderConfig?: Partial<OrderStructOptionsCommonStrict> ) { // Basic validation checks if ( (takerAsset.type === 'ERC1155' || takerAsset.type === 'ERC721') && (makerAsset.type === 'ERC1155' || makerAsset.type === 'ERC721') ) { throw new Error( '0x v4 only supports ERC721/ERC1155 <> ERC20. Currently 0x v4 does not support NFT<>NFT swaps, please use 0x v3 SDK for that.' ); } if (makerAsset.type === 'ERC20' && takerAsset.type === 'ERC20') { throw new Error( '0x v4 only supports ERC721/ERC1155 <> ERC20. Currently 0x v4 does not support NFT<>NFT swaps, please use 0x v3 SDK for that.' ); } // First determine if the maker or taker is trading the erc20 (to orient the direction of the trade) let direction: TradeDirection = TradeDirection.SellNFT; if (takerAsset.type === 'ERC20') { // NFT is on the maker side (so the maker is selling the NFT) direction = TradeDirection.SellNFT; } if (makerAsset.type === 'ERC20') { // NFT is on the taker side (so the maker is buying the NFT) direction = TradeDirection.BuyNFT; } const nft = ( direction === TradeDirection.BuyNFT ? takerAsset : makerAsset ) as SwappableAssetV4; const erc20 = ( direction === TradeDirection.BuyNFT ? makerAsset : takerAsset ) as UserFacingERC20AssetDataSerializedV4; return this.buildNftAndErc20Order( nft, erc20, DIRECTION_MAPPING[direction], makerAddress, orderConfig ); } getWrappedTokenAddress = (chainId: number | string) => { return getWrappedNativeToken(chainId); }; buildCollectionBasedOrder = ( erc20ToSell: UserFacingERC20AssetDataSerializedV4, nftCollectionToBid: { tokenAddress: string; type: 'ERC721' | 'ERC1155'; }, makerAddress: string ): NftOrderV4Serialized => { return this.buildNftAndErc20Order( { ...nftCollectionToBid, // Override tokenId to zero, tokenId is ignored when using token properties tokenId: '0', }, erc20ToSell, 'buy', makerAddress, { // Add the token property of 'collection', so this order will be valid for any nft in the collection tokenProperties: [CONTRACT_ORDER_VALIDATOR], } ); }; buildNftAndErc20Order = ( nft: SwappableAssetV4, erc20: UserFacingERC20AssetDataSerializedV4, sellOrBuyNft: 'sell' | 'buy' = 'sell', makerAddress: string, userConfig?: Partial<OrderStructOptionsCommonStrict> ): NftOrderV4Serialized => { const defaultConfig = { chainId: this.chainId, makerAddress: makerAddress, appId: this.appId, }; const config = { ...defaultConfig, ...userConfig }; const direction = sellOrBuyNft === 'sell' ? TradeDirection.SellNFT : TradeDirection.BuyNFT; // Validate that a bid does not use ETH. if (direction === TradeDirection.BuyNFT) { if (erc20.tokenAddress.toLowerCase() === ETH_ADDRESS_AS_ERC20) { throw new Error( 'NFT Bids cannot use the native token (e.g. ETH). Please use the wrapped native token (e.g. WETH)' ); } } switch (nft.type) { // Build ERC721 order case 'ERC721': const erc721Order = generateErc721Order(nft, erc20, { direction, maker: makerAddress, ...config, }); return erc721Order; // Build ERC1155 order case 'ERC1155': const erc1155Order = generateErc1155Order(nft, erc20, { direction, maker: makerAddress, ...config, }); return erc1155Order; default: throw new UnexpectedAssetTypeError((nft as any).type ?? 'Unknown'); } }; /** * Signs a 0x order. Requires a signer (e.g. wallet or private key) * Once signed, the order becomes fillable (as long as the order is valid) * 0x orders require a signature to fill. * @param order A 0x v4 order * @returns A signed 0x v4 order */ signOrder = async (order: NftOrderV4): Promise<SignedNftOrderV4> => { if (!this.signer) { throw new Error('Signed not defined'); } const rawSignature = await signOrderWithEoaWallet( order, this.signer as unknown as TypedDataSigner, this.chainId, this.exchangeProxy.address ); const ecSignature = parseRawSignature(rawSignature); const signedOrder = { ...order, signature: { signatureType: 2, r: ecSignature.r, s: ecSignature.s, v: ecSignature.v, }, }; return signedOrder; }; /** * Fill a 'Buy NFT' order (e.g. taker would be selling'their NFT to fill this order) without needing an approval * Use case: Users can accept offers/bids for their NFTs without needing to approve their NFT! 🤯 * @param signedOrder Signed Buy Nft order (e.g. direction = 1) * @param tokenId NFT token id that taker of trade will sell * @param fillOrderOverrides Trade specific (SDK-level) overrides * @param transactionOverrides General transaction overrides from ethers (gasPrice, gasLimit, etc) * @returns */ fillBuyNftOrderWithoutApproval = async ( signedOrder: SignedNftOrderV4, tokenId: string, fillOrderOverrides?: Partial<FillOrderOverrides>, transactionOverrides?: Partial<PayableOverrides> ) => { if (!this.signer) { throw new Error( 'Signer undefined. Signer must be provided to fill order' ); } if (signedOrder.direction !== TradeDirection.BuyNFT) { throw new Error( 'Only filling Buy NFT orders (direction=1) is valid for skipping approvals' ); } const signerAddress = await this.signer.getAddress(); const unwrapWeth = fillOrderOverrides?.fillOrderWithNativeTokenInsteadOfWrappedToken ?? false; // Handle ERC721 if ('erc721Token' in signedOrder) { const erc721Contract = ERC721__factory.connect( signedOrder.erc721Token, this.signer ); const encodingIface = new Interface(ERC721_TRANSFER_FROM_DATA); const fragment = encodingIface.getFunction('safeTransferFromErc721Data'); const data = encodingIface._encodeParams(fragment.inputs, [ signedOrder, signedOrder.signature, unwrapWeth, ]); const transferFromTx = await erc721Contract[ 'safeTransferFrom(address,address,uint256,bytes)' ]( signerAddress, this.exchangeProxy.address, fillOrderOverrides?.tokenIdToSellForCollectionOrder ?? tokenId, data, transactionOverrides ?? {} ); return transferFromTx; } // Handle ERC1155 if ('erc1155Token' in signedOrder) { const erc1155Contract = ERC1155__factory.connect( signedOrder.erc1155Token, this.signer ); const encodingIface = new Interface(ERC1155_TRANSFER_FROM_DATA); const fragment = encodingIface.getFunction('safeTransferFromErc1155Data'); const data = encodingIface._encodeParams(fragment.inputs, [ signedOrder, signedOrder.signature, unwrapWeth, ]); const transferFromTx = await erc1155Contract.safeTransferFrom( signerAddress, this.exchangeProxy.address, fillOrderOverrides?.tokenIdToSellForCollectionOrder ?? tokenId, signedOrder.erc1155TokenAmount ?? '1', data, transactionOverrides ?? {} ); return transferFromTx; } // Unknown format (NFT neither ERC721 or ERC1155) throw new Error('unknown order type'); }; /** * Fills a 'collection'-based order (e.g. a bid for any nft belonging to a particular collection) * @param signedOrder A 0x signed collection order * @param tokenId The token id to fill for the collection order * @param fillOrderOverrides Various fill options * @param transactionOverrides Ethers transaction overrides * @returns */ fillSignedCollectionOrder = async ( signedOrder: SignedNftOrderV4, tokenId: BigNumberish, fillOrderOverrides?: Partial<FillOrderOverrides>, transactionOverrides?: Partial<PayableOverrides> ) => { return this.fillSignedOrder( signedOrder, { tokenIdToSellForCollectionOrder: tokenId, ...fillOrderOverrides, }, { ...transactionOverrides, } ); }; isErc20NativeToken = (order: NftOrderV4): boolean => { return order.erc20Token.toLowerCase() === ETH_ADDRESS_AS_ERC20; }; /** * Fills a signed order * @param signedOrder A signed 0x v4 order * @param fillOrderOverrides Optional configuration on possible ways to fill the order * @param transactionOverrides Ethers transaction overrides (e.g. gas price) * @returns */ fillSignedOrder = async ( signedOrder: SignedNftOrderV4, fillOrderOverrides?: Partial<FillOrderOverrides>, transactionOverrides?: Partial<PayableOverrides> ) => { // Only Sell orders can be filled with ETH const canOrderTypeBeFilledWithNativeToken = signedOrder.direction === TradeDirection.SellNFT; // Is ERC20 being traded the native token const isNativeToken = this.isErc20NativeToken(signedOrder); const needsEthAttached = isNativeToken && canOrderTypeBeFilledWithNativeToken; const erc20TotalAmount = this.getErc20TotalIncludingFees(signedOrder); // do fill if ('erc1155Token' in signedOrder) { // If maker is selling an NFT, taker wants to 'buy' nft if (signedOrder.direction === TradeDirection.SellNFT) { return this.exchangeProxy.buyERC1155( signedOrder, signedOrder.signature, signedOrder.erc1155TokenAmount, '0x', { // If we're filling an order with ETH, be sure to include the value with fees added value: needsEthAttached ? erc20TotalAmount : undefined, ...transactionOverrides, } ); } else { // TODO(detect if erc20 token is wrapped token, then switch true. if true when not wrapped token, tx will fail) let unwrapNativeToken: boolean = fillOrderOverrides?.fillOrderWithNativeTokenInsteadOfWrappedToken ?? false; if (signedOrder.erc1155TokenProperties.length > 0) { // property based order, let's make sure they've specifically provided a tokenIdToSellForCollectionOrder if ( fillOrderOverrides?.tokenIdToSellForCollectionOrder === undefined ) { throw new Error( 'Collection order missing NFT tokenId to fill with. Specify in fillOrderOverrides.tokenIdToSellForCollectionOrder' ); } } // Otherwise, taker is selling the nft (and buying an ERC20) return this.exchangeProxy.sellERC1155( signedOrder, signedOrder.signature, fillOrderOverrides?.tokenIdToSellForCollectionOrder ?? signedOrder.erc1155TokenId, signedOrder.erc1155TokenAmount, unwrapNativeToken, '0x', { ...transactionOverrides, } ); } } else if ('erc721Token' in signedOrder) { // If maker is selling an NFT, taker wants to 'buy' nft if (signedOrder.direction === TradeDirection.SellNFT) { return this.exchangeProxy.buyERC721( signedOrder, signedOrder.signature, '0x', { // If we're filling an order with ETH, be sure to include the value with fees added value: needsEthAttached ? erc20TotalAmount : undefined, ...transactionOverrides, } ); } else { // TODO(detect if erc20 token is wrapped token, then switch true. if true when not wrapped token, tx will fail) let unwrapNativeToken: boolean = fillOrderOverrides?.fillOrderWithNativeTokenInsteadOfWrappedToken ?? false; if (signedOrder.erc721TokenProperties.length > 0) { // property based order, let's make sure they've specifically provided a tokenIdToSellForCollectionOrder if ( fillOrderOverrides?.tokenIdToSellForCollectionOrder === undefined ) { throw new Error( 'Collection order missing NFT tokenId to fill with. Specify in fillOrderOverrides.tokenIdToSellForCollectionOrder' ); } } // Otherwise, taker is selling the nft (and buying an ERC20) return this.exchangeProxy.sellERC721( signedOrder, signedOrder.signature, fillOrderOverrides?.tokenIdToSellForCollectionOrder ?? signedOrder.erc721TokenId, unwrapNativeToken, '0x', { ...transactionOverrides, } ); } } console.log('unsupported order', signedOrder); throw new Error('unsupport signedOrder type'); }; /** * Posts a 0x order to the Trader.xyz NFT open orderbook * @param signedOrder A valid 0x v4 signed order * @param chainId The chain id (e.g. '1' for mainnet, or '137' for polygon mainnet) * @param metadata An optional record object (key: string, value: string) that will be stored alongside the order in the orderbook * This is helpful for webapp builders, as they can save app-level order metadata * (e.g. maybe save a 'bidMessage' alongside the order, or extra image metadata) * @returns */ postOrder = ( signedOrder: SignedNftOrderV4, chainId: string | number, metadata?: Record<string, string> ): Promise<PostOrderResponsePayload> => { const parsedChainId = parseInt(chainId.toString(10), 10); const supportsMonitoring = SupportedChainsForV4OrderbookStatusMonitoring.includes(parsedChainId); warning( supportsMonitoring, `Chain ${chainId} does not support live orderbook status monitoring. Orders can be posted to be persisted, but status wont be monitored (e.g. updating status on a fill, cancel, or expiry.)` ); return postOrderToOrderbook(signedOrder, parsedChainId, metadata, { rootUrl: this.orderbookRootUrl, }); }; /** * Gets orders from the Trader.xyz Open NFT Orderbook * By default will find all order, active orders. * @param filters Various options to filter an order search * @returns An object that includes `orders` key with an array of orders that meet the search critera */ getOrders = async ( filters?: Partial<SearchOrdersParams> ): Promise<SearchOrdersResponsePayload> => { const orders = await searchOrderbook(filters, { rootUrl: this.orderbookRootUrl, }); return orders; }; /** * * @param sellOrder ERC721 Order to sell an NFT * @param buyOrder ERC721 Order to buy an NFT * @param transactionOverrides Ethers transaction overrides * @returns */ matchOrders = async ( // NOTE(johnrjj)- Should these types be SignedERC721OrderStruct directly since only 712 is supported for matching sellOrder: SignedNftOrderV4, buyOrder: SignedNftOrderV4, transactionOverrides?: Partial<PayableOverrides> ) => { if ('erc721Token' in sellOrder && 'erc721Token' in buyOrder) { // TODO(johnrjj) - More validation here before we match on-chain const contractTx = await this.exchangeProxy.matchERC721Orders( sellOrder, buyOrder, sellOrder.signature, buyOrder.signature, transactionOverrides ?? {} ); return contractTx; } throw new Error( 'Only ERC721 Orders are currently supported for matching. Please ensure both the sellOrder and buyOrder are ERC721 orders' ); }; getMakerAsset = (order: NftOrderV4): SwappableAssetV4 => { // Buy NFT - So maker asset is an ERC20 if (order.direction.toString(10) === TradeDirection.BuyNFT.toString()) { return { tokenAddress: order.erc20Token, amount: order.erc20TokenAmount.toString(10), type: 'ERC20' as const, }; } else if ( order.direction.toString(10) === TradeDirection.SellNFT.toString() ) { // Sell NFT - So maker asset is an NFT (either ERC721 or ERC1155) if ('erc721Token' in order) { return { tokenAddress: order.erc721Token, tokenId: order.erc721TokenId.toString(10), type: 'ERC721' as const, }; } else if ('erc1155Token' in order) { return { tokenAddress: order.erc1155Token, tokenId: order.erc1155TokenId.toString(10), amount: order.erc1155TokenAmount.toString(10), type: 'ERC1155' as const, }; } } throw new Error(`Unknown order direction ${order.direction}`); }; getTakerAsset = (order: NftOrderV4): SwappableAssetV4 => { // Buy NFT - So taker asset is an NFT [ERC721 or ERC1155] (because the taker is the NFT owner 'accepting' a buy order) if (order.direction.toString(10) === TradeDirection.BuyNFT.toString()) { if ('erc721Token' in order) { return { tokenAddress: order.erc721Token, tokenId: order.erc721TokenId.toString(10), type: 'ERC721' as const, }; } else if ('erc1155Token' in order) { return { tokenAddress: order.erc1155Token, tokenId: order.erc1155TokenId.toString(10), amount: order.erc1155TokenAmount.toString(10), type: 'ERC1155' as const, }; } } else if ( order.direction.toString(10) === TradeDirection.SellNFT.toString() ) { // Sell NFT - So taker asset is an ERC20 -- because the taker here is 'buying' the sell NFT order return { tokenAddress: order.erc20Token, amount: order.erc20TokenAmount.toString(10), type: 'ERC20' as const, }; } throw new Error(`Unknown order direction ${order.direction}`); }; /** * Validate an order signature given a signed order * Throws if invalid * @param signedOrder A 0x v4 signed order to validate signature for * @returns */ validateSignature = async ( signedOrder: SignedNftOrderV4 ): Promise<boolean> => { if ('erc721Token' in signedOrder) { // Validate functions on-chain return void if successful await this.exchangeProxy.validateERC721OrderSignature( signedOrder, signedOrder.signature ); return true; } else if ('erc1155Token' in signedOrder) { // Validate functions on-chain return void if successful await this.exchangeProxy.validateERC1155OrderSignature( signedOrder, signedOrder.signature ); return true; } else { throw new Error('Unknown order type (not ERC721 or ERC1155)'); } }; /** * Fetches the balance of an asset for a given wallet address * @param asset A Tradeable asset -- An ERC20, ERC721, or ERC1155 * @param walletAddress A wallet address ('0x1234...6789') * @param provider Optional, defaults to the class's provider but can be overridden * @returns A BigNumber balance (e.g. 1 or 0 for ERC721s. ERC20 and ERC1155s can have balances greater than 1) */ fetchBalanceForAsset = async ( asset: SwappableAssetV4, walletAddress: string, provider: BaseProvider = this.provider ): Promise<BigNumber> => { switch (asset.type) { case 'ERC20': const erc20 = ERC20__factory.connect(asset.tokenAddress, provider); return erc20.balanceOf(walletAddress); case 'ERC721': const erc721 = ERC721__factory.connect(asset.tokenAddress, provider); const owner = await erc721.ownerOf(asset.tokenId); if (owner.toLowerCase() === walletAddress.toLowerCase()) { return BigNumber.from(1); } return BigNumber.from(0); case 'ERC1155': const erc1155 = ERC1155__factory.connect(asset.tokenAddress, provider); return erc1155.balanceOf(walletAddress, asset.tokenId); default: throw new Error(`Asset type unknown ${(asset as any).type}`); } }; // TODO(johnrjj) Consolidate w/ checkOrderCanBeFilledMakerSide checkOrderCanBeFilledTakerSide = async ( order: NftOrderV4, takerWalletAddress: string ) => { const takerAsset = this.getTakerAsset(order); const takerApprovalStatus = await this.loadApprovalStatus( takerAsset, takerWalletAddress ); const takerBalance = await this.fetchBalanceForAsset( this.getTakerAsset(order), takerWalletAddress ); const hasBalance: boolean = takerBalance.gte( (takerAsset as UserFacingERC20AssetDataSerializedV4).amount ?? 1 ); const isApproved: boolean = takerApprovalStatus.contractApproved || takerApprovalStatus.tokenIdApproved || false; const canOrderBeFilled: boolean = hasBalance && isApproved; return { approvalStatus: takerApprovalStatus, balance: takerBalance.toString(), isApproved, hasBalance, canOrderBeFilled, }; }; checkOrderCanBeFilledMakerSide = async ( order: NftOrderV4 // override?: Partial<VerifyOrderOptionsOverrides> ) => { const makerAddress = order.maker; const makerAsset = this.getMakerAsset(order); const makerApprovalStatus = await this.loadApprovalStatus( makerAsset, makerAddress ); const makerBalance = await this.fetchBalanceForAsset( this.getMakerAsset(order), makerAddress ); const hasBalance: boolean = makerBalance.gte( (makerAsset as UserFacingERC20AssetDataSerializedV4).amount ?? 1 ); const isApproved: boolean = makerApprovalStatus.tokenIdApproved || makerApprovalStatus.contractApproved || false; const canOrderBeFilled: boolean = hasBalance && isApproved; return { approvalStatus: makerApprovalStatus, balance: makerBalance.toString(), isApproved, hasBalance, canOrderBeFilled, }; }; /** * Convenience function to sum all fees. Total fees denominated in erc20 token amount. * @param order A 0x v4 order (signed or un-signed); * @returns Total summed fees for a 0x v4 order. Amount is represented in Erc20 token units. */ getTotalFees = (order: NftOrderV4): BigNumber => { const fees = order.fees; // In 0x v4, fees are additive (not included in the original erc20 amount) let feesTotal = ZERO_AMOUNT; fees.forEach((fee) => { feesTotal = feesTotal.add(BigNumber.from(fee.amount)); }); return feesTotal; }; /** * Calculates total order cost. * In 0x v4, fees are additive (i.e. they are not deducted from the order amount, but added on top of) * @param order A 0x v4 order; * @returns Total cost of an order (base amount + fees). Amount is represented in Erc20 token units. Does not include gas costs. */ getErc20TotalIncludingFees = (order: NftOrderV4): BigNumber => { const fees = order.fees; // In 0x v4, fees are additive (not included in the original erc20 amount) let feesTotal = this.getTotalFees(order); const orderTotalCost = BigNumber.from(order.erc20TokenAmount).add( feesTotal ); return orderTotalCost; }; } export { NftSwapV4 };
the_stack
import { giveConsent } from '../helpers/consent-management'; import { SampleUser } from '../sample-data/checkout-flow'; import { standardUser } from '../sample-data/shared-users'; import { switchSiteContext } from '../support/utils/switch-site-context'; import { login, register } from './auth-forms'; import { clickHamburger, waitForPage } from './checkout-flow'; import { checkBanner } from './homepage'; import { signOutUser } from './login'; import { LANGUAGE_DE, LANGUAGE_LABEL } from './site-context-selector'; import { generateMail, randomString } from './user'; export const ANONYMOUS_BANNER = 'cx-anonymous-consent-management-banner'; export const ANONYMOUS_DIALOG = 'cx-anonymous-consent-dialog'; export const ANONYMOUS_OPEN_DIALOG = 'cx-anonymous-consent-open-dialog'; const BE_CHECKED = 'be.checked'; const NOT_BE_CHECKED = 'not.be.checked'; const BE_DISABLED = 'be.disabled'; const NOT_EXIST = 'not.exist'; const noRegistrationConsent = false; const clickRegistrationConsent = true; const firstCheckBoxPosition = 0; const secondCheckBoxPosition = 1; export const MARKETING_NEWSLETTER = 'MARKETING_NEWSLETTER'; export const PROFILE = 'PROFILE'; export const STORE_USER_INFORMATION = 'STORE_USER_INFORMATION'; export const noLegalDescriptionInDialog = false; export const displayLegalDescriptionInDialog = true; const personalizationConsentLabel = 'personalised'; const userGiveConsentRegistrationTest: SampleUser = { firstName: 'John', lastName: 'Doe', email: generateMail(randomString(), true), password: 'Password123!', }; const userTransferConsentTest: SampleUser = { firstName: 'Cypress', lastName: 'AnonymousUser', email: generateMail(randomString(), true), password: 'Password123!', }; const userFromConfigTest: SampleUser = { firstName: 'x', lastName: 'x', email: generateMail(randomString(), true), password: 'Password123!', }; export function anonoymousConsentConfig( registerConsent: string, showLegalDescriptionInDialog: boolean, requiredConsents: string[], consentManagementPage: { showAnonymousConsents: boolean; hideConsents: string[]; } ) { cy.cxConfig({ anonymousConsents: { registerConsent, showLegalDescriptionInDialog, requiredConsents, consentManagementPage, }, }); } export function registerNewUserAndLogin( newUser: SampleUser, giveRegistrationConsent = false, hiddenConsent? ) { cy.visit('/login/register'); register(newUser, giveRegistrationConsent, hiddenConsent); cy.get('cx-breadcrumb').contains('Login'); login(newUser.email, newUser.password); } export function navigateToConsentPage() { const consentsPage = waitForPage('/my-account/consents', 'getConsentsPage'); cy.selectUserMenuOption({ option: 'Consent Management', }); cy.wait(`@${consentsPage}`).its('response.statusCode').should('eq', 200); } export function seeBannerAsAnonymous() { cy.get(ANONYMOUS_BANNER).should('exist'); } export function checkBannerHidden() { cy.get(ANONYMOUS_BANNER).should('not.be.visible'); } export function checkDialogDescription() { cy.get(`${ANONYMOUS_DIALOG} .cx-dialog-description`).should(NOT_EXIST); } export function checkConsentsInConsentPage() { cy.get('.cx-consent-toggles cx-consent-management-form').should(NOT_EXIST); } export function clickAllowAllFromBanner() { cy.get(ANONYMOUS_BANNER).find('.btn-primary').click(); } export function clickViewDetailsFromBanner() { cy.get(ANONYMOUS_BANNER).find('.btn-action').click({ force: true }); } export function openAnonymousConsentsDialog() { cy.get('cx-anonymous-consent-open-dialog').within(() => { const link = cy.get('button'); link.should('exist'); link.click({ force: true }); }); } export function checkDialogOpen() { cy.get(ANONYMOUS_DIALOG).should('exist'); } export function checkDialogClosed() { cy.get(ANONYMOUS_DIALOG).should(NOT_EXIST); } export function closeAnonymousConsentsDialog() { cy.get(`${ANONYMOUS_DIALOG} button.close`).click({ force: true }); } export function toggleAnonymousConsent(position) { cy.get(`.cx-dialog-row:nth-child(${position})`) .find('input') .click({ force: true }); } export function checkInputConsentState(position, state) { cy.get('input[type="checkbox"]').eq(position).should(state); } export function checkAllInputConsentState(state) { cy.get('input[type="checkbox"]').each(($match) => { cy.wrap($match).should(state); }); } export function selectAllConsent() { cy.get(`${ANONYMOUS_DIALOG} .cx-action-link`).eq(1).click({ force: true }); } export function clearAllConsent() { cy.get(`${ANONYMOUS_DIALOG} .cx-action-link`).first().click({ force: true }); } export function checkConsentNotExist(text) { cy.get(`${ANONYMOUS_DIALOG} .cx-dialog-row`) .find('label') .each(($match) => { cy.wrap($match).should('not.contain', text); }); } export function loggedInUserBannerTest() { cy.get(ANONYMOUS_BANNER).should(NOT_EXIST); } export function loggedInUserFooterLinkTest() { cy.get('.anonymous-consents').should(NOT_EXIST); } export function sessionLogin() { standardUser.registrationData.email = generateMail(randomString(), true); cy.requireLoggedIn(standardUser); } export function registerUserAndCheckMyAccountConsent( user, consentCheckBox, position, hiddenConsent? ) { registerNewUserAndLogin(user, consentCheckBox, hiddenConsent); checkBanner(); navigateToConsentPage(); checkInputConsentState(position, BE_CHECKED); } export function testAsAnonymousUser() { it('should click the footer to check if all consents were accepted and withdraw all consents afterwards', () => { openAnonymousConsentsDialog(); checkAllInputConsentState(BE_CHECKED); clearAllConsent(); }); it('should click the footer to check if all consents were rejected and accept all consents again', () => { openAnonymousConsentsDialog(); checkAllInputConsentState(NOT_BE_CHECKED); selectAllConsent(); }); } export function giveRegistrationConsentTest() { it('should give the registration consent', () => { registerUserAndCheckMyAccountConsent( userGiveConsentRegistrationTest, clickRegistrationConsent, firstCheckBoxPosition ); }); } export function movingFromAnonymousToRegisteredUser() { it('should transfer anonymous consents and load the previously given registered consents when registered', () => { openAnonymousConsentsDialog(); cy.log('Giving second consent as anonymous user'); toggleAnonymousConsent(2); closeAnonymousConsentsDialog(); // a new email is needed for a fresh user (due to viewports) userTransferConsentTest.email = generateMail(randomString(), true); registerUserAndCheckMyAccountConsent( userTransferConsentTest, noRegistrationConsent, secondCheckBoxPosition ); cy.log('Giving first consent as logged in user'); giveConsent(); cy.log('Signing out logged in user'); signOutUser(); clickViewDetailsFromBanner(); cy.log('Toggling second consent as anonymous user'); toggleAnonymousConsent(2); closeAnonymousConsentsDialog(); const loginPage = waitForPage('/login', 'getLoginPage'); cy.onMobile(() => { clickHamburger(); }); cy.get('cx-login [role="link"]').click({ force: true }); cy.wait(`@${loginPage}`).its('response.statusCode').should('eq', 200); login(userTransferConsentTest.email, userTransferConsentTest.password); cy.log('Checking logged in user consents overriding anonymous consents'); navigateToConsentPage(); checkInputConsentState(0, BE_CHECKED); checkInputConsentState(1, BE_CHECKED); }); } export function testAsLoggedInUser() { it('should not render the banner and footer link', () => { cy.visit('/login'); login(userTransferConsentTest.email, userTransferConsentTest.password); checkBanner(); loggedInUserBannerTest(); loggedInUserFooterLinkTest(); signOutUser(); openAnonymousConsentsDialog(); checkInputConsentState(0, NOT_BE_CHECKED); checkInputConsentState(1, NOT_BE_CHECKED); checkInputConsentState(2, NOT_BE_CHECKED); }); } export function changeLanguageTest() { it('should pull the new consent templates but preserve the consents state', () => { clickViewDetailsFromBanner(); selectAllConsent(); openAnonymousConsentsDialog(); checkAllInputConsentState(BE_CHECKED); closeAnonymousConsentsDialog(); cy.intercept({ method: 'GET', query: { lang: LANGUAGE_DE, }, }).as('switchedContext'); cy.onMobile(() => { clickHamburger(); }); switchSiteContext(LANGUAGE_DE, LANGUAGE_LABEL); cy.wait('@switchedContext').its('response.statusCode').should('eq', 200); openAnonymousConsentsDialog(); checkAllInputConsentState(BE_CHECKED); }); } export function showAnonymousConfigTest() { it('should not display consents on the consents management page', () => { navigateToConsentPage(); checkConsentsInConsentPage(); signOutUser(); }); it('should not display the legal in the dialog', () => { clickViewDetailsFromBanner(); checkDialogDescription(); closeAnonymousConsentsDialog(); }); } export function anonymousConfigTestFlow() { it('should check new register consent and personalizing not visible in consent management page', () => { //first, check that marketing consent in the dialog is disabled openAnonymousConsentsDialog(); checkInputConsentState(0, BE_DISABLED); closeAnonymousConsentsDialog(); //then, register a user and check its consents registerUserAndCheckMyAccountConsent( userFromConfigTest, giveRegistrationConsentTest, secondCheckBoxPosition, personalizationConsentLabel ); checkInputConsentState(0, BE_DISABLED); checkInputConsentState(3, NOT_EXIST); }); } export function testAcceptAnonymousConsents() { it('should accept anonymous consents', () => { cy.visit('/'); cy.get(ANONYMOUS_BANNER).find('.btn-primary').click(); cy.get(ANONYMOUS_BANNER).should('not.be.visible'); cy.get('cx-anonymous-consent-open-dialog').within(() => { cy.get('button').click({ force: true }); }); cy.get('input[type="checkbox"]').each(($match) => { cy.wrap($match).should('be.checked'); }); cy.get(`${ANONYMOUS_DIALOG} .cx-action-link`) .first() .click({ force: true }); cy.get(ANONYMOUS_OPEN_DIALOG).within(() => { cy.get('button').click({ force: true }); }); cy.get('input[type="checkbox"]').each(($match) => { cy.wrap($match).should('not.be.checked'); }); }); }
the_stack
import type { Container } from "../../Core/Container"; import type { IContainerPlugin, ICoordinates, IDelta, IDimension } from "../../Core/Interfaces"; import { InlineArrangement, Type } from "./Enums"; import { Particle } from "../../Core/Particle"; import { Constants, deepExtend, getDistance, getDistances, itemFromArray } from "../../Utils"; import type { ISvgPath } from "./Interfaces/ISvgPath"; import type { RecursivePartial } from "../../Types"; import { PolygonMask } from "./Options/Classes/PolygonMask"; import { OutModeDirection } from "../../Enums"; import type { IPolygonMaskOptions } from "./types"; import { calcClosestPtOnSegment, drawPolygonMask, drawPolygonMaskPath, parsePaths, segmentBounce } from "./utils"; /** * Polygon Mask manager * @category Polygon Mask Plugin */ export class PolygonMaskInstance implements IContainerPlugin { redrawTimeout?: number; raw?: ICoordinates[]; paths?: ISvgPath[]; dimension: IDimension; offset?: ICoordinates; readonly path2DSupported; readonly options; private polygonMaskMoveRadius; constructor(private readonly container: Container) { this.dimension = { height: 0, width: 0, }; this.path2DSupported = !!window.Path2D; this.options = new PolygonMask(); this.polygonMaskMoveRadius = this.options.move.radius * container.retina.pixelRatio; } async initAsync(options?: RecursivePartial<IPolygonMaskOptions>): Promise<void> { this.options.load(options?.polygon); const polygonMaskOptions = this.options; this.polygonMaskMoveRadius = polygonMaskOptions.move.radius * this.container.retina.pixelRatio; /* If is set the url of svg element, load it and parse into raw polygon data */ if (polygonMaskOptions.enable) { await this.initRawData(); } } resize(): void { const container = this.container; const options = this.options; if (!(options.enable && options.type !== Type.none)) { return; } if (this.redrawTimeout) { clearTimeout(this.redrawTimeout); } this.redrawTimeout = window.setTimeout(async () => { await this.initRawData(true); container.particles.redraw(); }, 250); } stop(): void { delete this.raw; delete this.paths; } particlesInitialization(): boolean { const options = this.options; if ( options.enable && options.type === Type.inline && (options.inline.arrangement === InlineArrangement.onePerPoint || options.inline.arrangement === InlineArrangement.perPoint) ) { this.drawPoints(); return true; } return false; } particlePosition(position?: ICoordinates): ICoordinates | undefined { const options = this.options; if (!(options.enable && (this.raw?.length ?? 0) > 0)) { return; } return deepExtend({}, position ? position : this.randomPoint()) as ICoordinates; } particleBounce(particle: Particle, delta: IDelta, direction: OutModeDirection): boolean { return this.polygonBounce(particle, delta, direction); } clickPositionValid(position: ICoordinates): boolean { const options = this.options; return ( options.enable && options.type !== Type.none && options.type !== Type.inline && this.checkInsidePolygon(position) ); } draw(context: CanvasRenderingContext2D): void { if (!this.paths?.length) { return; } const options = this.options; const polygonDraw = options.draw; if (!(options.enable && polygonDraw.enable)) { return; } const rawData = this.raw; for (const path of this.paths) { const path2d = path.path2d; const path2dSupported = this.path2DSupported; if (!context) { continue; } if (path2dSupported && path2d && this.offset) { drawPolygonMaskPath(context, path2d, polygonDraw.stroke, this.offset); } else if (rawData) { drawPolygonMask(context, rawData, polygonDraw.stroke); } } } private polygonBounce(particle: Particle, _delta: IDelta, direction: OutModeDirection): boolean { const options = this.options; if (!this.raw || !options.enable || direction !== OutModeDirection.top) { return false; } if (options.type === Type.inside || options.type === Type.outside) { let closest: ICoordinates | undefined, dx: number | undefined, dy: number | undefined; const pos = particle.getPosition(), radius = particle.getRadius(); for (let i = 0, j = this.raw.length - 1; i < this.raw.length; j = i++) { const pi = this.raw[i], pj = this.raw[j]; closest = calcClosestPtOnSegment(pi, pj, pos); const dist = getDistances(pos, closest); [dx, dy] = [dist.dx, dist.dy]; if (dist.distance < radius) { segmentBounce(pi, pj, particle.velocity); return true; } } if (closest && dx !== undefined && dy !== undefined && !this.checkInsidePolygon(pos)) { const factor = { x: 1, y: 1 }; if (particle.position.x >= closest.x) { factor.x = -1; } if (particle.position.y >= closest.y) { factor.y = -1; } particle.position.x = closest.x + radius * 2 * factor.x; particle.position.y = closest.y + radius * 2 * factor.y; particle.velocity.mult(-1); return true; } } else if (options.type === Type.inline && particle.initialPosition) { const dist = getDistance(particle.initialPosition, particle.getPosition()); if (dist > this.polygonMaskMoveRadius) { particle.velocity.x = particle.velocity.y / 2 - particle.velocity.x; particle.velocity.y = particle.velocity.x / 2 - particle.velocity.y; return true; } } return false; } private checkInsidePolygon(position?: ICoordinates): boolean { const container = this.container; const options = this.options; if (!options.enable || options.type === Type.none || options.type === Type.inline) { return true; } // https://github.com/substack/point-in-polygon // ray-casting algorithm based on // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html if (!this.raw) { throw new Error(Constants.noPolygonFound); } const canvasSize = container.canvas.size; const x = position?.x ?? Math.random() * canvasSize.width; const y = position?.y ?? Math.random() * canvasSize.height; let inside = false; // if (this.path2DSupported && this.polygonPath && position) { // inside = container.canvas.isPointInPath(this.polygonPath, position); // } else { for (let i = 0, j = this.raw.length - 1; i < this.raw.length; j = i++) { const pi = this.raw[i]; const pj = this.raw[j]; const intersect = pi.y > y !== pj.y > y && x < ((pj.x - pi.x) * (y - pi.y)) / (pj.y - pi.y) + pi.x; if (intersect) { inside = !inside; } } // } return options.type === Type.inside ? inside : options.type === Type.outside ? !inside : false; } private parseSvgPath(xml: string, force?: boolean): ICoordinates[] | undefined { const forceDownload = force ?? false; if (this.paths !== undefined && !forceDownload) { return this.raw; } const container = this.container; const options = this.options; const parser = new DOMParser(); const doc = parser.parseFromString(xml, "image/svg+xml"); const svg = doc.getElementsByTagName("svg")[0]; let svgPaths = svg.getElementsByTagName("path"); if (!svgPaths.length) { svgPaths = doc.getElementsByTagName("path"); } this.paths = []; for (let i = 0; i < svgPaths.length; i++) { const path = svgPaths.item(i); if (path) { this.paths.push({ element: path, length: path.getTotalLength(), }); } } const pxRatio = container.retina.pixelRatio; const scale = options.scale / pxRatio; this.dimension.width = parseFloat(svg.getAttribute("width") ?? "0") * scale; this.dimension.height = parseFloat(svg.getAttribute("height") ?? "0") * scale; const position = options.position ?? { x: 50, y: 50, }; /* centering of the polygon mask */ this.offset = { x: (container.canvas.size.width * position.x) / (100 * pxRatio) - this.dimension.width / 2, y: (container.canvas.size.height * position.y) / (100 * pxRatio) - this.dimension.height / 2, }; return parsePaths(this.paths, scale, this.offset); } /** * Deprecate SVGPathElement.getPathSegAtLength removed in: * Chrome for desktop release 62 * Chrome for Android release 62 * Android WebView release 62 * Opera release 49 * Opera for Android release 49 */ private async downloadSvgPath(svgUrl?: string, force?: boolean): Promise<ICoordinates[] | undefined> { const options = this.options; const url = svgUrl || options.url; const forceDownload = force ?? false; // Load SVG from file on server if (!url || (this.paths !== undefined && !forceDownload)) { return this.raw; } const req = await fetch(url); if (!req.ok) { throw new Error("tsParticles Error - Error occurred during polygon mask download"); } return this.parseSvgPath(await req.text(), force); } private drawPoints(): void { if (!this.raw) { return; } for (const item of this.raw) { this.container.particles.addParticle({ x: item.x, y: item.y, }); } } private randomPoint(): ICoordinates { const container = this.container; const options = this.options; let position: ICoordinates; if (options.type === Type.inline) { switch (options.inline.arrangement) { case InlineArrangement.randomPoint: position = this.getRandomPoint(); break; case InlineArrangement.randomLength: position = this.getRandomPointByLength(); break; case InlineArrangement.equidistant: position = this.getEquidistantPointByIndex(container.particles.count); break; case InlineArrangement.onePerPoint: case InlineArrangement.perPoint: default: position = this.getPointByIndex(container.particles.count); } } else { position = { x: Math.random() * container.canvas.size.width, y: Math.random() * container.canvas.size.height, }; } if (this.checkInsidePolygon(position)) { return position; } else { return this.randomPoint(); } } private getRandomPoint(): ICoordinates { if (!this.raw || !this.raw.length) { throw new Error(Constants.noPolygonDataLoaded); } const coords = itemFromArray(this.raw); return { x: coords.x, y: coords.y, }; } private getRandomPointByLength(): ICoordinates { const options = this.options; if (!this.raw || !this.raw.length || !this.paths?.length) { throw new Error(Constants.noPolygonDataLoaded); } const path = itemFromArray(this.paths); const distance = Math.floor(Math.random() * path.length) + 1; const point = path.element.getPointAtLength(distance); return { x: point.x * options.scale + (this.offset?.x || 0), y: point.y * options.scale + (this.offset?.y || 0), }; } private getEquidistantPointByIndex(index: number): ICoordinates { const options = this.container.actualOptions; const polygonMaskOptions = this.options; if (!this.raw || !this.raw.length || !this.paths?.length) throw new Error(Constants.noPolygonDataLoaded); let offset = 0; let point: DOMPoint | undefined; const totalLength = this.paths.reduce((tot: number, path: ISvgPath) => tot + path.length, 0); const distance = totalLength / options.particles.number.value; for (const path of this.paths) { const pathDistance = distance * index - offset; if (pathDistance <= path.length) { point = path.element.getPointAtLength(pathDistance); break; } else { offset += path.length; } } return { x: (point?.x ?? 0) * polygonMaskOptions.scale + (this.offset?.x ?? 0), y: (point?.y ?? 0) * polygonMaskOptions.scale + (this.offset?.y ?? 0), }; } private getPointByIndex(index: number): ICoordinates { if (!this.raw || !this.raw.length) { throw new Error(Constants.noPolygonDataLoaded); } const coords = this.raw[index % this.raw.length]; return { x: coords.x, y: coords.y, }; } private createPath2D(): void { const options = this.options; if (!this.path2DSupported || !this.paths?.length) { return; } for (const path of this.paths) { const pathData = path.element?.getAttribute("d"); if (pathData) { const path2d = new Path2D(pathData); const matrix = document.createElementNS("http://www.w3.org/2000/svg", "svg").createSVGMatrix(); const finalPath = new Path2D(); const transform = matrix.scale(options.scale); if (finalPath.addPath) { finalPath.addPath(path2d, transform); path.path2d = finalPath; } else { delete path.path2d; } } else { delete path.path2d; } if (path.path2d || !this.raw) { continue; } path.path2d = new Path2D(); path.path2d.moveTo(this.raw[0].x, this.raw[0].y); this.raw.forEach((pos, i) => { if (i > 0) { path.path2d?.lineTo(pos.x, pos.y); } }); path.path2d.closePath(); } } private async initRawData(force?: boolean): Promise<void> { const options = this.options; if (options.url) { this.raw = await this.downloadSvgPath(options.url, force); } else if (options.data) { const data = options.data; let svg: string; if (typeof data !== "string") { const path = data.path instanceof Array ? data.path.map((t) => `<path d="${t}" />`).join("") : `<path d="${data.path}" />`; const namespaces = 'xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"'; svg = `<svg ${namespaces} width="${data.size.width}" height="${data.size.height}">${path}</svg>`; } else { svg = data; } this.raw = this.parseSvgPath(svg, force); } this.createPath2D(); } }
the_stack
import * as assert from "assert"; import { createHash } from "crypto"; import { PersistentCache } from "./cache"; import { FaastError, FaastErrorNames } from "./error"; import { deserialize, serialize } from "./serialize"; import { sleep } from "./shared"; export class Deferred<T = void> { promise: Promise<T>; resolve!: (arg: T | PromiseLike<T>) => void; reject!: (err?: any) => void; constructor() { this.promise = new Promise<T>((resolve, reject) => { this.resolve = resolve; this.reject = reject; }); } } export class DeferredWorker<T = void> extends Deferred<T> { constructor( private worker: () => Promise<T>, private cancel?: () => string | undefined ) { super(); } async execute() { const cancelMessage = this.cancel?.(); if (cancelMessage) { this.reject(new FaastError({ name: FaastErrorNames.ECANCEL }, cancelMessage)); } else { try { const rv = await this.worker(); this.resolve(rv); } catch (err) { this.reject(err); } } } } function popFirst<T>(set: Set<T>): T | undefined { let firstElem: T | undefined; for (const elem of set) { firstElem = elem; break; } if (firstElem) { set.delete(firstElem); } return firstElem; } export type RetryType = number | ((err: any, retries: number) => boolean); export async function retryOp<T>(retryN: RetryType, fn: (retries: number) => Promise<T>) { const retryTest = typeof retryN === "function" ? retryN : (_: any, i: number) => i < retryN; for (let i = 0; true; i++) { try { return await fn(i); } catch (err) { if (!retryTest(err, i)) { throw err; } await sleep( Math.min(30 * 1000, 1000 * (1 + Math.random()) * 2 ** i) + Math.random() ); } } } export class Funnel<T = void> { protected pendingQueue: Set<DeferredWorker<T>> = new Set(); protected executingQueue: Set<DeferredWorker<T>> = new Set(); public processed = 0; public errors = 0; constructor(public concurrency: number = 0, protected shouldRetry?: RetryType) {} push( worker: () => Promise<T>, shouldRetry?: RetryType, cancel?: () => string | undefined ) { const retryTest = shouldRetry || this.shouldRetry || 0; const retryWorker = () => retryOp(retryTest, worker); const future = new DeferredWorker(retryWorker, cancel); this.pendingQueue.add(future); setImmediate(() => this.doWork()); return future.promise; } clear() { this.pendingQueue.clear(); this.executingQueue.clear(); } promises() { return [...this.executingQueue, ...this.pendingQueue].map(p => p.promise); } all() { return Promise.all(this.promises().map(p => p.catch(_ => {}))); } size() { return this.pendingQueue.size + this.executingQueue.size; } setMaxConcurrency(maxConcurrency: number) { this.concurrency = maxConcurrency; } getConcurrency() { return this.executingQueue.size; } protected doWork() { const { pendingQueue } = this; while ( pendingQueue.size > 0 && (!this.concurrency || this.executingQueue.size < this.concurrency) ) { const worker = popFirst(pendingQueue)!; this.executingQueue.add(worker); worker.promise .then(_ => this.processed++) .catch(_ => this.errors++) .then(_ => { this.executingQueue.delete(worker); this.doWork(); }); worker.execute(); } } } /** * @internal */ export interface PumpOptions { concurrency: number; verbose?: boolean; } /** * @internal */ export class Pump<T = void> extends Funnel<T | void> { stopped: boolean = false; constructor(protected options: PumpOptions, protected worker: () => Promise<T>) { super(options.concurrency); options.verbose = options.verbose ?? true; } start() { const restart = () => { if (this.stopped) { return; } while (this.executingQueue.size + this.pendingQueue.size < this.concurrency) { this.push(async () => { try { return await this.worker(); } catch (err) { this.options.verbose && console.error(err); return; } finally { setImmediate(restart); } }); } }; this.stopped = false; restart(); } stop() { this.stopped = true; } drain() { this.stop(); return this.all(); } setMaxConcurrency(concurrency: number) { super.setMaxConcurrency(concurrency); if (!this.stopped) { this.start(); } } } export class RateLimiter<T = void> { protected lastTick = 0; protected bucket = 0; protected queue: Set<DeferredWorker<T>> = new Set(); constructor(protected targetRequestsPerSecond: number, protected burst: number = 1) { assert(targetRequestsPerSecond > 0); assert(this.burst >= 1); } push(worker: () => Promise<T>, cancel?: () => string | undefined) { this.updateBucket(); if (this.queue.size === 0 && this.bucket <= this.burst - 1) { this.bucket++; return worker(); } const future = new DeferredWorker(worker, cancel); this.queue.add(future); if (this.queue.size === 1) { this.drainQueue(); } return future.promise; } protected updateBucket() { const now = Date.now(); const secondsElapsed = (now - this.lastTick) / 1000; this.bucket -= secondsElapsed * this.targetRequestsPerSecond; this.bucket = Math.max(this.bucket, 0); this.lastTick = now; } protected async drainQueue() { const requestAmountToDrain = 1 - (this.burst - this.bucket); const secondsToDrain = requestAmountToDrain / this.targetRequestsPerSecond; if (secondsToDrain > 0) { await sleep(Math.ceil(secondsToDrain * 1000)); } this.updateBucket(); while (this.bucket <= this.burst - 1) { const next = popFirst(this.queue); if (!next) { break; } this.bucket++; next.execute(); } if (this.queue.size > 0) { this.drainQueue(); } } clear() { this.queue.clear(); } } /** * Specify {@link throttle} limits. These limits shape the way throttle invokes * the underlying function. * @public */ export interface Limits { /** * The maximum number of concurrent executions of the underlying function to * allow. Must be supplied, there is no default. Specifying `0` or * `Infinity` is allowed and means there is no concurrency limit. */ concurrency: number; /** * The maximum number of calls per second to allow to the underlying * function. Default: no rate limit. */ rate?: number; /** * The maximum number of calls to the underlying function to "burst" -- e.g. * the number that can be issued immediately as long as the rate limit is * not exceeded. For example, if rate is 5 and burst is 5, and 10 calls are * made to the throttled function, 5 calls are made immediately and then * after 1 second, another 5 calls are made immediately. Setting burst to 1 * means calls are issued uniformly every `1/rate` seconds. If `rate` is not * specified, then `burst` does not apply. Default: 1. */ burst?: number; /** * Retry if the throttled function returns a rejected promise. `retry` can * be a number or a function. If it is a number `N`, then up to `N` * additional attempts are made in addition to the initial call. If retry is * a function, it should return `true` if another retry attempt should be * made, otherwise `false`. The first argument will be the value of the * rejected promise from the previous call attempt, and the second argument * will be the number of previous retry attempts (e.g. the first call will * have value 0). Default: 0 (no retry attempts). */ retry?: number | ((err: any, retries: number) => boolean); /** * If `memoize` is `true`, then every call to the throttled function will be * saved as an entry in a map from arguments to return value. If same * arguments are seen again in a future call, the return value is retrieved * from the Map rather than calling the function again. This can be useful * for avoiding redundant calls that are expected to return the same results * given the same arguments. * * The arguments will be captured with `JSON.stringify`, therefore types * that do not stringify uniquely won't be distinguished from each other. * Care must be taken when specifying `memoize` to ensure avoid incorrect * results. */ memoize?: boolean; /** * Similar to `memoize` except the map from function arguments to results is * stored in a persistent cache on disk. This is useful to prevent redundant * calls to APIs which are expected to return the same results for the same * arguments, and which are likely to be called across many faast.js module * instantiations. This is used internally by faast.js for caching cloud * prices for AWS and Google, and for saving the last garbage collection * date for AWS. Persistent cache entries expire after a period of time. See * {@link PersistentCache}. */ cache?: PersistentCache; /** * A promise that, if resolved, causes cancellation of pending throttled * invocations. This is typically created using `Deferred`. The idea is to * use the resolving of the promise as an asynchronous signal that any * pending invocations in this throttled function should be cleared. * @internal */ cancel?: Promise<void>; } export function memoizeFn<A extends any[], R>( fn: (...args: A) => R, cache: Map<string, R> = new Map() ) { return (...args: A) => { const key = JSON.stringify(args); const prev = cache.get(key); if (prev) { return prev; } const value = fn(...args); cache.set(key, value); return value; }; } export function cacheFn<A extends any[], R>( cache: PersistentCache, fn: (...args: A) => Promise<R> ) { return async (...args: A) => { const key = serialize(args, true); const hasher = createHash("sha256"); hasher.update(key); const cacheKey = hasher.digest("hex"); const prev = await cache.get(cacheKey); if (prev) { const str = prev.toString(); if (str === "undefined") { return undefined; } return deserialize(str); } const value = await fn(...args); await cache.set(cacheKey, serialize(value, true)); return value; }; } /** * A decorator for rate limiting, concurrency limiting, retry, memoization, and * on-disk caching. See {@link Limits}. * @remarks * When programming against cloud services, databases, and other resources, it * is often necessary to control the rate of request issuance to avoid * overwhelming the service provider. In many cases the provider has built-in * safeguards against abuse, which automatically fail requests if they are * coming in too fast. Some systems don't have safeguards and precipitously * degrade their service level or fail outright when faced with excessive load. * * With faast.js it becomes very easy to (accidentally) generate requests from * thousands of cloud functions. The `throttle` function can help manage request * flow without resorting to setting up a separate service. This is in keeping * with faast.js' zero-ops philosophy. * * Usage is simple: * * ```typescript * async function operation() { ... } * const throttledOperation = throttle({ concurrency: 10, rate: 5 }, operation); * for(let i = 0; i < 100; i++) { * // at most 10 concurrent executions at a rate of 5 invocations per second. * throttledOperation(); * } * ``` * * Note that each invocation to `throttle` creates a separate function with a * separate limits. Therefore it is likely that you want to use `throttle` in a * global context, not within a dynamic context: * * ```typescript * async function operation() { ... } * for(let i = 0; i < 100; i++) { * // WRONG - each iteration creates a separate throttled function that's only called once. * const throttledOperation = throttle({ concurrency: 10, rate: 5 }, operation); * throttledOperation(); * } * ``` * * A better way to use throttle avoids creating a named `operation` function * altogether, ensuring it cannot be accidentally called without throttling: * * ```typescript * const operation = throttle({ concurrency: 10, rate: 5 }, async () => { * ... * }); * ``` * * Throttle supports functions with arguments automatically infers the correct * type for the returned function: * * ```typescript * // `operation` inferred to have type (str: string) => Promise<string> * const operation = throttle({ concurrency: 10, rate: 5 }, async (str: string) => { * return string; * }); * ``` * * In addition to limiting concurrency and invocation rate, `throttle` also * supports retrying failed invocations, memoizing calls, and on-disk caching. * See {@link Limits} for details. * * @param limits - see {@link Limits}. * @param fn - The function to throttle. It can take any arguments, but must * return a Promise (which includes `async` functions). * @returns Returns a throttled function with the same signature as the argument * `fn`. * @public */ export function throttle<A extends any[], R>( limits: Limits, fn: (...args: A) => Promise<R> ): (...args: A) => Promise<R> { const { concurrency, retry, rate, burst, memoize, cache, cancel } = limits; const funnel = new Funnel<R>(concurrency, retry); const cancellationQueue = [() => funnel.clear()]; let conditionedFunc: (...args: A) => Promise<R>; if (rate) { const rateLimiter = new RateLimiter<R>(rate, burst); cancellationQueue.push(() => rateLimiter.clear()); conditionedFunc = (...args: A) => funnel.push(() => rateLimiter.push(() => fn(...args))); } else { conditionedFunc = (...args: A) => funnel.push(() => fn(...args)); } if (cache) { conditionedFunc = cacheFn(cache, conditionedFunc); } if (memoize) { const mcache = new Map<string, Promise<R>>(); cancellationQueue.push(() => mcache.clear()); conditionedFunc = memoizeFn(conditionedFunc, mcache); } cancel?.then(() => cancellationQueue.forEach(cleanupFn => cleanupFn())); return conditionedFunc; } function iteratorResult<T>(value: T | Promise<T>) { return Promise.resolve(value).then(v => ({ done: false, value: v } as const)); } const done = Promise.resolve({ done: true, value: undefined } as const); export class AsyncQueue<T> { protected deferred: Array<Deferred<T>> = []; protected enqueued: Promise<T>[] = []; enqueue(value: T | Promise<T>) { if (this.deferred.length > 0) { const d = this.deferred.shift(); d!.resolve(value); } else { this.enqueued.push(Promise.resolve(value)); } } next(): Promise<T> { if (this.enqueued.length > 0) { return this.enqueued.shift()!; } const d = new Deferred<T>(); this.deferred.push(d); return d.promise; } clear() { this.deferred = []; this.enqueued = []; } } export class AsyncIterableQueue<T> extends AsyncQueue<IteratorResult<T>> { push(value: T | Promise<T>) { super.enqueue(iteratorResult(value)); } done() { super.enqueue(done); } [Symbol.asyncIterator]() { return this; } } export class AsyncOrderedQueue<T> { protected queue = new AsyncQueue<T>(); protected arrived: Map<number, Promise<T>> = new Map(); protected current = 0; push(value: T | Promise<T>, sequence: number) { this.enqueue(Promise.resolve(value), sequence); } pushImmediate(value: T | Promise<T>) { this.queue.enqueue(value); } enqueue(value: Promise<T>, sequence: number) { if (sequence < this.current) { return; } if (!this.arrived.has(sequence)) { this.arrived.set(sequence, value); } while (this.arrived.has(this.current)) { this.queue.enqueue(this.arrived.get(this.current)!); this.arrived.delete(this.current); this.current++; } } next(): Promise<T> { return this.queue.next(); } clear() { this.arrived.clear(); this.queue.clear(); this.current = 0; } }
the_stack
import 'phaser'; import variables from '~/variables'; import StateData from '~/data/stateData'; import Phaser from 'phaser'; import GoldEntry from '~/data/goldEntry'; import WindowUtils from '~/convert/windowUtils'; import OverlayConfigEvent, { ObjectiveSpawnConfig, OverlayConfig, ScoreboardPopUpConfig } from '~/data/config/overlayConfig'; import { VisualElement } from '~/visual/VisualElement'; import RegionMask from '~/data/RegionMask'; import ItemVisual from '~/visual/ItemVisual'; import LevelUpVisual from '~/visual/LevelUpVisual'; import InhibitorVisual from '~/visual/InhibitorVisual'; import ObjectiveTimerVisual from '~/visual/ObjectiveTimerVisual'; import ScoreboardVisual from '~/visual/ScoreboardVisual'; import InfoPageVisual from '~/visual/InfoPageVisual'; import GraphVisual from '~/visual/GraphVisual'; import ObjectivePopUpVisual from '~/visual/ObjectivePopUpVisual'; export default class IngameScene extends Phaser.Scene { [x: string]: any; ws!: WebSocket; displayRegions: RegionMask[]; loadedFonts: string[]; baronTimer!: ObjectiveTimerVisual; elderTimer!: ObjectiveTimerVisual; inhib!: InhibitorVisual; score!: ScoreboardVisual; info!: InfoPageVisual; centerGraph!: GraphVisual; state!: StateData | null; overlayCfg!: OverlayConfig | null; graphics!: Phaser.GameObjects.Graphics; currentVisualElements: VisualElement[] = []; visualIDs: number = 0; static Instance: IngameScene; constructor() { super('ingameOverlay'); IngameScene.Instance = this; this.displayRegions = []; this.loadedFonts = []; } preload() { variables.backendUrl = WindowUtils.GetQueryVariable('backend'); this.graphics = this.add.graphics(); this.load.script('chartjs', 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.min.js'); //Masks this.load.image('champCoverLeft', 'frontend/masks/ChampCoverLeft.png'); this.load.image('champCoverRight', 'frontend/masks/ChampCoverRight.png'); this.load.image('scoreboardMask', 'frontend/masks/ScoreboardMask.png'); this.load.image('itemTextMaskLeft', 'frontend/masks/ItemTextLeft.png'); this.load.image('itemTextMaskRight', 'frontend/masks/ItemTextRight.png'); this.load.image('infoPageMask', 'frontend/masks/InfoPage.png'); this.load.image('graphMask', 'frontend/Masks/Graph.png'); this.load.image('popUpMask', 'frontend/Masks/PopUpMask.png') //Objective Timers this.load.image('baronIcon', 'frontend/backgrounds/BaronIcon.png'); this.load.image('objectiveBg', 'frontend/backgrounds/ObjectiveBG.png'); this.load.image('elderIcon', 'frontend/backgrounds/DragonIcon.png'); this.load.image('objectiveBgLeft', 'frontend/backgrounds/ObjectiveBGLeft.png'); this.load.image('objectiveGold', 'frontend/images/ObjectiveGold.png'); this.load.image('objectiveCdr', 'frontend/images/ObjectiveCdr.png'); //Scoreboard this.load.image('scoreGold', 'frontend/images/ScoreboardGold.png'); this.load.image('scoreTower', 'frontend/images/tower.png'); this.load.image('scoreCenter', 'frontend/images/ScoreboardCenterIcon.png'); this.load.image('scoreBlueIcon', 'frontend/backgrounds/ScoreTeamIconBGLeft.png'); this.load.image('scoreRedIcon', 'frontend/backgrounds/ScoreTeamIconBGRight.png'); //Info Tab this.load.image('infoPageSeparator', 'frontend/images/InfoTabSeparator.png'); //Dragons this.load.image('dragon_Fire', 'frontend/images/dragons/fireLarge.png'); this.load.image('dragon_Mountain', 'frontend/images/dragons/mountainLarge.png'); this.load.image('dragon_Cloud', 'frontend/images/dragons/cloudLarge.png'); this.load.image('dragon_Ocean', 'frontend/images/dragons/oceanLarge.png'); this.load.image('dragon_Elder', 'frontend/images/dragons/elderLarge.png'); this.load.image('dragon_Hextech', 'frontend/images/dragons/hextechLarge.png'); this.load.image('dragon_Chemtech', 'frontend/images/dragons/chemtechLarge.png'); //Inhibitor this.load.svg('top', 'frontend/images/lanes/top.svg'); this.load.svg('mid', 'frontend/images/lanes/mid.svg'); this.load.svg('bot', 'frontend/images/lanes/bot.svg'); //Item this.load.image('itemTextBg', 'frontend/backgrounds/ItemText.png'); } create() { var div = document.getElementById('gameContainer'); const blue_1 = this.make.sprite({ x: 39, y: 152 + 37, key: 'champCoverLeft', add: false }).createBitmapMask(); const playerNotificationMaskSprite = this.make.sprite({ x: 78, y: 152 + 37, key: 'itemTextMaskLeft', add: false }); playerNotificationMaskSprite.setOrigin(0, 0.5); var playerNotificationWidth = playerNotificationMaskSprite.width / 2; const blue_1_notif = playerNotificationMaskSprite.createBitmapMask(); const blue_2 = this.make.sprite({ x: 39, y: 255 + 37, key: 'champCoverLeft', add: false }).createBitmapMask(); const blue_2_notif = this.make.sprite({ x: 78 + playerNotificationWidth, y: 255 + 37, key: 'itemTextMaskLeft', add: false }).createBitmapMask(); const blue_3 = this.make.sprite({ x: 39, y: 358 + 37, key: 'champCoverLeft', add: false }).createBitmapMask(); const blue_3_notif = this.make.sprite({ x: 78 + playerNotificationWidth, y: 358 + 37, key: 'itemTextMaskLeft', add: false }).createBitmapMask(); const blue_4 = this.make.sprite({ x: 39, y: 461 + 37, key: 'champCoverLeft', add: false }).createBitmapMask(); const blue_4_notif = this.make.sprite({ x: 78 + playerNotificationWidth, y: 461 + 37, key: 'itemTextMaskLeft', add: false }).createBitmapMask(); const blue_5 = this.make.sprite({ x: 39, y: 564 + 37, key: 'champCoverLeft', add: false }).createBitmapMask(); const blue_5_notif = this.make.sprite({ x: 78 + playerNotificationWidth, y: 564 + 37, key: 'itemTextMaskLeft', add: false }).createBitmapMask(); const red_1 = this.make.sprite({ x: 1920 - 39, y: 152 + 37, key: 'champCoverRight', add: false }).createBitmapMask(); const red_1_notif = this.make.sprite({ x: 1920 - 78 - playerNotificationWidth, y: 152 + 37, key: 'itemTextMaskRight', add: false }).createBitmapMask(); const red_2 = this.make.sprite({ x: 1920 - 39, y: 255 + 37, key: 'champCoverRight', add: false }).createBitmapMask(); const red_2_notif = this.make.sprite({ x: 1920 - 78 - playerNotificationWidth, y: 255 + 37, key: 'itemTextMaskRight', add: false }).createBitmapMask(); const red_3 = this.make.sprite({ x: 1920 - 39, y: 358 + 37, key: 'champCoverRight', add: false }).createBitmapMask(); const red_3_notif = this.make.sprite({ x: 1920 - 78 - playerNotificationWidth, y: 358 + 37, key: 'itemTextMaskRight', add: false }).createBitmapMask(); const red_4 = this.make.sprite({ x: 1920 - 39, y: 461 + 37, key: 'champCoverRight', add: false }).createBitmapMask(); const red_4_notif = this.make.sprite({ x: 1920 - 78 - playerNotificationWidth, y: 461 + 37, key: 'itemTextMaskRight', add: false }).createBitmapMask(); const red_5 = this.make.sprite({ x: 1920 - 39, y: 564 + 37, key: 'champCoverRight', add: false }).createBitmapMask(); const red_5_notif = this.make.sprite({ x: 1920 - 78 - playerNotificationWidth, y: 564 + 37, key: 'itemTextMaskRight', add: false }).createBitmapMask(); this.displayRegions = [ new RegionMask(0, [blue_1, blue_1_notif]), new RegionMask(1, [blue_2, blue_2_notif]), new RegionMask(2, [blue_3, blue_3_notif]), new RegionMask(3, [blue_4, blue_4_notif]), new RegionMask(4, [blue_5, blue_5_notif]), new RegionMask(5, [red_1, red_1_notif]), new RegionMask(6, [red_2, red_2_notif]), new RegionMask(7, [red_3, red_3_notif]), new RegionMask(8, [red_4, red_4_notif]), new RegionMask(9, [red_5, red_5_notif]), new RegionMask(10, []) ]; this.overlayCfg = null; const connect = () => { this.ws = new WebSocket(`${variables.useSSL ? 'wss' : 'ws'}://${variables.backendUrl}:${variables.backendPort}/${variables.backendWsLoc}`); this.ws.onopen = () => { console.log('[LB] Connection established!'); setTimeout(() => { console.log('[LB] Requesting overlay config'); this.ws.send('\{"requestType": "OverlayConfig","OverlayType": "Ingame"\}') }, 1000); }; this.ws.onclose = () => { setTimeout(connect, 500); this.score?.Stop(); this.inhib?.Stop(); this.baronTimer?.Stop(); this.elderTimer?.Stop(); this.info?.Stop(); this.centerGraph?.Stop(); this.centerGraph?.Stop(); console.log('[LB] Attempt reconnect in 500ms'); }; this.ws.onerror = () => { console.log('[LB] Connection error!'); }; this.ws.onmessage = msg => { const data = JSON.parse(msg.data); if (data.eventType) { switch (data.eventType) { case 'GameHeartbeat': OnNewState(data.stateData); break; case 'OverlayConfig': if (data.type !== 1) break; this.UpdateConfigWhenReady(data); break; case 'PlayerLevelUp': if (this.info.isActive && data.playerId < 5) break; new LevelUpVisual(this, data.playerId, data.level); break; case 'ObjectiveKilled': this.OnObjectiveKill(data.ObjectiveName, data.TeamName); break; case 'BuffDespawn': console.log('Legacy objective despawn: ' + JSON.stringify(data)); break; case 'ObjectiveSpawn': this.OnObjectiveSpawn(data.ObjectiveName); break; case 'ItemCompleted': if (this.info.isActive && data.playerId < 5) break; new ItemVisual(this, data.itemData, data.playerId); break; case 'GameEnd': console.log('Game Ended'); this.state = null; this.baronTimer?.Stop(); this.elderTimer?.Stop(); this.centerGraph?.Stop(); this.inhib?.Stop(); this.score?.Stop(); this.info?.Stop(); break; case 'GameStart': console.log('Game Start'); break; case 'GamePause': break; case 'GameUnpause': break; case 'ForceRefresh': window.location.reload(); //Ignore pick/ban events case 'newState': case 'newAction': case 'heartbeat': case 'champSelectStart': case 'champSelectEnd': break; default: console.log('[LB] Unknown event type: ' + JSON.stringify(data)); break; } } else { console.log('[LB] Unexpected packet format: ' + JSON.stringify(data)); } }; }; const OnNewState = (data: any): void => { //Dont show anything if overlay has not been configured yet if (this.overlayCfg === null) return; var newState = new StateData(data); if (this.state === undefined) this.state = newState; this.inhib.UpdateValues(newState.inhibitors); this.score.UpdateValues(newState); this.baronTimer.UpdateValues(newState.baron); this.elderTimer.UpdateValues(newState.dragon); this.info.UpdateValues(newState.infoPage); this.centerGraph.UpdateValues(newState.goldGraph); this.CheckSoulPoint(newState); this.state = newState; } connect(); } GetBlueColor = (state: StateData = this.state!): string => { let color = GetRGBAString(Phaser.Display.Color.IntegerToColor(variables.fallbackBlue), 1); if (state !== undefined && state.blueColor !== undefined && state.blueColor !== '') { color = state.blueColor; } return color; } GetRedColor = (state: StateData = this.state!): string => { let color = GetRGBAString(Phaser.Display.Color.IntegerToColor(variables.fallbackRed), 1); if (state !== undefined && state.redColor !== undefined && state.redColor !== '') { color = state.redColor; } return color; } UpdateConfig = (message: OverlayConfigEvent): void => { console.log('[LB] Configuring Visual Elements'); if (this.overlayCfg === null) { //Init Message, create Visual Elements this.overlayCfg = message.config; this.inhib = new InhibitorVisual(this); this.baronTimer = new ObjectiveTimerVisual(this, 'baron', message.config.BaronTimer); this.elderTimer = new ObjectiveTimerVisual(this, 'elder', message.config.ElderTimer); this.score = new ScoreboardVisual(this, message.config.Score); this.info = new InfoPageVisual(this, message.config.InfoPage); this.centerGraph = new GraphVisual(this, message.config.GoldGraph, [new GoldEntry(0, 100), new GoldEntry(40, -100)]); } else { //Update Message, update elements if needed this.inhib.UpdateConfig(message.config.Inhib); this.baronTimer.UpdateConfig(message.config.BaronTimer); this.elderTimer.UpdateConfig(message.config.ElderTimer); this.score.UpdateConfig(message.config.Score); this.info.UpdateConfig(message.config.InfoPage); this.centerGraph.UpdateConfig(message.config.GoldGraph); } console.log('[LB] Saving new display config'); this.overlayCfg = message.config; //console.log(message.config); } UpdateConfigWhenReady(message: OverlayConfigEvent): void { //Load new fonts let newFonts = message.config.GoogleFonts.filter(f => !this.loadedFonts.includes(f)); if (newFonts.length > 0) { this.load.rexWebFont({ google: { families: newFonts } }); console.log(`[LB] Loading ${newFonts.length} new fonts`); this.loadedFonts.push(...newFonts); this.load.start(); //Wait for loader to finish loading fonts this.load.once('complete', () => { console.log('[LB] Fonts loaded'); this.UpdateConfig(message); }); return; } this.UpdateConfig(message); } CheckSoulPoint(state: StateData): void { if (!this.overlayCfg?.ObjectiveKill.SoulPointScoreboardPopUp.Enabled) return; if (state.scoreboard.BlueTeam.Dragons.length === 3 && this.state?.scoreboard.BlueTeam.Dragons.length === 2) { console.log('Blue Soul Point'); new ObjectivePopUpVisual(this, this.overlayCfg!.ObjectiveKill.SoulPointScoreboardPopUp, `${state.scoreboard.BlueTeam.Dragons[2]}Soul`); } if (state.scoreboard.RedTeam.Dragons.length === 3 && this.state?.scoreboard.RedTeam.Dragons.length === 2) { console.log('Red Soul Point'); new ObjectivePopUpVisual(this, this.overlayCfg!.ObjectiveKill.SoulPointScoreboardPopUp, `${state.scoreboard.RedTeam.Dragons[2]}Soul`); } } OnObjectiveSpawn(objectiveName: string): void { let cfg: ScoreboardPopUpConfig | null = null; switch (objectiveName) { case 'Baron': cfg = this.overlayCfg!.ObjectiveSpawn.BaronSpawnScoreboardPopUp; break; case 'Herald': cfg = this.overlayCfg!.ObjectiveSpawn.HeraldSpawnScoreboardPopUp; break; default: cfg = this.overlayCfg!.ObjectiveSpawn.DrakeSpawnScoreboardPopUp; break; } console.log(`${objectiveName} spawned`); new ObjectivePopUpVisual(this, cfg, `${objectiveName.toLowerCase()}Spawn`); } OnObjectiveKill(objectiveName: string, teamName: string): void { let cfg: ScoreboardPopUpConfig | null = null; switch (objectiveName) { case 'Herald': cfg = this.overlayCfg!.ObjectiveKill.HeraldKillScoreboardPopUp; break; case 'Baron': cfg = this.overlayCfg!.ObjectiveKill.BaronKillScoreboardPopUp; break; case 'Elder': cfg = this.overlayCfg!.ObjectiveKill.ElderKillScoreboardPopUp; break; default: cfg = this.overlayCfg!.ObjectiveKill.DragonKillScoreboardPopUp; break; } console.log(`${objectiveName} killed`); new ObjectivePopUpVisual(this, cfg, `${objectiveName.toLowerCase()}Kill`); } } var GetRGBAString = function (color, alpha) { if (alpha === undefined) { alpha = color.alphaGL; } return 'rgba(' + color.red + ',' + color.green + ',' + color.blue + ',' + alpha + ')'; }
the_stack
const SPACING_UNIT = 5; const MEASUREMENT_UNIT = 'px'; /** * Do not use directly the colorPalette in your components * Create an entry in the colorUsage below instead */ const colorPalette = { primary500: '#3657FF', grey100: '#FAFAFA', grey200: '#F7F8FA', grey300: '#E9EBED', grey350: 'rgba(57, 63, 72, 0.3)', grey400: 'rgba(151, 151, 151, 0.80)', grey500: '#979797', grey800: '#4A4A4A', accentPurple200: '#F4BEF9', accentPurple500: '#8A0E95', accentGreen200: 'rgba(54,179,126,0.1)', accentGreen500: '#227251', accentYellow500: '#F7B500', white200: 'rgba(255,255,255,0.1)', white500: '#ffffff', lightGreen: '#3bafa3', auditSuccessGreen: '#0CCE6B', black100: 'rgba(0, 0, 0, 0.2)', black200: 'rgba(0, 0, 0, 0.5)', orange500: '#ffa400', orange200: '#ffe3b2', red500: '#B80009', red200: '#ffd2d2', auditFailRed: '#FF4E42', auditRunningOrange: '#ffa400', transparent: 'rgba(0,0,0,0)', }; /** * Use this dictionnary in your components * Define a new key each time you use a colour if it's for a different use * Ex: fill, border-color, background-color, color ... */ export const colorUsage = { // General h1Text: colorPalette.grey800, h2Text: colorPalette.grey800, h3Text: colorPalette.grey800, h4Text: colorPalette.grey800, introductionText: colorPalette.grey800, bodyText: colorPalette.grey800, labelText: colorPalette.grey800, quoteText: colorPalette.grey800, smallText: colorPalette.grey800, logoText: colorPalette.grey800, link: colorPalette.primary500, loader: colorPalette.primary500, defaultContentBackground: colorPalette.white500, // Popin popinErrorText: colorPalette.red500, popinErrorBackground: colorPalette.red200, popinInfoText: colorPalette.orange500, popinInfoBackground: colorPalette.orange200, // Button cancelButtonText: colorPalette.primary500, cancelButtonBorder: colorPalette.primary500, cancelButtonBackground: colorPalette.transparent, validateButtonText: colorPalette.white500, validateButtonBackground: colorPalette.primary500, submitButtonText: colorPalette.white500, submitButtonBackground: colorPalette.primary500, // Checkbox checkboxBorder: colorPalette.grey500, checkboxColor: colorPalette.primary500, checkboxBackground: colorPalette.white500, // Input inputText: colorPalette.grey800, inputTextPlaceholder: colorPalette.grey800, inputTextFocused: colorPalette.primary500, inputTextError: colorPalette.red500, inputTextLabel: colorPalette.grey800, inputTextBackground: colorPalette.transparent, inputSelectText: colorPalette.grey800, inputDisabledSelectText: colorPalette.grey500, inputSelectBorder: colorPalette.grey500, // Header headerLogo: colorPalette.primary500, headerFakeBackground: colorPalette.white500, headerShadowBox: colorPalette.grey350, headerButtonHoverText: colorPalette.primary500, accountMenuBackground: colorPalette.white500, accountMenuShadow: colorPalette.grey400, accountMenuText: colorPalette.grey800, accountMenuUserInfosBlockBorder: colorPalette.grey300, accountMenuActionItemHoverText: colorPalette.primary500, accountMenuNotification: colorPalette.red500, // Menu menuLink: colorPalette.grey800, menuBackground: colorPalette.grey200, menuArrow: colorPalette.grey800, menuArrowSelected: colorPalette.white500, menuLinkHover: colorPalette.primary500, menuLaunchAuditsButtonBackground: colorPalette.accentGreen500, menuLaunchAuditsButtonText: colorPalette.white500, // Root landingPageGlobalBackground: colorPalette.grey100, landingTheodoLink: colorPalette.primary500, landingImageShadowBox: colorPalette.black100, leadFormBorder: colorPalette.grey800, leadSubmitButtonBackground: colorPalette.accentGreen500, leadSubmitButtonWaitingBackground: colorPalette.grey800, leadSubmitButtonLoaderPrimary: colorPalette.white500, leadSubmitButtonLoaderSecondary: colorPalette.transparent, leadSubmitButtonSuccessBackground: colorPalette.accentGreen500, leadSubmitButtonSuccessCheck: colorPalette.white500, skipContentButtonColor: colorPalette.white500, skipContentButtonBackgroundColor: colorPalette.primary500, // Login Page connectButtonWaitingBackground: colorPalette.grey800, connectButtonLoaderPrimary: colorPalette.white500, connectButtonLoaderSecondary: colorPalette.transparent, loginInputBorder: colorPalette.grey800, // Audit auditLink: colorPalette.grey800, auditLinkBorder: colorPalette.grey300, auditLinkHoverText: colorPalette.primary500, auditLinkSelectedText: colorPalette.white500, auditLinkSelectedBackground: colorPalette.primary500, auditLinkSelectedBorder: colorPalette.grey500, // Graphs graphBorder: colorPalette.grey800, graphLine: colorPalette.primary500, graphTooltipCursor: colorPalette.lightGreen, graphTooltipBackground: colorPalette.grey300, graphTooltipShadowBox: colorPalette.black200, graphTooltipActiveDot: colorPalette.lightGreen, graphTooltipActiveDotBorder: colorPalette.white500, graphText: colorPalette.grey800, graphModalToggleButton: colorPalette.grey800, // Metrics metricsSettingsText: colorPalette.primary500, metricInformationIcon: colorPalette.primary500, metricTooltipBackground: colorPalette.grey300, metricTooltipShadowBox: colorPalette.black200, metricTooltipText: colorPalette.grey800, metricsModalBackground: colorPalette.grey200, metricsModalShadow: colorPalette.grey400, // Projects projectsMenuBackground: colorPalette.white500, projectsMenuShadow: colorPalette.grey400, projectsMenuItemText: colorPalette.grey800, projectsMenuItemHoverText: colorPalette.primary500, projectsMenuItemBackground: colorPalette.grey200, projectsMenuItemBorder: colorPalette.grey500, projectsMenuItemSnapshotBorder: colorPalette.grey800, projectsMenuItemStar: colorPalette.accentYellow500, // Project Settings projectSettingsContainerBorder: colorPalette.grey500, editableRowInputBorder: colorPalette.grey500, oddProjectMemberBackground: colorPalette.grey200, adminBadgeText: colorPalette.accentGreen500, adminBadgeBackground: colorPalette.accentGreen200, adminBadgeSelectedText: colorPalette.white500, adminBadgeSelectedBackground: colorPalette.white200, projectSettingsIconColor: colorPalette.grey800, createScriptButtonBackground: colorPalette.accentGreen500, createScriptButtonText: colorPalette.white500, scriptRowIcon: colorPalette.black200, // WebPageTest webPageTestLinkButtonBackground: colorPalette.primary500, webPageTestLinkButtonText: colorPalette.white500, webPageTestRadioButtonBorder: colorPalette.grey500, webPageTestRadioButtonColor: colorPalette.primary500, webPageTestRadioButtonBackground: colorPalette.white500, // Lighthouse lighthouseFail: colorPalette.auditFailRed, lighthouseFailSecondary: '#EB0F00', lighthouseAverage: colorPalette.auditRunningOrange, lighthouseAverageSecondary: '#D04900', lighthousePass: colorPalette.auditSuccessGreen, lighthousePassSecondary: '#018642', lighthouseLineColor: '#ebebeb', // Badge pageBadgeText: colorPalette.accentPurple500, pageBadgeBackground: colorPalette.accentPurple200, pageBadgeSelectedText: colorPalette.white500, pageBadgeSelectedBackground: colorPalette.white200, scriptBadgeText: colorPalette.accentGreen500, scriptBadgeBackground: colorPalette.accentGreen200, scriptBadgeSelectedText: colorPalette.white500, scriptBadgeSelectedBackground: colorPalette.white200, // AuditStatusHistoryIcon auditStatusHistoryIconSuccess: colorPalette.auditSuccessGreen, auditStatusHistoryIconPending: colorPalette.auditRunningOrange, auditStatusHistoryIconFailure: colorPalette.auditFailRed, // Not Found 404 notFoundButtonBackground: colorPalette.grey500, notFoundButtonText: colorPalette.white500, // ToggleButton ToggleButtonActiveBackground: colorPalette.accentGreen500, ToggleButtonDisabledBackground: colorPalette.grey500, ToggleButtonActiveLabelColor: colorPalette.accentGreen500, ToggleButtonDisabledLabelColor: colorPalette.grey500, }; export const fontFamily = { mainMono: `'IBM Plex Mono', monospace`, mainSans: `'IBM Plex Sans', sans-serif`, LighthouseMono: 'Roboto Mono, Menlo, dejavu sans mono, Consolas, Lucida Console, monospace', }; export const fontSize = { // General h1Text: '36px', h2Text: '30px', h3Text: '24px', h4Text: '20px', introductionText: '18px', labelText: '16px', bodyText: '14px', quoteText: '24px', smallText: '10px', logoText: '26px', link: '14px', button: '14px', inputText: '14px', inputTextPlaceholder: '14px', inputTextLabel: '12px', inputErrorMessage: '12px', inputSelectText: '14px', // Menu menuLink: '20px', menuLaunchAuditsButtonText: '14px', // Landing leadSubmitErrorMessage: '13px', // Audit auditLink: '20px', // Graphs graphText: '14px', // Metrics metricTooltip: '12px', // ProjectSettings createScriptButtonText: '14px', // WebPageTest webPageTestLink: '14px', // 404 notFoundButton: '14px', // Lighthouse lighthousePercentage: '38px', lighthouseGaugeLabel: '28px', lighthouseMetricsHeader: '16px', // Badge badgeText: '14px', }; export const lineHeight = { h1Text: '47px', h2Text: '39px', h3Text: '32px', h4Text: '27px', introductionText: '26px', bodyText: '20px', labelText: '20px', quoteText: '34px', smallText: '15px', link: '20px', logoText: '34px', button: '18px', inputText: '18px', inputTextPlaceholder: '16px', inputTextLabel: '16px', inputErrorMessage: '14px', inputSelectText: '18px', // Menu menuLink: '27px', menuLaunchAuditsButtonText: '18px', // Audits auditLink: '27px', // Graphs graphText: '14px', // Metrics metricTooltip: '16px', // ProjectSettings createScriptButtonText: '18px', // WebPageTest webPageTestLink: '18px', // 404 notFoundButton: '18px', // Lighthouse lighthousePercentage: '0', lighthouseGaugeLabel: '36px', // Badge badgeText: '18px', }; export const fontWeight = { h1Text: 'bold', h2Text: 'bold', h3Text: 'bold', h4Text: 'bold', labelText: '500', bodyText: '500', logoText: 'bold', linkText: 'bold', button: 'bold', inputErrorMessage: 'bold' as const, inputTextLabel: 'bold', // Header accountMenuActionItemHoverText: 'bold', // Menu menuLink: 'bold', menuLaunchAuditsButtonText: 'bold', // Landing landingTheodoLink: 'bold', // Audits auditLink: 'bold', // Graphs graphText: 'bold', // Metrics metricTooltip: '500', // WebPageTest webPageTestLink: 'bold', // 404 notFoundButton: 'bold', // Lighthouse lighthouseMetricsHeader: 'bold', // Badge badgeText: 'bold', }; export const fontStyle = { quoteText: 'italic', lighthouseNote: 'italic', inputErrorMessage: 'italic', }; export const zIndex: { [key: string]: number } = { modal: 3, header: 2, menu: 1, tooltip: 1, graphModalCloseButton: 1, metricModalCheckbox: 1, webPageTestRadioButton: 1, modalLoader: 4, }; export const getSpacing = (multiplier: number): string => `${multiplier * SPACING_UNIT}${MEASUREMENT_UNIT}`; export const responsiveThreshold = '460px'; export const modalSize = { big: '1375px', medium: '1000px', }; export const settingsContainerSize = '800px'; export const inheritVar = 'inherit';
the_stack
import { TEMPERATURE_MODULE_TYPE } from '@opentrons/shared-data' import { i18n } from '../../../localization' import { END_TERMINAL_ITEM_ID, PRESAVED_STEP_ID, START_TERMINAL_ITEM_ID, } from '../../../steplist/types' import { SINGLE_STEP_SELECTION_TYPE, MULTI_STEP_SELECTION_TYPE, TERMINAL_ITEM_SELECTION_TYPE, } from '../reducers' import { getHoveredStepLabware, getSelectedStepTitleInfo, getActiveItem, getMultiSelectLastSelected, _getSavedMultiSelectFieldValues, getMultiSelectFieldValues, getMultiSelectDisabledFields, getCountPerStepType, getBatchEditSelectedStepTypes, } from '../selectors' import { getMockMoveLiquidStep, getMockMixStep } from '../__fixtures__' import * as utils from '../../modules/utils' import { FormData } from '../../../form-types' function createArgsForStepId( stepId: string, stepArgs: any ): Record<string, Record<string, any>> { return { [stepId]: { stepArgs, }, } } const hoveredStepId = 'hoveredStepId' const labware = 'well plate' const mixCommand = 'mix' describe('getHoveredStepLabware', () => { let initialDeckState: any beforeEach(() => { initialDeckState = { labware: {}, pipettes: {}, modules: {}, } }) it('no labware is returned when no hovered step', () => { const stepArgs = { commandCreatorFnName: mixCommand, labware, } const argsByStepId = createArgsForStepId(hoveredStepId, stepArgs) const hoveredStep = null // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getHoveredStepLabware.resultFunc( argsByStepId, hoveredStep, initialDeckState ) expect(result).toEqual([]) }) it('no labware is returned when step is not found', () => { const stepArgs = { commandCreatorFnName: mixCommand, labware, } const argsByStepId = createArgsForStepId(hoveredStepId, stepArgs) const hoveredStep = 'another-step' // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getHoveredStepLabware.resultFunc( argsByStepId, hoveredStep, initialDeckState ) expect(result).toEqual([]) }) it('no labware is returned when no step arguments', () => { const stepArgs = null const argsByStepId = createArgsForStepId(hoveredStepId, stepArgs) // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getHoveredStepLabware.resultFunc( argsByStepId, hoveredStepId, initialDeckState ) expect(result).toEqual([]) }) ;['consolidate', 'distribute', 'transfer'].forEach(command => { it(`source and destination labware is returned when ${command}`, () => { const sourceLabware = 'test tube' const stepArgs = { commandCreatorFnName: command, destLabware: labware, sourceLabware, } const argsByStepId = createArgsForStepId(hoveredStepId, stepArgs) // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getHoveredStepLabware.resultFunc( argsByStepId, hoveredStepId, initialDeckState ) expect(result).toEqual([sourceLabware, labware]) }) }) it('labware is returned when command is mix', () => { const stepArgs = { commandCreatorFnName: mixCommand, labware, } const argsByStepId = createArgsForStepId(hoveredStepId, stepArgs) // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getHoveredStepLabware.resultFunc( argsByStepId, hoveredStepId, initialDeckState ) expect(result).toEqual([labware]) }) describe('modules', () => { const type = TEMPERATURE_MODULE_TYPE const setTempCommand = 'setTemperature' beforeEach(() => { initialDeckState = { labware: { def098: { slot: type, }, }, pipettes: {}, modules: { abc123: { id: 'abc123', type, model: 'someTempModel', slot: '1', moduleState: { type, status: 'TEMPERATURE_DEACTIVATED', targetTemperature: null, }, }, }, } }) it('labware on module is returned when module id exists', () => { // @ts-expect-error(sa, 2021-6-15): members of utils are readonly utils.getLabwareOnModule = jest.fn().mockReturnValue({ id: labware }) const stepArgs = { commandCreatorFnName: setTempCommand, module: type, } const argsByStepId = createArgsForStepId(hoveredStepId, stepArgs) // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getHoveredStepLabware.resultFunc( argsByStepId, hoveredStepId, initialDeckState ) expect(result).toEqual([labware]) }) it('no labware is returned when no labware on module', () => { // @ts-expect-error(sa, 2021-6-15): members of utils are readonly utils.getLabwareOnModule = jest.fn().mockReturnValue(null) const stepArgs = { commandCreatorFnName: setTempCommand, module: type, } const argsByStepId = createArgsForStepId(hoveredStepId, stepArgs) // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getHoveredStepLabware.resultFunc( argsByStepId, hoveredStepId, initialDeckState ) expect(result).toEqual([]) }) }) }) describe('getSelectedStepTitleInfo', () => { it('should return title info of the presaved form when the presaved terminal item is selected', () => { const unsavedForm = { stepName: 'The Step', stepType: 'transfer' } // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getSelectedStepTitleInfo.resultFunc( unsavedForm, {}, null, PRESAVED_STEP_ID ) expect(result).toEqual({ stepName: unsavedForm.stepName, stepType: unsavedForm.stepType, }) }) it('should return null when the start or end terminal item is selected', () => { const terminals = [START_TERMINAL_ITEM_ID, END_TERMINAL_ITEM_ID] terminals.forEach(terminalId => { const unsavedForm = { stepName: 'The Step', stepType: 'transfer' } // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getSelectedStepTitleInfo.resultFunc( unsavedForm, {}, null, PRESAVED_STEP_ID ) expect(result).toEqual({ stepName: unsavedForm.stepName, stepType: unsavedForm.stepType, }) }) }) it('should return title info of the saved step when a saved step is selected', () => { const savedForm = { stepName: 'The Step', stepType: 'transfer' } const stepId = 'selectedAndSavedStepId' // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getSelectedStepTitleInfo.resultFunc( null, { [stepId]: savedForm }, stepId, null ) expect(result).toEqual({ stepName: savedForm.stepName, stepType: savedForm.stepType, }) }) }) describe('getActiveItem', () => { const testCases = [ { title: 'should show what is hovered, if anything is hovered', selected: { selectionType: MULTI_STEP_SELECTION_TYPE, ids: ['notTheseSteps', 'nope'], }, hovered: { selectionType: SINGLE_STEP_SELECTION_TYPE, id: 'hoveredId', }, expected: { selectionType: SINGLE_STEP_SELECTION_TYPE, id: 'hoveredId', }, }, { title: 'should return null, if nothing is hovered and multi-select is selected', selected: { selectionType: MULTI_STEP_SELECTION_TYPE, ids: ['notTheseSteps', 'nope'], }, hovered: null, expected: null, }, { title: 'should show the single-selected step item, if nothing is hovered', selected: { selectionType: SINGLE_STEP_SELECTION_TYPE, id: 'singleStepId', }, hovered: null, expected: { selectionType: SINGLE_STEP_SELECTION_TYPE, id: 'singleStepId', }, }, { title: 'should show the single-selected terminal item, if nothing is hovered', selected: { selectionType: TERMINAL_ITEM_SELECTION_TYPE, id: 'someItem', }, hovered: null, expected: { selectionType: TERMINAL_ITEM_SELECTION_TYPE, id: 'someItem', }, }, ] testCases.forEach(({ title, selected, hovered, expected }) => { it(title, () => { // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getActiveItem.resultFunc(selected, hovered) expect(result).toEqual(expected) }) }) }) describe('getMultiSelectLastSelected', () => { it('should return null if the selected item is a single step', () => { // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getMultiSelectLastSelected.resultFunc({ selectionType: SINGLE_STEP_SELECTION_TYPE, id: 'foo', }) expect(result).toEqual(null) }) it('should return null if the selected item is a terminal item', () => { // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getMultiSelectLastSelected.resultFunc({ selectionType: TERMINAL_ITEM_SELECTION_TYPE, id: 'foo', }) expect(result).toEqual(null) }) it('should return the lastSelected step Id if the selected item is a multi-selection', () => { // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getMultiSelectLastSelected.resultFunc({ selectionType: MULTI_STEP_SELECTION_TYPE, ids: ['foo', 'spam', 'bar'], lastSelected: 'spam', }) expect(result).toEqual('spam') }) }) describe('_getSavedMultiSelectFieldValues', () => { let mockSavedStepForms: { another_move_liquid_step_id: Record<string, any> } let mockmultiSelectItemIds: string[] beforeEach(() => { mockSavedStepForms = { ...getMockMoveLiquidStep(), // just doing this so the ids are not the exact same another_move_liquid_step_id: { ...getMockMoveLiquidStep().move_liquid_step_id, }, } mockmultiSelectItemIds = [ 'move_liquid_step_id', 'another_move_liquid_step_id', ] }) afterEach(() => {}) it('should return null if any of the forms are an unhandled type', () => { const savedStepForms = { ...mockSavedStepForms, another_move_liquid_step_id: { ...mockSavedStepForms.another_move_liquid_step_id, stepType: 'someOtherThing', }, } expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type _getSavedMultiSelectFieldValues.resultFunc( savedStepForms, mockmultiSelectItemIds ) ).toBe(null) }) it('should return null if some forms are moveLiquid and others are mix', () => { const savedStepForms = { ...mockSavedStepForms, ...getMockMixStep(), } expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type _getSavedMultiSelectFieldValues.resultFunc(savedStepForms, [ 'move_liquid_step_id', 'mix_step_id', ]) ).toBe(null) }) describe('moveLiquid: when fields are NOT indeterminate', () => { it('should return the fields with the indeterminate boolean', () => { expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type _getSavedMultiSelectFieldValues.resultFunc( mockSavedStepForms, mockmultiSelectItemIds ) ).toEqual({ // aspirate settings aspirate_labware: { value: 'aspirate_labware_id', isIndeterminate: false, }, aspirate_wells: { isIndeterminate: true, }, aspirate_wells_grouped: { isIndeterminate: false, value: false, }, aspirate_flowRate: { value: null, isIndeterminate: false, }, aspirate_mmFromBottom: { value: 1, isIndeterminate: false, }, aspirate_wellOrder_first: { value: 't2b', isIndeterminate: false, }, aspirate_wellOrder_second: { value: 'l2r', isIndeterminate: false, }, preWetTip: { value: false, isIndeterminate: false, }, aspirate_mix_checkbox: { value: true, isIndeterminate: false, }, aspirate_mix_times: { value: '2', isIndeterminate: false, }, aspirate_mix_volume: { value: '5', isIndeterminate: false, }, aspirate_delay_checkbox: { value: true, isIndeterminate: false, }, aspirate_delay_seconds: { value: '2', isIndeterminate: false, }, aspirate_delay_mmFromBottom: { value: '1', isIndeterminate: false, }, aspirate_airGap_checkbox: { value: true, isIndeterminate: false, }, aspirate_airGap_volume: { value: '30', isIndeterminate: false, }, aspirate_touchTip_checkbox: { value: true, isIndeterminate: false, }, aspirate_touchTip_mmFromBottom: { value: 1, isIndeterminate: false, }, // dispense settings dispense_labware: { value: 'dispense_labware_id', isIndeterminate: false, }, dispense_flowRate: { value: null, isIndeterminate: false, }, dispense_mmFromBottom: { value: 0.5, isIndeterminate: false, }, dispense_wellOrder_first: { value: 't2b', isIndeterminate: false, }, dispense_wellOrder_second: { value: 'l2r', isIndeterminate: false, }, dispense_mix_checkbox: { value: true, isIndeterminate: false, }, dispense_mix_times: { value: null, isIndeterminate: false, }, dispense_mix_volume: { value: null, isIndeterminate: false, }, dispense_delay_checkbox: { value: true, isIndeterminate: false, }, dispense_delay_seconds: { value: '1', isIndeterminate: false, }, dispense_delay_mmFromBottom: { value: '0.5', isIndeterminate: false, }, dispense_airGap_checkbox: { value: true, isIndeterminate: false, }, dispense_airGap_volume: { value: null, isIndeterminate: false, }, dispense_touchTip_checkbox: { value: true, isIndeterminate: false, }, dispense_touchTip_mmFromBottom: { value: 1, isIndeterminate: false, }, blowout_checkbox: { value: true, isIndeterminate: false, }, blowout_location: { value: 'trashId', isIndeterminate: false, }, changeTip: { isIndeterminate: false, value: 'always', }, dispense_wells: { isIndeterminate: true, }, disposalVolume_checkbox: { isIndeterminate: false, value: true, }, disposalVolume_volume: { isIndeterminate: false, value: '20', }, pipette: { isIndeterminate: false, value: 'some_pipette_id', }, volume: { isIndeterminate: false, value: '30', }, path: { isIndeterminate: false, value: 'single', }, }) }) }) describe('moveLiquid: when fields are indeterminate', () => { let mockSavedStepFormsIndeterminate: Record<string, any> beforeEach(() => { mockSavedStepFormsIndeterminate = { ...getMockMoveLiquidStep(), // just doing this so the ids are not the exact same another_move_liquid_step_id: { ...getMockMoveLiquidStep().move_liquid_step_id, aspirate_labware: 'other_asp_labware', aspirate_flowRate: 2, aspirate_mmFromBottom: '2', aspirate_wellOrder_first: 'b2t', aspirate_wellOrder_second: 'r2l', preWetTip: true, path: 'multiAspirate', aspirate_mix_checkbox: false, // not going to change mix times or mix volumes, so they should NOT be indeterminate aspirate_delay_checkbox: false, // same thing here for delay seconds and mm from bottom aspirate_airGap_checkbox: false, // same thing here with air gap volume aspirate_touchTip_checkbox: false, // same thing with aspirate_touchTip_mmFromBottom dispense_labware: 'other_disp_labware', dispense_flowRate: 2, dispense_mmFromBottom: '2', dispense_wellOrder_first: 'b2t', dispense_wellOrder_second: 'r2l', dispense_mix_checkbox: false, // same thing here with mix times or mix volumes dispense_delay_checkbox: false, // same thing here for delay seconds and mm from bottom dispense_airGap_checkbox: false, // same thing here with air gap volume dispense_touchTip_checkbox: false, // same thing with dispense_touchTip_mmFromBottom blowout_checkbox: false, // same thing here with blowout location }, } }) it('should return the fields with the indeterminate boolean', () => { expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type _getSavedMultiSelectFieldValues.resultFunc( mockSavedStepFormsIndeterminate, mockmultiSelectItemIds ) ).toEqual({ // aspirate settings aspirate_labware: { isIndeterminate: true, }, aspirate_flowRate: { isIndeterminate: true, }, aspirate_mmFromBottom: { isIndeterminate: true, }, aspirate_wellOrder_first: { isIndeterminate: true, }, aspirate_wellOrder_second: { isIndeterminate: true, }, path: { isIndeterminate: true, }, preWetTip: { isIndeterminate: true, }, aspirate_mix_checkbox: { isIndeterminate: true, }, aspirate_mix_times: { isIndeterminate: false, value: '2', }, aspirate_mix_volume: { isIndeterminate: false, value: '5', }, aspirate_delay_checkbox: { isIndeterminate: true, }, aspirate_delay_seconds: { isIndeterminate: false, value: '2', }, aspirate_delay_mmFromBottom: { isIndeterminate: false, value: '1', }, aspirate_airGap_checkbox: { isIndeterminate: true, }, aspirate_airGap_volume: { isIndeterminate: false, value: '30', }, aspirate_touchTip_checkbox: { isIndeterminate: true, }, aspirate_touchTip_mmFromBottom: { isIndeterminate: false, value: 1, }, // dispense settings dispense_labware: { isIndeterminate: true, }, dispense_flowRate: { isIndeterminate: true, }, dispense_mmFromBottom: { isIndeterminate: true, }, dispense_wellOrder_first: { isIndeterminate: true, }, dispense_wellOrder_second: { isIndeterminate: true, }, dispense_mix_checkbox: { isIndeterminate: true, }, dispense_mix_times: { isIndeterminate: false, value: null, }, dispense_mix_volume: { isIndeterminate: false, value: null, }, dispense_delay_checkbox: { isIndeterminate: true, }, dispense_delay_seconds: { isIndeterminate: false, value: '1', }, dispense_delay_mmFromBottom: { isIndeterminate: false, value: '0.5', }, dispense_airGap_checkbox: { isIndeterminate: true, }, dispense_airGap_volume: { isIndeterminate: false, value: null, }, dispense_touchTip_checkbox: { isIndeterminate: true, }, dispense_touchTip_mmFromBottom: { isIndeterminate: false, value: 1, }, blowout_checkbox: { isIndeterminate: true, }, blowout_location: { isIndeterminate: false, value: 'trashId', }, aspirate_wells: { isIndeterminate: true, }, dispense_wells: { isIndeterminate: true, }, aspirate_wells_grouped: { isIndeterminate: false, value: false, }, changeTip: { isIndeterminate: false, value: 'always', }, disposalVolume_checkbox: { isIndeterminate: false, value: true, }, disposalVolume_volume: { isIndeterminate: false, value: '20', }, pipette: { isIndeterminate: false, value: 'some_pipette_id', }, volume: { isIndeterminate: false, value: '30', }, }) }) }) describe('mix: when fields are NOT indeterminate', () => { let mockMixSavedStepForms: Record<string, FormData> let mockMixMultiSelectItemIds: string[] beforeEach(() => { mockMixSavedStepForms = { ...getMockMixStep(), another_mix_step_id: { ...getMockMixStep().mix_step_id, stepId: 'another_mix_step_id', }, } mockMixMultiSelectItemIds = ['mix_step_id', 'another_mix_step_id'] }) it('should return the fields with the indeterminate boolean', () => { expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type _getSavedMultiSelectFieldValues.resultFunc( mockMixSavedStepForms, mockMixMultiSelectItemIds ) ).toEqual({ volume: { value: '100', isIndeterminate: false }, times: { value: null, isIndeterminate: false }, changeTip: { value: 'always', isIndeterminate: false }, labware: { value: 'some_labware_id', isIndeterminate: false }, mix_wellOrder_first: { value: 't2b', isIndeterminate: false }, mix_wellOrder_second: { value: 'l2r', isIndeterminate: false }, blowout_checkbox: { value: false, isIndeterminate: false }, blowout_location: { value: 'trashId', isIndeterminate: false }, mix_mmFromBottom: { value: 0.5, isIndeterminate: false }, pipette: { value: 'some_pipette_id', isIndeterminate: false }, wells: { isIndeterminate: true }, aspirate_flowRate: { value: null, isIndeterminate: false }, dispense_flowRate: { value: null, isIndeterminate: false }, aspirate_delay_checkbox: { value: false, isIndeterminate: false }, aspirate_delay_seconds: { value: '1', isIndeterminate: false }, dispense_delay_checkbox: { value: false, isIndeterminate: false }, dispense_delay_seconds: { value: '1', isIndeterminate: false }, mix_touchTip_checkbox: { value: false, isIndeterminate: false }, mix_touchTip_mmFromBottom: { value: null, isIndeterminate: false }, }) }) }) describe('mix: when fields are indeterminate', () => { let mockMixSavedStepFormsIndeterminate: Record<string, FormData> let mockMixMultiSelectItemIds: string[] beforeEach(() => { mockMixSavedStepFormsIndeterminate = { ...getMockMixStep(), another_mix_step_id: { ...getMockMixStep().mix_step_id, volume: '123', times: '6', changeTip: 'never', labware: 'other_labware_id', mix_wellOrder_first: 'b2t', mix_wellOrder_second: 'r2l', blowout_checkbox: true, blowout_location: 'some_blowout_location', mix_mmFromBottom: 2, pipette: 'other_pipette_id', wells: ['A2'], aspirate_flowRate: '11.1', dispense_flowRate: '11.2', aspirate_delay_checkbox: true, aspirate_delay_seconds: '2', dispense_delay_checkbox: true, dispense_delay_seconds: '3', mix_touchTip_checkbox: true, mix_touchTip_mmFromBottom: '14', }, } mockMixMultiSelectItemIds = ['mix_step_id', 'another_mix_step_id'] }) it('should return the fields with the indeterminate boolean', () => { expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type _getSavedMultiSelectFieldValues.resultFunc( mockMixSavedStepFormsIndeterminate, mockMixMultiSelectItemIds ) ).toEqual({ volume: { isIndeterminate: true }, times: { isIndeterminate: true }, changeTip: { isIndeterminate: true }, labware: { isIndeterminate: true }, mix_wellOrder_first: { isIndeterminate: true }, mix_wellOrder_second: { isIndeterminate: true }, blowout_checkbox: { isIndeterminate: true }, blowout_location: { isIndeterminate: true }, mix_mmFromBottom: { isIndeterminate: true }, pipette: { isIndeterminate: true }, wells: { isIndeterminate: true }, aspirate_flowRate: { isIndeterminate: true }, dispense_flowRate: { isIndeterminate: true }, aspirate_delay_checkbox: { isIndeterminate: true }, aspirate_delay_seconds: { isIndeterminate: true }, dispense_delay_checkbox: { isIndeterminate: true }, dispense_delay_seconds: { isIndeterminate: true }, mix_touchTip_checkbox: { isIndeterminate: true }, mix_touchTip_mmFromBottom: { isIndeterminate: true }, }) }) }) }) describe('getMultiSelectFieldValues', () => { it('should pass through saved changes when there are no saved', () => { const savedValues = { a: { value: 'blah', isIndeterminate: true } } const changes = {} // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getMultiSelectFieldValues.resultFunc(savedValues, changes) expect(result).toEqual(savedValues) }) it('should apply unsaved changes to override saved changes', () => { const savedValues = { a: { value: 'blah', isIndeterminate: true } } const changes = { a: '123' } // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getMultiSelectFieldValues.resultFunc(savedValues, changes) expect(result).toEqual({ a: { value: '123', isIndeterminate: false } }) }) it('should return null when savedValues is null (signifying invalid combination of stepTypes)', () => { const savedValues = null const changes = { a: '123' } // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getMultiSelectFieldValues.resultFunc(savedValues, changes) expect(result).toBe(null) }) }) describe('getMultiSelectDisabledFields', () => { describe('disabled field tooltips', () => { it('should exist', () => { const baseText = 'tooltip.step_fields.batch_edit.disabled' const disabledReasons = [ 'pipette-different', 'aspirate-labware-different', 'dispense-labware-different', 'multi-aspirate-present', 'multi-aspirate-present-pipette-different', 'multi-dispense-present', 'multi-dispense-present-pipette-different', ] expect.assertions(7) disabledReasons.forEach(reason => { const searchText = `${baseText}.${reason}` expect(i18n.t(`${baseText}.${reason}`) !== searchText).toBe(true) }) }) }) describe('when all forms are of type moveLiquid', () => { let mockSavedStepForms: Record<string, FormData> let mockmultiSelectItemIds: string[] beforeEach(() => { mockSavedStepForms = { ...getMockMoveLiquidStep(), // just doing this so the ids are not the exact same another_move_liquid_step_id: { ...getMockMoveLiquidStep().move_liquid_step_id, }, } mockmultiSelectItemIds = [ 'move_liquid_step_id', 'another_move_liquid_step_id', ] }) it('should return an empty object when no fields are different and path is single', () => { expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type getMultiSelectDisabledFields.resultFunc( mockSavedStepForms, mockmultiSelectItemIds ) ).toEqual({}) }) describe('when pipettes are different', () => { let savedStepForms: Record<string, FormData> beforeEach(() => { savedStepForms = { ...mockSavedStepForms, another_move_liquid_step_id: { ...mockSavedStepForms.another_move_liquid_step_id, pipette: 'different_pipette_id', }, } }) it('should return fields being disabled with associated reasons', () => { expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type getMultiSelectDisabledFields.resultFunc( savedStepForms, mockmultiSelectItemIds ) ).toEqual({ aspirate_mix_checkbox: i18n.t( 'tooltip.step_fields.batch_edit.disabled.pipette-different' ), aspirate_mix_volume: i18n.t( 'tooltip.step_fields.batch_edit.disabled.pipette-different' ), aspirate_mix_times: i18n.t( 'tooltip.step_fields.batch_edit.disabled.pipette-different' ), aspirate_flowRate: i18n.t( 'tooltip.step_fields.batch_edit.disabled.pipette-different' ), aspirate_airGap_checkbox: i18n.t( 'tooltip.step_fields.batch_edit.disabled.pipette-different' ), aspirate_airGap_volume: i18n.t( 'tooltip.step_fields.batch_edit.disabled.pipette-different' ), dispense_mix_checkbox: i18n.t( 'tooltip.step_fields.batch_edit.disabled.pipette-different' ), dispense_mix_volume: i18n.t( 'tooltip.step_fields.batch_edit.disabled.pipette-different' ), dispense_mix_times: i18n.t( 'tooltip.step_fields.batch_edit.disabled.pipette-different' ), dispense_flowRate: i18n.t( 'tooltip.step_fields.batch_edit.disabled.pipette-different' ), dispense_airGap_checkbox: i18n.t( 'tooltip.step_fields.batch_edit.disabled.pipette-different' ), dispense_airGap_volume: i18n.t( 'tooltip.step_fields.batch_edit.disabled.pipette-different' ), }) }) }) describe('when aspirate labware are different', () => { let savedStepForms: Record<string, FormData> beforeEach(() => { savedStepForms = { ...mockSavedStepForms, another_move_liquid_step_id: { ...mockSavedStepForms.another_move_liquid_step_id, aspirate_labware: 'different_aspirate_labware', }, } }) it('should return fields being disabled with associated reasons', () => { const aspirateLabwareDifferentText = i18n.t( 'tooltip.step_fields.batch_edit.disabled.aspirate-labware-different' ) expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type getMultiSelectDisabledFields.resultFunc( savedStepForms, mockmultiSelectItemIds ) ).toEqual({ aspirate_mmFromBottom: aspirateLabwareDifferentText, aspirate_delay_checkbox: aspirateLabwareDifferentText, aspirate_delay_seconds: aspirateLabwareDifferentText, aspirate_delay_mmFromBottom: aspirateLabwareDifferentText, aspirate_touchTip_checkbox: aspirateLabwareDifferentText, aspirate_touchTip_mmFromBottom: aspirateLabwareDifferentText, }) }) }) describe('when dispense labware are different', () => { let savedStepForms: Record<string, FormData> beforeEach(() => { savedStepForms = { ...mockSavedStepForms, another_move_liquid_step_id: { ...mockSavedStepForms.another_move_liquid_step_id, dispense_labware: 'different_dispense_labware', }, } }) it('should return fields being disabled with associated reasons', () => { const dispenseLabwareDifferentText = i18n.t( 'tooltip.step_fields.batch_edit.disabled.dispense-labware-different' ) expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type getMultiSelectDisabledFields.resultFunc( savedStepForms, mockmultiSelectItemIds ) ).toEqual({ dispense_mmFromBottom: dispenseLabwareDifferentText, dispense_delay_checkbox: dispenseLabwareDifferentText, dispense_delay_seconds: dispenseLabwareDifferentText, dispense_delay_mmFromBottom: dispenseLabwareDifferentText, dispense_touchTip_checkbox: dispenseLabwareDifferentText, dispense_touchTip_mmFromBottom: dispenseLabwareDifferentText, }) }) }) describe('when a form includes a multi aspirate path', () => { let savedStepForms: Record<string, FormData> beforeEach(() => { savedStepForms = { ...mockSavedStepForms, another_move_liquid_step_id: { ...mockSavedStepForms.another_move_liquid_step_id, path: 'multiAspirate', }, } }) it('should return fields being disabled with associated reasons', () => { expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type getMultiSelectDisabledFields.resultFunc( savedStepForms, mockmultiSelectItemIds ) ).toEqual({ aspirate_mix_checkbox: i18n.t( 'tooltip.step_fields.batch_edit.disabled.multi-aspirate-present' ), aspirate_mix_volume: i18n.t( 'tooltip.step_fields.batch_edit.disabled.multi-aspirate-present' ), aspirate_mix_times: i18n.t( 'tooltip.step_fields.batch_edit.disabled.multi-aspirate-present' ), }) }) }) describe('when a form includes a multi dispense path', () => { let savedStepForms: Record<string, FormData> beforeEach(() => { savedStepForms = { ...mockSavedStepForms, another_move_liquid_step_id: { ...mockSavedStepForms.another_move_liquid_step_id, path: 'multiDispense', }, } }) it('should return fields being disabled with associated reasons', () => { expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type getMultiSelectDisabledFields.resultFunc( savedStepForms, mockmultiSelectItemIds ) ).toEqual({ dispense_mix_checkbox: i18n.t( 'tooltip.step_fields.batch_edit.disabled.multi-dispense-present' ), dispense_mix_volume: i18n.t( 'tooltip.step_fields.batch_edit.disabled.multi-dispense-present' ), dispense_mix_times: i18n.t( 'tooltip.step_fields.batch_edit.disabled.multi-dispense-present' ), blowout_checkbox: i18n.t( 'tooltip.step_fields.batch_edit.disabled.multi-dispense-present' ), blowout_location: i18n.t( 'tooltip.step_fields.batch_edit.disabled.multi-dispense-present' ), }) }) }) describe('when pipettes are different AND a form includes a multi aspirate path', () => { let savedStepForms: Record<string, FormData> beforeEach(() => { savedStepForms = { ...mockSavedStepForms, another_move_liquid_step_id: { ...mockSavedStepForms.another_move_liquid_step_id, path: 'multiAspirate', pipette: 'different_pipette_id', }, } }) it('should return aspirate mix being disabled for both reasons', () => { expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type getMultiSelectDisabledFields.resultFunc( savedStepForms, mockmultiSelectItemIds ) ).toEqual( expect.objectContaining({ aspirate_mix_checkbox: i18n.t( 'tooltip.step_fields.batch_edit.disabled.multi-aspirate-present-pipette-different' ), aspirate_mix_volume: i18n.t( 'tooltip.step_fields.batch_edit.disabled.multi-aspirate-present-pipette-different' ), aspirate_mix_times: i18n.t( 'tooltip.step_fields.batch_edit.disabled.multi-aspirate-present-pipette-different' ), }) ) }) }) describe('when pipettes are different AND a form includes a multi dispense path', () => { let savedStepForms: Record<string, FormData> beforeEach(() => { savedStepForms = { ...mockSavedStepForms, another_move_liquid_step_id: { ...mockSavedStepForms.another_move_liquid_step_id, path: 'multiDispense', pipette: 'different_pipette_id', }, } }) it('should return aspirate mix being disabled for both reasons', () => { expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type getMultiSelectDisabledFields.resultFunc( savedStepForms, mockmultiSelectItemIds ) ).toEqual( expect.objectContaining({ dispense_mix_checkbox: i18n.t( 'tooltip.step_fields.batch_edit.disabled.multi-dispense-present-pipette-different' ), dispense_mix_volume: i18n.t( 'tooltip.step_fields.batch_edit.disabled.multi-dispense-present-pipette-different' ), dispense_mix_times: i18n.t( 'tooltip.step_fields.batch_edit.disabled.multi-dispense-present-pipette-different' ), }) ) }) }) }) describe('when all forms are of type mix', () => { let mockSavedStepForms: Record<string, FormData> let mockmultiSelectItemIds: string[] beforeEach(() => { mockSavedStepForms = { ...getMockMixStep(), // just doing this so the ids are not the exact same another_mix_step_id: { ...getMockMixStep().mix_step_id, }, } mockmultiSelectItemIds = ['mix_step_id', 'another_mix_step_id'] }) it('should return an empty object when no fields are different', () => { expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type getMultiSelectDisabledFields.resultFunc( mockSavedStepForms, mockmultiSelectItemIds ) ).toEqual({}) }) describe('when pipettes are different', () => { let savedStepForms: Record<string, FormData> beforeEach(() => { savedStepForms = { ...mockSavedStepForms, another_mix_step_id: { ...mockSavedStepForms.another_mix_step_id, pipette: 'different_pipette_id', }, } }) it('should return flow rate fields being disabled with associated reasons', () => { expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type getMultiSelectDisabledFields.resultFunc( savedStepForms, mockmultiSelectItemIds ) ).toEqual({ aspirate_flowRate: i18n.t( 'tooltip.step_fields.batch_edit.disabled.pipette-different' ), dispense_flowRate: i18n.t( 'tooltip.step_fields.batch_edit.disabled.pipette-different' ), }) }) }) describe('when labware are different', () => { let savedStepForms: Record<string, FormData> beforeEach(() => { savedStepForms = { ...mockSavedStepForms, another_mix_step_id: { ...mockSavedStepForms.another_mix_step_id, labware: 'different_labware_id', }, } }) it('should return fields being disabled with associated reasons', () => { const labwareDifferentText = i18n.t( 'tooltip.step_fields.batch_edit.disabled.labware-different' ) expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type getMultiSelectDisabledFields.resultFunc( savedStepForms, mockmultiSelectItemIds ) ).toEqual({ mix_mmFromBottom: labwareDifferentText, aspirate_delay_checkbox: labwareDifferentText, aspirate_delay_seconds: labwareDifferentText, dispense_delay_checkbox: labwareDifferentText, dispense_delay_seconds: labwareDifferentText, mix_touchTip_checkbox: labwareDifferentText, mix_touchTip_mmFromBottom: labwareDifferentText, }) }) }) }) it('should return null if when forms are not all uniformly moveliquid OR mix', () => { const savedStepForms = { ...getMockMoveLiquidStep(), ...getMockMixStep(), } const multiSelectItemIds = ['move_liquid_step_id', 'mix_step_id'] expect( // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type getMultiSelectDisabledFields.resultFunc( savedStepForms, multiSelectItemIds ) ).toBe(null) }) }) describe('getCountPerStepType', () => { it('should return an object representing counts of all selected step types', () => { const multiSelectItemIds = ['a', 'b', 'd'] const savedStepForms = { a: { stepType: 'magnet' }, b: { stepType: 'magnet' }, c: { stepType: 'mix' }, // not selected! 'mix' should not show in result d: { stepType: 'moveLiquid' }, } // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getCountPerStepType.resultFunc( multiSelectItemIds, savedStepForms ) expect(result).toEqual({ magnet: 2, moveLiquid: 1 }) }) it('should return an empty object when not in multi-select mode', () => { // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getCountPerStepType.resultFunc(null, {}) expect(result).toEqual({}) }) it('should return an empty object when no steps are multi-selected', () => { // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getCountPerStepType.resultFunc([], {}) expect(result).toEqual({}) }) }) describe('getBatchEditSelectedStepTypes', () => { it('should return a sorted array of selected step types that are in the multi-selection', () => { // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getBatchEditSelectedStepTypes.resultFunc({ magnet: 1, mix: 3, moveLiquid: 0, }) expect(result).toEqual(['magnet', 'mix']) }) it('should return an empty array when no steps are multi-selected', () => { // @ts-expect-error(sa, 2021-6-15): resultFunc not part of Selector type const result = getBatchEditSelectedStepTypes.resultFunc({}) expect(result).toEqual([]) }) })
the_stack
import BN from "bn.js"; import { EventData, PastEventOptions } from "web3-eth-contract"; export interface IERC721MetadataUpgradeableContract extends Truffle.Contract<IERC721MetadataUpgradeableInstance> { "new"( meta?: Truffle.TransactionDetails ): Promise<IERC721MetadataUpgradeableInstance>; } export interface Approval { name: "Approval"; args: { owner: string; approved: string; tokenId: BN; 0: string; 1: string; 2: BN; }; } export interface ApprovalForAll { name: "ApprovalForAll"; args: { owner: string; operator: string; approved: boolean; 0: string; 1: string; 2: boolean; }; } export interface Transfer { name: "Transfer"; args: { from: string; to: string; tokenId: BN; 0: string; 1: string; 2: BN; }; } type AllEvents = Approval | ApprovalForAll | Transfer; export interface IERC721MetadataUpgradeableInstance extends Truffle.ContractInstance { /** * Gives permission to `to` to transfer `tokenId` token to another account. The approval is cleared when the token is transferred. Only a single account can be approved at a time, so approving the zero address clears previous approvals. Requirements: - The caller must own the token or be an approved operator. - `tokenId` must exist. Emits an {Approval} event. */ approve: { ( to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<Truffle.TransactionResponse<AllEvents>>; call( to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<void>; sendTransaction( to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<string>; estimateGas( to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<number>; }; /** * Returns the number of tokens in ``owner``'s account. */ balanceOf(owner: string, txDetails?: Truffle.TransactionDetails): Promise<BN>; /** * Returns the account approved for `tokenId` token. Requirements: - `tokenId` must exist. */ getApproved( tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<string>; /** * Returns if the `operator` is allowed to manage all of the assets of `owner`. See {setApprovalForAll} */ isApprovedForAll( owner: string, operator: string, txDetails?: Truffle.TransactionDetails ): Promise<boolean>; /** * Returns the owner of the `tokenId` token. Requirements: - `tokenId` must exist. */ ownerOf( tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<string>; /** * Approve or remove `operator` as an operator for the caller. Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. Requirements: - The `operator` cannot be the caller. Emits an {ApprovalForAll} event. */ setApprovalForAll: { ( operator: string, _approved: boolean, txDetails?: Truffle.TransactionDetails ): Promise<Truffle.TransactionResponse<AllEvents>>; call( operator: string, _approved: boolean, txDetails?: Truffle.TransactionDetails ): Promise<void>; sendTransaction( operator: string, _approved: boolean, txDetails?: Truffle.TransactionDetails ): Promise<string>; estimateGas( operator: string, _approved: boolean, txDetails?: Truffle.TransactionDetails ): Promise<number>; }; /** * Returns true if this contract implements the interface defined by `interfaceId`. See the corresponding https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] to learn more about how these ids are created. This function call must use less than 30 000 gas. */ supportsInterface( interfaceId: string, txDetails?: Truffle.TransactionDetails ): Promise<boolean>; /** * Transfers `tokenId` token from `from` to `to`. WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. Requirements: - `from` cannot be the zero address. - `to` cannot be the zero address. - `tokenId` token must be owned by `from`. - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. Emits a {Transfer} event. */ transferFrom: { ( from: string, to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<Truffle.TransactionResponse<AllEvents>>; call( from: string, to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<void>; sendTransaction( from: string, to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<string>; estimateGas( from: string, to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<number>; }; /** * Returns the token collection name. */ name(txDetails?: Truffle.TransactionDetails): Promise<string>; /** * Returns the token collection symbol. */ symbol(txDetails?: Truffle.TransactionDetails): Promise<string>; /** * Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ tokenURI( tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<string>; methods: { /** * Gives permission to `to` to transfer `tokenId` token to another account. The approval is cleared when the token is transferred. Only a single account can be approved at a time, so approving the zero address clears previous approvals. Requirements: - The caller must own the token or be an approved operator. - `tokenId` must exist. Emits an {Approval} event. */ approve: { ( to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<Truffle.TransactionResponse<AllEvents>>; call( to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<void>; sendTransaction( to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<string>; estimateGas( to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<number>; }; /** * Returns the number of tokens in ``owner``'s account. */ balanceOf( owner: string, txDetails?: Truffle.TransactionDetails ): Promise<BN>; /** * Returns the account approved for `tokenId` token. Requirements: - `tokenId` must exist. */ getApproved( tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<string>; /** * Returns if the `operator` is allowed to manage all of the assets of `owner`. See {setApprovalForAll} */ isApprovedForAll( owner: string, operator: string, txDetails?: Truffle.TransactionDetails ): Promise<boolean>; /** * Returns the owner of the `tokenId` token. Requirements: - `tokenId` must exist. */ ownerOf( tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<string>; /** * Approve or remove `operator` as an operator for the caller. Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. Requirements: - The `operator` cannot be the caller. Emits an {ApprovalForAll} event. */ setApprovalForAll: { ( operator: string, _approved: boolean, txDetails?: Truffle.TransactionDetails ): Promise<Truffle.TransactionResponse<AllEvents>>; call( operator: string, _approved: boolean, txDetails?: Truffle.TransactionDetails ): Promise<void>; sendTransaction( operator: string, _approved: boolean, txDetails?: Truffle.TransactionDetails ): Promise<string>; estimateGas( operator: string, _approved: boolean, txDetails?: Truffle.TransactionDetails ): Promise<number>; }; /** * Returns true if this contract implements the interface defined by `interfaceId`. See the corresponding https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] to learn more about how these ids are created. This function call must use less than 30 000 gas. */ supportsInterface( interfaceId: string, txDetails?: Truffle.TransactionDetails ): Promise<boolean>; /** * Transfers `tokenId` token from `from` to `to`. WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. Requirements: - `from` cannot be the zero address. - `to` cannot be the zero address. - `tokenId` token must be owned by `from`. - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. Emits a {Transfer} event. */ transferFrom: { ( from: string, to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<Truffle.TransactionResponse<AllEvents>>; call( from: string, to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<void>; sendTransaction( from: string, to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<string>; estimateGas( from: string, to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<number>; }; /** * Returns the token collection name. */ name(txDetails?: Truffle.TransactionDetails): Promise<string>; /** * Returns the token collection symbol. */ symbol(txDetails?: Truffle.TransactionDetails): Promise<string>; /** * Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ tokenURI( tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<string>; /** * Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients are aware of the ERC721 protocol to prevent tokens from being forever locked. Requirements: - `from` cannot be the zero address. - `to` cannot be the zero address. - `tokenId` token must exist and be owned by `from`. - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. Emits a {Transfer} event. */ "safeTransferFrom(address,address,uint256)": { ( from: string, to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<Truffle.TransactionResponse<AllEvents>>; call( from: string, to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<void>; sendTransaction( from: string, to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<string>; estimateGas( from: string, to: string, tokenId: number | BN | string, txDetails?: Truffle.TransactionDetails ): Promise<number>; }; /** * Safely transfers `tokenId` token from `from` to `to`. Requirements: - `from` cannot be the zero address. - `to` cannot be the zero address. - `tokenId` token must exist and be owned by `from`. - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. Emits a {Transfer} event. */ "safeTransferFrom(address,address,uint256,bytes)": { ( from: string, to: string, tokenId: number | BN | string, data: string, txDetails?: Truffle.TransactionDetails ): Promise<Truffle.TransactionResponse<AllEvents>>; call( from: string, to: string, tokenId: number | BN | string, data: string, txDetails?: Truffle.TransactionDetails ): Promise<void>; sendTransaction( from: string, to: string, tokenId: number | BN | string, data: string, txDetails?: Truffle.TransactionDetails ): Promise<string>; estimateGas( from: string, to: string, tokenId: number | BN | string, data: string, txDetails?: Truffle.TransactionDetails ): Promise<number>; }; }; getPastEvents(event: string): Promise<EventData[]>; getPastEvents( event: string, options: PastEventOptions, callback: (error: Error, event: EventData) => void ): Promise<EventData[]>; getPastEvents(event: string, options: PastEventOptions): Promise<EventData[]>; getPastEvents( event: string, callback: (error: Error, event: EventData) => void ): Promise<EventData[]>; }
the_stack
import { getPluginDataLoaded, getAnnotationData, getRunToMetrics, getEmbeddingDataSet, getSelectedAnnotations, getFlaggedAnnotations, getHiddenAnnotations, getAnnotationsRegex, getMetricsRegex, getMetricArithmetic, getMetricFilters, getAnnotationSort, getPCExpanded, getAnnotationsExpanded, getShowCounts, getShowHiddenAnnotations, getSidebarWidth, getSidebarExpanded, getViewActive, getEmbeddingsMetric, getEmbeddingsSidebarWidth, getEmbeddingsSidebarExpanded, } from './npmi_selectors'; import { DataLoadState, Operator, SortOrder, ArithmeticKind, ViewActive, } from './npmi_types'; import { createSampleEmbeddingData, createNpmiState, createState, } from '../testing'; describe('npmi selectors', () => { describe('getPluginDataLoadState', () => { it('returns the correct NOT_LOADED state', () => { const state = createState(createNpmiState()); const annotationsLoaded = getPluginDataLoaded(state); expect(annotationsLoaded).toBe(DataLoadState.NOT_LOADED); }); it('returns the correct LOADING state', () => { const state = createState( createNpmiState({ pluginDataLoaded: { state: DataLoadState.LOADING, lastLoadedTimeInMs: null, }, }) ); const annotationsLoaded = getPluginDataLoaded(state); expect(annotationsLoaded).toBe(DataLoadState.LOADING); }); it('returns the correct LOADED state', () => { const state = createState( createNpmiState({ pluginDataLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 1234, }, }) ); const loaded = getPluginDataLoaded(state); expect(loaded).toBe(DataLoadState.LOADED); }); }); describe('getAnnotationData', () => { it('returns the correct empty object', () => { const state = createState(createNpmiState()); expect(getAnnotationData(state)).toEqual({}); }); it('returns the correct data', () => { const state = createState( createNpmiState({ annotationData: { annotation_new_1: [ { nPMIValue: 0.1687, countValue: 1671, annotation: 'annotation_1', metric: 'newtest1', run: 'run_1', }, ], annotation_new_2: [ { nPMIValue: 0.68761, countValue: 189, annotation: 'annotation_1', metric: 'newtest1', run: 'run_1', }, ], }, }) ); expect(getAnnotationData(state)).toEqual({ annotation_new_1: [ { nPMIValue: 0.1687, countValue: 1671, annotation: 'annotation_1', metric: 'newtest1', run: 'run_1', }, ], annotation_new_2: [ { nPMIValue: 0.68761, countValue: 189, annotation: 'annotation_1', metric: 'newtest1', run: 'run_1', }, ], }); }); }); describe('getRunToMetrics', () => { it('returns the correct empty object', () => { const state = createState(createNpmiState()); expect(getRunToMetrics(state)).toEqual({}); }); it('returns the correct data', () => { const state = createState( createNpmiState({ runToMetrics: { run_1: ['npmi_metric_1', 'npmi_metric_2'], }, }) ); expect(getRunToMetrics(state)).toEqual({ run_1: ['npmi_metric_1', 'npmi_metric_2'], }); }); }); describe('getEmbeddingDataSet', () => { it('returns correct undefined', () => { const state = createState(createNpmiState()); expect(getEmbeddingDataSet(state)).toEqual(undefined); }); it('returns the correct data', () => { const embeddingData = createSampleEmbeddingData(); const state = createState( createNpmiState({ embeddingDataSet: embeddingData, }) ); expect(getEmbeddingDataSet(state)).toEqual(embeddingData); }); }); describe('getSelectedAnnotations', () => { it('returns correct empty array', () => { const state = createState(createNpmiState()); expect(getSelectedAnnotations(state)).toEqual([]); }); it('returns correct state', () => { const state = createState( createNpmiState({ selectedAnnotations: ['annotation_1', 'annotation_2'], }) ); expect(getSelectedAnnotations(state)).toEqual([ 'annotation_1', 'annotation_2', ]); }); }); describe('getFlaggedAnnotations', () => { it('returns correct empty array', () => { const state = createState(createNpmiState()); expect(getFlaggedAnnotations(state)).toEqual([]); }); it('returns correct state', () => { const state = createState( createNpmiState({ flaggedAnnotations: ['annotation_1', 'annotation_2'], }) ); expect(getFlaggedAnnotations(state)).toEqual([ 'annotation_1', 'annotation_2', ]); }); }); describe('getHiddenAnnotations', () => { it('returns correct empty array', () => { const state = createState(createNpmiState()); expect(getHiddenAnnotations(state)).toEqual([]); }); it('returns correct state', () => { const state = createState( createNpmiState({ hiddenAnnotations: ['annotation_1', 'annotation_2'], }) ); expect(getHiddenAnnotations(state)).toEqual([ 'annotation_1', 'annotation_2', ]); }); }); describe('getAnnotationsRegex', () => { it('returns correct empty string', () => { const state = createState(createNpmiState()); expect(getAnnotationsRegex(state)).toEqual(''); }); it('returns correct value', () => { const state = createState( createNpmiState({ annotationsRegex: 'test', }) ); expect(getAnnotationsRegex(state)).toBe('test'); }); }); describe('getMetricsRegex', () => { it('returns correct empty string', () => { const state = createState(createNpmiState()); expect(getMetricsRegex(state)).toEqual(''); }); it('returns correct value', () => { const state = createState( createNpmiState({ metricsRegex: 'test', }) ); expect(getMetricsRegex(state)).toBe('test'); }); }); describe('getMetricArithmetic', () => { it('return correct empty array', () => { const state = createState(createNpmiState()); expect(getMetricArithmetic(state)).toEqual([]); }); it('return correct arithmetic', () => { const state = createState( createNpmiState({ metricArithmetic: [ {kind: ArithmeticKind.METRIC, metric: 'test'}, {kind: ArithmeticKind.OPERATOR, operator: Operator.AND}, {kind: ArithmeticKind.METRIC, metric: 'test2'}, ], }) ); expect(getMetricArithmetic(state)).toEqual([ {kind: ArithmeticKind.METRIC, metric: 'test'}, {kind: ArithmeticKind.OPERATOR, operator: Operator.AND}, {kind: ArithmeticKind.METRIC, metric: 'test2'}, ]); }); }); describe('getMetricFilters', () => { it('returns correct empty object', () => { const state = createState(createNpmiState()); expect(getMetricFilters(state)).toEqual({}); }); it('returns correct filters objext', () => { const state = createState( createNpmiState({ metricFilters: { test: {max: 1.0, min: -1.0, includeNaN: true}, test2: {max: 1.0, min: 0, includeNaN: false}, }, }) ); expect(getMetricFilters(state)).toEqual({ test: {max: 1.0, min: -1.0, includeNaN: true}, test2: {max: 1.0, min: 0, includeNaN: false}, }); }); }); describe('getAnnotationSort', () => { it('returns correct inital object', () => { const state = createState(createNpmiState()); expect(getAnnotationSort(state)).toEqual({ metric: '', order: SortOrder.DESCENDING, }); }); it('returns correct state', () => { const state = createState( createNpmiState({ sort: { metric: 'test', order: SortOrder.ASCENDNG, }, }) ); expect(getAnnotationSort(state)).toEqual({ metric: 'test', order: SortOrder.ASCENDNG, }); }); }); describe('getPCExpanded', () => { it('returns correct true state', () => { const state = createState(createNpmiState()); expect(getPCExpanded(state)).toBeTrue(); }); it('returns correct state', () => { const state = createState( createNpmiState({ pcExpanded: false, }) ); expect(getPCExpanded(state)).toBeFalse(); }); }); describe('getAnnotationsExpanded', () => { it('returns correct true state', () => { const state = createState(createNpmiState()); expect(getAnnotationsExpanded(state)).toBeTrue(); }); it('returns correct state', () => { const state = createState( createNpmiState({ annotationsExpanded: false, }) ); expect(getAnnotationsExpanded(state)).toBeFalse(); }); }); describe('getSidebarExpanded', () => { it('returns correct true state', () => { const state = createState(createNpmiState()); expect(getSidebarExpanded(state)).toBeTrue(); }); it('returns correct state', () => { const state = createState( createNpmiState({ sidebarExpanded: false, }) ); expect(getSidebarExpanded(state)).toBeFalse(); }); }); describe('getShowCounts', () => { it('returns correct true state', () => { const state = createState(createNpmiState()); expect(getShowCounts(state)).toBeTrue(); }); it('returns correct state', () => { const state = createState( createNpmiState({ showCounts: false, }) ); expect(getShowCounts(state)).toBeFalse(); }); }); describe('getShowHiddenAnnotations', () => { it('returns correct false state', () => { const state = createState(createNpmiState()); expect(getShowHiddenAnnotations(state)).toBeFalse(); }); it('returns correct state', () => { const state = createState( createNpmiState({ showHiddenAnnotations: true, }) ); expect(getShowHiddenAnnotations(state)).toBeTrue(); }); }); describe('getViewActive', () => { it('returns correct initial state', () => { const state = createState(createNpmiState()); expect(getViewActive(state)).toBe(ViewActive.DEFAULT); }); it('returns correct state', () => { const state = createState( createNpmiState({ viewActive: ViewActive.EMBEDDINGS, }) ); expect(getViewActive(state)).toBe(ViewActive.EMBEDDINGS); }); }); describe('getSidebarWidth', () => { it('returns correct initial state', () => { const state = createState(createNpmiState()); expect(getSidebarWidth(state)).toBe(300); }); it('returns correct state', () => { const state = createState( createNpmiState({ sidebarWidth: 100, }) ); expect(getSidebarWidth(state)).toBe(100); }); }); describe('getEmbeddingsMetric', () => { it('returns correct initial state', () => { const state = createState(createNpmiState()); expect(getEmbeddingsMetric(state)).toBe(''); }); it('returns correct state', () => { const state = createState( createNpmiState({ embeddingsMetric: 'test', }) ); expect(getEmbeddingsMetric(state)).toBe('test'); }); }); describe('getEmbeddingsSidebarWidth', () => { it('returns correct initial state', () => { const state = createState(createNpmiState()); expect(getEmbeddingsSidebarWidth(state)).toBe(500); }); it('returns correct state', () => { const state = createState( createNpmiState({ embeddingsSidebarWidth: 100, }) ); expect(getEmbeddingsSidebarWidth(state)).toBe(100); }); }); describe('getEmbeddingsSidebarExpanded', () => { it('returns correct true state', () => { const state = createState(createNpmiState()); expect(getEmbeddingsSidebarExpanded(state)).toBeTrue(); }); it('returns correct state', () => { const state = createState( createNpmiState({ embeddingsSidebarExpanded: false, }) ); expect(getEmbeddingsSidebarExpanded(state)).toBeFalse(); }); }); });
the_stack
import React, { Component } from "react"; import Modal from "react-modal"; import dateformat from "dateformat"; import { RouteComponentProps, withRouter } from "react-router"; import { BalanceBlockHighlight } from "./BalanceBlocks"; import styles from "./Transactions.module.css"; import cstyles from "./Common.module.css"; import { Transaction, Info, AddressBookEntry, TxDetail } from "./AppState"; import ScrollPane from "./ScrollPane"; import Utils from "../utils/utils"; import { ZcashURITarget } from "../utils/uris"; import routes from "../constants/routes.json"; import RPC from "../rpc"; const { shell } = window.require("electron"); type TxModalInternalProps = { modalIsOpen: boolean; closeModal: () => void; tx?: Transaction; currencyName: string; setSendTo: (targets: ZcashURITarget | ZcashURITarget[]) => void; }; const TxModalInternal: React.FC<RouteComponentProps & TxModalInternalProps> = ({ modalIsOpen, tx, closeModal, currencyName, setSendTo, history, }) => { let txid = ""; let type = ""; let typeIcon = ""; let typeColor = ""; let confirmations = 0; let detailedTxns: TxDetail[] = []; let amount = 0; let datePart = ""; let timePart = ""; let price = 0; let priceString = ""; if (tx) { txid = tx.txid; type = tx.type; if (tx.type === "receive") { typeIcon = "fa-arrow-circle-down"; typeColor = "green"; } else { typeIcon = "fa-arrow-circle-up"; typeColor = "red"; } datePart = dateformat(tx.time * 1000, "mmm dd, yyyy"); timePart = dateformat(tx.time * 1000, "hh:MM tt"); confirmations = tx.confirmations; detailedTxns = tx.detailedTxns; amount = Math.abs(tx.amount); price = tx.zecPrice; if (price) { priceString = `USD ${price.toFixed(2)} / ZEC`; } } const openTxid = () => { if (currencyName === "TAZ") { shell.openExternal(`https://chain.so/tx/ZECTEST/${txid}`); } else { shell.openExternal(`https://zcha.in/transactions/${txid}`); } }; const doReply = (address: string) => { const defaultFee = RPC.getDefaultFee(); setSendTo(new ZcashURITarget(address, defaultFee)); closeModal(); history.push(routes.SEND); }; const totalAmounts = tx && tx.detailedTxns ? tx.detailedTxns.reduce((s, t) => Math.abs(parseFloat(t.amount)) + s, 0) : 0; const fees = tx ? Math.abs(tx.amount) - totalAmounts : 0; return ( <Modal isOpen={modalIsOpen} onRequestClose={closeModal} className={styles.txmodal} overlayClassName={styles.txmodalOverlay} > <div className={[cstyles.verticalflex].join(" ")}> <div className={[cstyles.marginbottomlarge, cstyles.center].join(" ")}>Transaction Status</div> <div className={[cstyles.center].join(" ")}> <i className={["fas", typeIcon].join(" ")} style={{ fontSize: "96px", color: typeColor }} /> </div> <div className={[cstyles.center].join(" ")}> {type} <BalanceBlockHighlight zecValue={amount} usdValue={Utils.getZecToUsdString(price, Math.abs(amount))} currencyName={currencyName} /> </div> <div className={[cstyles.flexspacebetween].join(" ")}> <div> <div className={[cstyles.sublight].join(" ")}>Time</div> <div> {datePart} {timePart} </div> </div> {type === "sent" && ( <div> <div className={[cstyles.sublight].join(" ")}>Fees</div> <div>ZEC {Utils.maxPrecisionTrimmed(fees)}</div> </div> )} <div> <div className={[cstyles.sublight].join(" ")}>Confirmations</div> <div>{confirmations}</div> </div> </div> <div className={cstyles.margintoplarge} /> <div className={[cstyles.flexspacebetween].join(" ")}> <div> <div className={[cstyles.sublight].join(" ")}>TXID</div> <div>{txid}</div> </div> <div className={cstyles.primarybutton} onClick={openTxid}> View TXID &nbsp; <i className={["fas", "fa-external-link-square-alt"].join(" ")} /> </div> </div> <div className={cstyles.margintoplarge} /> <hr /> {detailedTxns.map((txdetail) => { const { bigPart, smallPart } = Utils.splitZecAmountIntoBigSmall(Math.abs(parseFloat(txdetail.amount))); let { address } = txdetail; const { memo } = txdetail; if (!address) { address = "(Shielded)"; } let replyTo: string = ""; if (tx && tx.type === "receive" && memo) { const split = memo.split(/[ :\n\r\t]+/); if (split && split.length > 0 && Utils.isSapling(split[split.length - 1])) { replyTo = split[split.length - 1]; } } return ( <div key={address} className={cstyles.verticalflex}> <div className={[cstyles.sublight].join(" ")}>Address</div> <div>{Utils.splitStringIntoChunks(address, 6).join(" ")}</div> <div className={cstyles.margintoplarge} /> <div className={[cstyles.sublight].join(" ")}>Amount</div> <div className={[cstyles.flexspacebetween].join(" ")}> <div className={[cstyles.verticalflex].join(" ")}> <div> <span> {currencyName} {bigPart} </span> <span className={[cstyles.small, cstyles.zecsmallpart].join(" ")}>{smallPart}</span> </div> <div>{Utils.getZecToUsdString(price, Math.abs(amount))}</div> </div> <div className={[cstyles.verticalflex, cstyles.margintoplarge].join(" ")}> <div className={[cstyles.sublight].join(" ")}>{priceString}</div> </div> </div> <div className={cstyles.margintoplarge} /> {memo && ( <div> <div className={[cstyles.sublight].join(" ")}>Memo</div> <div className={[cstyles.flexspacebetween].join(" ")}> <div className={[cstyles.memodiv].join(" ")}>{memo}</div> {replyTo && ( <div className={cstyles.primarybutton} onClick={() => doReply(replyTo)}> Reply </div> )} </div> </div> )} <hr /> </div> ); })} <div className={[cstyles.center, cstyles.margintoplarge].join(" ")}> <button type="button" className={cstyles.primarybutton} onClick={closeModal}> Close </button> </div> </div> </Modal> ); }; const TxModal = withRouter(TxModalInternal); type TxItemBlockProps = { transaction: Transaction; currencyName: string; zecPrice: number; txClicked: (tx: Transaction) => void; addressBookMap: Map<string, string>; }; const TxItemBlock = ({ transaction, currencyName, zecPrice, txClicked, addressBookMap }: TxItemBlockProps) => { const txDate = new Date(transaction.time * 1000); const datePart = dateformat(txDate, "mmm dd, yyyy"); const timePart = dateformat(txDate, "hh:MM tt"); return ( <div> <div className={[cstyles.small, cstyles.sublight, styles.txdate].join(" ")}>{datePart}</div> <div className={[cstyles.well, styles.txbox].join(" ")} onClick={() => { txClicked(transaction); }} > <div className={styles.txtype}> <div>{transaction.type}</div> <div className={[cstyles.padtopsmall, cstyles.sublight].join(" ")}>{timePart}</div> </div> <div className={styles.txaddressamount}> {transaction.detailedTxns.map((txdetail) => { const { bigPart, smallPart } = Utils.splitZecAmountIntoBigSmall(Math.abs(parseFloat(txdetail.amount))); let { address } = txdetail; const { memo } = txdetail; if (!address) { address = "(Shielded)"; } const label = addressBookMap.get(address) || ""; return ( <div key={address} className={cstyles.padtopsmall}> <div className={styles.txaddress}> <div className={cstyles.highlight}>{label}</div> <div>{Utils.splitStringIntoChunks(address, 6).join(" ")}</div> <div className={[ cstyles.small, cstyles.sublight, cstyles.padtopsmall, cstyles.memodiv, styles.txmemo, ].join(" ")} > {memo} </div> </div> <div className={[styles.txamount, cstyles.right].join(" ")}> <div> <span> {currencyName} {bigPart} </span> <span className={[cstyles.small, cstyles.zecsmallpart].join(" ")}>{smallPart}</span> </div> <div className={[cstyles.sublight, cstyles.small, cstyles.padtopsmall].join(" ")}> {Utils.getZecToUsdString(zecPrice, Math.abs(parseFloat(txdetail.amount)))} </div> </div> </div> ); })} </div> </div> </div> ); }; type Props = { transactions: Transaction[]; addressBook: AddressBookEntry[]; info: Info; setSendTo: (targets: ZcashURITarget[] | ZcashURITarget) => void; }; type State = { clickedTx?: Transaction; modalIsOpen: boolean; numTxnsToShow: number; }; export default class Transactions extends Component<Props, State> { constructor(props: Props) { super(props); this.state = { clickedTx: undefined, modalIsOpen: false, numTxnsToShow: 100 }; } txClicked = (tx: Transaction) => { // Show the modal if (!tx) return; this.setState({ clickedTx: tx, modalIsOpen: true }); }; closeModal = () => { this.setState({ clickedTx: undefined, modalIsOpen: false }); }; show100MoreTxns = () => { const { numTxnsToShow } = this.state; this.setState({ numTxnsToShow: numTxnsToShow + 100 }); }; render() { const { transactions, info, addressBook, setSendTo } = this.props; const { clickedTx, modalIsOpen, numTxnsToShow } = this.state; const isLoadMoreEnabled = transactions && numTxnsToShow < transactions.length; const addressBookMap: Map<string, string> = addressBook.reduce((m, obj) => { m.set(obj.address, obj.label); return m; }, new Map()); return ( <div> <div className={[cstyles.xlarge, cstyles.padall, cstyles.center].join(" ")}>Transactions</div> {/* Change the hardcoded height */} <ScrollPane offsetHeight={100}> { /* If no transactions, show the "loading..." text */ !transactions && <div className={[cstyles.center, cstyles.margintoplarge].join(" ")}>Loading...</div> } {transactions && transactions.length === 0 && ( <div className={[cstyles.center, cstyles.margintoplarge].join(" ")}>No Transactions Yet</div> )} {transactions && transactions.slice(0, numTxnsToShow).map((t) => { const key = t.type + t.txid + (t.position || ""); return ( <TxItemBlock key={key} transaction={t} currencyName={info.currencyName} zecPrice={info.zecPrice} txClicked={this.txClicked} addressBookMap={addressBookMap} /> ); })} {isLoadMoreEnabled && ( <div style={{ marginLeft: "45%", width: "100px" }} className={cstyles.primarybutton} onClick={this.show100MoreTxns} > Load more </div> )} </ScrollPane> <TxModal modalIsOpen={modalIsOpen} tx={clickedTx} closeModal={this.closeModal} currencyName={info.currencyName} setSendTo={setSendTo} /> </div> ); } }
the_stack
import * as assert from 'assert'; import * as fs from 'fs'; import * as path from 'path'; import rewire = require('rewire'); import * as sinon from 'sinon'; import uuid = require('uuid'); import * as vscode from 'vscode'; import { TruffleCommands } from '../../src/commands/TruffleCommands'; import { Constants } from '../../src/Constants'; import * as helpers from '../../src/helpers'; import { openZeppelinHelper, TruffleConfiguration } from '../../src/helpers'; import * as commands from '../../src/helpers/command'; import { CancellationEvent, ItemType } from '../../src/Models'; import { AzureBlockchainNetworkNode, AzureBlockchainProject, AzureBlockchainService, BlockchainDataManagerNetworkNode, BlockchainDataManagerProject, BlockchainDataManagerService, IExtensionItem, InfuraNetworkNode, InfuraProject, InfuraService, LocalNetworkNode, LocalProject, LocalService, Member, Service, } from '../../src/Models/TreeItems'; import { ConsortiumResourceExplorer } from '../../src/resourceExplorers'; import { GanacheService, MnemonicRepository, OpenZeppelinMigrationsService, TreeManager } from '../../src/services'; import { OpenZeppelinService } from '../../src/services'; import { OZContractValidated } from '../../src/services/openZeppelin/models'; import { TestConstants } from '../TestConstants'; import { AzureAccountHelper } from '../testHelpers/AzureAccountHelper'; const { service } = Constants.treeItemData; describe('TruffleCommands', () => { describe('Integration test', async () => { describe('deployContracts', () => { let requiredMock: sinon.SinonMock; let checkAppsSilentMock: sinon.SinonExpectation; let installTruffleMock: sinon.SinonExpectation; let isHdWalletProviderRequiredMock: sinon.SinonExpectation; let checkHdWalletProviderVersionMock: sinon.SinonExpectation; let installTruffleHdWalletProviderMock: sinon.SinonExpectation; let getWorkspaceRootMock: any; let windowMock: sinon.SinonMock; let showQuickPickMock: any; let showInputBoxMock: any; let showSaveDialogMock: sinon.SinonExpectation; let showInformationMessageMock: any; let ganacheServiceMock: sinon.SinonMock; let startGanacheServerMock: sinon.SinonExpectation; let getItemsMock: sinon.SinonStub<[], IExtensionItem[]>; let loadStateMock: sinon.SinonStub<[], IExtensionItem[]>; let servicesItems: Service[]; let truffleConfigSetNetworkMock: any; let truffleConfigGetNetworkMock: any; let truffleConfigGenerateMnemonicMock: any; let commandContextMock: sinon.SinonMock; let executeCommandMock: sinon.SinonExpectation; let mnemonicRepositoryMock: sinon.SinonMock; let getMnemonicMock: sinon.SinonStub<any[], any>; let getAllMnemonicPathsMock: sinon.SinonStub<any[], any>; let saveMnemonicPathMock: sinon.SinonExpectation; let writeFileSyncMock: any; let getAccessKeysMock: any; let getExtensionMock: any; let openZeppelinvalidateContractsAsyncMock: any; let projectJsonExistsStub: sinon.SinonStub<[], boolean>; let shouldUpgradeOpenZeppelinAsyncStub: sinon.SinonStub<[], Promise<boolean>>; beforeEach(async () => { sinon.stub(helpers.openZeppelinHelper, 'tryGetCurrentOpenZeppelinVersionAsync'); sinon.stub(helpers.openZeppelinHelper, 'defineContractRequiredParameters'); sinon.stub(OpenZeppelinMigrationsService, 'generateMigrations'); getWorkspaceRootMock = sinon.stub(helpers, 'getWorkspaceRoot'); requiredMock = sinon.mock(helpers.required); checkAppsSilentMock = requiredMock.expects('checkAppsSilent'); installTruffleMock = requiredMock.expects('installTruffle'); isHdWalletProviderRequiredMock = requiredMock.expects('isHdWalletProviderRequired'); checkHdWalletProviderVersionMock = requiredMock.expects('checkHdWalletProviderVersion'); installTruffleHdWalletProviderMock = requiredMock.expects('installTruffleHdWalletProvider'); isHdWalletProviderRequiredMock.returns(false); checkHdWalletProviderVersionMock.returns(false); windowMock = sinon.mock(vscode.window); showQuickPickMock = sinon.stub(vscode.window, 'showQuickPick'); showInputBoxMock = sinon.stub(vscode.window, 'showInputBox'); showSaveDialogMock = windowMock.expects('showSaveDialog'); sinon.stub(vscode.window, 'showErrorMessage'); showInformationMessageMock = sinon.stub(vscode.window, 'showInformationMessage'); ganacheServiceMock = sinon.mock(GanacheService); startGanacheServerMock = ganacheServiceMock.expects('startGanacheServer'); getItemsMock = sinon.stub(TreeManager, 'getItems'); loadStateMock = sinon.stub(TreeManager, 'loadState'); servicesItems = await createTestServicesItems(); getItemsMock.returns(servicesItems); loadStateMock.returns(servicesItems); truffleConfigSetNetworkMock = sinon.stub(TruffleConfiguration.TruffleConfig.prototype, 'setNetworks'); truffleConfigGetNetworkMock = sinon.stub(TruffleConfiguration.TruffleConfig.prototype, 'getNetworks'); truffleConfigGetNetworkMock.returns(getTestTruffleNetworks()); truffleConfigGenerateMnemonicMock = sinon.stub(TruffleConfiguration, 'generateMnemonic'); truffleConfigGenerateMnemonicMock.returns(TestConstants.testMnemonic); commandContextMock = sinon.mock(commands); executeCommandMock = commandContextMock.expects('executeCommand'); mnemonicRepositoryMock = sinon.mock(MnemonicRepository); getMnemonicMock = mnemonicRepositoryMock.expects('getMnemonic').returns(TestConstants.testMnemonic); getAllMnemonicPathsMock = mnemonicRepositoryMock.expects('getAllMnemonicPaths').returns([] as string[]); saveMnemonicPathMock = mnemonicRepositoryMock.expects('saveMnemonicPath'); writeFileSyncMock = sinon.stub(fs, 'writeFileSync'); getAccessKeysMock = sinon.stub(ConsortiumResourceExplorer.prototype, 'getAccessKeys'); getExtensionMock = sinon.stub(vscode.extensions, 'getExtension').returns(AzureAccountHelper.mockExtension); projectJsonExistsStub = sinon.stub(OpenZeppelinService, 'projectJsonExists').returns(false); shouldUpgradeOpenZeppelinAsyncStub = sinon.stub(openZeppelinHelper, 'shouldUpgradeOpenZeppelinAsync') .resolves(false); const openZeppelinServiceMock = sinon.mock(OpenZeppelinService); openZeppelinvalidateContractsAsyncMock = openZeppelinServiceMock.expects('validateContractsAsync') .resolves([]); }); afterEach(() => { sinon.restore(); }); it('should throw exception when config file not found', async () => { // Arrange getWorkspaceRootMock.returns(__dirname); executeCommandMock.returns(uuid.v4()); // Act and assert await assert.rejects(TruffleCommands.deployContracts(), Error, Constants.errorMessageStrings.TruffleConfigIsNotExist); }); it('should throw cancellationEvent when showQuickPick return undefined', async () => { // Arrange getWorkspaceRootMock.returns(path.join(__dirname, TestConstants.truffleCommandTestDataFolder)); executeCommandMock.returns(uuid.v4()); showQuickPickMock.returns(undefined); // Act and assert await assert.rejects(TruffleCommands.deployContracts(), CancellationEvent); }); it('should install TruffleHdWalletProvider when it required', async () => { // Arrange checkAppsSilentMock.returns(true); getWorkspaceRootMock.returns(path.join(__dirname, TestConstants.truffleCommandTestDataFolder)); isHdWalletProviderRequiredMock.returns(true); checkHdWalletProviderVersionMock.returns(false); executeCommandMock.returns(uuid.v4()); showInformationMessageMock.returns(Constants.informationMessage.installButton); showQuickPickMock.onCall(0).callsFake((items: any) => { return items.find((item: any) => item.label === TestConstants.servicesNames.development); }); // Act await TruffleCommands.deployContracts(); // Assert assert.strictEqual(showQuickPickMock.calledOnce, true, 'showQuickPick should be called once'); assert.strictEqual(showInputBoxMock.called, false, 'showInputBox should not be called'); assert.strictEqual(checkAppsSilentMock.calledOnce, true, 'checkAppsSilent should be called once'); assert.strictEqual(installTruffleMock.called, false, 'installTruffle should not be called'); assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called'); assert.strictEqual(executeCommandMock.called, true, 'executeCommand should be called'); assert.strictEqual(startGanacheServerMock.called, true, 'startGanacheServer should be called'); assert.strictEqual(truffleConfigSetNetworkMock.called, false, 'truffleConfig.setNetwork should not be called'); assert.strictEqual( isHdWalletProviderRequiredMock.calledOnce, true, 'isHdWalletProviderRequired should be called'); assert.strictEqual( checkHdWalletProviderVersionMock.calledOnce, true, 'checkHdWalletProviderVersion should be called'); assert.strictEqual( installTruffleHdWalletProviderMock.calledOnce, true, 'installTruffleHdWalletProvider should be called'); }); it('should not install TruffleHdWalletProvider when it version correct', async () => { // Arrange checkAppsSilentMock.returns(true); getWorkspaceRootMock.returns(path.join(__dirname, TestConstants.truffleCommandTestDataFolder)); isHdWalletProviderRequiredMock.returns(true); checkHdWalletProviderVersionMock.returns(true); executeCommandMock.returns(uuid.v4()); showQuickPickMock.onCall(0).callsFake((items: any) => { return items.find((item: any) => item.label === TestConstants.servicesNames.development); }); // Act await TruffleCommands.deployContracts(); // Assert assert.strictEqual(showQuickPickMock.calledOnce, true, 'showQuickPick should be called once'); assert.strictEqual(showInputBoxMock.called, false, 'showInputBox should not be called'); assert.strictEqual(checkAppsSilentMock.calledOnce, true, 'checkAppsSilent should be called once'); assert.strictEqual(installTruffleMock.called, false, 'installTruffle should not be called'); assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called'); assert.strictEqual(executeCommandMock.called, true, 'executeCommand should be called'); assert.strictEqual(startGanacheServerMock.called, true, 'startGanacheServer should be called'); assert.strictEqual(truffleConfigSetNetworkMock.called, false, 'truffleConfig.setNetwork should not be called'); assert.strictEqual(isHdWalletProviderRequiredMock.calledOnce, true, 'isHdWalletProviderRequired should be called'); assert.strictEqual( checkHdWalletProviderVersionMock.calledOnce, true, 'checkHdWalletProviderVersion should be called'); assert.strictEqual( installTruffleHdWalletProviderMock.calledOnce, false, 'installTruffleHdWalletProvider should not be called'); }); it('to development should complete successfully with updating OpenZeppelin', async () => { // Arrange checkAppsSilentMock.returns(true); getWorkspaceRootMock.returns(path.join(__dirname, TestConstants.truffleCommandTestDataFolder)); executeCommandMock.returns(uuid.v4()); isHdWalletProviderRequiredMock.returns(false); projectJsonExistsStub.returns(true); shouldUpgradeOpenZeppelinAsyncStub.resolves(true); const updateOpenZeppelinInUserSettingsSpy = sinon.stub(helpers.openZeppelinHelper, 'upgradeOpenZeppelinUserSettingsAsync').resolves(); const updateOpenZeppelinContractsSpy = sinon.stub(helpers.openZeppelinHelper, 'upgradeOpenZeppelinContractsAsync').resolves(); const truffleCommandsRewire = rewire('../../src/commands/TruffleCommands'); truffleCommandsRewire.__set__('validateOpenZeppelinContracts', sinon.mock()); const validateOpenZeppelinContractsMock = truffleCommandsRewire.__get__('validateOpenZeppelinContracts'); showQuickPickMock.onCall(0).callsFake((items: any) => { return items.find((item: any) => item.label === TestConstants.servicesNames.development); }); // Act await truffleCommandsRewire.TruffleCommands.deployContracts(); // Assert assert.strictEqual(showQuickPickMock.calledOnce, true, 'showQuickPick should be called once'); assert.strictEqual(showInputBoxMock.called, false, 'showInputBox should not be called'); assert.strictEqual(checkAppsSilentMock.calledOnce, true, 'checkAppsSilent should be called once'); assert.strictEqual(installTruffleMock.called, false, 'installTruffle should not be called'); assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called'); assert.strictEqual(executeCommandMock.called, true, 'executeCommand should be called'); assert.strictEqual(startGanacheServerMock.called, true, 'startGanacheServer should be called'); assert.strictEqual(truffleConfigSetNetworkMock.called, false, 'truffleConfig.setNetwork should not be called'); assert.strictEqual(isHdWalletProviderRequiredMock.calledOnce, true, 'isHdWalletProviderRequired should be called'); assert.strictEqual(updateOpenZeppelinInUserSettingsSpy.called, true, 'updateOpenZeppelinInUserSettings should be called'); assert.strictEqual(updateOpenZeppelinContractsSpy.called, true, 'updateOpenZeppelinContracts should be called'); assert.strictEqual(validateOpenZeppelinContractsMock.calledOnce, true, 'validateOpenZeppelinContracts should be called'); assert.strictEqual( checkHdWalletProviderVersionMock.calledOnce, false, 'checkHdWalletProviderVersion should not be called'); assert.strictEqual( installTruffleHdWalletProviderMock.calledOnce, false, 'installTruffleHdWalletProvider should not be called'); }); it('to development should throw exception when there is an error on command execution', async () => { // Arrange checkAppsSilentMock.returns(true); getWorkspaceRootMock.returns(path.join(__dirname, TestConstants.truffleCommandTestDataFolder)); executeCommandMock.throws(TestConstants.testError); showQuickPickMock.callsFake((items: any) => { return items.find((item: any) => item.label === TestConstants.servicesNames.development); }); // Act and assert await assert.rejects(TruffleCommands.deployContracts(), Error); assert.strictEqual(showQuickPickMock.calledOnce, true, 'showQuickPick should be called once'); assert.strictEqual(showInputBoxMock.called, false, 'showInputBox should not be called'); assert.strictEqual(checkAppsSilentMock.calledOnce, true, 'checkAppsSilent should be called once'); assert.strictEqual(installTruffleMock.called, false, 'installTruffle should not be called'); assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called'); assert.strictEqual(executeCommandMock.called, true, 'executeCommand should be called'); assert.strictEqual(startGanacheServerMock.called, true, 'startGanacheServer should be called'); assert.strictEqual(truffleConfigSetNetworkMock.called, false, 'truffleConfig.setNetwork should not be called'); assert.strictEqual(isHdWalletProviderRequiredMock.calledOnce, true, 'isHdWalletProviderRequired should be called'); assert.strictEqual( checkHdWalletProviderVersionMock.calledOnce, false, 'checkHdWalletProviderVersion should not be called'); assert.strictEqual( installTruffleHdWalletProviderMock.calledOnce, false, 'installTruffleHdWalletProvider should not be called'); }); it('to network should complete successfully', async () => { // Arrange checkAppsSilentMock.returns(true); getWorkspaceRootMock.returns(path.join(__dirname, TestConstants.truffleCommandTestDataFolder)); executeCommandMock.returns(uuid.v4()); showQuickPickMock.onCall(0).callsFake((items: any) => { return items.find((item: any) => item.label === TestConstants.servicesNames.testNetwork); }); // Act await TruffleCommands.deployContracts(); // Assert assert.strictEqual(showQuickPickMock.calledOnce, true, 'showQuickPick should be called once'); assert.strictEqual(showInputBoxMock.called, false, 'showInputBox should not be called'); assert.strictEqual(checkAppsSilentMock.calledOnce, true, 'checkAppsSilent should be called once'); assert.strictEqual(installTruffleMock.called, false, 'installTruffle should not be called'); assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called'); assert.strictEqual(executeCommandMock.called, true, 'executeCommand should be called'); assert.strictEqual(startGanacheServerMock.called, false, 'startGanacheServer should not be called'); assert.strictEqual(truffleConfigSetNetworkMock.called, false, 'truffleConfig.setNetwork should not be called'); assert.strictEqual(isHdWalletProviderRequiredMock.calledOnce, true, 'isHdWalletProviderRequired should be called'); assert.strictEqual( checkHdWalletProviderVersionMock.calledOnce, false, 'checkHdWalletProviderVersion should not be called'); assert.strictEqual( installTruffleHdWalletProviderMock.calledOnce, false, 'installTruffleHdWalletProvider should not be called'); }); it('to network should throw exception when there is an error on command execution', async () => { // Arrange checkAppsSilentMock.returns(true); getWorkspaceRootMock.returns(path.join(__dirname, TestConstants.truffleCommandTestDataFolder)); executeCommandMock.throws(TestConstants.testError); showQuickPickMock.onCall(0).callsFake((items: any) => { return items.find((item: any) => item.label === TestConstants.servicesNames.testNetwork); }); // Act and assert await assert.rejects(TruffleCommands.deployContracts()); assert.strictEqual(showQuickPickMock.calledOnce, true, 'showQuickPick should be called once'); assert.strictEqual(showInputBoxMock.called, false, 'showInputBox should not be called'); assert.strictEqual(checkAppsSilentMock.calledOnce, true, 'checkAppsSilent should be called once'); assert.strictEqual(installTruffleMock.called, false, 'installTruffle should not be called'); assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called'); assert.strictEqual(executeCommandMock.called, true, 'executeCommand should be called'); assert.strictEqual(startGanacheServerMock.called, false, 'startGanacheServer should not be called'); assert.strictEqual(truffleConfigSetNetworkMock.called, false, 'truffleConfig.setNetwork should not be called'); assert.strictEqual(isHdWalletProviderRequiredMock.calledOnce, true, 'isHdWalletProviderRequired should be called'); assert.strictEqual( checkHdWalletProviderVersionMock.calledOnce, false, 'checkHdWalletProviderVersion should not be called'); assert.strictEqual( installTruffleHdWalletProviderMock.calledOnce, false, 'installTruffleHdWalletProvider should not be called'); }); it('to local network should complete successfully', async () => { // Arrange const { local } = TestConstants.consortiumTestNames; checkAppsSilentMock.returns(true); getWorkspaceRootMock.returns(path.join(__dirname, TestConstants.truffleCommandTestDataFolder)); executeCommandMock.returns(uuid.v4()); const networkNodeName = getDeployName(service.local.prefix, local, local); showQuickPickMock.onCall(0).callsFake((items: any) => { return items.find((item: any) => item.label === networkNodeName); }); // Act await TruffleCommands.deployContracts(); // Assert assert.strictEqual(showQuickPickMock.calledOnce, true, 'showQuickPick should be called once'); assert.strictEqual(showInputBoxMock.called, false, 'showInputBox should not be called'); assert.strictEqual(checkAppsSilentMock.calledOnce, true, 'checkAppsSilent should be called once'); assert.strictEqual(installTruffleMock.called, false, 'installTruffle should not be called'); assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called'); assert.strictEqual(executeCommandMock.called, true, 'executeCommand should be called'); assert.strictEqual(startGanacheServerMock.called, true, 'startGanacheServer should be called'); assert.strictEqual(truffleConfigSetNetworkMock.called, true, 'truffleConfig.setNetwork should be called'); assert.strictEqual( isHdWalletProviderRequiredMock.calledOnce, true, 'isHdWalletProviderRequired should be called'); assert.strictEqual( checkHdWalletProviderVersionMock.calledOnce, false, 'checkHdWalletProviderVersion should not be called'); assert.strictEqual( installTruffleHdWalletProviderMock.calledOnce, false, 'installTruffleHdWalletProvider should not be called'); }); it('to local network should throw exception when there is an error on command execution', async () => { // Arrange const { local } = TestConstants.consortiumTestNames; checkAppsSilentMock.returns(true); getWorkspaceRootMock.returns(path.join(__dirname, TestConstants.truffleCommandTestDataFolder)); executeCommandMock.throws(TestConstants.testError); const networkNodeName = getDeployName(service.local.prefix, local, local); showQuickPickMock.onCall(0).callsFake((items: any) => { return items.find((item: any) => item.label === networkNodeName); }); // Act and assert await assert.rejects(TruffleCommands.deployContracts()); assert.strictEqual(showQuickPickMock.calledOnce, true, 'showQuickPick should be called once'); assert.strictEqual(showInputBoxMock.called, false, 'showInputBox should not be called'); assert.strictEqual(checkAppsSilentMock.calledOnce, true, 'checkAppsSilent should be called once'); assert.strictEqual(installTruffleMock.called, false, 'installTruffle should not be called'); assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called'); assert.strictEqual(executeCommandMock.called, true, 'executeCommand should be called'); assert.strictEqual(startGanacheServerMock.called, true, 'startGanacheServer should be called'); assert.strictEqual(truffleConfigSetNetworkMock.called, true, 'truffleConfig.setNetwork should be called'); assert.strictEqual( isHdWalletProviderRequiredMock.calledOnce, true, 'isHdWalletProviderRequired should be called'); assert.strictEqual( checkHdWalletProviderVersionMock.calledOnce, false, 'checkHdWalletProviderVersion should not be called'); assert.strictEqual( installTruffleHdWalletProviderMock.calledOnce, false, 'installTruffleHdWalletProvider should not be called'); }); it('to AzureBlockchainService should generate mnemonic and complete successfully', async () => { // Arrange const { consortium, member, transactionNode } = azureNames; checkAppsSilentMock.returns(true); getWorkspaceRootMock.returns(path.join(__dirname, TestConstants.truffleCommandTestDataFolder)); executeCommandMock.returns(uuid.v4()); getAccessKeysMock.returns(uuid.v4()); const networkNodeName = getDeployName(service.azure.prefix, consortium, transactionNode, [member]); showQuickPickMock.onCall(0).callsFake((items: any) => { return items.find((item: any) => item.label === networkNodeName); }); showQuickPickMock.onCall(1).callsFake((items: any) => { return items.find((item: any) => item.label === Constants.placeholders.generateMnemonic); }); showSaveDialogMock.returns(uuid.v4()); // Act await TruffleCommands.deployContracts(); // Assert assert.strictEqual(showQuickPickMock.called, true, 'showQuickPick should be called'); assert.strictEqual(showQuickPickMock.callCount, 2, 'showQuickPick should be called twice'); assert.strictEqual(getAccessKeysMock.called, true, 'getAccessKeys should be called'); assert.strictEqual(showInputBoxMock.called, false, 'showInputBox should not be called'); assert.strictEqual(getMnemonicMock.called, false, 'getMnemonic should not be called'); assert.strictEqual(getAllMnemonicPathsMock.called, true, 'getAllMnemonicPaths should be called'); assert.strictEqual(saveMnemonicPathMock.called, true, 'saveMnemonicPath should be called'); assert.strictEqual(writeFileSyncMock.called, true, 'writeFileSync should be called'); assert.strictEqual(checkAppsSilentMock.calledOnce, true, 'checkAppsSilent should be called once'); assert.strictEqual(installTruffleMock.called, false, 'installTruffle should not be called'); assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called'); assert.strictEqual(executeCommandMock.called, true, 'executeCommand should be called'); assert.strictEqual(startGanacheServerMock.called, false, 'startGanacheServer should not be called'); assert.strictEqual(truffleConfigSetNetworkMock.called, true, 'truffleConfig.setNetwork should be called'); assert.strictEqual(getExtensionMock.called, true, 'getExtension should be called'); assert.strictEqual( isHdWalletProviderRequiredMock.calledOnce, true, 'isHdWalletProviderRequired should be called'); assert.strictEqual( checkHdWalletProviderVersionMock.calledOnce, false, 'checkHdWalletProviderVersion should not be called'); assert.strictEqual( installTruffleHdWalletProviderMock.calledOnce, false, 'installTruffleHdWalletProvider should not be called'); }); it('to AzureBlockchainService should complete successfully when user paste mnemonic', async () => { // Arrange const { consortium, member, transactionNode } = azureNames; checkAppsSilentMock.returns(true); getWorkspaceRootMock.returns(path.join(__dirname, TestConstants.truffleCommandTestDataFolder)); executeCommandMock.returns(uuid.v4()); getAccessKeysMock.returns(uuid.v4()); const networkNodeName = getDeployName(service.azure.prefix, consortium, transactionNode, [member]); showQuickPickMock.onCall(0).callsFake((items: any) => { return items.find((item: any) => item.label === networkNodeName); }); showQuickPickMock.onCall(1).callsFake((items: any) => { return items.find((item: any) => item.label === Constants.placeholders.pasteMnemonic); }); showInputBoxMock.onCall(0).returns(TestConstants.testMnemonic); showSaveDialogMock.returns(uuid.v4()); // Act await TruffleCommands.deployContracts(); // Assert assert.strictEqual(showQuickPickMock.called, true, 'showQuickPick should be called'); assert.strictEqual(showQuickPickMock.callCount, 2, 'showQuickPick should be called twice'); assert.strictEqual(getAccessKeysMock.called, true, 'getAccessKeys should be called'); assert.strictEqual(showInputBoxMock.calledOnce, true, 'showInputBox should be called once'); assert.strictEqual(getMnemonicMock.called, false, 'getMnemonic should not be called'); assert.strictEqual(getAllMnemonicPathsMock.called, true, 'getAllMnemonicPaths should be called'); assert.strictEqual(saveMnemonicPathMock.called, true, 'saveMnemonicPath should be called'); assert.strictEqual(writeFileSyncMock.called, true, 'writeFileSync should be called'); assert.strictEqual(checkAppsSilentMock.calledOnce, true, 'checkAppsSilent should be called once'); assert.strictEqual(installTruffleMock.called, false, 'installTruffle should not be called'); assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called'); assert.strictEqual(executeCommandMock.called, true, 'executeCommand should be called'); assert.strictEqual(startGanacheServerMock.called, false, 'startGanacheServer should not be called'); assert.strictEqual(truffleConfigSetNetworkMock.called, true, 'truffleConfig.setNetwork should be called'); assert.strictEqual(getExtensionMock.called, true, 'getExtension should be called'); assert.strictEqual( isHdWalletProviderRequiredMock.calledOnce, true, 'isHdWalletProviderRequired should be called'); assert.strictEqual( checkHdWalletProviderVersionMock.calledOnce, false, 'checkHdWalletProviderVersion should not be called'); assert.strictEqual( installTruffleHdWalletProviderMock.calledOnce, false, 'installTruffleHdWalletProvider should not be called'); }); it('Blockchain Data Manager should be ignored in deploy destination list', async () => { // Arrange let isBDMExist = false; const { local } = TestConstants.consortiumTestNames; checkAppsSilentMock.returns(true); getWorkspaceRootMock.returns(path.join(__dirname, TestConstants.truffleCommandTestDataFolder)); executeCommandMock.returns(uuid.v4()); const networkNodeName = getDeployName(service.local.prefix, local, local); showQuickPickMock.onCall(0).callsFake((items: any) => { isBDMExist = items.some((item: any) => item.detail === Constants.treeItemData.service.bdm.label); return items.find((item: any) => item.label === networkNodeName); }); // Act await TruffleCommands.deployContracts(); // Assert assert.strictEqual(isBDMExist, false, 'deploy destination list should not have Blockchain Data Manager'); }); describe('validating openZeppelin contracts before deploy', () => { beforeEach(() => { checkAppsSilentMock.resolves(true); getWorkspaceRootMock.returns(path.join(__dirname, TestConstants.truffleCommandTestDataFolder)); showInputBoxMock.returns(Constants.confirmationDialogResult.yes); executeCommandMock.returns(uuid.v4()); showQuickPickMock.onCall(0).callsFake((items: any) => { return items.find((item: any) => item.label === TestConstants.servicesNames.testNetwork); }); }); afterEach(() => { sinon.restore(); }); it('should pass when openZeppelin contracts are valid', async () => { // Arrange projectJsonExistsStub.returns(true); openZeppelinvalidateContractsAsyncMock.resolves([new OZContractValidated('1', true, true)]); // Act await TruffleCommands.deployContracts(); // Assert assert.strictEqual(executeCommandMock.called, true, 'executeCommand should be called'); }); it('should throw error when downloaded openZeppelin contract has invalid hash', async () => { // Arrange projectJsonExistsStub.returns(true); openZeppelinvalidateContractsAsyncMock.resolves([new OZContractValidated('1', true, false)]); // Act and Assert await assert.rejects(TruffleCommands.deployContracts(), Error); }); it('should throw error when downloaded openZeppelin contract doesn\'t exist on the disk', async () => { // Arrange projectJsonExistsStub.returns(true); openZeppelinvalidateContractsAsyncMock.resolves([new OZContractValidated('1', false)]); // Act and Assert await assert.rejects(TruffleCommands.deployContracts(), Error); }); it('should throw error when any downloaded openZeppelin contract is invalid', async () => { // Arrange projectJsonExistsStub.returns(true); openZeppelinvalidateContractsAsyncMock.resolves([ new OZContractValidated('1', true, false), new OZContractValidated('2', true, true), ]); // Act and Assert await assert.rejects(TruffleCommands.deployContracts(), Error); }); }); }); }); }); const azureNames = { consortium: uuid.v4(), member: uuid.v4(), transactionNode: TestConstants.servicesNames.testConsortium, }; async function createTestServicesItems(): Promise<Service[]> { const services: Service[] = []; const azureBlockchainService = new AzureBlockchainService(); const localService = new LocalService(); const infuraService = new InfuraService(); const bdmService = new BlockchainDataManagerService(); const azureBlockchainProject = new AzureBlockchainProject( azureNames.consortium, uuid.v4(), uuid.v4(), [azureNames.member], ); const member = new Member(azureNames.member); const transactionNode = new AzureBlockchainNetworkNode(azureNames.transactionNode, uuid.v4(), '*', '', '', azureNames.member); member.addChild(transactionNode); azureBlockchainProject.addChild(member); const defaultPort = 8545; const defaultLabel = TestConstants.consortiumTestNames.local; const localProject = new LocalProject(defaultLabel, defaultPort); const defaultUrl = `${Constants.networkProtocols.http}${Constants.localhost}:${defaultPort}`; const localNetworkNode = new LocalNetworkNode(defaultLabel, defaultUrl, '*'); localProject.addChild(localNetworkNode); const infuraProject = new InfuraProject(uuid.v4(), uuid.v4()); const infuraNetworkNode = new InfuraNetworkNode(uuid.v4(), uuid.v4(), uuid.v4()); infuraProject.addChild(infuraNetworkNode); const bdmProject = new BlockchainDataManagerProject(uuid.v4(), uuid.v4(), uuid.v4()); const bdmNetworkNode = new BlockchainDataManagerNetworkNode( uuid.v4(), '*', uuid.v4(), uuid.v4(), [], ItemType.BLOCKCHAIN_DATA_MANAGER_APPLICATION, uuid.v4()); bdmProject.addChild(bdmNetworkNode); azureBlockchainService.addChild(azureBlockchainProject); localService.addChild(localProject); infuraService.addChild(infuraProject); bdmService.addChild(bdmProject); services.push(azureBlockchainService, localService, infuraService, bdmService); return services; } function getTestTruffleNetworks(): TruffleConfiguration.INetwork[] { const networks: TruffleConfiguration.INetwork[] = []; networks.push({ name: TestConstants.servicesNames.development, options: { host: '127.0.0.1', network_id: '*', port: 8545, }, }, { name: TestConstants.servicesNames.testNetwork, options: { gasPrice: 100000000000, network_id: 2, }, }); return networks; } function getDeployName(prefix: string, projectName: string, nodeName: string, args?: string[]): string { if (args) { return [prefix, projectName, ...args, nodeName].join('_'); } return [prefix, projectName, nodeName].join('_'); }
the_stack
import UniversalRouter, { Route } from './UniversalRouter' test('requires routes', () => { // @ts-expect-error missing argument expect(() => new UniversalRouter()).toThrow(/Invalid routes/) // @ts-expect-error wrong argument expect(() => new UniversalRouter(12)).toThrow(/Invalid routes/) // @ts-expect-error wrong argument expect(() => new UniversalRouter(null)).toThrow(/Invalid routes/) }) test('supports custom route resolver', async () => { const resolveRoute: jest.Mock = jest.fn((context) => context.route.component) const action: jest.Mock = jest.fn() const router = new UniversalRouter( { path: '/a', action, children: [ { path: '/:b', component: null, action } as Route, { path: '/c', component: 'c', action } as Route, { path: '/d', component: 'd', action } as Route, ], }, { resolveRoute }, ) await expect(router.resolve('/a/c')).resolves.toBe('c') expect(resolveRoute.mock.calls.length).toBe(3) expect(action.mock.calls.length).toBe(0) }) test('supports custom error handler', async () => { const errorHandler: jest.Mock = jest.fn(() => 'result') const router = new UniversalRouter([], { errorHandler }) await expect(router.resolve('/')).resolves.toBe('result') expect(errorHandler.mock.calls.length).toBe(1) const error = errorHandler.mock.calls[0][0] const context = errorHandler.mock.calls[0][1] expect(error).toBeInstanceOf(Error) expect(error.message).toBe('Route not found') expect(error.status).toBe(404) expect(context.pathname).toBe('/') expect(context.router).toBe(router) }) test('handles route errors', async () => { const errorHandler: jest.Mock = jest.fn(() => 'result') const route = { path: '/', action: (): never => { throw new Error('custom') }, } const router = new UniversalRouter(route, { errorHandler }) await expect(router.resolve('/')).resolves.toBe('result') expect(errorHandler.mock.calls.length).toBe(1) const error = errorHandler.mock.calls[0][0] const context = errorHandler.mock.calls[0][1] expect(error).toBeInstanceOf(Error) expect(error.message).toBe('custom') expect(context.pathname).toBe('/') expect(context.path).toBe('/') expect(context.router).toBe(router) expect(context.route).toBe(route) }) test('throws when route not found', async () => { const router = new UniversalRouter([]) let err try { await router.resolve('/') } catch (e) { err = e } expect(err).toBeInstanceOf(Error) expect(err.message).toBe('Route not found') expect(err.status).toBe(404) }) test("executes the matching route's action method and return its result", async () => { const action: jest.Mock = jest.fn(() => 'b') const router = new UniversalRouter({ path: '/a', action }) await expect(router.resolve('/a')).resolves.toBe('b') expect(action.mock.calls.length).toBe(1) expect(action.mock.calls[0][0]).toHaveProperty('path', '/a') }) test('finds the first route whose action method !== undefined or null', async () => { const action1: jest.Mock = jest.fn(() => undefined) const action2: jest.Mock = jest.fn(() => null) const action3: jest.Mock = jest.fn(() => 'c') const action4: jest.Mock = jest.fn(() => 'd') const router = new UniversalRouter([ { path: '/a', action: action1 }, { path: '/a', action: action2 }, { path: '/a', action: action3 }, { path: '/a', action: action4 }, ]) await expect(router.resolve('/a')).resolves.toBe('c') expect(action1.mock.calls.length).toBe(1) expect(action2.mock.calls.length).toBe(1) expect(action3.mock.calls.length).toBe(1) expect(action4.mock.calls.length).toBe(0) }) test('allows to pass context variables to action methods', async () => { const action: jest.Mock = jest.fn(() => true) const router = new UniversalRouter([{ path: '/a', action }]) await expect(router.resolve({ pathname: '/a', test: 'b' })).resolves.toBe(true) expect(action.mock.calls.length).toBe(1) expect(action.mock.calls[0][0]).toHaveProperty('path', '/a') expect(action.mock.calls[0][0]).toHaveProperty('test', 'b') }) test('skips action methods of routes that do not match the URL path', async () => { const action: jest.Mock = jest.fn() const router = new UniversalRouter([{ path: '/a', action }]) let err try { await router.resolve('/b') } catch (e) { err = e } expect(err).toBeInstanceOf(Error) expect(err.message).toBe('Route not found') expect(err.status).toBe(404) expect(action.mock.calls.length).toBe(0) }) test('supports asynchronous route actions', async () => { const router = new UniversalRouter([{ path: '/a', action: async (): Promise<string> => 'b' }]) await expect(router.resolve('/a')).resolves.toBe('b') }) test('captures URL parameters to context.params', async () => { const action: jest.Mock = jest.fn(() => true) const router = new UniversalRouter([{ path: '/:one/:two', action }]) await expect(router.resolve({ pathname: '/a/b' })).resolves.toBe(true) expect(action.mock.calls.length).toBe(1) expect(action.mock.calls[0][0]).toHaveProperty('params', { one: 'a', two: 'b' }) }) test('provides all URL parameters to each route', async () => { const action1: jest.Mock = jest.fn() const action2: jest.Mock = jest.fn(() => true) const router = new UniversalRouter([ { path: '/:one', action: action1, children: [ { path: '/:two', action: action2, }, ], }, ]) await expect(router.resolve({ pathname: '/a/b' })).resolves.toBe(true) expect(action1.mock.calls.length).toBe(1) expect(action1.mock.calls[0][0]).toHaveProperty('params', { one: 'a' }) expect(action2.mock.calls.length).toBe(1) expect(action2.mock.calls[0][0]).toHaveProperty('params', { one: 'a', two: 'b' }) }) test('overrides URL parameters with same name in child routes', async () => { const action1: jest.Mock = jest.fn() const action2: jest.Mock = jest.fn(() => true) const router = new UniversalRouter([ { path: '/:one', action: action1, children: [ { path: '/:one', action: action1, }, { path: '/:two', action: action2, }, ], }, ]) await expect(router.resolve({ pathname: '/a/b' })).resolves.toBe(true) expect(action1.mock.calls.length).toBe(2) expect(action1.mock.calls[0][0]).toHaveProperty('params', { one: 'a' }) expect(action1.mock.calls[1][0]).toHaveProperty('params', { one: 'b' }) expect(action2.mock.calls.length).toBe(1) expect(action2.mock.calls[0][0]).toHaveProperty('params', { one: 'a', two: 'b' }) }) test('does not collect parameters from previous routes', async () => { const action1: jest.Mock = jest.fn(() => undefined) const action2: jest.Mock = jest.fn(() => undefined) const action3: jest.Mock = jest.fn(() => true) const router = new UniversalRouter([ { path: '/:one', action: action1, children: [ { path: '/:two', action: action1, }, ], }, { path: '/:three', action: action2, children: [ { path: '/:four', action: action2, }, { path: '/:five', action: action3, }, ], }, ]) await expect(router.resolve({ pathname: '/a/b' })).resolves.toBe(true) expect(action1.mock.calls.length).toBe(2) expect(action1.mock.calls[0][0]).toHaveProperty('params', { one: 'a' }) expect(action1.mock.calls[1][0]).toHaveProperty('params', { one: 'a', two: 'b' }) expect(action2.mock.calls.length).toBe(2) expect(action2.mock.calls[0][0]).toHaveProperty('params', { three: 'a' }) expect(action2.mock.calls[1][0]).toHaveProperty('params', { three: 'a', four: 'b' }) expect(action3.mock.calls.length).toBe(1) expect(action3.mock.calls[0][0]).toHaveProperty('params', { three: 'a', five: 'b' }) }) test('supports next() across multiple routes', async () => { const log: number[] = [] const router = new UniversalRouter([ { path: '/test', children: [ { path: '', action(): void { log.push(2) }, children: [ { path: '', action({ next }): Promise<void> { log.push(3) return next().then(() => { log.push(6) }) }, children: [ { path: '', action({ next }): Promise<void> { log.push(4) return next().then(() => { log.push(5) }) }, }, ], }, ], }, { path: '', action(): void { log.push(7) }, children: [ { path: '', action(): void { log.push(8) }, }, { path: '(.*)', action(): void { log.push(9) }, }, ], }, ], async action({ next }): Promise<unknown> { log.push(1) const result = await next() log.push(10) return result }, }, { path: '/:id', action(): void { log.push(11) }, }, { path: '/test', action(): string { log.push(12) return 'done' }, }, { path: '/*', action(): void { log.push(13) }, }, ]) await expect(router.resolve('/test')).resolves.toBe('done') expect(log).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) }) test('supports next(true) across multiple routes', async () => { const log: number[] = [] const router = new UniversalRouter({ action({ next }): Promise<unknown> { log.push(1) return next().then((result) => { log.push(9) return result }) }, children: [ { path: '/a/b/c', action({ next }): Promise<unknown> { log.push(2) return next(true).then((result) => { log.push(8) return result }) }, }, { path: '/a', action(): void { log.push(3) }, children: [ { path: '/b', action({ next }): Promise<unknown> { log.push(4) return next().then((result) => { log.push(6) return result }) }, children: [ { path: '/c', action(): void { log.push(5) }, }, ], }, { path: '/b/c', action(): string { log.push(7) return 'done' }, }, ], }, ], }) await expect(router.resolve('/a/b/c')).resolves.toBe('done') expect(log).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]) }) test('supports parametrized routes', async () => { const action: jest.Mock = jest.fn(() => true) const router = new UniversalRouter([{ path: '/path/:a/other/:b', action }]) await expect(router.resolve('/path/1/other/2')).resolves.toBe(true) expect(action.mock.calls.length).toBe(1) expect(action.mock.calls[0][0]).toHaveProperty('params.a', '1') expect(action.mock.calls[0][0]).toHaveProperty('params.b', '2') expect(action.mock.calls[0][1]).toHaveProperty('a', '1') expect(action.mock.calls[0][1]).toHaveProperty('b', '2') }) test('supports nested routes (1)', async () => { const action1: jest.Mock = jest.fn() const action2: jest.Mock = jest.fn(() => true) const router = new UniversalRouter([ { path: '', action: action1, children: [ { path: '/a', action: action2, }, ], }, ]) await expect(router.resolve('/a')).resolves.toBe(true) expect(action1.mock.calls.length).toBe(1) expect(action1.mock.calls[0][0]).toHaveProperty('path', '') expect(action2.mock.calls.length).toBe(1) expect(action2.mock.calls[0][0]).toHaveProperty('path', '/a') }) test('supports nested routes (2)', async () => { const action1: jest.Mock = jest.fn() const action2: jest.Mock = jest.fn(() => true) const router = new UniversalRouter([ { path: '/a', action: action1, children: [ { path: '/b', action: action2, }, ], }, ]) await expect(router.resolve('/a/b')).resolves.toBe(true) expect(action1.mock.calls.length).toBe(1) expect(action1.mock.calls[0][0]).toHaveProperty('path', '/a') expect(action2.mock.calls.length).toBe(1) expect(action2.mock.calls[0][0]).toHaveProperty('path', '/b') }) test('supports nested routes (3)', async () => { const action1: jest.Mock = jest.fn(() => undefined) const action2: jest.Mock = jest.fn(() => null) const action3: jest.Mock = jest.fn(() => true) const router = new UniversalRouter([ { path: '/a', action: action1, children: [ { path: '/b', action: action2, }, ], }, { path: '/a/b', action: action3, }, ]) await expect(router.resolve('/a/b')).resolves.toBe(true) expect(action1.mock.calls.length).toBe(1) expect(action1.mock.calls[0][0]).toHaveProperty('baseUrl', '') expect(action1.mock.calls[0][0]).toHaveProperty('path', '/a') expect(action2.mock.calls.length).toBe(1) expect(action2.mock.calls[0][0]).toHaveProperty('baseUrl', '/a') expect(action2.mock.calls[0][0]).toHaveProperty('path', '/b') expect(action3.mock.calls.length).toBe(1) expect(action3.mock.calls[0][0]).toHaveProperty('baseUrl', '') expect(action3.mock.calls[0][0]).toHaveProperty('path', '/a/b') }) test('re-throws an error', async () => { const error = new Error('test error') const router = new UniversalRouter([ { path: '/a', action(): never { throw error }, }, ]) let err try { await router.resolve('/a') } catch (e) { err = e } expect(err).toBe(error) }) test('respects baseUrl', async () => { const action: jest.Mock = jest.fn(() => 17) const routes = { path: '/a', children: [ { path: '/b', children: [{ path: '/c', action }], }, ], } const router = new UniversalRouter(routes, { baseUrl: '/base' }) await expect(router.resolve('/base/a/b/c')).resolves.toBe(17) expect(action.mock.calls.length).toBe(1) expect(action.mock.calls[0][0]).toHaveProperty('pathname', '/base/a/b/c') expect(action.mock.calls[0][0]).toHaveProperty('path', '/c') expect(action.mock.calls[0][0]).toHaveProperty('baseUrl', '/base/a/b') expect(action.mock.calls[0][0]).toHaveProperty('route', routes.children[0].children[0]) expect(action.mock.calls[0][0]).toHaveProperty('router', router) let err try { await router.resolve('/a/b/c') } catch (e) { err = e } expect(action.mock.calls.length).toBe(1) expect(err).toBeInstanceOf(Error) expect(err.message).toBe('Route not found') expect(err.status).toBe(404) }) test('matches routes with trailing slashes', async () => { const router = new UniversalRouter([ { path: '/', action: (): string => 'a' }, { path: '/page/', action: (): string => 'b' }, { path: '/child', children: [ { path: '/', action: (): string => 'c' }, { path: '/page/', action: (): string => 'd' }, ], }, ]) await expect(router.resolve('/')).resolves.toBe('a') await expect(router.resolve('/page/')).resolves.toBe('b') await expect(router.resolve('/child/')).resolves.toBe('c') await expect(router.resolve('/child/page/')).resolves.toBe('d') }) test('skips nested routes when middleware route returns null', async () => { const middleware: jest.Mock = jest.fn(() => null) const action: jest.Mock = jest.fn(() => 'skipped') const router = new UniversalRouter([ { path: '/match', action: middleware, children: [{ action }], }, { path: '/match', action: (): number => 404, }, ]) await expect(router.resolve('/match')).resolves.toBe(404) expect(action.mock.calls.length).toBe(0) expect(middleware.mock.calls.length).toBe(1) }) test('matches nested routes when middleware route returns undefined', async () => { const middleware: jest.Mock = jest.fn(() => undefined) const action: jest.Mock = jest.fn(() => null) const router = new UniversalRouter([ { path: '/match', action: middleware, children: [{ action }], }, { path: '/match', action: (): number => 404, }, ]) await expect(router.resolve('/match')).resolves.toBe(404) expect(action.mock.calls.length).toBe(1) expect(middleware.mock.calls.length).toBe(1) }) test('handles route not found error correctly', async () => { const router = new UniversalRouter({ path: '/', action({ next }): unknown { return next() }, children: [{ path: '/child' }], }) let err try { await router.resolve('/404') } catch (e) { err = e } expect(err).toBeInstanceOf(Error) expect(err.message).toBe('Route not found') expect(err.status).toBe(404) }) test('handles malformed URI params', async () => { const router = new UniversalRouter({ path: '/:a', action: (ctx): object => ctx.params }) await expect(router.resolve('/%AF')).resolves.toStrictEqual({ a: '%AF' }) }) test('decodes params correctly', async () => { const router = new UniversalRouter({ path: '/:a/:b/:c', action: (ctx): object => ctx.params }) await expect(router.resolve('/%2F/%3A/caf%C3%A9')).resolves.toStrictEqual({ a: '/', b: ':', c: 'café', }) }) test('decodes repeated parameters correctly', async () => { const router = new UniversalRouter({ path: '/:a+', action: (ctx): object => ctx.params }) await expect(router.resolve('/x%2Fy/z/%20/%AF')).resolves.toStrictEqual({ a: ['x/y', 'z', ' ', '%AF'], }) }) test('matches 0 routes (1)', async () => { const action: jest.Mock = jest.fn(() => true) const route = { path: '/', action } await expect(new UniversalRouter(route).resolve('/a')).rejects.toThrow(/Route not found/) expect(action.mock.calls.length).toBe(0) }) test('matches 0 routes (2)', async () => { const action: jest.Mock = jest.fn(() => true) const route = { path: '/a', action } await expect(new UniversalRouter(route).resolve('/')).rejects.toThrow(/Route not found/) expect(action.mock.calls.length).toBe(0) }) test('matches 0 routes (3)', async () => { const action: jest.Mock = jest.fn(() => true) const route = { path: '/a', action, children: [{ path: '/b', action }] } await expect(new UniversalRouter(route).resolve('/b')).rejects.toThrow(/Route not found/) expect(action.mock.calls.length).toBe(0) }) test('matches 0 routes (4)', async () => { const action: jest.Mock = jest.fn(() => true) const route = { path: 'a', action, children: [{ path: 'b', action }] } await expect(new UniversalRouter(route).resolve('ab')).rejects.toThrow(/Route not found/) expect(action.mock.calls.length).toBe(0) }) test('matches 0 routes (5)', async () => { const action: jest.Mock = jest.fn(() => true) const route = { action } await expect(new UniversalRouter(route).resolve('/a')).rejects.toThrow(/Route not found/) expect(action.mock.calls.length).toBe(0) }) test('matches 0 routes (6)', async () => { const action: jest.Mock = jest.fn(() => true) const route = { path: '/', action } await expect(new UniversalRouter(route).resolve('')).rejects.toThrow(/Route not found/) expect(action.mock.calls.length).toBe(0) }) test('matches 0 routes (7)', async () => { const action: jest.Mock = jest.fn(() => true) const route = { path: '/:a+', action, children: [] } await expect(new UniversalRouter(route).resolve('')).rejects.toThrow(/Route not found/) expect(action.mock.calls.length).toBe(0) }) test('matches 1 route (1)', async () => { const action: jest.Mock = jest.fn(() => true) const route = { path: '/', action, } await expect(new UniversalRouter(route).resolve('/')).resolves.toBe(true) expect(action.mock.calls.length).toBe(1) const context = action.mock.calls[0][0] expect(context).toHaveProperty('baseUrl', '') expect(context).toHaveProperty('path', '/') expect(context).toHaveProperty('route.path', '/') }) test('matches 1 route (2)', async () => { const action: jest.Mock = jest.fn(() => true) const route = { path: '/a', action, } await expect(new UniversalRouter(route).resolve('/a')).resolves.toBe(true) expect(action.mock.calls.length).toBe(1) const context = action.mock.calls[0][0] expect(context).toHaveProperty('baseUrl', '') expect(context).toHaveProperty('path', '/a') expect(context).toHaveProperty('route.path', '/a') }) test('matches 2 routes (1)', async () => { const action: jest.Mock = jest.fn(() => undefined) const route = { path: '', action, children: [ { path: '/a', action, }, ], } await expect(new UniversalRouter(route).resolve('/a')).rejects.toThrow(/Route not found/) expect(action.mock.calls.length).toBe(2) const context1 = action.mock.calls[0][0] expect(context1).toHaveProperty('baseUrl', '') expect(context1).toHaveProperty('path', '') expect(context1).toHaveProperty('route.path', '') const context2 = action.mock.calls[1][0] expect(context2).toHaveProperty('baseUrl', '') expect(context2).toHaveProperty('path', '/a') expect(context2).toHaveProperty('route.path', '/a') }) test('matches 2 routes (2)', async () => { const action: jest.Mock = jest.fn(() => undefined) const route = { path: '/a', action, children: [ { path: '/b', action, children: [ { path: '/c', action, }, ], }, ], } await expect(new UniversalRouter(route).resolve('/a/b/c')).rejects.toThrow(/Route not found/) expect(action.mock.calls.length).toBe(3) const context1 = action.mock.calls[0][0] expect(context1).toHaveProperty('baseUrl', '') expect(context1).toHaveProperty('route.path', '/a') const context2 = action.mock.calls[1][0] expect(context2).toHaveProperty('baseUrl', '/a') expect(context2).toHaveProperty('route.path', '/b') const context3 = action.mock.calls[2][0] expect(context3).toHaveProperty('baseUrl', '/a/b') expect(context3).toHaveProperty('route.path', '/c') }) test('matches 2 routes (3)', async () => { const action: jest.Mock = jest.fn(() => undefined) const route = { path: '', action, children: [ { path: '', action, }, ], } await expect(new UniversalRouter(route).resolve('/')).rejects.toThrow(/Route not found/) expect(action.mock.calls.length).toBe(2) const context1 = action.mock.calls[0][0] expect(context1).toHaveProperty('baseUrl', '') expect(context1).toHaveProperty('route.path', '') const context2 = action.mock.calls[1][0] expect(context2).toHaveProperty('baseUrl', '') expect(context2).toHaveProperty('route.path', '') }) test('matches an array of paths', async () => { const action: jest.Mock = jest.fn(() => true) const route = { path: ['/e', '/f'], action } await expect(new UniversalRouter(route).resolve('/f')).resolves.toBe(true) expect(action.mock.calls.length).toBe(1) const context = action.mock.calls[0][0] expect(context).toHaveProperty('baseUrl', '') expect(context).toHaveProperty('route.path', ['/e', '/f']) })
the_stack
type bool = number; declare function hexdump(target: NativePointer, options?: object): void; declare function int64(v: string | number): Int64; declare function uint64(v: string | number): UInt64; declare function ptr(v: string | number): NativePointer; declare var NULL: NativePointer; // TODO: recv([type, ]callback) declare function recv(callback); declare function send(message, data?); declare function setTimeout(fn, delay); declare function clearTimeout(id); declare function setInterval(fn, delay); declare function clearInterval(id); declare var rpc: { exports: {} } declare namespace Frida { var version: string; } declare namespace Process { var arch: string; var platform: string; var pageSize: number; var pointerSize: number; function isDebuggerAttached(); function getCurrentThreadId(); function enumerateThreads(callbacks: { onMatch: (thread) => string, onComplete: () => void }); function enumerateThreadsSync(): Array<any>; function findModuleByAddress(address); function getModuleByAddress(address); function findModuleByName(name); function getModuleByName(name); function enumerateModules(callbacks: { onMatch: (module) => string, onComplete: () => void }); function enumerateModulesSync(); function findRangeByAddress(address); function getRangeByAddress(address); function enumerateRanges(protection_or_specifier, callbacks: { onMatch: (range) => string, onComplete: () => void }); function enumerateRangesSync(protection_or_specifier); function enumerateMallocRanges(callbacks: { onMatch: (range) => string, onComplete: () => void }); function enumerateMallocRangesSync(protection); } declare namespace Module { function enumerateImports(name, callbacks: { onMatch: (imp) => string, onComplete: () => void }); function enumerateImportsSync(name); function enumerateExports(name, callbacks: { onMatch: (imp) => string, onComplete: () => void }); function enumerateExportsSync(name); function enumerateRanges(name, protection, callbacks: { onMatch: (range) => string, onComplete: () => void }); function enumerateRangesSync(name, protection); function findBaseAddress(name); function findExportByName(module: string | null, exp: string): NativePointer | null; function getExportByName(module: string | null, exp: string): NativePointer; } declare namespace Memory { function scan(address, size, pattern, callbacks: { onMatch: (address, size) => string, onError: (reason) => void, onComplete: () => void }); function scanSync(address, size, pattern); function alloc(size): NativePointer; function copy(dst, src, n); function dup(address, size); function protect(address, size, protection); function allocUtf8String(str): NativePointer; function allocUtf16String(str): NativePointer; function allocAnsiString(str): NativePointer; function patchCode(address, size, apply): void; } declare namespace MemoryAccessMonitor { function enable(ranges, callbacks: { onAccess: (details) => void }); function disable(); } declare namespace Thread { function backtrace(context?, backtracer?: Backtracer); function sleep(delay: number); } declare enum Backtracer { ACCURATE, FUZZY } declare class Int64 { constructor(v); add(rhs: Int64 | number): Int64; sub(rhs: Int64 | number): Int64; and(rhs: Int64 | number): Int64; or(rhs: Int64 | number): Int64; xor(rhs: Int64 | number): Int64; shr(n: number): Int64; shl(n: number): Int64; compare(rhs: Int64 | number); toNumber(): number; toString(radix?); } declare class UInt64 { constructor(v); add(rhs: UInt64 | number): UInt64; sub(rhs: UInt64 | number): UInt64; and(rhs: UInt64 | number): UInt64; or(rhs: UInt64 | number): UInt64; xor(rhs: UInt64 | number): UInt64; shr(n: number): UInt64; shl(n: number): UInt64; compare(rhs: UInt64 | number); toNumber(): number; toString(radix?); } declare class X86Writer { offset: number; constructor(codeAddress: NativePointer, options?: object); flush(); putRet(); putRetImm(immValue: number); putPopReg(reg: string); putMovRegReg(dstReg: string, srcReg: string); putAddRegImm(dstReg: string, immValue: number); putSubRegImm(dstReg: string, immValue: number); putCallAddress(address: NativePointer); putU8(value: number); putBytes(data: ArrayBuffer); putPushReg(reg: string); } declare class NativePointer { constructor(s); add(rhs: NativePointer | number): NativePointer; sub(rhs: NativePointer | number): NativePointer; and(rhs: NativePointer | number): NativePointer; or(rhs: NativePointer | number): NativePointer; xor(rhs: NativePointer | number): NativePointer; shr(n: number): NativePointer; shl(n: number): NativePointer; equals(rhs: NativePointer); compare(rhs: NativePointer | number); toInt32(): number; toString(radix?); toMatchPattern(): string; readPointer(): NativePointer; writePointer(ptr: NativePointer); readS8(): number; readU8(): number; readS16(): number; readU16(): number; readS32(): number; readU32(): number; // readShort(address); // readUShort(address); // readInt(address); // readUInt(address); readFloat(): number; // readDouble(address); // writeS8(address, value); // writeU8(address, value); // writeS16(address, value); // writeU16(address, value); // writeS32(address, value); writeU32(value: number); // writeShort(address, value); // writeUShort(address, value); // writeInt(address, value); // writeUInt(address, value); writeFloat(value: number); // writeDouble(address, value); // readS64(address): Int64; readU64(): UInt64; // readLong(address): Int64; // readULong(address): UInt64; // writeS64(address, value: Int64); writeU64(value: number); // writeLong(address, value: Int64); // writeULong(address, value: UInt64); // readByteArray(address, length): ArrayBuffer; // writeByteArray(address, bytes: ArrayBuffer | Array<any>); readCString(size?: number): string; readUtf8String(size?: number) : string; readUtf16String(length?: number): string; // readAnsiString(address, size?); // writeUtf8String(address, str); // writeUtf16String(address, str); // writeAnsiString(address, str); toJSON(): string; } interface NativeFunction { (...args: Array<NativePointer|number>); } declare class NativeFunction extends NativePointer { constructor(address: NativePointer, returnType: string, argTypes: Array<string>, abi?: string); } declare class NativeCallback extends NativePointer { constructor(func, returnType, argTypes, abi?); } declare namespace Socket { function type(handle): string; function localAddress(handle): { ip: string, port: number, path: string }; function peerAddress(handle): { ip: string, port: number, path: string }; } declare abstract class Stream { close(); } declare abstract class InputStream extends Stream { // TODO: the read and readAll functions return type should be Promise<ArrayBuffer> read(size: number): any; readAll(size: number): any; } declare abstract class OutputStream extends Stream { write(data: ArrayBuffer | Array<number>): any; writeAll(data: ArrayBuffer | Array<number>): any; } declare class UnixInputStream extends InputStream { constructor(fd, options?: { autoClose: boolean }); } declare class UnixOutputStream extends OutputStream { constructor(fd, options?: { autoClose: boolean }); } declare class Win32InputStream extends InputStream { constructor(handle, options?: { autoClose: boolean }); } declare class Win32OutputStream extends OutputStream { constructor(handle, options?: { autoClose: boolean }); } // Cannot define class File, because of default typescript definition in lib.d.ts // declare class File { // } declare interface InvocationListener { detach(): void; } declare namespace Interceptor { function attach(target: NativePointer, callbacks: { onEnter: (args) => void, onLeave?: (retval: NativePointer) => void }): InvocationListener; function detachAll(); function replace(target: NativePointer, replacement: NativeCallback); function revert(target: NativePointer); } declare namespace Stalker { function follow(threadId?, options?: { events: { call: boolean, ret: boolean, exec: boolean }, onReceive: (events) => void, onCallSummary: (summary) => void }); function unfollow(threadId?); function garbageCollect(); function addCallProbe(address, callback: (args) => void); var thrustThreshold: number; var queueCapacity: number; var queueDrainInterval: number; } declare class ApiResolver { constructor(type); enumerateMatches(query: string, callbacks: { onMatch: (match) => void, onComplete: () => void }); enumerateMatchesSync(query: string); } declare namespace DebugSymbol { function fromAddress(address); function getFunctionByName(name: string): NativePointer; function findFunctionsNamed(name: string): NativePointer[]; function findFunctionsMatching(glob: string): NativePointer[]; } declare namespace Instruction { function parse(target: NativePointer); } declare namespace ObjC { var available: boolean; var api: any; var classes: any; var protocols: any; var mainQueue: any; function schedule(queue, work); class Object { constructor(handle: NativePointer, protocol?); $kind: string; $super: ObjC.Object; $superClass: ObjC.Object; $class: ObjC.Object; $className: string; $protocols: ObjC.Protocol[]; $methods: string[]; equals(other: ObjC.Object): boolean; } class Protocol { constructor(handle: NativePointer); } function implement(method, fn): NativeCallback; function registerProxy(properties: { protocols?, methods?, events?}); function registerClass(properties: { name?, super?, protocols?, methods?}); function registerProtocol(properties: { name?, protocols?, methods?}); function bind(obj: ObjC.Object, data); function unbind(obj: ObjC.Object); function getBoundData(obj: ObjC.Object); function choose(specifier, callbacks: { onMatch: (instance) => void, onComplete: () => void }); function chooseSync(specifier); function selector(name: string); function selectorAsString(sel): string; } declare namespace Java { var available: boolean; function enumerateLoadedClasses(callbacks: { onMatch: (className) => void, onComplete: () => void }); function perform(fn); function use(className); function choose(className, callbacks: { onMatch: (instance) => string | void, onComplete: () => void }); function cast(handle, klass); } declare namespace WeakRef { function bind(value, fn); function unbind(id); }
the_stack
import test from 'ava'; import * as sinon from 'sinon'; import * as common from '../../../common'; import {clone} from '../../../common'; import * as Api from '../api/v2'; import {ActionsSdkConversationOptions, ActionsSdkConversation} from '../conv'; import {Permission} from '..'; const CONVERSATION_ID = '1234'; const USER_ID = 'abcd'; function buildRequest( convType: string, intent: string, data?: {} ): Api.GoogleActionsV2AppRequest { const appRequest = { conversation: { conversationId: CONVERSATION_ID, type: convType, conversationToken: data, }, user: { userId: USER_ID, locale: 'en_US', }, inputs: [ { intent, rawInputs: [ { inputType: 'KEYBOARD', query: 'Talk to my test app', }, ], }, ], surface: { capabilities: [ { name: 'actions.capability.SCREEN_OUTPUT', }, { name: 'actions.capability.MEDIA_RESPONSE_AUDIO', }, { name: 'actions.capability.WEB_BROWSER', }, { name: 'actions.capability.AUDIO_OUTPUT', }, ], }, availableSurfaces: [ { capabilities: [ { name: 'actions.capability.SCREEN_OUTPUT', }, { name: 'actions.capability.AUDIO_OUTPUT', }, ], }, ], } as Api.GoogleActionsV2AppRequest; return appRequest; } test('new conversation', t => { const intent = 'actions.intent.MAIN'; const appRequest = buildRequest('NEW', intent, ''); const options = { body: appRequest, headers: {}, } as ActionsSdkConversationOptions<{}, {}>; const conv = new ActionsSdkConversation(options); t.is(conv.body, appRequest); t.is(conv.intent, intent); t.is(conv.id, CONVERSATION_ID); t.is(conv.type, 'NEW'); t.false(conv.digested); t.deepEqual(conv.data, {}); }); test('data is parsed from init', t => { const intent = 'example.intent.foo'; const sessionData = { foo: 'bar', }; const appRequest = buildRequest('ACTIVE', intent); const options = { body: appRequest, headers: {}, init: { data: sessionData, }, } as ActionsSdkConversationOptions<{}, {}>; const conv = new ActionsSdkConversation(options); t.deepEqual(conv.data, sessionData); }); test('data is parsed from conversation token', t => { const intent = 'example.intent.foo'; const sessionData = { foo: 'bar', }; const data = { data: sessionData, }; const appRequest = buildRequest('ACTIVE', intent, JSON.stringify(data)); const options = { body: appRequest, headers: {}, } as ActionsSdkConversationOptions<{}, {}>; const conv = new ActionsSdkConversation(options); t.deepEqual(conv.data, sessionData); }); test('conv.data is parsed correctly', t => { const data = { a: '1', b: '2', c: { d: '3', e: '4', }, }; const conv = new ActionsSdkConversation({ body: { conversation: { conversationToken: JSON.stringify({data}), }, } as Api.GoogleActionsV2AppRequest, }); t.deepEqual(conv.data, data); }); test('conv generates no conversationToken from empty conv.data', t => { const response = "What's up?"; const conv = new ActionsSdkConversation(); t.deepEqual(conv.data, {}); conv.ask(response); t.deepEqual(clone(conv.serialize()), { expectUserResponse: true, expectedInputs: [ { inputPrompt: { richInitialPrompt: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, possibleIntents: [ { intent: 'actions.intent.TEXT', }, ], }, ], }); }); test('conv generates first conv.data replaced correctly', t => { const response = "What's up?"; const data = { a: '1', b: '2', c: { d: '3', e: '4', }, }; const conv = new ActionsSdkConversation(); t.deepEqual(conv.data, {}); conv.ask(response); conv.data = data; t.deepEqual(clone(conv.serialize()), { expectUserResponse: true, expectedInputs: [ { inputPrompt: { richInitialPrompt: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, possibleIntents: [ { intent: 'actions.intent.TEXT', }, ], }, ], conversationToken: JSON.stringify({data}), }); }); test('conv generates first conv.data mutated correctly', t => { const response = "What's up?"; const a = '7'; const conv = new ActionsSdkConversation<{a?: string}>(); t.deepEqual(conv.data, {}); conv.ask(response); conv.data.a = a; t.deepEqual(clone(conv.serialize()), { expectUserResponse: true, expectedInputs: [ { inputPrompt: { richInitialPrompt: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, possibleIntents: [ { intent: 'actions.intent.TEXT', }, ], }, ], conversationToken: JSON.stringify({data: {a}}), }); }); test('conv generates different conv.data correctly', t => { const response = "What's up?"; const data = { a: '1', b: '2', c: { d: '3', e: '4', }, }; const e = '6'; const conv = new ActionsSdkConversation<typeof data>({ body: { conversation: { conversationToken: JSON.stringify({data}), }, } as Api.GoogleActionsV2AppRequest, }); t.deepEqual(conv.data, data); conv.ask(response); conv.data.c.e = e; t.deepEqual(clone(conv.serialize()), { expectUserResponse: true, expectedInputs: [ { inputPrompt: { richInitialPrompt: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, possibleIntents: [ { intent: 'actions.intent.TEXT', }, ], }, ], conversationToken: JSON.stringify({ data: { a: '1', b: '2', c: { d: '3', e, }, }, }), }); }); test('conv generates different conv.data correctly when only with init data', t => { const response = "What's up?"; const data = { a: '1', b: '2', c: { d: '3', e: '4', }, }; const a = '7'; const conv = new ActionsSdkConversation<typeof data>({ body: { conversation: { conversationToken: JSON.stringify({data}), }, } as Api.GoogleActionsV2AppRequest, init: { data, }, }); t.deepEqual(conv.data, data); conv.ask(response); conv.data.a = a; t.deepEqual(clone(conv.serialize()), { expectUserResponse: true, expectedInputs: [ { inputPrompt: { richInitialPrompt: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, possibleIntents: [ { intent: 'actions.intent.TEXT', }, ], }, ], conversationToken: JSON.stringify({ data: { a, b: '2', c: { d: '3', e: '4', }, }, }), }); }); test('conv generates same conv.data persisted', t => { const response = "What's up?"; const data = { a: '1', b: '2', c: { d: '3', e: '4', }, }; const conv = new ActionsSdkConversation<typeof data>({ body: { conversation: { conversationToken: JSON.stringify({data}), }, } as Api.GoogleActionsV2AppRequest, }); t.deepEqual(conv.data, data); conv.ask(response); t.deepEqual(clone(conv.serialize()), { expectUserResponse: true, expectedInputs: [ { inputPrompt: { richInitialPrompt: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, possibleIntents: [ { intent: 'actions.intent.TEXT', }, ], }, ], conversationToken: JSON.stringify({data}), }); }); test('conv sends userStorage when it is not empty', t => { const response = "What's up?"; const data = { a: '1', b: '2', c: { d: '3', e: '4', }, }; const conv = new ActionsSdkConversation(); t.deepEqual(conv.user.storage, {}); conv.user.storage = data; conv.ask(response); t.deepEqual(clone(conv.serialize()), { expectUserResponse: true, expectedInputs: [ { inputPrompt: { richInitialPrompt: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, possibleIntents: [ { intent: 'actions.intent.TEXT', }, ], }, ], userStorage: JSON.stringify({data}), }); }); test('conv does not send userStorage when it is empty', t => { const response = "What's up?"; const conv = new ActionsSdkConversation(); t.deepEqual(conv.user.storage, {}); conv.ask(response); t.deepEqual(clone(conv.serialize()), { expectUserResponse: true, expectedInputs: [ { inputPrompt: { richInitialPrompt: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, possibleIntents: [ { intent: 'actions.intent.TEXT', }, ], }, ], }); }); test('conv sends correct ask response', t => { const response = "What's up?"; const conv = new ActionsSdkConversation(); conv.ask(response); t.deepEqual(clone(conv.serialize()), { expectUserResponse: true, expectedInputs: [ { inputPrompt: { richInitialPrompt: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, possibleIntents: [ { intent: 'actions.intent.TEXT', }, ], }, ], }); }); test('conv sends correct close response', t => { const response = 'Bye'; const conv = new ActionsSdkConversation(); conv.close(response); t.deepEqual(clone(conv.serialize()), { expectUserResponse: false, finalResponse: { richResponse: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, }); }); test('conv sends speechBiasingHints when set', t => { const response = 'What is your favorite color out of red, blue, and green?'; const biasing = ['red', 'blue', 'green']; const conv = new ActionsSdkConversation(); conv.speechBiasing = biasing; conv.ask(response); t.deepEqual(clone(conv.serialize()), { expectUserResponse: true, expectedInputs: [ { inputPrompt: { richInitialPrompt: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, possibleIntents: [ { intent: 'actions.intent.TEXT', }, ], speechBiasingHints: biasing, }, ], }); }); test('conv does not send inputPrompt when items are empty', t => { const conv = new ActionsSdkConversation(); conv.ask(new Permission({permissions: 'NAME'})); t.deepEqual(clone(conv.serialize()), { expectUserResponse: true, expectedInputs: [ { possibleIntents: [ { inputValueData: { '@type': 'type.googleapis.com/google.actions.v2.PermissionValueSpec', permissions: ['NAME'], }, intent: 'actions.intent.PERMISSION', }, ], }, ], }); });
the_stack
import {Env} from 'onnxruntime-common'; import {WebGLContext} from './backends/webgl/webgl-context'; export declare namespace Logger { export interface SeverityTypeMap { verbose: 'v'; info: 'i'; warning: 'w'; error: 'e'; fatal: 'f'; } export type Severity = keyof SeverityTypeMap; export type Provider = 'none'|'console'; /** * Logging config that used to control the behavior of logger */ export interface Config { /** * Specify the logging provider. 'console' by default */ provider?: Provider; /** * Specify the minimal logger serverity. 'warning' by default */ minimalSeverity?: Logger.Severity; /** * Whether to output date time in log. true by default */ logDateTime?: boolean; /** * Whether to output source information (Not yet supported). false by default */ logSourceLocation?: boolean; } export interface CategorizedLogger { verbose(content: string): void; info(content: string): void; warning(content: string): void; error(content: string): void; fatal(content: string): void; } } // eslint-disable-next-line @typescript-eslint/no-redeclare export interface Logger { (category: string): Logger.CategorizedLogger; verbose(content: string): void; verbose(category: string, content: string): void; info(content: string): void; info(category: string, content: string): void; warning(content: string): void; warning(category: string, content: string): void; error(content: string): void; error(category: string, content: string): void; fatal(content: string): void; fatal(category: string, content: string): void; /** * Reset the logger configuration. * @param config specify an optional default config */ reset(config?: Logger.Config): void; /** * Set the logger's behavior on the given category * @param category specify a category string. If '*' is specified, all previous configuration will be overwritten. If * '' is specified, the default behavior will be updated. * @param config the config object to indicate the logger's behavior */ set(category: string, config: Logger.Config): void; /** * Set the logger's behavior from ort-common env * @param env the env used to set logger. Currently only setting loglevel is supported through Env. */ setWithEnv(env: Env): void; } interface LoggerProvider { log(severity: Logger.Severity, content: string, category?: string): void; } class NoOpLoggerProvider implements LoggerProvider { log(_severity: Logger.Severity, _content: string, _category?: string) { // do nothing } } class ConsoleLoggerProvider implements LoggerProvider { log(severity: Logger.Severity, content: string, category?: string) { // eslint-disable-next-line no-console console.log(`${this.color(severity)} ${category ? '\x1b[35m' + category + '\x1b[0m ' : ''}${content}`); } private color(severity: Logger.Severity) { switch (severity) { case 'verbose': return '\x1b[34;40mv\x1b[0m'; case 'info': return '\x1b[32mi\x1b[0m'; case 'warning': return '\x1b[30;43mw\x1b[0m'; case 'error': return '\x1b[31;40me\x1b[0m'; case 'fatal': return '\x1b[101mf\x1b[0m'; default: throw new Error(`unsupported severity: ${severity}`); } } } const SEVERITY_VALUE = { verbose: 1000, info: 2000, warning: 4000, error: 5000, fatal: 6000 }; const LOGGER_PROVIDER_MAP: {readonly [provider: string]: Readonly<LoggerProvider>} = { ['none']: new NoOpLoggerProvider(), ['console']: new ConsoleLoggerProvider() }; const LOGGER_DEFAULT_CONFIG = { provider: 'console', minimalSeverity: 'warning', logDateTime: true, logSourceLocation: false }; let LOGGER_CONFIG_MAP: {[category: string]: Readonly<Required<Logger.Config>>} = {['']: LOGGER_DEFAULT_CONFIG as Required<Logger.Config>}; function log(category: string): Logger.CategorizedLogger; function log(severity: Logger.Severity, content: string): void; function log(severity: Logger.Severity, category: string, content: string): void; function log(severity: Logger.Severity, arg1: string, arg2?: string): void; function log( arg0: string|Logger.Severity, arg1?: string, arg2?: string|number, arg3?: number): Logger.CategorizedLogger|void { if (arg1 === undefined) { // log(category: string): Logger.CategorizedLogger; return createCategorizedLogger(arg0); } else if (arg2 === undefined) { // log(severity, content); logInternal(arg0 as Logger.Severity, arg1, 1); } else if (typeof arg2 === 'number' && arg3 === undefined) { // log(severity, content, stack) logInternal(arg0 as Logger.Severity, arg1, arg2); } else if (typeof arg2 === 'string' && arg3 === undefined) { // log(severity, category, content) logInternal(arg0 as Logger.Severity, arg2, 1, arg1); } else if (typeof arg2 === 'string' && typeof arg3 === 'number') { // log(severity, category, content, stack) logInternal(arg0 as Logger.Severity, arg2, arg3, arg1); } else { throw new TypeError('input is valid'); } } function createCategorizedLogger(category: string): Logger.CategorizedLogger { return { verbose: log.verbose.bind(null, category), info: log.info.bind(null, category), warning: log.warning.bind(null, category), error: log.error.bind(null, category), fatal: log.fatal.bind(null, category) }; } // NOTE: argument 'category' is put the last parameter beacause typescript // doesn't allow optional argument put in front of required argument. This // order is different from a usual logging API. function logInternal(severity: Logger.Severity, content: string, stack: number, category?: string) { const config = LOGGER_CONFIG_MAP[category || ''] || LOGGER_CONFIG_MAP['']; if (SEVERITY_VALUE[severity] < SEVERITY_VALUE[config.minimalSeverity]) { return; } if (config.logDateTime) { content = `${new Date().toISOString()}|${content}`; } if (config.logSourceLocation) { // TODO: calculate source location from 'stack' } LOGGER_PROVIDER_MAP[config.provider].log(severity, content, category); } // eslint-disable-next-line @typescript-eslint/no-namespace namespace log { export function verbose(content: string): void; export function verbose(category: string, content: string): void; export function verbose(arg0: string, arg1?: string) { log('verbose', arg0, arg1); } export function info(content: string): void; export function info(category: string, content: string): void; export function info(arg0: string, arg1?: string) { log('info', arg0, arg1); } export function warning(content: string): void; export function warning(category: string, content: string): void; export function warning(arg0: string, arg1?: string) { log('warning', arg0, arg1); } export function error(content: string): void; export function error(category: string, content: string): void; export function error(arg0: string, arg1?: string) { log('error', arg0, arg1); } export function fatal(content: string): void; export function fatal(category: string, content: string): void; export function fatal(arg0: string, arg1?: string) { log('fatal', arg0, arg1); } export function reset(config?: Logger.Config): void { LOGGER_CONFIG_MAP = {}; set('', config || {}); } export function set(category: string, config: Logger.Config): void { if (category === '*') { reset(config); } else { const previousConfig = LOGGER_CONFIG_MAP[category] || LOGGER_DEFAULT_CONFIG; LOGGER_CONFIG_MAP[category] = { provider: config.provider || previousConfig.provider, minimalSeverity: config.minimalSeverity || previousConfig.minimalSeverity, logDateTime: (config.logDateTime === undefined) ? previousConfig.logDateTime : config.logDateTime, logSourceLocation: (config.logSourceLocation === undefined) ? previousConfig.logSourceLocation : config.logSourceLocation }; } // TODO: we want to support wildcard or regex? } export function setWithEnv(env: Env): void { const config: Logger.Config = {}; if (env.logLevel) { config.minimalSeverity = env.logLevel as Logger.Severity; } set('', config); } } // eslint-disable-next-line @typescript-eslint/no-redeclare, @typescript-eslint/naming-convention export const Logger: Logger = log; export declare namespace Profiler { export interface Config { maxNumberEvents?: number; flushBatchSize?: number; flushIntervalInMilliseconds?: number; } export type EventCategory = 'session'|'node'|'op'|'backend'; export interface Event { end(): void|Promise<void>; } } // TODO // class WebGLEvent implements Profiler.Event {} class Event implements Profiler.Event { constructor( public category: Profiler.EventCategory, public name: string, public startTime: number, private endCallback: (e: Event) => void|Promise<void>, public timer?: WebGLQuery, public ctx?: WebGLContext) {} end() { return this.endCallback(this); } async checkTimer(): Promise<number> { if (this.ctx === undefined || this.timer === undefined) { throw new Error('No webgl timer found'); } else { this.ctx.endTimer(); return this.ctx.waitForQueryAndGetTime(this.timer); } } } class EventRecord { constructor( public category: Profiler.EventCategory, public name: string, public startTime: number, public endTime: number) {} } export class Profiler { static create(config?: Profiler.Config): Profiler { if (config === undefined) { return new this(); } return new this(config.maxNumberEvents, config.flushBatchSize, config.flushIntervalInMilliseconds); } private constructor(maxNumberEvents?: number, flushBatchSize?: number, flushIntervalInMilliseconds?: number) { this._started = false; this._maxNumberEvents = maxNumberEvents === undefined ? 10000 : maxNumberEvents; this._flushBatchSize = flushBatchSize === undefined ? 10 : flushBatchSize; this._flushIntervalInMilliseconds = flushIntervalInMilliseconds === undefined ? 5000 : flushIntervalInMilliseconds; } // start profiling start() { this._started = true; this._timingEvents = []; this._flushTime = now(); this._flushPointer = 0; } // stop profiling stop() { this._started = false; for (; this._flushPointer < this._timingEvents.length; this._flushPointer++) { this.logOneEvent(this._timingEvents[this._flushPointer]); } } // create an event scope for the specific function event<T>(category: Profiler.EventCategory, name: string, func: () => T, ctx?: WebGLContext): T; event<T>(category: Profiler.EventCategory, name: string, func: () => Promise<T>, ctx?: WebGLContext): Promise<T>; event<T>(category: Profiler.EventCategory, name: string, func: () => T | Promise<T>, ctx?: WebGLContext): T |Promise<T> { const event = this._started ? this.begin(category, name, ctx) : undefined; let isPromise = false; const res = func(); // we consider a then-able object is a promise if (res && typeof (res as Promise<T>).then === 'function') { isPromise = true; return new Promise<T>((resolve, reject) => { (res as Promise<T>) .then( async value => { // fulfilled if (event) { await event.end(); } resolve(value); }, async reason => { // rejected if (event) { await event.end(); } reject(reason); }); }); } if (!isPromise && event) { const eventRes = event.end(); if (eventRes && typeof eventRes.then === 'function') { return new Promise<T>((resolve, reject) => { (eventRes).then( () => { // fulfilled resolve(res); }, (reason) => { // rejected reject(reason); }); }); } } return res; } // begin an event begin(category: Profiler.EventCategory, name: string, ctx?: WebGLContext): Event { if (!this._started) { throw new Error('profiler is not started yet'); } if (ctx === undefined) { const startTime = now(); this.flush(startTime); return new Event(category, name, startTime, e => this.endSync(e)); } else { const timer: WebGLQuery = ctx.beginTimer(); return new Event(category, name, 0, async e => this.end(e), timer, ctx); } } // end the specific event private async end(event: Event): Promise<void> { const endTime: number = await event.checkTimer(); if (this._timingEvents.length < this._maxNumberEvents) { this._timingEvents.push(new EventRecord(event.category, event.name, event.startTime, endTime)); this.flush(endTime); } } private endSync(event: Event): void { const endTime: number = now(); if (this._timingEvents.length < this._maxNumberEvents) { this._timingEvents.push(new EventRecord(event.category, event.name, event.startTime, endTime)); this.flush(endTime); } } private logOneEvent(event: EventRecord) { Logger.verbose( `Profiler.${event.category}`, `${(event.endTime - event.startTime).toFixed(2)}ms on event '${event.name}' at ${event.endTime.toFixed(2)}`); } private flush(currentTime: number) { if (this._timingEvents.length - this._flushPointer >= this._flushBatchSize || currentTime - this._flushTime >= this._flushIntervalInMilliseconds) { // should flush when either batch size accumlated or interval elepsed for (const previousPointer = this._flushPointer; this._flushPointer < previousPointer + this._flushBatchSize && this._flushPointer < this._timingEvents.length; this._flushPointer++) { this.logOneEvent(this._timingEvents[this._flushPointer]); } this._flushTime = now(); } } get started() { return this._started; } private _started = false; private _timingEvents: EventRecord[]; private readonly _maxNumberEvents: number; private readonly _flushBatchSize: number; private readonly _flushIntervalInMilliseconds: number; private _flushTime: number; private _flushPointer = 0; } /** * returns a number to represent the current timestamp in a resolution as high as possible. */ export const now = (typeof performance !== 'undefined' && performance.now) ? () => performance.now() : Date.now;
the_stack
import { expect } from 'chai'; import * as fs from 'fs'; import * as path from 'path'; import * as oniguruma from 'vscode-oniguruma'; import * as vsctm from 'vscode-textmate'; describe('TextMate grammar tests', async () => { before(async () => { // prepare grammar parser const nodeModulesDir = path.join(__dirname, '..', '..', '..', '..', '..', '..', 'node_modules'); const onigWasmPath = path.join(nodeModulesDir, 'vscode-oniguruma', 'release', 'onig.wasm'); const wasmBin = fs.readFileSync(onigWasmPath).buffer; await oniguruma.loadWASM(wasmBin); }); // prepare grammar scope loader const grammarDir = path.join(__dirname, '..', '..', '..', '..', '..', '..', 'syntaxes'); const registry = new vsctm.Registry({ onigLib: Promise.resolve({ createOnigScanner: (sources) => new oniguruma.OnigScanner(sources), createOnigString: (str) => new oniguruma.OnigString(str) }), loadGrammar: (scopeName) => { return new Promise<vsctm.IRawGrammar | null>((resolve, reject) => { const grammarFileName = `${scopeName}.tmGrammar.json`; const grammarFilePath = path.join(grammarDir, grammarFileName); let contents: string; if (!fs.existsSync(grammarFilePath)) { // tests can't delegate to well-known languages because those grammars aren't in this repo, so we create a catch-all const emptyGrammar = { scopeName, patterns: [ { name: `language.line.${scopeName}`, match: '^.*$' } ] }; contents = JSON.stringify(emptyGrammar); } else { const buffer = fs.readFileSync(grammarFilePath); contents = buffer.toString('utf-8'); } const grammar = vsctm.parseRawGrammar(contents, grammarFilePath); resolve(grammar); }); } }); async function getTokens(text: Array<string>, initialScope?: string): Promise<Array<Array<any>>> { const grammar = await registry.loadGrammar(initialScope ?? 'source.dotnet-interactive'); let ruleStack = vsctm.INITIAL; let allTokens = []; for (let i = 0; i < text.length; i++) { let lineTokens = []; const line = text[i]; const parsedLineTokens = grammar!.tokenizeLine(line, ruleStack); for (let j = 0; j < parsedLineTokens.tokens.length; j++) { const token = parsedLineTokens.tokens[j]; const tokenText = line.substring(token.startIndex, token.endIndex); lineTokens.push({ tokenText, scopes: token.scopes }); } allTokens.push(lineTokens); ruleStack = parsedLineTokens.ruleStack; } return allTokens; } it('all supported language specifiers', async () => { const text = [ '#!csharp', '#!cs', '#!fsharp', '#!fs', '#!html', '#!javascript', '#!js', '#!markdown', '#!md', '#!powershell', '#!pwsh', '#!sql', '#!sql-adventureworks', '#!kql', '#!kql-default', ]; const tokens = await getTokens(text); expect(tokens).to.deep.equal([ [ { tokenText: '#!csharp', scopes: ['source.dotnet-interactive', 'language.switch.csharp'] } ], [ { tokenText: '#!cs', scopes: ['source.dotnet-interactive', 'language.switch.csharp'] } ], [ { tokenText: '#!fsharp', scopes: ['source.dotnet-interactive', 'language.switch.fsharp'] } ], [ { tokenText: '#!fs', scopes: ['source.dotnet-interactive', 'language.switch.fsharp'] } ], [ { tokenText: '#!html', scopes: ['source.dotnet-interactive', 'language.switch.html'] } ], [ { tokenText: '#!javascript', scopes: ['source.dotnet-interactive', 'language.switch.javascript'] } ], [ { tokenText: '#!js', scopes: ['source.dotnet-interactive', 'language.switch.javascript'] } ], [ { tokenText: '#!markdown', scopes: ['source.dotnet-interactive', 'language.switch.markdown'] } ], [ { tokenText: '#!md', scopes: ['source.dotnet-interactive', 'language.switch.markdown'] } ], [ { tokenText: '#!powershell', scopes: ['source.dotnet-interactive', 'language.switch.powershell'] } ], [ { tokenText: '#!pwsh', scopes: ['source.dotnet-interactive', 'language.switch.powershell'] } ], [ { tokenText: '#!sql', scopes: ['source.dotnet-interactive', 'language.switch.sql'] } ], [ { tokenText: '#!sql-adventureworks', scopes: ['source.dotnet-interactive', 'language.switch.sql'] } ], [ { tokenText: '#!kql', scopes: ['source.dotnet-interactive', 'language.switch.kql'] } ], [ { tokenText: '#!kql-default', scopes: ['source.dotnet-interactive', 'language.switch.kql'] } ], ]); }); it("magic command doesn't invalidate language", async () => { const text = [ '#!fsharp', '// this is fsharp', '#!some-magic-command', '// this is still fsharp' ]; const tokens = await getTokens(text); expect(tokens).to.deep.equal([ [ { tokenText: '#!fsharp', scopes: ['source.dotnet-interactive', 'language.switch.fsharp'] } ], [ { tokenText: '// this is fsharp', scopes: ['source.dotnet-interactive', 'language.switch.fsharp', 'language.line.source.fsharp'] } ], [ { tokenText: '#!', scopes: ['source.dotnet-interactive', 'language.switch.fsharp', 'comment.line.magic-commands', 'comment.line.magic-commands.hash-bang'] }, { tokenText: 'some-magic-command', scopes: ['source.dotnet-interactive', 'language.switch.fsharp', 'comment.line.magic-commands', 'keyword.control.magic-commands'] } ], [ { tokenText: '// this is still fsharp', scopes: ['source.dotnet-interactive', 'language.switch.fsharp', 'language.line.source.fsharp'] } ] ]); }); const allLanguages = [ ['csharp', 'csharp'], ['fsharp', 'fsharp'], ['html', 'html'], ['javascript', 'javascript'], ['markdown', 'markdown'], ['powershell', 'powershell'], ['sql', 'sql'], ['sql-adventureworks', 'sql'], ['kql', 'kql'], ['kql-default', 'kql'], ]; for (const [magicCommand, language] of allLanguages) { it(`language ${language} can switch to all other languages`, async () => { let text = [`#!${magicCommand}`]; let expected = [ [ { tokenText: `#!${magicCommand}`, scopes: ['source.dotnet-interactive', `language.switch.${language}`] } ] ]; for (const [otherMagicCommand, otherLanguage] of allLanguages) { text.push(`#!${otherMagicCommand}`); expected.push([ { tokenText: `#!${otherMagicCommand}`, scopes: ['source.dotnet-interactive', `language.switch.${otherLanguage}`] } ]); } const tokens = await getTokens(text); expect(tokens).to.deep.equal(expected); }); } it('sub-parsing within magic commands', async () => { const text = ['#!share --from csharp x "some string" /a b']; const tokens = await getTokens(text, 'source.dotnet-interactive.magic-commands'); expect(tokens).to.deep.equal([ [ { tokenText: '#!', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands', 'comment.line.magic-commands.hash-bang'] }, { tokenText: 'share', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands', 'keyword.control.magic-commands'] }, { tokenText: ' ', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands'] }, { tokenText: '--from', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands', 'constant.language.magic-commands'] }, { tokenText: ' ', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands'] }, { tokenText: 'csharp', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands', 'variable.parameter.magic-commands'] }, { tokenText: ' ', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands'] }, { tokenText: 'x', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands', 'variable.parameter.magic-commands'] }, { tokenText: ' ', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands'] }, { tokenText: '"', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands', 'string.quoted.double.magic-commands'] }, { tokenText: 'some string', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands', 'string.quoted.double.magic-commands'] }, { tokenText: '"', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands', 'string.quoted.double.magic-commands'] }, { tokenText: ' ', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands'] }, { tokenText: '/a', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands', 'constant.language.magic-commands'] }, { tokenText: ' ', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands'] }, { tokenText: 'b', scopes: ['source.dotnet-interactive.magic-commands', 'comment.line.magic-commands', 'variable.parameter.magic-commands'] } ] ]); }); });
the_stack
import type { Room } from 'xxscreeps/game/room'; import type { RoomIntentPayload, SingleIntent } from 'xxscreeps/engine/processor'; import type { Shard } from 'xxscreeps/engine/db'; import type { flushUsers } from 'xxscreeps/game/room/room'; import Fn from 'xxscreeps/utility/functional'; import { Channel } from 'xxscreeps/engine/db/channel'; import { runnerUsersSetKey } from 'xxscreeps/engine/runner/model'; import { getServiceChannel } from 'xxscreeps/engine/service'; import { KeyvalScript } from 'xxscreeps/engine/db/storage/script'; export function getProcessorChannel(shard: Shard) { type Message = { type: 'finalize'; time: number } | { type: 'process'; time: number; roomNames?: string[] } | { type: 'shutdown' }; return new Channel<Message>(shard.pubsub, 'channel/processor'); } export function getRoomChannel(shard: Shard, roomName: string) { type Message = { type: 'didUpdate'; time: number } | { type: 'willSpawn' }; return new Channel<Message>(shard.pubsub, `processor/room/${roomName}`); } export const processorTimeKey = 'processor/time'; export const activeRoomsKey = 'processor/activeRooms'; const sleepingRoomsKey = 'processor/inactiveRooms'; export const userToIntentRoomsSetKey = (userId: string) => `user/${userId}/intentRooms`; export const userToPresenceRoomsSetKey = (userId: string) => `user/${userId}/presenceRooms`; export const userToVisibleRoomsSetKey = (userId: string) => `user/${userId}/visibleRooms`; export const processRoomsSetKey = (time: number) => `tick${time}/processRooms`; export const finalizeExtraRoomsSetKey = (time: number) => `tick${time}/finalizeExtraRooms`; const activeRoomsProcessingKey = (time: number) => `tick${time}/processedRooms`; const processRoomsPendingKey = (time: number) => `tick${time}/processRoomsPending`; const finalizedRoomsPendingKey = (time: number) => `tick${time}/finalizedRoomsPending`; const intentsListForRoomKey = (roomName: string) => `rooms/${roomName}/intents`; const finalIntentsListForRoomKey = (roomName: string) => `rooms/${roomName}/finalIntents`; const CompareAndSwap = new KeyvalScript(( keyval, [ key ]: [ string, string], [ expected, desired ]: [ expected: number | string, desired: number | string ], ) => { const current = keyval.get(key); if (`${current}` === `${expected}`) { keyval.set(key, desired); return 1; } else { return 0; } }, { lua: `if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('set', KEYS[1], ARGV[2]) else return 0 end`, }); const SCardStore = new KeyvalScript( (keyval, [ into, from ]: [ string, string ]) => { const result = keyval.scard(from); keyval.set(into, result); return result; }, { lua: `local result = redis.call('scard', KEYS[2]) redis.call('set', KEYS[1], result) return result`, }, ); const ZCardStore = new KeyvalScript( (keyval, [ into, from ]: [ string, string ]) => { const result = keyval.zcard(from); keyval.set(into, result); return result; }, { lua: `local result = redis.call('zcard', KEYS[2]) redis.call('set', KEYS[1], result) return result`, }, ); const ZSetToSet = new KeyvalScript( (keyval, [ into, from ]: [string, string]) => keyval.sadd(into, keyval.zrange(from, 0, -1)), { lua: `local members = redis.call('zrange', KEYS[2], 0, -1) local result = 0 for ii = 1, #members, 5000 do result = result + redis.call('sadd', KEYS[1], unpack(members, ii, math.min(ii + 4999, #members))) end return result`, }); async function pushIntentsForRoom(shard: Shard, roomName: string, userId: string, intents?: RoomIntentPayload) { return intents && shard.scratch.rpush(intentsListForRoomKey(roomName), [ JSON.stringify({ userId, intents }) ]); } export function pushIntentsForRoomNextTick(shard: Shard, roomName: string, userId: string, intents: Partial<RoomIntentPayload>) { return Promise.all([ // Add this room to the active set shard.scratch.zadd(sleepingRoomsKey, [ [ shard.time + 1, roomName ] ]), // Save intents pushIntentsForRoom(shard, roomName, userId, { local: {}, object: {}, ...intents, }), ]); } export async function publishRunnerIntentsForRooms( shard: Shard, userId: string, time: number, roomNames: string[], intents: Record<string, RoomIntentPayload | undefined>, ) { const notify = [ ...Fn.filter(await Promise.all(Fn.map(roomNames, async roomName => { const [ count ] = await Promise.all([ // Decrement count of users that this room is waiting for shard.scratch.zadd(processRoomsSetKey(time), [ [ -1, roomName ] ], { if: 'xx', incr: true }), // Add intents to list pushIntentsForRoom(shard, roomName, userId, intents[roomName]), ]); if (count === null || count > 0) { return; } else if (count < 0) { // Reset count back to 0 in the case we've published intents for an abandoned tick // NOTE: These intents will still be processed at some point, which is probably not desired. await shard.scratch.zadd(processRoomsSetKey(time), [ [ 0, roomName ] ], { if: 'xx' }); } return roomName; }))) ]; if (notify.length > 0) { // Publish process task to workers await getProcessorChannel(shard).publish({ type: 'process', time, roomNames: notify }); } } export async function publishInterRoomIntents(shard: Shard, roomName: string, time: number, intents: SingleIntent[]) { const [ count ] = await Promise.all([ // Mark this room as active for this tick shard.scratch.sadd(activeRoomsProcessingKey(time), [ roomName ]), // Save intents shard.scratch.rpush(finalIntentsListForRoomKey(roomName), [ JSON.stringify(intents) ]), ]); if (count) { // Save this room to the set of rooms that need to finalize await shard.scratch.sadd(finalizeExtraRoomsSetKey(time), [ roomName ]); } } export async function acquireIntentsForRoom(shard: Shard, roomName: string) { const key = intentsListForRoomKey(roomName); const [ payloads ] = await Promise.all([ shard.scratch.lrange(key, 0, -1), shard.scratch.vdel(key), ]); return payloads.map(json => { const value: { userId: string; intents: RoomIntentPayload } = JSON.parse(json); return value; }); } export async function acquireFinalIntentsForRoom(shard: Shard, roomName: string) { const key = finalIntentsListForRoomKey(roomName); const [ payloads ] = await Promise.all([ shard.scratch.lrange(key, 0, -1), shard.scratch.vdel(key), ]); return payloads.map((json): SingleIntent[] => JSON.parse(json)); } export async function begetRoomProcessQueue(shard: Shard, time: number, processorTime: number, early?: boolean) { if (processorTime > time) { // The processor has lagged and is running through old `process` messages return processorTime; } const currentTime = Number(await shard.scratch.get(processorTimeKey)); if (currentTime === time) { // Already in sync return time; } else if (currentTime !== time - 1) { // First iteration of laggy processor return currentTime; } if (await shard.scratch.eval(CompareAndSwap, [ processorTimeKey ], [ time - 1, time ])) { // Guarantee atomicity of the following transaction await Promise.all([ shard.scratch.load(ZCardStore), shard.scratch.load(ZSetToSet), ]); // Copy active and waking rooms into current processing queue const tmpKey = 'processorWakeUp'; const processSet = processRoomsSetKey(time); const [ , count ] = await Promise.all([ // Save waking rooms to temporary key shard.scratch.zrangeStore(tmpKey, sleepingRoomsKey, 0, time, { by: 'score' }), // Combine active rooms and waking rooms into current processing queue shard.scratch.zunionStore(processSet, [ activeRoomsKey, tmpKey ], { weights: [ 1, 0 ] }), // Remove temporary key shard.scratch.vdel(tmpKey), // Remove waking rooms from sleeping rooms shard.scratch.zremRange(sleepingRoomsKey, 0, time), // Initialize counter for rooms that need to be processed shard.scratch.eval(ZCardStore, [ processRoomsPendingKey(time), processSet ], []), // Copy processing queue into active rooms set shard.scratch.eval(ZSetToSet, [ activeRoomsProcessingKey(time), processSet ], []), ]); if (count === 0) { // In this case there are *no* rooms to process so we take care to make sure processing // doesn't halt. // Delete "0" value await shard.scratch.vdel(processRoomsPendingKey(time)); if (early) { // We're invoking the function at the end of the previous queue, and the main loop is not // currently ready for the next tick. We'll set the processor time back the way it was so // that this code will be invoked again at the start of the next tick. await shard.scratch.eval(CompareAndSwap, [ processorTimeKey ], [ time, time - 1 ]); return time - 1; } else { // The current processor tick has started, so we can now send the finished notification. await getServiceChannel(shard).publish({ type: 'tickFinished', time }); } } return time; } else { return Number(await shard.scratch.get(processorTimeKey)); } } export async function roomDidProcess(shard: Shard, time: number) { // Decrement count of remaining rooms to process const count = await shard.scratch.decr(processRoomsPendingKey(time)); if (count === 0) { // Count rooms which need to be finalized const roomsKey = activeRoomsProcessingKey(time); await shard.scratch.eval(SCardStore, [ finalizedRoomsPendingKey(time), roomsKey ], []); await Promise.all([ // Publish finalization task to workers getProcessorChannel(shard).publish({ type: 'finalize', time }), // Delete rooms bookkeeping set shard.scratch.vdel(roomsKey), // Delete "0" value from scratch shard.scratch.vdel(processRoomsPendingKey(time)), ]); } } export async function roomsDidFinalize(shard: Shard, roomsCount: number, time: number) { if (roomsCount > 0) { // Decrement number of finalization rooms remaining const remaining = await shard.scratch.decrBy(finalizedRoomsPendingKey(time), roomsCount); if (remaining === 0) { const [ nextTime ] = await Promise.all([ // Set up state for next tick begetRoomProcessQueue(shard, time + 1, time, true), // Delete "0" value from scratch shard.scratch.vdel(finalizedRoomsPendingKey(time)), ]); // Notify main loop that we're ready for the next tick await getServiceChannel(shard).publish({ type: 'tickFinished', time }); return nextTime; } } return time; } const isSystemUser = (userId: string) => userId.length <= 2; export async function updateUserRoomRelationships(shard: Shard, room: Room, previous?: ReturnType<typeof flushUsers>) { const checkPlayers = (current: string[], previous?: string[]) => { // Filter out NPCs const players = [ ...Fn.reject(current, isSystemUser) ]; // Apply diff return previous ? { players, added: [ ...Fn.reject(players, id => previous.includes(id)) ], removed: [ ...Fn.reject(previous, id => isSystemUser(id) || players.includes(id)) ], } : { players, added: players, removed: [], }; }; const roomName = room.name; const users = room['#users']; const intentPlayers = checkPlayers(users.intents, previous?.intents); const presencePlayers = checkPlayers(users.presence, previous?.presence); const visionPlayers = checkPlayers(users.vision, previous?.vision); await Promise.all([ // Update intent, presence, and vision relationships ...Fn.concat(Fn.map([ [ intentPlayers, userToIntentRoomsSetKey ], [ presencePlayers, userToPresenceRoomsSetKey ], [ visionPlayers, userToVisibleRoomsSetKey ], ] as const, ([ players, toKey ]) => Fn.concat( // Add new user associations Fn.map(players.added, playerId => shard.scratch.sadd(toKey(playerId), [ roomName ])), // Remove stale user associations Fn.map(players.removed, playerId => shard.scratch.srem(toKey(playerId), [ roomName ])), ))), // Mark players active for runner shard.scratch.sadd('activeUsers', intentPlayers.added), // Update user count in processing queue previous && (intentPlayers.added.length + intentPlayers.removed.length) === 0 ? undefined : shard.scratch.zadd(activeRoomsKey, [ [ intentPlayers.players.length, roomName ] ]), ]); } export function sleepRoomUntil(shard: Shard, roomName: string, time: number, wakeTime: number) { return Promise.all([ // Copy current room state to buffer0 and buffer1 shard.copyRoomFromPreviousTick(roomName, time + 1), // Remove from active room set shard.scratch.zrem(activeRoomsKey, [ roomName ]), // Set alarm to wake up wakeTime === Infinity ? undefined : shard.scratch.zadd(sleepingRoomsKey, [ [ wakeTime, roomName ] ], { if: 'nx' }), ]); } export async function abandonIntentsForTick(shard: Shard, time: number) { const key = processRoomsSetKey(time); const [ pending ] = await Promise.all([ // Fetch which rooms we're waiting on, for diagnostics shard.scratch.zrange(key, 0, 1000), // Update all processor pending counts to 0 shard.scratch.zinterStore(key, [ key ], { weights: [ 0 ] }), // Clear runner queue shard.scratch.vdel(runnerUsersSetKey(time)), ]); // Publish process task to workers await getProcessorChannel(shard).publish({ type: 'process', time }); return pending; }
the_stack
import { ethers, upgrades, waffle } from "hardhat"; import { Signer, BigNumber } from "ethers"; import chai from "chai"; import { solidity } from "ethereum-waffle"; import "@openzeppelin/test-helpers"; import { MockERC20, MockERC20__factory, PancakeFactory, PancakeFactory__factory, PancakeRouterV2__factory, PancakeRouterV2, MockVaultForRestrictedCakeMaxiAddBaseWithFarm, MockVaultForRestrictedCakeMaxiAddBaseWithFarm__factory, WETH, WETH__factory, CakeToken, CakeToken__factory, SimplePriceOracle, SimplePriceOracle__factory, MockPancakeswapV2CakeMaxiWorker, MockPancakeswapV2CakeMaxiWorker__factory, PancakePair__factory, IERC20__factory, IERC20, } from "../../../../typechain"; import * as TimeHelpers from "../../../helpers/time"; import { SingleAssetWorkerConfig__factory } from "../../../../typechain/factories/SingleAssetWorkerConfig__factory"; import { SingleAssetWorkerConfig } from "../../../../typechain/SingleAssetWorkerConfig"; chai.use(solidity); const { expect } = chai; describe("SingleAssetWorkerConfig", () => { const FOREVER = "2000000000"; /// PancakeswapV2-related instance(s) let factoryV2: PancakeFactory; let routerV2: PancakeRouterV2; /// Token-related instance(s) let wbnb: WETH; let baseToken: MockERC20; let cake: CakeToken; /// Accounts let deployer: Signer; let alice: Signer; let bob: Signer; let eve: Signer; /// SingleAssetWorkerConfig let singleAssetWorkerConfig: SingleAssetWorkerConfig; /// Workers let cakeMaxiWorkerNative: MockPancakeswapV2CakeMaxiWorker; let cakeMaxiWorkerNonNative: MockPancakeswapV2CakeMaxiWorker; /// Vault let mockedVault: MockVaultForRestrictedCakeMaxiAddBaseWithFarm; /// Contract Signer let baseTokenAsAlice: MockERC20; let cakeAsAlice: MockERC20; let wbnbTokenAsAlice: WETH; let wbnbTokenAsBob: WETH; let routerV2AsAlice: PancakeRouterV2; let simplePriceOracleAsAlice: SimplePriceOracle; let singleAssetWorkerConfigAsAlice: SingleAssetWorkerConfig; /// SimpleOracle-related instance(s) let simplePriceOracle: SimplePriceOracle; /// LP Prices let lpPriceBaseBnb: BigNumber; let lpPriceFarmBNB: BigNumber; let lpPriceBNBFarm: BigNumber; let lpPriceBNBBase: BigNumber; async function fixture() { [deployer, alice, bob, eve] = await ethers.getSigners(); /// Deploy SimpleOracle const SimplePriceOracle = (await ethers.getContractFactory( "SimplePriceOracle", deployer )) as SimplePriceOracle__factory; simplePriceOracle = (await upgrades.deployProxy(SimplePriceOracle, [ await alice.getAddress(), ])) as SimplePriceOracle; await simplePriceOracle.deployed(); // Setup Vault const MockVault = (await ethers.getContractFactory( "MockVaultForRestrictedCakeMaxiAddBaseWithFarm", deployer )) as MockVaultForRestrictedCakeMaxiAddBaseWithFarm__factory; mockedVault = (await upgrades.deployProxy(MockVault)) as MockVaultForRestrictedCakeMaxiAddBaseWithFarm; await mockedVault.deployed(); await mockedVault.setMockOwner(await alice.getAddress()); // Setup Pancakeswap const PancakeFactory = (await ethers.getContractFactory("PancakeFactory", deployer)) as PancakeFactory__factory; factoryV2 = await PancakeFactory.deploy(await deployer.getAddress()); await factoryV2.deployed(); const WBNB = (await ethers.getContractFactory("WETH", deployer)) as WETH__factory; wbnb = await WBNB.deploy(); await wbnb.deployed(); const PancakeRouterV2 = (await ethers.getContractFactory("PancakeRouterV2", deployer)) as PancakeRouterV2__factory; routerV2 = await PancakeRouterV2.deploy(factoryV2.address, wbnb.address); await routerV2.deployed(); /// Deploy SingleAssetWorkerConfig const SingleAssetWorkerConfig = (await ethers.getContractFactory( "SingleAssetWorkerConfig", deployer )) as SingleAssetWorkerConfig__factory; singleAssetWorkerConfig = (await upgrades.deployProxy(SingleAssetWorkerConfig, [ simplePriceOracle.address, routerV2.address, ])) as SingleAssetWorkerConfig; await singleAssetWorkerConfig.deployed(); /// Setup token stuffs const MockERC20 = (await ethers.getContractFactory("MockERC20", deployer)) as MockERC20__factory; baseToken = (await upgrades.deployProxy(MockERC20, ["BTOKEN", "BTOKEN", 18])) as MockERC20; await baseToken.deployed(); await baseToken.mint(await deployer.getAddress(), ethers.utils.parseEther("1000")); await baseToken.mint(await alice.getAddress(), ethers.utils.parseEther("1000")); await baseToken.mint(await bob.getAddress(), ethers.utils.parseEther("1000")); const CakeToken = (await ethers.getContractFactory("CakeToken", deployer)) as CakeToken__factory; cake = await CakeToken.deploy(); await cake.deployed(); await cake["mint(address,uint256)"](await deployer.getAddress(), ethers.utils.parseEther("1000")); await cake["mint(address,uint256)"](await alice.getAddress(), ethers.utils.parseEther("1000")); await cake["mint(address,uint256)"](await bob.getAddress(), ethers.utils.parseEther("1000")); await factoryV2.createPair(baseToken.address, wbnb.address); await factoryV2.createPair(cake.address, wbnb.address); /// Setup Cake Maxi Worker const CakeMaxiWorker = (await ethers.getContractFactory( "MockPancakeswapV2CakeMaxiWorker", deployer )) as MockPancakeswapV2CakeMaxiWorker__factory; cakeMaxiWorkerNative = (await CakeMaxiWorker.deploy( wbnb.address, cake.address, [wbnb.address, cake.address], [cake.address, wbnb.address] )) as MockPancakeswapV2CakeMaxiWorker; await cakeMaxiWorkerNative.deployed(); cakeMaxiWorkerNonNative = (await CakeMaxiWorker.deploy( baseToken.address, cake.address, [baseToken.address, wbnb.address, cake.address], [cake.address, baseToken.address] )) as MockPancakeswapV2CakeMaxiWorker; await cakeMaxiWorkerNonNative.deployed(); // Assign contract signer baseTokenAsAlice = MockERC20__factory.connect(baseToken.address, alice); cakeAsAlice = MockERC20__factory.connect(cake.address, alice); wbnbTokenAsAlice = WETH__factory.connect(wbnb.address, alice); wbnbTokenAsBob = WETH__factory.connect(wbnb.address, bob); routerV2AsAlice = PancakeRouterV2__factory.connect(routerV2.address, alice); singleAssetWorkerConfigAsAlice = SingleAssetWorkerConfig__factory.connect(singleAssetWorkerConfig.address, alice); simplePriceOracleAsAlice = SimplePriceOracle__factory.connect(simplePriceOracle.address, alice); await simplePriceOracle.setFeeder(await alice.getAddress()); // Adding liquidity to the pool await wbnbTokenAsAlice.deposit({ value: ethers.utils.parseEther("52"), }); await wbnbTokenAsBob.deposit({ value: ethers.utils.parseEther("50"), }); await cakeAsAlice.approve(routerV2.address, ethers.utils.parseEther("0.1")); await baseTokenAsAlice.approve(routerV2.address, ethers.utils.parseEther("1")); await wbnbTokenAsAlice.approve(routerV2.address, ethers.utils.parseEther("11")); // Add liquidity to the BTOKEN-WBNB pool on Pancakeswap await routerV2AsAlice.addLiquidity( baseToken.address, wbnb.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("10"), "0", "0", await alice.getAddress(), FOREVER ); // Add liquidity to the CAKE-WBNB pool on Pancakeswap await routerV2AsAlice.addLiquidity( cake.address, wbnb.address, ethers.utils.parseEther("0.1"), ethers.utils.parseEther("1"), "0", "0", await alice.getAddress(), FOREVER ); lpPriceBaseBnb = ethers.utils.parseEther("10").mul(ethers.utils.parseEther("1")).div(ethers.utils.parseEther("1")); lpPriceBNBBase = ethers.utils.parseEther("1").mul(ethers.utils.parseEther("1")).div(ethers.utils.parseEther("10")); lpPriceFarmBNB = ethers.utils.parseEther("1").mul(ethers.utils.parseEther("1")).div(ethers.utils.parseEther("0.1")); lpPriceBNBFarm = ethers.utils.parseEther("0.1").mul(ethers.utils.parseEther("1")).div(ethers.utils.parseEther("1")); await singleAssetWorkerConfig.setConfigs( [cakeMaxiWorkerNative.address, cakeMaxiWorkerNonNative.address], [ { acceptDebt: true, workFactor: 1, killFactor: 1, maxPriceDiff: 11000 }, { acceptDebt: true, workFactor: 1, killFactor: 1, maxPriceDiff: 11000 }, ] ); } beforeEach(async () => { await waffle.loadFixture(fixture); }); describe("#emergencySetAcceptDebt", async () => { context("when non owner try to set governor", async () => { it("should be reverted", async () => { await expect(singleAssetWorkerConfigAsAlice.setGovernor(await deployer.getAddress())).to.be.revertedWith( "Ownable: caller is not the owner" ); }); }); context("when an owner set governor", async () => { it("should work", async () => { await singleAssetWorkerConfig.setGovernor(await deployer.getAddress()); expect(await singleAssetWorkerConfig.governor()).to.be.eq(await deployer.getAddress()); }); }); context("when non governor try to use emergencySetAcceptDebt", async () => { it("should revert", async () => { await expect( singleAssetWorkerConfigAsAlice.emergencySetAcceptDebt([cakeMaxiWorkerNative.address], false) ).to.be.revertedWith("SingleAssetWorkerConfig::onlyGovernor:: msg.sender not governor"); }); }); context("when governor uses emergencySetAcceptDebt", async () => { it("should work", async () => { await singleAssetWorkerConfig.setGovernor(await deployer.getAddress()); await singleAssetWorkerConfig.emergencySetAcceptDebt( [cakeMaxiWorkerNative.address, cakeMaxiWorkerNonNative.address], false ); expect((await singleAssetWorkerConfig.workers(cakeMaxiWorkerNative.address)).acceptDebt).to.be.eq(false); expect((await singleAssetWorkerConfig.workers(cakeMaxiWorkerNative.address)).workFactor).to.be.eq(1); expect((await singleAssetWorkerConfig.workers(cakeMaxiWorkerNative.address)).killFactor).to.be.eq(1); expect((await singleAssetWorkerConfig.workers(cakeMaxiWorkerNative.address)).maxPriceDiff).to.be.eq(11000); expect((await singleAssetWorkerConfig.workers(cakeMaxiWorkerNonNative.address)).acceptDebt).to.be.eq(false); expect((await singleAssetWorkerConfig.workers(cakeMaxiWorkerNonNative.address)).workFactor).to.be.eq(1); expect((await singleAssetWorkerConfig.workers(cakeMaxiWorkerNonNative.address)).killFactor).to.be.eq(1); expect((await singleAssetWorkerConfig.workers(cakeMaxiWorkerNonNative.address)).maxPriceDiff).to.be.eq(11000); }); }); }); describe("#isStable()", async () => { context("When the baseToken is not a wrap native", async () => { context("When the oracle hasn't updated any prices", async () => { it("should be reverted", async () => { await simplePriceOracleAsAlice.setPrices( [wbnb.address, cake.address, baseToken.address, wbnb.address], [baseToken.address, wbnb.address, wbnb.address, cake.address], [1, 1, 1, 1] ); await TimeHelpers.increase(BigNumber.from("86401")); // 1 day and 1 second have passed await expect(singleAssetWorkerConfigAsAlice.isStable(cakeMaxiWorkerNonNative.address)).to.revertedWith( "SingleAssetWorkerConfig::isStable:: price too stale" ); }); }); context("When the price on PCS is higher than oracle price with 10% threshold", async () => { it("should be reverted", async () => { // feed the price with price too low on the first hop await simplePriceOracleAsAlice.setPrices( [baseToken.address, wbnb.address], [wbnb.address, baseToken.address], [lpPriceFarmBNB.mul(10000).div(11001), lpPriceBNBFarm.mul(10000).div(11001)] ); await expect( singleAssetWorkerConfigAsAlice.isStable(cakeMaxiWorkerNonNative.address), "BTOKEN -> WBNB is not too high" ).to.revertedWith("SingleAssetWorkerConfig::isStable:: price too high"); // when price from oracle and PCS is within the range, but price from oracle is lower than the price on PCS on the second hop await simplePriceOracleAsAlice.setPrices( [baseToken.address, wbnb.address, cake.address, wbnb.address], [wbnb.address, baseToken.address, wbnb.address, cake.address], [lpPriceFarmBNB, lpPriceBNBFarm, lpPriceBaseBnb.mul(10000).div(11001), lpPriceBNBBase.mul(10000).div(11001)] ); await expect( singleAssetWorkerConfigAsAlice.isStable(cakeMaxiWorkerNonNative.address), "WBNB -> CAKE is not too high" ).to.revertedWith("SingleAssetWorkerConfig::isStable:: price too high"); }); }); context("When the price on PCS is lower than oracle price with 10% threshold", async () => { it("should be reverted", async () => { // feed the price with price too low on the first hop await simplePriceOracleAsAlice.setPrices( [baseToken.address, wbnb.address], [wbnb.address, baseToken.address], [lpPriceFarmBNB.mul(11001).div(10000), lpPriceBNBFarm.mul(11001).div(10000)] ); await expect(singleAssetWorkerConfigAsAlice.isStable(cakeMaxiWorkerNonNative.address)).to.revertedWith( "SingleAssetWorkerConfig::isStable:: price too low" ); // when price from oracle and PCS is within the range, but price from oracle is higher than the price on PCS on the second hop await simplePriceOracleAsAlice.setPrices( [baseToken.address, wbnb.address, cake.address, wbnb.address], [wbnb.address, baseToken.address, wbnb.address, cake.address], [lpPriceFarmBNB, lpPriceBNBFarm, lpPriceBaseBnb.mul(11001).div(10000), lpPriceBNBBase.mul(11001).div(10000)] ); await expect(singleAssetWorkerConfigAsAlice.isStable(cakeMaxiWorkerNonNative.address)).to.revertedWith( "SingleAssetWorkerConfig::isStable:: price too low" ); }); }); context("when price is stable", async () => { it("should return true", async () => { // feed the correct price on both hops await simplePriceOracleAsAlice.setPrices( [cake.address, wbnb.address, baseToken.address, wbnb.address], [wbnb.address, cake.address, wbnb.address, baseToken.address], [lpPriceFarmBNB, lpPriceBNBFarm, lpPriceBaseBnb, lpPriceBNBBase] ); const isStable = await singleAssetWorkerConfigAsAlice.isStable(cakeMaxiWorkerNonNative.address); expect(isStable).to.true; }); }); }); context("When the baseToken is a wrap native", async () => { context("When the oracle hasn't updated any prices", async () => { it("should be reverted", async () => { await simplePriceOracleAsAlice.setPrices([wbnb.address, cake.address], [cake.address, wbnb.address], [1, 1]); await TimeHelpers.increase(BigNumber.from("86401")); // 1 day and 1 second have passed await expect(singleAssetWorkerConfigAsAlice.isStable(cakeMaxiWorkerNative.address)).to.revertedWith( "SingleAssetWorkerConfig::isStable:: price too stale" ); }); }); context("When price is too high", async () => { it("should be reverted", async () => { // feed the price with price too low on the first hop await simplePriceOracleAsAlice.setPrices( [wbnb.address, cake.address], [cake.address, wbnb.address], [lpPriceBNBFarm.mul(10000).div(11001), lpPriceFarmBNB.mul(10000).div(11001)] ); await expect(singleAssetWorkerConfigAsAlice.isStable(cakeMaxiWorkerNative.address)).to.revertedWith( "SingleAssetWorkerConfig::isStable:: price too high" ); }); }); context("When price is too low", async () => { it("should be reverted", async () => { // feed the price with price too low on the first hop await simplePriceOracleAsAlice.setPrices( [wbnb.address, cake.address], [cake.address, wbnb.address], [lpPriceBNBFarm.mul(11001).div(10000), lpPriceFarmBNB.mul(11001).div(10000)] ); await expect(singleAssetWorkerConfigAsAlice.isStable(cakeMaxiWorkerNative.address)).to.revertedWith( "SingleAssetWorkerConfig::isStable:: price too low" ); }); }); context("when price is stable", async () => { it("should return true", async () => { // feed the price with price too low on the first hop await simplePriceOracleAsAlice.setPrices( [wbnb.address, cake.address], [cake.address, wbnb.address], [lpPriceBNBFarm, lpPriceFarmBNB] ); const isStable = await singleAssetWorkerConfigAsAlice.isStable(cakeMaxiWorkerNative.address); expect(isStable).to.true; }); }); }); }); describe("#isReserveConsistent", async () => { context("when reserve is consistent", async () => { it("should return true", async () => { expect(await singleAssetWorkerConfig.isReserveConsistent(cakeMaxiWorkerNonNative.address)).to.be.eq(true); }); }); context("when reserve is inconsistent", async () => { it("should revert", async () => { const path = [baseToken.address, wbnb.address, cake.address]; for (let i = 1; i < path.length; i++) { const lp = PancakePair__factory.connect(await factoryV2.getPair(path[i - 1], path[i]), deployer); const [t0Address, t1Address] = await Promise.all([lp.token0(), lp.token1()]); const [token0, token1] = [ IERC20__factory.connect(t0Address, deployer), IERC20__factory.connect(t1Address, deployer), ]; if (token0.address === wbnb.address) await wbnb.deposit({ value: ethers.utils.parseEther("10") }); await token0.transfer(lp.address, ethers.utils.parseEther("10")); await expect(singleAssetWorkerConfig.isReserveConsistent(cakeMaxiWorkerNonNative.address)).to.be.revertedWith( "SingleAssetWorkerConfig::isReserveConsistent:: bad t0 balance" ); await lp.skim(await deployer.getAddress()); if (token1.address === wbnb.address) await wbnb.deposit({ value: ethers.utils.parseEther("10") }); await token1.transfer(lp.address, ethers.utils.parseEther("10")); await expect(singleAssetWorkerConfig.isReserveConsistent(cakeMaxiWorkerNonNative.address)).to.be.revertedWith( "SingleAssetWorkerConfig::isReserveConsistent:: bad t1 balance" ); await lp.skim(await deployer.getAddress()); } }); }); }); });
the_stack
import * as moment from "moment"; /** * Defines the query context that Bing used for the request. */ export interface QueryContext { /** * The query string as specified in the request. */ originalQuery: string; /** * The query string used by Bing to perform the query. Bing uses the altered query string if the * original query string contained spelling mistakes. For example, if the query string is "saling * downwind", the altered query string will be "sailing downwind". This field is included only if * the original query string contains a spelling mistake. */ readonly alteredQuery?: string; /** * AlteredQuery that is formatted for display purpose. The query string in the * AlterationDisplayQuery can be html-escaped and can contain hit-highlighting characters */ readonly alterationDisplayQuery?: string; /** * The query string to use to force Bing to use the original string. For example, if the query * string is "saling downwind", the override query string will be "+saling downwind". Remember to * encode the query string which results in "%2Bsaling+downwind". This field is included only if * the original query string contains a spelling mistake. */ readonly alterationOverrideQuery?: string; /** * A Boolean value that indicates whether the specified query has adult intent. The value is true * if the query has adult intent; otherwise, false. */ readonly adultIntent?: boolean; /** * A Boolean value that indicates whether Bing requires the user's location to provide accurate * results. If you specified the user's location by using the X-MSEdge-ClientIP and * X-Search-Location headers, you can ignore this field. For location aware queries, such as * "today's weather" or "restaurants near me" that need the user's location to provide accurate * results, this field is set to true. For location aware queries that include the location (for * example, "Seattle weather"), this field is set to false. This field is also set to false for * queries that are not location aware, such as "best sellers". */ readonly askUserForLocation?: boolean; readonly isTransactional?: boolean; /** * Polymorphic Discriminator */ _type: string; } /** * Defines additional information about an entity such as type hints. */ export interface EntitiesEntityPresentationInfo { /** * The supported scenario. Possible values include: 'DominantEntity', 'DisambiguationItem', * 'ListItem' */ entityScenario: string; /** * A list of hints that indicate the entity's type. The list could contain a single hint such as * Movie or a list of hints such as Place, LocalBusiness, Restaurant. Each successive hint in the * array narrows the entity's type. */ readonly entityTypeHints?: string[]; /** * A display version of the entity hint. For example, if entityTypeHints is Artist, this field * may be set to American Singer. */ readonly entityTypeDisplayHint?: string; readonly query?: string; readonly entitySubTypeHints?: string[]; /** * Polymorphic Discriminator */ _type: string; } /** * Response base */ export interface ResponseBase { /** * Polymorphic Discriminator */ _type: string; } /** * Defines the identity of a resource. */ export interface Identifiable extends ResponseBase { /** * A String identifier. */ readonly id?: string; } /** * Defines a response. All schemas that return at the root of the response must inherit from this * object. */ export interface Response extends Identifiable { /** * The URL that returns this resource. */ readonly readLink?: string; /** * The URL to Bing's search result for this item. */ readonly webSearchUrl?: string; readonly potentialAction?: Action[]; readonly immediateAction?: Action[]; readonly preferredClickthroughUrl?: string; readonly adaptiveCard?: string; } /** * Defines a thing. */ export interface Thing extends Response { /** * The name of the thing represented by this object. */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. */ readonly url?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; } /** * Defines an answer. */ export interface Answer extends Response { } /** * Defines a search result answer. */ export interface SearchResultsAnswer extends Answer { readonly queryContext?: QueryContext; /** * The estimated number of webpages that are relevant to the query. Use this number along with * the count and offset query parameters to page the results. */ readonly totalEstimatedMatches?: number; readonly isFamilyFriendly?: boolean; } /** * Defines a local entity answer. */ export interface Places extends SearchResultsAnswer { /** * A list of local entities, such as restaurants or hotels. */ value: Thing[]; } /** * Defines the top-level object that the response includes when the request succeeds. */ export interface SearchResponse extends Response { /** * An object that contains the query string that Bing used for the request. This object contains * the query string as entered by the user. It may also contain an altered query string that Bing * used for the query if the query string contained a spelling mistake. */ readonly queryContext?: QueryContext; /** * A list of local entities such as restaurants or hotels that are relevant to the query. */ readonly places?: Places; readonly lottery?: SearchResultsAnswer; readonly searchResultsConfidenceScore?: number; } export interface GeoCoordinates { latitude: number; longitude: number; readonly elevation?: number; /** * Polymorphic Discriminator */ _type: string; } /** * A utility class that serves as the umbrella for a number of 'intangible' things such as * quantities, structured values, etc. */ export interface Intangible extends Thing { } export interface StructuredValue extends Intangible { } /** * Defines a postal address. */ export interface PostalAddress extends StructuredValue { readonly streetAddress?: string; /** * The city where the street address is located. For example, Seattle. */ readonly addressLocality?: string; readonly addressSubregion?: string; /** * The state or province code where the street address is located. This could be the two-letter * code. For example, WA, or the full name , Washington. */ readonly addressRegion?: string; /** * The zip code or postal code where the street address is located. For example, 98052. */ readonly postalCode?: string; readonly postOfficeBoxNumber?: string; /** * The country/region where the street address is located. This could be the two-letter ISO code. * For example, US, or the full name, United States. */ readonly addressCountry?: string; /** * The two letter ISO code of this country. For example, US. */ readonly countryIso?: string; /** * The neighborhood where the street address is located. For example, Westlake. */ readonly neighborhood?: string; /** * Region Abbreviation. For example, WA. */ readonly addressRegionAbbreviation?: string; /** * The complete address. For example, 2100 Westlake Ave N, Bellevue, WA 98052. */ readonly text?: string; readonly houseNumber?: string; readonly streetName?: string; readonly formattingRuleId?: string; } /** * Defines information about a local entity, such as a restaurant or hotel. */ export interface Place extends Thing { readonly geo?: GeoCoordinates; readonly routablePoint?: GeoCoordinates; /** * The postal address of where the entity is located */ readonly address?: PostalAddress; /** * The entity's telephone number */ readonly telephone?: string; } /** * The most generic kind of creative work, including books, movies, photographs, software programs, * etc. */ export interface CreativeWork extends Thing { /** * The URL to a thumbnail of the item. */ readonly thumbnailUrl?: string; /** * For internal use only. */ readonly about?: Thing[]; /** * For internal use only. */ readonly mentions?: Thing[]; /** * The source of the creative work. */ readonly provider?: Thing[]; readonly creator?: Thing; /** * Text content of this creative work */ readonly text?: string; readonly discussionUrl?: string; readonly commentCount?: number; readonly mainEntity?: Thing; readonly headLine?: string; readonly copyrightHolder?: Thing; readonly copyrightYear?: number; readonly disclaimer?: string; readonly isAccessibleForFree?: boolean; readonly genre?: string[]; readonly isFamilyFriendly?: boolean; } /** * Defines an action. */ export interface Action extends CreativeWork { readonly location?: Place[]; /** * The result produced in the action. */ readonly result?: Thing[]; /** * A display name for the action. */ readonly displayName?: string; /** * A Boolean representing whether this result is the top action. */ readonly isTopAction?: boolean; /** * Use this URL to get additional data to determine how to take the appropriate action. For * example, the serviceUrl might return JSON along with an image URL. */ readonly serviceUrl?: string; } /** * Defines the error that occurred. */ export interface ErrorModel { /** * The error code that identifies the category of error. Possible values include: 'None', * 'ServerError', 'InvalidRequest', 'RateLimitExceeded', 'InvalidAuthorization', * 'InsufficientAuthorization' */ code: string; /** * The error code that further helps to identify the error. Possible values include: * 'UnexpectedError', 'ResourceError', 'NotImplemented', 'ParameterMissing', * 'ParameterInvalidValue', 'HttpNotAllowed', 'Blocked', 'AuthorizationMissing', * 'AuthorizationRedundancy', 'AuthorizationDisabled', 'AuthorizationExpired' */ readonly subCode?: string; /** * A description of the error. */ message: string; /** * A description that provides additional information about the error. */ readonly moreDetails?: string; /** * The parameter in the request that caused the error. */ readonly parameter?: string; /** * The parameter's value in the request that was not valid. */ readonly value?: string; /** * Polymorphic Discriminator */ _type: string; } /** * The top-level response that represents a failed request. */ export interface ErrorResponse extends Response { /** * A list of errors that describe the reasons why the request failed. */ errors: ErrorModel[]; } export interface SearchAction extends Action { readonly displayText?: string; readonly query?: string; readonly richContent?: Answer[]; readonly formattingRuleId?: string; }
the_stack
import { SpreadsheetHelper } from "../util/spreadsheethelper.spec"; import { defaultData } from '../util/datasource.spec'; import { CellModel, DialogBeforeOpenEventArgs, Spreadsheet, dialog } from "../../../src/index"; import { Dialog } from "../../../src/spreadsheet/services/index"; describe('Data validation ->', () => { let helper: SpreadsheetHelper = new SpreadsheetHelper('spreadsheet'); describe('Public Method ->', () => { beforeAll((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }], }] }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('', (done: Function) => { helper.invoke('addDataValidation', [{ type: 'TextLength', operator: 'LessThanOrEqualTo', value1: '12' }, 'A2:A7']); const cell: CellModel = helper.getInstance().sheets[0].rows[1].cells[0]; expect(JSON.stringify(cell.validation)).toBe('{"type":"TextLength","operator":"LessThanOrEqualTo","value1":"12"}'); helper.invoke('addInvalidHighlight', ['A2:A7']); let td: HTMLElement = helper.invoke('getCell', [1, 0]); expect(td.style.backgroundColor).toBe('rgb(255, 255, 255)'); expect(td.style.color).toBe('rgb(0, 0, 0)'); td = helper.invoke('getCell', [4, 0]); expect(td.style.backgroundColor).toBe('rgb(255, 255, 0)'); expect(td.style.color).toBe('rgb(255, 0, 0)'); helper.invoke('removeInvalidHighlight', ['A2:A7']); expect(td.style.backgroundColor).toBe('rgb(255, 255, 255)'); expect(td.style.color).toBe('rgb(0, 0, 0)'); helper.invoke('removeDataValidation', ['A2:A7']); expect(helper.getInstance().sheets[0].rows[1].cells[0].validation).toBeUndefined(); done(); }); it('Add list validation', (done: Function) => { helper.invoke('addDataValidation', [{ type: 'List', value1: '12,13,14' }, 'D2']); const cell: CellModel = helper.getInstance().sheets[0].rows[1].cells[3]; expect(JSON.stringify(cell.validation)).toBe('{"type":"List","value1":"12,13,14"}'); helper.invoke('selectRange', ['D2']); const td: HTMLElement = helper.invoke('getCell', [1, 3]).children[0]; expect(td.classList).toContain('e-validation-list'); const coords: ClientRect = td.getBoundingClientRect(); helper.triggerMouseAction('mousedown', { x: coords.left, y: coords.top }, document, td); helper.triggerMouseAction('mousedup', { x: coords.left, y: coords.top }, document, td); (td.querySelector('.e-dropdownlist') as any).ej2_instances[0].dropDownClick({ preventDefault: function () { }, target: td.children[0] }); setTimeout(() => { helper.click('.e-ddl.e-popup li:nth-child(2)'); expect(helper.getInstance().sheets[0].rows[1].cells[3].value).toBe(13); expect(helper.invoke('getCell', [1, 3]).innerText).toBe('13'); helper.editInUI('15'); setTimeout(() => { expect(helper.getElements('.e-validationerror-dlg').length).toBe(1); helper.setAnimationToNone('.e-validationerror-dlg'); helper.click('.e-validationerror-dlg .e-footer-content button:nth-child(2)'); done(); }); }); }); }); describe('UI Interaction ->', () => { beforeAll((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }], }] }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Add Data validation', (done: Function) => { helper.invoke('selectRange', ['E2']); (helper.getElementFromSpreadsheet('.e-tab-header').children[0].children[5] as HTMLElement).click(); helper.getElementFromSpreadsheet('#' + helper.id + '_datavalidation').click(); setTimeout(() => { helper.click('.e-datavalidation-ddb li:nth-child(1)'); helper.getElements('.e-datavalidation-dlg #minvalue')[0].value = '12'; helper.getElements('.e-datavalidation-dlg #maxvalue')[0].value = '25'; helper.setAnimationToNone('.e-datavalidation-dlg'); helper.getElements('.e-datavalidation-dlg .e-footer-content')[0].children[1].click(); expect(JSON.stringify(helper.getInstance().sheets[0].rows[1].cells[4].validation)).toBe('{"type":"WholeNumber","operator":"Between","value1":"12","value2":"25","ignoreBlank":true,"inCellDropDown":null}'); helper.editInUI('26'); setTimeout(() => { expect(helper.getElements('.e-validationerror-dlg').length).toBe(1); helper.setAnimationToNone('.e-validationerror-dlg'); helper.click('.e-validationerror-dlg .e-footer-content button:nth-child(2)'); expect(helper.invoke('getCell', [1, 4]).textContent).toBe('20'); done(); }); }); }); it('Highlight invalid data', (done: Function) => { helper.invoke('updateCell', [{ value: 26 }, 'E2']); helper.getElementFromSpreadsheet('#' + helper.id + '_datavalidation').click(); setTimeout(() => { helper.click('.e-datavalidation-ddb li:nth-child(2)'); expect(helper.invoke('getCell', [1, 4]).style.backgroundColor).toBe('rgb(255, 255, 0)'); expect(helper.invoke('getCell', [1, 4]).style.color).toBe('rgb(255, 0, 0)'); done(); }); }); it('Remove highlight', (done: Function) => { helper.getElementFromSpreadsheet('#' + helper.id + '_datavalidation').click(); setTimeout(() => { helper.click('.e-datavalidation-ddb li:nth-child(3)'); expect(helper.invoke('getCell', [1, 4]).style.backgroundColor).toBe('rgb(255, 255, 255)'); expect(helper.invoke('getCell', [1, 4]).style.color).toBe('rgb(0, 0, 0)'); done(); }); }); it('Remove data validation', (done: Function) => { helper.getElementFromSpreadsheet('#' + helper.id + '_datavalidation').click(); setTimeout(() => { helper.click('.e-datavalidation-ddb li:nth-child(4)'); expect(helper.getInstance().sheets[0].rows[1].cells[4].validation).toBeUndefined(); helper.editInUI('30'); expect(helper.getElements('.e-validationerror-dlg').length).toBe(0); done(); }); }); it('Dialog interaction', (done: Function) => { helper.getElementFromSpreadsheet('#' + helper.id + '_datavalidation').click(); setTimeout(() => { helper.click('.e-datavalidation-ddb li:nth-child(1)'); setTimeout(() => { let ddlElem: any = helper.getElements('.e-datavalidation-dlg .e-allow .e-dropdownlist')[0]; ddlElem.ej2_instances[0].dropDownClick({ preventDefault: function () { }, target: ddlElem.parentElement }); setTimeout(() => { helper.click('.e-ddl.e-popup li:nth-child(5)'); ddlElem = helper.getElements('.e-datavalidation-dlg .e-data .e-dropdownlist')[0]; ddlElem.ej2_instances[0].dropDownClick({ preventDefault: function () { }, target: ddlElem.parentElement }); setTimeout(() => { helper.click('.e-ddl.e-popup li:nth-child(3)'); helper.triggerKeyNativeEvent(9); helper.getElements('.e-datavalidation-dlg .e-values .e-input')[0].value = 'dumm'; helper.triggerKeyEvent('keyup', 89, null, null, null, helper.getElements('.e-datavalidation-dlg .e-values e-input')[0]); helper.setAnimationToNone('.e-datavalidation-dlg'); // helper.click('.e-datavalidation-dlg .e-footer-content button:nth-child(2)'); // This case need to be fixed // expect(helper.getElements('.e-datavalidation-dlg .e-values .e-dlg-error')[0].textContent).toBe('Please enter a correct value.'); // This case need to be fixed helper.getElements('.e-datavalidation-dlg .e-values .e-input')[0].value = '3'; helper.click('.e-datavalidation-dlg .e-footer-content button:nth-child(2)'); expect(JSON.stringify(helper.getInstance().sheets[0].rows[1].cells[4].validation)).toBe('{"type":"TextLength","operator":"EqualTo","value1":"3","value2":"","ignoreBlank":true,"inCellDropDown":null}'); done(); }); }); }); }); }); it('Add list validation for range', (done: Function) => { helper.invoke('addDataValidation', [{ type: 'List', value1: '=G2:G6' }, 'D2']); const cell: CellModel = helper.getInstance().sheets[0].rows[1].cells[3]; expect(JSON.stringify(cell.validation)).toBe('{"type":"List","value1":"=G2:G6"}'); helper.invoke('selectRange', ['D2']); const td: HTMLElement = helper.invoke('getCell', [1, 3]).children[0]; expect(td.classList).toContain('e-validation-list'); const coords: ClientRect = td.getBoundingClientRect(); helper.triggerMouseAction('mousedown', { x: coords.left, y: coords.top }, document, td); helper.triggerMouseAction('mouseup', { x: coords.left, y: coords.top }, document, td); (td.querySelector('.e-dropdownlist') as any).ej2_instances[0].dropDownClick({ preventDefault: function () { }, target: td.children[0] }); setTimeout(() => { helper.click('.e-ddl.e-popup li:nth-child(4)'); setTimeout(() => { expect(helper.getInstance().sheets[0].rows[1].cells[3].value).toBe(11); // Check this now expect(helper.invoke('getCell', [1, 3]).innerText).toBe('11'); // check this now helper.editInUI('10'); setTimeout(() => { expect(helper.getElements('.e-validationerror-dlg').length).toBe(0); done(); }); }); }); }); it('Add list validation for range of Whole column', (done: Function) => { helper.invoke('selectRange', ['I1']); helper.getElementFromSpreadsheet('#' + helper.id + '_datavalidation').click(); setTimeout(() => { helper.click('.e-datavalidation-ddb li:nth-child(1)'); setTimeout(() => { let ddlElem: any = helper.getElements('.e-datavalidation-dlg .e-allow .e-dropdownlist')[0]; ddlElem.ej2_instances[0].value = 'List'; ddlElem.ej2_instances[0].dataBind(); helper.getElements('.e-datavalidation-dlg .e-values .e-input')[0].value = '=G:G'; helper.setAnimationToNone('.e-datavalidation-dlg'); helper.click('.e-datavalidation-dlg .e-footer-content button:nth-child(2)'); expect(JSON.stringify(helper.getInstance().sheets[0].rows[0].cells[8].validation)).toBe('{"type":"List","operator":"Between","value1":"=G:G","value2":"","ignoreBlank":true,"inCellDropDown":true}'); const td: HTMLElement = helper.invoke('getCell', [0, 8]).children[0]; (td.querySelector('.e-dropdownlist') as any).ej2_instances[0].dropDownClick({ preventDefault: function () { }, target: td.children[0] }); setTimeout(() => { expect(helper.getElements('.e-ddl.e-popup ul')[0].textContent).toBe('Discount15711101336129'); helper.click('.e-ddl.e-popup li:nth-child(4)'); done(); }); }); }); }); }); describe('CR-Issues ->', () => { describe('I282749, I300338, I303567 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: [{ 'Employee ID': '', 'Employee Name': '', 'Gender': '', 'Department': '', 'Date of Joining': '', 'Salary': '', 'City': '' }] }], selectedRange: 'A1:A10' }], created: (): void => { const spreadsheet: Spreadsheet = helper.getInstance(); spreadsheet.cellFormat({ fontWeight: 'bold', textAlign: 'center', verticalAlign: 'middle' }, 'A1:F1'); spreadsheet.cellFormat({ fontWeight: 'bold' }, 'E31:F31'); spreadsheet.cellFormat({ textAlign: 'right' }, 'E31'); spreadsheet.numberFormat('$#,##0.00', 'F2:F31'); spreadsheet.addDataValidation( { type: 'List', operator: 'Between', value1: '1,2', value2: '', ignoreBlank: true, inCellDropDown: true, isHighlighted: true }, 'A2:A100'); } }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Cell alignment and filtering issue ~ from 275309 (while applying data validation)', (done: Function) => { helper.getElement('#' + helper.id + '_sorting').click(); helper.getElement('#' + helper.id + '_applyfilter').click(); helper.invoke('selectRange', ['A2']); setTimeout((): void => { let ddl: HTMLElement = helper.invoke('getCell', [1, 0]).querySelector('.e-ddl') as HTMLElement; helper.triggerMouseAction('mousedown', { x: ddl.getBoundingClientRect().left + 2, y: ddl.getBoundingClientRect().top + 2 }, ddl, ddl); let cell: HTMLElement = helper.invoke('getCell', [1, 0]); helper.triggerMouseAction( 'mouseup', { x: cell.getBoundingClientRect().left + 1, y: cell.getBoundingClientRect().top + 1 }, document, cell); setTimeout((): void => { helper.getElement('#' + helper.getElement().id + 'listValid_popup .e-list-item').click(); helper.invoke('selectRange', ['A3']); setTimeout((): void => { ddl = helper.invoke('getCell', [2, 0]).querySelector('.e-ddl') as HTMLElement; helper.triggerMouseAction('mousedown', { x: ddl.getBoundingClientRect().left + 2, y: ddl.getBoundingClientRect().top + 2 }, ddl, ddl); cell = helper.invoke('getCell', [2, 0]); helper.triggerMouseAction( 'mouseup', { x: cell.getBoundingClientRect().left + 1, y: cell.getBoundingClientRect().top + 1 }, document, cell); setTimeout((): void => { helper.getElement('#' + helper.getElement().id + 'listValid_popup .e-list-item:last-child').click(); helper.invoke('selectRange', ['A1']); const filterCell: HTMLElement = helper.invoke('getCell', [0, 0]).querySelector('.e-filter-icon'); helper.triggerMouseAction( 'mousedown', { x: filterCell.getBoundingClientRect().left + 1, y: filterCell.getBoundingClientRect().top + 1 }, null, filterCell); cell = helper.invoke('getCell', [0, 0]); helper.triggerMouseAction( 'mouseup', { x: cell.getBoundingClientRect().left + 1, y: cell.getBoundingClientRect().top + 1 }, document, cell); setTimeout((): void => { helper.getElement('.e-excelfilter .e-check:not(.e-selectall)').click(); helper.getElement('.e-excelfilter .e-footer-content .e-btn.e-primary').click(); const spreadsheet: Spreadsheet = helper.getInstance(); expect(spreadsheet.sheets[0].selectedRange).toBe('A1:A1'); helper.invoke('selectRange', ['A4']); setTimeout((): void => { expect(!!helper.invoke('getCell', [3, 0]).querySelector('.e-validation-list')).toBeTruthy(); expect(!!helper.invoke('getCell', [4, 0]).querySelector('.e-validation-list')).toBeFalsy(); done(); }, 101); }, 100); }, 10); }, 10); }, 10); }, 10); }); }); describe('I301019, I300657 ->', () => { beforeAll((done: Function) => { helper.initializeSpreadsheet( { sheets: [{ rows: [{ cells: [{ value: 'Food', validation: { type: 'Decimal', operator: 'NotEqualTo', ignoreBlank: true, value1: '0' } }] }], selectedRange: 'A1:A1' }] }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('unexcepted set validations from cellbuilder', (done: Function) => { helper.getElement('#' + helper.id + '_ribbon .e-tab-header .e-toolbar-item:nth-child(6)').click(); helper.getElement('#' + helper.id + '_datavalidation').click(); helper.getElement('#' + helper.id + '_datavalidation-popup .e-item').click(); setTimeout((): void => { // Data validation model is not set properly in dialog. let dlg: HTMLElement = helper.getElement().querySelector('.e-datavalidation-dlg') as HTMLElement; expect(!!dlg).toBeTruthy(); expect((dlg.querySelector('.e-cellrange .e-input') as HTMLInputElement).value).toBe('A1:A1'); expect((dlg.querySelector('.e-ignoreblank .e-checkbox') as HTMLInputElement).checked).toBeTruthy(); (helper.getInstance().serviceLocator.getService(dialog) as Dialog).hide(); setTimeout((): void => { done(); }); }); }); it('custom message on spreadsheet validation', (done: Function) => { const spreadsheet: Spreadsheet = helper.getInstance(); spreadsheet.dialogBeforeOpen = (args: DialogBeforeOpenEventArgs): void => { if (args.dialogName === 'ValidationErrorDialog') { args.content = 'Invalid value'; } }; spreadsheet.dataBind(); helper.edit('A1', '0'); setTimeout((): void => { let dlg: HTMLElement = helper.getElement().querySelector('.e-validationerror-dlg') as HTMLElement; expect(!!dlg).toBeTruthy(); expect(dlg.querySelector('.e-dlg-content').textContent).toBe('Invalid value'); (spreadsheet.serviceLocator.getService(dialog) as Dialog).hide(); setTimeout((): void => { done(); }); }); }); }); describe('I275309 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ created: (): void => { const spreadsheet: Spreadsheet = helper.getInstance(); spreadsheet.addDataValidation( { type: 'List', operator: 'Between', value1: '1', value2:'1', ignoreBlank: true, inCellDropDown: true, isHighlighted: true }, 'X1:X10'); spreadsheet.addDataValidation( { type: 'List', operator: 'Between', value1: '2', value2:'2', ignoreBlank: true, inCellDropDown: true, isHighlighted: true }, 'Y1:Y10'); spreadsheet.addDataValidation( { type: 'List', operator: 'Between', value1: '3', value2:'3', ignoreBlank: true, inCellDropDown: true, isHighlighted: true }, 'Z1:Z10'); spreadsheet.autoFit('1:100'); } }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Dropdownlist added randomly in cells while directly scrolling the spreadsheet', (done: Function) => { helper.invoke('goTo', ['G1']); setTimeout((): void => { helper.invoke('goTo', ['Q1']); setTimeout((): void => { helper.invoke('goTo', ['V1']); helper.invoke('selectRange', ['X1']); setTimeout((): void => { expect(!!helper.invoke('getCell', [0, 23]).querySelector('.e-validation-list')).toBeTruthy(); helper.invoke('selectRange', ['Z1']); setTimeout((): void => { expect(!!helper.invoke('getCell', [0, 25]).querySelector('.e-validation-list')).toBeTruthy(); helper.invoke('selectRange', ['AA1']); setTimeout((): void => { expect(!!helper.invoke('getCell', [0, 26]).querySelector('.e-validation-list')).toBeFalsy(); done(); }); }); }); }); }); }); }); }); });
the_stack
import { createQueue, Subscription } from '@effection/subscription'; import { Operation, Task, Resource, spawn } from '@effection/core'; import { DeepPartial, matcher } from './match'; import { createBuffer } from './buffer'; /** * A callback operation to {@link createStream}. This is an operation which takes * a `publish` function as an argument. Each time the publish function is * invoked with a value, the stream emits that value. * * @typeParam T the type of the values that are emitted by the stream * @typeParam TReturn the return value of the operation */ export type StreamCallback<T,TReturn> = (publish: (value: T) => void) => Operation<TReturn>; /** * A `Stream` of values. A `Stream` can be subscribed to, which creates an * iterable `Subscription`. * * See [the guide on Streams and Subscriptions](https://frontside.com/effection/docs/guides/collections) for more details. * * @typeParam T the type of the values that are emitted by the stream * @typeParam TReturn the return value of the operation */ export interface Stream<T, TReturn = undefined> extends Resource<Subscription<T, TReturn>> { /** * Create a new `Stream` which only emits those values for which the filter * predicate returns `true`. This is similar to the `filter` method on `Array`. * * ### Example * * ```typescript * let comments = createStream(function*(publish) { * publish({ text: "hello", state: "published" }); * publish({ text: "world", state: "draft" }); * }); * let publishedComments = comments.filter((c) => c.state === 'published'); * yield publishedComments.forEach(console.log); // => { text: "hello", state: "published" } * ``` * * @param predicate a function which takes a stream item and returns true or false * @typeParam R the type of the items of the returned stream which is narrowed if the filter predicate is able to narrow the type of `T` */ filter<R extends T>(predicate: (value: T) => value is R): Stream<R, TReturn>; filter(predicate: (value: T) => boolean): Stream<T, TReturn>; filter(predicate: (value: T) => boolean): Stream<T, TReturn>; /** * Create a new `Stream` which only emits those values for which the item matches * the structure of the given reference item, that is all keys and values in the * reference must match the item. * * ### Example * * ```typescript * let comments = createStream(function*(publish) { * publish({ text: "hello", state: "published" }); * publish({ text: "world", state: "draft" }); * }); * let publishedComments = comments.match({ state: 'published' }); * yield publishedComments.forEach(console.log); // => { text: "hello", state: "published" } * ``` * * @param reference a reference item that the stream items are matched against. */ match(reference: DeepPartial<T>): Stream<T,TReturn>; /** * Create a new `Stream` which only emits those values for which the item contains * the given string as a substring, or matches the given regexp. * * ### Example * * ```typescript * let words = createStream(function*(publish) { * ["effection", "frontside", "frontend", "fiesta"].forEach(publish); * }); * yield words.grep("front").forEach(console.log); // => frontside, frontend * yield words.grep(/^f/).forEach(console.log); // => frontside, frontend, fiesta * ``` * * @param search match each item against this substring or regexp */ grep(search: string | RegExp): Stream<T,TReturn>; /** * Create a new `Stream` which applies the given mapping function to each * item. This is similar to the `map` method on `Array`. * * ### Example * * ```typescript * let comments = createStream(function*(publish) { * publish({ text: "hello", state: "published" }); * publish({ text: "world", state: "draft" }); * }); * * let commentTexts = comments.map((comment) => comment.text); * * yield commentTexts.forEach(console.log); // => "hello", "world" * ``` * * @typeParam R the type of the mapped items * @param mapper a mapping function to apply to the items in the stream */ map<R>(mapper: (value: T) => R): Stream<R, TReturn>; /** * Returns the first item in the stream, or `undefined` if the stream * closes before another item is emitted. */ first(): Operation<T | undefined>; /** * Returns the first item in the stream, or throws an error if the stream * closes before before another item is emitted. */ expect(): Operation<T>; /** * Iterates all items of the stream, returns the value the stream closes * with. The given callback is invoked for each item in the stream. The * callback can be either a regular function which returns `undefined`, or an * operation. * * ### Example * * Iterating with a regular function: * * ```typescript * let comments = createStream(function*(publish) { * publish({ text: "hello", state: "published" }); * publish({ text: "world", state: "draft" }); * return 2; * }); * * let result = yield comments.forEach((item) => { * console.log(item); * }); * * console.log(result) // => 2 * ``` * * Iterating with an operation: * * ```typescript * let comments = createStream(function*(publish) { * publish({ text: "hello", state: "published" }); * publish({ text: "world", state: "draft" }); * }); * * yield comments.forEach(function*(value) { * yield createComment(value); * }); * ``` * */ forEach(visit: (value: T) => (Operation<void> | void)): Operation<TReturn>; /** * Wait for the stream to close and return the value it closes with. * * ### Example * * ```typescript * let comments = createStream(function*(publish) { * publish({ text: "hello", state: "published" }); * publish({ text: "world", state: "draft" }); * return 2; * }); * * let result = yield comments.join(); * * console.log(result) // => 2 * ``` */ join(): Operation<TReturn>; /** * Block until the stream finishes, and return a synchronous iterator over * all of the emitted values. * * ### Example * * ```typescript * let comments = createStream(function*(publish) { * publish("hello"); * publish("world"); * return 2; * }); * * let result = yield comments.collect(); * * console.log(result.next()); // => { done: false, value: "hello" } * console.log(result.next()); // => { done: false, value: "world" } * console.log(result.next()); // => { done: true, value: 2 } * ``` */ collect(): Operation<Iterator<T, TReturn>>; /** * Block until the stream finishes and return an array of all of the items * that were emitted. * * ### Example * * ```typescript * let comments = createStream(function*(publish) { * publish("hello"); * publish("world"); * return 2; * }); * * let result = yield comments.toArray(); * * console.log(result); // => ["hello", "world"] * ``` */ toArray(): Operation<T[]>; /** * @hidden */ subscribe(scope: Task): Subscription<T, TReturn>; /** * Returns a buffer which will be filled as items are emitted to the stream. * The buffer can be iterated synchronously, and so it can be used to keep * track of the items that were emitted by the stream. * * If the `limit` is given, then the size of the buffer is limited to that * number of items. If the limit is exceeded, the oldest item gets removed * from the buffer. Internally this uses a ringbuffer to make this efficient. * * ### Example * * ```typescript * let comments = createStream(function*(publish) { * yield sleep(50); * publish("hello"); * publish("world"); * }); * * let buffer = yield comments.toBuffer(); * * console.log(Array.from(buffer)); // => [] * * yield sleep(100); * * console.log(Array.from(buffer)); // => ["hello", "world"] * ``` * * @param limit the maximum number of items to cache, if omitted the limit is infinite */ toBuffer(limit?: number): Resource<Iterable<T>>; /** * Returns a new stream which keeps track of and emits all items that were * emitted since `buffered` was called. Internally this uses a buffer to * store the last items with an optional `limit`. * * If the `limit` is given, then the size of the buffer is limited to that * number of items. If the limit is exceeded, the oldest item gets removed * from the buffer. Internally this uses a ringbuffer to make this efficient. * * Note that an unlimited buffer will never be emptied, and so it will grow * forever. Be careful as this might constitute a memory leak. * * ### Example * * ```typescript * // we use a `Channel` to illustrate this, a channel is also a `Stream` * let comments = createChannel(); * * yield spawn(function*(publish) { * yield sleep(50); * comments.send("hello"); * yield sleep(50); * comments.send("world"); * comments.close(); * }); * * // we create a buffered stream here * let bufferedComments = yield comments.buffered(); * * // after this sleep "hello" has been emitted, but "world" has not * yield sleep(75); * * // iterating `comments` at this point, we will not receive the "hello" item * yield spawn(comments.forEach(console.log)); // "world" * * // if we iterate the buffered stream, we get both emitted items * yield spawn(bufferedComments.forEach(console.log)); // "hello", "world" * ``` * * @param limit the maximum number of items to cache, if omitted the limit is infinite */ buffered(limit?: number): Resource<Stream<T, TReturn>>; } /** * Create a new stream of values. The given callback operation is run each time * someone subscribes to the stream, so it may be invoked multiple times. The * stream emits a value each time the `publish` function passed as an argument * to the callback is invoked. The stream is closed when the callback function * returns, and the return value of the callback is the value the stream closes * with. * * ### Example * * ```typescript * import { main, createStream, sleep, all } from 'effection'; * * main(function*() { * let stream = createStream<number, string>(function*(publish) { * yield sleep(100); * publish(1); * yield sleep(100); * publish(2); * return "I'm done"; * }); * * // we can subscribe multiple times * let result = yield all([ * stream.forEach((value) => { console.log(value) }); // => '1', '2' * stream.forEach((value) => { console.log(value) }); // => '1', '2' * ]); * console.log(result) // => ["I'm done", "I'm done"] * }); * ``` * * See [the guide on Streams and Subscriptions](https://frontside.com/effection/docs/guides/collections) for more details. */ export function createStream<T, TReturn = undefined>(callback: StreamCallback<T, TReturn>, name = 'stream'): Stream<T, TReturn> { let subscribe = (task: Task) => { let queue = createQueue<T, TReturn>(name); task.run(function*() { let result = yield callback(queue.send); queue.closeWith(result); }, { labels: { name: 'publisher', expand: false } }); return queue.subscription; }; function filter<R extends T>(predicate: (value: T) => value is R): Stream<T, TReturn> function filter(predicate: (value: T) => boolean): Stream<T, TReturn> function filter(predicate: (value: T) => boolean): Stream<T, TReturn> { return createStream((publish) => { return stream.forEach((value) => function*() { if(predicate(value)) { publish(value); } }); }, `${name}.filter()`); } let stream = { subscribe, filter, *init(task: Task) { return subscribe(task); }, match(reference: DeepPartial<T>): Stream<T,TReturn> { return stream.filter(matcher(reference)); }, grep(search: string | RegExp): Stream<T,TReturn> { if(typeof(search) === 'string') { return stream.filter((value) => String(value).includes(search)); } else { return stream.filter((value) => !!String(value).match(search)); } }, map<R>(mapper: (value: T) => R): Stream<R, TReturn> { return createStream((publish) => { return stream.forEach((value: T) => function*() { publish(mapper(value)); }); }, `${name}.map()`); }, first(): Operation<T | undefined> { return task => subscribe(task).first(); }, expect(): Operation<T> { return task => subscribe(task).expect(); }, forEach(visit: (value: T) => (Operation<void> | void)): Operation<TReturn> { return task => subscribe(task).forEach(visit); }, join(): Operation<TReturn> { return task => subscribe(task).join(); }, collect(): Operation<Iterator<T, TReturn>> { return task => subscribe(task).collect(); }, toArray(): Operation<T[]> { return task => subscribe(task).toArray(); }, toBuffer(limit = Infinity): Resource<Iterable<T>> { return { name: `${name}.buffer(${limit})`, *init() { let buffer = createBuffer<T>(limit); yield spawn(stream.forEach((value) => { buffer.push(value) })); return buffer; } }; }, buffered(limit = Infinity): Resource<Stream<T, TReturn>> { return { *init() { let buffer = yield stream.toBuffer(limit); return createStream<T, TReturn>((publish) => function*() { for(let value of buffer) { publish(value); } return yield stream.forEach(publish); }, `${name}.buffered(${limit})`); } }; } }; return stream; }
the_stack
import { transformErrorForSerialization } from 'vs/base/common/errors'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; import { globals, isWeb } from 'vs/base/common/platform'; import * as types from 'vs/base/common/types'; import * as strings from 'vs/base/common/strings'; const INITIALIZE = '$initialize'; export interface IWorker extends IDisposable { getId(): number; postMessage(message: Message, transfer: ArrayBuffer[]): void; } export interface IWorkerCallback { (message: Message): void; } export interface IWorkerFactory { create(moduleId: string, callback: IWorkerCallback, onErrorCallback: (err: any) => void): IWorker; } let webWorkerWarningLogged = false; export function logOnceWebWorkerWarning(err: any): void { if (!isWeb) { // running tests return; } if (!webWorkerWarningLogged) { webWorkerWarningLogged = true; console.warn('Could not create web worker(s). Falling back to loading web worker code in main thread, which might cause UI freezes. Please see https://github.com/microsoft/monaco-editor#faq'); } console.warn(err.message); } const enum MessageType { Request, Reply, SubscribeEvent, Event, UnsubscribeEvent } class RequestMessage { public readonly type = MessageType.Request; constructor( public readonly vsWorker: number, public readonly req: string, public readonly method: string, public readonly args: any[] ) { } } class ReplyMessage { public readonly type = MessageType.Reply; constructor( public readonly vsWorker: number, public readonly seq: string, public readonly res: any, public readonly err: any ) { } } class SubscribeEventMessage { public readonly type = MessageType.SubscribeEvent; constructor( public readonly vsWorker: number, public readonly req: string, public readonly eventName: string, public readonly arg: any ) { } } class EventMessage { public readonly type = MessageType.Event; constructor( public readonly vsWorker: number, public readonly req: string, public readonly event: any ) { } } class UnsubscribeEventMessage { public readonly type = MessageType.UnsubscribeEvent; constructor( public readonly vsWorker: number, public readonly req: string ) { } } type Message = RequestMessage | ReplyMessage | SubscribeEventMessage | EventMessage | UnsubscribeEventMessage; interface IMessageReply { resolve: (value?: any) => void; reject: (error?: any) => void; } interface IMessageHandler { sendMessage(msg: any, transfer?: ArrayBuffer[]): void; handleMessage(method: string, args: any[]): Promise<any>; handleEvent(eventName: string, arg: any): Event<any>; } class SimpleWorkerProtocol { private _workerId: number; private _lastSentReq: number; private _pendingReplies: { [req: string]: IMessageReply }; private _pendingEmitters: Map<string, Emitter<any>>; private _pendingEvents: Map<string, IDisposable>; private _handler: IMessageHandler; constructor(handler: IMessageHandler) { this._workerId = -1; this._handler = handler; this._lastSentReq = 0; this._pendingReplies = Object.create(null); this._pendingEmitters = new Map<string, Emitter<any>>(); this._pendingEvents = new Map<string, IDisposable>(); } public setWorkerId(workerId: number): void { this._workerId = workerId; } public sendMessage(method: string, args: any[]): Promise<any> { const req = String(++this._lastSentReq); return new Promise<any>((resolve, reject) => { this._pendingReplies[req] = { resolve: resolve, reject: reject }; this._send(new RequestMessage(this._workerId, req, method, args)); }); } public listen(eventName: string, arg: any): Event<any> { let req: string | null = null; const emitter = new Emitter<any>({ onFirstListenerAdd: () => { req = String(++this._lastSentReq); this._pendingEmitters.set(req, emitter); this._send(new SubscribeEventMessage(this._workerId, req, eventName, arg)); }, onLastListenerRemove: () => { this._pendingEmitters.delete(req!); this._send(new UnsubscribeEventMessage(this._workerId, req!)); req = null; } }); return emitter.event; } public handleMessage(message: Message): void { if (!message || !message.vsWorker) { return; } if (this._workerId !== -1 && message.vsWorker !== this._workerId) { return; } this._handleMessage(message); } private _handleMessage(msg: Message): void { switch (msg.type) { case MessageType.Reply: return this._handleReplyMessage(msg); case MessageType.Request: return this._handleRequestMessage(msg); case MessageType.SubscribeEvent: return this._handleSubscribeEventMessage(msg); case MessageType.Event: return this._handleEventMessage(msg); case MessageType.UnsubscribeEvent: return this._handleUnsubscribeEventMessage(msg); } } private _handleReplyMessage(replyMessage: ReplyMessage): void { if (!this._pendingReplies[replyMessage.seq]) { console.warn('Got reply to unknown seq'); return; } const reply = this._pendingReplies[replyMessage.seq]; delete this._pendingReplies[replyMessage.seq]; if (replyMessage.err) { let err = replyMessage.err; if (replyMessage.err.$isError) { err = new Error(); err.name = replyMessage.err.name; err.message = replyMessage.err.message; err.stack = replyMessage.err.stack; } reply.reject(err); return; } reply.resolve(replyMessage.res); } private _handleRequestMessage(requestMessage: RequestMessage): void { const req = requestMessage.req; const result = this._handler.handleMessage(requestMessage.method, requestMessage.args); result.then((r) => { this._send(new ReplyMessage(this._workerId, req, r, undefined)); }, (e) => { if (e.detail instanceof Error) { // Loading errors have a detail property that points to the actual error e.detail = transformErrorForSerialization(e.detail); } this._send(new ReplyMessage(this._workerId, req, undefined, transformErrorForSerialization(e))); }); } private _handleSubscribeEventMessage(msg: SubscribeEventMessage): void { const req = msg.req; const disposable = this._handler.handleEvent(msg.eventName, msg.arg)((event) => { this._send(new EventMessage(this._workerId, req, event)); }); this._pendingEvents.set(req, disposable); } private _handleEventMessage(msg: EventMessage): void { if (!this._pendingEmitters.has(msg.req)) { console.warn('Got event for unknown req'); return; } this._pendingEmitters.get(msg.req)!.fire(msg.event); } private _handleUnsubscribeEventMessage(msg: UnsubscribeEventMessage): void { if (!this._pendingEvents.has(msg.req)) { console.warn('Got unsubscribe for unknown req'); return; } this._pendingEvents.get(msg.req)!.dispose(); this._pendingEvents.delete(msg.req); } private _send(msg: Message): void { const transfer: ArrayBuffer[] = []; if (msg.type === MessageType.Request) { for (let i = 0; i < msg.args.length; i++) { if (msg.args[i] instanceof ArrayBuffer) { transfer.push(msg.args[i]); } } } else if (msg.type === MessageType.Reply) { if (msg.res instanceof ArrayBuffer) { transfer.push(msg.res); } } this._handler.sendMessage(msg, transfer); } } export interface IWorkerClient<W> { getProxyObject(): Promise<W>; dispose(): void; } /** * Main thread side */ export class SimpleWorkerClient<W extends object, H extends object> extends Disposable implements IWorkerClient<W> { private readonly _worker: IWorker; private readonly _onModuleLoaded: Promise<string[]>; private readonly _protocol: SimpleWorkerProtocol; private readonly _lazyProxy: Promise<W>; constructor(workerFactory: IWorkerFactory, moduleId: string, host: H) { super(); let lazyProxyReject: ((err: any) => void) | null = null; this._worker = this._register(workerFactory.create( 'vs/base/common/worker/simpleWorker', (msg: Message) => { this._protocol.handleMessage(msg); }, (err: any) => { // in Firefox, web workers fail lazily :( // we will reject the proxy lazyProxyReject?.(err); } )); this._protocol = new SimpleWorkerProtocol({ sendMessage: (msg: any, transfer: ArrayBuffer[]): void => { this._worker.postMessage(msg, transfer); }, handleMessage: (method: string, args: any[]): Promise<any> => { if (typeof (host as any)[method] !== 'function') { return Promise.reject(new Error('Missing method ' + method + ' on main thread host.')); } try { return Promise.resolve((host as any)[method].apply(host, args)); } catch (e) { return Promise.reject(e); } }, handleEvent: (eventName: string, arg: any): Event<any> => { if (propertyIsDynamicEvent(eventName)) { const event = (host as any)[eventName].call(host, arg); if (typeof event !== 'function') { throw new Error(`Missing dynamic event ${eventName} on main thread host.`); } return event; } if (propertyIsEvent(eventName)) { const event = (host as any)[eventName]; if (typeof event !== 'function') { throw new Error(`Missing event ${eventName} on main thread host.`); } return event; } throw new Error(`Malformed event name ${eventName}`); } }); this._protocol.setWorkerId(this._worker.getId()); // Gather loader configuration let loaderConfiguration: any = null; if (typeof globals.require !== 'undefined' && typeof globals.require.getConfig === 'function') { // Get the configuration from the Monaco AMD Loader loaderConfiguration = globals.require.getConfig(); } else if (typeof globals.requirejs !== 'undefined') { // Get the configuration from requirejs loaderConfiguration = globals.requirejs.s.contexts._.config; } const hostMethods = types.getAllMethodNames(host); // Send initialize message this._onModuleLoaded = this._protocol.sendMessage(INITIALIZE, [ this._worker.getId(), JSON.parse(JSON.stringify(loaderConfiguration)), moduleId, hostMethods, ]); // Create proxy to loaded code const proxyMethodRequest = (method: string, args: any[]): Promise<any> => { return this._request(method, args); }; const proxyListen = (eventName: string, arg: any): Event<any> => { return this._protocol.listen(eventName, arg); }; this._lazyProxy = new Promise<W>((resolve, reject) => { lazyProxyReject = reject; this._onModuleLoaded.then((availableMethods: string[]) => { resolve(createProxyObject<W>(availableMethods, proxyMethodRequest, proxyListen)); }, (e) => { reject(e); this._onError('Worker failed to load ' + moduleId, e); }); }); } public getProxyObject(): Promise<W> { return this._lazyProxy; } private _request(method: string, args: any[]): Promise<any> { return new Promise<any>((resolve, reject) => { this._onModuleLoaded.then(() => { this._protocol.sendMessage(method, args).then(resolve, reject); }, reject); }); } private _onError(message: string, error?: any): void { console.error(message); console.info(error); } } function propertyIsEvent(name: string): boolean { // Assume a property is an event if it has a form of "onSomething" return name[0] === 'o' && name[1] === 'n' && strings.isUpperAsciiLetter(name.charCodeAt(2)); } function propertyIsDynamicEvent(name: string): boolean { // Assume a property is a dynamic event (a method that returns an event) if it has a form of "onDynamicSomething" return /^onDynamic/.test(name) && strings.isUpperAsciiLetter(name.charCodeAt(9)); } function createProxyObject<T extends object>( methodNames: string[], invoke: (method: string, args: unknown[]) => unknown, proxyListen: (eventName: string, arg: any) => Event<any> ): T { const createProxyMethod = (method: string): () => unknown => { return function () { const args = Array.prototype.slice.call(arguments, 0); return invoke(method, args); }; }; const createProxyDynamicEvent = (eventName: string): (arg: any) => Event<any> => { return function (arg) { return proxyListen(eventName, arg); }; }; const result = {} as T; for (const methodName of methodNames) { if (propertyIsDynamicEvent(methodName)) { (<any>result)[methodName] = createProxyDynamicEvent(methodName); continue; } if (propertyIsEvent(methodName)) { (<any>result)[methodName] = proxyListen(methodName, undefined); continue; } (<any>result)[methodName] = createProxyMethod(methodName); } return result; } export interface IRequestHandler { _requestHandlerBrand: any; [prop: string]: any; } export interface IRequestHandlerFactory<H> { (host: H): IRequestHandler; } /** * Worker side */ export class SimpleWorkerServer<H extends object> { private _requestHandlerFactory: IRequestHandlerFactory<H> | null; private _requestHandler: IRequestHandler | null; private _protocol: SimpleWorkerProtocol; constructor(postMessage: (msg: Message, transfer?: ArrayBuffer[]) => void, requestHandlerFactory: IRequestHandlerFactory<H> | null) { this._requestHandlerFactory = requestHandlerFactory; this._requestHandler = null; this._protocol = new SimpleWorkerProtocol({ sendMessage: (msg: any, transfer: ArrayBuffer[]): void => { postMessage(msg, transfer); }, handleMessage: (method: string, args: any[]): Promise<any> => this._handleMessage(method, args), handleEvent: (eventName: string, arg: any): Event<any> => this._handleEvent(eventName, arg) }); } public onmessage(msg: any): void { this._protocol.handleMessage(msg); } private _handleMessage(method: string, args: any[]): Promise<any> { if (method === INITIALIZE) { return this.initialize(<number>args[0], <any>args[1], <string>args[2], <string[]>args[3]); } if (!this._requestHandler || typeof this._requestHandler[method] !== 'function') { return Promise.reject(new Error('Missing requestHandler or method: ' + method)); } try { return Promise.resolve(this._requestHandler[method].apply(this._requestHandler, args)); } catch (e) { return Promise.reject(e); } } private _handleEvent(eventName: string, arg: any): Event<any> { if (!this._requestHandler) { throw new Error(`Missing requestHandler`); } if (propertyIsDynamicEvent(eventName)) { const event = (this._requestHandler as any)[eventName].call(this._requestHandler, arg); if (typeof event !== 'function') { throw new Error(`Missing dynamic event ${eventName} on request handler.`); } return event; } if (propertyIsEvent(eventName)) { const event = (this._requestHandler as any)[eventName]; if (typeof event !== 'function') { throw new Error(`Missing event ${eventName} on request handler.`); } return event; } throw new Error(`Malformed event name ${eventName}`); } private initialize(workerId: number, loaderConfig: any, moduleId: string, hostMethods: string[]): Promise<string[]> { this._protocol.setWorkerId(workerId); const proxyMethodRequest = (method: string, args: any[]): Promise<any> => { return this._protocol.sendMessage(method, args); }; const proxyListen = (eventName: string, arg: any): Event<any> => { return this._protocol.listen(eventName, arg); }; const hostProxy = createProxyObject<H>(hostMethods, proxyMethodRequest, proxyListen); if (this._requestHandlerFactory) { // static request handler this._requestHandler = this._requestHandlerFactory(hostProxy); return Promise.resolve(types.getAllMethodNames(this._requestHandler)); } if (loaderConfig) { // Remove 'baseUrl', handling it is beyond scope for now if (typeof loaderConfig.baseUrl !== 'undefined') { delete loaderConfig['baseUrl']; } if (typeof loaderConfig.paths !== 'undefined') { if (typeof loaderConfig.paths.vs !== 'undefined') { delete loaderConfig.paths['vs']; } } if (typeof loaderConfig.trustedTypesPolicy !== undefined) { // don't use, it has been destroyed during serialize delete loaderConfig['trustedTypesPolicy']; } // Since this is in a web worker, enable catching errors loaderConfig.catchError = true; globals.require.config(loaderConfig); } return new Promise<string[]>((resolve, reject) => { // Use the global require to be sure to get the global config // ESM-comment-begin const req = (globals.require || require); // ESM-comment-end // ESM-uncomment-begin // const req = globals.require; // ESM-uncomment-end req([moduleId], (module: { create: IRequestHandlerFactory<H> }) => { this._requestHandler = module.create(hostProxy); if (!this._requestHandler) { reject(new Error(`No RequestHandler!`)); return; } resolve(types.getAllMethodNames(this._requestHandler)); }, reject); }); } } /** * Called on the worker side */ export function create(postMessage: (msg: Message, transfer?: ArrayBuffer[]) => void): SimpleWorkerServer<any> { return new SimpleWorkerServer(postMessage, null); }
the_stack
import {sendNotify} from './sendNotify'; import USER_AGENT, {get, getShareCodePool, o2s, requireConfig, wait} from './TS_USER_AGENTS' import {H5ST} from "./utils/h5st"; let cookie: string = '', res: any = '', data: any, UserName: string let shareCodeSelf: string[] = [], shareCodePool: string[] = [], shareCode: string[] = [], shareCodeFile: object = require('./jdFruitShareCodes') let message: string = '', h5stTool: H5ST = new H5ST("0c010", USER_AGENT, "8389547038003203") !(async () => { let cookiesArr: string[] = await requireConfig() for (let [index, value] of cookiesArr.entries()) { cookie = value UserName = decodeURIComponent(cookie.match(/pt_pin=([^;]*)/)![1]) console.log(`\n开始【京东账号${index + 1}】${UserName}\n`) message += `【账号${index + 1}】 ${UserName}\n` await h5stTool.__genAlgo() try { if (Object.keys(shareCodeFile)[index]) { shareCodeSelf = shareCodeFile[Object.keys(shareCodeFile)[index]].split('@') } console.log(`第${index + 1}个账号获取的内部互助`, shareCodeSelf) // 初始化 res = await api('initForFarm', {"version": 11, "channel": 3}) o2s(res) if (res.code === '6') { console.log('黑号') await wait(5000) continue } await wait(1000) if (res.todayGotWaterGoalTask.canPop) { data = await api('gotWaterGoalTaskForFarm', {"type": 3, "version": 14, "channel": 1, "babelChannel": "120"}) o2s(data) console.log("弹窗获得水滴", data.addEnergy) } o2s(res, 'initForFarm') let totalEnergy: number = res.farmUserPro.totalEnergy // 背包剩余水滴 if (res.farmUserPro.treeState === 2) { console.log("可以兑换奖品了") await sendNotify("东东农场", `账号${index + 1} ${UserName}\n\n已成熟`) } else if (res.farmUserPro.treeState === 0) { console.log("自动种植") } // 添加好友 // 删除好友 res = await api('friendListInitForFarm', {"lastId": null, "version": 14, "channel": 1, "babelChannel": "120"}) await wait(1000) if (!res.newFriendMsg) { for (let fr of res.friends) { res = await api('deleteFriendForFarm', {"shareCode": fr.shareCode, "version": 14, "channel": 1, "babelChannel": "121"}) await wait(1000) if (res.code === '0') { console.log(`删除好友${fr.nickName}成功`) } else { console.log(`删除好友${fr.nickName}失败`) break } } } // 背包 // process.env.jdFruitBeanCard = 'True' // if (process.env.jdFruitBeanCard.toLowerCase() === 'true') { // res = await api('myCardInfoForFarm', {"version": 14, "channel": 3, "babelChannel": "10"}) // o2s(res, 'myCardInfoForFarm') // let beanCard: number = res.beanCard // 换豆卡 // console.log('换豆卡数量', beanCard) // for (let i = 0; i < 10; i++) { // if (totalEnergy >= 100 && beanCard) { // data = await api('userMyCardForFarm', {"cardType": "beanCard", "babelChannel": "10", "channel": 3, "version": 14}) // console.log('使用水滴换豆卡,获得京豆', data.beanCount) // totalEnergy -= 100 // beanCard-- // await wait(1000) // } // } // } else { // console.log('未设置水滴换豆卡环境变量') // } // 好友邀请奖励 res = await api('friendListInitForFarm', {"lastId": null, "version": 14, "channel": 1, "babelChannel": "120"}) o2s(res, 'friendListInitForFarm') let friendList: any[] = res.friends if (res.inviteFriendCount > res.inviteFriendGotAwardCount) { data = await api('awardInviteFriendForFarm', {}) await wait(1000) o2s(data, '好友邀请奖励') } // 给好友浇水 res = await api('taskInitForFarm', {"version": 14, "channel": 1, "babelChannel": "120"}) o2s(res, 'taskInitForFarm') await wait(1000) console.log(`今日已给${res.waterFriendTaskInit.waterFriendCountKey}个好友浇水`); if (res.waterFriendTaskInit.waterFriendCountKey < res.waterFriendTaskInit.waterFriendMax) { for (let i = res.waterFriendTaskInit.waterFriendCountKey; i < res.waterFriendTaskInit.waterFriendMax; i++) { for (let fr of friendList) { if (fr.friendState === 1) { data = await api('waterFriendForFarm', {"shareCode": fr.shareCode, "version": 14, "channel": 1, "babelChannel": "120"}) if (data.code === '0') console.log(`给好友${fr.nickName}浇水成功`) if (data.cardInfo) { console.log('获得卡片') } await wait(2000) break } } } } else if (res.waterFriendTaskInit.waterFriendCountKey === res.waterFriendTaskInit.waterFriendMax && !res.waterFriendTaskInit.waterFriendGotAward) { data = await api('waterFriendGotAwardForFarm', {"version": 14, "channel": 1, "babelChannel": "120"}) console.log('给好友浇水奖励', data.addWater) await wait(1000) } // 签到 res = await api('clockInInitForFarm', {"timestamp": Date.now(), "version": 14, "channel": 1, "babelChannel": "120"}) await wait(1000) if (!res.todaySigned) { data = await api('clockInForFarm', {"type": 1, "version": 14, "channel": 1, "babelChannel": "120"}) if (data.signDay === 7) { // data = await api('gotClockInGift', {"type": 2, "version": 14, "channel": 1, "babelChannel": "120"}) // o2s(data, 'gotClockInGift') // await wait(1000) } await wait(1000) } res = await api('clockInInitForFarm', {"timestamp": Date.now(), "version": 14, "channel": 1, "babelChannel": "120"}) for (let t of res.themes || []) { if (!t.hadGot) { console.log('关注', t.name) res = await api('clockInFollowForFarm', {"id": t.id, "type": "theme", "step": 1, "version": 14, "channel": 1, "babelChannel": "120"}) await wait(5000) res = await api('clockInFollowForFarm', {"id": t.id, "type": "theme", "step": 2, "version": 14, "channel": 1, "babelChannel": "120"}) console.log('获得水滴', res.amount) } } // 任务 res = await api('taskInitForFarm', {"version": 14, "channel": 1, "babelChannel": "120"}) o2s(res) if (res.signInit.todaySigned) { console.log(`今天已签到,已经连续签到${res.signInit.totalSigned}天,下次签到可得${res.signInit.signEnergyEachAmount}g`); } else { data = await api('signForFarm', {"version": 14, "channel": 1, "babelChannel": "120"}) o2s(data, 'signForFarm') console.log('签到成功', data.amount) await wait(1000) } if (!res.gotBrowseTaskAdInit.f) { for (let t of res.gotBrowseTaskAdInit.userBrowseTaskAds) { if (t.hadFinishedTimes !== t.limit) { data = await api('browseAdTaskForFarm', {"advertId": t.advertId, "type": 0, "version": 14, "channel": 1, "babelChannel": "120"}) o2s(data, 'browseAdTaskForFarm') await wait(t.time * 1000 || 1000) data = await api('browseAdTaskForFarm', {"advertId": t.advertId, "type": 1, "version": 14, "channel": 1, "babelChannel": "120"}) console.log('任务完成,获得', data.amount) } await wait(1000) } } if (!res.gotThreeMealInit.f) { if (![10, 15, 16, 22, 23].includes(new Date().getHours())) { data = await api('gotThreeMealForFarm', {"version": 14, "channel": 1, "babelChannel": "120"}) if (data.code === '0') { console.log('定时奖励成功', data.amount) } await wait(1000) } } if (!res.waterRainInit.f) { if (Date.now < res.waterRainInit.lastTime + 3 * 60 * 60 * 1000) { data = await api('waterRainForFarm', {"type": 1, "hongBaoTimes": 100, "version": 3}) o2s(data, 'waterRainForFarm') if (data.code === '0') { console.log('获得水滴', data.addEnergy) } } } if (!res.firstWaterInit.f && res.firstWaterInit.totalWaterTimes !== 0) { data = await api('firstWaterTaskForFarm', {"version": 14, "channel": 1, "babelChannel": "120"}) console.log('firstWaterTaskForFarm', data.amount) } // 红包 res = await api('initForTurntableFarm', {"version": 4, "channel": 1}) o2s(res, 'initForTurntableFarm') for (let t of res.turntableBrowserAds) { if (!t.status) { console.log("browserForTurntableFarm", t.main) data = await api('browserForTurntableFarm', {"type": 1, "adId": t.adId, "version": 4, "channel": 1}) await wait(t.browserTimes * 1000 || 1000) data = await api('browserForTurntableFarm', {"type": 2, "adId": t.adId, "version": 4, "channel": 1}) } } if (!res.timingGotStatus && res.remainLotteryTimes) { if (Date.now() > (res.timingLastSysTime + 60 * 60 * res.timingIntervalHours * 1000)) { data = await api('timingAwardForTurntableFarm', {"version": 4, "channel": 1}) await wait(1000) o2s(data, 'timingAwardForTurntableFarm') } else { console.log(`免费赠送的抽奖机会未到时间`) } } // 天天红包助力 shareCodePool = await getShareCodePool('farm', 30) shareCode = Array.from(new Set([...shareCodeSelf, ...shareCodePool])) for (let code of shareCodeSelf) { console.log('去红包助力', code) data = await api('initForFarm', {"shareCode": `${code}-3`, "lng": "0.000000", "lat": "0.000000", "sid": "2871ac0252645ef0e2731aa7d03c1d3w", "un_area": "16_1341_1347_44750", "version": 14, "channel": 1, "babelChannel": 0}) await wait(3000) if (data.code === '0') { console.log('红包助力成功') } else if (data.code === '11') { console.log('红包已助力过') } else if (data.code === '13') { console.log('上限') break } } // 抽奖 for (let i = 0; i < res.remainLotteryTimes; i++) { data = await api('lotteryForTurntableFarm', {"type": 1, "version": 4, "channel": 1}) if (data.type === 'thanks') { console.log('抽奖获得 空气') } else { console.log('抽奖获得', data.type) } await wait(2000) } // 助力 shareCodePool = await getShareCodePool('farm', 30) shareCode = Array.from(new Set([...shareCodeSelf, ...shareCodePool])) for (let code of shareCodeSelf) { console.log('去助力', code) res = await api('initForFarm', {"mpin": "", "utm_campaign": "t_335139774", "utm_medium": "appshare", "shareCode": code, "utm_term": "Wxfriends", "utm_source": "iosapp", "imageUrl": "", "nickName": "", "version": 14, "channel": 2, "babelChannel": 0}) await wait(6000) o2s(res, '助力') if (res.helpResult.code === '7') { console.log('不给自己助力') } else if (res.helpResult.code === '0') { console.log('助力成功,获得', res.helpResult.salveHelpAddWater) } else if (res.helpResult.code === '8') { console.log('上限') break } else if (res.helpResult.code === '9') { console.log('已助力') } else if (res.helpResult.code === '10') { console.log('已满') } else if (res.helpResult.remainTimes === 0) { console.log('次数用完') break } } // 助力奖励 res = await api('farmAssistInit', {"version": 14, "channel": 1, "babelChannel": "120"}) await wait(1000) o2s(res, 'farmAssistInit') let farmAssistInit_waterEnergy: number = 0 for (let t of res.assistStageList) { if (t.percentage === '100%' && t.stageStaus === 2) { data = await api('receiveStageEnergy', {"version": 14, "channel": 1, "babelChannel": "120"}) await wait(1000) farmAssistInit_waterEnergy += t.waterEnergy } else if (t.stageStaus === 3) { farmAssistInit_waterEnergy += t.waterEnergy } } console.log('收到助力', res.assistFriendList.length) console.log('助力已领取', farmAssistInit_waterEnergy) message += `【助力已领取】 ${farmAssistInit_waterEnergy}\n` message += '\n\n' } catch (e) { console.log(e) } finally { await wait(5000) } } if (message) await sendNotify('东东农场', message) })() async function api(fn: string, body: object) { let h5st: string = h5stTool.__genH5st({ 'appid': 'wh5', 'body': JSON.stringify(body), 'client': 'apple', 'clientVersion': '10.2.4', 'functionId': fn, }) return await get(`https://api.m.jd.com/client.action?functionId=${fn}&body=${JSON.stringify(body)}&appid=wh5&client=apple&clientVersion=10.2.4&h5st=${h5st}`, { "Host": "api.m.jd.com", "Origin": "https://carry.m.jd.com", "User-Agent": USER_AGENT, "Accept-Language": "zh-CN,zh-Hans;q=0.9", "Referer": "https://carry.m.jd.com/", "Cookie": cookie }) }
the_stack
import { Property, Complex, ChildProperty, Collection } from '@syncfusion/ej2-base'; import { VisibleLabels, Size, VisibleRange, Rect, Align } from '../utils/helper'; import { Font, Border } from '../model/base'; import { FontModel, BorderModel } from '../model/base-model'; import { RangeModel, PointerModel, LabelModel, TickModel, LineModel } from './axis-model'; import { Point, Placement, MarkerType, Position} from '../utils/enum'; import { LinearGradientModel, RadialGradientModel} from '../axes/gradient-model'; /** Sets and gets the options for customizing the axis line in linear gauge. */ export class Line extends ChildProperty<Line> { /** * Sets and gets the dash-array of the axis line. */ @Property('') public dashArray: string; /** * Sets and gets the height of the axis line. * * @aspDefaultValueIgnore */ @Property(null) public height: number; /** * Sets and gets the width of the axis line. * * @default 2 */ @Property(2) public width: number; /** * Sets and gets the color for the axis line. */ @Property(null) public color: string; /** * Sets and gets the offset to position the axis line in linear gauge. * */ @Property(0) public offset: number; } /** * Sets and gets the options for customizing the appearance of the axis labels. */ export class Label extends ChildProperty<Label> { /** * Sets and gets the options for customizing the style of the text in axis labels. */ @Complex<FontModel>({ size: '12px', color: null, fontStyle: null, fontWeight: null }, Font) public font: FontModel; /** * Enables or disables the color of the label to use the color of the ranges in linear gauge. * * @default false */ @Property(false) public useRangeColor: boolean; /** * Sets and gets the format for the axis label. This property accepts any global format string like 'C', 'n1', 'P' etc. * Also accepts placeholder like '{value}°C' in which value represent the axis label e.g. 20°C. */ @Property('') public format: string; /** * Sets and gets the value to position the axis labels in linear gauge. * * @default 0 */ @Property(0) public offset: number; /** * Sets and gets the position of the axis label in linear gauge. * * @default Auto */ @Property('Auto') public position: Position; } /** * Sets and gets the options for customizing the ranges of an axis. */ export class Range extends ChildProperty<Range> { /** * Sets and gets the start value for the range in axis. * * @default 0 */ @Property(0) public start: number; /** * Sets and gets the end value for the range in axis. * * @default 0 */ @Property(0) public end: number; /** * Sets and gets the properties to render a linear gradient for the range. * If both linear and radial gradient is set, then the linear gradient will be rendered in the range. * * @default null */ @Property(null) public linearGradient: LinearGradientModel; /** * Sets and gets the properties to render a radial gradient for the range. * * @default null */ @Property(null) public radialGradient: RadialGradientModel; /** * Sets and gets the position to place the ranges in the axis. * * @default Outside */ @Property('Outside') public position: Position; /** * Sets and gets the color of the axis range. */ @Property('') public color: string; /** * Sets and gets the width of the start of the range in axis. * * @default 10 */ @Property(10) public startWidth: number; /** * Sets and gets the width of the end of the range in axis. * * @default 10 */ @Property(10) public endWidth: number; /** * Sets and gets the value to position the range in the axis. * * @default '0' */ @Property(0) public offset: number | string; /** * Sets and gets the options to customize the color and width of the border for the axis range. */ @Complex<BorderModel>({ color: '#000000', width: 0 }, Border) public border: BorderModel; /** @private */ public bounds: Rect; /** @private */ public path: string; /** @private */ public interior: string; /** @private */ public currentOffset: number; } /** * Sets and gets the options for customizing the minor tick lines in axis. */ export class Tick extends ChildProperty<Tick> { /** * Sets and gets the height of the tick line in the axis. */ @Property(20) public height: number; /** * Sets and gets the width of the tick line in the axis. * * @default 2 */ @Property(2) public width: number; /** * Sets and gets the gap between the ticks in the axis. * * @aspDefaultValueIgnore */ @Property(null) public interval: number; /** * Sets and gets the color for the major or minor tick line. This property accepts value in hex code, * rgba string as a valid CSS color string. */ @Property(null) public color: string; /** * Sets and gets the value to move the ticks from the axis. * * @aspDefaultValueIgnore */ @Property(null) public offset: number; /** * Sets and gets the value to place the ticks in the axis. * * @default Auto */ @Property('Auto') public position: Position; } /** * Sets and gets the options for customizing the pointers of an axis in linear gauge. */ export class Pointer extends ChildProperty<Pointer> { /** * Sets and gets the type of pointer in axis. * * @default Marker */ @Property('Marker') public type: Point; /** * Sets and gets the properties to render a linear gradient for the pointer. * If both linear and radial gradient is set, then the linear gradient will be rendered in the pointer. * * @default null */ @Property(null) public linearGradient: LinearGradientModel; /** * Sets and gets the properties to render a radial gradient for the pointer. * * @default null */ @Property(null) public radialGradient: RadialGradientModel; /** * Sets and gets the value of the pointer in axis. * * @default null */ @Property(null) public value: number; /** * Sets and gets the type of the marker for pointers in axis. * * @default InvertedTriangle */ @Property('InvertedTriangle') public markerType: MarkerType; /** * Sets and gets the URL path for the image in marker when the marker type is chosen as image. * * @default null */ @Property(null) public imageUrl: string; /** * Sets and gets the options to optimize the color and width of the border for pointers. */ @Complex<BorderModel>({ color: '#808080' }, Border) public border: BorderModel; /** * Sets and gets the corner radius for pointer. * * @default 10 */ @Property(10) public roundedCornerRadius: number; /** * Sets and gets the place of the pointer. * * @default Far */ @Property('Far') public placement: Placement; /** * Sets and gets the height of the pointer. * * @default 20 */ @Property(20) public height: number; /** * Sets and gets the width of the pointer. * * @default 20 */ @Property(20) public width: number; /** * Sets and gets the color of the pointer. */ @Property(null) public color: string; /** * Sets and gets the opacity of pointer in linear gauge. * * @default 1 */ @Property(1) public opacity: number; /** * Sets and gets the duration of animation in pointer. * * @default 0 */ @Property(0) public animationDuration: number; /** * Enables or disables the drag movement of pointer. * * @default false */ @Property(false) public enableDrag: boolean; /** * Sets and gets the value to position the pointer from the axis. * * @default '0' */ @Property(0) public offset: number | string; /** * Sets and gets the position of the pointer. * * @default Auto */ @Property('Auto') public position: Position; /** * Sets and gets the description for the pointer. * * @default null */ @Property(null) public description: string; /** @private */ public bounds: Rect; /** @private */ public startValue: number; /** @private */ public animationComplete: boolean = true; /** @private */ public currentValue: number = null; /** @private */ public currentOffset: number; /** @private */ public pathElement: Element[]; } /** * Sets and gets the options for customizing the axis of a gauge. */ export class Axis extends ChildProperty<Axis> { /** * Sets and gets the minimum value for the axis. * * @default 0 */ @Property(0) public minimum: number; /** * Sets and gets the maximum value for the axis. * * @default 100 */ @Property(100) public maximum: number; /** * Enables or disables the inversed axis. */ @Property(false) public isInversed: boolean; /** * Shows or hides the last label in the axis of the linear gauge. */ @Property(false) public showLastLabel: boolean; /** * Enables or disables the opposed position of the axis in the linear gauge. */ @Property(false) public opposedPosition: boolean; /** * Sets and gets the options for customizing the axis line. */ @Complex(<LineModel>{}, Line) public line: LineModel; /** * Sets and gets the options for customizing the ranges of an axis. */ @Collection<RangeModel>([{}], Range) public ranges: RangeModel[]; /** * Sets and gets the options for customizing the pointers of an axis. */ @Collection<PointerModel>([{}], Pointer) public pointers: PointerModel[]; /** * Sets and gets the options for customizing the major tick lines. */ @Complex<TickModel>({ width: 2, height: 20 }, Tick) public majorTicks: TickModel; /** * Sets and gets the options for customizing the minor tick lines. */ @Complex<TickModel>({ width: 1, height: 10 }, Tick) public minorTicks: TickModel; /** * Sets and gets the options for customizing the appearance of the label in axis. */ @Complex<LabelModel>({}, Label) public labelStyle: LabelModel; /** @private */ public visibleLabels: VisibleLabels[] = []; /** @private */ public maxLabelSize: Size; /** @private */ public visibleRange: VisibleRange; /** @private */ public lineBounds: Rect; /** @private */ public majorTickBounds: Rect; /** @private */ public minorTickBounds: Rect; /** @private */ public labelBounds: Rect; /** @private */ public pointerBounds: Rect; /** @private */ public bounds: Rect; /** @private */ public maxTickLength: number; /** @private */ public checkAlign: Align; /** @private */ public majorInterval: number; /** @private */ public minorInterval: number; }
the_stack
import { Cell, ICell } from './cell.ts'; import { IRow, Row } from './row.ts'; import type { IBorderOptions, ITableSettings, Table } from './table.ts'; import { consumeWords, longest, stripeColors } from './utils.ts'; interface IRenderSettings { padding: number[]; width: number[]; columns: number; hasBorder: boolean; hasHeaderBorder: boolean; hasBodyBorder: boolean; rows: Row<Cell>[]; } export class TableLayout { public constructor( private table: Table, private options: ITableSettings ) {} public toString(): string { const opts: IRenderSettings = this.createLayout(); return opts.rows.length ? this.renderRows( opts ) : ''; } protected createLayout(): IRenderSettings { Object.keys( this.options.chars ).forEach( ( key: string ) => { if ( typeof this.options.chars[ key as keyof IBorderOptions ] !== 'string' ) { this.options.chars[ key as keyof IBorderOptions ] = ''; } } ); const hasBodyBorder: boolean = this.table.getBorder() || this.table.hasBodyBorder(); const hasHeaderBorder: boolean = this.table.hasHeaderBorder(); const hasBorder: boolean = hasHeaderBorder || hasBodyBorder; const header: Row | undefined = this.table.getHeader(); const rows: Row<Cell>[] = this.spanRows( header ? [ header, ...this.table ] : this.table.slice() ); const columns: number = Math.max( ...rows.map( row => row.length ) ); for ( const row of rows ) { const length: number = row.length; if ( length < columns ) { const diff = columns - length; for ( let i = 0; i < diff; i++ ) { row.push( this.createCell( null, row ) ); } } } const padding: number[] = []; const width: number[] = []; for ( let colIndex: number = 0; colIndex < columns; colIndex++ ) { const minCellWidth: number = Array.isArray( this.options.minCellWidth ) ? this.options.minCellWidth[ colIndex ] : this.options.minCellWidth; const maxCellWidth: number = Array.isArray( this.options.maxCellWidth ) ? this.options.maxCellWidth[ colIndex ] : this.options.maxCellWidth; const cellWidth: number = longest( colIndex, rows, maxCellWidth ); width[ colIndex ] = Math.min( maxCellWidth, Math.max( minCellWidth, cellWidth ) ); padding[ colIndex ] = Array.isArray( this.options.padding ) ? this.options.padding[ colIndex ] : this.options.padding; } return { padding, width, rows, columns, hasBorder, hasBodyBorder, hasHeaderBorder }; } protected spanRows( _rows: IRow[], rowIndex: number = 0, colIndex: number = 0, rowSpan: number[] = [], colSpan: number = 1 ): Row<Cell>[] { const rows: Row<Cell>[] = _rows as Row<Cell>[]; if ( rowIndex >= rows.length && rowSpan.every( span => span === 1 ) ) { return rows; } else if ( rows[ rowIndex ] && colIndex >= rows[ rowIndex ].length && colIndex >= rowSpan.length && colSpan === 1 ) { return this.spanRows( rows, ++rowIndex, 0, rowSpan, 1 ); } if ( colSpan > 1 ) { colSpan--; rowSpan[ colIndex ] = rowSpan[ colIndex - 1 ]; rows[ rowIndex ].splice( colIndex - 1, 0, rows[ rowIndex ][ colIndex - 1 ] ); return this.spanRows( rows, rowIndex, ++colIndex, rowSpan, colSpan ); } if ( colIndex === 0 ) { rows[ rowIndex ] = this.createRow( rows[ rowIndex ] || [] ); } if ( rowSpan[ colIndex ] > 1 ) { rowSpan[ colIndex ]--; rows[ rowIndex ].splice( colIndex, 0, rows[ rowIndex - 1 ][ colIndex ] ); return this.spanRows( rows, rowIndex, ++colIndex, rowSpan, colSpan ); } rows[ rowIndex ][ colIndex ] = this.createCell( rows[ rowIndex ][ colIndex ] || null, rows[ rowIndex ] ); colSpan = rows[ rowIndex ][ colIndex ].getColSpan(); rowSpan[ colIndex ] = rows[ rowIndex ][ colIndex ].getRowSpan(); return this.spanRows( rows, rowIndex, ++colIndex, rowSpan, colSpan ); } protected createRow( row: IRow ): Row<Cell> { return Row.from( row ).border( this.table.getBorder(), false ) as Row<Cell>; } protected createCell( cell: ICell | null, row: Row ): Cell { return Cell.from( cell ?? '' ).border( row.getBorder(), false ); } protected renderRows( opts: IRenderSettings ): string { let result: string = ''; const rowSpan: number[] = new Array( opts.columns ).fill( 1 ); for ( let rowIndex = 0; rowIndex < opts.rows.length; rowIndex++ ) { result += this.renderRow( rowSpan, rowIndex, opts ); } return result.slice( 0, -1 ); } protected renderRow( rowSpan: number[], rowIndex: number, opts: IRenderSettings, inMultiline?: boolean ): string { const row: Row<Cell> = opts.rows[ rowIndex ]; const prevRow: Row<Cell> | undefined = opts.rows[ rowIndex - 1 ]; const nextRow: Row<Cell> | undefined = opts.rows[ rowIndex + 1 ]; let result: string = ''; let colSpan: number = 1; // border top row if ( !inMultiline && rowIndex === 0 && row.hasBorder() ) { result += this.renderBorderRow( undefined, row, rowSpan, opts ); } let isMultilineRow: boolean = false; result += ' '.repeat( this.options.indent || 0 ); for ( let colIndex = 0; colIndex < opts.columns; colIndex++ ) { if ( colSpan > 1 ) { colSpan--; rowSpan[ colIndex ] = rowSpan[ colIndex - 1 ]; continue; } result += this.renderCell( colIndex, row, prevRow, rowSpan, opts ); if ( rowSpan[ colIndex ] > 1 ) { if ( !inMultiline ) { rowSpan[ colIndex ]--; } } else if ( !prevRow || prevRow[ colIndex ] !== row[ colIndex ] ) { rowSpan[ colIndex ] = row[ colIndex ].getRowSpan(); } colSpan = row[ colIndex ].getColSpan(); if ( rowSpan[ colIndex ] === 1 && row[ colIndex ].length ) { isMultilineRow = true; } } if ( opts.columns > 0 ) { if ( row[ opts.columns - 1 ].getBorder() ) { result += this.options.chars.right; } else if ( opts.hasBorder ) { result += ' '; } } result += '\n'; if ( isMultilineRow ) { // skip border return result + this.renderRow( rowSpan, rowIndex, opts, isMultilineRow ); } // border mid row if ( ( rowIndex === 0 && opts.hasHeaderBorder ) || ( rowIndex < opts.rows.length - 1 && opts.hasBodyBorder ) ) { result += this.renderBorderRow( row, nextRow, rowSpan, opts ); } // border bottom row if ( rowIndex === opts.rows.length - 1 && row.hasBorder() ) { result += this.renderBorderRow( row, undefined, rowSpan, opts ); } return result; } protected renderCell( colIndex: number, row: Row<Cell>, prevRow: Row<Cell> | undefined, rowSpan: number[], opts: IRenderSettings, noBorder?: boolean ): string { let result: string = ''; const prevCell: Cell | undefined = row[ colIndex - 1 ]; const cell: Cell = row[ colIndex ]; if ( !noBorder ) { if ( colIndex === 0 ) { if ( cell.getBorder() ) { result += this.options.chars.left; } else if ( opts.hasBorder ) { result += ' '; } } else { if ( cell.getBorder() || prevCell?.getBorder() ) { result += this.options.chars.middle; } else if ( opts.hasBorder ) { result += ' '; } } } let maxLength: number = opts.width[ colIndex ]; const colSpan: number = cell.getColSpan(); if ( colSpan > 1 ) { for ( let o = 1; o < colSpan; o++ ) { // add padding and with of next cell maxLength += opts.width[ colIndex + o ] + opts.padding[ colIndex + o ]; if ( opts.hasBorder ) { // add padding again and border with maxLength += opts.padding[ colIndex + o ] + 1; } } } const { current, next } = this.renderCellValue( cell, maxLength ); row[ colIndex ].setValue( next ); if ( opts.hasBorder ) { result += ' '.repeat( opts.padding[ colIndex ] ); } result += current; if ( opts.hasBorder || colIndex < opts.columns - 1 ) { result += ' '.repeat( opts.padding[ colIndex ] ); } return result; } protected renderCellValue( cell: Cell, maxLength: number ): { current: string, next: Cell } { const length: number = Math.min( maxLength, stripeColors( cell.toString() ).length ); let words: string = consumeWords( length, cell.toString() ); // break word if word is longer than max length const breakWord = stripeColors( words ).length > length; if ( breakWord ) { words = words.slice( 0, length ); } // get next content and remove leading space if breakWord is not true const next = cell.toString().slice( words.length + ( breakWord ? 0 : 1 ) ); const fillLength = maxLength - stripeColors( words ).length; const current = words + ' '.repeat( fillLength ); return { current, next: cell.clone( next ) }; } protected renderBorderRow( prevRow: Row<Cell> | undefined, nextRow: Row<Cell> | undefined, rowSpan: number[], opts: IRenderSettings ): string { let result = ''; let colSpan: number = 1; for ( let colIndex = 0; colIndex < opts.columns; colIndex++ ) { if ( rowSpan[ colIndex ] > 1 ) { if ( !nextRow ) { throw new Error( 'invalid layout' ); } if ( colSpan > 1 ) { colSpan--; continue; } } result += this.renderBorderCell( colIndex, prevRow, nextRow, rowSpan, opts ); colSpan = nextRow?.[ colIndex ].getColSpan() ?? 1; } return result.length ? ' '.repeat( this.options.indent ) + result + '\n' : ''; } protected renderBorderCell( colIndex: number, prevRow: Row<Cell> | undefined, nextRow: Row<Cell> | undefined, rowSpan: number[], opts: IRenderSettings ): string { // a1 | b1 // ------- // a2 | b2 const a1: Cell | undefined = prevRow?.[ colIndex - 1 ]; const a2: Cell | undefined = nextRow?.[ colIndex - 1 ]; const b1: Cell | undefined = prevRow?.[ colIndex ]; const b2: Cell | undefined = nextRow?.[ colIndex ]; const a1Border: boolean = !!a1?.getBorder(); const a2Border: boolean = !!a2?.getBorder(); const b1Border: boolean = !!b1?.getBorder(); const b2Border: boolean = !!b2?.getBorder(); const hasColSpan = ( cell: Cell | undefined ): boolean => ( cell?.getColSpan() ?? 1 ) > 1; const hasRowSpan = ( cell: Cell | undefined ): boolean => ( cell?.getRowSpan() ?? 1 ) > 1; let result = ''; if ( colIndex === 0 ) { if ( rowSpan[ colIndex ] > 1 ) { if ( b1Border ) { result += this.options.chars.left; } else { result += ' '; } } else if ( b1Border && b2Border ) { result += this.options.chars.leftMid; } else if ( b1Border ) { result += this.options.chars.bottomLeft; } else if ( b2Border ) { result += this.options.chars.topLeft; } else { result += ' '; } } else if ( colIndex < opts.columns ) { if ( ( a1Border && b2Border ) || ( b1Border && a2Border ) ) { const a1ColSpan: boolean = hasColSpan( a1 ); const a2ColSpan: boolean = hasColSpan( a2 ); const b1ColSpan: boolean = hasColSpan( b1 ); const b2ColSpan: boolean = hasColSpan( b2 ); const a1RowSpan: boolean = hasRowSpan( a1 ); const a2RowSpan: boolean = hasRowSpan( a2 ); const b1RowSpan: boolean = hasRowSpan( b1 ); const b2RowSpan: boolean = hasRowSpan( b2 ); const hasAllBorder = a1Border && b2Border && b1Border && a2Border; const hasAllRowSpan = a1RowSpan && b1RowSpan && a2RowSpan && b2RowSpan; const hasAllColSpan = a1ColSpan && b1ColSpan && a2ColSpan && b2ColSpan; if ( hasAllRowSpan && hasAllBorder ) { result += this.options.chars.middle; } else if ( hasAllColSpan && hasAllBorder && a1 === b1 && a2 === b2 ) { result += this.options.chars.mid; } else if ( a1ColSpan && b1ColSpan && a1 === b1 ) { result += this.options.chars.topMid; } else if ( a2ColSpan && b2ColSpan && a2 === b2 ) { result += this.options.chars.bottomMid; } else if ( a1RowSpan && a2RowSpan && a1 === a2 ) { result += this.options.chars.leftMid; } else if ( b1RowSpan && b2RowSpan && b1 === b2 ) { result += this.options.chars.rightMid; } else { result += this.options.chars.midMid; } } else if ( a1Border && b1Border ) { if ( hasColSpan( a1 ) && hasColSpan( b1 ) && a1 === b1 ) { result += this.options.chars.bottom; } else { result += this.options.chars.bottomMid; } } else if ( b1Border && b2Border ) { if ( rowSpan[ colIndex ] > 1 ) { result += this.options.chars.left; } else { result += this.options.chars.leftMid; } } else if ( b2Border && a2Border ) { if ( hasColSpan( a2 ) && hasColSpan( b2 ) && a2 === b2 ) { result += this.options.chars.top; } else { result += this.options.chars.topMid; } } else if ( a1Border && a2Border ) { if ( hasRowSpan( a1 ) && a1 === a2 ) { result += this.options.chars.right; } else { result += this.options.chars.rightMid; } } else if ( a1Border ) { result += this.options.chars.bottomRight; } else if ( b1Border ) { result += this.options.chars.bottomLeft; } else if ( a2Border ) { result += this.options.chars.topRight; } else if ( b2Border ) { result += this.options.chars.topLeft; } else { result += ' '; } } const length = opts.padding[ colIndex ] + opts.width[ colIndex ] + opts.padding[ colIndex ]; if ( rowSpan[ colIndex ] > 1 && nextRow ) { result += this.renderCell( colIndex, nextRow, prevRow, rowSpan, opts, true ); if ( nextRow[ colIndex ] === nextRow[ nextRow.length - 1 ] ) { if ( b1Border ) { result += this.options.chars.right; } else { result += ' '; } return result; } } else if ( b1Border && b2Border ) { result += this.options.chars.mid.repeat( length ); } else if ( b1Border ) { result += this.options.chars.bottom.repeat( length ); } else if ( b2Border ) { result += this.options.chars.top.repeat( length ); } else { result += ' '.repeat( length ); } if ( colIndex === opts.columns - 1 ) { if ( b1Border && b2Border ) { result += this.options.chars.rightMid; } else if ( b1Border ) { result += this.options.chars.bottomRight; } else if ( b2Border ) { result += this.options.chars.topRight; } else { result += ' '; } } return result; } }
the_stack
import { animate, state, style, transition, trigger } from '@angular/animations'; import { AfterViewInit, ChangeDetectorRef, Component, ContentChild, ElementRef, EventEmitter, forwardRef, HostListener, Input, OnChanges, OnInit, Output, QueryList, Renderer2, SimpleChanges, TemplateRef, ViewChild, ViewChildren, } from '@angular/core'; import { FormControl, NG_VALIDATORS, NG_VALUE_ACCESSOR, NgModel, Validators } from '@angular/forms'; import { of } from 'rxjs'; import { CommonDataService } from '../../services/data/common.data.service'; import { DisplayFieldService } from '../../services/data/display.field.service'; import { DropDownListComponent } from './../../base/dropdownlist.component'; import { ListBaseComponent } from './../../base/list.base.component'; @Component({ selector: 'amexio-typeahead', templateUrl: './typeahead.component.html', animations: [ trigger('changeState', [ state('visible', style({ 'max-height': '200px', })), state('hidden', style({ 'max-height': '0px', })), transition('*=>*', animate('200ms')), ]), ], providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: AmexioTypeAheadComponent, multi: true, }, { provide: NG_VALIDATORS, useExisting: forwardRef(() => AmexioTypeAheadComponent), multi: true, }], }) export class AmexioTypeAheadComponent extends ListBaseComponent<string> implements OnChanges, OnInit, AfterViewInit, Validators { private _fieldlabel: string; private _haslabel: boolean; private _key: any; public viewdata: any; public displayValue = ''; /* Properties name : field-label datatype : string version : 4.0 onwards default : description : The label of this field */ @Input('field-label') set fieldlabel(v: string) { if (v != null && v.length > 0) { this._fieldlabel = v; this.initComponent(); } } get fieldlabel() { return this._fieldlabel; } /* Properties name : has-label datatype : boolean version : 4.0 onwards default : false description : Flag to set label */ @Input('has-label') set haslabel(v: boolean) { this._haslabel = v; } get haslabel(): boolean { return this._haslabel; } /* Properties name : data datatype : any version : 4.0 onwards default : description : Local data for dropdown. */ _data: any; componentLoaded: boolean; @Input('data') set data(value: any) { this._data = value; if (this.componentLoaded) { this.setData(this._data); } } get data(): any { return this._data; } @Input('key') set key(v: any) { this._key = v; this.displayfield = this._key; } get key(): any { return this._key; } @Input('allow-blank') allowblank: boolean; @Input('data-reader') datareader: string; @Input('http-method') httpmethod: string; @Input('http-url') httpurl: string; @Input('display-field') displayfield: string; @Input('value-field') valuefield: string; @Input('place-holder') placeholder: string; @Input('icon-feedback') iconfeedback: boolean; @Input('font-style') fontstyle: string; @Input('font-family') fontfamily: string; @Input('font-size') fontsize: string; @Input('enable-popover') enablepopover: boolean; @Input('trigger-char') triggerchar: number; @Input() name: string; @Input() disabled: boolean; @Output() onBlur: any = new EventEmitter<any>(); @Output('input') onInputOutput: any = new EventEmitter<any>(); @Output('focus') onFocusOutput: any = new EventEmitter<any>(); @Output() change: any = new EventEmitter<any>(); @Output() onClick: any = new EventEmitter<any>(); @Output() isComponentValid: any = new EventEmitter<any>(); @ViewChild(NgModel) model: NgModel; @ViewChildren(DropDownListComponent) private dropdownlist: QueryList<DropDownListComponent>; dropdown: DropDownListComponent[]; @ContentChild('amexioBodyTmpl') bodyTemplate: TemplateRef<any>; rowindex = 0; componentId: string; maskloader = true; ariaListExpand = false; isValid: boolean; responseData: any; previousData: any; filterarray: any = []; constructor( private displayFieldService: DisplayFieldService, public dataService: CommonDataService, public element: ElementRef, renderer: Renderer2, cd: ChangeDetectorRef) { super(renderer, element, cd); } ngAfterViewInit() { this.dropdown = this.dropdownlist.toArray(); setTimeout(() => { this.dropdown.forEach((dropdown) => { dropdown.template = this.bodyTemplate; }); }, 200); } ngOnChanges(changes: SimpleChanges) { if (changes.placeholder && !changes.placeholder.isFirstChange()) { this.placeholder = changes.placeholder.currentValue; } } ngOnInit() { this.name = this.generateName(this.name, this.fieldlabel, 'typeaheadinput'); this.componentId = this.createCompId('typeahead', this.displayfield); if (!this.valuefield) { this.valuefield = this.displayfield; } this.isValid = this.allowblank; this.isComponentValid.emit(this.allowblank); if (this.placeholder === '' || this.placeholder == null) { this.placeholder = 'Choose Option'; } if (!this.triggerchar) { this.triggerchar = 1; } if (this.httpmethod && this.httpurl) { this.dataService.fetchData(this.httpurl, this.httpmethod).subscribe((response) => { this.responseData = response; }, (error) => { }, () => { this.setData(this.responseData); }); } else if (this.data) { this.previousData = JSON.parse(JSON.stringify(this.data)); this.setData(this.data); } this.componentLoaded = true; } generateIndex() { this.viewdata.value.forEach((element: any, index: number) => { element['index'] = this.componentId + 'listitem' + index; }); } closeOnEScapeKey(event: any) { this.ariaListExpand = false; this.hide(); } input(event: any) { this.filterarray = []; let value: string; this.displayValue = event.target.value; this.rowindex = 0; if (this.displayValue.length >= 0 && !this.self && this.displayValue.length >= this.triggerchar) { this.dropdownstyle = { visibility: 'visible' }; this.ariaListExpand = true; this.bindDocumentClickListener(); } else { this.dropdownstyle = { visibility: 'hidden' }; this.ariaListExpand = false; } this.onInputOutput.emit(event); if (this.displayValue.length > 0) { if (this.displayValue === this.displayValue.toUpperCase()) { value = this.displayValue.toLowerCase(); } else { value = this.displayValue; } this.viewdata.value.forEach((element: any) => { if ((this.displayFieldService.findValue(this.displayfield, element).toLowerCase()).startsWith(value)) { this.filterarray.push(element); } }); } } focustoLast() { this.rowindex = this.filterarray.length - 1; this.setScrollToList(this.rowindex); this.setAriaActiveDescendant(this.rowindex); } focus(event: any) { this.self = true; this.dropdownstyle = { visibility: 'hidden' }; this.bindDocumentClickListener(); this.onFocusOutput.emit(event); } keyup(event: any) { const keycode: number = event.keyCode; if (keycode === 40) { this.rowindex++; } else if (keycode === 38) { this.rowindex--; } else if (keycode === 40 || keycode === 38) { this.rowindex = 0; } if (this.rowindex < 0) { this.rowindex = this.filterarray.length - 1; } else if (this.rowindex >= this.filterarray.length) { this.rowindex = 0; } this.setAriaActiveDescendant(this.rowindex); if (keycode === 13) { const data = this.dropdown[0].selectedItem(); this.value = data[0].attributes['valuefield'].value; this.displayValue = data[0].attributes['displayfield'].value; this.itemClicked(); this.isComponentValid.emit(true); } else if (keycode === 40 || keycode === 38) { this.dropdown[0].scroll(this.rowindex); } } // METHOS FOR BLUR EVENT blur(event: any) { super.blur(event); const userinput: string = event.target.value; const listitems: any[] = this.viewdata.value; listitems.forEach((item) => { if ((this.displayFieldService.findValue(this.displayfield, item) + '').toLowerCase() === userinput.toLowerCase()) { this.displayValue = this.displayFieldService.findValue(this.displayfield, item); this.value = item[this.valuefield]; this.isComponentValid.emit(true); } }); this.onBlur.emit(event); } // METHOD TO DISPLAY ITEM WHEN SELECTED onDropDownListItemClick(data: any) { if (this.valuefield) { this.value = data[this.valuefield]; } else { this.value = this.displayFieldService.findValue(this.displayfield, data); } this.displayValue = this.displayFieldService.findValue(this.displayfield, data); this.onClick.emit(data); this.ariaListExpand = false; } // METHOD TO READ CURRENT ELEMENT FOCUSED setAriaActiveDescendant(rowindex: any) { if (this.filterarray.length > 0) { const inputid = document.getElementById(this.componentId); inputid.setAttribute('aria-activedescendant', this.filterarray[rowindex].index); } else if (this.displayValue.length < 1) { const inputid = document.getElementById(this.componentId); inputid.setAttribute('aria-activedescendant', 'listitem'); } } // METHOD TO SET SCROLL BASED ON ROWINDEX setScrollToList(rowindex: any) { const listitems = this.element.nativeElement.getElementsByClassName('list-items')[rowindex]; if (listitems) { listitems.scrollIntoView({ behavior: 'smooth' }); } } writeValue(v: any) { super.writeValue(v); if (v && this.viewdata) { this.showValue(); } } private showValue() { const listitems: any[] = this.viewdata.value; listitems.forEach((item) => { if (item[this.valuefield] === this.value) { this.displayValue = this.displayFieldService.findValue(this.displayfield, item); this.isComponentValid.emit(true); } }); } // METHOD TO INITIALIZE COMPONENT initComponent() { if (this.fieldlabel != null && this.fieldlabel.length > 0) { this.haslabel = true; } } // METHOD TO EMIT CHANGE EVENT onChange(event: any) { if (event != null) { this.change.emit(event); } } // METHOD TO SET DATA IN DROPDOWN setData(httpResponse: any) { let responsedata = httpResponse; if (this.datareader != null) { const dr = this.datareader.split('.'); for (const ir of dr) { responsedata = responsedata[ir]; } } else { responsedata = httpResponse; } this.viewdata = of(responsedata); this.generateIndex(); // SET USER SELECTION if (this.value != null) { const valueKey = this.valuefield; const displayKey = this.displayfield; const val = this.value; this.viewdata.forEach((item: any) => { if (item[valueKey] === val) { this.isValid = true; this.displayValue = item[displayKey]; } }); } this.maskloader = false; } public validate(c: FormControl) { return ((!this.allowblank && this.value) || this.allowblank) ? null : { jsonParseError: { valid: true, }, }; } }
the_stack
import { createAction, ACTION_PARAMETERS } from '@tramvai/core'; import { createContainer } from '@tinkoff/dippy'; import { ActionExecution } from './actionExecution'; import { alwaysCondition } from './conditions/always'; import { actionType } from './constants'; const contextMock = { isContext: true }; const createActionNameFactory = (name, result, conditions = {}) => createAction({ fn: (c, payload) => result.push(`action: ${name} with: ${payload}`), name, conditions, }); describe('actionExecution in global page', () => { it('Запуск page действий без каких либо опций', async () => { const instance = new ActionExecution({ di: createContainer(), store: { getState: (reducer?: any) => { if (reducer) { return undefined; } return {}; }, } as any, actionConditionals: [], // @ts-ignore context: contextMock, }); const result = []; const action1 = createActionNameFactory('action1', result); const action2 = createActionNameFactory('action2', result); await instance.run(action1, '@globalAction', actionType.global); await instance.run(action2, '@globalAction', actionType.global); expect(result).toMatchInlineSnapshot(` Array [ "action: action1 with: @globalAction", "action: action2 with: @globalAction", ] `); // Экшен не должен выполниться. Автоматическиая дедубликация await instance.run(action1, '@globalAction', actionType.global); await instance.run(action1, '@globalAction', actionType.global); await instance.run(action2, '@globalAction', actionType.global); await instance.run(action2, '@globalAction', actionType.global); await instance.run(action1, '@globalAction', actionType.global); expect(result).toMatchInlineSnapshot(` Array [ "action: action1 with: @globalAction", "action: action2 with: @globalAction", ] `); }); it('Запуск page экшенов с фильтрами', async () => { const instance = new ActionExecution({ di: createContainer(), store: { getState: (reducer?: any) => { if (reducer) { return undefined; } return {}; }, } as any, actionConditionals: [ { key: 'neverCondition', fn: (cheker) => { if (cheker.conditions.never) { cheker.forbid(); } }, }, ], // @ts-ignore context: contextMock, }); const result = []; await instance.run( createActionNameFactory('action1', result), '@globalAction', actionType.global ); await instance.run( createActionNameFactory('action2', result, { never: true }), '@globalAction', actionType.global ); await instance.run( createActionNameFactory('action3', result, { never: true }), '@globalAction', actionType.global ); await instance.run( createActionNameFactory('action4', result), '@globalAction', actionType.global ); expect(result).toMatchInlineSnapshot(` Array [ "action: action1 with: @globalAction", "action: action4 with: @globalAction", ] `); }); it('Множественный запуск page actions с проверкой, что только измененые экшены запускаются ', async () => { const instance = new ActionExecution({ di: createContainer(), store: { getState: (reducer?: any) => { if (reducer) { return undefined; } return {}; }, } as any, actionConditionals: [alwaysCondition], // @ts-ignore context: contextMock, }); const result = []; const action1 = createActionNameFactory('action multi 1', result); const action2 = createActionNameFactory('action multi 2', result, { always: true }); await instance.run(action1, '@globalAction', actionType.global); await instance.run(action2, '@globalAction', actionType.global); expect(result).toMatchInlineSnapshot(` Array [ "action: action multi 1 with: @globalAction", "action: action multi 2 with: @globalAction", ] `); await instance.run( createActionNameFactory('action multi 1', result), '@globalAction', actionType.global ); await instance.run(action2, '@globalAction', actionType.global); expect(result).toMatchInlineSnapshot(` Array [ "action: action multi 1 with: @globalAction", "action: action multi 2 with: @globalAction", "action: action multi 2 with: @globalAction", ] `); }); it('Востанавливаем состояние выполненных экшенов и проверяем на влияние будущих экшенов', async () => { const state = { actionTramvai: { serverState: { 'action resume 1': { status: 'success', state: { test: '@globalAction' } }, 'action resume 3': { status: 'success', state: { test: '@globalAction' } }, }, }, }; const instance = new ActionExecution({ di: createContainer(), store: { getState: (reducer?: any) => { if (reducer) { return state[reducer.storeName]; } return state; }, } as any, actionConditionals: [ { key: 'test', fn: (cheker) => { const last = cheker.payload; if (cheker.getState() !== last) { cheker.setState(last); cheker.allow(); } }, }, ], // @ts-ignore context: contextMock, }); const result = []; const action1 = createActionNameFactory('action resume 1', result); const action2 = createActionNameFactory('action resume 2', result); const action3 = createActionNameFactory('action resume 3', result); await instance.run(action1, '@globalAction', actionType.global); await instance.run(action2, '@globalAction', actionType.global); await instance.run(action3, '@globalAction', actionType.global); await instance.run(action3, '@globalAction', actionType.global); await instance.run(action3, '@globalAction', actionType.global); expect(result).toMatchInlineSnapshot(` Array [ "action: action resume 2 with: @globalAction", ] `); }); it('Получение и использование значений переданных в conditions экшенов', async () => { const instance = new ActionExecution({ di: createContainer(), store: { getState: (reducer?: any) => { if (reducer) { return undefined; } return {}; }, } as any, actionConditionals: [ { key: 'value', fn: (cheker) => { const { role } = cheker.conditions; if (role) { if (cheker.getState() !== role) { cheker.setState(role); cheker.allow(); } } }, }, ], // @ts-ignore context: contextMock, }); const result = []; const action1 = createActionNameFactory('action 1', result, { role: 'client' }); const action2 = createActionNameFactory('action 1', result, { role: 'admin' }); await instance.run(action1, '@globalAction', actionType.global); await instance.run(action1, '@globalAction', actionType.global); await instance.run(action1, '@globalAction', actionType.global); await instance.run(action2, '@globalAction', actionType.global); await instance.run(action2, '@globalAction', actionType.global); await instance.run(action1, '@globalAction', actionType.global); // Выполняем экшены по одному разу, дальше из-за одинакового conditions, скипаем expect(result).toMatchInlineSnapshot(` Array [ "action: action 1 with: @globalAction", "action: action 1 with: @globalAction", "action: action 1 with: @globalAction", ] `); }); it('Передаем в экшены di, если были добавлены в deps', async () => { const instance = new ActionExecution({ di: createContainer([ { provide: 'dep1', useValue: 'dep1 value' }, { provide: 'dep2', useValue: 'dep2 value' }, ]), store: { getState: (reducer?: any) => { if (reducer) { return undefined; } return {}; }, } as any, actionConditionals: [], // @ts-ignore context: contextMock, }); const result = []; await instance.run( createAction({ fn: (context, payload, deps) => result.push([context, payload, deps]), name: 'action1', deps: { dep1: 'dep1', dep2: 'dep2' }, }), '@globalAction', actionType.global ); await instance.run( createAction({ fn: (context, payload, deps) => result.push([context, payload, deps]), name: 'action2', deps: { dep2: 'dep2' }, }), '@globalAction', actionType.global ); // Экшен не должен выполниться. Автоматическиая дедубликация await instance.run( createAction({ fn: (context, payload, deps) => result.push([context, payload, deps]), name: 'action1', }), '@globalAction', actionType.global ); expect(result).toMatchSnapshot(); }); it('Преобразование экшенов с старого вида в новый через transformAction', async () => { const instance = new ActionExecution({ di: createContainer(), store: { getState: (reducer?: any) => { if (reducer) { return undefined; } return {}; }, } as any, actionConditionals: [], // @ts-ignore context: contextMock, transformAction: (action: any) => { if (!action[ACTION_PARAMETERS]) { return createAction({ fn: action, name: action.name }); } return action; }, }); const result = []; await instance.run( createActionNameFactory('action1', result), '@globalAction', actionType.global ); const actionOld = (c, payload) => result.push(payload); await instance.run(actionOld as any, '@globalAction', actionType.global); expect(result).toMatchInlineSnapshot(` Array [ "action: action1 with: @globalAction", "@globalAction", ] `); }); }); describe('actionExecution in actions', () => { it('Запуск множество экшенов без каких либо опций с изначальным стейтом', async () => { const state = { actionTramvai: { serverState: { action1: { status: 'success', state: {} }, action2: { status: 'success', state: {} }, }, }, }; const instance = new ActionExecution({ di: createContainer(), store: { getState: (reducer?: any) => { if (reducer) { return state[reducer.storeName]; } return state; }, } as any, actionConditionals: [], // @ts-ignore context: contextMock, }); const result = []; const action1 = createActionNameFactory('action1', result); const action2 = createActionNameFactory('action2', result); await instance.run(action1, 1); await instance.run(action2, 2); expect(result).toMatchInlineSnapshot(` Array [ "action: action1 with: 1", "action: action2 with: 2", ] `); // Экшен не должен выполниться. Автоматическиая дедубликация await instance.run(action1, 3); await instance.run(action1, 4); await instance.run(action2, 5); expect(result).toMatchInlineSnapshot(` Array [ "action: action1 with: 1", "action: action2 with: 2", "action: action1 with: 3", "action: action1 with: 4", "action: action2 with: 5", ] `); }); it('Ограничение по ролям', async () => { const instance = new ActionExecution({ di: createContainer(), store: { getState: (reducer?: any) => { if (reducer) { return undefined; } return {}; }, } as any, actionConditionals: [ { key: 'roles', fn: (cheker) => { const { role } = cheker.conditions; if (role) { if (role !== 'admin') { cheker.forbid(); } } }, }, ], // @ts-ignore context: contextMock, }); const result = []; const action1 = createActionNameFactory('action 1', result, { role: 'client' }); const action2 = createActionNameFactory('action 2', result, { role: 'admin' }); await instance.run(action1, 1); await instance.run(action2, 2); await instance.run(action2, 3); await instance.run(action1, 4); // Выполняем экшены по одному разу, дальше из-за одинакового conditions, скипаем expect(result).toMatchInlineSnapshot(` Array [ "action: action 2 with: 2", "action: action 2 with: 3", ] `); }); });
the_stack
import { GraphQLInputType, GraphQLList, GraphQLNamedType, GraphQLNonNull, GraphQLType, isWrappingType, isListType, isNonNullType, } from 'graphql' import type { DynamicInputMethodDef, DynamicOutputMethodDef } from '../dynamicMethod' import type { DynamicOutputPropertyDef } from '../dynamicProperty' import type { NexusPlugin } from '../plugin' import type { AllInputTypes, GetGen } from '../typegenTypeHelpers' import { PrintedGenTyping, PrintedGenTypingImport, Unreachable } from '../utils' import { NexusArgDef, arg } from './args' import type { NexusEnumTypeDef } from './enumType' import type { NexusExtendInputTypeDef } from './extendInputType' import type { NexusExtendTypeDef } from './extendType' import type { NexusInputObjectTypeDef } from './inputObjectType' import type { NexusInterfaceTypeDef } from './interfaceType' import { list, NexusListDef } from './list' import { NexusNonNullDef, nonNull } from './nonNull' import { NexusNullDef, nullable } from './nullable' import type { NexusObjectTypeDef } from './objectType' import type { NexusScalarTypeDef } from './scalarType' import { isNexusMetaType, NexusMetaType, resolveNexusMetaType } from './nexusMeta' import type { NexusUnionTypeDef } from './unionType' import { NexusTypes, NexusWrappedSymbol } from './_types' /** Input(named): Nexus only */ export type AllNexusNamedInputTypeDefs<T extends string = any> = | NexusInputObjectTypeDef<T> | NexusEnumTypeDef<T> | NexusScalarTypeDef<T> /** Input(named): Nexus + GraphQLInput */ export type AllNamedInputTypeDefs<T extends string = any> = | AllNexusNamedInputTypeDefs<T> | Exclude<GraphQLInputType, GraphQLList<any> | GraphQLNonNull<any>> /** Input(all): Nexus + GraphQL */ export type AllNexusInputTypeDefs<T extends string = any> = | AllNamedInputTypeDefs<T> | NexusListDef<any> | NexusNonNullDef<any> | NexusNullDef<any> | GraphQLList<any> | GraphQLNonNull<any> /** Output(named): Nexus only */ export type AllNexusNamedOutputTypeDefs = | NexusObjectTypeDef<any> | NexusInterfaceTypeDef<any> | NexusUnionTypeDef<any> | NexusEnumTypeDef<any> | NexusScalarTypeDef<any> /** Output(all): Nexus only */ export type AllNexusOutputTypeDefs = | AllNexusNamedOutputTypeDefs | NexusListDef<any> | NexusNonNullDef<any> | NexusNullDef<any> /** Input + output(named): Nexus only */ export type AllNexusNamedTypeDefs = AllNexusNamedInputTypeDefs | AllNexusNamedOutputTypeDefs /** Input + output(all): Nexus only */ export type AllNexusTypeDefs = AllNexusOutputTypeDefs | AllNexusInputTypeDefs /** Input + output(all): Nexus only + Name */ export type AllNamedTypeDefs = AllNexusNamedTypeDefs | GraphQLNamedType /** All inputs to list(...) */ export type NexusListableTypes = | GetGen<'allNamedTypes', string> | AllNamedTypeDefs | NexusArgDef<any> | NexusListDef<NexusListableTypes> | NexusNonNullDef<NexusNonNullableTypes> | NexusNullDef<NexusNullableTypes> | GraphQLType | NexusMetaType /** All inputs to nonNull(...) */ export type NexusNonNullableTypes = | GetGen<'allNamedTypes', string> | AllNamedTypeDefs | NexusListDef<NexusListableTypes> | NexusArgDef<any> | NexusMetaType /** All inputs to nullable(...) */ export type NexusNullableTypes = | GetGen<'allNamedTypes', string> | AllNamedTypeDefs | NexusListDef<NexusListableTypes> | NexusArgDef<any> | NexusMetaType export type AllNexusNamedArgsDefs<T extends AllInputTypes = AllInputTypes> = | T | NexusArgDef<T> | AllNamedInputTypeDefs<T> | GraphQLInputType export type AllNexusArgsDefs = | AllNexusNamedArgsDefs | NexusListDef<any> | NexusNonNullDef<any> | NexusNullDef<any> | GraphQLInputType const NamedTypeDefs = new Set([ NexusTypes.Enum, NexusTypes.Object, NexusTypes.Scalar, NexusTypes.Union, NexusTypes.Interface, NexusTypes.InputObject, ]) export const isNexusTypeDef = (obj: any): obj is { [NexusWrappedSymbol]: NexusTypes } => { console.warn(`isNexusTypeDef is deprecated, use isNexusStruct`) return isNexusStruct(obj) } export function isNexusStruct(obj: any): obj is { [NexusWrappedSymbol]: NexusTypes } { return obj && Boolean(obj[NexusWrappedSymbol]) } export function isNexusNamedTypeDef(obj: any): obj is AllNexusNamedTypeDefs { return isNexusStruct(obj) && NamedTypeDefs.has(obj[NexusWrappedSymbol]) && 'name' in obj } export function isNexusListTypeDef(obj: any): obj is NexusListDef<any> { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.List } export function isNexusNonNullTypeDef(obj: any): obj is NexusNonNullDef<any> { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.NonNull } export function isNexusNullTypeDef(obj: any): obj is NexusNullDef<any> { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.Null } export function isNexusWrappingType( obj: any ): obj is NexusListDef<any> | NexusNullDef<any> | NexusNonNullDef<any> { return isNexusListTypeDef(obj) || isNexusNullTypeDef(obj) || isNexusNonNullTypeDef(obj) } export function isNexusExtendInputTypeDef(obj: any): obj is NexusExtendInputTypeDef<string> { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.ExtendInputObject } export function isNexusExtendTypeDef(obj: any): obj is NexusExtendTypeDef<string> { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.ExtendObject } export function isNexusEnumTypeDef(obj: any): obj is NexusEnumTypeDef<string> { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.Enum } export function isNexusInputObjectTypeDef(obj: any): obj is NexusInputObjectTypeDef<string> { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.InputObject } export function isNexusObjectTypeDef(obj: any): obj is NexusObjectTypeDef<string> { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.Object } export function isNexusScalarTypeDef(obj: any): obj is NexusScalarTypeDef<string> { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.Scalar } export function isNexusUnionTypeDef(obj: any): obj is NexusUnionTypeDef<string> { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.Union } export function isNexusInterfaceTypeDef(obj: any): obj is NexusInterfaceTypeDef<string> { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.Interface } export function isNexusArgDef(obj: any): obj is NexusArgDef<AllInputTypes> { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.Arg } export function isNexusNamedOuputTypeDef(obj: any): obj is AllNexusNamedOutputTypeDefs { return isNexusNamedTypeDef(obj) && !isNexusInputObjectTypeDef(obj) } export function isNexusNamedInputTypeDef(obj: any): obj is AllNexusNamedInputTypeDefs { return isNexusNamedTypeDef(obj) && !isNexusObjectTypeDef(obj) && !isNexusInterfaceTypeDef(obj) } export function isNexusDynamicOutputProperty<T extends string>(obj: any): obj is DynamicOutputPropertyDef<T> { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.DynamicOutputProperty } export function isNexusDynamicOutputMethod<T extends string>(obj: any): obj is DynamicOutputMethodDef<T> { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.DynamicOutputMethod } export function isNexusDynamicInputMethod<T extends string>(obj: any): obj is DynamicInputMethodDef<T> { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.DynamicInput } export function isNexusPrintedGenTyping(obj: any): obj is PrintedGenTyping { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.PrintedGenTyping } export function isNexusPrintedGenTypingImport(obj: any): obj is PrintedGenTypingImport { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.PrintedGenTypingImport } export function isNexusPlugin(obj: any): obj is NexusPlugin { return isNexusStruct(obj) && obj[NexusWrappedSymbol] === NexusTypes.Plugin } export type NexusWrapKind = 'NonNull' | 'Null' | 'List' export type NexusFinalWrapKind = 'NonNull' | 'List' export function unwrapGraphQLDef(typeDef: GraphQLType): { namedType: GraphQLNamedType wrapping: NexusFinalWrapKind[] } { const wrapping: NexusFinalWrapKind[] = [] let namedType = typeDef while (isWrappingType(namedType)) { if (isListType(namedType)) { wrapping.unshift('List') } else if (isNonNullType(namedType)) { wrapping.unshift('NonNull') } else { throw new Unreachable(namedType) } namedType = namedType.ofType } return { namedType, wrapping } } /** Unwraps any wrapped Nexus or GraphQL types, turning into a list of wrapping */ export function unwrapNexusDef( typeDef: AllNexusTypeDefs | AllNexusArgsDefs | GraphQLType | NexusMetaType | string ): { namedType: AllNexusNamedTypeDefs | AllNexusArgsDefs | GraphQLNamedType | string wrapping: NexusWrapKind[] } { const wrapping: NexusWrapKind[] = [] let namedType = typeDef while (isNexusWrappingType(namedType) || isWrappingType(namedType) || isNexusMetaType(namedType)) { if (isNexusMetaType(namedType)) { namedType = resolveNexusMetaType(namedType) } else if (isWrappingType(namedType)) { if (isListType(namedType)) { wrapping.unshift('List') } else if (isNonNullType(namedType)) { wrapping.unshift('NonNull') } else { throw new Unreachable(namedType) } namedType = namedType.ofType } else { if (isNexusNonNullTypeDef(namedType)) { wrapping.unshift('NonNull') } if (isNexusNullTypeDef(namedType)) { wrapping.unshift('Null') } if (isNexusListTypeDef(namedType)) { wrapping.unshift('List') } namedType = namedType.ofNexusType } } return { namedType, wrapping } } /** Takes the named type, and applies any of the NexusFinalWrapKind to create a properly wrapped GraphQL type. */ export function rewrapAsGraphQLType(baseType: GraphQLNamedType, wrapping: NexusFinalWrapKind[]): GraphQLType { let finalType: GraphQLType = baseType wrapping.forEach((wrap) => { if (wrap === 'List') { finalType = new GraphQLList(finalType) } else if (wrap === 'NonNull') { if (!isNonNullType(finalType)) { finalType = new GraphQLNonNull(finalType) } } else { throw new Unreachable(wrap) } }) return finalType } /** * Apply the wrapping consistently to the arg `type` * * NonNull(list(stringArg())) -> arg({ type: nonNull(list('String')) }) */ export function normalizeArgWrapping(argVal: AllNexusArgsDefs): NexusArgDef<AllInputTypes> { if (isNexusArgDef(argVal)) { return argVal } if (isNexusWrappingType(argVal)) { let { namedType, wrapping } = unwrapNexusDef(argVal) if (isNexusArgDef(namedType)) { const config = namedType.value return arg({ ...config, type: applyNexusWrapping(config.type, wrapping) }) } return arg({ type: applyNexusWrapping(namedType, wrapping) }) } return arg({ type: argVal }) } /** * Applies the ['List', 'NonNull', 'Nullable'] * * @param toWrap * @param wrapping */ export function applyNexusWrapping(toWrap: any, wrapping: NexusWrapKind[]) { let finalType = toWrap wrapping.forEach((wrap) => { if (wrap === 'List') { finalType = list(finalType) } else if (wrap === 'NonNull') { finalType = nonNull(finalType) } else if (wrap === 'Null') { finalType = nullable(finalType) } else { throw new Unreachable(wrap) } }) return finalType } /** * Takes the "nonNullDefault" value, the chained wrapping, and the field wrapping, to determine the proper * list of wrapping to apply to the field */ export function finalizeWrapping( nonNullDefault: boolean, typeWrapping: NexusWrapKind[] | ReadonlyArray<NexusWrapKind>, chainWrapping?: NexusWrapKind[] ): NexusFinalWrapKind[] { let finalChain: NexusFinalWrapKind[] = [] const allWrapping = typeWrapping.concat(chainWrapping ?? []) // Ensure the first item is wrapped, if we're not guarding if (nonNullDefault && (!allWrapping[0] || allWrapping[0] === 'List')) { allWrapping.unshift('NonNull') } for (let i = 0; i < allWrapping.length; i++) { const current = allWrapping[i] const next = allWrapping[i + 1] if (current === 'Null') { continue } else if (current === 'NonNull') { finalChain.push('NonNull') } else if (current === 'List') { finalChain.push('List') if (nonNullDefault && (next === 'List' || !next)) { finalChain.push('NonNull') } } } return finalChain }
the_stack
import { createMuiTheme } from '@material-ui/core/styles'; import { getForumType, ThemeOptions } from './themeNames'; import deepmerge from 'deepmerge'; import isPlainObject from 'is-plain-object'; import type { PartialDeep } from 'type-fest' import { defaultShadePalette, defaultComponentPalette } from './defaultPalette'; const monoStack = [ '"Liberation Mono"', 'Menlo', 'Courier', 'monospace' ].join(',') // Will be used for the distance between the post title divider and the text on // mobile // Matches distance from the bottom of the secondaryInfo to the divider // = 16 (see header and divider) + the ~4 pixel distance from the bottom // of the secondaryInfo text to the bottom of the associated div const titleDividerSpacing = 20 export const zIndexes = { frontpageBooks: 0, frontpageSplashImage: 0, sequenceBanner: 0, singleColumnSection: 1, commentsMenu: 2, sequencesPageContent: 2, sequencesImageScrim: 2, editSequenceTitleInput: 3, postsVote: 2, postItemAuthor: 2, singleLineCommentMeta: 3, postItemTitle: 3, sidebarHoverOver: 3, sidebarActionMenu: 3, commentPermalinkIcon: 3, reviewVotingMenu: 4, singleLineCommentHover: 4, questionPageWhitescreen: 4, footerNav: 4, textbox: 5, styledMapPopup: 6, nextUnread: 999, sunshineSidebar: 1000, postItemMenu: 1001, layout: 1100, tabNavigation: 1101, searchResults: 1102, header: 1300, karmaChangeNotifier: 1400, notificationsMenu: 1500, gatherTownIframe: 9999, // 1000001 higher than everything except intercom afNonMemberPopup: 9999, lwPopper: 10000, lwPopperTooltip: 10001, loginDialog: 10002, searchBar: 100000, commentBoxPopup: 10000000001, // has to be higher than Intercom, // ckEditorToolbar: 10000000002, // has to be higher than commentBoxPopup, (note: the css had to be applied in an scss file, "_editor.scss", but the position is listed here for ease of reference) petrovDayButton: 6, petrovDayLoss: 1000000 } export const baseTheme: BaseThemeSpecification = { shadePalette: defaultShadePalette(), componentPalette: (shadePalette: ThemeShadePalette) => defaultComponentPalette(shadePalette), make: (palette: ThemePalette): PartialDeep<ThemeType> => { const spacingUnit = 8 return { breakpoints: { values: { xs: 0, sm: 600, md: 960, lg: 1280, xl: 1400, }, }, spacing: { unit: spacingUnit, titleDividerSpacing, }, typography: { postStyle: { fontFamily: palette.fonts.sansSerifStack, }, contentNotice: { fontStyle: "italic", color: palette.grey[600], fontSize:".9em", // This should be at least as big as the margin-bottom of <p> tags (18.1 // on LW), and the distance on mobile between the divider and the top of // the notice is as good as any marginBottom: titleDividerSpacing, wordBreak: "break-word" }, body1: { fontSize: '1.4rem', lineHeight: '2rem' }, body2: { fontWeight: 400, fontSize: '1.1rem', lineHeight: '1.5rem', }, smallText: { fontFamily: palette.fonts.sansSerifStack, fontWeight: 400, fontSize: "1rem", lineHeight: '1.4rem' }, tinyText: { fontWeight: 400, fontSize: ".75rem", lineHeight: '1.4rem' }, // used by h3 display0: { color: palette.grey[700], fontSize: '1.6rem', marginTop: '1em', // added by MUI to display1, which we're imitating fontWeight: 400, lineHeight: "1.20588em", }, display1: { color: palette.grey[800], fontSize: '2rem', marginTop: '1em' }, display2: { color: palette.grey[800], fontSize: '2.8rem', marginTop: '1em' }, display3: { color: palette.grey[800], marginTop: '1.2em', fontSize: '3rem' }, display4: { color: palette.grey[800], }, title: { fontSize: 18, fontWeight: 400, marginBottom: 3, }, // Used for ui text that's (on LW) serifed rather than the primary // sans-serif ui font. On the EA Forum this is overridden with sans-serif uiSecondary: { fontFamily: palette.fonts.sansSerifStack, }, caption: { fontSize: ".9rem" }, blockquote: { fontWeight: 400, paddingTop: spacingUnit*2, paddingRight: spacingUnit*2, paddingBottom: spacingUnit*2, paddingLeft: spacingUnit*2, borderLeft: `solid 3px ${palette.grey[300]}`, margin: 0, }, commentBlockquote: { fontWeight: 400, paddingTop: spacingUnit, paddingRight: spacingUnit*3, paddingBottom: spacingUnit, paddingLeft: spacingUnit*2, borderLeft: `solid 3px ${palette.grey[300]}`, margin: 0, marginLeft: spacingUnit*1.5, }, codeblock: { backgroundColor: palette.grey[100], borderRadius: "5px", border: `solid 1px ${palette.grey[300]}`, padding: '1rem', whiteSpace: 'pre-wrap', margin: "1em 0", }, code: { fontFamily: monoStack, fontSize: ".7em", fontWeight: 400, backgroundColor: palette.grey[100], borderRadius: 2, paddingTop: 3, paddingBottom: 3, lineHeight: 1.42 }, li: { marginBottom: '.5rem', }, commentHeader: { fontSize: '1.5rem', marginTop: '.5em', fontWeight:500, }, subheading: { fontSize:15, color: palette.grey[600] }, subtitle: { fontSize: 16, fontWeight: 600, marginBottom: ".5rem" }, }, zIndexes: { ...zIndexes }, postImageStyles: {}, voting: { strongVoteDelay: 1000, }, shadows: [ // All from material-UI "none", `0px 1px 3px 0px ${palette.boxShadowColor(0.2)},0px 1px 1px 0px ${palette.boxShadowColor(0.14)},0px 2px 1px -1px ${palette.boxShadowColor(0.12)}`, `0px 1px 5px 0px ${palette.boxShadowColor(0.2)},0px 2px 2px 0px ${palette.boxShadowColor(0.14)},0px 3px 1px -2px ${palette.boxShadowColor(0.12)}`, `0px 1px 8px 0px ${palette.boxShadowColor(0.2)},0px 3px 4px 0px ${palette.boxShadowColor(0.14)},0px 3px 3px -2px ${palette.boxShadowColor(0.12)}`, `0px 2px 4px -1px ${palette.boxShadowColor(0.2)},0px 4px 5px 0px ${palette.boxShadowColor(0.14)},0px 1px 10px 0px ${palette.boxShadowColor(0.12)}`, `0px 3px 5px -1px ${palette.boxShadowColor(0.2)},0px 5px 8px 0px ${palette.boxShadowColor(0.14)},0px 1px 14px 0px ${palette.boxShadowColor(0.12)}`, `0px 3px 5px -1px ${palette.boxShadowColor(0.2)},0px 6px 10px 0px ${palette.boxShadowColor(0.14)},0px 1px 18px 0px ${palette.boxShadowColor(0.12)}`, `0px 4px 5px -2px ${palette.boxShadowColor(0.2)},0px 7px 10px 1px ${palette.boxShadowColor(0.14)},0px 2px 16px 1px ${palette.boxShadowColor(0.12)}`, `0px 5px 5px -3px ${palette.boxShadowColor(0.2)},0px 8px 10px 1px ${palette.boxShadowColor(0.14)},0px 3px 14px 2px ${palette.boxShadowColor(0.12)}`, `0px 5px 6px -3px ${palette.boxShadowColor(0.2)},0px 9px 12px 1px ${palette.boxShadowColor(0.14)},0px 3px 16px 2px ${palette.boxShadowColor(0.12)}`, `0px 6px 6px -3px ${palette.boxShadowColor(0.2)},0px 10px 14px 1px ${palette.boxShadowColor(0.14)},0px 4px 18px 3px ${palette.boxShadowColor(0.12)}`, `0px 6px 7px -4px ${palette.boxShadowColor(0.2)},0px 11px 15px 1px ${palette.boxShadowColor(0.14)},0px 4px 20px 3px ${palette.boxShadowColor(0.12)}`, `0px 7px 8px -4px ${palette.boxShadowColor(0.2)},0px 12px 17px 2px ${palette.boxShadowColor(0.14)},0px 5px 22px 4px ${palette.boxShadowColor(0.12)}`, `0px 7px 8px -4px ${palette.boxShadowColor(0.2)},0px 13px 19px 2px ${palette.boxShadowColor(0.14)},0px 5px 24px 4px ${palette.boxShadowColor(0.12)}`, `0px 7px 9px -4px ${palette.boxShadowColor(0.2)},0px 14px 21px 2px ${palette.boxShadowColor(0.14)},0px 5px 26px 4px ${palette.boxShadowColor(0.12)}`, `0px 8px 9px -5px ${palette.boxShadowColor(0.2)},0px 15px 22px 2px ${palette.boxShadowColor(0.14)},0px 6px 28px 5px ${palette.boxShadowColor(0.12)}`, `0px 8px 10px -5px ${palette.boxShadowColor(0.2)},0px 16px 24px 2px ${palette.boxShadowColor(0.14)},0px 6px 30px 5px ${palette.boxShadowColor(0.12)}`, `0px 8px 11px -5px ${palette.boxShadowColor(0.2)},0px 17px 26px 2px ${palette.boxShadowColor(0.14)},0px 6px 32px 5px ${palette.boxShadowColor(0.12)}`, `0px 9px 11px -5px ${palette.boxShadowColor(0.2)},0px 18px 28px 2px ${palette.boxShadowColor(0.14)},0px 7px 34px 6px ${palette.boxShadowColor(0.12)}`, `0px 9px 12px -6px ${palette.boxShadowColor(0.2)},0px 19px 29px 2px ${palette.boxShadowColor(0.14)},0px 7px 36px 6px ${palette.boxShadowColor(0.12)}`, `0px 10px 13px -6px ${palette.boxShadowColor(0.2)},0px 20px 31px 3px ${palette.boxShadowColor(0.14)},0px 8px 38px 7px ${palette.boxShadowColor(0.12)}`, `0px 10px 13px -6px ${palette.boxShadowColor(0.2)},0px 21px 33px 3px ${palette.boxShadowColor(0.14)},0px 8px 40px 7px ${palette.boxShadowColor(0.12)}`, `0px 10px 14px -6px ${palette.boxShadowColor(0.2)},0px 22px 35px 3px ${palette.boxShadowColor(0.14)},0px 8px 42px 7px ${palette.boxShadowColor(0.12)}`, `0px 11px 14px -7px ${palette.boxShadowColor(0.2)},0px 23px 36px 3px ${palette.boxShadowColor(0.14)},0px 9px 44px 8px ${palette.boxShadowColor(0.12)}`, `0px 11px 15px -7px ${palette.boxShadowColor(0.2)},0px 24px 38px 3px ${palette.boxShadowColor(0.14)},0px 9px 46px 8px ${palette.boxShadowColor(0.12)}`, ], overrides: { MuiTooltip: { tooltip: { backgroundColor: palette.panelBackground.tooltipBackground, color: palette.text.tooltipText, }, }, MuiChip: { root: { color: palette.text.normal, //Necessary because this uses getContrastText() which produces a non-theme color }, }, MuiButton: { contained: { // TODO: Override color, for which material-UI uses getContrastText() which produces a non-theme color }, }, MuiSelect: { selectMenu: { paddingLeft: spacingUnit } }, MuiFormControlLabel: { label: { fontFamily: palette.fonts.sansSerifStack, fontSize: "1.1rem", fontWeight: 400, lineHeight: "1.5rem", } }, MuiTableCell: { body: { fontSize: '1.1rem', lineHeight: '1.5rem', paddingLeft: 16, paddingRight: 16, paddingTop: 12, paddingBottom: 12, marginTop: 0, marginBottom: 0, wordBreak: "normal", } } }, rawCSS: [], } } };
the_stack
import { union, defaultsDeep, isArray, toArray, mergeWith } from 'lodash' import { FabrixApp } from './' import { Templates } from './' import { ApiNotDefinedError, ConfigNotDefinedError, ConfigValueError, GraphCompletenessError, IllegalAccessError, NamespaceConflictError, PackageNotDefinedError, TimeoutError, SanityError, SpoolError, ValidationError } from './errors' import { FabrixService } from './common/Service' import { FabrixController } from './common/Controller' import { FabrixPolicy } from './common/Policy' import { FabrixModel } from './common/Model' import { FabrixResolver } from './common/Resolver' import { Spool, ILifecycle, FabrixGeneric } from './common' declare global { namespace NodeJS { interface Global { [key: string]: any } } } export const Errors = { ApiNotDefinedError, ConfigNotDefinedError, ConfigValueError, GraphCompletenessError, IllegalAccessError, NamespaceConflictError, PackageNotDefinedError, TimeoutError, SanityError, SpoolError, ValidationError } export const Core = { // An Exception convenience: added v1.5 BreakException: {}, // Methods reserved so that they are not autobound reservedMethods: [ 'app', 'api', 'log', '__', // this reserved method comes from i18n 'constructor', 'undefined', 'methods', 'config', 'schema', // Should additional resource types be added to reserved or should this be removed completely? 'services', 'models' ], // Deprecated v1.6 globals: Object.freeze(Object.assign({ Service: FabrixService, Controller: FabrixController, Policy: FabrixPolicy, Model: FabrixModel, Resolver: FabrixResolver }, Errors)), // Deprecated v1.6 globalPropertyOptions: Object.freeze({ writable: false, enumerable: false, configurable: false }), /** * Deprecated v1.6 * Prepare the global namespace with required Fabrix types. Ignore identical * values already present; fail on non-matching values. * * @throw NamespaceConflictError */ assignGlobals (): void { Object.entries(Core.globals).forEach(([name, type]) => { if (global[name] === type) { return } if (global[name] && global[name] !== type) { throw new NamespaceConflictError(name, Object.keys(Core.globals)) } const descriptor = Object.assign({ value: type }, Core.globalPropertyOptions) Object.defineProperty(global, name, descriptor) }) }, /** * Bind the context of API resource methods. */ bindMethods (app: FabrixApp, resource: string): any { return Object.entries(app.api[resource] || { }) .map(([ resourceName, Resource ]: [string, any]) => { const objContext = <typeof Resource> Resource const obj = new objContext(app) obj.methods = Core.getClassMethods(obj) || [ ] Object.entries(obj.methods).forEach(([ _, method]: [any, string]) => { obj[method] = obj[method].bind(obj) }) return [ resourceName, obj ] }) .reduce((result, [ resourceName, _resource ]: [string, any]) => Object.assign(result, { [resourceName]: _resource }), { }) }, /** * Instantiate resource classes and bind resource methods */ bindResourceMethods(app: FabrixApp, resources: string[]): void { resources.forEach(resource => { try { app[resource] = Core.bindMethods(app, resource) } catch (err) { app.log.error(err) } }) }, /** * Traverse prototype chain and aggregate all class method names */ getClassMethods (obj: any): string[] { const props: string[] = [ ] const objectRoot = new Object() while (!obj.isPrototypeOf(objectRoot)) { Object.getOwnPropertyNames(obj).forEach(prop => { if ( props.indexOf(prop) === -1 && !Core.reservedMethods.some(p => p === prop) && typeof obj[prop] === 'function' ) { props.push(prop) } }) obj = Object.getPrototypeOf(obj) } return props }, /** * Get the property names of an Object */ getPropertyNames(obj) { return Object.getOwnPropertyNames(obj.prototype) }, /** * If the object has a prototype property */ hasPrototypeProperty(obj, proto) { return obj.prototype.hasOwnProperty(proto) }, /** * Merge the Prototype of uninitiated classes */ mergePrototype(obj, next, proto) { obj.prototype[proto] = next.prototype[proto] }, /** * Merge the app api resources with the ones provided by the spools * Given that they are allowed by app.config.main.resources */ mergeApi (app: FabrixApp) { const spools = Object.keys(app.spools).reverse() app.resources.forEach(resource => { spools.forEach(s => { // Add the defaults from the spools Apis defaultsDeep(app.api, app.spools[s].api) // Deep merge the Api Core.mergeApiResource(app, app.spools[s], resource) }) }) }, /** * Adds Api resources that were not merged by default */ mergeApiResource (app: FabrixApp, spool: Spool, resource: string) { if (app.api.hasOwnProperty(resource) && spool.api.hasOwnProperty(resource)) { Object.keys(spool.api[resource]).forEach(method => { Core.mergeApiResourceMethod(app, spool, resource, method) }) } }, /** * Adds Api resource methods that were not merged by default */ mergeApiResourceMethod (app: FabrixApp, spool: Spool, resource: string, method: string) { if (spool.api[resource].hasOwnProperty(method) && app.api[resource].hasOwnProperty(method)) { const spoolProto = Core.getPropertyNames(spool.api[resource][method]) spoolProto.forEach(proto => { if (!Core.hasPrototypeProperty(app.api[resource][method], proto)) { Core.mergePrototype(app.api[resource][method], spool.api[resource][method], proto) app.log.silly(`${spool.name}.api.${resource}.${method}.${proto} extending app.api.${resource}.${method}.${proto}`) } }) } }, /** * Merge the spool api resources with the ones provided by other spools * Given that they are allowed by app.config.main.resources */ mergeSpoolApi (app: FabrixApp, spool: Spool) { app.resources = union(app.resources, Object.keys(app.api), Object.keys(spool.api)) const spools = Object.keys(app.spools) .filter(s => s !== spool.name) app.resources.forEach(resource => { spools.forEach(s => { Core.mergeSpoolApiResource(app, app.spools[s], spool, resource) }) }) }, /** * Merge two Spools Api Resources's in order of their load */ mergeSpoolApiResource (app: FabrixApp, spool: Spool, next: Spool, resource: string) { if (spool && spool.api.hasOwnProperty(resource) && next.api.hasOwnProperty(resource)) { Object.keys(next.api[resource]).forEach(method => { Core.mergeSpoolApiResourceMethod(app, spool, next, resource, method) }) } }, /** * Merge two Spools Api Resources Method's in order of their load */ mergeSpoolApiResourceMethod (app: FabrixApp, spool: Spool, next: Spool, resource: string, method: string) { if (spool && spool.api[resource].hasOwnProperty(method) && next.api[resource].hasOwnProperty(method)) { const spoolProto = Core.getPropertyNames(spool.api[resource][method]) spoolProto.forEach(proto => { if (!Core.hasPrototypeProperty(next.api[resource][method], proto)) { Core.mergePrototype(next.api[resource][method], spool.api[resource][method], proto) app.log.silly(`${spool.name}.api.${resource}.${method}.${proto} extending ${next.name}.api.${resource}.${method}.${proto}`) } }) } }, /** * Merge extensions provided by spools into the app */ mergeExtensions ( app: FabrixApp, spool: Spool ): void { const extensions = spool.extensions || {} for (const ext of Object.keys(extensions)) { if (!extensions.hasOwnProperty(ext)) { continue } if (app.hasOwnProperty(ext)) { app.log.warn(`Spool Extension ${spool.name}.${ext} overriding app.${ext}`) } Object.defineProperty(app, ext, spool.extensions[ext]) } }, defaultsDeep: (...args) => { const output = {} toArray(args).reverse().forEach(function (item) { mergeWith(output, item, function (objectValue, sourceValue) { return isArray(sourceValue) ? sourceValue : undefined }) }) return output }, collector: (stack, key, val) => { let idx: any = stack[stack.length - 1].indexOf(key) try { const props: any = Object.keys(val) if (!props.length) { throw props } props.unshift({idx: idx}) stack.push(props) } catch (e) { while (!(stack[stack.length - 1].length - 2)) { idx = stack[stack.length - 1][0].idx stack.pop() } if (idx + 1) { stack[stack.length - 1].splice(idx, 1) } } return val }, isNotCircular: (obj): boolean => { let stack = [[]] try { return !!JSON.stringify(obj, Core.collector.bind(null, stack)) } catch (e) { if (e.message.indexOf('circular') !== -1) { let idx = 0 let path = '' let parentProp = '' while (idx + 1) { idx = stack.pop()[0].idx parentProp = stack[stack.length - 1][idx] if (!parentProp) { break } path = '.' + parentProp + path } } return false } }, /** * Create configured paths if they don't exist and target is Node.js */ async createDefaultPaths (app: FabrixApp): Promise<any> { const paths: {[key: string]: string} = app.config.get('main.paths') || { } const target: string = app.config.get('main.target') || 'node' if (target !== 'browser') { const mkdirp = await import('mkdirp') for (const [, dir] of Object.entries(paths)) { await mkdirp(dir, null, function (err: Error) { if (err) { app.log.error(err) } }) } } }, /** * Bind listeners to fabrix application events */ bindApplicationListeners (app: FabrixApp): void { app.once('spool:all:configured', () => { if (app.config.get('main.freezeConfig') === false) { app.log.warn('freezeConfig is disabled. Configuration will not be frozen.') app.log.warn('Please only use this flag for testing/debugging purposes.') } else { app.config.freeze() } }) app.once('spool:all:initialized', () => { app.log.silly(Templates.silly.initialized) app.log.info(Templates.info.initialized) }) app.once('spool:all:sane', () => { app.log.silly(Templates.silly.sane) app.log.info(Templates.info.sane) }) app.once('fabrix:ready', () => { app.log.info(Templates.info.ready(app)) app.log.debug(Templates.debug.ready(app)) app.log.silly(Templates.silly.ready(app)) app.log.info(Templates.hr) app.log.info(Templates.docs) }) app.once('fabrix:stop', () => { app.log.info(Templates.info.stop) app.config.unfreeze() }) }, /** * Bind lifecycle boundary event listeners. That is, when all spools have * completed a particular phase, e.g. "configure" or "initialize", emit an * :all:<phase> event. */ bindSpoolPhaseListeners ( app: FabrixApp, spools: Spool[] = [] ): void { // TODO, eliminate waiting on lifecycle events that will not exist // https://github.com/fabrix-app/fabrix/issues/14 const validatedEvents = spools.map(spool => `spool:${spool.name}:validated`) const configuredEvents = spools.map(spool => `spool:${spool.name}:configured`) const initializedEvents = spools.map(spool => `spool:${spool.name}:initialized`) const sanityEvents = spools.map(spool => `spool:${spool.name}:sane`) app.after(configuredEvents) .then(async () => { await this.createDefaultPaths(app) app.emit('spool:all:configured') }) .catch(err => { app.log.error(err) throw err }) app.after(validatedEvents) .then(() => app.emit('spool:all:validated')) .catch(err => { app.log.error(err) throw err }) app.after(initializedEvents) .then(() => { app.emit('spool:all:initialized') }) .catch(err => { app.log.error(err) throw err }) app.after(sanityEvents) .then(() => { app.emit('spool:all:sane') app.emit('fabrix:ready') }) .catch(err => { app.log.error(err) throw err }) }, /** * Bind individual lifecycle method listeners. That is, when each spool * completes each lifecycle, fire individual events for those spools. */ bindSpoolMethodListeners ( app: FabrixApp, spool: Spool ) { const lifecycle = spool.lifecycle app.after((lifecycle.sanity.listen).concat('spool:all:initialized')) .then(() => app.log.debug('spool: sanity check', spool.name)) .then(() => spool.stage = 'sanity') .then(() => spool.sanity()) .then(() => app.emit(`spool:${spool.name}:sane`)) .then(() => spool.stage = 'sane') .catch(err => this.handlePromiseRejection(app, err)) app.after((lifecycle.initialize.listen).concat('spool:all:configured')) .then(() => app.log.debug('spool: initializing', spool.name)) .then(() => spool.stage = 'initializing') .then(() => spool.initialize()) .then(() => app.emit(`spool:${spool.name}:initialized`)) .then(() => spool.stage = 'initialized') .catch(err => this.handlePromiseRejection(app, err)) app.after((lifecycle.configure.listen).concat('spool:all:validated')) .then(() => app.log.debug('spool: configuring', spool.name)) .then(() => spool.stage = 'configuring') .then(() => spool.configure()) .then(() => app.emit(`spool:${spool.name}:configured`)) .then(() => spool.stage = 'configured') .catch(err => this.handlePromiseRejection(app, err)) app.after(['fabrix:start']) .then(() => app.log.debug('spool: validating', spool.name)) .then(() => spool.stage = 'validating') .then(() => spool.validate()) .then(() => app.emit(`spool:${spool.name}:validated`)) .then(() => spool.stage = 'validated') .catch(err => this.handlePromiseRejection(app, err)) }, /** * Handle a promise rejection */ handlePromiseRejection (app: FabrixApp, err: Error): void { app.log.error(err) throw err return } }
the_stack
import { EventEmitter } from '@angular/core'; import { importAllAngularServices } from 'tests/unit-test-utils.ajs'; /** * @fileoverview Unit tests for QuestionPlayerComponent. */ describe('QuestionPlayerComponent', () => { let ctrl = null; let $rootScope = null; let $scope = null; let $location = null; let $q = null; let $uibModal = null; let PlayerPositionService = null; let PreventPageUnloadEventService = null; let ExplorationPlayerStateService = null; let QuestionPlayerStateService = null; let UserService = null; let mockWindow = null; let userInfo = { _isModerator: true, _isAdmin: false, _isTopicManager: false, _isSuperAdmin: false, _canCreateCollections: true, _preferredSiteLanguageCode: 'en', _username: 'username1', _email: 'tester@example.org', _isLoggedIn: true, isModerator: () => true, isAdmin: () => false, isSuperAdmin: () => false, isTopicManager: () => false, canCreateCollections: () => true, getPreferredSiteLanguageCode: () =>'en', getUsername: () => 'username1', getEmail: () => 'tester@example.org', isLoggedIn: () => true }; beforeEach(angular.mock.module('oppia')); importAllAngularServices(); beforeEach(angular.mock.module('oppia', function($provide) { mockWindow = { location: { href: '' } }; $provide.value('$window', mockWindow); })); beforeEach(angular.mock.inject( function($injector, $componentController) { $rootScope = $injector.get('$rootScope'); $scope = $rootScope.$new(); $location = $injector.get('$location'); $q = $injector.get('$q'); $uibModal = $injector.get('$uibModal'); PlayerPositionService = $injector.get('PlayerPositionService'); PreventPageUnloadEventService = $injector.get( 'PreventPageUnloadEventService'); ExplorationPlayerStateService = $injector.get( 'ExplorationPlayerStateService'); QuestionPlayerStateService = $injector.get('QuestionPlayerStateService'); UserService = $injector.get('UserService'); ctrl = $componentController('questionPlayer', { $scope: $scope }, { getQuestionPlayerConfig: () => {} }); spyOnProperty( QuestionPlayerStateService, 'resultsPageIsLoadedEventEmitter' ).and.returnValue(new EventEmitter<boolean>()); spyOn(QuestionPlayerStateService.resultsPageIsLoadedEventEmitter, 'emit'); })); afterEach(() => { ctrl.$onDestroy(); }); it('should set component properties on initialization', () => { expect(ctrl.currentQuestion).toBe(undefined); expect(ctrl.totalQuestions).toBe(undefined); expect(ctrl.currentProgress).toBe(undefined); expect(ctrl.totalScore).toBe(undefined); expect(ctrl.scorePerSkillMapping).toBe(undefined); expect(ctrl.testIsPassed).toBe(undefined); ctrl.$onInit(); expect(ctrl.currentQuestion).toBe(0); expect(ctrl.totalQuestions).toBe(0); expect(ctrl.currentProgress).toBe(0); expect(ctrl.totalScore).toBe(0.0); expect(ctrl.scorePerSkillMapping).toEqual({}); expect(ctrl.testIsPassed).toBe(true); expect(QuestionPlayerStateService.resultsPageIsLoadedEventEmitter.emit) .toHaveBeenCalledWith(false); }); it('should add subscriptions on initialization', () => { spyOn(PlayerPositionService.onCurrentQuestionChange, 'subscribe'); spyOn(ExplorationPlayerStateService.onTotalQuestionsReceived, 'subscribe'); spyOn(QuestionPlayerStateService.onQuestionSessionCompleted, 'subscribe'); ctrl.$onInit(); expect(PlayerPositionService.onCurrentQuestionChange.subscribe) .toHaveBeenCalled(); expect(ExplorationPlayerStateService.onTotalQuestionsReceived.subscribe) .toHaveBeenCalled(); expect(QuestionPlayerStateService.onQuestionSessionCompleted.subscribe) .toHaveBeenCalled(); }); it('should update current question when current question is changed', () => { spyOnProperty(PlayerPositionService, 'onCurrentQuestionChange') .and.returnValue(new EventEmitter()); ctrl.$onInit(); ctrl.totalQuestions = 5; expect(ctrl.currentQuestion).toBe(0); expect(ctrl.currentProgress).toBe(0); PlayerPositionService.onCurrentQuestionChange.emit(3); $scope.$apply(); expect(ctrl.currentQuestion).toBe(4); expect(ctrl.currentProgress).toBe(80); }); it('should update total number of questions when count is received', () => { spyOnProperty(ExplorationPlayerStateService, 'onTotalQuestionsReceived') .and.returnValue(new EventEmitter()); ctrl.$onInit(); expect(ctrl.totalQuestions).toBe(0); ExplorationPlayerStateService.onTotalQuestionsReceived.emit(3); $scope.$apply(); expect(ctrl.totalQuestions).toBe(3); }); it('should change location hash when question session is completed', () => { spyOnProperty(QuestionPlayerStateService, 'onQuestionSessionCompleted') .and.returnValue(new EventEmitter()); spyOn($location, 'hash').and.stub(); ctrl.$onInit(); QuestionPlayerStateService.onQuestionSessionCompleted.emit('new uri'); $scope.$apply(); expect($location.hash).toHaveBeenCalledWith( 'question-player-result=%22new%20uri%22'); }); it('should get user info on initialization', () => { spyOn(UserService, 'getUserInfoAsync').and.returnValue( $q.resolve(userInfo) ); expect(ctrl.canCreateCollections).toBe(undefined); expect(ctrl.isLoggedIn).toBe(undefined); ctrl.$onInit(); $scope.$apply(); expect(ctrl.canCreateCollections).toBe(true); expect(ctrl.userIsLoggedIn).toBe(true); }); it('should calculate scores, mastery degree and check if user' + ' has passed test', () => { spyOnProperty(PlayerPositionService, 'onCurrentQuestionChange') .and.returnValue(new EventEmitter()); spyOn($location, 'hash').and.returnValue( 'question-player-result=%22new%20uri%22'); spyOn(ctrl, 'calculateScores').and.stub(); spyOn(ctrl, 'calculateMasteryDegrees').and.stub(); spyOn(ctrl, 'hasUserPassedTest').and.returnValue(true); expect(ctrl.testIsPassed).toBe(undefined); ctrl.$onInit(); ctrl.userIsLoggedIn = true; PlayerPositionService.onCurrentQuestionChange.emit(3); $scope.$apply(); expect(ctrl.calculateScores).toHaveBeenCalled(); expect(ctrl.calculateMasteryDegrees).toHaveBeenCalled(); expect(ctrl.testIsPassed).toBe(true); }); it('should get the inner class name for action button', () => { expect(ctrl.getActionButtonInnerClass('REVIEW_LOWEST_SCORED_SKILL')) .toBe('review-lowest-scored-skill-inner'); expect(ctrl.getActionButtonInnerClass('RETRY_SESSION')) .toBe('new-session-inner'); expect(ctrl.getActionButtonInnerClass('DASHBOARD')) .toBe('my-dashboard-inner'); expect(ctrl.getActionButtonInnerClass('INVALID_TYPE')) .toBe(''); }); it('should get html for action button icon', () => { expect(ctrl.getActionButtonIconHtml( 'REVIEW_LOWEST_SCORED_SKILL').toString()) .toBe('<i class="material-icons md-18 action-button-icon">&#59497;</i>'); expect(ctrl.getActionButtonIconHtml('RETRY_SESSION').toString()) .toBe('<i class="material-icons md-18 action-button-icon">&#58837;</i>'); expect(ctrl.getActionButtonIconHtml('DASHBOARD').toString()) .toBe('<i class="material-icons md-18 action-button-icon">&#59530;</i>'); }); it('should open review lowest scored skill modal when use clicks ' + 'on action button with type REVIEW_LOWEST_SCORED_SKILL', () => { let skills, skillIds; spyOn($uibModal, 'open').and.callFake((options) => { skills = options.resolve.skills(); skillIds = options.resolve.skillIds(); return { result: $q.resolve() }; }); ctrl.scorePerSkillMapping = { skill1: { score: 5, total: 8, description: '' }, skill2: { score: 8, total: 8, description: '' } }; ctrl.performAction({ type: 'REVIEW_LOWEST_SCORED_SKILL' }); $scope.$apply(); expect(skills).toEqual(['']); expect(skillIds).toEqual(['skill1']); }); it('should close review lowest scored skill modal', () => { spyOn($uibModal, 'open').and.returnValue({ result: $q.reject() }); ctrl.scorePerSkillMapping = { skill1: { score: 5, total: 8 }, skill2: { score: 8, total: 8 } }; ctrl.performAction({ type: 'REVIEW_LOWEST_SCORED_SKILL' }); $scope.$apply(); expect($uibModal.open).toHaveBeenCalled(); }); it('should redirect user if action button has a URL', () => { expect(mockWindow.location.href).toBe(''); ctrl.performAction({ url: '/url' }); expect(mockWindow.location.href).toBe('/url'); }); it('should check if action buttons footer is to be shown or not', () => { ctrl.questionPlayerConfig = { resultActionButtons: ['first'] }; expect(ctrl.showActionButtonsFooter()).toBe(true); ctrl.questionPlayerConfig = { resultActionButtons: [] }; expect(ctrl.showActionButtonsFooter()).toBe(false); }); it('should check if the user has passed the test or not', () => { ctrl.questionPlayerConfig = { questionPlayerMode: { modeType: 'PASS_FAIL', passCutoff: 1.5 } }; ctrl.scorePerSkillMapping = { skill1: { score: 5, total: 8 }, skill2: { score: 8, total: 8 } }; expect(ctrl.hasUserPassedTest()).toBe(false); ctrl.questionPlayerConfig = { questionPlayerMode: { modeType: 'PASS_FAIL', passCutoff: 0.5 } }; expect(ctrl.hasUserPassedTest()).toBe(true); }); it('should get score percentage to set score bar width', () => { expect(ctrl.getScorePercentage({ score: 5, total: 10 })).toBe(50); expect(ctrl.getScorePercentage({ score: 3, total: 10 })).toBe(30); }); it('should calculate score based on question state data', () => { let questionStateData = { ques1: { answers: ['1'], usedHints: [], viewedSolution: false, }, ques2: { answers: ['3', '4'], usedHints: ['hint1'], viewedSolution: true, linkedSkillIds: ['skillId1', 'skillId2'] } }; ctrl.questionPlayerConfig = { skillList: ['skillId1'], skillDescriptions: ['description1'] }; ctrl.totalScore = 0.0; ctrl.calculateScores(questionStateData); expect(ctrl.totalScore).toBe(50); expect(QuestionPlayerStateService.resultsPageIsLoadedEventEmitter.emit) .toHaveBeenCalledWith(true); }); it('should calculate mastery degrees', () => { ctrl.questionPlayerConfig = { skillList: ['skillId1'], skillDescriptions: ['description1'] }; let questionStateData = { ques1: { answers: [], usedHints: ['hint1'], viewedSolution: false, }, ques2: { answers: [{ isCorrect: false, taggedSkillMisconceptionId: 'skillId1-misconception1' }, { isCorrect: true, }], usedHints: ['hint1'], viewedSolution: true, linkedSkillIds: ['skillId1', 'skillId2'] }, ques3: { answers: [{ isCorrect: false, taggedSkillMisconceptionId: 'skillId1-misconception1' }], usedHints: ['hint1'], viewedSolution: false, linkedSkillIds: ['skillId1'] }, ques4: { answers: [{ isCorrect: false, }], usedHints: ['hint1'], viewedSolution: false, linkedSkillIds: ['skillId1'] } }; expect(ctrl.masteryPerSkillMapping).toEqual(undefined); ctrl.calculateMasteryDegrees(questionStateData); expect(ctrl.masteryPerSkillMapping).toEqual({ skillId1: -0.04000000000000001 }); }); it('should open concept card modal when user clicks on review' + ' and retry', () => { spyOn(ctrl, 'openConceptCardModal').and.stub(); ctrl.failedSkillIds = ['skillId1']; ctrl.reviewConceptCardAndRetryTest(); expect(ctrl.openConceptCardModal).toHaveBeenCalled(); }); it('should throw error when user clicks on review and retry' + ' and there are no failed skills', () => { ctrl.failedSkillIds = []; expect(() => ctrl.reviewConceptCardAndRetryTest()).toThrowError( 'No failed skills' ); }); it('should get color for score based on score per skill', () => { let scorePerSkill = { score: 5, total: 7 }; ctrl.questionPlayerConfig = { questionPlayerMode: { modeType: 'NOT_PASS_FAIL', passCutoff: 1.5 } }; expect(ctrl.getColorForScore(scorePerSkill)).toBe('rgb(0, 150, 136)'); ctrl.questionPlayerConfig = { questionPlayerMode: { modeType: 'PASS_FAIL', passCutoff: 1.5 } }; expect(ctrl.getColorForScore(scorePerSkill)).toBe('rgb(217, 92, 12)'); ctrl.questionPlayerConfig = { questionPlayerMode: { modeType: 'PASS_FAIL', passCutoff: 0.5 } }; expect(ctrl.getColorForScore(scorePerSkill)).toBe('rgb(0, 150, 136)'); }); it('should get color for score bar based on score per skill', () => { let scorePerSkill = { score: 5, total: 7 }; ctrl.questionPlayerConfig = { questionPlayerMode: { modeType: 'NOT_PASS_FAIL', passCutoff: 1.5 } }; expect(ctrl.getColorForScoreBar(scorePerSkill)).toBe('rgb(32, 93, 134)'); ctrl.questionPlayerConfig = { questionPlayerMode: { modeType: 'PASS_FAIL', passCutoff: 1.5 } }; expect(ctrl.getColorForScoreBar(scorePerSkill)).toBe('rgb(217, 92, 12)'); ctrl.questionPlayerConfig = { questionPlayerMode: { modeType: 'PASS_FAIL', passCutoff: 0.5 } }; expect(ctrl.getColorForScoreBar(scorePerSkill)).toBe('rgb(32, 93, 134)'); }); it('should open skill mastery modal when user clicks on skill', () => { let masteryPerSkillMapping; let skillId; let openConceptCardModal; let userIsLoggedIn; ctrl.masteryPerSkillMapping = { skillId1: -0.1 }; ctrl.openConceptCardModal = false; ctrl.userIsLoggedIn = true; spyOn($uibModal, 'open').and.callFake((options) => { masteryPerSkillMapping = options.resolve.masteryPerSkillMapping(); openConceptCardModal = options.resolve.openConceptCardModal(); skillId = options.resolve.skillId(); userIsLoggedIn = options.resolve.userIsLoggedIn(); return { result: $q.resolve() }; }); ctrl.openSkillMasteryModal('skillId1'); $scope.$apply(); expect(masteryPerSkillMapping).toEqual({skillId1: -0.1}); expect(skillId).toBe('skillId1'); expect(openConceptCardModal).toBe(false); expect(userIsLoggedIn).toBe(true); }); it('should close skill master modal when user clicks cancel', () => { ctrl.masteryPerSkillMapping = { skillId1: -0.1 }; spyOn($uibModal, 'open').and.callFake((options) => { return { result: $q.reject() }; }); ctrl.openSkillMasteryModal('skillId1'); $scope.$apply(); expect($uibModal.open).toHaveBeenCalled(); }); it('should prevent page reload or exit in between' + 'practice session', function() { spyOn(PreventPageUnloadEventService, 'addListener').and .callFake((callback) => callback()); ctrl.$onInit(); expect(PreventPageUnloadEventService.addListener) .toHaveBeenCalledWith(jasmine.any(Function)); }); });
the_stack
namespace gdjs { export namespace evtTools { export namespace firebaseTools { /** * Firebase Cloud database Event Tools. * @namespace */ export namespace database { /** * (Over)writes a variable in a collection as database variable. * @param path - The path where to store the variable. * @param variable - The variable to write. * @param [callbackStateVariable] - The variable where to store the result. */ export const writeVariable = ( path: string, variable: gdjs.Variable, callbackStateVariable?: gdjs.Variable ) => { firebase .database() .ref(path) .set(variable.toJSObject()) .then(() => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; /** * (Over)writes a field of a database variable. * @param path - The path where to write the field. * @param field - What field to write. * @param value - The value to write. * @param [callbackStateVariable] - The variable where to store the result. */ export const writeField = ( path: string, field: string, value: string | number, callbackStateVariable?: gdjs.Variable ) => { firebase .database() .ref(path) .set({ [field]: value }) .then(() => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; /** * Updates a database variable. * @param path - The name under wich the variable will be saved (document name). * @param variable - The variable to update. * @param [callbackStateVariable] - The variable where to store the result. */ export const updateVariable = ( path: string, variable: gdjs.Variable, callbackStateVariable?: gdjs.Variable ) => { firebase .database() .ref(path) .update(variable.toJSObject()) .then(() => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; /** * Updates a field of a database variable. * @param path - The name under wich the variable will be saved (document name). * @param field - The field where to update. * @param value - The value to write. * @param [callbackStateVariable] - The variable where to store the result. */ export const updateField = ( path: string, field: string, value: string | number, callbackStateVariable?: gdjs.Variable ) => { const updateObject = {}; updateObject[field] = value; firebase .database() .ref(path) .update(updateObject) .then(() => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; /** * Deletes a database variable. * @param path - The name under wich the variable will be saved (document name). * @param [callbackStateVariable] - The variable where to store the result. */ export const deleteVariable = ( path: string, callbackStateVariable?: gdjs.Variable ) => { firebase .database() .ref(path) .remove() .then(() => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; /** * Deletes a field of a database variable. * @param path - The name under wich the variable will be saved (document name). * @param field - The field to delete. * @param [callbackStateVariable] - The variable where to store the result. */ export const deleteField = ( path: string, field: string, callbackStateVariable?: gdjs.Variable ) => { const updateObject = {}; updateObject[field] = null; firebase .database() .ref(path) .update(updateObject) .then(() => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; /** * Gets a database variable and store it in a variable. * @param path - The name under wich the variable will be saved (document name). * @param callbackValueVariable - The variable where to store the result. * @param [callbackStateVariable] - The variable where to store if the operation was successful. */ export const getVariable = ( path: string, callbackValueVariable: gdjs.Variable, callbackStateVariable?: gdjs.Variable ) => { firebase .database() .ref(path) .once('value') .then((snapshot) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); if (typeof callbackValueVariable !== 'undefined') callbackValueVariable.fromJSObject(snapshot.val()); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; /** * Gets a field of a database variable and store it in a variable. * @param path - The name under wich the variable will be saved (document name). * @param field - The field to get. * @param callbackValueVariable - The variable where to store the result. * @param [callbackStateVariable] - The variable where to store if the operation was successful. */ export const getField = ( path: string, field: string, callbackValueVariable: gdjs.Variable, callbackStateVariable?: gdjs.Variable ) => { firebase .database() .ref(path) .once('value') .then((snapshot) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); if (typeof callbackValueVariable !== 'undefined') callbackValueVariable.fromJSObject(snapshot.val()[field]); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; /** * Checks for existence of a database variable. * @param path - The name under wich the variable will be saved (document name). * @param callbackValueVariable - The variable where to store the result. * @param [callbackStateVariable] - The variable where to store if the operation was successful. */ export const hasVariable = ( path: string, callbackValueVariable: gdjs.Variable, callbackStateVariable?: gdjs.Variable ) => { firebase .database() .ref(path) .once('value') .then((snapshot) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); if (typeof callbackValueVariable !== 'undefined') callbackValueVariable.setBoolean( snapshot.exists() && snapshot.val() !== null && snapshot.val() !== undefined ); }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; /** * Checks for existence of a database variable. * @param path - The name under wich the variable will be saved (document name). * @param field - The field to check. * @param callbackValueVariable - The variable where to store the result. * @param [callbackStateVariable] - The variable where to store if the operation was successful. */ export const hasField = ( path: string, field: string, callbackValueVariable: gdjs.Variable, callbackStateVariable?: gdjs.Variable ) => { firebase .database() .ref(path) .once('value') .then((snapshot) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString('ok'); if (typeof callbackValueVariable !== 'undefined') { const value = snapshot.val()[field]; callbackValueVariable.setBoolean( snapshot.exists() && value !== null && value !== undefined ); } }) .catch((error) => { if (typeof callbackStateVariable !== 'undefined') callbackStateVariable.setString(error.message); }); }; } } } }
the_stack
const serverRequire = require; let THREE: typeof SupEngine.THREE; // NOTE: It is important that we require THREE through SupEngine // so that we inherit any settings, like the global Euler order // (or, alternatively, we could duplicate those settings...) if ((<any>global).window == null) { THREE = serverRequire("../../../../SupEngine").THREE; serverRequire("../componentConfigs/BaseComponentConfig.js"); SupCore.system.requireForAllPlugins("componentConfigs/index.js"); } else if ((<any>window).SupEngine != null) THREE = SupEngine.THREE; import * as path from "path"; import * as fs from "fs"; import * as _ from "lodash"; import { Component } from "./SceneComponents"; import SceneNodes, { Node } from "./SceneNodes"; type AddNodeCallback = SupCore.Data.Base.ErrorCallback & ((err: string, nodeId: string, node: Node, parentId: string, index: number) => void); type SetNodePropertyCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, id: string, path: string, value: any) => void); type MoveNodeCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, id: string, parentId: string, index: number) => void); type DuplicateNodeCallback = SupCore.Data.Base.ErrorCallback & ((err: string, nodeId: string, rootNode: Node, newNodes: DuplicatedNode[]) => void); type RemoveNodeCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, id: string) => void); type AddComponentCallback = SupCore.Data.Base.ErrorCallback & ((err: string, componentId: string, component: Component, nodeId: string, index: number) => void); type EditComponentCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, nodeId: string, componentId: string, command: string, ...args: any[]) => void); type RemoveComponentCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, nodeId: string, componentId: string) => void); export interface DuplicatedNode { node: Node; parentId: string; index: number; } interface ScenePub { formatVersion: number; nodes: Node[]; } export default class SceneAsset extends SupCore.Data.Base.Asset { static currentFormatVersion = 1; static schema: SupCore.Data.Schema = { nodes: { type: "array" }, }; pub: ScenePub; componentPathsByDependentAssetId: { [assetId: string]: string[] }; nodes: SceneNodes; constructor(id: string, pub: any, server: ProjectServer) { super(id, pub, SceneAsset.schema, server); } init(options: any, callback: Function) { this.pub = { formatVersion: SceneAsset.currentFormatVersion, nodes: [] }; super.init(options, callback); } load(assetPath: string) { fs.readFile(path.join(assetPath, "scene.json"), { encoding: "utf8" }, (err, json) => { if (err != null && err.code === "ENOENT") { fs.readFile(path.join(assetPath, "asset.json"), { encoding: "utf8" }, (err, json) => { fs.rename(path.join(assetPath, "asset.json"), path.join(assetPath, "scene.json"), (err) => { this._onLoaded(assetPath, JSON.parse(json)); }); }); } else { this._onLoaded(assetPath, JSON.parse(json)); } }); } migrate(assetPath: string, pub: ScenePub, callback: (hasMigrated: boolean) => void) { // Migrate component configs let hasMigratedComponents = false; const componentClasses = this.server.system.getPlugins<SupCore.Data.ComponentConfigClass>("componentConfigs"); const walk = (node: Node) => { for (const component of node.components) { const componentClass = componentClasses[component.type]; if (componentClass.migrate != null && componentClass.migrate(component.config)) hasMigratedComponents = true; } for (const child of node.children) walk(child); }; for (const node of pub.nodes) walk(node); if (pub.formatVersion === SceneAsset.currentFormatVersion) { callback(hasMigratedComponents); return; } // node.prefabId used to be set to the empty string // when the node was a prefab but had no scene associated. // It was replaced with node.prefab.sceneAssetId // in Superpowers v0.16. function migrateOldPrefab(node: Node) { const oldPrefabId = (node as any).prefabId; if (oldPrefabId != null) { delete (node as any).prefabId; node.prefab = { sceneAssetId: oldPrefabId.length > 0 ? oldPrefabId : null }; } else { for (const child of node.children) migrateOldPrefab(child); } } if (pub.formatVersion == null) { for (const rootNode of pub.nodes) migrateOldPrefab(rootNode); pub.formatVersion = 1; } callback(true); } save(outputPath: string, callback: (err: Error) => void) { this.write(fs.writeFile, outputPath, callback); } clientExport(outputPath: string, callback: (err: Error) => void) { this.write(SupApp.writeFile, outputPath, callback); } private write(writeFile: Function, outputPath: string, callback: (err: Error) => any) { const json = JSON.stringify(this.pub, null, 2); writeFile(path.join(outputPath, "scene.json"), json, { encoding: "utf8" }, callback); } setup() { this.componentPathsByDependentAssetId = {}; this.nodes = new SceneNodes(this.pub.nodes, this); this.nodes.on("addDependencies", (depIds: string[], componentPath: string) => { this._onAddComponentDependencies(componentPath, depIds); }); this.nodes.on("removeDependencies", (depIds: string[], componentPath: string) => { this._onRemoveComponentDependencies(componentPath, depIds); }); this.nodes.walk((node: Node) => { if (node.prefab != null && node.prefab.sceneAssetId != null) this._onAddComponentDependencies(`${node.id}_${node.prefab.sceneAssetId}`, [ node.prefab.sceneAssetId ]); }); for (const nodeId in this.nodes.componentsByNodeId) { const components = this.nodes.componentsByNodeId[nodeId]; for (const componentId in components.configsById) { const config = components.configsById[componentId]; const componentPath = `${nodeId}_${componentId}`; ((config: SupCore.Data.Base.ComponentConfig, componentPath: string) => { config.on("addDependencies", (depIds: string[]) => { this._onAddComponentDependencies(componentPath, depIds); }); config.on("removeDependencies", (depIds: string[]) => { this._onRemoveComponentDependencies(componentPath, depIds); }); })(config, componentPath); config.restore(); } } } /* NOTE: We're restore()'ing all the components during this.setup() since we need to rebuild this.componentPathsByDependentAssetId every time the scene asset is loaded. It's a bit weird but it all works out since this.setup() is called right before this.restore() anyway.*/ restore() { this.emit("addDependencies", Object.keys(this.componentPathsByDependentAssetId)); } server_addNode(client: SupCore.RemoteClient, name: string, options: any, callback: AddNodeCallback) { if (name.indexOf("/") !== -1) { callback("Actor name cannot contain slashes"); return; } const parentId = (options != null) ? options.parentId : null; const parentNode = this.nodes.byId[parentId]; if (parentNode != null && parentNode.prefab != null) { callback("Can't create children node on prefabs"); return; } if (this.nodes.pub.length !== 0 && parentNode == null) { const entry = this.server.data.entries.byId[this.id]; if (entry.dependentAssetIds.length > 0) { callback("A prefab can only have one root actor"); return; } } const sceneNode: Node = { id: null, name: name, children: <Node[]>[], components: <Component[]>[], position: (options != null && options.transform != null && options.transform.position != null) ? options.transform.position : { x: 0, y: 0, z: 0 }, orientation: (options != null && options.transform != null && options.transform.orientation != null) ? options.transform.orientation : { x: 0, y: 0, z: 0, w: 1 }, scale: (options != null && options.transform != null && options.transform.scale != null) ? options.transform.scale : { x: 1, y: 1, z: 1 }, visible: true, layer: 0, prefab: (options.prefab) ? { sceneAssetId: null } : null }; const index = (options != null) ? options.index : null; this.nodes.add(sceneNode, parentId, index, (err, actualIndex) => { if (err != null) { callback(err); return; } callback(null, sceneNode.id, sceneNode, parentId, actualIndex); this.emit("change"); }); } client_addNode(node: Node, parentId: string, index: number) { this.nodes.client_add(node, parentId, index); } server_setNodeProperty(client: SupCore.RemoteClient, id: string, path: string, value: any, callback: SetNodePropertyCallback) { if (path === "name" && value.indexOf("/") !== -1) { callback("Actor name cannot contain slashes"); return; } this.nodes.setProperty(id, path, value, (err, actualValue) => { if (err != null) { callback(err); return; } callback(null, null, id, path, actualValue); this.emit("change"); }); } client_setNodeProperty(id: string, path: string, value: any) { this.nodes.client_setProperty(id, path, value); } server_moveNode(client: SupCore.RemoteClient, id: string, parentId: string, index: number, callback: MoveNodeCallback) { const node = this.nodes.byId[id]; if (node == null) { callback(`Invalid node id: ${id}`); return; } const parentNode = this.nodes.byId[parentId]; if (parentNode != null && parentNode.prefab != null) { callback("Can't move children node on prefabs"); return; } if (parentNode == null) { const entry = this.server.data.entries.byId[this.id]; if (entry.dependentAssetIds.length > 0) { callback("A prefab can only have one root actor"); return; } } const globalMatrix = this.computeGlobalMatrix(node); this.nodes.move(id, parentId, index, (err, actualIndex) => { if (err != null) { callback(err); return; } this.applyGlobalMatrix(node, globalMatrix); callback(null, null, id, parentId, actualIndex); this.emit("change"); }); } computeGlobalMatrix(node: Node) { const matrix = new THREE.Matrix4().compose(<THREE.Vector3>node.position, <THREE.Quaternion>node.orientation, <THREE.Vector3>node.scale); const parentNode = this.nodes.parentNodesById[node.id]; if (parentNode != null) { const parentGlobalMatrix = this.computeGlobalMatrix(parentNode); matrix.multiplyMatrices(parentGlobalMatrix, matrix); } return matrix; } applyGlobalMatrix(node: Node, matrix: THREE.Matrix4) { const parentNode = this.nodes.parentNodesById[node.id]; if (parentNode != null) { const parentGlobalMatrix = this.computeGlobalMatrix(parentNode); matrix.multiplyMatrices(new THREE.Matrix4().getInverse(parentGlobalMatrix), matrix); } const position = new THREE.Vector3(); const orientation = new THREE.Quaternion(); const scale = new THREE.Vector3(); matrix.decompose(position, orientation, scale); node.position = { x: position.x, y: position.y, z: position.z }; node.orientation = { x: orientation.x, y: orientation.y, z: orientation.z, w: orientation.w }; node.scale = { x: scale.x, y: scale.y, z: scale.z }; } client_moveNode(id: string, parentId: string, index: number) { const node = this.nodes.byId[id]; const globalMatrix = this.computeGlobalMatrix(node); this.nodes.client_move(id, parentId, index); this.applyGlobalMatrix(node, globalMatrix); } server_duplicateNode(client: SupCore.RemoteClient, newName: string, id: string, index: number, callback: DuplicateNodeCallback) { if (newName.indexOf("/") !== -1) { callback("Actor name cannot contain slashes"); return; } const referenceNode = this.nodes.byId[id]; if (referenceNode == null) { callback(`Invalid node id: ${id}`); return; } const parentNode = this.nodes.parentNodesById[id]; if (parentNode == null) { const entry = this.server.data.entries.byId[this.id]; if (entry.dependentAssetIds.length > 0) { callback("A prefab can only have one root actor"); return; } } const newNodes: DuplicatedNode[] = []; let totalNodeCount = 0; const walk = (node: Node) => { totalNodeCount += 1; for (const childNode of node.children) walk(childNode); }; walk(referenceNode); const rootNode: Node = { id: null, name: newName, children: [], components: _.cloneDeep(referenceNode.components), position: _.cloneDeep(referenceNode.position), orientation: _.cloneDeep(referenceNode.orientation), scale: _.cloneDeep(referenceNode.scale), visible: referenceNode.visible, layer: referenceNode.layer, prefab: _.cloneDeep(referenceNode.prefab) }; const parentId = (parentNode != null) ? parentNode.id : null; const addNode = (newNode: Node, parentId: string, index: number, children: Node[]) => { this.nodes.add(newNode, parentId, index, (err, actualIndex) => { if (err != null) { callback(err); return; } for (const componentId in this.nodes.componentsByNodeId[newNode.id].configsById) { const config = this.nodes.componentsByNodeId[newNode.id].configsById[componentId]; const componentPath = `${newNode.id}_${componentId}`; ((config: SupCore.Data.Base.ComponentConfig, componentPath: string) => { config.on("addDependencies", (depIds: string[]) => { this._onAddComponentDependencies(componentPath, depIds); }); config.on("removeDependencies", (depIds: string[]) => { this._onRemoveComponentDependencies(componentPath, depIds); }); })(config, componentPath); config.restore(); } newNodes.push({ node: newNode, parentId, index: actualIndex }); if (newNodes.length === totalNodeCount) { callback(null, rootNode.id, rootNode, newNodes); this.emit("change"); } for (let childIndex = 0; childIndex < children.length; childIndex++) { const childNode = children[childIndex]; const node: Node = { id: null, name: childNode.name, children: [], components: _.cloneDeep(childNode.components), position: _.cloneDeep(childNode.position), orientation: _.cloneDeep(childNode.orientation), scale: _.cloneDeep(childNode.scale), visible: childNode.visible, layer: childNode.layer, prefab: _.cloneDeep(childNode.prefab) }; addNode(node, newNode.id, childIndex, childNode.children); } }); }; addNode(rootNode, parentId, index, referenceNode.children); } client_duplicateNode(rootNode: Node, newNodes: DuplicatedNode[]) { for (const newNode of newNodes) { newNode.node.children.length = 0; this.nodes.client_add(newNode.node, newNode.parentId, newNode.index); } } server_removeNode(client: SupCore.RemoteClient, id: string, callback: RemoveNodeCallback) { this.nodes.remove(id, (err) => { if (err != null) { callback(err); return; } callback(null, null, id); this.emit("change"); }); } client_removeNode(id: string) { this.nodes.client_remove(id); } // Components _onAddComponentDependencies(componentPath: string, depIds: string[]) { // console.log `Adding component dependencies: ${componentPath} - ${depIds}` const addedDepIds: string[] = []; for (const depId of depIds) { if (this.componentPathsByDependentAssetId[depId] == null) this.componentPathsByDependentAssetId[depId] = []; const componentPaths = this.componentPathsByDependentAssetId[depId]; if (componentPaths.indexOf(componentPath) === -1) { componentPaths.push(componentPath); if (componentPaths.length === 1) addedDepIds.push(depId); } } if (addedDepIds.length > 0) this.emit("addDependencies", addedDepIds); } _onRemoveComponentDependencies(componentPath: string, depIds: string[]) { // console.log `Removing component dependencies: ${componentPath} - ${depIds}` const removedDepIds: string[] = []; for (const depId of depIds) { const componentPaths = this.componentPathsByDependentAssetId[depId]; const index = (componentPaths != null) ? componentPaths.indexOf(componentPath) : null; if (index != null && index !== -1) { componentPaths.splice(index, 1); if (componentPaths.length === 0) { removedDepIds.push(depId); delete this.componentPathsByDependentAssetId[depId]; } } } if (removedDepIds.length > 0) this.emit("removeDependencies", removedDepIds); } server_addComponent(client: SupCore.RemoteClient, nodeId: string, componentType: string, index: number, callback: AddComponentCallback) { const componentConfigClass = this.server.system.getPlugins<SupCore.Data.ComponentConfigClass>("componentConfigs")[componentType]; if (componentConfigClass == null) { callback("Invalid component type"); return; } const node = this.nodes.byId[nodeId]; if (node != null && node.prefab != null) { callback("Can't add component on prefabs"); return; } const component: Component = { type: componentType, config: componentConfigClass.create(), }; this.nodes.addComponent(nodeId, component, index, (err, actualIndex) => { if (err != null) { callback(err); return; } const config = this.nodes.componentsByNodeId[nodeId].configsById[component.id]; const componentPath = `${nodeId}_${component.id}`; config.on("addDependencies", (depIds: string[]) => { this._onAddComponentDependencies(componentPath, depIds); }); config.on("removeDependencies", (depIds: string[]) => { this._onRemoveComponentDependencies(componentPath, depIds); }); callback(null, component.id, component, nodeId, actualIndex); this.emit("change"); }); } client_addComponent(component: Component, nodeId: string, index: number) { this.nodes.client_addComponent(nodeId, component, index); } server_editComponent(client: SupCore.RemoteClient, nodeId: string, componentId: string, command: string, ...args: any[]) { const callback: EditComponentCallback = args.pop(); const components = this.nodes.componentsByNodeId[nodeId]; if (components == null) { callback(`Invalid node id: ${nodeId}`); return; } const componentConfig = components.configsById[componentId]; if (componentConfig == null) { callback(`Invalid component id: ${componentId}`); return; } const commandMethod = (<any>componentConfig)[`server_${command}`]; if (commandMethod == null) { callback("Invalid component command"); return; } commandMethod.call(componentConfig, client, ...args, (err: string, ...callbackArgs: any[]) => { if (err != null) { callback(err); return; } callback(null, null, nodeId, componentId, command, ...callbackArgs); this.emit("change"); }); } client_editComponent(nodeId: string, componentId: string, command: string, ...args: any[]) { const componentConfig = this.nodes.componentsByNodeId[nodeId].configsById[componentId]; const commandMethod = (<any>componentConfig)[`client_${command}`]; commandMethod.apply(componentConfig, args); } server_removeComponent(client: SupCore.RemoteClient, nodeId: string, componentId: string, callback: RemoveComponentCallback) { const components = this.nodes.componentsByNodeId[nodeId]; if (components == null) { callback(`Invalid node id: ${nodeId}`); return; } components.remove(componentId, (err) => { if (err != null) { callback(err); return; } callback(null, null, nodeId, componentId); this.emit("change"); }); } client_removeComponent(nodeId: string, componentId: string) { this.nodes.componentsByNodeId[nodeId].client_remove(componentId); } }
the_stack
* @packageDocumentation * @module tiledmap */ import { Label, HorizontalTextAlignment, VerticalTextAlignment } from '../2d/components/label'; import codec from '../../external/compression/ZipUtils.js'; import zlib from '../../external/compression/zlib.min.js'; import { SAXParser } from '../core/asset-manager/plist-parser'; import { GID, MixedGID, Orientation, PropertiesInfo, RenderOrder, StaggerAxis, StaggerIndex, TiledAnimation, TiledAnimationType, TileFlag, TMXImageLayerInfo, TMXLayerInfo, TMXObject, TMXObjectGroupInfo, TMXObjectType, TMXTilesetInfo, } from './tiled-types'; import { Color, errorID, logID, Size, Vec2 } from '../core'; import { SpriteFrame } from '../2d/assets'; function uint8ArrayToUint32Array (uint8Arr: Uint8Array): null | Uint32Array | number[] { if (uint8Arr.length % 4 !== 0) return null; const arrLen = uint8Arr.length / 4; const retArr = window.Uint32Array ? new Uint32Array(arrLen) : []; for (let i = 0; i < arrLen; i++) { const offset = i * 4; retArr[i] = uint8Arr[offset] + uint8Arr[offset + 1] * (1 << 8) + uint8Arr[offset + 2] * (1 << 16) + uint8Arr[offset + 3] * (1 << 24); } return retArr; } function strToHAlign (value): HorizontalTextAlignment { const hAlign = Label.HorizontalAlign; switch (value) { case 'center': return hAlign.CENTER; case 'right': return hAlign.RIGHT; default: return hAlign.LEFT; } } function strToVAlign (value): VerticalTextAlignment { const vAlign = Label.VerticalAlign; switch (value) { case 'center': return vAlign.CENTER; case 'bottom': return vAlign.BOTTOM; default: return vAlign.TOP; } } function strToColor (value: string): Color { if (!value) { return new Color(0, 0, 0, 255); } value = (value.indexOf('#') !== -1) ? value.substring(1) : value; if (value.length === 8) { const a = parseInt(value.substr(0, 2), 16) || 255; const r = parseInt(value.substr(2, 2), 16) || 0; const g = parseInt(value.substr(4, 2), 16) || 0; const b = parseInt(value.substr(6, 2), 16) || 0; return new Color(r, g, b, a); } else { const r = parseInt(value.substr(0, 2), 16) || 0; const g = parseInt(value.substr(2, 2), 16) || 0; const b = parseInt(value.substr(4, 2), 16) || 0; return new Color(r, g, b, 255); } } function getPropertyList (node: Element, map?: PropertiesInfo): PropertiesInfo { const res: any[] = []; const properties = node.getElementsByTagName('properties'); for (let i = 0; i < properties.length; ++i) { const property = properties[i].getElementsByTagName('property'); for (let j = 0; j < property.length; ++j) { res.push(property[j]); } } map = map || ({} as any); for (let i = 0; i < res.length; i++) { const element = res[i]; const name = element.getAttribute('name'); const type = element.getAttribute('type') || 'string'; let value = element.getAttribute('value'); if (type === 'int') { value = parseInt(value); } else if (type === 'float') { value = parseFloat(value); } else if (type === 'bool') { value = value === 'true'; } else if (type === 'color') { value = strToColor(value); } map![name] = value; } return map!; } /** * <p>cc.TMXMapInfo contains the information about the map like: <br/> * - Map orientation (hexagonal, isometric or orthogonal)<br/> * - Tile size<br/> * - Map size</p> * * <p>And it also contains: <br/> * - Layers (an array of TMXLayerInfo objects)<br/> * - Tilesets (an array of TMXTilesetInfo objects) <br/> * - ObjectGroups (an array of TMXObjectGroupInfo objects) </p> * * <p>This information is obtained from the TMX file. </p> * @class TMXMapInfo */ export class TMXMapInfo { /** * Properties of the map info. * @property {Array} properties */ properties: PropertiesInfo = {} as any; /** * Map orientation. * @property {Number} orientation */ orientation: Orientation | null = null; /** * Parent element. * @property {Object} parentElement */ parentElement: Record<string, unknown> | null = null; /** * Parent GID. * @property {Number} parentGID */ parentGID: MixedGID = 0 as unknown as any; /** * Layer attributes. * @property {Object} layerAttrs */ layerAttrs = 0; /** * Is reading storing characters stream. * @property {Boolean} storingCharacters */ storingCharacters = false; /** * Current string stored from characters stream. * @property {String} currentString */ currentString: string | null = null; renderOrder: RenderOrder = RenderOrder.RightDown; protected _supportVersion = [1, 4, 0]; protected _objectGroups: TMXObjectGroupInfo[] = []; protected _allChildren: (TMXLayerInfo | TMXImageLayerInfo | TMXObjectGroupInfo)[] = []; protected _mapSize = new Size(0, 0); get mapSize () { return this._mapSize; } protected _tileSize = new Size(0, 0); get tileSize () { return this._tileSize; } protected _layers: TMXLayerInfo[] = []; protected _tilesets: TMXTilesetInfo[] = []; protected _imageLayers: TMXImageLayerInfo[] = []; protected _tileProperties: Map<GID, PropertiesInfo> = new Map(); protected _tileAnimations: TiledAnimationType = {} as any; protected _tsxContentMap: { [key: string]: string } | null = null; // map of textures indexed by name protected _spriteFrameMap: { [key: string]: SpriteFrame } | null = null; protected _spfSizeMap: { [key: string]: Size } = {}; // hex map values protected _staggerAxis: StaggerAxis | null = null; protected _staggerIndex: StaggerIndex | null = null; protected _hexSideLength = 0; protected _imageLayerSPF: { [key: string]: SpriteFrame } | null = null; constructor (tmxFile: string, tsxContentMap: { [key: string]: string }, spfTexturesMap: { [key: string]: SpriteFrame }, textureSizes: { [key: string]: Size }, imageLayerTextures: { [key: string]: SpriteFrame }) { this.initWithXML(tmxFile, tsxContentMap, spfTexturesMap, textureSizes, imageLayerTextures); } /* Gets Map orientation. * @return {Number} */ getOrientation () { return this.orientation; } /** * Set the Map orientation. * @param {Number} value */ setOrientation (value: Orientation) { this.orientation = value; } /** * Gets the staggerAxis of map. * @return {TiledMap.StaggerAxis} */ getStaggerAxis () { return this._staggerAxis; } /** * Set the staggerAxis of map. * @param {TiledMap.StaggerAxis} value */ setStaggerAxis (value: StaggerAxis) { this._staggerAxis = value; } /** * Gets stagger index * @return {TiledMap.StaggerIndex} */ getStaggerIndex () { return this._staggerIndex; } /** * Set the stagger index. * @param {TiledMap.StaggerIndex} value */ setStaggerIndex (value) { this._staggerIndex = value; } /** * Gets Hex side length. * @return {Number} */ getHexSideLength () { return this._hexSideLength; } /** * Set the Hex side length. * @param {Number} value */ setHexSideLength (value: number) { this._hexSideLength = value; } /** * Map width & height * @return {Size} */ getMapSize () { return new Size(this._mapSize.width, this._mapSize.height); } /** * Map width & height * @param {Size} value */ setMapSize (value: Size) { this._mapSize.width = value.width; this._mapSize.height = value.height; } get mapWidth () { return this._mapSize.width; } set mapWidth (width: number) { this._mapSize.width = width; } get mapHeight () { return this._mapSize.height; } set mapHeight (height: number) { this._mapSize.height = height; } /** * Tiles width & height * @return {Size} */ getTileSize () { return new Size(this._tileSize.width, this._tileSize.height); } /** * Tiles width & height * @param {Size} value */ setTileSize (value: Size) { this._tileSize.width = value.width; this._tileSize.height = value.height; } get tileWidth () { return this._tileSize.width; } set tileWidth (width) { this._tileSize.width = width; } /** * Height of a tile */ get tileHeight () { return this._tileSize.height; } set tileHeight (height: number) { this._tileSize.height = height; } /** * Layers * @return {Array} */ getLayers () { return this._layers; } /** * Layers * @param {cc.TMXLayerInfo} value */ setLayers (value: TMXLayerInfo) { this._allChildren.push(value); this._layers.push(value); } /** * ImageLayers * @return {Array} */ getImageLayers () { return this._imageLayers; } /** * ImageLayers * @param {cc.TMXImageLayerInfo} value */ setImageLayers (value: TMXImageLayerInfo) { this._allChildren.push(value); this._imageLayers.push(value); } /** * tilesets * @return {Array} */ getTilesets () { return this._tilesets; } /** * tilesets * @param {cc.TMXTilesetInfo} value */ setTilesets (value: TMXTilesetInfo) { this._tilesets.push(value); } /** * ObjectGroups * @return {Array} */ getObjectGroups () { return this._objectGroups; } /** * ObjectGroups * @param {cc.TMXObjectGroup} value */ setObjectGroups (value: TMXObjectGroupInfo) { this._allChildren.push(value); this._objectGroups.push(value); } getAllChildren () { return this._allChildren; } /** * parent element * @return {Object} */ getParentElement () { return this.parentElement; } /** * parent element * @param {Object} value */ setParentElement (value) { this.parentElement = value; } /** * parent GID * @return {Number} */ getParentGID () { return this.parentGID; } /** * parent GID * @param {Number} value */ setParentGID (value) { this.parentGID = value; } /** * Layer attribute * @return {Object} */ getLayerAttribs () { return this.layerAttrs; } /** * Layer attribute * @param {Object} value */ setLayerAttribs (value) { this.layerAttrs = value; } /** * Is reading storing characters stream * @return {Boolean} */ getStoringCharacters () { return this.storingCharacters; } /** * Is reading storing characters stream * @param {Boolean} value */ setStoringCharacters (value) { this.storingCharacters = value; } /** * Properties * @return {Array} */ getProperties () { return this.properties; } /** * Properties * @param {object} value */ setProperties (value) { this.properties = value; } /** * initializes a TMX format with an XML string and a TMX resource path * @param {String} tmxString * @param {Object} tsxMap * @param {Object} spfTextureMap * @return {Boolean} */ initWithXML (tmxString: string, tsxMap: { [key: string]: string }, spfTextureMap: { [key: string]: SpriteFrame }, textureSizes: { [key: string]: Size }, imageLayerTextures: { [key: string]: SpriteFrame }) { this._tilesets.length = 0; this._layers.length = 0; this._imageLayers.length = 0; this._tsxContentMap = tsxMap; this._spriteFrameMap = spfTextureMap; this._imageLayerSPF = imageLayerTextures; this._spfSizeMap = textureSizes; this._objectGroups.length = 0; this._allChildren.length = 0; this.properties = {} as any; this._tileProperties = new Map(); this._tileAnimations = new Map(); // tmp vars this.currentString = ''; this.storingCharacters = false; this.layerAttrs = TMXLayerInfo.ATTRIB_NONE; this.parentElement = null; return this.parseXMLString(tmxString); } /** * Initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string * @param {String} xmlString * @param {Number} tilesetFirstGid * @return {Element} */ parseXMLString (xmlStr: string, tilesetFirstGid?: number) { const parser = new SAXParser(); const mapXML: Document = parser.parse(xmlStr); let i: number; // PARSE <map> const map = mapXML.documentElement; const orientationStr = map.getAttribute('orientation'); const staggerAxisStr = map.getAttribute('staggeraxis'); const staggerIndexStr = map.getAttribute('staggerindex'); const hexSideLengthStr = map.getAttribute('hexsidelength'); const renderorderStr = map.getAttribute('renderorder'); const version = map.getAttribute('version') || '1.0.0'; if (map.nodeName === 'map') { const versionArr = version.split('.'); const supportVersion = this._supportVersion; for (i = 0; i < supportVersion.length; i++) { const v = parseInt(versionArr[i]) || 0; const sv = supportVersion[i]; if (sv < v) { logID(7216, version); break; } } if (orientationStr === 'orthogonal') this.orientation = Orientation.ORTHO; else if (orientationStr === 'isometric') this.orientation = Orientation.ISO; else if (orientationStr === 'hexagonal') this.orientation = Orientation.HEX; else if (orientationStr !== null) logID(7217, orientationStr); if (renderorderStr === 'right-up') { this.renderOrder = RenderOrder.RightUp; } else if (renderorderStr === 'left-up') { this.renderOrder = RenderOrder.LeftUp; } else if (renderorderStr === 'left-down') { this.renderOrder = RenderOrder.LeftDown; } else { this.renderOrder = RenderOrder.RightDown; } if (staggerAxisStr === 'x') { this.setStaggerAxis(StaggerAxis.STAGGERAXIS_X); } else if (staggerAxisStr === 'y') { this.setStaggerAxis(StaggerAxis.STAGGERAXIS_Y); } if (staggerIndexStr === 'odd') { this.setStaggerIndex(StaggerIndex.STAGGERINDEX_ODD); } else if (staggerIndexStr === 'even') { this.setStaggerIndex(StaggerIndex.STAGGERINDEX_EVEN); } if (hexSideLengthStr) { this.setHexSideLength(parseFloat(hexSideLengthStr)); } let mapSize = new Size(0, 0); mapSize.width = parseFloat(map.getAttribute('width')!); mapSize.height = parseFloat(map.getAttribute('height')!); this.setMapSize(mapSize); mapSize = new Size(0, 0); mapSize.width = parseFloat(map.getAttribute('tilewidth')!); mapSize.height = parseFloat(map.getAttribute('tileheight')!); this.setTileSize(mapSize); // The parent element is the map this.properties = getPropertyList(map); } // PARSE <tileset> let tilesets: Element[] = map.getElementsByTagName('tileset') as unknown as Element[]; if (map.nodeName !== 'map') { tilesets = []; tilesets.push(map); } for (i = 0; i < tilesets.length; i++) { const curTileset = tilesets[i]; // If this is an external tileset then start parsing that const tsxName = curTileset.getAttribute('source'); if (tsxName) { const currentFirstGID = parseInt(curTileset.getAttribute('firstgid')!); const tsxXmlString = this._tsxContentMap![tsxName]; if (tsxXmlString) { this.parseXMLString(tsxXmlString, currentFirstGID); } } else { const images = curTileset.getElementsByTagName('image'); const collection = images.length > 1; const firstImage = images[0]; let firstImageName: string = firstImage.getAttribute('source')!; firstImageName = firstImageName.replace(/\\/g, '/'); const tiles = curTileset.getElementsByTagName('tile'); const tileCount = tiles && tiles.length || 1; let tile: Element | null = null; const tilesetName = curTileset.getAttribute('name') || ''; const tilesetSpacing = parseInt(curTileset.getAttribute('spacing')!) || 0; const tilesetMargin = parseInt(curTileset.getAttribute('margin')!) || 0; const fgid = tilesetFirstGid || (parseInt(curTileset.getAttribute('firstgid')!) || 0); const tilesetSize = new Size(0, 0); tilesetSize.width = parseFloat(curTileset.getAttribute('tilewidth')!); tilesetSize.height = parseFloat(curTileset.getAttribute('tileheight')!); // parse tile offset const curTileOffset = curTileset.getElementsByTagName('tileoffset')[0]; let tileOffsetX = 0; let tileOffsetY = 0; if (curTileOffset) { tileOffsetX = parseFloat(curTileOffset.getAttribute('x')!) || 0; tileOffsetY = parseFloat(curTileOffset.getAttribute('y')!) || 0; } let tileset: TMXTilesetInfo | null = null; for (let tileIdx = 0; tileIdx < tileCount; tileIdx++) { const curImage = images[tileIdx] ? images[tileIdx] : firstImage; if (!curImage) continue; let curImageName: string = curImage.getAttribute('source')!; curImageName = curImageName.replace(/\\/g, '/'); if (!tileset || collection) { tileset = new TMXTilesetInfo(); tileset.name = tilesetName; tileset.firstGid = ((fgid as unknown as number) & TileFlag.FLIPPED_MASK) as unknown as GID; tileset.tileOffset.x = tileOffsetX; tileset.tileOffset.y = tileOffsetY; tileset.collection = collection; if (!collection) { tileset.imageName = curImageName; tileset.imageSize.width = parseFloat(curImage.getAttribute('width')!) || 0; tileset.imageSize.height = parseFloat(curImage.getAttribute('height')!) || 0; tileset.sourceImage = this._spriteFrameMap![curImageName]; if (!tileset.sourceImage) { const nameWithPostfix = TMXMapInfo.getNameWithPostfix(curImageName); tileset.imageName = nameWithPostfix; tileset.sourceImage = this._spriteFrameMap![nameWithPostfix]; if (!tileset.sourceImage) { const shortName = TMXMapInfo.getShortName(curImageName); tileset.imageName = shortName; tileset.sourceImage = this._spriteFrameMap![shortName]; if (!tileset.sourceImage) { console.error(`[error]: ${shortName} not find in [${Object.keys(this._spriteFrameMap!).join(', ')}]`); errorID(7221, curImageName); console.warn(`Please try asset type of ${curImageName} to 'sprite-frame'`); } } } } tileset.spacing = tilesetSpacing; tileset.margin = tilesetMargin; tileset._tileSize.width = tilesetSize.width; tileset._tileSize.height = tilesetSize.height; this.setTilesets(tileset); } // parse tiles by tileIdx tile = tiles && tiles[tileIdx]; if (!tile) { continue; } this.parentGID = (fgid + (parseInt(tile.getAttribute('id')!) || 0)) as any; const tileImages = tile.getElementsByTagName('image'); if (tileImages && tileImages.length > 0) { const image = tileImages[0]; let imageName = image.getAttribute('source')!; imageName = imageName.replace(/\\/g, '/'); tileset.imageName = imageName; tileset.imageSize.width = parseFloat(image.getAttribute('width')!) || 0; tileset.imageSize.height = parseFloat(image.getAttribute('height')!) || 0; tileset._tileSize.width = tileset.imageSize.width; tileset._tileSize.height = tileset.imageSize.height; tileset.sourceImage = this._spriteFrameMap![imageName]; if (!tileset.sourceImage) { const nameWithPostfix = TMXMapInfo.getNameWithPostfix(imageName); tileset.imageName = nameWithPostfix; tileset.sourceImage = this._spriteFrameMap![nameWithPostfix]; if (!tileset.sourceImage) { const shortName = TMXMapInfo.getShortName(imageName); tileset.imageName = shortName; tileset.sourceImage = this._spriteFrameMap![shortName]; if (!tileset.sourceImage) { errorID(7221, imageName); console.warn(`Please try asset type of ${imageName} to 'sprite-frame'`); } } } tileset.firstGid = ((this.parentGID as unknown as number) & TileFlag.FLIPPED_MASK) as unknown as GID; } const pid = ((TileFlag.FLIPPED_MASK & this.parentGID as unknown as number) >>> 0) as unknown as GID; this._tileProperties.set(pid, getPropertyList(tile)); const animations = tile.getElementsByTagName('animation'); if (animations && animations.length > 0) { const animation = animations[0]; const framesData = animation.getElementsByTagName('frame'); const animationProp: TiledAnimation = { frames: [], dt: 0, frameIdx: 0 }; this._tileAnimations.set(pid, animationProp); const frames = animationProp.frames; for (let frameIdx = 0; frameIdx < framesData.length; frameIdx++) { const frame = framesData[frameIdx]; const tileid = fgid + (parseInt(frame.getAttribute('tileid')!) || 0); const duration = parseFloat(frame.getAttribute('duration')!) || 0; frames.push({ tileid: tileid as unknown as GID, duration: duration / 1000, grid: null }); } } } } } // PARSE <layer> & <objectgroup> in order const childNodes = map.childNodes; for (i = 0; i < childNodes.length; i++) { const childNode = childNodes[i]; if (this._shouldIgnoreNode(childNode)) { continue; } if (childNode.nodeName === 'imagelayer') { const imageLayer = this._parseImageLayer(childNode as Element); if (imageLayer) { this.setImageLayers(imageLayer); } } if (childNode.nodeName === 'layer') { const layer = this._parseLayer(childNode as Element); this.setLayers(layer!); } if (childNode.nodeName === 'objectgroup') { const objectGroup = this._parseObjectGroup(childNode as Element); this.setObjectGroups(objectGroup); } } return map; } protected _shouldIgnoreNode (node: ChildNode): boolean { return node.nodeType === 3 // text || node.nodeType === 8 // comment || node.nodeType === 4; // cdata } protected _parseImageLayer (selLayer: Element) { const datas = selLayer.getElementsByTagName('image'); if (!datas || datas.length === 0) return null; const imageLayer = new TMXImageLayerInfo(); imageLayer.name = selLayer.getAttribute('name')!; imageLayer.offset.x = parseFloat(selLayer.getAttribute('offsetx')!) || 0; imageLayer.offset.y = parseFloat(selLayer.getAttribute('offsety')!) || 0; const visible = selLayer.getAttribute('visible'); imageLayer.visible = !(visible === '0'); const opacity = selLayer.getAttribute('opacity'); imageLayer.opacity = opacity ? Math.round(255 * parseFloat(opacity)) : 255; const tintColor = selLayer.getAttribute('tintcolor'); imageLayer.tintColor = tintColor ? strToColor(tintColor) : null; const data = datas[0]; const source = data.getAttribute('source'); imageLayer.sourceImage = this._imageLayerSPF![source!]; imageLayer.width = parseInt(data.getAttribute('width')!) || 0; imageLayer.height = parseInt(data.getAttribute('height')!) || 0; imageLayer.trans = strToColor(data.getAttribute('trans')!); if (!imageLayer.sourceImage) { errorID(7221, source); console.warn(`Please try asset type of ${source} to 'sprite-frame'`); return null; } return imageLayer; } protected _parseLayer (selLayer: Element) { const data = selLayer.getElementsByTagName('data')[0]; const layer = new TMXLayerInfo(); layer.name = selLayer.getAttribute('name')!; const layerSize = new Size(0, 0); layerSize.width = parseFloat(selLayer.getAttribute('width')!); layerSize.height = parseFloat(selLayer.getAttribute('height')!); layer.layerSize = layerSize; const visible = selLayer.getAttribute('visible'); layer.visible = !(visible === '0'); const opacity = selLayer.getAttribute('opacity'); if (opacity) layer.opacity = Math.round(255 * parseFloat(opacity)); else layer.opacity = 255; layer.offset = new Vec2(parseFloat(selLayer.getAttribute('offsetx')!) || 0, parseFloat(selLayer.getAttribute('offsety')!) || 0); const tintColor = selLayer.getAttribute('tintcolor'); layer.tintColor = tintColor ? strToColor(tintColor) : null; let nodeValue = ''; for (let j = 0; j < data.childNodes.length; j++) { nodeValue += data.childNodes[j].nodeValue; } nodeValue = nodeValue.trim(); // Unpack the tilemap data const compression = data.getAttribute('compression'); const encoding = data.getAttribute('encoding'); if (compression && compression !== 'gzip' && compression !== 'zlib') { logID(7218); return null; } let tiles; switch (compression) { case 'gzip': tiles = codec.unzipBase64AsArray(nodeValue, 4); break; case 'zlib': { const inflator = new zlib.Inflate(codec.Base64.decodeAsArray(nodeValue, 1)); tiles = uint8ArrayToUint32Array(inflator.decompress()); break; } case null: case '': // Uncompressed if (encoding === 'base64') tiles = codec.Base64.decodeAsArray(nodeValue, 4); else if (encoding === 'csv') { tiles = []; const csvTiles = nodeValue.split(','); for (let csvIdx = 0; csvIdx < csvTiles.length; csvIdx++) tiles.push(parseInt(csvTiles[csvIdx])); } else { // XML format const selDataTiles = data.getElementsByTagName('tile'); tiles = []; for (let xmlIdx = 0; xmlIdx < selDataTiles.length; xmlIdx++) tiles.push(parseInt(selDataTiles[xmlIdx].getAttribute('gid')!)); } break; default: if (this.layerAttrs === TMXLayerInfo.ATTRIB_NONE) logID(7219); break; } if (tiles) { layer.tiles = new Uint32Array(tiles); } // The parent element is the last layer layer.properties = getPropertyList(selLayer); return layer; } protected _parseObjectGroup (selGroup: Element) { const objectGroup = new TMXObjectGroupInfo(); objectGroup.name = selGroup.getAttribute('name') || ''; objectGroup.offset = new Vec2(parseFloat(selGroup.getAttribute('offsetx')!), parseFloat(selGroup.getAttribute('offsety')!)); const opacity = selGroup.getAttribute('opacity'); if (opacity) objectGroup.opacity = Math.round(255 * parseFloat(opacity)); else objectGroup.opacity = 255; const tintColor = selGroup.getAttribute('tintcolor'); objectGroup.tintColor = tintColor ? strToColor(tintColor) : null; const visible = selGroup.getAttribute('visible'); if (visible && parseInt(visible) === 0) objectGroup.visible = false; const color = selGroup.getAttribute('color'); if (color) objectGroup.color.fromHEX(color); const draworder = selGroup.getAttribute('draworder'); if (draworder) objectGroup.draworder = draworder as any; // set the properties to the group objectGroup.setProperties(getPropertyList(selGroup)); const objects = selGroup.getElementsByTagName('object'); if (objects) { for (let j = 0; j < objects.length; j++) { const selObj = objects[j]; // The value for "type" was blank or not a valid class name // Create an instance of TMXObjectInfo to store the object and its properties const objectProp: TMXObject = {} as any; // Set the id of the object objectProp.id = selObj.getAttribute('id') || j; // Set the name of the object to the value for "name" objectProp.name = selObj.getAttribute('name') || ''; // Assign all the attributes as key/name pairs in the properties dictionary objectProp.width = parseFloat(selObj.getAttribute('width')!) || 0; objectProp.height = parseFloat(selObj.getAttribute('height')!) || 0; objectProp.x = parseFloat(selObj.getAttribute('x')!) || 0; objectProp.y = parseFloat(selObj.getAttribute('y')!) || 0; objectProp.rotation = parseFloat(selObj.getAttribute('rotation')!) || 0; getPropertyList(selObj, objectProp as any); // visible const visibleAttr = selObj.getAttribute('visible'); objectProp.visible = !(visibleAttr && parseInt(visibleAttr) === 0); // text const texts = selObj.getElementsByTagName('text'); if (texts && texts.length > 0) { const text = texts[0]; objectProp.type = TMXObjectType.TEXT; objectProp.wrap = text.getAttribute('wrap') === '1'; objectProp.color = strToColor(text.getAttribute('color')!); objectProp.halign = strToHAlign(text.getAttribute('halign')); objectProp.valign = strToVAlign(text.getAttribute('valign')); objectProp.pixelsize = parseInt(text.getAttribute('pixelsize')!) || 16; objectProp.text = text.childNodes[0].nodeValue!; } // image const gid = selObj.getAttribute('gid'); if (gid) { objectProp.gid = parseInt(gid) as any; objectProp.type = TMXObjectType.IMAGE; } // ellipse const ellipse = selObj.getElementsByTagName('ellipse'); if (ellipse && ellipse.length > 0) { objectProp.type = TMXObjectType.ELLIPSE; } // polygon const polygonProps = selObj.getElementsByTagName('polygon'); if (polygonProps && polygonProps.length > 0) { objectProp.type = TMXObjectType.POLYGON; const selPgPointStr = polygonProps[0].getAttribute('points'); if (selPgPointStr) objectProp.points = this._parsePointsString(selPgPointStr)!; } // polyline const polylineProps = selObj.getElementsByTagName('polyline'); if (polylineProps && polylineProps.length > 0) { objectProp.type = TMXObjectType.POLYLINE; const selPlPointStr = polylineProps[0].getAttribute('points'); if (selPlPointStr) objectProp.polylinePoints = this._parsePointsString(selPlPointStr)!; } if (!objectProp.type) { objectProp.type = TMXObjectType.RECT; } // Add the object to the objectGroup objectGroup.objects.push(objectProp); } if (draworder !== 'index') { objectGroup.objects.sort((a, b) => a.y - b.y); } } return objectGroup; } protected _parsePointsString (pointsString?: string) { if (!pointsString) return null; const points: { x: number, y: number }[] = []; const pointsStr = pointsString.split(' '); for (let i = 0; i < pointsStr.length; i++) { const selPointStr = pointsStr[i].split(','); points.push({ x: parseFloat(selPointStr[0]), y: parseFloat(selPointStr[1]) }); } return points; } /** * Sets the tile animations. * @return {Object} */ setTileAnimations (animations: TiledAnimationType) { this._tileAnimations = animations; } /** * Gets the tile animations. * @return {Object} */ getTileAnimations (): TiledAnimationType { return this._tileAnimations; } /** * Gets the tile properties. * @return {Object} */ getTileProperties () { return this._tileProperties; } /** * Set the tile properties. * @param {Object} tileProperties */ setTileProperties (tileProperties: Map<GID, PropertiesInfo>) { this._tileProperties = tileProperties; } /** * Gets the currentString * @return {String} */ getCurrentString () { return this.currentString; } /** * Set the currentString * @param {String} currentString */ setCurrentString (currentString: string) { this.currentString = currentString; } static getNameWithPostfix (name: string) { name = name.replace(/\\/g, '/'); const slashIndex = name.lastIndexOf('/') + 1; const strLen = name.length; return name.substring(slashIndex, strLen); } static getShortName (name: string) { name = name.replace(/\\/g, '/'); const slashIndex = name.lastIndexOf('/') + 1; let dotIndex = name.lastIndexOf('.'); dotIndex = dotIndex < 0 ? name.length : dotIndex; return name.substring(slashIndex, dotIndex); } }
the_stack
import React, { MutableRefObject, useEffect, useRef, useState } from 'react'; import { BoxProps, CylinderProps, useRaycastVehicle } from '@react-three/cannon'; import * as THREE from 'three'; import { DebouncedFunc } from 'lodash'; import { useFrame } from '@react-three/fiber'; import { RootState } from '@react-three/fiber/dist/declarations/src/core/store'; import throttle from 'lodash/throttle'; import Chassis from './Chassis'; import Wheel from './Wheel'; import { CHASSIS_BACK_WHEEL_SHIFT, CHASSIS_BASE_COLOR, CHASSIS_FRONT_WHEEL_SHIFT, CHASSIS_GROUND_CLEARANCE, CHASSIS_RELATIVE_POSITION, CHASSIS_WHEEL_WIDTH, SENSORS_NUM, WHEEL_CUSTOM_SLIDING_ROTATION_SPEED, WHEEL_DAMPING_COMPRESSION, WHEEL_DAMPING_RELAXATION, WHEEL_FRICTION_SLIP, WHEEL_MAX_SUSPENSION_FORCE, WHEEL_MAX_SUSPENSION_TRAVEL, WHEEL_RADIUS, WHEEL_ROLL_INFLUENCE, WHEEL_SUSPENSION_REST_LENGTH, WHEEL_SUSPENSION_STIFFNESS } from './constants'; import { CarMetaData, CarType, RaycastVehiclePublicApi, SensorValuesType, userCarUUID, WheelInfoOptions, } from '../types/car'; import { ON_MOVE_THROTTLE_TIMEOUT, ON_UPDATE_LABEL_THROTTLE_TIMEOUT } from '../constants/performance'; import { formatLossValue } from '../../evolution/utils/evolution'; import { RectanglePoints, ThreeRectanglePoints } from '../../../types/vectors'; import { carLoss as getCarLoss } from '../../../libs/carGenetic'; import { LOSS_VALUE_BAD_THRESHOLD, LOSS_VALUE_GOOD_THRESHOLD } from '../../evolution/constants/evolution'; import { PARKING_SPOT_POINTS } from '../constants/parking'; export type OnCarReadyArgs = { api: RaycastVehiclePublicApi, chassis: THREE.Object3D, wheelsNum: number, }; type CarProps = { uuid: userCarUUID, bodyProps: BoxProps, wheelRadius?: number, wireframe?: boolean, styled?: boolean, movable?: boolean, withSensors?: boolean, withLabel?: boolean, visibleSensors?: boolean, baseColor?: string, onCollide?: (carMetaData: CarMetaData, event: any) => void, onSensors?: (sensors: SensorValuesType) => void, onMove?: (wheelsPositions: RectanglePoints) => void, collisionFilterGroup?: number, collisionFilterMask?: number, onCarReady?: (args: OnCarReadyArgs) => void, onCarDestroy?: () => void, car?: CarType, performanceBoost?: boolean, } const flWheelIndex = 0; const frWheelIndex = 1; const blWheelIndex = 2; const brWheelIndex = 3; function Car(props: CarProps) { const { uuid, wheelRadius = WHEEL_RADIUS, wireframe = false, withLabel = false, styled = true, withSensors = false, visibleSensors = false, movable = false, baseColor = CHASSIS_BASE_COLOR, collisionFilterGroup, collisionFilterMask, bodyProps = {}, onCollide = () => {}, onCarReady = () => {}, onCarDestroy = () => {}, onSensors = () => {}, onMove = () => {}, car = { licencePlate: '', generationIndex: 0, genomeIndex: 0 }, performanceBoost = false, } = props; const chassis = useRef<THREE.Object3D | undefined>(); const apiRef = useRef<RaycastVehiclePublicApi | undefined>(); const wheelsRef = useRef<MutableRefObject<THREE.Object3D | undefined>[]>([]); const wheelsPositionRef = useRef<ThreeRectanglePoints>({ fl: new THREE.Vector3(), fr: new THREE.Vector3(), bl: new THREE.Vector3(), br: new THREE.Vector3(), }); const [carLoss, setCarLoss] = useState<number | null>(null); const onUpdateLabelThrottledRef = useRef<DebouncedFunc<(...args: any[]) => any> | null>(null); const onMoveThrottledRef = useRef<DebouncedFunc<(...args: any[]) => any> | null>(null); const wheels: MutableRefObject<THREE.Object3D | undefined>[] = []; const wheelInfos: WheelInfoOptions[] = []; const wheelInfo = { isFrontWheel: false, radius: wheelRadius, directionLocal: [0, -1, 0], // Same as Physics gravity. axleLocal: [-1, 0, 0], // wheel rotates around X-axis, invert if wheels rotate the wrong way chassisConnectionPointLocal: [1, 0, 1], suspensionStiffness: WHEEL_SUSPENSION_STIFFNESS, suspensionRestLength: WHEEL_SUSPENSION_REST_LENGTH, maxSuspensionForce: WHEEL_MAX_SUSPENSION_FORCE, maxSuspensionTravel: WHEEL_MAX_SUSPENSION_TRAVEL, dampingRelaxation: WHEEL_DAMPING_RELAXATION, dampingCompression: WHEEL_DAMPING_COMPRESSION, frictionSlip: WHEEL_FRICTION_SLIP, rollInfluence: WHEEL_ROLL_INFLUENCE, useCustomSlidingRotationalSpeed: true, customSlidingRotationalSpeed: WHEEL_CUSTOM_SLIDING_ROTATION_SPEED, }; // FrontLeft [-X, Y, Z]. const flWheel = useRef<THREE.Object3D | undefined>(); const flWheelInfo = { ...wheelInfo, isFrontWheel: true, chassisConnectionPointLocal: [ -CHASSIS_WHEEL_WIDTH / 2, CHASSIS_GROUND_CLEARANCE, CHASSIS_FRONT_WHEEL_SHIFT, ], }; // FrontRight [X, Y, Z]. const frWheel = useRef<THREE.Object3D | undefined>(); const frWheelInfo = { ...wheelInfo, isFrontWheel: true, chassisConnectionPointLocal: [ CHASSIS_WHEEL_WIDTH / 2, CHASSIS_GROUND_CLEARANCE, CHASSIS_FRONT_WHEEL_SHIFT ], }; // BackLeft [-X, Y, -Z]. const blWheel = useRef<THREE.Object3D | undefined>(); const blWheelInfo = { ...wheelInfo, isFrontWheel: false, chassisConnectionPointLocal: [ -CHASSIS_WHEEL_WIDTH / 2, CHASSIS_GROUND_CLEARANCE, CHASSIS_BACK_WHEEL_SHIFT, ], }; // BackRight [X, Y, -Z]. const brWheel = useRef<THREE.Object3D | undefined>(); const brWheelInfo = { ...wheelInfo, isFrontWheel: false, chassisConnectionPointLocal: [ CHASSIS_WHEEL_WIDTH / 2, CHASSIS_GROUND_CLEARANCE, CHASSIS_BACK_WHEEL_SHIFT, ], }; wheels[flWheelIndex] = flWheel; wheels[frWheelIndex] = frWheel; wheels[blWheelIndex] = blWheel; wheels[brWheelIndex] = brWheel; wheelInfos[flWheelIndex] = flWheelInfo; wheelInfos[frWheelIndex] = frWheelInfo; wheelInfos[blWheelIndex] = blWheelInfo; wheelInfos[brWheelIndex] = brWheelInfo; const isSensorObstacle = !movable; const [vehicle, vehicleAPI] = useRaycastVehicle(() => ({ chassisBody: chassis, wheels, wheelInfos, indexForwardAxis: 2, indexRightAxis: 0, indexUpAxis: 1, })); const wheelMetaData: CarMetaData = { uuid: 'wheel', type: 'wheel', isSensorObstacle, }; const wheelBodyProps: CylinderProps = { position: bodyProps.position, userData: wheelMetaData, }; const carMetaData: CarMetaData = { uuid, type: 'chassis', isSensorObstacle, }; apiRef.current = vehicleAPI; wheelsRef.current = wheels; const onUnmount = () => { if (onUpdateLabelThrottledRef.current) { onUpdateLabelThrottledRef.current.cancel(); } if (onMoveThrottledRef.current) { onMoveThrottledRef.current.cancel(); } onCarDestroy(); }; useEffect(() => { if (!apiRef.current || !chassis.current) { return onUnmount; } onCarReady({ api: apiRef.current, chassis: chassis.current, wheelsNum: wheelsRef.current.length, }); return onUnmount; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); if (!onMoveThrottledRef.current) { onMoveThrottledRef.current = throttle(onMove, ON_MOVE_THROTTLE_TIMEOUT, { leading: true, trailing: true, }); } // @TODO: Move the logic of label content population to the evolution components. // Car shouldn't know about the evolution loss function. const onUpdateLabel = (wheelsPositions: RectanglePoints) => { const loss = getCarLoss({ wheelsPosition: wheelsPositions, parkingLotCorners: PARKING_SPOT_POINTS, }); setCarLoss(loss); }; if (!onUpdateLabelThrottledRef.current) { onUpdateLabelThrottledRef.current = throttle(onUpdateLabel, ON_UPDATE_LABEL_THROTTLE_TIMEOUT, { leading: false, trailing: true, }); } useFrame((state: RootState, delta: number) => { if (!wheels || wheels.length !== 4) { return; } if ( !wheels[flWheelIndex].current || !wheels[frWheelIndex].current || !wheels[blWheelIndex].current || !wheels[brWheelIndex].current ) { return; } // @ts-ignore wheels[flWheelIndex].current.getWorldPosition(wheelsPositionRef.current.fr); // @ts-ignore wheels[frWheelIndex].current.getWorldPosition(wheelsPositionRef.current.fl); // @ts-ignore wheels[blWheelIndex].current.getWorldPosition(wheelsPositionRef.current.br); // @ts-ignore wheels[brWheelIndex].current.getWorldPosition(wheelsPositionRef.current.bl); const {fl, fr, bl, br} = wheelsPositionRef.current; const wheelPositions: RectanglePoints = { fl: fl.toArray(), fr: fr.toArray(), bl: bl.toArray(), br: br.toArray(), }; if (onMoveThrottledRef.current) { onMoveThrottledRef.current(wheelPositions); } // @TODO: Move the logic of label content population to the evolution components. // Car shouldn't know about the evolution loss function. if (withLabel && onUpdateLabelThrottledRef.current) { onUpdateLabelThrottledRef.current(wheelPositions); } }); let distanceColor = 'black'; if (carLoss !== null) { if (carLoss <= LOSS_VALUE_GOOD_THRESHOLD) { distanceColor = 'limegreen'; } else if (carLoss <= LOSS_VALUE_BAD_THRESHOLD) { distanceColor = 'orange'; } else { distanceColor = 'red'; } } const label = withLabel ? ( <span> Loss: {' '} <span style={{color: distanceColor, fontWeight: 'bold'}}> {formatLossValue(carLoss)} </span> </span> ) : null; return ( <group ref={vehicle}> <Chassis ref={chassis} sensorsNum={car.sensorsNum || SENSORS_NUM} chassisPosition={CHASSIS_RELATIVE_POSITION} styled={styled} wireframe={wireframe} movable={movable} label={label} withSensors={withSensors} visibleSensors={visibleSensors} baseColor={baseColor} bodyProps={{ ...bodyProps }} onCollide={(event) => onCollide(carMetaData, event)} onSensors={onSensors} userData={carMetaData} collisionFilterGroup={collisionFilterGroup} collisionFilterMask={collisionFilterMask} performanceBoost={performanceBoost} /> <Wheel ref={flWheel} radius={wheelRadius} bodyProps={wheelBodyProps} styled={styled} wireframe={wireframe} baseColor={baseColor} performanceBoost={performanceBoost} isLeft /> <Wheel ref={frWheel} radius={wheelRadius} bodyProps={wheelBodyProps} styled={styled} wireframe={wireframe} baseColor={baseColor} performanceBoost={performanceBoost} /> <Wheel ref={blWheel} radius={wheelRadius} bodyProps={wheelBodyProps} styled={styled} wireframe={wireframe} baseColor={baseColor} performanceBoost={performanceBoost} isLeft /> <Wheel ref={brWheel} radius={wheelRadius} bodyProps={wheelBodyProps} styled={styled} wireframe={wireframe} baseColor={baseColor} performanceBoost={performanceBoost} /> </group> ) } export default Car;
the_stack
import { Component } from "../component"; import { defaultRuntimeFeatures, getPrismClient, IRuntimeFeatures, treeShakeBundle } from "./prism-client"; import { Module } from "../chef/javascript/components/module"; import { Stylesheet } from "../chef/css/stylesheet"; import { IRenderSettings, ModuleFormat, ScriptLanguages } from "../chef/helpers"; import { IFinalPrismSettings, IPrismSettings, makePrismSettings } from "../settings"; import { fileBundle } from "../bundled-files"; import { registerFSWriteCallback, registerFSReadCallback, __fileSystemReadCallback, __fileSystemWriteCallback } from "../filesystem"; import { join, basename } from "path"; import { ExportStatement, ImportStatement } from "../chef/javascript/components/statements/import-export"; import { UseStatement } from "../chef/rust/statements/use"; /** * Component cannot import another component as there single source. Use `compileComponentFromFSMap` * for multiple components * @param componentSource * @param partialSettings */ export function compileSingleComponentFromString( componentSource: string, partialSettings: Partial<IPrismSettings> = {} ): Map<string, string> { if (typeof componentSource !== "string") throw Error("compileSingleComponentFromString requires string"); if (typeof partialSettings.outputPath === "undefined") { partialSettings.outputPath = ""; } const outputMap = new Map(); // swap callbacks const fileSystemReadCallback = __fileSystemReadCallback; const fileSystemWriteCallback = __fileSystemWriteCallback; registerFSReadCallback(filename => { if (filename === "/index.prism" || filename === "\\index.prism" || filename === "index.prism") { return componentSource; } else { throw Error(`Cannot read path '${filename}'`); } }); registerFSWriteCallback((filename, content) => { outputMap.set(filename, content); }); compileComponent("", partialSettings); // replace callbacks registerFSReadCallback(fileSystemReadCallback); registerFSWriteCallback(fileSystemWriteCallback); return outputMap; } export function compileComponentFromFSMap( componentSourceMap: Map<string, string>, partialSettings: Partial<IPrismSettings> = {} ): Map<string, string> { if (!(componentSourceMap instanceof Map)) throw Error("compileComponentFromFSMap requires Map"); if (typeof partialSettings.outputPath === "undefined") { partialSettings.outputPath = ""; } if (typeof partialSettings.projectPath === "undefined") { partialSettings.projectPath = "."; } // swap callbacks const oldFileSystemReadCallback = __fileSystemReadCallback; const oldFileSystemWriteCallback = __fileSystemWriteCallback; registerFSReadCallback(filename => { if (componentSourceMap.has(filename)) { return componentSourceMap.get(filename)!; } else { throw Error(`Cannot read path '${filename}'`); } }); const outputMap = new Map(); registerFSWriteCallback((filename, content) => { outputMap.set(filename, content); }); compileComponent("", partialSettings); // replace callbacks registerFSReadCallback(oldFileSystemReadCallback); registerFSWriteCallback(oldFileSystemWriteCallback); return outputMap; } export function compileComponentFromFSObject( componentSourceObject: Record<string, string>, partialSettings: Partial<IPrismSettings> = {} ): Map<string, string> { if (typeof partialSettings.outputPath === "undefined") { partialSettings.outputPath = ""; } if (typeof partialSettings.projectPath === "undefined") { partialSettings.projectPath = "."; } // swap callbacks const oldFileSystemReadCallback = __fileSystemReadCallback; const oldFileSystemWriteCallback = __fileSystemWriteCallback; registerFSReadCallback(filename => { if (filename in componentSourceObject) { return componentSourceObject[filename]; } else { throw Error(`Cannot read path '${filename}'`); } }); const outputMap = new Map(); registerFSWriteCallback((filename, content) => { outputMap.set(filename, content); }); compileComponent("", partialSettings); // replace callbacks registerFSReadCallback(oldFileSystemReadCallback); registerFSWriteCallback(oldFileSystemWriteCallback); return outputMap; } /** * Generate a script for a component. Will also generate imported components down the tree. Unlike * compileApplication does not do all components in src folder and does not generate router * @param projectPath The entry point * @returns Returns the component component name */ export function compileComponent( projectPath: string, partialSettings: Partial<IPrismSettings> = {} ): string { // Clear any previously build components Component.registeredComponents.clear(); // In general components are built for client. Override isomorphic default if (typeof partialSettings.context === "undefined") { partialSettings.context = "client"; } // Component doesn't include routing partialSettings.clientSideRouting = false; const settings: IFinalPrismSettings = makePrismSettings(projectPath, partialSettings); const features: IRuntimeFeatures = { ...defaultRuntimeFeatures, isomorphic: settings.context === "isomorphic" }; if (settings.buildTimings) console.time("Parse component file and its imports"); const component = Component.registerComponent(settings.absoluteComponentPath, settings, features); if (settings.buildTimings) console.timeEnd("Parse component file and its imports"); const clientRenderSettings: Partial<IRenderSettings> = { minify: settings.minify, moduleFormat: ModuleFormat.ESM, comments: settings.comments, scriptLanguage: settings.outputTypeScript ? ScriptLanguages.Typescript : ScriptLanguages.Javascript }; for (const registeredComponent of Component.registeredComponents.values()) { registeredComponent.generateCode(settings); } const outputName: string = basename(settings.absoluteComponentPath); let bundledClientModule: Module; if (settings.bundleOutput) { bundledClientModule = getPrismClient(false); if (settings.minify) { treeShakeBundle(features, bundledClientModule); } bundledClientModule.filename = join(settings.absoluteOutputPath, outputName + ".js"); } else { const prismClient = getPrismClient(false); prismClient.filename = join(settings.absoluteOutputPath, "prism"); prismClient.writeToFile(clientRenderSettings); } const bundledStylesheet = new Stylesheet(join(settings.absoluteOutputPath, outputName + ".css")); let scriptLanguage: ScriptLanguages; switch (settings.backendLanguage) { case "js": scriptLanguage = ScriptLanguages.Javascript; break; case "ts": scriptLanguage = ScriptLanguages.Typescript; break; case "rust": scriptLanguage = ScriptLanguages.Rust; break; default: throw Error(`Unknown script language "${settings.backendLanguage}"`); } const serverRenderSettings: Partial<IRenderSettings> = { scriptLanguage }; // This bundles all the components together into a single client module, single stylesheet if (settings.bundleOutput) { addComponentToBundle(component, bundledClientModule!, bundledStylesheet); } else { for (const [, registeredComponent] of Component.registeredComponents) { registeredComponent.clientModule.writeToFile(clientRenderSettings); if (registeredComponent.stylesheet && !registeredComponent.useShadowDOM) { registeredComponent.stylesheet.writeToFile({ minify: settings.minify }); } if (registeredComponent.serverModule) { registeredComponent.serverModule.writeToFile(serverRenderSettings); } } } if (settings.buildTimings) console.time("Render and write script & style bundle"); if (settings.bundleOutput) { // TODO temporary removing of all imports as it is bundled bundledClientModule!.statements = bundledClientModule!.statements .filter(statement => !(statement instanceof ImportStatement && (settings.includeCSSImports ? !statement.from.endsWith(".css") : true)) ).map(statement => statement instanceof ExportStatement ? statement.exported : statement ); bundledClientModule!.writeToFile(clientRenderSettings); if (bundledStylesheet.rules.length > 0) { bundledStylesheet.writeToFile(clientRenderSettings); } } // Bundle server modules and add util functions if (settings.context === "isomorphic") { const bundledServerModule = Module.fromString(fileBundle.get("server.ts")!, "server.ts"); bundledServerModule.filename = join(settings.absoluteOutputPath, "component.server.js"); for (const [, comp] of Component.registeredComponents) { bundledServerModule.combine(comp.serverModule! as Module); } // TODO temporary removing of all imports as it is bundled if (settings.backendLanguage === "rust") { bundledServerModule!.statements = bundledServerModule!.statements.filter(statement => !(statement instanceof UseStatement) ); } else { bundledServerModule!.statements = bundledServerModule!.statements.filter(statement => !(statement instanceof ImportStatement) ); } bundledServerModule.writeToFile(serverRenderSettings); } if (settings.buildTimings) console.timeEnd("Render and write script & style bundle"); return component.tagName; } /** * Adds components scripts and stylesheet to a given Module and Stylesheet * Recursively adds the imported components * TODO server module * @param component * @param scriptBundle * @param styleBundle */ function addComponentToBundle( component: Component, scriptBundle: Module, styleBundle?: Stylesheet, bundleComponents: Set<Component> = new Set() ): void { scriptBundle.combine(component.clientModule); if (component.stylesheet && !component.useShadowDOM && styleBundle) { styleBundle.combine(component.stylesheet); } for (const [, importedComponent] of component.importedComponents) { // Handles cyclic imports if (bundleComponents.has(importedComponent)) continue; bundleComponents.add(importedComponent); addComponentToBundle(importedComponent, scriptBundle, styleBundle, bundleComponents); } }
the_stack
import { parse, parseType } from 'graphql/language/parser'; import { DirectiveLocation, Kind, Source, TokenKind } from 'graphql/language'; import { invariant } from './utils/misc'; import { getArgumentValues } from 'graphql/execution/values'; import type { DocumentNode, ScalarTypeDefinitionNode, ObjectTypeDefinitionNode, InterfaceTypeDefinitionNode, UnionTypeDefinitionNode, SchemaDefinitionNode, DirectiveDefinitionNode, TypeNode, NamedTypeNode, DirectiveNode, InputValueDefinitionNode, EnumTypeDefinitionNode, InputObjectTypeDefinitionNode, DefinitionNode, ObjectTypeExtensionNode, InputObjectTypeExtensionNode, InterfaceTypeExtensionNode, UnionTypeExtensionNode, EnumTypeExtensionNode, ScalarTypeExtensionNode, FieldDefinitionNode, EnumValueDefinitionNode, ArgumentNode, StringValueNode, Location, } from 'graphql/language/ast'; import deprecate from './utils/deprecate'; import { inspect, keyValMap } from './utils/misc'; import { GraphQLInt, GraphQLFloat, GraphQLString, GraphQLBoolean, GraphQLScalarType, GraphQLID, GraphQLList, GraphQLNonNull, GraphQLEnumType, GraphQLObjectType, GraphQLInputObjectType, GraphQLInterfaceType, GraphQLDirective, GraphQLDeprecatedDirective, GraphQLUnionType, valueFromAST, GraphQLFieldConfigArgumentMap, } from './graphql'; import type { GraphQLType, GraphQLInputType } from './graphql'; import { GraphQLDate, GraphQLBuffer, GraphQLJSON, GraphQLJSONObject } from './type'; import type { InputTypeComposerFieldConfigMap, InputTypeComposerFieldConfigMapDefinition, InputTypeComposerFieldConfig, InputTypeComposerFieldConfigDefinition, InputTypeComposerFieldConfigAsObjectDefinition, } from './InputTypeComposer'; import type { ObjectTypeComposerFieldConfig, ObjectTypeComposerFieldConfigDefinition, ObjectTypeComposerFieldConfigMap, ObjectTypeComposerFieldConfigMapDefinition, ObjectTypeComposerArgumentConfig, ObjectTypeComposerArgumentConfigDefinition, ObjectTypeComposerArgumentConfigMap, ObjectTypeComposerArgumentConfigMapDefinition, ObjectTypeComposerDefinition, } from './ObjectTypeComposer'; import { ObjectTypeComposer } from './ObjectTypeComposer'; import type { SchemaComposer } from './SchemaComposer'; import { InputTypeComposer } from './InputTypeComposer'; import { ScalarTypeComposer } from './ScalarTypeComposer'; import { EnumTypeComposer, EnumTypeComposerValueConfigDefinition, EnumTypeComposerValueConfigMapDefinition, } from './EnumTypeComposer'; import { InterfaceTypeComposer, InterfaceTypeComposerDefinition, InterfaceTypeComposerThunked, } from './InterfaceTypeComposer'; import { UnionTypeComposer } from './UnionTypeComposer'; import { ListComposer } from './ListComposer'; import { NonNullComposer } from './NonNullComposer'; import { ThunkComposer } from './ThunkComposer'; import { Resolver } from './Resolver'; import { TypeStorage } from './TypeStorage'; import type { ThunkWithSchemaComposer, Directive } from './utils/definitions'; import { isFunction, isObject } from './utils/is'; import { AnyTypeComposer, ComposeOutputType, ComposeOutputTypeDefinition, ComposeInputType, ComposeInputTypeDefinition, NamedTypeComposer, isInputTypeDefinitionString, isTypeDefinitionString, isOutputTypeDefinitionString, isInterfaceTypeDefinitionString, isSomeOutputTypeComposer, isSomeInputTypeComposer, isTypeNameString, isEnumTypeDefinitionString, isScalarTypeDefinitionString, isUnionTypeDefinitionString, } from './utils/typeHelpers'; import { parseValueNode } from './utils/definitionNode'; // @ts-ignore for GraphQL 15 and below (in v16 it was removed) import { dedentBlockStringValue } from 'graphql/language/blockString'; /** * Eg. `type Name { field: Int }` */ export type TypeDefinitionString = string; /** * Eg. `Int`, `Int!`, `[Int]` */ export type TypeWrappedString = string; /** * Eg. `Int`, `Float` */ export type TypeNameString = string; export type TypeAsString = TypeDefinitionString | TypeWrappedString | TypeNameString; /** * Type storage and type generator from `Schema Definition Language` (`SDL`). * This is slightly rewritten [buildASTSchema](https://github.com/graphql/graphql-js/blob/master/src/utilities/buildASTSchema.js) * utility from `graphql-js` that allows to create type from a string (SDL). */ export class TypeMapper<TContext = any> { schemaComposer: SchemaComposer<TContext>; constructor(schemaComposer: SchemaComposer<TContext>) { if (!schemaComposer) { throw new Error('TypeMapper must have SchemaComposer instance.'); } this.schemaComposer = schemaComposer; } /* @deprecated 8.0.0 */ static isOutputType(type: unknown): boolean { deprecate("Use `import { isSomeOutputTypeComposer } from './utils/typeHelpers'` instead."); return isSomeOutputTypeComposer(type); } /* @deprecated 8.0.0 */ static isInputType(type: unknown): boolean { deprecate("Use `import { isSomeInputTypeComposer } from './utils/typeHelpers'` instead."); return isSomeInputTypeComposer(type); } /* @deprecated 8.0.0 */ static isTypeNameString(str: string): boolean { deprecate("Use `import { isTypeNameString } from './utils/typeHelpers'` instead."); return isTypeNameString(str); } /* @deprecated 8.0.0 */ static isTypeDefinitionString(str: string): boolean { deprecate("Use `import { isTypeDefinitionString } from './utils/typeHelpers'` instead."); return isTypeDefinitionString(str); } /* @deprecated 8.0.0 */ static isOutputTypeDefinitionString(str: string): boolean { deprecate("Use `import { isOutputTypeDefinitionString } from './utils/typeHelpers'` instead."); return isOutputTypeDefinitionString(str); } /* @deprecated 8.0.0 */ static isInputTypeDefinitionString(str: string): boolean { deprecate("Use `import { isInputTypeDefinitionString } from './utils/typeHelpers'` instead."); return isInputTypeDefinitionString(str); } /* @deprecated 8.0.0 */ static isEnumTypeDefinitionString(str: string): boolean { deprecate("Use `import { isEnumTypeDefinitionString } from './utils/typeHelpers'` instead."); return isEnumTypeDefinitionString(str); } /* @deprecated 8.0.0 */ static isScalarTypeDefinitionString(str: string): boolean { deprecate("Use `import { isScalarTypeDefinitionString } from './utils/typeHelpers'` instead."); return isScalarTypeDefinitionString(str); } /* @deprecated 8.0.0 */ static isInterfaceTypeDefinitionString(str: string): boolean { deprecate( "Use `import { isInterfaceTypeDefinitionString } from './utils/typeHelpers'` instead." ); return isInterfaceTypeDefinitionString(str); } /* @deprecated 8.0.0 */ static isUnionTypeDefinitionString(str: string): boolean { deprecate("Use `import { isUnionTypeDefinitionString } from './utils/typeHelpers'` instead."); return isUnionTypeDefinitionString(str); } convertGraphQLTypeToComposer(type: GraphQLType): AnyTypeComposer<TContext> { if (type instanceof GraphQLObjectType) { return ObjectTypeComposer.create(type, this.schemaComposer); } else if (type instanceof GraphQLInputObjectType) { return InputTypeComposer.create(type, this.schemaComposer); } else if (type instanceof GraphQLScalarType) { return ScalarTypeComposer.create(type, this.schemaComposer); } else if (type instanceof GraphQLEnumType) { return EnumTypeComposer.create(type, this.schemaComposer); } else if (type instanceof GraphQLInterfaceType) { return InterfaceTypeComposer.create(type, this.schemaComposer); } else if (type instanceof GraphQLUnionType) { return UnionTypeComposer.create(type, this.schemaComposer); } else if (type instanceof GraphQLNonNull) { // schema do not store wrapped types return new NonNullComposer(this.convertGraphQLTypeToComposer(type.ofType)); } else if (type instanceof GraphQLList) { // schema do not store wrapped types return new ListComposer(this.convertGraphQLTypeToComposer(type.ofType)); } throw new Error(`Cannot convert to Composer the following value: ${inspect(type)}`); } convertSDLWrappedTypeName(str: TypeWrappedString | TypeNameString): AnyTypeComposer<TContext> { const typeAST: TypeNode = parseType(str); return this.typeFromAST(typeAST); } convertSDLTypeDefinition(str: TypeDefinitionString): NamedTypeComposer<TContext> | void { if (this.schemaComposer.has(str)) { return this.schemaComposer.getAnyTC(str); } const astDocument: DocumentNode = parse(str); if (!astDocument || astDocument.kind !== Kind.DOCUMENT) { throw new Error( 'You should provide correct type syntax. ' + "Eg. convertSDLTypeDefinition('type IntRange { min: Int, max: Int }')" ); } const types = this.parseTypes(astDocument); const type = types[0]; if (type) { this.schemaComposer.set(type.getTypeName(), type); // Also keep type string representation for avoiding duplicates type defs for same strings this.schemaComposer.set(str, type); return type; } return undefined; } convertOutputTypeDefinition( typeDef: ThunkWithSchemaComposer< | ComposeOutputTypeDefinition<any> | ObjectTypeComposerDefinition<any, any> | Readonly<Resolver<any, any>>, SchemaComposer<TContext> >, fieldName: string = '', typeName: string = '' ): ComposeOutputType<TContext> | void { if (typeof typeDef === 'string') { if (isInputTypeDefinitionString(typeDef)) { throw new Error( `Should be OutputType, but got input type definition: ${inspect(typeDef)}'` ); } let tc; if (this.schemaComposer.has(typeDef)) { tc = this.schemaComposer.getAnyTC(typeDef); } else { tc = isTypeDefinitionString(typeDef) ? this.convertSDLTypeDefinition(typeDef) : this.convertSDLWrappedTypeName(typeDef); if (!tc) { throw new Error(`Cannot convert to OutputType the following string: ${inspect(typeDef)}`); } } if (!isSomeOutputTypeComposer(tc)) { throw new Error(`Provided incorrect OutputType: ${inspect(typeDef)}`); } return tc; } else if (isSomeOutputTypeComposer(typeDef)) { return typeDef; } else if (Array.isArray(typeDef)) { if (typeDef.length !== 1) { throw new Error( `Array must have exact one output type definition, but has ${typeDef.length}: ${inspect( typeDef )}` ); } const tc = this.convertOutputTypeDefinition(typeDef[0], fieldName, typeName); if (!tc) { throw new Error(`Cannot construct TypeComposer from ${inspect(typeDef)}`); } return new ListComposer(tc); } else if (isFunction(typeDef)) { return new ThunkComposer(() => { const def = typeDef(this.schemaComposer); const tc = this.convertOutputFieldConfig(def as any, fieldName, typeName).type; if (!isSomeOutputTypeComposer(tc)) { throw new Error(`Provided incorrect OutputType: Function[${inspect(def)}]`); } return tc as any; }); } else if (typeDef instanceof Resolver) { return typeDef.getTypeComposer(); } else if (typeDef instanceof GraphQLList || typeDef instanceof GraphQLNonNull) { const type = this.convertGraphQLTypeToComposer(typeDef); if (isSomeOutputTypeComposer(type)) { return type; } else { throw new Error(`Provided incorrect OutputType: ${inspect(type)}`); } } else if ( typeDef instanceof GraphQLObjectType || typeDef instanceof GraphQLEnumType || typeDef instanceof GraphQLInterfaceType || typeDef instanceof GraphQLUnionType || typeDef instanceof GraphQLScalarType ) { return this.convertGraphQLTypeToComposer(typeDef) as any; } if (typeDef instanceof InputTypeComposer) { throw new Error(`Should be OutputType, but provided InputTypeComposer ${inspect(typeDef)}`); } return undefined; } convertOutputFieldConfig<TSource>( composeFC: | ObjectTypeComposerFieldConfigDefinition<TSource, TContext> | Readonly<Resolver<any, TContext>>, fieldName: string = '', typeName: string = '' ): ObjectTypeComposerFieldConfig<TSource, TContext> { try { if (!composeFC) { throw new Error(`You provide empty output field definition: ${inspect(composeFC)}`); } if (composeFC instanceof Resolver) { return { type: composeFC.type, args: composeFC.getArgs(), resolve: composeFC.getFieldResolver(), description: composeFC.getDescription(), extensions: composeFC.extensions, directives: composeFC.directives || [], projection: composeFC.projection, }; } // convert type when its provided as composeFC const tcFromFC = this.convertOutputTypeDefinition(composeFC as any, fieldName, typeName); if (tcFromFC) { return { type: tcFromFC }; } // convert type when its provided in composeIFC.type if (isObject(composeFC)) { const { type, args, ...rest } = composeFC as any; if (!type) { throw new Error( `Definition object should contain 'type' property: ${inspect(composeFC)}` ); } const tc = this.convertOutputTypeDefinition(type, fieldName, typeName); if (tc) { const fc = { type: tc, args: this.convertArgConfigMap(args || {}, fieldName, typeName), ...rest, } as ObjectTypeComposerFieldConfig<any, any, any>; const deprecatedDirectiveIdx = fc?.directives?.findIndex((d) => d.name === 'deprecated') ?? -1; if (fc.deprecationReason) { if (!fc.directives) fc.directives = []; if (deprecatedDirectiveIdx >= 0) { fc.directives[deprecatedDirectiveIdx].args = { reason: fc.deprecationReason }; } else { fc.directives.push({ name: 'deprecated', args: { reason: fc.deprecationReason } }); } } else if (deprecatedDirectiveIdx >= 0) { fc.deprecationReason = fc?.directives?.[deprecatedDirectiveIdx]?.args?.reason; } return fc; } } throw new Error(`Cannot convert to OutputType the following value: ${inspect(composeFC)}`); } catch (e: any) { e.message = `TypeError[${typeName}.${fieldName}]: ${e.message}`; throw e; } } convertOutputFieldConfigMap<TSource>( composeFields: ObjectTypeComposerFieldConfigMapDefinition<TSource, TContext>, typeName: string = '' ): ObjectTypeComposerFieldConfigMap<TSource, TContext> { const fields: ObjectTypeComposerFieldConfigMap<TSource, TContext> = {}; Object.keys(composeFields).forEach((name) => { fields[name] = this.convertOutputFieldConfig(composeFields[name], name, typeName); }); return fields; } convertArgConfig( composeAC: ObjectTypeComposerArgumentConfigDefinition, argName: string = '', fieldName: string = '', typeName: string = '' ): ObjectTypeComposerArgumentConfig { try { if (!composeAC) { throw new Error(`You provide empty argument config ${inspect(composeAC)}`); } // convert type when its provided as composeAC const tcFromAC = this.convertInputTypeDefinition(composeAC as any); if (tcFromAC) { return { type: tcFromAC }; } // convert type when its provided in composeIFC.type if (isObject(composeAC)) { const { type, ...rest } = composeAC as any; if (!type) { throw new Error( `Definition object should contain 'type' property: ${inspect(composeAC)}'` ); } const tc = this.convertInputTypeDefinition(type); if (tc) { const ac = { type: tc, ...rest, } as ObjectTypeComposerArgumentConfig; const deprecatedDirectiveIdx = ac?.directives?.findIndex((d) => d.name === 'deprecated') ?? -1; if (ac.deprecationReason) { if (!ac.directives) ac.directives = []; if (deprecatedDirectiveIdx >= 0) { ac.directives[deprecatedDirectiveIdx].args = { reason: ac.deprecationReason }; } else { ac.directives.push({ name: 'deprecated', args: { reason: ac.deprecationReason } }); } } else if (deprecatedDirectiveIdx >= 0) { ac.deprecationReason = ac?.directives?.[deprecatedDirectiveIdx]?.args?.reason; } return ac; } } throw new Error(`Cannot convert to InputType the following value: ${inspect(tcFromAC)}`); } catch (e: any) { e.message = `TypeError[${typeName}.${fieldName}.${argName}]: ${e.message}`; throw e; } } convertArgConfigMap( composeArgsConfigMap: ObjectTypeComposerArgumentConfigMapDefinition<any>, fieldName: string = '', typeName: string = '' ): ObjectTypeComposerArgumentConfigMap<any> { const argsConfigMap = {} as ObjectTypeComposerArgumentConfigMap<any>; if (composeArgsConfigMap) { Object.keys(composeArgsConfigMap).forEach((argName) => { argsConfigMap[argName] = this.convertArgConfig( composeArgsConfigMap[argName], argName, fieldName, typeName ); }); } return argsConfigMap; } convertInputTypeDefinition( typeDef: ThunkWithSchemaComposer<ComposeInputTypeDefinition, SchemaComposer<TContext>>, fieldName: string = '', typeName: string = '' ): ComposeInputType | void { if (typeof typeDef === 'string') { if (isOutputTypeDefinitionString(typeDef)) { throw new Error(`Should be InputType, but got output type definition: ${inspect(typeDef)}`); } let tc; if (this.schemaComposer.has(typeDef)) { tc = this.schemaComposer.getAnyTC(typeDef) as any; } else { tc = isTypeDefinitionString(typeDef) ? this.convertSDLTypeDefinition(typeDef) : this.convertSDLWrappedTypeName(typeDef); if (!tc) { throw new Error(`Cannot convert to InputType the following string: ${inspect(typeDef)}`); } } if (!isSomeInputTypeComposer(tc)) { throw new Error(`Provided incorrect InputType: ${inspect(typeDef)}`); } return tc; } else if (isSomeInputTypeComposer(typeDef)) { return typeDef; } else if (Array.isArray(typeDef)) { if (typeDef.length !== 1) { throw new Error( `Array must have exact one input type definition, but has ${typeDef.length}: ${inspect( typeDef )}` ); } const tc = this.convertInputTypeDefinition(typeDef[0], fieldName, typeName); if (!tc) { throw new Error(`Cannot construct TypeComposer from ${inspect(typeDef)}`); } return new ListComposer(tc); } else if (isFunction(typeDef)) { return new ThunkComposer(() => { const def = typeDef(this.schemaComposer); const tc = this.convertInputFieldConfig(def, fieldName, typeName).type; if (!isSomeInputTypeComposer(tc)) { throw new Error(`Provided incorrect InputType: Function[${inspect(def)}]`); } return tc as any; }); } else if (typeDef instanceof GraphQLList || typeDef instanceof GraphQLNonNull) { const type = this.convertGraphQLTypeToComposer(typeDef); if (isSomeInputTypeComposer(type)) { return type; } else { throw new Error(`Provided incorrect InputType: ${inspect(type)}`); } } else if ( typeDef instanceof GraphQLInputObjectType || typeDef instanceof GraphQLScalarType || typeDef instanceof GraphQLEnumType ) { return this.convertGraphQLTypeToComposer(typeDef) as any; } if (typeDef instanceof ObjectTypeComposer) { throw new Error(`Should be InputType, but provided ObjectTypeComposer ${inspect(typeDef)}`); } return undefined; } convertInputFieldConfig( composeIFC: InputTypeComposerFieldConfigDefinition, fieldName: string = '', typeName: string = '' ): InputTypeComposerFieldConfig { try { if (!composeIFC) { throw new Error(`You provide empty input field definition: ${inspect(composeIFC)}`); } // convert type when its provided as composeIFC const tcFromIFC = this.convertInputTypeDefinition(composeIFC as any, fieldName, typeName); if (tcFromIFC) { return { type: tcFromIFC }; } // convert type when its provided in composeIFC.type if (isObject(composeIFC)) { const { type, ...rest } = composeIFC as any; if (!type) { throw new Error( `Definition object should contain 'type' property: ${inspect(composeIFC)}` ); } const tc = this.convertInputTypeDefinition(type, fieldName, typeName); if (tc) { const fc = { type: tc, ...rest, } as InputTypeComposerFieldConfig; const deprecatedDirectiveIdx = fc?.directives?.findIndex((d) => d.name === 'deprecated') ?? -1; if (fc.deprecationReason) { if (!fc.directives) fc.directives = []; if (deprecatedDirectiveIdx >= 0) { fc.directives[deprecatedDirectiveIdx].args = { reason: fc.deprecationReason }; } else { fc.directives.push({ name: 'deprecated', args: { reason: fc.deprecationReason } }); } } else if (deprecatedDirectiveIdx >= 0) { fc.deprecationReason = fc?.directives?.[deprecatedDirectiveIdx]?.args?.reason; } return fc; } } throw new Error(`Cannot convert to InputType the following value: ${inspect(composeIFC)}`); } catch (e: any) { e.message = `TypeError[${typeName}.${fieldName}]: ${e.message}`; throw e; } } convertInputFieldConfigMap( composeFields: InputTypeComposerFieldConfigMapDefinition, typeName: string = '' ): InputTypeComposerFieldConfigMap { const fields: InputTypeComposerFieldConfigMap = {}; Object.keys(composeFields).forEach((name) => { fields[name] = this.convertInputFieldConfig(composeFields[name], name, typeName); }); return fields; } convertInterfaceTypeDefinition( typeDef: InterfaceTypeComposerDefinition<any, TContext> ): InterfaceTypeComposerThunked<any, TContext> { if (this.schemaComposer.hasInstance(typeDef, InterfaceTypeComposer)) { return this.schemaComposer.getIFTC(typeDef); } else if (typeof typeDef === 'string') { const tc = isInterfaceTypeDefinitionString(typeDef) ? this.convertSDLTypeDefinition(typeDef) : this.convertSDLWrappedTypeName(typeDef); if (!(tc instanceof InterfaceTypeComposer) && !(tc instanceof ThunkComposer)) { throw new Error( `Cannot convert to InterfaceType the following definition: ${inspect(typeDef)}` ); } return tc; } else if (typeDef instanceof GraphQLInterfaceType) { return new InterfaceTypeComposer(typeDef, this.schemaComposer); } else if (typeDef instanceof InterfaceTypeComposer || typeDef instanceof ThunkComposer) { return typeDef; } else if (isFunction(typeDef)) { return new ThunkComposer( () => this.convertInterfaceTypeDefinition(typeDef(this.schemaComposer)) as any ); } throw new Error( `Cannot convert to InterfaceType the following definition: ${inspect(typeDef)}` ); } parseTypesFromString(str: string): TypeStorage<string, NamedTypeComposer<TContext>> { const source = new Source(str); source.name = 'GraphQL SDL'; const astDocument: DocumentNode = parse(source); if (!astDocument || astDocument.kind !== 'Document') { throw new Error('You should provide correct SDL syntax.'); } const types = this.parseTypes(astDocument); const typeStorage = new TypeStorage(); types.forEach((type) => { typeStorage.set(type.getTypeName(), type); }); return typeStorage; } // ----------------------------------------------- // Internal methods // ----------------------------------------------- parseTypes(astDocument: DocumentNode): Array<NamedTypeComposer<TContext>> { const types = []; for (let i = 0; i < astDocument.definitions.length; i++) { const def = astDocument.definitions[i]; const type = this.makeSchemaDef(def); if (type) { types[i] = type; } } return types; } typeFromAST(typeNode: TypeNode): AnyTypeComposer<TContext> { if (typeNode.kind === Kind.LIST_TYPE) { return new ListComposer(this.typeFromAST(typeNode.type)); } else if (typeNode.kind === Kind.NON_NULL_TYPE) { return new NonNullComposer(this.typeFromAST(typeNode.type)); } invariant(typeNode.kind === Kind.NAMED_TYPE, `Must be a named type for ${inspect(typeNode)}.`); const typeName = typeNode.name.value; if (this.schemaComposer.has(typeName)) { return this.schemaComposer.get(typeName); } const st = this.getBuiltInType(typeName); if (st) return st; return new ThunkComposer(() => { return this.schemaComposer.get(typeName); }, typeName); } typeFromASTInput(typeNode: TypeNode): ComposeInputType { const tc = this.typeFromAST(typeNode); if (!isSomeInputTypeComposer(tc)) { throw new Error(`TypeAST should be for Input types. But received ${inspect(typeNode)}`); } return tc; } typeFromASTOutput(typeNode: TypeNode): ComposeOutputType<TContext> { const tc = this.typeFromAST(typeNode); if (!isSomeOutputTypeComposer(tc)) { throw new Error(`TypeAST should be for Output types. But received ${inspect(typeNode)}`); } return tc; } makeSchemaDef(def: DefinitionNode): NamedTypeComposer<any> | null { if (!def) { throw new Error('def must be defined'); } switch (def.kind) { case Kind.OBJECT_TYPE_DEFINITION: return this.makeTypeDef(def); case Kind.INTERFACE_TYPE_DEFINITION: return this.makeInterfaceDef(def); case Kind.ENUM_TYPE_DEFINITION: return this.makeEnumDef(def); case Kind.UNION_TYPE_DEFINITION: return this.makeUnionDef(def); case Kind.SCALAR_TYPE_DEFINITION: return this.makeScalarDef(def); case Kind.SCHEMA_DEFINITION: this.checkSchemaDef(def); return null; case Kind.DIRECTIVE_DEFINITION: { const directive = this.makeDirectiveDef(def); if (directive) this.schemaComposer.addDirective(directive); return null; } case Kind.INPUT_OBJECT_TYPE_DEFINITION: return this.makeInputObjectDef(def); case Kind.OBJECT_TYPE_EXTENSION: return this.makeExtendTypeDef(def); case Kind.INPUT_OBJECT_TYPE_EXTENSION: return this.makeExtendInputObjectDef(def); case Kind.INTERFACE_TYPE_EXTENSION: return this.makeExtendInterfaceDef(def); case Kind.UNION_TYPE_EXTENSION: return this.makeExtendUnionDef(def); case Kind.ENUM_TYPE_EXTENSION: return this.makeExtendEnumDef(def); case Kind.SCALAR_TYPE_EXTENSION: return this.makeExtendScalarDef(def); default: throw new Error(`Type kind "${def.kind}" not supported.`); } } makeArguments( values?: ReadonlyArray<InputValueDefinitionNode> ): ObjectTypeComposerArgumentConfigMap<any> { if (!values) { return {}; } const result = {} as ObjectTypeComposerArgumentConfigMap<any>; values.forEach((value) => { const key = value.name.value; const typeName = this.getNamedTypeAST(value.type).name.value; const type = this.typeFromASTInput(value.type); const ac = { type, description: getDescription(value), directives: this.parseDirectives(value.directives), deprecationReason: this.getDeprecationReason(value.directives), astNode: value, } as ObjectTypeComposerArgumentConfig; if (value.defaultValue) { if (!this.schemaComposer.has(typeName) && (value?.defaultValue as any)?.value) { ac.defaultValue = (value.defaultValue as any).value; } else { const typeDef = this.schemaComposer.get(typeName); const wrappedType = this.buildWrappedTypeDef(typeDef, value.type); if (isSomeInputTypeComposer(wrappedType)) { ac.defaultValue = valueFromAST( value.defaultValue, wrappedType.getType() as GraphQLInputType ); } else { throw new Error('Non-input type as an argument.'); } } } result[key] = ac; }); return result; } makeFieldDefMap( def: | ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode | ObjectTypeExtensionNode | InterfaceTypeExtensionNode ): ObjectTypeComposerFieldConfigMap<any, any> { if (!def.fields) return {}; return keyValMap( def.fields, (field: FieldDefinitionNode) => field.name.value, (field: FieldDefinitionNode) => { const fc: ObjectTypeComposerFieldConfig<any, any, any> = { type: this.typeFromASTOutput(field.type), description: getDescription(field), args: this.makeArguments(field.arguments), deprecationReason: this.getDeprecationReason(field.directives), astNode: field, directives: this.parseDirectives(field.directives), }; return fc; } ); } makeInputFieldDef( def: InputObjectTypeDefinitionNode | InputObjectTypeExtensionNode ): InputTypeComposerFieldConfigMapDefinition { if (!def.fields) return {}; return keyValMap( def.fields, (field: InputValueDefinitionNode) => field.name.value, (field: InputValueDefinitionNode) => { const fc: InputTypeComposerFieldConfigAsObjectDefinition = { type: this.typeFromASTInput(field.type), description: getDescription(field), deprecationReason: this.getDeprecationReason(field.directives), astNode: field, directives: this.parseDirectives(field.directives), }; if (field.defaultValue) { fc.defaultValue = valueFromAST(field.defaultValue, (fc as any).type.getType()); } return fc; } ); } makeEnumDef(def: EnumTypeDefinitionNode): EnumTypeComposer<TContext> { const tc = this.schemaComposer.createEnumTC({ name: def.name.value, description: getDescription(def), values: this.makeEnumValuesDef(def), directives: this.parseDirectives(def.directives), astNode: def, }); return tc; } makeEnumValuesDef( def: EnumTypeDefinitionNode | EnumTypeExtensionNode ): EnumTypeComposerValueConfigMapDefinition { if (!def.values) return {}; return keyValMap( def.values, (enumValue: EnumValueDefinitionNode) => enumValue.name.value, (enumValue: EnumValueDefinitionNode) => { const ec: EnumTypeComposerValueConfigDefinition = { description: getDescription(enumValue), deprecationReason: this.getDeprecationReason(enumValue.directives), directives: this.parseDirectives(enumValue.directives), }; return ec; } ); } makeInputObjectDef(def: InputObjectTypeDefinitionNode): InputTypeComposer<TContext> { const tc = this.schemaComposer.createInputTC({ name: def.name.value, description: getDescription(def), fields: this.makeInputFieldDef(def), astNode: def, directives: this.parseDirectives(def.directives), }); return tc; } makeDirectiveDef(def: DirectiveDefinitionNode): GraphQLDirective { const locations = def.locations.map(({ value }) => value) as DirectiveLocation[]; const args = {} as GraphQLFieldConfigArgumentMap; (def.arguments || []).forEach((value) => { const key = value.name.value; let val; const wrappedType = this.typeFromAST(value.type); if (isSomeInputTypeComposer(wrappedType)) { val = { type: wrappedType.getType(), description: getDescription(value), defaultValue: valueFromAST(value.defaultValue, wrappedType.getType() as GraphQLInputType), }; } else { throw new Error('Non-input type as an argument.'); } args[key] = val; }); return new GraphQLDirective({ name: def.name.value, description: getDescription(def), locations, args, astNode: def, }); } getBuiltInType(name: string): ScalarTypeComposer<TContext> | undefined { let type: GraphQLScalarType | undefined; switch (name) { case 'String': type = GraphQLString; break; case 'Float': type = GraphQLFloat; break; case 'Int': type = GraphQLInt; break; case 'Boolean': type = GraphQLBoolean; break; case 'ID': type = GraphQLID; break; case 'JSON': type = GraphQLJSON; break; case 'JSONObject': type = GraphQLJSONObject; break; case 'Date': type = GraphQLDate; break; case 'Buffer': type = GraphQLBuffer; break; default: type = undefined; break; } if (type) { return this.schemaComposer.createScalarTC(type); } return undefined; } makeScalarDef(def: ScalarTypeDefinitionNode): ScalarTypeComposer<TContext> { let tc: ScalarTypeComposer<TContext> | undefined; const stc = this.getBuiltInType(def.name.value); if (stc) { tc = stc; } if (!tc) { tc = this.schemaComposer.createScalarTC({ name: def.name.value, description: getDescription(def), serialize: (v) => v, astNode: def, }); } if (def.directives) { tc.setDirectives(this.parseDirectives(def.directives)); } return tc; } makeImplementedInterfaces( def: | ObjectTypeDefinitionNode | ObjectTypeExtensionNode | InterfaceTypeDefinitionNode | InterfaceTypeExtensionNode ): Array<InterfaceTypeComposerThunked<any, TContext>> { return (def.interfaces || []).map((iface) => { const name = this.getNamedTypeAST(iface).name.value; if (this.schemaComposer.hasInstance(name, InterfaceTypeComposer)) { return this.schemaComposer.getIFTC(name); } else { return new ThunkComposer(() => this.schemaComposer.getIFTC(name), name); } }); } makeTypeDef(def: ObjectTypeDefinitionNode): ObjectTypeComposer<any, TContext> { const name = def.name.value; const tc = this.schemaComposer.createObjectTC({ name, description: getDescription(def), fields: this.makeFieldDefMap(def), interfaces: this.makeImplementedInterfaces(def), astNode: def, directives: this.parseDirectives(def.directives), }); return tc; } makeInterfaceDef(def: InterfaceTypeDefinitionNode): InterfaceTypeComposer<any, TContext> { const tc = this.schemaComposer.createInterfaceTC({ name: def.name.value, description: getDescription(def), fields: this.makeFieldDefMap(def), interfaces: this.makeImplementedInterfaces(def), astNode: def, directives: this.parseDirectives(def.directives), }); return tc; } makeUnionDef(def: UnionTypeDefinitionNode): UnionTypeComposer<any, TContext> { const types = def.types; const tc = this.schemaComposer.createUnionTC({ name: def.name.value, description: getDescription(def), types: (types || []).map((ref) => this.getNamedTypeAST(ref).name.value), astNode: def, }); if (def.directives) { tc.setDirectives(this.parseDirectives(def.directives)); } return tc; } checkSchemaDef(def: SchemaDefinitionNode): void { const validNames = { query: 'Query', mutation: 'Mutation', subscription: 'Subscription', }; def.operationTypes.forEach((d) => { if (d.operation) { const validTypeName = validNames[d.operation]; const actualTypeName = d.type.name.value; if (actualTypeName !== validTypeName) { throw new Error( `Incorrect type name '${actualTypeName}' for '${d.operation}'. The valid definition is "schema { ${d.operation}: ${validTypeName} }"` ); } } }); } getNamedTypeAST(typeAST: TypeNode): NamedTypeNode { let namedType = typeAST; while (namedType.kind === Kind.LIST_TYPE || namedType.kind === Kind.NON_NULL_TYPE) { namedType = namedType.type; } return namedType; } buildWrappedTypeDef( innerType: AnyTypeComposer<any>, inputTypeAST: TypeNode ): AnyTypeComposer<TContext> { if (inputTypeAST.kind === Kind.LIST_TYPE) { return new ListComposer(this.buildWrappedTypeDef(innerType, inputTypeAST.type)); } if (inputTypeAST.kind === Kind.NON_NULL_TYPE) { const wrappedType = this.buildWrappedTypeDef(innerType, inputTypeAST.type); return new NonNullComposer(wrappedType); } return innerType; } getDeprecationReason(directives: ReadonlyArray<DirectiveNode> | undefined): string | undefined { const deprecatedAST = directives?.find( (directive) => directive.name.value === GraphQLDeprecatedDirective.name ); if (!deprecatedAST) { return; } const { reason } = getArgumentValues(GraphQLDeprecatedDirective, deprecatedAST) as any; return reason; } parseDirectives(directives: ReadonlyArray<DirectiveNode> | undefined): Array<Directive> { const result = [] as Array<Directive>; if (!directives) return result; directives.forEach((directive) => { const name = directive.name.value; const directiveDef = this.schemaComposer._getDirective(name); const args = directiveDef ? getArgumentValues(directiveDef, directive) : keyValMap( directive.arguments || [], (arg: ArgumentNode) => arg.name.value, (arg: ArgumentNode) => parseValueNode(arg.value) ); result.push({ name, args }); }); return result; } makeExtendTypeDef(def: ObjectTypeExtensionNode): ObjectTypeComposer<any, TContext> { const tc = this.schemaComposer.getOrCreateOTC(def.name.value); tc.addInterfaces(this.makeImplementedInterfaces(def)); tc.addFields(this.makeFieldDefMap(def)); if (def.directives) { tc.setDirectives([...tc.getDirectives(), ...this.parseDirectives(def.directives)]); } return tc; } makeExtendInputObjectDef(def: InputObjectTypeExtensionNode): InputTypeComposer<TContext> { const tc = this.schemaComposer.getOrCreateITC(def.name.value); tc.addFields(this.makeInputFieldDef(def)); if (def.directives) { tc.setDirectives([...tc.getDirectives(), ...this.parseDirectives(def.directives)]); } return tc; } makeExtendInterfaceDef(def: InterfaceTypeExtensionNode): InterfaceTypeComposer<any, TContext> { const tc = this.schemaComposer.getOrCreateIFTC(def.name.value); tc.addFields(this.makeFieldDefMap(def)); if (def.directives) { tc.setDirectives([...tc.getDirectives(), ...this.parseDirectives(def.directives)]); } return tc; } makeExtendUnionDef(def: UnionTypeExtensionNode): UnionTypeComposer<any, TContext> { const types = def.types; const tc = this.schemaComposer.getOrCreateUTC(def.name.value); tc.addTypes((types || []).map((ref) => this.getNamedTypeAST(ref).name.value)); if (def.directives) { tc.setDirectives([...tc.getDirectives(), ...this.parseDirectives(def.directives)]); } return tc; } makeExtendEnumDef(def: EnumTypeExtensionNode): EnumTypeComposer<TContext> { const tc = this.schemaComposer.getOrCreateETC(def.name.value); tc.addFields(this.makeEnumValuesDef(def)); if (def.directives) { tc.setDirectives([...tc.getDirectives(), ...this.parseDirectives(def.directives)]); } return tc; } makeExtendScalarDef(def: ScalarTypeExtensionNode): ScalarTypeComposer<TContext> { const tc = this.schemaComposer.getSTC(def.name.value); if (def.directives) { tc.setDirectives([...tc.getDirectives(), ...this.parseDirectives(def.directives)]); } return tc; } } /** * Given an ast node, returns its string description. * * Accepts options as a second argument: * * - commentDescriptions: * Provide true to use preceding comments as the description. * */ export function getDescription( node: { description?: StringValueNode; loc?: Location }, options?: { commentDescriptions?: boolean } ): string | null | undefined { if (node.description) { return node.description.value; } if (options?.commentDescriptions === true) { const rawValue = getLeadingCommentBlock(node); if (rawValue !== undefined) { if (!dedentBlockStringValue) { // in GraphQL 16 `commentDescriptions` was removed return undefined; } else { // GraphQL 15 and below return dedentBlockStringValue('\n' + rawValue); } } } return undefined; } function getLeadingCommentBlock(node: { description?: StringValueNode; loc?: Location; }): string | null | undefined { const loc = node.loc; if (!loc) { return; } const comments = []; let token = loc.startToken.prev; while ( token != null && token.kind === TokenKind.COMMENT && token.next && token.prev && token.line + 1 === token.next.line && token.line !== token.prev.line ) { const value = String(token.value); comments.push(value); token = token.prev; } return comments.length > 0 ? comments.reverse().join('\n') : undefined; }
the_stack
import {Model} from "../../model" import {LayoutDOM, LayoutDOMView} from "../layouts/layout_dom" import {Styles} from "./styles" import {span} from "core/dom" import {View} from "core/view" import {DOMView} from "core/dom_view" import {build_views, remove_views} from "core/build_views" import * as p from "core/properties" import {isString} from "core/util/types" import {entries} from "core/util/object" import * as styles from "styles/tooltips.css" import {Index as DataIndex, _get_column_value} from "core/util/templating" import {ColumnarDataSource} from "../sources/columnar_data_source" export {Styles} export abstract class DOMNodeView extends DOMView { override model: DOMNode } export namespace DOMNode { export type Attrs = p.AttrsOf<Props> export type Props = Model.Props } export interface DOMNode extends DOMNode.Attrs {} export abstract class DOMNode extends Model { override properties: DOMNode.Props override __view_type__: DOMNodeView static override __module__ = "bokeh.models.dom" constructor(attrs?: Partial<DOMNode.Attrs>) { super(attrs) } } export class TextView extends DOMNodeView { override model: Text override el: globalThis.Text override render(): void { super.render() this.el.textContent = this.model.content } protected override _createElement(): globalThis.Text { return document.createTextNode("") } } export namespace Text { export type Attrs = p.AttrsOf<Props> export type Props = DOMNode.Props & { content: p.Property<string> } } export interface Text extends Text.Attrs {} export class Text extends DOMNode { override properties: Text.Props override __view_type__: TextView constructor(attrs?: Partial<Text.Attrs>) { super(attrs) } static { this.prototype.default_view = TextView this.define<Text.Props>(({String}) => ({ content: [ String, "" ], })) } } export abstract class PlaceholderView extends DOMNodeView { override model: Placeholder static override tag_name = "span" as const abstract update(source: ColumnarDataSource, i: DataIndex, vars: object/*, formatters?: Formatters*/): void } export namespace Placeholder { export type Attrs = p.AttrsOf<Props> export type Props = DOMNode.Props & {} } export interface Placeholder extends Placeholder.Attrs {} export abstract class Placeholder extends DOMNode { override properties: Placeholder.Props override __view_type__: PlaceholderView constructor(attrs?: Partial<Placeholder.Attrs>) { super(attrs) } static { this.define<Placeholder.Props>(({}) => ({})) } } export class IndexView extends PlaceholderView { override model: Index update(_source: ColumnarDataSource, i: DataIndex, _vars: object/*, formatters?: Formatters*/): void { this.el.textContent = i.toString() } } export namespace Index { export type Attrs = p.AttrsOf<Props> export type Props = Placeholder.Props & {} } export interface Index extends Index.Attrs {} export class Index extends Placeholder { override properties: Index.Props override __view_type__: IndexView constructor(attrs?: Partial<Index.Attrs>) { super(attrs) } static { this.prototype.default_view = IndexView this.define<Index.Props>(({}) => ({})) } } export class ValueRefView extends PlaceholderView { override model: ValueRef update(source: ColumnarDataSource, i: DataIndex, _vars: object/*, formatters?: Formatters*/): void { const value = _get_column_value(this.model.field, source, i) const text = value == null ? "???" : `${value}` //.toString() this.el.textContent = text } } export namespace ValueRef { export type Attrs = p.AttrsOf<Props> export type Props = Placeholder.Props & { field: p.Property<string> } } export interface ValueRef extends ValueRef.Attrs {} export class ValueRef extends Placeholder { override properties: ValueRef.Props override __view_type__: ValueRefView constructor(attrs?: Partial<ValueRef.Attrs>) { super(attrs) } static { this.prototype.default_view = ValueRefView this.define<ValueRef.Props>(({String}) => ({ field: [ String ], })) } } export class ColorRefView extends ValueRefView { override model: ColorRef value_el?: HTMLElement swatch_el?: HTMLElement override render(): void { super.render() this.value_el = span() this.swatch_el = span({class: styles.tooltip_color_block}, " ") this.el.appendChild(this.value_el) this.el.appendChild(this.swatch_el) } override update(source: ColumnarDataSource, i: DataIndex, _vars: object/*, formatters?: Formatters*/): void { const value = _get_column_value(this.model.field, source, i) const text = value == null ? "???" : `${value}` //.toString() this.el.textContent = text } } export namespace ColorRef { export type Attrs = p.AttrsOf<Props> export type Props = ValueRef.Props & { hex: p.Property<boolean> swatch: p.Property<boolean> } } export interface ColorRef extends ColorRef.Attrs {} export class ColorRef extends ValueRef { override properties: ColorRef.Props override __view_type__: ColorRefView constructor(attrs?: Partial<ColorRef.Attrs>) { super(attrs) } static { this.prototype.default_view = ColorRefView this.define<ColorRef.Props>(({Boolean}) => ({ hex: [ Boolean, true ], swatch: [ Boolean, true ], })) } } export abstract class DOMElementView extends DOMNodeView { override model: DOMElement override el: HTMLElement child_views: Map<DOMNode | LayoutDOM, DOMNodeView | LayoutDOMView> = new Map() override async lazy_initialize(): Promise<void> { await super.lazy_initialize() const children = this.model.children.filter((obj): obj is DOMNode | LayoutDOM => obj instanceof Model) await build_views(this.child_views, children, {parent: this}) } override render(): void { super.render() const {style} = this.model if (style != null) { /* type IsString<T> = T extends string ? T : never type Key = Exclude<IsString<keyof CSSStyleDeclaration>, "length" | "parentRule" | "getPropertyPriority" | "getPropertyValue" | "item" | "removeProperty" | "setProperty"> //this.el.style[key as Key] = value */ if (style instanceof Styles) { for (const prop of style) { const value = prop.get_value() if (isString(value)) { const name = prop.attr.replace(/_/g, "-") if (this.el.style.hasOwnProperty(name)) { this.el.style.setProperty(name, value as string) } } } } else { for (const [key, value] of entries(style)) { const name = key.replace(/_/g, "-") if (this.el.style.hasOwnProperty(name)) { this.el.style.setProperty(name, value) } } } } for (const child of this.model.children) { if (isString(child)) { const node = document.createTextNode(child) this.el.appendChild(node) } else { const child_view = this.child_views.get(child)! child_view.renderTo(this.el) } } } } export namespace DOMElement { export type Attrs = p.AttrsOf<Props> export type Props = DOMNode.Props & { style: p.Property<Styles | {[key: string]: string} | null> children: p.Property<(string | DOMNode | LayoutDOM)[]> } } export interface DOMElement extends DOMElement.Attrs {} export abstract class DOMElement extends DOMNode { override properties: DOMElement.Props override __view_type__: DOMElementView constructor(attrs?: Partial<DOMElement.Attrs>) { super(attrs) } static { this.define<DOMElement.Props>(({String, Array, Dict, Or, Nullable, Ref}) => ({ style: [ Nullable(Or(Ref(Styles), Dict(String))), null ], children: [ Array(Or(String, Ref(DOMNode), Ref(LayoutDOM))), [] ], })) } } export abstract class ActionView extends View { override model: Action abstract update(source: ColumnarDataSource, i: DataIndex, vars: object/*, formatters?: Formatters*/): void } export namespace Action { export type Attrs = p.AttrsOf<Props> export type Props = Model.Props & {} } export interface Action extends Action.Attrs {} export abstract class Action extends Model { override properties: Action.Props override __view_type__: ActionView static override __module__ = "bokeh.models.dom" constructor(attrs?: Partial<Action.Attrs>) { super(attrs) } static { this.define<Action.Props>(({}) => ({})) } } export class TemplateView extends DOMElementView { override model: Template static override tag_name = "div" as const action_views: Map<Action, ActionView> = new Map() override async lazy_initialize(): Promise<void> { await super.lazy_initialize() await build_views(this.action_views, this.model.actions, {parent: this}) } override remove(): void { remove_views(this.action_views) super.remove() } update(source: ColumnarDataSource, i: DataIndex, vars: object = {}/*, formatters?: Formatters*/): void { function descend(obj: DOMElementView): void { for (const child of obj.child_views.values()) { if (child instanceof PlaceholderView) { child.update(source, i, vars) } else if (child instanceof DOMElementView) { descend(child) } } } descend(this) for (const action of this.action_views.values()) { action.update(source, i, vars) } } } export namespace Template { export type Attrs = p.AttrsOf<Props> export type Props = DOMElement.Props & { actions: p.Property<Action[]> } } export interface Template extends Template.Attrs {} export class Template extends DOMElement { override properties: Template.Props override __view_type__: TemplateView static { this.prototype.default_view = TemplateView this.define<Template.Props>(({Array, Ref}) => ({ actions: [ Array(Ref(Action)), [] ], })) } } export class SpanView extends DOMElementView { override model: Span static override tag_name = "span" as const } export class Span extends DOMElement { override __view_type__: SpanView static { this.prototype.default_view = SpanView } } export class DivView extends DOMElementView { override model: Div static override tag_name = "div" as const } export class Div extends DOMElement { override __view_type__: DivView static { this.prototype.default_view = DivView } } export class TableView extends DOMElementView { override model: Table static override tag_name = "table" as const } export class Table extends DOMElement { override __view_type__: TableView static { this.prototype.default_view = TableView } } export class TableRowView extends DOMElementView { override model: TableRow static override tag_name = "tr" as const } export class TableRow extends DOMElement { override __view_type__: TableRowView static { this.prototype.default_view = TableRowView } } ///// import {RendererGroup} from "../renderers/renderer" import {enumerate} from "core/util/iterator" export class ToggleGroupView extends ActionView { override model: ToggleGroup update(_source: ColumnarDataSource, i: DataIndex, _vars: object/*, formatters?: Formatters*/): void { for (const [group, j] of enumerate(this.model.groups)) { group.visible = i == j } } } export namespace ToggleGroup { export type Attrs = p.AttrsOf<Props> export type Props = Action.Props & { groups: p.Property<RendererGroup[]> } } export interface ToggleGroup extends ToggleGroup.Attrs {} export class ToggleGroup extends Action { override properties: ToggleGroup.Props override __view_type__: ToggleGroupView constructor(attrs?: Partial<ToggleGroup.Attrs>) { super(attrs) } static { this.prototype.default_view = ToggleGroupView this.define<ToggleGroup.Props>(({Array, Ref}) => ({ groups: [ Array(Ref(RendererGroup)), [] ], })) } } /* export namespace X { export type Attrs = p.AttrsOf<Props> export type Props = Y.Props & {} } export interface X extends X.Attrs {} export class X extends Y { override properties: X.Props constructor(attrs?: Partial<X.Attrs>) { super(attrs) } static { this.define<X.Props>(({}) => ({ })) } } */
the_stack
'use strict'; import { IPCMessageReader, IPCMessageWriter, createConnection, IConnection, TextDocumentSyncKind, TextDocuments, TextDocument, Diagnostic, DiagnosticSeverity, InitializeParams, InitializeResult, TextDocumentIdentifier, TextDocumentPositionParams, CompletionItem, CompletionItemKind, RequestType, Position, SignatureHelp, SignatureInformation, ParameterInformation } from 'vscode-languageserver'; import { TreeBuilder } from "./hvy/treeBuilder"; import { FileNode, FileSymbolCache, SymbolType, AccessModifierNode, ClassNode } from "./hvy/nodes"; import { Debug } from './util/Debug'; import { SuggestionBuilder } from './suggestionBuilder'; import { DefinitionProvider } from "./providers/definition"; import Storage from './util/Storage'; import { Files } from "./util/Files"; import { DocumentSymbolProvider } from "./providers/documentSymbol"; import { WorkspaceSymbolProvider } from "./providers/workspaceSymbol"; const util = require('util'); // Glob for file searching const glob = require("glob"); // FileQueue for queuing files so we don't open too many const FileQueue = require('filequeue'); const fq = new FileQueue(200); let connection: IConnection = createConnection(new IPCMessageReader(process), new IPCMessageWriter(process)); let documents: TextDocuments = new TextDocuments(); documents.listen(connection); Debug.SetConnection(connection); let treeBuilder: TreeBuilder = new TreeBuilder(); treeBuilder.SetConnection(connection); let workspaceTree: FileNode[] = []; let cache:Storage = new Storage(); // Prevent garbage collection of essential objects let timer = setInterval(() => { treeBuilder.Ping(); return workspaceTree.length; }, 15000); let workspaceRoot: string; var craneProjectDir: string; let enableCache: boolean = true; connection.onInitialize((params): InitializeResult => { workspaceRoot = params.rootPath; return { capabilities: { textDocumentSync: documents.syncKind, completionProvider: { resolveProvider: true, triggerCharacters: ['.', ':', '$', '>', "\\"] }, definitionProvider: true, documentSymbolProvider: true, workspaceSymbolProvider: true } } }); // The settings interface describe the server relevant settings part interface Settings { languageServerExample: ExampleSettings; } // These are the example settings we defined in the client's package.json // file interface ExampleSettings { maxNumberOfProblems: number; } // hold the maxNumberOfProblems setting let maxNumberOfProblems: number; // The settings have changed. Is send on server activation // as well. connection.onDidChangeConfiguration((change) => { let settings = <Settings>change.settings; maxNumberOfProblems = settings.languageServerExample.maxNumberOfProblems || 100; // Revalidate any open text documents //documents.all().forEach(validateTextDocument); }); // Use this to send a request to the client // https://github.com/Microsoft/vscode/blob/80bd73b5132268f68f624a86a7c3e56d2bbac662/extensions/json/client/src/jsonMain.ts // https://github.com/Microsoft/vscode/blob/580d19ab2e1fd6488c3e515e27fe03dceaefb819/extensions/json/server/src/server.ts //connection.sendRequest() connection.onDidChangeWatchedFiles((change) => { // Monitored files have change in VSCode connection.console.log('We recevied an file change event'); }); // This handler provides the initial list of the completion items. connection.onCompletion((textDocumentPosition: TextDocumentPositionParams): CompletionItem[] => { var toReturn: CompletionItem[] = null; var doc = documents.get(textDocumentPosition.textDocument.uri); try { var suggestionBuilder = new SuggestionBuilder(); suggestionBuilder.prepare(textDocumentPosition, doc, workspaceTree); toReturn = suggestionBuilder.build(); } catch (ex) { let message = ""; if (ex.message) message = ex.message; if (ex.stack) message += " :: STACK TRACE :: " + ex.stack; if (message && message != "") Debug.sendErrorTelemetry(message); Debug.error("Completion error: " + ex.message + "\n" + ex.stack); } return toReturn; }); // This handler resolve additional information for the item selected in // the completion list. connection.onCompletionResolve((item: CompletionItem): CompletionItem => { // TODO -- Add phpDoc info // if (item.data === 1) { // item.detail = 'TypeScript details', // item.documentation = 'TypeScript documentation' // } else if (item.data === 2) { // item.detail = 'JavaScript details', // item.documentation = 'JavaScript documentation' // } return item; }); connection.onDefinition((params, cancellationToken) => { return new Promise((resolve, reject) => { var locations = null; try { let path = Files.getPathFromUri(params.textDocument.uri); let filenode = getFileNodeFromPath(path); let definitionProvider = new DefinitionProvider(params, path, filenode, workspaceTree); locations = definitionProvider.findDefinition(); } catch (ex) { let message = ""; if (ex.message) message = ex.message; if (ex.stack) message += " :: STACK TRACE :: " + ex.stack; if (message && message != "") Debug.sendErrorTelemetry(message); } resolve(locations); }); }); connection.onDocumentSymbol((params, cancellationToken) => { return new Promise((resolve, reject) => { var symbols = null; try { let path = Files.getPathFromUri(params.textDocument.uri); let filenode = getFileNodeFromPath(path); let documentSymbolProvider = new DocumentSymbolProvider(filenode); symbols = documentSymbolProvider.findSymbols(); } catch (ex) { let message = ""; if (ex.message) message = ex.message; if (ex.stack) message += " :: STACK TRACE :: " + ex.stack; if (message && message != "") Debug.sendErrorTelemetry(message); } resolve(symbols); }); }); connection.onWorkspaceSymbol((params, cancellationToken) => { return new Promise((resolve, reject) => { var symbols = null; try { let workspaceSymbolProvider = new WorkspaceSymbolProvider(workspaceTree, params.query); symbols = workspaceSymbolProvider.findSymbols(); } catch (ex) { let message = ""; if (ex.message) message = ex.message; if (ex.stack) message += " :: STACK TRACE :: " + ex.stack; if (message && message != "") Debug.sendErrorTelemetry(message); } resolve(symbols); }); }); var buildObjectTreeForDocument: RequestType<{path:string,text:string}, any, any, any> = new RequestType("buildObjectTreeForDocument"); connection.onRequest(buildObjectTreeForDocument, (requestObj) => { var fileUri = requestObj.path; var text = requestObj.text; treeBuilder.Parse(text, fileUri).then(result => { addToWorkspaceTree(result.tree); // notifyClientOfWorkComplete(); return true; }) .catch(error => { Debug.error("Build request error :\n" + (error.stack ? error.stack : error)); notifyClientOfWorkComplete(); return false; }); }); var deleteFile: RequestType<{path:string}, any, any, any> = new RequestType("deleteFile"); connection.onRequest(deleteFile, (requestObj) => { var node = getFileNodeFromPath(requestObj.path); if (node instanceof FileNode) { removeFromWorkspaceTree(node); } }); var saveTreeCache: RequestType<{ projectDir: string, projectTree: string }, any, any, any> = new RequestType("saveTreeCache"); connection.onRequest(saveTreeCache, request => { saveProjectTree(request.projectDir, request.projectTree).then(saved => { notifyClientOfWorkComplete(); }).catch(error => { Debug.error(util.inspect(error, false, null)); }); }); let docsDoneCount = 0; let refreshProcessing = false; var docsToDo: string[] = []; var stubsToDo: string[] = []; var buildFromFiles: RequestType<{ files: string[], craneRoot: string, projectPath: string, treePath: string, enableCache: boolean, rebuild: boolean }, any, any, any> = new RequestType("buildFromFiles"); connection.onRequest(buildFromFiles, (project) => { if (refreshProcessing) { // Don't reparse if we're in the middle of parsing return; } refreshProcessing = true; if (project.rebuild) { workspaceTree = []; treeBuilder = new TreeBuilder(); } enableCache = project.enableCache; docsToDo = project.files; docsDoneCount = 0; Debug.info("Preparing to parse workspace..."); // Run asynchronously setTimeout(() => { glob(project.craneRoot + '/phpstubs/*/*.php', (err, fileNames) => { // Process the php stubs stubsToDo = fileNames; Debug.info(`Processing ${stubsToDo.length} stubs from ${project.craneRoot}/phpstubs`) Debug.info(`Stub files to process: ${stubsToDo.length}`); processStub().then(data => { Debug.info('Stubs parsing done!'); Debug.info(`Workspace files to process: ${docsToDo.length}`); processWorkspaceFiles(project.projectPath, project.treePath); }).catch(data => { Debug.info('No stubs found!'); Debug.info(`Workspace files to process: ${docsToDo.length}`); processWorkspaceFiles(project.projectPath, project.treePath); }); }); }, 100); }); var buildFromProject: RequestType<{treePath:string, enableCache:boolean}, any, any, any> = new RequestType("buildFromProject"); connection.onRequest(buildFromProject, (data) => { enableCache = data.enableCache; cache.read(data.treePath, (err, data) => { if (err) { Debug.error('Could not read cache file'); Debug.error((util.inspect(err, false, null))); } else { Debug.info('Cache file successfully read'); workspaceTree = data; notifyClientOfWorkComplete(); } }); }); /** * Processes the stub files */ function processStub() { return new Promise((resolve, reject) => { var offset: number = 0; if (stubsToDo.length == 0) { reject(); } stubsToDo.forEach(file => { fq.readFile(file, { encoding: 'utf8' }, (err, data) => { treeBuilder.Parse(data, file).then(result => { addToWorkspaceTree(result.tree); Debug.info(`${offset} Stub Processed: ${file}`); offset++; if (offset == stubsToDo.length) { resolve(); } }).catch(err => { Debug.error(`${offset} Stub Error: ${file}`); Debug.error((util.inspect(err, false, null))); offset++; if (offset == stubsToDo.length) { resolve(); } }); }); }); }); } /** * Processes the users workspace files */ function processWorkspaceFiles(projectPath: string, treePath: string) { docsToDo.forEach(file => { fq.readFile(file, { encoding: 'utf8' }, (err, data) => { treeBuilder.Parse(data, file).then(result => { addToWorkspaceTree(result.tree); docsDoneCount++; connection.sendNotification("fileProcessed", { filename: file, total: docsDoneCount, error: null }); if (docsToDo.length == docsDoneCount) { workspaceProcessed(projectPath, treePath); } }).catch(data => { docsDoneCount++; if (docsToDo.length == docsDoneCount) { workspaceProcessed(projectPath, treePath); } Debug.error(util.inspect(data, false, null)); Debug.error(`Issue processing ${file}`); connection.sendNotification("fileProcessed", { filename: file, total: docsDoneCount, error: util.inspect(data, false, null) }); }); }); }); } function workspaceProcessed(projectPath, treePath) { Debug.info("Workspace files have processed"); saveProjectTree(projectPath, treePath).then(savedTree => { notifyClientOfWorkComplete(); if (savedTree) { Debug.info('Project tree has been saved'); } }).catch(error => { Debug.error(util.inspect(error, false, null)); }); } function addToWorkspaceTree(tree:FileNode) { // Loop through existing filenodes and replace if exists, otherwise add var fileNode = workspaceTree.filter((fileNode) => { return fileNode.path == tree.path; })[0]; var index = workspaceTree.indexOf(fileNode); if (index !== -1) { workspaceTree[index] = tree; } else { workspaceTree.push(tree); } } function removeFromWorkspaceTree(tree: FileNode) { var index: number = workspaceTree.indexOf(tree); if (index > -1) { workspaceTree.splice(index, 1); } } function getClassNodeFromTree(className:string): ClassNode { var toReturn = null; for (var i = 0, l = workspaceTree.length; i < l; i++) { var fileNode = workspaceTree[i]; for (var j = 0, sl = fileNode.classes.length; j < sl; j++) { var classNode = fileNode.classes[j]; if (classNode.name.toLowerCase() == className.toLowerCase()) { toReturn = classNode; } } } return toReturn; } function getTraitNodeFromTree(traitName: string): ClassNode { var toReturn = null; for (var i = 0, l = workspaceTree.length; i < l; i++) { var fileNode = workspaceTree[i]; for (var j = 0, sl = fileNode.traits.length; j < sl; j++) { var traitNode = fileNode.traits[j]; if (traitNode.name.toLowerCase() == traitName.toLowerCase()) { toReturn = traitNode; } } } return toReturn; } function getFileNodeFromPath(path: string): FileNode { var returnNode = null; for (var i = 0, l = workspaceTree.length; i < l; i++) { var fileNode = workspaceTree[i]; if (fileNode.path == path) { returnNode = fileNode; } } return returnNode; } function notifyClientOfWorkComplete() { refreshProcessing = false; connection.sendRequest("workDone"); } function saveProjectTree(projectPath: string, treeFile: string): Promise<boolean> { return new Promise((resolve, reject) => { if (!enableCache) { resolve(false); } else { cache.save(treeFile, workspaceTree, (result) => { if (result === true) { resolve(true); } else { reject(result); } }); } }); } connection.listen();
the_stack
import { EventRef, MetadataCache, SectionCache, TAbstractFile, TFile, Vault, } from 'obsidian'; import { Mutex } from 'async-mutex'; import { Task } from './Task'; import type { Events } from './Events'; export enum State { Cold = 'Cold', Initializing = 'Initializing', Warm = 'Warm', } export class Cache { private readonly metadataCache: MetadataCache; private readonly metadataCacheEventReferences: EventRef[]; private readonly vault: Vault; private readonly vaultEventReferences: EventRef[]; private readonly events: Events; private readonly eventsEventReferences: EventRef[]; private readonly tasksMutex: Mutex; private state: State; private tasks: Task[]; /** * We cannot know if this class will be instantiated because obsidian started * or because the plugin was activated later. This means we have to load the * whole vault once after the first metadata cache resolve to ensure that we * load the entire vault in case obsidian is starting up. In the case of * obsidian starting, the task cache's initial load would end up with 0 tasks, * as the metadata cache would still be empty. */ private loadedAfterFirstResolve: boolean; constructor({ metadataCache, vault, events, }: { metadataCache: MetadataCache; vault: Vault; events: Events; }) { this.metadataCache = metadataCache; this.metadataCacheEventReferences = []; this.vault = vault; this.vaultEventReferences = []; this.events = events; this.eventsEventReferences = []; this.tasksMutex = new Mutex(); this.state = State.Cold; this.tasks = []; this.loadedAfterFirstResolve = false; this.subscribeToCache(); this.subscribeToVault(); this.subscribeToEvents(); this.loadVault(); } public unload(): void { for (const eventReference of this.metadataCacheEventReferences) { this.metadataCache.offref(eventReference); } for (const eventReference of this.vaultEventReferences) { this.vault.offref(eventReference); } for (const eventReference of this.eventsEventReferences) { this.events.off(eventReference); } } public getTasks(): Task[] { return this.tasks; } public getState(): State { return this.state; } private notifySubscribers(): void { this.events.triggerCacheUpdate({ tasks: this.tasks, state: this.state, }); } private subscribeToCache(): void { const resolvedEventeReference = this.metadataCache.on( 'resolved', async () => { // Resolved fires on every change. // We only want to initialize if we haven't already. if (!this.loadedAfterFirstResolve) { this.loadedAfterFirstResolve = true; this.loadVault(); } }, ); this.metadataCacheEventReferences.push(resolvedEventeReference); // Does not fire when starting up obsidian and only works for changes. const changedEventReference = this.metadataCache.on( 'changed', (file: TFile) => { this.tasksMutex.runExclusive(() => { this.indexFile(file); }); }, ); this.metadataCacheEventReferences.push(changedEventReference); } private subscribeToVault(): void { const createdEventReference = this.vault.on( 'create', (file: TAbstractFile) => { if (!(file instanceof TFile)) { return; } this.tasksMutex.runExclusive(() => { this.indexFile(file); }); }, ); this.vaultEventReferences.push(createdEventReference); const deletedEventReference = this.vault.on( 'delete', (file: TAbstractFile) => { if (!(file instanceof TFile)) { return; } this.tasksMutex.runExclusive(() => { this.tasks = this.tasks.filter((task: Task) => { return task.path !== file.path; }); this.notifySubscribers(); }); }, ); this.vaultEventReferences.push(deletedEventReference); const renamedEventReference = this.vault.on( 'rename', (file: TAbstractFile, oldPath: string) => { if (!(file instanceof TFile)) { return; } this.tasksMutex.runExclusive(() => { this.tasks = this.tasks.map((task: Task): Task => { if (task.path === oldPath) { return new Task({ ...task, path: file.path }); } else { return task; } }); this.notifySubscribers(); }); }, ); this.vaultEventReferences.push(renamedEventReference); } private subscribeToEvents(): void { const requestReference = this.events.onRequestCacheUpdate((handler) => { handler({ tasks: this.tasks, state: this.state }); }); this.eventsEventReferences.push(requestReference); } private loadVault(): Promise<void> { return this.tasksMutex.runExclusive(async () => { this.state = State.Initializing; await Promise.all( this.vault.getMarkdownFiles().map((file: TFile) => { return this.indexFile(file); }), ); this.state = State.Warm; // Notify that the cache is now warm: this.notifySubscribers(); }); } private async indexFile(file: TFile): Promise<void> { const fileCache = this.metadataCache.getFileCache(file); if (fileCache === null || fileCache === undefined) { return; } let listItems = fileCache.listItems; if (listItems === undefined) { // When there is no list items cache, there are no tasks. // Still continue to notify watchers of removal. listItems = []; } const fileContent = await this.vault.cachedRead(file); const fileLines = fileContent.split('\n'); // Remove all tasks from this file from the cache before // adding the ones that are currently in the file. this.tasks = this.tasks.filter((task: Task) => { return task.path !== file.path; }); // We want to store section information with every task so // that we can use that when we post process the markdown // rendered lists. let currentSection: SectionCache | null = null; let sectionIndex = 0; for (const listItem of listItems) { if (listItem.task !== undefined) { if ( currentSection === null || currentSection.position.end.line < listItem.position.start.line ) { // We went past the current section (or this is the first task). // Find the section that is relevant for this task and the following of the same section. currentSection = this.getSection({ lineNumberTask: listItem.position.start.line, sections: fileCache.sections, }); sectionIndex = 0; } if (currentSection === null) { // Cannot process a task without a section. continue; } const line = fileLines[listItem.position.start.line]; const task = Task.fromLine({ line, path: file.path, sectionStart: currentSection.position.start.line, sectionIndex, precedingHeader: this.getPrecedingHeader({ lineNumberTask: listItem.position.start.line, sections: fileCache.sections, fileLines, }), }); if (task !== null) { sectionIndex++; this.tasks.push(task); } } } // All updated, inform our subscribers. this.notifySubscribers(); } private getSection({ lineNumberTask, sections, }: { lineNumberTask: number; sections: SectionCache[] | undefined; }): SectionCache | null { if (sections === undefined) { return null; } for (const section of sections) { if ( section.type === 'list' && section.position.start.line <= lineNumberTask && section.position.end.line >= lineNumberTask ) { return section; } } return null; } private getPrecedingHeader({ lineNumberTask, sections, fileLines, }: { lineNumberTask: number; sections: SectionCache[] | undefined; fileLines: string[]; }): string | null { if (sections === undefined) { return null; } let precedingHeaderSection: SectionCache | undefined; for (const section of sections) { if (section.type === 'heading') { if (section.position.start.line > lineNumberTask) { // Break out of the loop as the last header was the preceding one. break; } precedingHeaderSection = section; } } if (precedingHeaderSection === undefined) { return null; } const lineNumberPrecedingHeader = precedingHeaderSection.position.start.line; const linePrecedingHeader = fileLines[lineNumberPrecedingHeader]; const headerRegex = /^#+ +(.*)/u; const headerMatch = linePrecedingHeader.match(headerRegex); if (headerMatch === null) { return null; } else { return headerMatch[1]; } } }
the_stack
import React from 'react'; import { DataTable, Table, TableBody, TableCell, TableContainer, TableHead, TableHeader, TableRow, TableSelectAll, TableSelectRow, TableToolbar, TableToolbarContent, TableToolbarSearch, TableBatchActions, TableBatchAction, Row, Button, Modal } from 'carbon-components-react'; import { Delete16, Download16 } from '@carbon/icons-react'; import "../styles/multiScanReports.scss" import "../styles/reportManagerTable.scss" interface IReportManagerTableState { redisplayTable: boolean, // note this is just a simulated state to force table to rerender after a delete, etc. modalScreenShot: boolean, screenShotRow: number, screenShot: string, url: string, pageTitle: string, date: string, userScanLabel: string, deleteModal: boolean, deleteModalSelectedRows: any } interface IReportManagerTableProps { layout: "main" | "sub", storedScans: { actualStoredScan: boolean; // denotes actual stored scan vs a current scan that is kept when scans are not being stored isSelected: boolean; // stored scan is selected in the Datatable url: string; pageTitle: string; dateTime: number | undefined; scanLabel: string; userScanLabel: string; ruleSet: any; guidelines: any; reportDate: Date; violations: any; needsReviews: any; recommendations: any; elementsNoViolations: number; elementsNoFailures: number; storedScan: string; screenShot: string; storedScanData: string; }[], reportHandler: (typeScan: string) => void, setStoredScanCount: () => void, storeScanLabel: (e:any, i:number) => void, clearSelectedStoredScans: () => void, } export default class ReportManagerTable extends React.Component<IReportManagerTableProps, IReportManagerTableState> { myRef: React.RefObject<HTMLButtonElement>; constructor(props:any) { super(props); this.myRef = React.createRef(); } state: IReportManagerTableState = { redisplayTable: true, modalScreenShot: false, screenShotRow: 0, screenShot: "", url: "", pageTitle: "", date: "", userScanLabel: "", deleteModal: false, deleteModalSelectedRows: null }; format_date(timestamp: string) { var date = new Date(timestamp); return ("00" + (date.getMonth() + 1)).slice(-2) + "/" +("00" + date.getDate()).slice(-2) + "/" + ("00" + date.getFullYear()).slice(-2) + ' ' + ("00" + date.getHours()).slice(-2) + ":" + ("00" + date.getMinutes()).slice(-2) + ":" + ("00" + date.getSeconds()).slice(-2); } downloadScanReports(selectedRows:any) { // clear old selected rows this.props.clearSelectedStoredScans(); // set selected rows / scans in storedScans for (let i=0; i<selectedRows.length; i++) { if (selectedRows[i].isSelected === true) { this.props.storedScans[selectedRows[i].id].isSelected = true; } } this.props.reportHandler("selected"); } deleteSelected(selectedRows:any) { // get index(s) of selected row(s) to delete that match up with storedScans let indexes:number[] = []; // clear old selected rows this.props.clearSelectedStoredScans(); for (let i=0; i<selectedRows.length; i++) { if (selectedRows[i].isSelected === true) { // this.props.storedScans[selectedRows[i].id].isSelected = true; indexes.push(selectedRows[i].id); } } for (var i = indexes.length -1; i >= 0; i--) this.props.storedScans.splice(indexes[i], 1); // update state storedScanCount this.props.setStoredScanCount(); // need a change of state to rerender scan manager if (this.state.redisplayTable === true) { this.setState({ redisplayTable: false }); } else if (this.state.redisplayTable === false) { this.setState({ redisplayTable: true }); } // document.getElementById("secretSelectAll")?.click(); //@ts-ignore this.myRef.current.click(); } handleSelectAll = (selectAll: { (): void; (): void; }) => () => { selectAll(); }; screenShotModal(rowNum:number) { this.setState({ screenShotRow: rowNum, modalScreenShot: true, screenShot: this.props.storedScans[rowNum].screenShot, url: this.props.storedScans[rowNum].url, pageTitle: this.props.storedScans[rowNum].pageTitle, //@ts-ignore date: this.format_date(this.props.storedScans[rowNum].dateTime).toString(), userScanLabel: this.props.storedScans[rowNum].userScanLabel, }); } deleteModalHandler() { this.setState({ deleteModal: true, }); } render() { const headers = [ { header: 'URL', key: 'url', }, { header: 'Page title', key: 'title', }, { header: 'Date and Time', key: 'date', }, { header: 'Scan label', key: 'label', }, { header: 'Details', key: 'details', }, ]; // create scan rows from stored scans let rows:any[] = []; for (let i=0; i<this.props.storedScans.length; i++) { if (this.props.storedScans[i].actualStoredScan === true) { rows[i] = {}; rows[i].id = i; rows[i].url = this.props.storedScans[i].url; rows[i].title = this.props.storedScans[i].pageTitle; //@ts-ignore rows[i].date = this.format_date(this.props.storedScans[i].dateTime); rows[i].label = this.props.storedScans[i].userScanLabel; rows[i].details = "view" } } return ( <React.Fragment> <div className="headerLeftRN" > <Row style={{marginTop:"64px",paddingLeft:"16px",height:"100%"}}> <div className="bx--col-lg-3 bx--col-sm-4 stored-scans" style={{marginBottom:"14px"}}> Stored Scans </div> <div className="bx--col-lg-8 bx--col-sm-6" style={{paddingLeft:0, maxWidth:"100%"}}> <div style={{overflowX:"auto", paddingBottom:"16px"}}> <DataTable size="compact" rows={rows} headers={headers} render={({ getTableProps, rows, getRowProps, headers, getHeaderProps, selectedRows, getSelectionProps, getBatchActionProps, onInputChange, getTableContainerProps, selectAll, }) => ( <React.Fragment> {/* Since I could not figure out how to call selectAll outside of the DataTable context I made a dummy button to do it */} <Button ref={this.myRef} id="secretSelectAll" style={{display:"none"}} onClick={this.handleSelectAll(selectAll)}> Select All </Button> <TableContainer {...getTableContainerProps()}> <TableToolbar> <TableBatchActions {...getBatchActionProps()}> <TableBatchAction tabIndex={getBatchActionProps().shouldShowBatchActions ? 0 : -1} renderIcon={Download16} onClick={() => this.downloadScanReports(selectedRows)} > Download </TableBatchAction> <TableBatchAction tabIndex={getBatchActionProps().shouldShowBatchActions ? 0 : -1} renderIcon={Delete16} //onClick={() => this.deleteSelected(selectedRows)} onClick={(() => { this.setState({ deleteModalSelectedRows: selectedRows }); this.deleteModalHandler(); // console.log(selectedRows); // console.log(typeof selectedRows); // this.deleteSelected(selectedRows); // this.props.clearStoredScans(true); }).bind(this)} > Delete </TableBatchAction> </TableBatchActions> <TableToolbarContent> <TableToolbarSearch tabIndex={getBatchActionProps().shouldShowBatchActions ? -1 : 0} onChange={onInputChange} /> </TableToolbarContent> </TableToolbar> <Table {...getTableProps()}> <TableHead> <TableRow> <TableSelectAll {...getSelectionProps()} /> {headers.map((header:any) => ( <TableHeader {...getHeaderProps({ header })}> {header.header} </TableHeader> ))} </TableRow> </TableHead> <TableBody> {rows.map((row:any, i:number) => ( <TableRow {...getRowProps({ row })}> <TableSelectRow {...getSelectionProps({ row })} /> {row.cells.map((cell:any,index:number) => ( // <TableCell key={cell.id}>{cell.value}</TableCell> <TableCell key={cell.id}> {index == 0 ? <div style={{textOverflow:"ellipsis", overflow:"hidden", whiteSpace:"nowrap", direction:"rtl", width:"10rem"}}>{cell.value}</div> : ""} {index == 1 ? <div style={{textOverflow:"ellipsis", overflow:"hidden", whiteSpace:"nowrap", direction:"rtl", width:"10rem"}}>{cell.value}</div> : ""} {index == 2 ? cell.value : ""} {index == 3 ? <input style={{width:"6rem"}} type="text" placeholder={cell.value} onBlur={(e) => {this.props.storeScanLabel(e,i)}}/> : ""} {index == 4 ? <a onClick={() => this.screenShotModal(i)} href="javascript:void(0);">{cell.value}</a> : ""} </TableCell> ))} </TableRow> ))} </TableBody> </Table> </TableContainer> <Modal aria-label="Scan details" modalHeading="Details" passiveModal={true} open={this.state.modalScreenShot} onRequestClose={(() => { this.setState({ modalScreenShot: false }); }).bind(this)} style={{paddingRight:"2rem"}} > <div className="bx--row"> <div className="bx--col-lg-8 bx--col-md-4 bx--col-sm-2"> <img src={this.state.screenShot} alt="Screenshot of page scanned" width="100%"/> </div> <div className="bx--col-lg-8 bx--col-md-4 bx--col-sm-2"> <div><strong>Scan label: </strong> <input style={{width:"6rem"}} type="text" placeholder={this.state.userScanLabel} onBlur={(e) => {this.props.storeScanLabel(e,this.state.screenShotRow) }}/> </div> <div><strong>URL: </strong>{this.state.url}</div> <div><strong>Page title: </strong>{this.state.pageTitle}</div> <div>{this.state.date}</div> </div> </div> </Modal> <Modal aria-label="Delete stored scans" modalHeading="Delete stored scans" size='sm' danger={true} open={this.state.deleteModal} shouldSubmitOnEnter={false} onRequestClose={(() => { this.setState({ deleteModal: false }); }).bind(this)} onRequestSubmit={(() => { this.setState({ deleteModal: false }); this.deleteSelected(this.state.deleteModalSelectedRows); }).bind(this)} selectorPrimaryFocus=".bx--modal-footer .bx--btn--secondary" primaryButtonText="Delete" secondaryButtonText="Cancel" primaryButtonDisabled={false} preventCloseOnClickOutside={true} > <p style={{ marginBottom: '1rem' }}> Are you sure you want to delete selected scans? This action is irreversible. </p> </Modal> </React.Fragment> )} /> {/* {selectAll(selectAll)} */} </div> </div> </Row> </div> </React.Fragment> ) } }
the_stack
import { basename, strings } from '@angular-devkit/core'; import { chain, externalSchematic, noop, Rule, SchematicContext, SchematicsException, Tree, } from '@angular-devkit/schematics'; import { getDecoratorMetadata, getSourceNodes, insertImport, isImported, } from '@schematics/angular/utility/ast-utils'; import { Change, InsertChange } from '@schematics/angular/utility/change'; import { ANGULAR_CORE, ANGULAR_SCHEMATICS, CMS_COMPONENT_DATA_CLASS, CMS_COMPONENT_DATA_PROPERTY_NAME, CMS_CONFIG, CONFIG_MODULE_CLASS, OBSERVABLE_CLASS, RXJS, SPARTACUS_CORE, SPARTACUS_STOREFRONTLIB, UTF_8, } from '../shared/constants'; import { commitChanges, defineProperty, findConstructor, getMetadataProperty, getPathResultsForFile, getTsSourceFile, injectService, InsertDirection, } from '../shared/utils/file-utils'; import { addToModuleDeclarations, addToModuleExports, addToModuleImports, buildRelativePath, stripTsFromImport, } from '../shared/utils/module-file-utils'; import { getProjectFromWorkspace } from '../shared/utils/workspace-utils'; import { CxCmsComponentSchema } from './schema'; function buildComponentModule(options: CxCmsComponentSchema): string { const moduleName = options.module || ''; return Boolean(options.declareCmsModule) ? options.declareCmsModule : moduleName; } function buildDeclaringCmsModule(options: CxCmsComponentSchema): string { return Boolean(options.declareCmsModule) ? options.declareCmsModule : options.name; } function updateModule(options: CxCmsComponentSchema): Rule { return (tree: Tree, context: SchematicContext) => { const rawComponentModule = buildDeclaringCmsModule(options); const componentModule = `${strings.dasherize( rawComponentModule )}.module.ts`; const modulePath = getPathResultsForFile(tree, componentModule, '/src')[0]; if (!modulePath) { context.logger.error(`Could not find the ${modulePath}`); return; } const changes: Change[] = []; const moduleTs = getTsSourceFile(tree, modulePath); if (!isImported(moduleTs, CONFIG_MODULE_CLASS, SPARTACUS_CORE)) { const insertImportChange = insertImport( moduleTs, modulePath, `${CONFIG_MODULE_CLASS}`, SPARTACUS_CORE, false ); changes.push(insertImportChange); } if (!isImported(moduleTs, CMS_CONFIG, SPARTACUS_CORE)) { const insertImportChange = insertImport( moduleTs, modulePath, `${CMS_CONFIG}`, SPARTACUS_CORE, false ); changes.push(insertImportChange); } const componentName = `${strings.classify(options.name)}${strings.classify( options.type )}`; /*** updating the module's metadata start ***/ const addToModuleImportsChanges = addToModuleImports( tree, modulePath, `${CONFIG_MODULE_CLASS}.withConfig(<${CMS_CONFIG}>{ cmsComponents: { ${componentName}: { component: ${componentName}, }, }, })`, moduleTs ); changes.push(...addToModuleImportsChanges); const addToModuleDeclarationsChanges = addToModuleDeclarations( tree, modulePath, componentName, moduleTs ); changes.push(...addToModuleDeclarationsChanges); const addToModuleExportsChanges = addToModuleExports( tree, modulePath, componentName, moduleTs ); changes.push(...addToModuleExportsChanges); /*** updating the module's metadata end ***/ const componentImportSkipped = !Boolean(options.declareCmsModule); if (componentImportSkipped) { const componentFileName = `${strings.dasherize( options.name )}.${strings.dasherize(options.type)}.ts`; const componentPath = getPathResultsForFile( tree, componentFileName, '/src' )[0]; const componentRelativeImportPath = buildRelativePath( modulePath, componentPath ); const componentImport = insertImport( moduleTs, modulePath, componentName, stripTsFromImport(componentRelativeImportPath), false ); changes.push(componentImport); } commitChanges(tree, modulePath, changes, InsertDirection.RIGHT); context.logger.info(`Updated ${modulePath}`); }; } function updateComponent(options: CxCmsComponentSchema): Rule { return (tree: Tree, _context: SchematicContext) => { if (!options.cmsComponentData) { return; } if (!options.cmsComponentDataModel) { throw new SchematicsException(`"cmsComponentDataModel" can't be falsy`); } const cmsComponentData = `${CMS_COMPONENT_DATA_CLASS}<${strings.classify( options.cmsComponentDataModel )}>`; const componentFileName = `${strings.dasherize( options.name )}.${strings.dasherize(options.type)}.ts`; const project = getProjectFromWorkspace(tree, options); const componentPath = getPathResultsForFile( tree, componentFileName, project.sourceRoot )[0]; const changes: Change[] = []; const componentTs = getTsSourceFile(tree, componentPath); const nodes = getSourceNodes(componentTs); const constructorNode = findConstructor(nodes); const injectionChange = injectService({ constructorNode, path: componentPath, serviceName: cmsComponentData, modifier: 'private', propertyName: CMS_COMPONENT_DATA_PROPERTY_NAME, }); changes.push(injectionChange); const componentDataProperty = ` ${CMS_COMPONENT_DATA_PROPERTY_NAME}$: Observable<${strings.classify( options.cmsComponentDataModel )}> = this.${CMS_COMPONENT_DATA_PROPERTY_NAME}.data$;`; const componentDataPropertyChange = defineProperty( nodes, componentPath, componentDataProperty ); changes.push(componentDataPropertyChange); const cmsComponentImport = insertImport( componentTs, componentPath, strings.classify(options.cmsComponentDataModel), stripTsFromImport(options.cmsComponentDataModelPath), false ); changes.push(cmsComponentImport); const cmsComponentDataImport = insertImport( componentTs, componentPath, CMS_COMPONENT_DATA_CLASS, SPARTACUS_STOREFRONTLIB, false ); changes.push(cmsComponentDataImport); const observableImport = insertImport( componentTs, componentPath, OBSERVABLE_CLASS, RXJS, false ); changes.push(observableImport); commitChanges(tree, componentPath, changes, InsertDirection.LEFT); }; } function updateTemplate(options: CxCmsComponentSchema): Rule { return (tree: Tree, _context: SchematicContext) => { const componentFileName = `${strings.dasherize( options.name )}.${strings.dasherize(options.type)}.ts`; const project = getProjectFromWorkspace(tree, options); const componentPath = getPathResultsForFile( tree, componentFileName, project.sourceRoot )[0]; const componentTs = getTsSourceFile(tree, componentPath); let templatePath = ''; let templateContent = ''; let startIndex: number; if (options.inlineTemplate) { templatePath = componentPath; const decorator = getDecoratorMetadata( componentTs, 'Component', ANGULAR_CORE )[0]; const inlineTemplate = getMetadataProperty(decorator, 'template'); templateContent = inlineTemplate.getText(); startIndex = inlineTemplate.name.parent.end - 1; } else { const componentTemplateFileName = `${strings.dasherize( options.name )}.${strings.dasherize(options.type)}.html`; templatePath = getPathResultsForFile( tree, componentTemplateFileName, project.sourceRoot )[0]; const buffer = tree.read(templatePath); templateContent = buffer ? buffer.toString(UTF_8) : ''; startIndex = templateContent.length; } if (Boolean(templateContent)) { const insertion = new InsertChange( templatePath, startIndex, `<ng-container *ngIf="${CMS_COMPONENT_DATA_PROPERTY_NAME}$ | async as data">{{data | json}}</ng-container>` ); commitChanges(tree, templatePath, [insertion], InsertDirection.RIGHT); } }; } function declareInModule(options: CxCmsComponentSchema): Rule { return (tree: Tree, context: SchematicContext) => { if (!(options.declareCmsModule && options.module)) { return; } const sourceCmsModule = basename(options.declareCmsModule as any); const sourceCmsModuleFileName = `${strings.dasherize( sourceCmsModule )}.module.ts`; const sourceCmsModulePath = getPathResultsForFile( tree, sourceCmsModuleFileName, '/src' )[0]; if (!sourceCmsModulePath) { context.logger.error(`Could not find the ${sourceCmsModulePath}`); return; } const destinationModuleName = basename(options.module as any); const destinationFileName = `${strings.dasherize( destinationModuleName )}.module.ts`; const destinationModulePath = getPathResultsForFile( tree, destinationFileName, '/src' )[0]; if (!destinationModulePath) { context.logger.error(`Could not find the ${destinationModulePath}`); return; } const sourceCmsModuleRelativeImportPath = buildRelativePath( destinationModulePath, sourceCmsModulePath ); const destinationModuleTs = getTsSourceFile(tree, destinationModulePath); const sourceCmsModuleClassified = strings.classify(sourceCmsModule); const moduleFileImport = insertImport( destinationModuleTs, destinationModulePath, sourceCmsModuleClassified, stripTsFromImport(sourceCmsModuleRelativeImportPath), false ); const moduleImport = addToModuleImports( tree, destinationModulePath, sourceCmsModuleClassified, destinationModuleTs ); const changes: Change[] = [moduleFileImport, ...moduleImport]; commitChanges(tree, destinationModulePath, changes, InsertDirection.LEFT); }; } function validateArguments(options: CxCmsComponentSchema): void { if (options.cmsComponentData && !Boolean(options.cmsComponentDataModel)) { throw new SchematicsException( 'You have to specify the "cmsComponentDataModel" option.' ); } } export function addCmsComponent(options: CxCmsComponentSchema): Rule { return (tree: Tree, context: SchematicContext) => { validateArguments(options); // angular's component CLI flags const { declareCmsModule, export: exportOption, name: componentName, changeDetection, flat, inlineStyle, inlineTemplate, lintFix, prefix, project, selector, skipSelector, type, skipTests, style, viewEncapsulation, } = options; const componentModule = buildComponentModule(options); // angular's module CLI flags const { path, routing, routingScope, route, commonModule, module: declaringModule, } = options; const createCmsModule = !Boolean(declareCmsModule); const skipImport = createCmsModule; return chain([ // we are creating a new module if the declared module is not provided createCmsModule ? externalSchematic(ANGULAR_SCHEMATICS, 'module', { project, name: componentName, path, routing, routingScope, route, commonModule, lintFix, module: declaringModule, }) : noop(), externalSchematic(ANGULAR_SCHEMATICS, 'component', { changeDetection, export: exportOption, flat, inlineStyle, inlineTemplate, lintFix, module: componentModule, name: componentName, prefix, project, selector, skipSelector, type, skipTests, style, viewEncapsulation, skipImport, }), updateModule(options), updateComponent(options), updateTemplate(options), !createCmsModule && declaringModule ? declareInModule(options) : noop(), ])(tree, context); }; }
the_stack
import React, { useContext, useMemo, useCallback, useEffect, Suspense } from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter, Route, Switch, Link, Redirect, useRouteMatch, useParams, } from 'react-router-dom'; import { Provider, useDispatch } from 'react-redux'; import throttle from 'lodash.throttle'; import { ToastContainer } from 'react-toastify'; // Moment.js locales (must be imported from this file to avoid being run in // nodejs context). import 'moment/dist/locale/fr'; import 'moment/dist/locale/es'; import 'moment/dist/locale/tr'; // Global variables import { get, init, reduxStore, actions } from './store'; import { translate as $t, debug, computeIsSmallScreen, useKresusState, assert } from './helpers'; import URL from './urls'; import { FORCE_DEMO_MODE, URL_PREFIX } from '../shared/instance'; // Components import About from './components/about'; import Reports from './components/reports'; import Budget from './components/budget'; import DuplicatesList from './components/duplicates'; import Settings from './components/settings'; import Accesses from './components/accesses'; import Categories from './components/categories'; import Transactions from './components/transactions'; import Onboarding from './components/onboarding'; import Dashboard from './components/dashboard'; import TransactionRules from './components/rules'; import Menu from './components/menu'; import DropdownMenu from './components/menu/dropdown'; import DemoButton from './components/header/demo-button'; import DisplayIf from './components/ui/display-if'; import ErrorReporter from './components/ui/error-reporter'; import Overlay, { LoadingMessage } from './components/overlay'; import { DriverAccount } from './components/drivers/account'; import { getDriver, ViewContext, DriverType, NoDriver } from './components/drivers'; import 'normalize.css/normalize.css'; import 'font-awesome/css/font-awesome.css'; import 'react-toastify/dist/ReactToastify.min.css'; import './css/base.css'; const RESIZE_THROTTLING = 100; // Lazy-loaded components const ChartsComp = React.lazy(() => import('./components/charts')); const Charts = () => { return ( <Suspense fallback={<LoadingMessage message={$t('client.spinner.loading')} />}> <ChartsComp /> </Suspense> ); }; const SectionTitle = () => { const titleKey = URL.sections.title(useParams()); if (titleKey === null) { return null; } const title = $t(`client.menu.${titleKey}`); return <span className="section-title">&nbsp;/&nbsp;{title}</span>; }; const RedirectIfUnknownAccount = (props: { children: React.ReactNode | React.ReactNode[] }) => { const view = useContext(ViewContext); const initialAccountId = useKresusState(state => get.initialAccountId(state)); if (view.driver === NoDriver) { return <Redirect to={URL.reports.url(new DriverAccount(initialAccountId))} push={false} />; } return <>{props.children}</>; }; export const RedirectIfNotAccount = (props: { children: React.ReactNode | React.ReactNode[] }) => { const view = useContext(ViewContext); if (view.driver.type !== DriverType.Account) { return <Redirect to={URL.reports.url(view.driver)} push={false} />; } return <>{props.children}</>; }; const View = () => { const params = useParams<{ driver: string; value: string; }>(); const currentDriver = useMemo(() => { return getDriver(params.driver, params.value); }, [params.driver, params.value]); const banks = useKresusState(state => state.banks); const currentView = useMemo(() => { return currentDriver.getView(banks); }, [currentDriver, banks]); return ( <ViewContext.Provider value={currentView}> <Switch> <Route path={URL.reports.pattern}> <RedirectIfUnknownAccount> <Reports /> </RedirectIfUnknownAccount> </Route> <Route path={URL.budgets.pattern}> <RedirectIfNotAccount> <RedirectIfUnknownAccount> <Budget /> </RedirectIfUnknownAccount> </RedirectIfNotAccount> </Route> <Route path={URL.charts.pattern}> <RedirectIfUnknownAccount> <Charts /> </RedirectIfUnknownAccount> </Route> <Route path={URL.duplicates.pattern}> <RedirectIfNotAccount> <DuplicatesList /> </RedirectIfNotAccount> </Route> <Route path={URL.transactions.pattern}> <Transactions /> </Route> </Switch> </ViewContext.Provider> ); }; const Kresus = () => { // Retrieve the URL prefix and remove a potential trailing '/'. const urlPrefix = useKresusState(state => { const prefix = get.instanceProperty(state, URL_PREFIX); if (prefix === null) { return ''; } return prefix.replace(/\/$/g, ''); }); const initialAccountId = useKresusState(state => get.initialAccountId(state)); const forcedDemoMode = useKresusState(state => get.boolInstanceProperty(state, FORCE_DEMO_MODE) ); const isSmallScreen = useKresusState(state => get.isSmallScreen(state)); const dispatch = useDispatch(); // eslint-disable-next-line react-hooks/exhaustive-deps const handleWindowResize = useCallback( throttle(event => { const newIsSmallScreen = computeIsSmallScreen(event.target.innerWidth); if (newIsSmallScreen !== isSmallScreen) { actions.setIsSmallScreen(dispatch, newIsSmallScreen); } }, RESIZE_THROTTLING), [dispatch, isSmallScreen] ); const handleToggleMenu = useCallback(() => { actions.toggleMenu(dispatch); }, [dispatch]); const hideMenu = useCallback(() => { actions.toggleMenu(dispatch, true); }, [dispatch]); const handleContentClick = isSmallScreen ? hideMenu : undefined; useEffect(() => { window.addEventListener('resize', handleWindowResize); return () => { window.removeEventListener('resize', handleWindowResize); }; }); return ( <ErrorReporter> <BrowserRouter basename={`${urlPrefix}/#`}> <Switch> <Route path={[URL.woobReadme.pattern, URL.onboarding.pattern]}> <DisplayOrRedirectToInitialScreen> <Onboarding /> </DisplayOrRedirectToInitialScreen> </Route> <Route path="/" exact={false}> <DisplayOrRedirectToInitialScreen> <header> <button className="menu-toggle" onClick={handleToggleMenu}> <span className="fa fa-navicon" /> </button> <h1> <Link to={URL.dashboard.url()}>{$t('client.KRESUS')}</Link> </h1> <Route path={URL.sections.pattern}> <SectionTitle /> </Route> <DisplayIf condition={forcedDemoMode}> <p className="disable-demo-mode">{$t('client.demo.forced')}</p> </DisplayIf> <DisplayIf condition={!forcedDemoMode}> <DemoButton /> </DisplayIf> <DropdownMenu /> </header> <main> <Route path={URL.sections.genericPattern}> <Menu /> </Route> <div id="content-container"> <div className="content" onClick={handleContentClick}> <Switch> <Route path={URL.view.pattern}> <View /> </Route> <Route path={URL.settings.pattern}> <Settings /> </Route> <Route path={URL.categories.pattern}> <Categories /> </Route> <Route path={URL.about.pattern}> <About /> </Route> <Route path={URL.accesses.pattern}> <Accesses /> </Route> <Route path={URL.dashboard.pattern}> <Dashboard /> </Route> <Route path={URL.rules.pattern}> <TransactionRules /> </Route> <Redirect to={URL.reports.url( new DriverAccount(initialAccountId) )} push={false} /> </Switch> </div> </div> </main> </DisplayOrRedirectToInitialScreen> </Route> <Redirect from="" to="/" push={false} /> </Switch> <ToastContainer /> <Overlay /> </BrowserRouter> </ErrorReporter> ); }; const DisplayOrRedirectToInitialScreen = (props: { children: React.ReactNode | React.ReactNode[]; }) => { const hasAccess = useKresusState(state => get.accessIds(state).length > 0); const isWoobInstalled = useKresusState(state => get.isWoobInstalled(state)); const displayWoobReadme = useRouteMatch({ path: URL.woobReadme.pattern }); const displayOnboarding = useRouteMatch({ path: URL.onboarding.pattern }); if (!isWoobInstalled) { if (!displayWoobReadme) { return <Redirect to={URL.woobReadme.url()} push={false} />; } } else if (!hasAccess) { if (!displayOnboarding) { return <Redirect to={URL.onboarding.url()} push={false} />; } } else if (displayWoobReadme || displayOnboarding) { return <Redirect to="/" push={false} />; } return <>{props.children}</>; }; export default async function runKresus() { try { const initialState = await init(); // Define the redux store initial content. Object.assign(reduxStore.getState(), initialState); const appElement = document.getElementById('app'); assert(appElement !== null, 'well, good luck :-)'); // Remove the loading class on the app element. appElement.classList.remove('before-load'); ReactDOM.render( // Pass the Redux store as context to the rest of the app. <Provider store={reduxStore}> <Kresus /> </Provider>, appElement ); } catch (err) { let errMessage = ''; if (err) { debug(err); errMessage = `\n${err.shortMessage || JSON.stringify(err)}`; } window.alert(`Error when starting the app:${errMessage}\nCheck the console.`); } }
the_stack
import { underline } from 'colorette'; import { cli, command } from '../dist/index.js'; let mockProcessExit: jest.SpyInstance; let mockConsoleLog: jest.SpyInstance; let mockConsoleError: jest.SpyInstance; beforeAll(() => { process.stdout.columns = 90; mockProcessExit = jest.spyOn(process, 'exit').mockImplementation(); }); beforeEach(() => { mockConsoleLog = jest.spyOn(console, 'log').mockImplementation(); mockConsoleError = jest.spyOn(console, 'error').mockImplementation(); mockProcessExit.mockClear(); }); afterEach(() => { mockConsoleLog.mockRestore(); mockConsoleError.mockRestore(); }); afterAll(() => { mockProcessExit.mockRestore(); }); describe('show help', () => { test('empty cli', () => { cli( {}, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('name', () => { cli( { name: 'npm', }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('empty parameters', () => { cli( { parameters: [], }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('parameters with no name', () => { cli( { parameters: ['<arg-a>', '[arg-b]'], }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('parameters with name', () => { cli( { name: 'my-cli', parameters: ['<arg-a>', '[arg-b]'], }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('parameters with optional --', () => { cli( { name: 'my-cli', parameters: ['<arg-a>', '[arg-b]', '--', '[arg-c]'], }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('parameters with required --', () => { cli( { name: 'my-cli', parameters: ['<arg-a>', '[arg-b]', '--', '<arg-c>'], }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('empty commands', () => { cli( { commands: [], }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('commands', () => { const testCommand = command({ name: 'test', }); cli( { name: 'my-cli', commands: [ testCommand, ], }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('commands with description', () => { const testCommand = command({ name: 'test', help: { description: 'test command', }, }); cli( { name: 'my-cli', commands: [ testCommand, ], }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('undefined flags', () => { cli( { flags: undefined, }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('empty flags', () => { cli( { flags: {}, }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('flags', () => { cli( { flags: { flag: Boolean, flagA: String, flagB: { type: Number, }, flagC: { type: RegExp, default: /hello/, }, }, }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('help disabled', () => { cli( { help: false, }, undefined, ['--help'], ); expect(mockProcessExit).not.toHaveBeenCalled(); }); test('help disabled but shown', () => { const argv = cli( { name: 'my-cli', help: false, }, undefined, ['--help'], ); argv.showHelp({ version: '1.2.3', }); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('empty help.examples', () => { cli( { help: { examples: [], }, }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('help.version with --help', () => { cli( { help: { version: '1.0.0', }, }, undefined, ['--help'], ); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('help.version with --version', () => { const parsed = cli( { help: { version: '1.0.0', }, }, undefined, ['--version'], ); expect(mockProcessExit).not.toHaveBeenCalled(); expect(parsed.unknownFlags).toStrictEqual({ version: [true], }); }); test('help.usage string', () => { cli( { help: { usage: 'usage string', }, }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('help.usage array', () => { cli( { help: { usage: [ 'usage string a', 'usage string b', 'usage string c', ], }, }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('help.description', () => { cli( { help: { description: 'test description', }, }, undefined, ['--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('command help', () => { const testCommand = command({ name: 'test', parameters: ['<arg a>', '<arg b>'], help: { description: 'test command', }, }); cli( { name: 'my-cli', commands: [ testCommand, ], }, undefined, ['test', '--help'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('command help disabled', () => { const testCommand = command({ name: 'test', help: false, }); cli( { name: 'my-cli', commands: [ testCommand, ], }, undefined, ['test', '--help'], ); expect(mockProcessExit).not.toHaveBeenCalled(); }); }); describe('invalid usage', () => { test('missing required parameter', () => { cli( { name: 'my-cli', parameters: ['<value-a>'], }, undefined, [], ); expect(mockProcessExit).toHaveBeenCalledWith(1); const { calls } = mockConsoleError.mock; expect(calls[0][0]).toMatchSnapshot(); }); }); test('show version', () => { cli( { version: '1.0.0', }, undefined, ['--version'], ); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('smoke test', () => { cli({ name: 'my-cli', version: '1.1.1', commands: [ command({ name: 'my-command', help: { description: 'my command description', }, }), ], parameters: ['<urls...>'], flags: { outputDir: { type: String, alias: 'o', description: 'Tweet screenshot output directory', placeholder: '<path>', }, width: { type: Number, alias: 'w', description: 'Width of tweet', default: 550, placeholder: '<width>', }, showTweet: { type: Boolean, alias: 't', description: 'Show tweet thread', }, darkMode: { type: Boolean, alias: 'd', description: 'Show tweet in dark mode', }, locale: { type: String, description: 'Locale', default: 'en', placeholder: '<locale>', }, }, help: { examples: [ '# Snapshot a tweet', 'snap-tweet https://twitter.com/jack/status/20', '', '# Snapshot a tweet with Japanese locale', 'snap-tweet https://twitter.com/TwitterJP/status/578707432 --locale ja', '', '# Snapshot a tweet with dark mode and 900px width', 'snap-tweet https://twitter.com/Interior/status/463440424141459456 --width 900 --dark-mode', ], }, }, undefined, ['--help']); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); }); test('help customization', () => { const simpleFlags = { bundle: { type: Boolean, description: 'Bundle all dependencies into the output files', }, define: { type: String, description: 'Substitute K with V while parsing', }, }; const advancedFlags = { allowOverwrite: { type: Boolean, description: 'Allow output files to overwrite input files', }, assetNames: { type: Boolean, description: 'Path template to use for "file" loader files (default "[name]-[hash]")', }, }; cli({ name: 'esbuild', version: '1.0.0', parameters: ['[entry points]'], flags: { ...simpleFlags, ...advancedFlags, // Overwrite to remove alias help: Boolean, }, help: { examples: [ '# Produces dist/entry_point.js and dist/entry_point.js.map', 'esbuild --bundle entry_point.js --outdir=dist --minify --sourcemap', ], render(nodes, renderers) { // Remove name nodes.splice(0, 1); // Replace "flags" with "options" in Usage nodes[0].data.body = nodes[0].data.body.replace('flags', 'options'); // Add Documentation & Repository nodes.splice(1, 0, { type: 'section', data: { title: 'Documentation:', body: underline('https://esbuild.github.io/'), }, }); // Split Flags into "Simple options" and "Advanced options" const flags = nodes[2].data.body.data; nodes.splice(2, 1, { type: 'section', data: { title: 'Simple options:', body: { type: 'table', data: { ...flags, tableData: flags.tableData.filter( ([flagName]: [{ data: { name: string }}]) => flagName.data.name in simpleFlags, ), }, }, indentBody: 0, }, }, { type: 'section', data: { title: 'Advanced options:', body: { type: 'table', data: { ...flags, tableData: flags.tableData.filter( ([flagName]: [{ data: { name: string }}]) => flagName.data.name in advancedFlags, ), }, }, indentBody: 0, }, }); // Update renderer so flags that accept a value shows `=...` renderers.flagOperator = () => '='; renderers.flagParameter = flagType => (flagType === Boolean ? '' : '...'); const extendedRenderer = Object.assign(renderers, { someRenderer(value: number) { return `Received value: ${value}`; }, }); return extendedRenderer.render([ ...nodes, { type: 'someRenderer', data: 123, }, ]); }, }, }, undefined, ['--help']); expect(mockProcessExit).toHaveBeenCalledWith(0); const { calls } = mockConsoleLog.mock; expect(calls[0][0]).toMatchSnapshot(); });
the_stack
import { Viewport } from '../mol-canvas3d/camera/util'; import { ICamera } from '../mol-canvas3d/camera'; import { Scene } from './scene'; import { WebGLContext } from './webgl/context'; import { Mat4, Vec3, Vec4, Vec2, Quat } from '../mol-math/linear-algebra'; import { GraphicsRenderable } from './renderable'; import { Color } from '../mol-util/color'; import { ValueCell, deepEqual } from '../mol-util'; import { GlobalUniformValues } from './renderable/schema'; import { GraphicsRenderVariant } from './webgl/render-item'; import { ParamDefinition as PD } from '../mol-util/param-definition'; import { Clipping } from '../mol-theme/clipping'; import { stringToWords } from '../mol-util/string'; import { degToRad } from '../mol-math/misc'; import { createNullTexture, Texture, Textures } from './webgl/texture'; import { arrayMapUpsert } from '../mol-util/array'; import { clamp } from '../mol-math/interpolate'; export interface RendererStats { programCount: number shaderCount: number attributeCount: number elementsCount: number framebufferCount: number renderbufferCount: number textureCount: number vertexArrayCount: number drawCount: number instanceCount: number instancedDrawCount: number } interface Renderer { readonly stats: RendererStats readonly props: Readonly<RendererProps> clear: (toBackgroundColor: boolean) => void clearDepth: () => void update: (camera: ICamera) => void renderPick: (group: Scene.Group, camera: ICamera, variant: GraphicsRenderVariant, depthTexture: Texture | null) => void renderDepth: (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => void renderMarkingDepth: (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => void renderMarkingMask: (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => void renderBlended: (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => void renderBlendedOpaque: (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => void renderBlendedTransparent: (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => void renderBlendedVolumeOpaque: (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => void renderBlendedVolumeTransparent: (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => void renderWboitOpaque: (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => void renderWboitTransparent: (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => void setProps: (props: Partial<RendererProps>) => void setViewport: (x: number, y: number, width: number, height: number) => void setTransparentBackground: (value: boolean) => void setDrawingBufferSize: (width: number, height: number) => void setPixelRatio: (value: number) => void dispose: () => void } export const RendererParams = { backgroundColor: PD.Color(Color(0x000000), { description: 'Background color of the 3D canvas' }), // the following are general 'material' parameters pickingAlphaThreshold: PD.Numeric(0.5, { min: 0.0, max: 1.0, step: 0.01 }, { description: 'The minimum opacity value needed for an object to be pickable.' }), interiorDarkening: PD.Numeric(0.5, { min: 0.0, max: 1.0, step: 0.01 }), interiorColorFlag: PD.Boolean(true, { label: 'Use Interior Color' }), interiorColor: PD.Color(Color.fromNormalizedRgb(0.3, 0.3, 0.3)), highlightColor: PD.Color(Color.fromNormalizedRgb(1.0, 0.4, 0.6)), selectColor: PD.Color(Color.fromNormalizedRgb(0.2, 1.0, 0.1)), highlightStrength: PD.Numeric(0.7, { min: 0.0, max: 1.0, step: 0.1 }), selectStrength: PD.Numeric(0.7, { min: 0.0, max: 1.0, step: 0.1 }), markerPriority: PD.Select(1, [[1, 'Highlight'], [2, 'Select']]), xrayEdgeFalloff: PD.Numeric(1, { min: 0.0, max: 3.0, step: 0.1 }), style: PD.MappedStatic('matte', { custom: PD.Group({ lightIntensity: PD.Numeric(0.6, { min: 0.0, max: 1.0, step: 0.01 }), ambientIntensity: PD.Numeric(0.4, { min: 0.0, max: 1.0, step: 0.01 }), metalness: PD.Numeric(0.0, { min: 0.0, max: 1.0, step: 0.01 }), roughness: PD.Numeric(1.0, { min: 0.0, max: 1.0, step: 0.01 }), reflectivity: PD.Numeric(0.5, { min: 0.0, max: 1.0, step: 0.01 }), }, { isExpanded: true }), flat: PD.Group({}), matte: PD.Group({}), glossy: PD.Group({}), metallic: PD.Group({}), plastic: PD.Group({}), }, { label: 'Lighting', description: 'Style in which the 3D scene is rendered/lighted' }), clip: PD.Group({ variant: PD.Select('instance', PD.arrayToOptions<Clipping.Variant>(['instance', 'pixel'])), objects: PD.ObjectList({ type: PD.Select('plane', PD.objectToOptions(Clipping.Type, t => stringToWords(t))), invert: PD.Boolean(false), position: PD.Vec3(Vec3()), rotation: PD.Group({ axis: PD.Vec3(Vec3.create(1, 0, 0)), angle: PD.Numeric(0, { min: -180, max: 180, step: 1 }, { description: 'Angle in Degrees' }), }, { isExpanded: true }), scale: PD.Vec3(Vec3.create(1, 1, 1)), }, o => stringToWords(o.type)) }) }; export type RendererProps = PD.Values<typeof RendererParams> export type Style = { lightIntensity: number ambientIntensity: number metalness: number roughness: number reflectivity: number } export function getStyle(props: RendererProps['style']): Style { switch (props.name) { case 'custom': return props.params as Style; case 'flat': return { lightIntensity: 0, ambientIntensity: 1, metalness: 0, roughness: 0.4, reflectivity: 0.5 }; case 'matte': return { lightIntensity: 0.7, ambientIntensity: 0.3, metalness: 0, roughness: 1, reflectivity: 0.5 }; case 'glossy': return { lightIntensity: 0.7, ambientIntensity: 0.3, metalness: 0, roughness: 0.4, reflectivity: 0.5 }; case 'metallic': return { lightIntensity: 0.7, ambientIntensity: 0.7, metalness: 0.6, roughness: 0.6, reflectivity: 0.5 }; case 'plastic': return { lightIntensity: 0.7, ambientIntensity: 0.3, metalness: 0, roughness: 0.2, reflectivity: 0.5 }; } } type Clip = { variant: Clipping.Variant objects: { count: number type: number[] invert: boolean[] position: number[] rotation: number[] scale: number[] } } const tmpQuat = Quat(); function getClip(props: RendererProps['clip'], clip?: Clip): Clip { const { type, invert, position, rotation, scale } = clip?.objects || { type: (new Array(5)).fill(1), invert: (new Array(5)).fill(false), position: (new Array(5 * 3)).fill(0), rotation: (new Array(5 * 4)).fill(0), scale: (new Array(5 * 3)).fill(1), }; for (let i = 0, il = props.objects.length; i < il; ++i) { const p = props.objects[i]; type[i] = Clipping.Type[p.type]; invert[i] = p.invert; Vec3.toArray(p.position, position, i * 3); Quat.toArray(Quat.setAxisAngle(tmpQuat, p.rotation.axis, degToRad(p.rotation.angle)), rotation, i * 4); Vec3.toArray(p.scale, scale, i * 3); } return { variant: props.variant, objects: { count: props.objects.length, type, invert, position, rotation, scale } }; } namespace Renderer { export function create(ctx: WebGLContext, props: Partial<RendererProps> = {}): Renderer { const { gl, state, stats, extensions: { fragDepth } } = ctx; const p = PD.merge(RendererParams, PD.getDefaultValues(RendererParams), props); const style = getStyle(p.style); const clip = getClip(p.clip); const viewport = Viewport(); const drawingBufferSize = Vec2.create(gl.drawingBufferWidth, gl.drawingBufferHeight); const bgColor = Color.toVec3Normalized(Vec3(), p.backgroundColor); let transparentBackground = false; const nullDepthTexture = createNullTexture(gl); const sharedTexturesList: Textures = [ ['tDepth', nullDepthTexture] ]; const view = Mat4(); const invView = Mat4(); const modelView = Mat4(); const invModelView = Mat4(); const invProjection = Mat4(); const modelViewProjection = Mat4(); const invModelViewProjection = Mat4(); const cameraDir = Vec3(); const viewOffset = Vec2(); const globalUniforms: GlobalUniformValues = { uModel: ValueCell.create(Mat4.identity()), uView: ValueCell.create(view), uInvView: ValueCell.create(invView), uModelView: ValueCell.create(modelView), uInvModelView: ValueCell.create(invModelView), uInvProjection: ValueCell.create(invProjection), uProjection: ValueCell.create(Mat4()), uModelViewProjection: ValueCell.create(modelViewProjection), uInvModelViewProjection: ValueCell.create(invModelViewProjection), uIsOrtho: ValueCell.create(1), uViewOffset: ValueCell.create(viewOffset), uPixelRatio: ValueCell.create(ctx.pixelRatio), uViewport: ValueCell.create(Viewport.toVec4(Vec4(), viewport)), uDrawingBufferSize: ValueCell.create(drawingBufferSize), uCameraPosition: ValueCell.create(Vec3()), uCameraDir: ValueCell.create(cameraDir), uNear: ValueCell.create(1), uFar: ValueCell.create(10000), uFogNear: ValueCell.create(1), uFogFar: ValueCell.create(10000), uFogColor: ValueCell.create(bgColor), uRenderWboit: ValueCell.create(false), uMarkingDepthTest: ValueCell.create(false), uTransparentBackground: ValueCell.create(false), uClipObjectType: ValueCell.create(clip.objects.type), uClipObjectInvert: ValueCell.create(clip.objects.invert), uClipObjectPosition: ValueCell.create(clip.objects.position), uClipObjectRotation: ValueCell.create(clip.objects.rotation), uClipObjectScale: ValueCell.create(clip.objects.scale), // the following are general 'material' uniforms uLightIntensity: ValueCell.create(style.lightIntensity), uAmbientIntensity: ValueCell.create(style.ambientIntensity), uMetalness: ValueCell.create(style.metalness), uRoughness: ValueCell.create(style.roughness), uReflectivity: ValueCell.create(style.reflectivity), uPickingAlphaThreshold: ValueCell.create(p.pickingAlphaThreshold), uInteriorDarkening: ValueCell.create(p.interiorDarkening), uInteriorColorFlag: ValueCell.create(p.interiorColorFlag), uInteriorColor: ValueCell.create(Color.toVec3Normalized(Vec3(), p.interiorColor)), uHighlightColor: ValueCell.create(Color.toVec3Normalized(Vec3(), p.highlightColor)), uSelectColor: ValueCell.create(Color.toVec3Normalized(Vec3(), p.selectColor)), uHighlightStrength: ValueCell.create(p.highlightStrength), uSelectStrength: ValueCell.create(p.selectStrength), uMarkerPriority: ValueCell.create(p.markerPriority), uXrayEdgeFalloff: ValueCell.create(p.xrayEdgeFalloff), }; const globalUniformList = Object.entries(globalUniforms); let globalUniformsNeedUpdate = true; const renderObject = (r: GraphicsRenderable, variant: GraphicsRenderVariant) => { if (r.state.disposed || !r.state.visible || (!r.state.pickable && variant[0] === 'p')) { return; } let definesNeedUpdate = false; if (r.state.noClip) { if (r.values.dClipObjectCount.ref.value !== 0) { ValueCell.update(r.values.dClipObjectCount, 0); definesNeedUpdate = true; } } else { if (r.values.dClipObjectCount.ref.value !== clip.objects.count) { ValueCell.update(r.values.dClipObjectCount, clip.objects.count); definesNeedUpdate = true; } if (r.values.dClipVariant.ref.value !== clip.variant) { ValueCell.update(r.values.dClipVariant, clip.variant); definesNeedUpdate = true; } } if (definesNeedUpdate) r.update(); const program = r.getProgram(variant); if (state.currentProgramId !== program.id) { // console.log('new program') globalUniformsNeedUpdate = true; program.use(); } if (globalUniformsNeedUpdate) { // console.log('globalUniformsNeedUpdate') program.setUniforms(globalUniformList); globalUniformsNeedUpdate = false; } if (r.values.dRenderMode) { // indicates direct-volume // culling done in fragment shader state.disable(gl.CULL_FACE); state.frontFace(gl.CCW); if (variant === 'colorBlended') { // depth test done manually in shader against `depthTexture` // still need to enable when fragDepth can be used to write depth if (r.values.dRenderMode.ref.value === 'volume' || !fragDepth) { state.disable(gl.DEPTH_TEST); state.depthMask(false); } else { state.enable(gl.DEPTH_TEST); state.depthMask(r.values.uAlpha.ref.value === 1.0); } } } else { if (r.values.dDoubleSided) { if (r.values.dDoubleSided.ref.value || r.values.hasReflection.ref.value) { state.disable(gl.CULL_FACE); } else { state.enable(gl.CULL_FACE); } } else { // webgl default state.disable(gl.CULL_FACE); } if (r.values.dFlipSided) { if (r.values.dFlipSided.ref.value) { state.frontFace(gl.CW); state.cullFace(gl.FRONT); } else { state.frontFace(gl.CCW); state.cullFace(gl.BACK); } } else { // webgl default state.frontFace(gl.CCW); state.cullFace(gl.BACK); } } r.render(variant, sharedTexturesList); }; const update = (camera: ICamera) => { ValueCell.update(globalUniforms.uView, camera.view); ValueCell.update(globalUniforms.uInvView, Mat4.invert(invView, camera.view)); ValueCell.update(globalUniforms.uProjection, camera.projection); ValueCell.update(globalUniforms.uInvProjection, Mat4.invert(invProjection, camera.projection)); ValueCell.updateIfChanged(globalUniforms.uIsOrtho, camera.state.mode === 'orthographic' ? 1 : 0); ValueCell.update(globalUniforms.uViewOffset, camera.viewOffset.enabled ? Vec2.set(viewOffset, camera.viewOffset.offsetX * 16, camera.viewOffset.offsetY * 16) : Vec2.set(viewOffset, 0, 0)); ValueCell.update(globalUniforms.uCameraPosition, camera.state.position); ValueCell.update(globalUniforms.uCameraDir, Vec3.normalize(cameraDir, Vec3.sub(cameraDir, camera.state.target, camera.state.position))); ValueCell.updateIfChanged(globalUniforms.uFar, camera.far); ValueCell.updateIfChanged(globalUniforms.uNear, camera.near); ValueCell.updateIfChanged(globalUniforms.uFogFar, camera.fogFar); ValueCell.updateIfChanged(globalUniforms.uFogNear, camera.fogNear); ValueCell.updateIfChanged(globalUniforms.uTransparentBackground, transparentBackground); }; const updateInternal = (group: Scene.Group, camera: ICamera, depthTexture: Texture | null, renderWboit: boolean, markingDepthTest: boolean) => { arrayMapUpsert(sharedTexturesList, 'tDepth', depthTexture || nullDepthTexture); ValueCell.update(globalUniforms.uModel, group.view); ValueCell.update(globalUniforms.uModelView, Mat4.mul(modelView, group.view, camera.view)); ValueCell.update(globalUniforms.uInvModelView, Mat4.invert(invModelView, modelView)); ValueCell.update(globalUniforms.uModelViewProjection, Mat4.mul(modelViewProjection, modelView, camera.projection)); ValueCell.update(globalUniforms.uInvModelViewProjection, Mat4.invert(invModelViewProjection, modelViewProjection)); ValueCell.updateIfChanged(globalUniforms.uRenderWboit, renderWboit); ValueCell.updateIfChanged(globalUniforms.uMarkingDepthTest, markingDepthTest); state.enable(gl.SCISSOR_TEST); state.colorMask(true, true, true, true); const { x, y, width, height } = viewport; gl.viewport(x, y, width, height); gl.scissor(x, y, width, height); globalUniformsNeedUpdate = true; state.currentRenderItemId = -1; }; const renderPick = (group: Scene.Group, camera: ICamera, variant: GraphicsRenderVariant, depthTexture: Texture | null) => { state.disable(gl.BLEND); state.enable(gl.DEPTH_TEST); state.depthMask(true); updateInternal(group, camera, depthTexture, false, false); const { renderables } = group; for (let i = 0, il = renderables.length; i < il; ++i) { if (!renderables[i].state.colorOnly) { renderObject(renderables[i], variant); } } }; const renderDepth = (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => { state.disable(gl.BLEND); state.enable(gl.DEPTH_TEST); state.depthMask(true); updateInternal(group, camera, depthTexture, false, false); const { renderables } = group; for (let i = 0, il = renderables.length; i < il; ++i) { renderObject(renderables[i], 'depth'); } }; const renderMarkingDepth = (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => { state.disable(gl.BLEND); state.enable(gl.DEPTH_TEST); state.depthMask(true); updateInternal(group, camera, depthTexture, false, false); const { renderables } = group; for (let i = 0, il = renderables.length; i < il; ++i) { const r = renderables[i]; if (r.values.markerAverage.ref.value !== 1) { renderObject(renderables[i], 'markingDepth'); } } }; const renderMarkingMask = (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => { state.disable(gl.BLEND); state.enable(gl.DEPTH_TEST); state.depthMask(true); updateInternal(group, camera, depthTexture, false, !!depthTexture); const { renderables } = group; for (let i = 0, il = renderables.length; i < il; ++i) { const r = renderables[i]; if (r.values.markerAverage.ref.value > 0) { renderObject(renderables[i], 'markingMask'); } } }; const renderBlended = (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => { renderBlendedOpaque(group, camera, depthTexture); renderBlendedTransparent(group, camera, depthTexture); }; const renderBlendedOpaque = (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => { state.disable(gl.BLEND); state.enable(gl.DEPTH_TEST); state.depthMask(true); updateInternal(group, camera, depthTexture, false, false); const { renderables } = group; for (let i = 0, il = renderables.length; i < il; ++i) { const r = renderables[i]; if (r.state.opaque) { renderObject(r, 'colorBlended'); } } }; const renderBlendedTransparent = (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => { state.enable(gl.DEPTH_TEST); updateInternal(group, camera, depthTexture, false, false); const { renderables } = group; if (transparentBackground) { state.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); } else { state.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); } state.enable(gl.BLEND); state.depthMask(true); for (let i = 0, il = renderables.length; i < il; ++i) { const r = renderables[i]; if (!r.state.opaque && r.state.writeDepth) { renderObject(r, 'colorBlended'); } } state.depthMask(false); for (let i = 0, il = renderables.length; i < il; ++i) { const r = renderables[i]; if (!r.state.opaque && !r.state.writeDepth) { renderObject(r, 'colorBlended'); } } }; const renderBlendedVolumeOpaque = (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => { state.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); state.enable(gl.BLEND); updateInternal(group, camera, depthTexture, false, false); const { renderables } = group; for (let i = 0, il = renderables.length; i < il; ++i) { const r = renderables[i]; // TODO: simplify, handle in renderable.state??? // uAlpha is updated in "render" so we need to recompute it here const alpha = clamp(r.values.alpha.ref.value * r.state.alphaFactor, 0, 1); if (alpha === 1 && r.values.transparencyAverage.ref.value !== 1 && !r.values.dXrayShaded?.ref.value) { renderObject(r, 'colorBlended'); } } }; const renderBlendedVolumeTransparent = (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => { state.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); state.enable(gl.BLEND); updateInternal(group, camera, depthTexture, false, false); const { renderables } = group; for (let i = 0, il = renderables.length; i < il; ++i) { const r = renderables[i]; // TODO: simplify, handle in renderable.state??? // uAlpha is updated in "render" so we need to recompute it here const alpha = clamp(r.values.alpha.ref.value * r.state.alphaFactor, 0, 1); if (alpha < 1 || r.values.transparencyAverage.ref.value > 0 || r.values.dXrayShaded?.ref.value) { renderObject(r, 'colorBlended'); } } }; const renderWboitOpaque = (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => { state.disable(gl.BLEND); state.enable(gl.DEPTH_TEST); state.depthMask(true); updateInternal(group, camera, depthTexture, false, false); const { renderables } = group; for (let i = 0, il = renderables.length; i < il; ++i) { const r = renderables[i]; // TODO: simplify, handle in renderable.state??? // uAlpha is updated in "render" so we need to recompute it here const alpha = clamp(r.values.alpha.ref.value * r.state.alphaFactor, 0, 1); if (alpha === 1 && r.values.transparencyAverage.ref.value !== 1 && r.values.dRenderMode?.ref.value !== 'volume' && r.values.dPointStyle?.ref.value !== 'fuzzy' && !r.values.dXrayShaded?.ref.value) { renderObject(r, 'colorWboit'); } } }; const renderWboitTransparent = (group: Scene.Group, camera: ICamera, depthTexture: Texture | null) => { updateInternal(group, camera, depthTexture, true, false); const { renderables } = group; for (let i = 0, il = renderables.length; i < il; ++i) { const r = renderables[i]; // TODO: simplify, handle in renderable.state??? // uAlpha is updated in "render" so we need to recompute it here const alpha = clamp(r.values.alpha.ref.value * r.state.alphaFactor, 0, 1); if (alpha < 1 || r.values.transparencyAverage.ref.value > 0 || r.values.dRenderMode?.ref.value === 'volume' || r.values.dPointStyle?.ref.value === 'fuzzy' || !!r.values.uBackgroundColor || r.values.dXrayShaded?.ref.value) { renderObject(r, 'colorWboit'); } } }; return { clear: (toBackgroundColor: boolean) => { state.enable(gl.SCISSOR_TEST); state.enable(gl.DEPTH_TEST); state.colorMask(true, true, true, true); state.depthMask(true); if (transparentBackground) { state.clearColor(0, 0, 0, 0); } else if (toBackgroundColor) { state.clearColor(bgColor[0], bgColor[1], bgColor[2], 1); } else { state.clearColor(1, 1, 1, 1); } gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); }, clearDepth: () => { state.enable(gl.SCISSOR_TEST); state.enable(gl.DEPTH_TEST); state.depthMask(true); gl.clear(gl.DEPTH_BUFFER_BIT); }, update, renderPick, renderDepth, renderMarkingDepth, renderMarkingMask, renderBlended, renderBlendedOpaque, renderBlendedTransparent, renderBlendedVolumeOpaque, renderBlendedVolumeTransparent, renderWboitOpaque, renderWboitTransparent, setProps: (props: Partial<RendererProps>) => { if (props.backgroundColor !== undefined && props.backgroundColor !== p.backgroundColor) { p.backgroundColor = props.backgroundColor; Color.toVec3Normalized(bgColor, p.backgroundColor); ValueCell.update(globalUniforms.uFogColor, Vec3.copy(globalUniforms.uFogColor.ref.value, bgColor)); } if (props.pickingAlphaThreshold !== undefined && props.pickingAlphaThreshold !== p.pickingAlphaThreshold) { p.pickingAlphaThreshold = props.pickingAlphaThreshold; ValueCell.update(globalUniforms.uPickingAlphaThreshold, p.pickingAlphaThreshold); } if (props.interiorDarkening !== undefined && props.interiorDarkening !== p.interiorDarkening) { p.interiorDarkening = props.interiorDarkening; ValueCell.update(globalUniforms.uInteriorDarkening, p.interiorDarkening); } if (props.interiorColorFlag !== undefined && props.interiorColorFlag !== p.interiorColorFlag) { p.interiorColorFlag = props.interiorColorFlag; ValueCell.update(globalUniforms.uInteriorColorFlag, p.interiorColorFlag); } if (props.interiorColor !== undefined && props.interiorColor !== p.interiorColor) { p.interiorColor = props.interiorColor; ValueCell.update(globalUniforms.uInteriorColor, Color.toVec3Normalized(globalUniforms.uInteriorColor.ref.value, p.interiorColor)); } if (props.highlightColor !== undefined && props.highlightColor !== p.highlightColor) { p.highlightColor = props.highlightColor; ValueCell.update(globalUniforms.uHighlightColor, Color.toVec3Normalized(globalUniforms.uHighlightColor.ref.value, p.highlightColor)); } if (props.selectColor !== undefined && props.selectColor !== p.selectColor) { p.selectColor = props.selectColor; ValueCell.update(globalUniforms.uSelectColor, Color.toVec3Normalized(globalUniforms.uSelectColor.ref.value, p.selectColor)); } if (props.highlightStrength !== undefined && props.highlightStrength !== p.highlightStrength) { p.highlightStrength = props.highlightStrength; ValueCell.update(globalUniforms.uHighlightStrength, p.highlightStrength); } if (props.selectStrength !== undefined && props.selectStrength !== p.selectStrength) { p.selectStrength = props.selectStrength; ValueCell.update(globalUniforms.uSelectStrength, p.selectStrength); } if (props.markerPriority !== undefined && props.markerPriority !== p.markerPriority) { p.markerPriority = props.markerPriority; ValueCell.update(globalUniforms.uMarkerPriority, p.markerPriority); } if (props.xrayEdgeFalloff !== undefined && props.xrayEdgeFalloff !== p.xrayEdgeFalloff) { p.xrayEdgeFalloff = props.xrayEdgeFalloff; ValueCell.update(globalUniforms.uXrayEdgeFalloff, p.xrayEdgeFalloff); } if (props.style !== undefined) { p.style = props.style; Object.assign(style, getStyle(props.style)); ValueCell.updateIfChanged(globalUniforms.uLightIntensity, style.lightIntensity); ValueCell.updateIfChanged(globalUniforms.uAmbientIntensity, style.ambientIntensity); ValueCell.updateIfChanged(globalUniforms.uMetalness, style.metalness); ValueCell.updateIfChanged(globalUniforms.uRoughness, style.roughness); ValueCell.updateIfChanged(globalUniforms.uReflectivity, style.reflectivity); } if (props.clip !== undefined && !deepEqual(props.clip, p.clip)) { p.clip = props.clip; Object.assign(clip, getClip(props.clip, clip)); ValueCell.update(globalUniforms.uClipObjectPosition, clip.objects.position); ValueCell.update(globalUniforms.uClipObjectRotation, clip.objects.rotation); ValueCell.update(globalUniforms.uClipObjectScale, clip.objects.scale); ValueCell.update(globalUniforms.uClipObjectType, clip.objects.type); } }, setViewport: (x: number, y: number, width: number, height: number) => { gl.viewport(x, y, width, height); gl.scissor(x, y, width, height); if (x !== viewport.x || y !== viewport.y || width !== viewport.width || height !== viewport.height) { Viewport.set(viewport, x, y, width, height); ValueCell.update(globalUniforms.uViewport, Vec4.set(globalUniforms.uViewport.ref.value, x, y, width, height)); } }, setTransparentBackground: (value: boolean) => { transparentBackground = value; }, setDrawingBufferSize: (width: number, height: number) => { if (width !== drawingBufferSize[0] || height !== drawingBufferSize[1]) { ValueCell.update(globalUniforms.uDrawingBufferSize, Vec2.set(drawingBufferSize, width, height)); } }, setPixelRatio: (value: number) => { ValueCell.update(globalUniforms.uPixelRatio, value); }, props: p, get stats(): RendererStats { return { programCount: ctx.stats.resourceCounts.program, shaderCount: ctx.stats.resourceCounts.shader, attributeCount: ctx.stats.resourceCounts.attribute, elementsCount: ctx.stats.resourceCounts.elements, framebufferCount: ctx.stats.resourceCounts.framebuffer, renderbufferCount: ctx.stats.resourceCounts.renderbuffer, textureCount: ctx.stats.resourceCounts.texture, vertexArrayCount: ctx.stats.resourceCounts.vertexArray, drawCount: stats.drawCount, instanceCount: stats.instanceCount, instancedDrawCount: stats.instancedDrawCount, }; }, dispose: () => { // TODO } }; } } export { Renderer };
the_stack
import type { AstNode, ColorTokenType, IntegerNode, SymbolBaseNode } from '@spyglassmc/core' import { atArray, CommentNode, FloatNode, ResourceLocationNode, StringNode } from '@spyglassmc/core' export interface ModuleNode extends AstNode { type: 'mcdoc:module', children: TopLevelNode[], } export const ModuleNode = Object.freeze({ is(node: AstNode | undefined): node is ModuleNode { return (node as ModuleNode | undefined)?.type === 'mcdoc:module' }, }) export type TopLevelNode = | CommentNode | DispatchStatementNode | EnumNode | InjectionNode | StructNode | TypeAliasNode | UseStatementNode export const TopLevelNode = Object.freeze({ is(node: AstNode | undefined): node is TopLevelNode { return ( CommentNode.is(node) || DispatchStatementNode.is(node) || EnumNode.is(node) || InjectionNode.is(node) || StructNode.is(node) || TypeAliasNode.is(node) || UseStatementNode.is(node) ) }, }) export interface DispatchStatementNode extends AstNode { type: 'mcdoc:dispatch_statement', children: (CommentNode | AttributeNode | LiteralNode | ResourceLocationNode | IndexBodyNode | TypeNode)[] } export const DispatchStatementNode = Object.freeze({ destruct(node: DispatchStatementNode): { attributes: AttributeNode[], location?: ResourceLocationNode, index?: IndexBodyNode, target?: TypeNode, } { return { attributes: node.children.filter(AttributeNode.is), location: node.children.find(ResourceLocationNode.is), index: node.children.find(IndexBodyNode.is), target: node.children.find(TypeNode.is), } }, is(node: AstNode | undefined): node is DispatchStatementNode { return (node as DispatchStatementNode | undefined)?.type === 'mcdoc:dispatch_statement' }, }) export interface LiteralNode extends AstNode { type: 'mcdoc:literal', value: string, colorTokenType?: ColorTokenType, } export const LiteralNode = Object.freeze({ is(node: AstNode | undefined): node is LiteralNode { return (node as LiteralNode | undefined)?.type === 'mcdoc:literal' }, }) export interface IndexBodyNode extends AstNode { type: 'mcdoc:index_body', children: (CommentNode | IndexNode)[], } export const IndexBodyNode = Object.freeze({ destruct(node: IndexBodyNode): { parallelIndices: IndexNode[], } { return { parallelIndices: node.children.filter(IndexNode.is), } }, is(node: AstNode | undefined): node is IndexBodyNode { return (node as IndexBodyNode | undefined)?.type === 'mcdoc:index_body' }, }) export type IndexNode = StaticIndexNode | DynamicIndexNode export const IndexNode = Object.freeze({ is(node: AstNode | undefined): node is IndexNode { return StaticIndexNode.is(node) || DynamicIndexNode.is(node) }, }) export type StaticIndexNode = LiteralNode | IdentifierNode | StringNode | ResourceLocationNode export const StaticIndexNode = Object.freeze({ is(node: AstNode | undefined): node is StaticIndexNode { return LiteralNode.is(node) || IdentifierNode.is(node) || StringNode.is(node) || ResourceLocationNode.is(node) }, }) export interface IdentifierNode extends SymbolBaseNode { type: 'mcdoc:identifier', } export const IdentifierNode = Object.freeze({ is(node: AstNode | undefined): node is IdentifierNode { return (node as IdentifierNode | undefined)?.type === 'mcdoc:identifier' }, }) export interface DynamicIndexNode extends AstNode { type: 'mcdoc:dynamic_index', children: (CommentNode | AccessorKeyNode)[], } export const DynamicIndexNode = Object.freeze({ destruct(node: DynamicIndexNode): { keys: AccessorKeyNode[], } { return { keys: node.children.filter(AccessorKeyNode.is), } }, is(node: AstNode | undefined): node is DynamicIndexNode { return (node as DynamicIndexNode | undefined)?.type === 'mcdoc:dynamic_index' }, }) export type AccessorKeyNode = LiteralNode | IdentifierNode | StringNode export const AccessorKeyNode = Object.freeze({ is(node: AstNode | undefined): node is AccessorKeyNode { return LiteralNode.is(node) || IdentifierNode.is(node) || StringNode.is(node) }, }) export type TypeNode = | AnyTypeNode | BooleanTypeNode | StringTypeNode | LiteralTypeNode | NumericTypeNode | PrimitiveArrayTypeNode | ListTypeNode | TupleTypeNode | EnumNode | StructNode | ReferenceTypeNode | DispatcherTypeNode | UnionTypeNode export const TypeNode = Object.freeze({ is(node: AstNode | undefined): node is TypeNode { return ( AnyTypeNode.is(node) || BooleanTypeNode.is(node) || StringTypeNode.is(node) || LiteralTypeNode.is(node) || NumericTypeNode.is(node) || PrimitiveArrayTypeNode.is(node) || ListTypeNode.is(node) || TupleTypeNode.is(node) || EnumNode.is(node) || StructNode.is(node) || PathNode.is(node) || DispatcherTypeNode.is(node) || UnionTypeNode.is(node) ) }, }) export interface TypeBaseNode<CN extends AstNode> extends AstNode { type: `mcdoc:${string}`, children: (CommentNode | AttributeNode | IndexBodyNode | CN)[] } export const TypeBaseNode = Object.freeze({ destruct(node: TypeBaseNode<any>): { attributes: AttributeNode[], indices: IndexBodyNode[], } { return { attributes: node.children.filter(AttributeNode.is), indices: node.children.filter(IndexBodyNode.is), } }, }) export interface AttributeNode extends AstNode { type: 'mcdoc:attribute', children: (CommentNode | IdentifierNode | AttributeValueNode)[], } export const AttributeNode = Object.freeze({ destruct(node: AttributeNode): { name: IdentifierNode, value: AttributeValueNode, } { return { name: node.children.find(IdentifierNode.is)!, value: node.children.find(AttributeValueNode.is)!, } }, is(node: AstNode | undefined): node is AttributeNode { return (node as AttributeNode | undefined)?.type === 'mcdoc:attribute' }, }) export type AttributeValueNode = TypeNode | AttributeTreeNode export const AttributeValueNode = Object.freeze({ is(node: AstNode | undefined): node is AttributeValueNode { return TypeNode.is(node) || AttributeTreeNode.is(node) }, }) export interface AttributeTreeNode extends AstNode { type: 'mcdoc:attribute/tree', children: (CommentNode | AttributeTreePosValuesNode | AttributeTreeNamedValuesNode)[], delim: '(' | '[' | '{', } export const AttributeTreeNode = Object.freeze({ destruct(node: AttributeTreeNode): { positional?: AttributeTreePosValuesNode, named?: AttributeTreeNamedValuesNode, } { return { positional: node.children.find(AttributeTreePosValuesNode.is), named: node.children.find(AttributeTreeNamedValuesNode.is), } }, is(node: AstNode | undefined): node is AttributeTreeNode { return (node as AttributeTreeNode | undefined)?.type === 'mcdoc:attribute/tree' }, }) export interface AttributeTreePosValuesNode extends AstNode { type: 'mcdoc:attribute/tree/pos', children: (CommentNode | AttributeValueNode)[], } export const AttributeTreePosValuesNode = Object.freeze({ destruct(node: AttributeTreePosValuesNode): { values: AttributeValueNode[], } { return { values: node.children.filter(AttributeValueNode.is), } }, is(node: AstNode | undefined): node is AttributeTreePosValuesNode { return (node as AttributeTreePosValuesNode | undefined)?.type === 'mcdoc:attribute/tree/pos' }, }) export interface AttributeTreeNamedValuesNode extends AstNode { type: 'mcdoc:attribute/tree/named', children: (CommentNode | IdentifierNode | StringNode | AttributeValueNode)[], } export const AttributeTreeNamedValuesNode = Object.freeze({ destruct(node: AttributeTreeNamedValuesNode): { values: AttributeTreeNamedKeyValuePair[], } { const ans: { values: AttributeTreeNamedKeyValuePair[] } = { values: [], } let key: IdentifierNode | StringNode | undefined for (const child of node.children) { if (CommentNode.is(child)) { continue } if (IdentifierNode.is(child) || StringNode.is(child)) { key = child } else if (key) { ans.values.push({ key, value: child }) key = undefined } } return ans }, is(node: AstNode | undefined): node is AttributeTreeNamedValuesNode { return (node as AttributeTreeNamedValuesNode | undefined)?.type === 'mcdoc:attribute/tree/named' }, }) export interface AttributeTreeNamedKeyValuePair { key: IdentifierNode | StringNode, value: AttributeValueNode, } export interface AnyTypeNode extends TypeBaseNode<LiteralNode> { type: 'mcdoc:type/any', } export const AnyTypeNode = Object.freeze({ is(node: AstNode | undefined): node is AnyTypeNode { return (node as AnyTypeNode | undefined)?.type === 'mcdoc:type/any' }, }) export interface BooleanTypeNode extends TypeBaseNode<LiteralNode> { type: 'mcdoc:type/boolean', } export const BooleanTypeNode = Object.freeze({ is(node: AstNode | undefined): node is BooleanTypeNode { return (node as BooleanTypeNode | undefined)?.type === 'mcdoc:type/boolean' }, }) export interface IntRangeNode extends AstNode { type: 'mcdoc:int_range', children: (IntegerNode | LiteralNode)[], } export const IntRangeNode = Object.freeze({ destruct(node: IntRangeNode): { min?: IntegerNode, max?: IntegerNode, } { return destructRangeNode(node) }, is(node: AstNode | undefined): node is IntRangeNode { return (node as IntRangeNode | undefined)?.type === 'mcdoc:int_range' }, }) export interface LiteralTypeNode extends TypeBaseNode<LiteralTypeValueNode> { type: 'mcdoc:type/literal', } export const LiteralTypeNode = Object.freeze({ destruct(node: LiteralTypeNode): { value: LiteralTypeValueNode, } { return { value: node.children.find(LiteralTypeValueNode.is)!, } }, is(node: AstNode | undefined): node is LiteralTypeNode { return (node as LiteralTypeNode | undefined)?.type === 'mcdoc:type/literal' }, }) export type LiteralTypeValueNode = LiteralNode | TypedNumberNode | StringNode export const LiteralTypeValueNode = Object.freeze({ is(node: AstNode | undefined): node is LiteralTypeValueNode { return LiteralNode.is(node) || TypedNumberNode.is(node) || StringNode.is(node) }, }) export interface TypedNumberNode extends AstNode { type: 'mcdoc:typed_number', children: (FloatNode | LiteralNode)[], } export const TypedNumberNode = Object.freeze({ destruct(node: TypedNumberNode): { value: FloatNode, suffix?: LiteralNode, } { return { value: node.children.find(FloatNode.is)!, suffix: node.children.find(LiteralNode.is), } }, is(node: AstNode | undefined): node is TypedNumberNode { return (node as TypedNumberNode | undefined)?.type === 'mcdoc:typed_number' }, }) export interface NumericTypeNode extends TypeBaseNode<LiteralNode | FloatRangeNode | IntRangeNode> { type: 'mcdoc:type/numeric_type' } export const NumericTypeNode = Object.freeze({ destruct(node: NumericTypeNode): { numericKind: LiteralNode, valueRange?: FloatRangeNode | IntRangeNode, } { return { numericKind: node.children.find(LiteralNode.is)!, valueRange: node.children.find(FloatRangeNode.is) || node.children.find(IntRangeNode.is), } }, is(node: AstNode | undefined): node is NumericTypeNode { return (node as NumericTypeNode | undefined)?.type === 'mcdoc:type/numeric_type' }, }) function destructRangeNode<N extends FloatRangeNode | IntRangeNode>(node: N): { min?: N extends FloatRangeNode ? FloatNode : IntegerNode, max?: N extends FloatRangeNode ? FloatNode : IntegerNode, } { let min: (FloatNode & IntegerNode) | undefined let max: (FloatNode & IntegerNode) | undefined if (node.children.length === 1) { // a min = max = node.children[0] as FloatNode & IntegerNode } else if (node.children.length === 3) { // a..b min = node.children[0] as FloatNode & IntegerNode max = node.children[2] as FloatNode & IntegerNode } else if (LiteralNode.is(node.children[0])) { // ..b max = node.children[1] as FloatNode & IntegerNode } else { // a.. min = node.children[1] as FloatNode & IntegerNode } return { min, max, } } export interface FloatRangeNode extends AstNode { type: 'mcdoc:float_range', children: (FloatNode | LiteralNode)[], } export const FloatRangeNode = Object.freeze({ destruct(node: FloatRangeNode): { min?: FloatNode, max?: FloatNode, } { return destructRangeNode(node) }, is(node: AstNode | undefined): node is FloatRangeNode { return (node as FloatRangeNode | undefined)?.type === 'mcdoc:float_range' }, }) export interface PrimitiveArrayTypeNode extends TypeBaseNode<LiteralNode | IntRangeNode> { type: 'mcdoc:type/primitive_array', } export const PrimitiveArrayTypeNode = Object.freeze({ destruct(node: PrimitiveArrayTypeNode): { arrayKind: LiteralNode, lengthRange?: IntRangeNode, valueRange?: IntRangeNode, } { let lengthRange: IntRangeNode | undefined let valueRange: IntRangeNode | undefined let afterBrackets = false for (const child of node.children) { if (LiteralNode.is(child) && child.value === '[]') { afterBrackets = true } else if (IntRangeNode.is(child)) { if (afterBrackets) { lengthRange = child } else { valueRange = child } } } return { arrayKind: node.children.find(LiteralNode.is)!, lengthRange, valueRange, } }, is(node: AstNode | undefined): node is PrimitiveArrayTypeNode { return (node as PrimitiveArrayTypeNode | undefined)?.type === 'mcdoc:type/primitive_array' }, }) export interface ListTypeNode extends TypeBaseNode<TypeNode | IntRangeNode> { type: 'mcdoc:type/list', } export const ListTypeNode = Object.freeze({ destruct(node: ListTypeNode): { item: TypeNode, lengthRange?: IntRangeNode, } { return { item: node.children.find(TypeNode.is)!, lengthRange: node.children.find(IntRangeNode.is), } }, is(node: AstNode | undefined): node is ListTypeNode { return (node as ListTypeNode | undefined)?.type === 'mcdoc:type/list' }, }) export interface StringTypeNode extends TypeBaseNode<LiteralNode | IntRangeNode> { type: 'mcdoc:type/string', } export const StringTypeNode = Object.freeze({ destruct(node: StringTypeNode): { lengthRange?: IntRangeNode, } { return { lengthRange: node.children.find(IntRangeNode.is), } }, is(node: AstNode | undefined): node is StringTypeNode { return (node as StringTypeNode | undefined)?.type === 'mcdoc:type/string' }, }) export interface TupleTypeNode extends TypeBaseNode<TypeNode> { type: 'mcdoc:type/tuple', } export const TupleTypeNode = Object.freeze({ destruct(node: TupleTypeNode): { items: TypeNode[], } { return { items: node.children.filter(TypeNode.is), } }, is(node: AstNode | undefined): node is TupleTypeNode { return (node as TupleTypeNode | undefined)?.type === 'mcdoc:type/tuple' }, }) export interface EnumNode extends TypeBaseNode<DocCommentsNode | LiteralNode | IdentifierNode | EnumBlockNode> { type: 'mcdoc:enum', } const EnumKinds = new Set(['byte', 'short', 'int', 'long', 'float', 'double', 'string'] as const) export type EnumKind = typeof EnumKinds extends Set<infer V> ? V : never export const EnumNode = Object.freeze({ kinds: EnumKinds, destruct(node: EnumNode): { block: EnumBlockNode, docComments?: DocCommentsNode, enumKind?: EnumKind, identifier?: IdentifierNode, } { return { block: node.children.find(EnumBlockNode.is)!, docComments: node.children.find(DocCommentsNode.is), enumKind: getEnumKind(node), identifier: node.children.find(IdentifierNode.is), } function getEnumKind(node: EnumNode): EnumKind | undefined { for (const literal of node.children.filter(LiteralNode.is)) { if (EnumKinds.has(literal.value as EnumKind)) { return literal.value as EnumKind } } return undefined } }, is(node: AstNode | undefined): node is EnumNode { return (node as EnumNode | undefined)?.type === 'mcdoc:enum' }, }) export interface DocCommentsNode extends AstNode { type: 'mcdoc:doc_comments', children: CommentNode[], } export const DocCommentsNode = Object.freeze({ /** * @returns The text content of this doc comment block. */ asText(node: DocCommentsNode | undefined): string | undefined { if (!node) { return undefined } let comments = node.children.map(doc => doc.comment) // If every comment contains a leading space or is empty, stripe the leading spaces off. // e.g. /// This is an example doc comment. // /// // /// Another line. // should be converted to "This is an example doc comment.\n\nAnother line." if (comments.every(s => s.length === 0 || s.startsWith(' '))) { comments = comments.map(s => s.slice(1)) } return comments.join('\n') }, is(node: AstNode | undefined): node is DocCommentsNode { return (node as DocCommentsNode | undefined)?.type === 'mcdoc:doc_comments' }, }) export interface EnumBlockNode extends AstNode { type: 'mcdoc:enum/block', children: (CommentNode | EnumFieldNode)[], } export const EnumBlockNode = Object.freeze({ destruct(node: EnumBlockNode): { fields: EnumFieldNode[], } { return { fields: node.children.filter(EnumFieldNode.is), } }, is(node: AstNode | undefined): node is EnumBlockNode { return (node as EnumBlockNode | undefined)?.type === 'mcdoc:enum/block' }, }) export interface EnumFieldNode extends AstNode { type: 'mcdoc:enum/field', children: (CommentNode | PrelimNode | IdentifierNode | EnumValueNode)[], } export const EnumFieldNode = Object.freeze({ destruct(node: EnumFieldNode): { attributes: AttributeNode[], identifier: IdentifierNode, value: EnumValueNode, } { return { attributes: node.children.filter(AttributeNode.is), identifier: node.children.find(IdentifierNode.is)!, value: node.children.find(EnumValueNode.is)!, } }, is(node: AstNode | undefined): node is EnumFieldNode { return (node as EnumFieldNode | undefined)?.type === 'mcdoc:enum/field' }, }) export type EnumValueNode = TypedNumberNode | StringNode export const EnumValueNode = Object.freeze({ is(node: AstNode | undefined): node is EnumValueNode { return TypedNumberNode.is(node) || StringNode.is(node) }, }) export type PrelimNode = AttributeNode | DocCommentsNode export const PrelimNode = Object.freeze({ is(node: AstNode | undefined): node is PrelimNode { return AttributeNode.is(node) || DocCommentsNode.is(node) }, }) export interface StructNode extends TypeBaseNode<DocCommentsNode | LiteralNode | IdentifierNode | StructBlockNode> { type: 'mcdoc:struct', } export const StructNode = Object.freeze({ destruct(node: StructNode): { block: StructBlockNode, docComments?: DocCommentsNode, identifier?: IdentifierNode, } { return { block: node.children.find(StructBlockNode.is)!, docComments: node.children.find(DocCommentsNode.is), identifier: node.children.find(IdentifierNode.is), } }, is(node: AstNode | undefined): node is StructNode { return (node as StructNode | undefined)?.type === 'mcdoc:struct' }, }) export interface ReferenceTypeNode extends TypeBaseNode<PathNode | TypeNode> { type: 'mcdoc:type/reference', } export const ReferenceTypeNode = Object.freeze({ destruct(node: ReferenceTypeNode): { path: PathNode, typeParameters: TypeNode[], } { return { path: node.children.find(PathNode.is)!, typeParameters: node.children.filter(TypeNode.is), } }, is(node: AstNode | undefined): node is ReferenceTypeNode { return (node as ReferenceTypeNode | undefined)?.type === 'mcdoc:type/reference' }, }) export interface TypeParamBlockNode extends AstNode { type: 'mcdoc:type_param_block', children: (CommentNode | TypeParamNode)[], } export const TypeParamBlockNode = Object.freeze({ destruct(node: TypeParamBlockNode): { params: TypeParamNode[], } { return { params: node.children.filter(TypeParamNode.is), } }, is(node: AstNode | undefined): node is TypeParamBlockNode { return (node as TypeParamBlockNode | undefined)?.type === 'mcdoc:type_param_block' }, }) export interface TypeParamNode extends AstNode { type: 'mcdoc:type_param', children: (CommentNode | IdentifierNode | LiteralNode | PathNode)[], } export const TypeParamNode = Object.freeze({ destruct(node: TypeParamNode): { constraint?: PathNode, identifier: IdentifierNode, } { return { constraint: node.children.find(PathNode.is), identifier: node.children.find(IdentifierNode.is)!, } }, is(node: AstNode | undefined): node is TypeParamNode { return (node as TypeParamNode | undefined)?.type === 'mcdoc:type_param' }, }) export interface PathNode extends AstNode { type: 'mcdoc:path', children: (LiteralNode | IdentifierNode)[], isAbsolute?: boolean, } export const PathNode = Object.freeze({ destruct(node: PathNode | undefined): { children: (LiteralNode | IdentifierNode)[], isAbsolute?: boolean, lastIdentifier?: IdentifierNode, } { const lastChild = atArray(node?.children, -1) return { children: node?.children ?? [], isAbsolute: node?.isAbsolute, lastIdentifier: IdentifierNode.is(lastChild) ? lastChild : undefined, } }, is(node: AstNode | undefined): node is PathNode { return (node as PathNode | undefined)?.type === 'mcdoc:path' }, }) export interface StructBlockNode extends AstNode { type: 'mcdoc:struct/block', children: (CommentNode | StructFieldNode)[], } export const StructBlockNode = Object.freeze({ destruct(node: StructBlockNode): { fields: StructFieldNode[], } { return { fields: node.children.filter(StructFieldNode.is), } }, is(node: AstNode | undefined): node is StructBlockNode { return (node as StructBlockNode | undefined)?.type === 'mcdoc:struct/block' }, }) export type StructFieldNode = StructPairFieldNode | StructSpreadFieldNode export const StructFieldNode = Object.freeze({ is(node: AstNode | undefined): node is StructFieldNode { return StructPairFieldNode.is(node) || StructSpreadFieldNode.is(node) }, }) export interface StructPairFieldNode extends AstNode { type: 'mcdoc:struct/field/pair', children: (CommentNode | PrelimNode | StructKeyNode | TypeNode)[], isOptional?: boolean, } export const StructPairFieldNode = Object.freeze({ destruct(node: StructPairFieldNode): { attributes: AttributeNode[], key: StructKeyNode, type: TypeNode, } { return { attributes: node.children.filter(AttributeNode.is), key: node.children.find(StructKeyNode.is)!, type: node.children.find(TypeNode.is)!, } }, is(node: AstNode | undefined): node is StructPairFieldNode { return (node as StructPairFieldNode | undefined)?.type === 'mcdoc:struct/field/pair' }, }) export type StructKeyNode = StringNode | IdentifierNode | StructMapKeyNode export const StructKeyNode = Object.freeze({ is(node: AstNode | undefined): node is StructKeyNode { return StringNode.is(node) || IdentifierNode.is(node) || StructMapKeyNode.is(node) }, }) export interface StructMapKeyNode extends AstNode { type: 'mcdoc:struct/map_key', children: (CommentNode | TypeNode)[], } export const StructMapKeyNode = Object.freeze({ destruct(node: StructMapKeyNode): { type: TypeNode, } { return { type: node.children.find(TypeNode.is)!, } }, is(node: AstNode | undefined): node is StructMapKeyNode { return (node as StructMapKeyNode | undefined)?.type === 'mcdoc:struct/map_key' }, }) export interface StructSpreadFieldNode extends AstNode { type: 'mcdoc:struct/field/spread', children: (CommentNode | AttributeNode | TypeNode)[], } export const StructSpreadFieldNode = Object.freeze({ destruct(node: StructSpreadFieldNode): { attributes: AttributeNode[], type: TypeNode, } { return { attributes: node.children.filter(AttributeNode.is), type: node.children.find(TypeNode.is)!, } }, is(node: AstNode | undefined): node is StructSpreadFieldNode { return (node as StructSpreadFieldNode | undefined)?.type === 'mcdoc:struct/field/spread' }, }) export interface DispatcherTypeNode extends TypeBaseNode<ResourceLocationNode | IndexBodyNode> { type: 'mcdoc:type/dispatcher', } export const DispatcherTypeNode = Object.freeze({ destruct(node: DispatcherTypeNode): { location: ResourceLocationNode, index: IndexBodyNode, } { return { location: node.children.find(ResourceLocationNode.is)!, index: node.children.find(IndexBodyNode.is)!, } }, is(node: AstNode | undefined): node is DispatcherTypeNode { return (node as DispatcherTypeNode | undefined)?.type === 'mcdoc:type/dispatcher' }, }) export interface UnionTypeNode extends TypeBaseNode<TypeNode> { type: 'mcdoc:type/union', } export const UnionTypeNode = Object.freeze({ destruct(node: UnionTypeNode): { members: TypeNode[], } { return { members: node.children.filter(TypeNode.is), } }, is(node: AstNode | undefined): node is UnionTypeNode { return (node as UnionTypeNode | undefined)?.type === 'mcdoc:type/union' }, }) export interface InjectionNode extends AstNode { type: 'mcdoc:injection', children: (CommentNode | LiteralNode | InjectionContentNode)[] } export const InjectionNode = Object.freeze({ destruct(node: InjectionNode): { injection: InjectionContentNode, } { return { injection: node.children.find(InjectionContentNode.is)!, } }, is(node: AstNode | undefined): node is InjectionNode { return (node as InjectionNode | undefined)?.type === 'mcdoc:injection' }, }) export type InjectionContentNode = EnumInjectionNode | StructInjectionNode export const InjectionContentNode = Object.freeze({ is(node: AstNode | undefined): node is InjectionContentNode { return EnumInjectionNode.is(node) || StructInjectionNode.is(node) }, }) export interface EnumInjectionNode extends AstNode { type: 'mcdoc:injection/enum', children: (CommentNode | LiteralNode | PathNode | EnumBlockNode)[], } export const EnumInjectionNode = Object.freeze({ is(node: AstNode | undefined): node is EnumInjectionNode { return (node as EnumInjectionNode | undefined)?.type === 'mcdoc:injection/enum' }, }) export interface StructInjectionNode extends AstNode { type: 'mcdoc:injection/struct', children: (CommentNode | LiteralNode | PathNode | StructBlockNode)[], } export const StructInjectionNode = Object.freeze({ is(node: AstNode | undefined): node is StructInjectionNode { return (node as StructInjectionNode | undefined)?.type === 'mcdoc:injection/struct' }, }) export interface TypeAliasNode extends AstNode { type: 'mcdoc:type_alias', children: (CommentNode | DocCommentsNode | LiteralNode | IdentifierNode | TypeParamBlockNode | TypeNode)[], } export const TypeAliasNode = Object.freeze({ destruct(node: TypeAliasNode): { docComments?: DocCommentsNode, identifier?: IdentifierNode, typeParams?: TypeParamBlockNode, rhs?: TypeNode, } { return { docComments: node.children.find(DocCommentsNode.is), identifier: node.children.find(IdentifierNode.is), typeParams: node.children.find(TypeParamBlockNode.is), rhs: node.children.find(TypeNode.is), } }, is(node: AstNode | undefined): node is TypeAliasNode { return (node as TypeAliasNode | undefined)?.type === 'mcdoc:type_alias' }, }) export interface UseStatementNode extends AstNode { type: 'mcdoc:use_statement', children: (CommentNode | LiteralNode | PathNode | IdentifierNode)[] } export const UseStatementNode = Object.freeze({ destruct(node: UseStatementNode): { binding?: IdentifierNode, path?: PathNode, } { return { binding: node.children.find(IdentifierNode.is), path: node.children.find(PathNode.is), } }, is(node: AstNode | undefined): node is UseStatementNode { return (node as UseStatementNode | undefined)?.type === 'mcdoc:use_statement' }, })
the_stack
import React from 'react'; import { fireEvent, render } from '@testing-library/react'; import Select, { SelectProps } from './Select'; import SvgSmileyHappy from '@itwin/itwinui-icons-react/cjs/icons/SmileyHappy'; import { MenuItem } from '../Menu'; function assertSelect( select: HTMLElement, { text = '', isPlaceholderVisible = false, hasIcon = false } = {}, ) { expect(select).toBeTruthy(); expect(select.getAttribute('aria-expanded')).toEqual('false'); const selectButton = select.querySelector( '.iui-select-button', ) as HTMLElement; expect(selectButton).toBeTruthy(); expect(selectButton.classList.contains('iui-placeholder')).toBe( isPlaceholderVisible, ); expect(selectButton.textContent).toEqual(text); expect(!!selectButton.querySelector('.iui-icon')).toBe(hasIcon); } function assertMenu( menu: HTMLUListElement, { maxHeight = '300px', hasIcon = false, selectedIndex = -1, disabledIndex = -1, } = {}, ) { expect(menu).toBeTruthy(); expect(menu.getAttribute('role')).toEqual('listbox'); expect(menu.style.maxHeight).toEqual(maxHeight); expect(menu.classList).toContain('iui-scroll'); const menuItems = menu.querySelectorAll('.iui-menu-item'); expect(menuItems.length).toBe(3); menuItems.forEach((item, index) => { expect(item.textContent).toContain(`Test${index}`); expect(!!item.querySelector('.iui-icon')).toBe(hasIcon); expect(item.classList.contains('iui-active')).toBe(selectedIndex === index); expect(item.classList.contains('iui-disabled')).toBe( disabledIndex === index, ); }); } function renderComponent(props?: Partial<SelectProps<number>>) { return render( <Select<number> options={[...new Array(3)].map((_, index) => ({ label: `Test${index}`, value: index, }))} {...props} />, ); } beforeEach(() => { jest.clearAllMocks(); }); it('should render empty select', () => { const { container } = renderComponent(); const select = container.querySelector('.iui-select') as HTMLElement; assertSelect(select); }); it('should show placeholder', () => { const { container } = renderComponent({ placeholder: 'TestPlaceholder' }); const select = container.querySelector('.iui-select') as HTMLElement; assertSelect(select, { text: 'TestPlaceholder', isPlaceholderVisible: true }); }); it('should show value inside select', () => { const { container } = renderComponent({ placeholder: 'TestPlaceholder', value: 1, }); const select = container.querySelector('.iui-select') as HTMLElement; assertSelect(select, { text: 'Test1' }); }); it('should show value with icon inside select', () => { const { container } = renderComponent({ value: 1, options: [...new Array(3)].map((_, index) => ({ label: `Test${index}`, value: index, icon: <SvgSmileyHappy />, })), }); const select = container.querySelector('.iui-select') as HTMLElement; assertSelect(select, { text: 'Test1', hasIcon: true }); }); it('should render disabled select', () => { const mockedFn = jest.fn(); const { container } = renderComponent({ disabled: true, onChange: mockedFn, }); const selectButton = container.querySelector( '.iui-select-button.iui-disabled', ) as HTMLElement; expect(selectButton).toBeTruthy(); selectButton.click(); expect(mockedFn).not.toHaveBeenCalled(); expect(selectButton.getAttribute('tabIndex')).toBeNull(); fireEvent.keyDown(selectButton, 'Spacebar'); expect(document.querySelector('.iui-menu')).toBeNull(); }); it('should set focus on select and call onBlur', () => { const onBlur = jest.fn(); const { container } = renderComponent({ setFocus: true, onBlur }); const select = container.querySelector('.iui-select') as HTMLElement; assertSelect(select); const selectButton = container.querySelector( '.iui-select-button', ) as HTMLElement; expect(selectButton).toBeTruthy(); expect(selectButton).toHaveFocus(); expect(selectButton.getAttribute('tabIndex')).toBe('0'); expect(onBlur).not.toHaveBeenCalled(); fireEvent.click(selectButton); expect(selectButton).not.toHaveFocus(); expect(onBlur).toHaveBeenCalled(); }); it('should render select with custom className', () => { const { container } = renderComponent({ className: 'test-className' }); const select = container.querySelector('.iui-select') as HTMLElement; assertSelect(select); expect(select.classList).toContain('test-className'); }); it('should render select with custom style', () => { const { container } = renderComponent({ style: { color: 'red' } }); const select = container.querySelector('.iui-select') as HTMLElement; assertSelect(select); expect(select.style.color).toEqual('red'); }); it('should use custom render for selected item', () => { const { container } = render( <Select value='red' selectedItemRenderer={(option) => ( <span style={{ color: option?.value }}>{option?.label}</span> )} options={[ { value: 'yellow', label: 'Yellow' }, { value: 'green', label: 'Green' }, { value: 'red', label: 'Red' }, ]} />, ); const select = container.querySelector('.iui-select') as HTMLElement; assertSelect(select, { text: 'Red' }); const selectedValue = select.querySelector( '.iui-select-button > span', ) as HTMLElement; expect(selectedValue).toBeTruthy(); expect(selectedValue.style.color).toEqual('red'); }); it('should open menu on click', () => { const { container } = renderComponent(); const select = container.querySelector('.iui-select') as HTMLElement; expect(select).toBeTruthy(); let menu = document.querySelector('.iui-menu') as HTMLUListElement; expect(menu).toBeFalsy(); fireEvent.click(select.querySelector('.iui-select-button') as HTMLElement); menu = document.querySelector('.iui-menu') as HTMLUListElement; assertMenu(menu); }); it('should respect visible prop', () => { const options = [...new Array(3)].map((_, index) => ({ label: `Test${index}`, value: index, })); const { container, rerender } = render( <Select options={options} popoverProps={{ visible: true }} />, ); const select = container.querySelector('.iui-select') as HTMLElement; expect(select).toBeTruthy(); const tippy = document.querySelector('[data-tippy-root]') as HTMLElement; expect(tippy).toBeVisible(); assertMenu(document.querySelector('.iui-menu') as HTMLUListElement); fireEvent.click(select.querySelector('.iui-select-button') as HTMLElement); expect(tippy).not.toBeVisible(); rerender(<Select options={options} popoverProps={{ visible: true }} />); expect(tippy).toBeVisible(); }); it.each(['Enter', ' ', 'Spacebar'])( 'should open menu on "%s" key press', (key) => { const { container } = renderComponent(); const select = container.querySelector('.iui-select') as HTMLElement; expect(select).toBeTruthy(); let menu = document.querySelector('.iui-menu') as HTMLUListElement; expect(menu).toBeFalsy(); fireEvent.keyDown( select.querySelector('.iui-select-button') as HTMLElement, { key, }, ); menu = document.querySelector('.iui-menu') as HTMLUListElement; assertMenu(menu); }, ); it('should show menu items with icons', () => { const { container } = renderComponent({ options: [...new Array(3)].map((_, index) => ({ label: `Test${index}`, value: index, icon: <SvgSmileyHappy />, })), }); const select = container.querySelector('.iui-select') as HTMLElement; expect(select).toBeTruthy(); fireEvent.click(select.querySelector('.iui-select-button') as HTMLElement); const menu = document.querySelector('.iui-menu') as HTMLUListElement; assertMenu(menu, { hasIcon: true }); }); it('should show menu with disabled item', () => { const { container } = renderComponent({ options: [...new Array(3)].map((_, index) => ({ label: `Test${index}`, value: index, disabled: index === 1, })), }); const select = container.querySelector('.iui-select') as HTMLElement; expect(select).toBeTruthy(); fireEvent.click(select.querySelector('.iui-select-button') as HTMLElement); const menu = document.querySelector('.iui-menu') as HTMLUListElement; assertMenu(menu, { disabledIndex: 1 }); }); it('should show selected item in menu', () => { const scrollSpy = jest.spyOn(window.HTMLElement.prototype, 'scrollIntoView'); const { container } = renderComponent({ value: 1, options: [...new Array(3)].map((_, index) => ({ label: `Test${index}`, value: index, })), }); const select = container.querySelector('.iui-select') as HTMLElement; expect(select).toBeTruthy(); fireEvent.click(select.querySelector('.iui-select-button') as HTMLElement); const menu = document.querySelector('.iui-menu') as HTMLUListElement; assertMenu(menu, { selectedIndex: 1 }); expect(scrollSpy).toHaveBeenCalledTimes(1); }); it('should call onChange on item click', () => { const onChange = jest.fn(); const { container } = renderComponent({ onChange, }); const select = container.querySelector('.iui-select') as HTMLElement; expect(select).toBeTruthy(); fireEvent.click(select.querySelector('.iui-select-button') as HTMLElement); const menu = document.querySelector('.iui-menu') as HTMLUListElement; assertMenu(menu); const menuItem = menu.querySelectorAll('li'); expect(menuItem.length).toBe(3); fireEvent.click(menuItem[1]); expect(onChange).toHaveBeenCalledWith(1); }); it('should render menu with custom className', () => { const { container } = renderComponent({ menuClassName: 'test-className' }); const select = container.querySelector('.iui-select') as HTMLElement; expect(select).toBeTruthy(); fireEvent.click(select.querySelector('.iui-select-button') as HTMLElement); const menu = document.querySelector('.iui-menu') as HTMLUListElement; assertMenu(menu); expect(menu.classList).toContain('test-className'); }); it('should render menu with custom style', () => { const { container } = renderComponent({ menuStyle: { color: 'red' } }); const select = container.querySelector('.iui-select') as HTMLElement; expect(select).toBeTruthy(); fireEvent.click(select.querySelector('.iui-select-button') as HTMLElement); const menu = document.querySelector('.iui-menu') as HTMLUListElement; assertMenu(menu); expect(menu.style.color).toEqual('red'); }); it('should use custom renderer for menu items', () => { const { container } = render( <Select itemRenderer={(option) => ( <MenuItem style={{ color: option.value }}>{option.label}</MenuItem> )} options={[ { value: 'yellow', label: 'Yellow' }, { value: 'green', label: 'Green' }, { value: 'red', label: 'Red' }, ]} />, ); const select = container.querySelector('.iui-select') as HTMLElement; expect(select).toBeTruthy(); fireEvent.click(select.querySelector('.iui-select-button') as HTMLElement); const menu = document.querySelector('.iui-menu') as HTMLUListElement; expect(menu).toBeTruthy(); const menuItems = menu.querySelectorAll('li'); expect(menuItems.length).toBe(3); expect(menuItems[0].textContent).toEqual('Yellow'); expect(menuItems[1].textContent).toEqual('Green'); expect(menuItems[2].textContent).toEqual('Red'); expect(menuItems[0].style.color).toEqual('yellow'); expect(menuItems[1].style.color).toEqual('green'); expect(menuItems[2].style.color).toEqual('red'); }); it.each(['small', 'large'] as const)( 'should render small and large sizes', (size) => { const { container } = renderComponent({ size }); expect(container.querySelector(`.iui-select.iui-${size}`)).toBeTruthy(); }, ); it('should render large SelectOption', () => { const { container } = renderComponent({ options: [...new Array(3)].map((_, index) => ({ label: `Test${index}`, size: 'large', value: index, })), }); const select = container.querySelector('.iui-select') as HTMLElement; expect(select).toBeTruthy(); fireEvent.click(select.querySelector('.iui-select-button') as HTMLElement); const menuItems = select.querySelectorAll('.iui-menu-item.iui-large'); expect(menuItems.length).toEqual(3); }); it('should render sublabel', () => { const { container } = renderComponent({ options: [...new Array(3)].map((_, index) => ({ label: `Test${index}`, sublabel: `Sublabel ${index}`, value: index, })), }); const select = container.querySelector('.iui-select') as HTMLElement; expect(select).toBeTruthy(); fireEvent.click(select.querySelector('.iui-select-button') as HTMLElement); const menuItems = select.querySelectorAll('.iui-menu-item.iui-large'); expect(menuItems.length).toEqual(3); menuItems.forEach((menuItem, index) => { const sublabel = menuItem.querySelector( '.iui-content .iui-menu-description', ) as HTMLElement; expect(sublabel).toBeTruthy(); expect(sublabel.textContent).toEqual(`Sublabel ${index}`); }); }); it('should pass custom props to menu item', () => { const { container } = renderComponent({ options: [ { label: `Test`, value: 1, className: 'test-class', 'data-value': 'Test one', }, ], }); fireEvent.click(container.querySelector('.iui-select-button') as HTMLElement); const menuItem = container.querySelector( '.iui-menu-item.test-class', ) as HTMLElement; expect(menuItem.getAttribute('data-value')).toBe('Test one'); });
the_stack
"use strict"; import Boom from "@hapi/boom"; import Bounce from "@hapi/bounce"; import Hoek from "@hapi/hoek"; import Teamwork from "@hapi/teamwork"; import { parseNesMessage, protocol, stringifyNesMessage } from "./utils"; const internals = { version: "2", }; export class Socket { public server; public id; public app; public info; public _removed; public _pinged; private _ws; private _listener; private _helloed; private _processingCount; private _packets; private _sending; private _lastPinged; public constructor(ws, req, listener) { this._ws = ws; this._listener = listener; this._helloed = false; this._pinged = true; this._processingCount = 0; this._packets = []; this._sending = false; this._removed = new Teamwork.Team(); this.server = this._listener._server; this.id = this._listener._generateId(); this.app = {}; this.info = { remoteAddress: req.socket.remoteAddress, remotePort: req.socket.remotePort, "x-forwarded-for": req.headers["x-forwarded-for"], }; this._ws.on("message", (message) => this._onMessage(message)); this._ws.on("ping", () => this.terminate()); this._ws.on("pong", () => this.terminate()); } public disconnect() { this._ws.close(); return this._removed; } public terminate() { this._ws.terminate(); return this._removed; } public isOpen() { return this._ws.readyState === 1; } // public even though it starts with _ ; this is to match the original code public _active() { return this._pinged || this._sending || this._processingCount; } // public because used in listener ; from original code public _send(message, options?) { options = options || {}; if (!this.isOpen()) { // Open return Promise.reject(Boom.internal("Socket not open")); } let string; try { string = stringifyNesMessage(message); if (options.replace) { Object.keys(options.replace).forEach((token) => { string = string.replace(`"${token}"`, options.replace[token]); }); } } catch (err) { this.server.log(["nes", "serialization", "error"], message.type); /* istanbul ignore else */ if (message.id) { return this._error(Boom.internal("Failed serializing message"), message); } /* istanbul ignore next */ return Promise.reject(err); } const team = new Teamwork.Team(); this._packets.push({ message: string, type: message.type, team }); this._flush(); return team.work; } // private even though it does not start with _ ; adapted from the original code private caseInsensitiveKey(object, key) { const keys = Object.keys(object); for (let i = 0; i < keys.length; ++i) { const current = keys[i]; if (key === current.toLowerCase()) { return object[current]; } } return undefined; } private async _flush() { if (this._sending || !this._packets.length) { return; } this._sending = true; const packet = this._packets.shift(); let messages = [packet.message]; // Break message into smaller chunks const maxChunkChars = this._listener._settings.payload.maxChunkChars; if (maxChunkChars && packet.message.length > maxChunkChars) { messages = []; const parts = Math.ceil(packet.message.length / maxChunkChars); for (let i = 0; i < parts; ++i) { const last = i === parts - 1; const prefix = last ? "!" : "+"; messages.push(prefix + packet.message.slice(i * maxChunkChars, (i + 1) * maxChunkChars)); } } let error; for (let i = 0; i < messages.length; ++i) { const message = messages[i]; const team = new Teamwork.Team(); this._ws.send(message, (err) => team.attend(err)); try { await team.work; } catch (err) { error = err; break; } if (packet.type !== "ping") { this._pinged = true; // Consider the connection valid if send() was successful } } this._sending = false; packet.team.attend(error); setImmediate(() => this._flush()); } //@ts-ignore private _error(err, request?) { if (err.output?.statusCode === protocol.gracefulErrorStatusCode) { err = Boom.boomify(err); const message = Hoek.clone(err.output); delete message.payload.statusCode; message.headers = this._filterHeaders(message.headers); message.payload = Buffer.from(JSON.stringify(message.payload)); if (request) { message.type = request.type; message.id = request.id; } return this._send(message); } else { this.terminate(); return Promise.resolve(); } } private async _onMessage(message) { let request; try { if (!(message instanceof Buffer)) { return this.terminate(); } request = parseNesMessage(message); } catch (err) { return this.terminate(); } this._pinged = true; ++this._processingCount; let response, options, error; try { const lifecycleResponse = await this._lifecycle(request); response = lifecycleResponse.response; options = lifecycleResponse.options; } catch (err) { Bounce.rethrow(err, "system"); error = err; } try { if (error) { await this._error(error, request); } else if (response) { await this._send(response, options); } } catch (err) { Bounce.rethrow(err, "system"); this.terminate(); } --this._processingCount; } private async _lifecycle(request): Promise<any> { if (!request.type) { throw Boom.badRequest("Cannot parse message"); } if (!request.id) { throw Boom.badRequest("Message missing id"); } // Initialization and Authentication if (request.type === "ping") { if (this._lastPinged && (Date.now() < this._lastPinged + 1000)) { this._lastPinged = Date.now(); throw Boom.badRequest("Exceeded ping limit"); } this._lastPinged = Date.now(); return {}; } if (request.type === "hello") { return this._processHello(request); } if (!this._helloed) { throw Boom.badRequest("Connection is not initialized"); } // Endpoint request if (request.type === "request") { request.method = "POST"; return this._processRequest(request); } // Unknown throw Boom.badRequest("Unknown message type"); } private async _processHello(request) { /* istanbul ignore next */ if (this._helloed) { throw Boom.badRequest("Connection already initialized"); } if (request.version !== internals.version) { throw Boom.badRequest( "Incorrect protocol version (expected " + internals.version + " but received " + (request.version || "none") + ")", ); } this._helloed = true; // Prevents the client from reusing the socket if erred (leaves socket open to ensure client gets the error response) if (this._listener._settings.onConnection) { await this._listener._settings.onConnection(this); } const response = { type: "hello", id: request.id, heartbeat: this._listener._settings.heartbeat, socket: this.id, }; return { response }; } private async _processRequest(request) { let method = request.method; if (!method) { throw Boom.badRequest("Message missing method"); } let path = request.path; if (!path) { throw Boom.badRequest("Message missing path"); } if (request.headers && this.caseInsensitiveKey(request.headers, "authorization")) { throw Boom.badRequest("Cannot include an Authorization header"); } if (path[0] !== "/") { // Route id const route = this.server.lookup(path); if (!route) { throw Boom.notFound(); } path = route.path; method = route.method; if (method === "*") { throw Boom.badRequest("Cannot use route id with wildcard method route config"); } } const shot = { method, url: path, payload: request.payload, headers: { ...request.headers, "content-type": "application/octet-stream" }, auth: null, validate: false, plugins: { nes: { socket: this, }, }, remoteAddress: this.info.remoteAddress, allowInternals: true, }; const res = await this.server.inject(shot); if (res.statusCode >= 400) { throw Boom.boomify(new Error(res.result), { statusCode: res.statusCode }); } const response = { type: "request", id: request.id, statusCode: res.statusCode, payload: res.result, headers: this._filterHeaders(res.headers), }; return { response, options: {} }; } private _filterHeaders(headers) { const filter = this._listener._settings.headers; if (!filter) { return undefined; } if (filter === "*") { return headers; } const filtered = {}; const fields = Object.keys(headers); for (let i = 0; i < fields.length; ++i) { const field = fields[i]; if (filter.indexOf(field.toLowerCase()) !== -1) { filtered[field] = headers[field]; } } return filtered; } }
the_stack
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { AbstractClient } from "../../../common/abstract_client" import { ClientConfig } from "../../../common/interface" import { DescribeVpcRuleOverviewResponse, DescribeNatFwInstanceRequest, ModifyNatFwVpcDnsSwitchResponse, DescribeNatFwInstanceWithRegionRequest, DescribeRuleOverviewResponse, CfwNatDnatRule, StaticInfo, ModifyPublicIPSwitchStatusResponse, ModifyAcRuleResponse, DescribeTableStatusResponse, AddAcRuleRequest, ModifyNatFwVpcDnsSwitchRequest, SecurityGroupApiRuleData, DeleteNatFwInstanceResponse, DeleteAllAccessControlRuleRequest, ModifySecurityGroupRuleRequest, ModifyAllVPCSwitchStatusResponse, VpcZoneData, DatabaseWhiteListRuleData, DescribeNatFwVpcDnsLstRequest, DescribeCfwEipsRequest, DescribeTLogInfoResponse, ModifyAllSwitchStatusRequest, DescribeUnHandleEventTabListRequest, DescribeAssociatedInstanceListResponse, AssociatedInstanceInfo, DescribeNatRuleOverviewResponse, RemoveAcRuleResponse, NatFwInstance, DeleteNatFwInstanceRequest, CreateSecurityGroupRulesResponse, ExpandCfwVerticalRequest, ModifyAllPublicIPSwitchStatusResponse, DeleteVpcInstanceResponse, ModifyAssetScanRequest, ModifyBlockIgnoreListRequest, DeleteSecurityGroupRuleResponse, ModifySecurityGroupAllRuleStatusRequest, ModifySequenceRulesRequest, CreateNatFwInstanceRequest, ModifySecurityGroupItemRuleStatusResponse, NewModeItems, VpcDnsInfo, ModifyItemSwitchStatusResponse, ModifyNatFwReSelectResponse, DeleteSecurityGroupRuleRequest, SetNatFwEipRequest, SetNatFwEipResponse, AcListsData, ModifyPublicIPSwitchStatusRequest, SequenceData, CreateSecurityGroupApiRulesResponse, ModifySecurityGroupItemRuleStatusRequest, DescribeSourceAssetRequest, SecurityGroupOrderIndexData, DescribeSourceAssetResponse, DescribeTLogInfoRequest, DescribeSecurityGroupListResponse, AssetZone, RunSyncAssetRequest, DescribeTLogIpListRequest, DescribeNatFwInstancesInfoRequest, DescribeTableStatusRequest, DescribeSecurityGroupListRequest, ModifyResourceGroupRequest, CreateNatFwInstanceResponse, ModifyAllSwitchStatusResponse, DescribeNatFwInfoCountResponse, SecurityGroupListData, CreateNatFwInstanceWithDomainResponse, RemoveAcRuleRequest, ModifyAllRuleStatusRequest, RuleInfoData, DescribeAcListsResponse, ModifyAllPublicIPSwitchStatusRequest, DescribeBlockStaticListResponse, ModifySecurityGroupSequenceRulesRequest, CreateDatabaseWhiteListRulesResponse, ScanInfo, CreateChooseVpcsResponse, DescribeUnHandleEventTabListResponse, NatFwFilter, ScanResultInfo, ModifySecurityGroupSequenceRulesResponse, IpStatic, UnHandleEventDetail, DeleteResourceGroupRequest, DescribeBlockByIpTimesListRequest, ModifyVPCSwitchStatusResponse, ModifyAllVPCSwitchStatusRequest, ModifySequenceRulesResponse, DeleteSecurityGroupAllRuleResponse, DescribeResourceGroupNewResponse, DescribeNatFwInstanceWithRegionResponse, DescribeResourceGroupNewRequest, ModifyBlockTopRequest, DeleteAcRuleResponse, IocListData, InstanceInfo, ModifyNatFwSwitchResponse, RunSyncAssetResponse, DescribeBlockByIpTimesListResponse, SetNatFwDnatRuleResponse, DescribeRuleOverviewRequest, DescribeAcListsRequest, DescribeVpcRuleOverviewRequest, UnHandleEvent, DescribeAssociatedInstanceListRequest, DeleteAcRuleRequest, DeleteAllAccessControlRuleResponse, ModifyNatFwSwitchRequest, DescribeNatRuleOverviewRequest, CreateDatabaseWhiteListRulesRequest, NatInstanceInfo, NatFwEipsInfo, DescribeResourceGroupResponse, DeleteSecurityGroupAllRuleRequest, DescribeTLogIpListResponse, StopSecurityGroupRuleDispatchResponse, DescribeNatFwInfoCountRequest, AddAcRuleResponse, ModifyNatFwReSelectRequest, SetNatFwDnatRuleRequest, DescribeSyncAssetStatusResponse, SecurityGroupBothWayInfo, ModifyAllRuleStatusResponse, StopSecurityGroupRuleDispatchRequest, DescribeGuideScanInfoRequest, ModifyBlockTopResponse, CreateSecurityGroupApiRulesRequest, DescribeNatFwVpcDnsLstResponse, CreateChooseVpcsRequest, ExpandCfwVerticalResponse, DescribeBlockStaticListRequest, TLogInfo, CreateSecurityGroupRulesRequest, DeleteVpcInstanceRequest, SwitchListsData, CreateNatFwInstanceWithDomainRequest, DescribeSwitchListsResponse, DescribeSyncAssetStatusRequest, DescribeCfwEipsResponse, ModifyResourceGroupResponse, DeleteResourceGroupResponse, DescribeSwitchListsRequest, ModifyItemSwitchStatusRequest, CreateAcRulesResponse, ModifyAssetScanResponse, ModifyAcRuleRequest, DescribeNatFwInstancesInfoResponse, ModifyVPCSwitchStatusRequest, ModifyBlockIgnoreListResponse, DescribeNatFwInstanceResponse, ModifySecurityGroupRuleResponse, ModifySecurityGroupAllRuleStatusResponse, DnsVpcSwitch, DescribeResourceGroupRequest, CreateAcRulesRequest, ModifyTableStatusRequest, ModifyTableStatusResponse, DescribeGuideScanInfoResponse, } from "./cfw_models" /** * cfw client * @class */ export class Client extends AbstractClient { constructor(clientConfig: ClientConfig) { super("cfw.tencentcloudapi.com", "2019-09-04", clientConfig) } /** * 获取当前用户接入nat防火墙的所有子网数及natfw实例个数 */ async DescribeNatFwInfoCount( req?: DescribeNatFwInfoCountRequest, cb?: (error: string, rep: DescribeNatFwInfoCountResponse) => void ): Promise<DescribeNatFwInfoCountResponse> { return this.request("DescribeNatFwInfoCount", req, cb) } /** * nat规则列表概况 */ async DescribeNatRuleOverview( req: DescribeNatRuleOverviewRequest, cb?: (error: string, rep: DescribeNatRuleOverviewResponse) => void ): Promise<DescribeNatRuleOverviewResponse> { return this.request("DescribeNatRuleOverview", req, cb) } /** * 中止安全组规则下发 */ async StopSecurityGroupRuleDispatch( req?: StopSecurityGroupRuleDispatchRequest, cb?: (error: string, rep: StopSecurityGroupRuleDispatchResponse) => void ): Promise<StopSecurityGroupRuleDispatchResponse> { return this.request("StopSecurityGroupRuleDispatch", req, cb) } /** * 修改规则表状态 */ async ModifyTableStatus( req: ModifyTableStatusRequest, cb?: (error: string, rep: ModifyTableStatusResponse) => void ): Promise<ModifyTableStatusResponse> { return this.request("ModifyTableStatus", req, cb) } /** * 展示当前natfw 实例对应的vpc dns开关 */ async DescribeNatFwVpcDnsLst( req: DescribeNatFwVpcDnsLstRequest, cb?: (error: string, rep: DescribeNatFwVpcDnsLstResponse) => void ): Promise<DescribeNatFwVpcDnsLstResponse> { return this.request("DescribeNatFwVpcDnsLst", req, cb) } /** * 互联网边界防火墙一键开关 */ async ModifyAllPublicIPSwitchStatus( req: ModifyAllPublicIPSwitchStatusRequest, cb?: (error: string, rep: ModifyAllPublicIPSwitchStatusResponse) => void ): Promise<ModifyAllPublicIPSwitchStatusResponse> { return this.request("ModifyAllPublicIPSwitchStatus", req, cb) } /** * 获取安全组关联实例列表 */ async DescribeAssociatedInstanceList( req: DescribeAssociatedInstanceListRequest, cb?: (error: string, rep: DescribeAssociatedInstanceListResponse) => void ): Promise<DescribeAssociatedInstanceListResponse> { return this.request("DescribeAssociatedInstanceList", req, cb) } /** * 创建、选择vpc */ async CreateChooseVpcs( req: CreateChooseVpcsRequest, cb?: (error: string, rep: CreateChooseVpcsResponse) => void ): Promise<CreateChooseVpcsResponse> { return this.request("CreateChooseVpcs", req, cb) } /** * vpc规则列表概况 */ async DescribeVpcRuleOverview( req: DescribeVpcRuleOverviewRequest, cb?: (error: string, rep: DescribeVpcRuleOverviewResponse) => void ): Promise<DescribeVpcRuleOverviewResponse> { return this.request("DescribeVpcRuleOverview", req, cb) } /** * GetNatFwInstanceWithRegion 获取租户新增运维的NAT实例,带上地域 */ async DescribeNatFwInstanceWithRegion( req?: DescribeNatFwInstanceWithRegionRequest, cb?: (error: string, rep: DescribeNatFwInstanceWithRegionResponse) => void ): Promise<DescribeNatFwInstanceWithRegionResponse> { return this.request("DescribeNatFwInstanceWithRegion", req, cb) } /** * 删除规则 */ async DeleteAcRule( req: DeleteAcRuleRequest, cb?: (error: string, rep: DeleteAcRuleResponse) => void ): Promise<DeleteAcRuleResponse> { return this.request("DeleteAcRule", req, cb) } /** * ModifyResourceGroup-资产中心资产组信息修改 */ async ModifyResourceGroup( req: ModifyResourceGroupRequest, cb?: (error: string, rep: ModifyResourceGroupResponse) => void ): Promise<ModifyResourceGroupResponse> { return this.request("ModifyResourceGroup", req, cb) } /** * 创建安全组API规则 */ async CreateSecurityGroupApiRules( req: CreateSecurityGroupApiRulesRequest, cb?: (error: string, rep: CreateSecurityGroupApiRulesResponse) => void ): Promise<CreateSecurityGroupApiRulesResponse> { return this.request("CreateSecurityGroupApiRules", req, cb) } /** * DescribeResourceGroupNew资产中心资产树信息 */ async DescribeResourceGroupNew( req: DescribeResourceGroupNewRequest, cb?: (error: string, rep: DescribeResourceGroupNewResponse) => void ): Promise<DescribeResourceGroupNewResponse> { return this.request("DescribeResourceGroupNew", req, cb) } /** * 全部删除规则 */ async DeleteAllAccessControlRule( req: DeleteAllAccessControlRuleRequest, cb?: (error: string, rep: DeleteAllAccessControlRuleResponse) => void ): Promise<DeleteAllAccessControlRuleResponse> { return this.request("DeleteAllAccessControlRule", req, cb) } /** * 查询安全组规则列表 */ async DescribeSecurityGroupList( req: DescribeSecurityGroupListRequest, cb?: (error: string, rep: DescribeSecurityGroupListResponse) => void ): Promise<DescribeSecurityGroupListResponse> { return this.request("DescribeSecurityGroupList", req, cb) } /** * 编辑单条安全组规则 */ async ModifySecurityGroupRule( req: ModifySecurityGroupRuleRequest, cb?: (error: string, rep: ModifySecurityGroupRuleResponse) => void ): Promise<ModifySecurityGroupRuleResponse> { return this.request("ModifySecurityGroupRule", req, cb) } /** * DescribeNatFwInstance 获取租户所有NAT实例 */ async DescribeNatFwInstance( req?: DescribeNatFwInstanceRequest, cb?: (error: string, rep: DescribeNatFwInstanceResponse) => void ): Promise<DescribeNatFwInstanceResponse> { return this.request("DescribeNatFwInstance", req, cb) } /** * 资产扫描 */ async ModifyAssetScan( req: ModifyAssetScanRequest, cb?: (error: string, rep: ModifyAssetScanResponse) => void ): Promise<ModifyAssetScanResponse> { return this.request("ModifyAssetScan", req, cb) } /** * 防火墙开关列表 */ async DescribeSwitchLists( req: DescribeSwitchListsRequest, cb?: (error: string, rep: DescribeSwitchListsResponse) => void ): Promise<DescribeSwitchListsResponse> { return this.request("DescribeSwitchLists", req, cb) } /** * 创建暴露数据库白名单规则 */ async CreateDatabaseWhiteListRules( req: CreateDatabaseWhiteListRulesRequest, cb?: (error: string, rep: CreateDatabaseWhiteListRulesResponse) => void ): Promise<CreateDatabaseWhiteListRulesResponse> { return this.request("CreateDatabaseWhiteListRules", req, cb) } /** * 创建防火墙实例和接入域名 */ async CreateNatFwInstanceWithDomain( req: CreateNatFwInstanceWithDomainRequest, cb?: (error: string, rep: CreateNatFwInstanceWithDomainResponse) => void ): Promise<CreateNatFwInstanceWithDomainResponse> { return this.request("CreateNatFwInstanceWithDomain", req, cb) } /** * 删除全部规则 */ async DeleteSecurityGroupAllRule( req: DeleteSecurityGroupAllRuleRequest, cb?: (error: string, rep: DeleteSecurityGroupAllRuleResponse) => void ): Promise<DeleteSecurityGroupAllRuleResponse> { return this.request("DeleteSecurityGroupAllRule", req, cb) } /** * 添加互联网边界规则 */ async AddAcRule( req: AddAcRuleRequest, cb?: (error: string, rep: AddAcRuleResponse) => void ): Promise<AddAcRuleResponse> { return this.request("AddAcRule", req, cb) } /** * 创建规则 */ async CreateAcRules( req: CreateAcRulesRequest, cb?: (error: string, rep: CreateAcRulesResponse) => void ): Promise<CreateAcRulesResponse> { return this.request("CreateAcRules", req, cb) } /** * 启用停用全部规则 */ async ModifySecurityGroupAllRuleStatus( req: ModifySecurityGroupAllRuleStatusRequest, cb?: (error: string, rep: ModifySecurityGroupAllRuleStatusResponse) => void ): Promise<ModifySecurityGroupAllRuleStatusResponse> { return this.request("ModifySecurityGroupAllRuleStatus", req, cb) } /** * 访问控制列表 */ async DescribeAcLists( req: DescribeAcListsRequest, cb?: (error: string, rep: DescribeAcListsResponse) => void ): Promise<DescribeAcListsResponse> { return this.request("DescribeAcLists", req, cb) } /** * 创建企业安全组规则 */ async CreateSecurityGroupRules( req: CreateSecurityGroupRulesRequest, cb?: (error: string, rep: CreateSecurityGroupRulesResponse) => void ): Promise<CreateSecurityGroupRulesResponse> { return this.request("CreateSecurityGroupRules", req, cb) } /** * 查询规则列表概况 */ async DescribeRuleOverview( req: DescribeRuleOverviewRequest, cb?: (error: string, rep: DescribeRuleOverviewResponse) => void ): Promise<DescribeRuleOverviewResponse> { return this.request("DescribeRuleOverview", req, cb) } /** * DescribeTLogInfo告警中心概况 */ async DescribeTLogInfo( req: DescribeTLogInfoRequest, cb?: (error: string, rep: DescribeTLogInfoResponse) => void ): Promise<DescribeTLogInfoResponse> { return this.request("DescribeTLogInfo", req, cb) } /** * nat 防火墙VPC DNS 开关切换 */ async ModifyNatFwVpcDnsSwitch( req: ModifyNatFwVpcDnsSwitchRequest, cb?: (error: string, rep: ModifyNatFwVpcDnsSwitchResponse) => void ): Promise<ModifyNatFwVpcDnsSwitchResponse> { return this.request("ModifyNatFwVpcDnsSwitch", req, cb) } /** * 单个修改VPC火墙开关 */ async ModifyVPCSwitchStatus( req: ModifyVPCSwitchStatusRequest, cb?: (error: string, rep: ModifyVPCSwitchStatusResponse) => void ): Promise<ModifyVPCSwitchStatusResponse> { return this.request("ModifyVPCSwitchStatus", req, cb) } /** * VPC防火墙一键开关 */ async ModifyAllVPCSwitchStatus( req: ModifyAllVPCSwitchStatusRequest, cb?: (error: string, rep: ModifyAllVPCSwitchStatusResponse) => void ): Promise<ModifyAllVPCSwitchStatusResponse> { return this.request("ModifyAllVPCSwitchStatus", req, cb) } /** * 支持对拦截列表、忽略列表如下操作: 批量增加拦截IP、忽略IP/域名 批量删除拦截IP、忽略IP/域名 批量修改拦截IP、忽略IP/域名生效事件 */ async ModifyBlockIgnoreList( req: ModifyBlockIgnoreListRequest, cb?: (error: string, rep: ModifyBlockIgnoreListResponse) => void ): Promise<ModifyBlockIgnoreListResponse> { return this.request("ModifyBlockIgnoreList", req, cb) } /** * 删除防火墙实例 */ async DeleteVpcInstance( req?: DeleteVpcInstanceRequest, cb?: (error: string, rep: DeleteVpcInstanceResponse) => void ): Promise<DeleteVpcInstanceResponse> { return this.request("DeleteVpcInstance", req, cb) } /** * DescribeGuideScanInfo新手引导扫描接口信息 */ async DescribeGuideScanInfo( req?: DescribeGuideScanInfoRequest, cb?: (error: string, rep: DescribeGuideScanInfoResponse) => void ): Promise<DescribeGuideScanInfoResponse> { return this.request("DescribeGuideScanInfo", req, cb) } /** * DescribeUnHandleEventTabList 告警中心伪攻击链事件未处置接口 */ async DescribeUnHandleEventTabList( req: DescribeUnHandleEventTabListRequest, cb?: (error: string, rep: DescribeUnHandleEventTabListResponse) => void ): Promise<DescribeUnHandleEventTabListResponse> { return this.request("DescribeUnHandleEventTabList", req, cb) } /** * 设置防火墙实例弹性公网ip,目前仅支持新增模式的防火墙实例 */ async SetNatFwEip( req: SetNatFwEipRequest, cb?: (error: string, rep: SetNatFwEipResponse) => void ): Promise<SetNatFwEipResponse> { return this.request("SetNatFwEip", req, cb) } /** * DescribeSourceAsset-查询资产组全部资产信息 */ async DescribeSourceAsset( req: DescribeSourceAssetRequest, cb?: (error: string, rep: DescribeSourceAssetResponse) => void ): Promise<DescribeSourceAssetResponse> { return this.request("DescribeSourceAsset", req, cb) } /** * DeleteResourceGroup-资产中心资产组删除 */ async DeleteResourceGroup( req: DeleteResourceGroupRequest, cb?: (error: string, rep: DeleteResourceGroupResponse) => void ): Promise<DeleteResourceGroupResponse> { return this.request("DeleteResourceGroup", req, cb) } /** * 创建防火墙实例 */ async CreateNatFwInstance( req: CreateNatFwInstanceRequest, cb?: (error: string, rep: CreateNatFwInstanceResponse) => void ): Promise<CreateNatFwInstanceResponse> { return this.request("CreateNatFwInstance", req, cb) } /** * 配置防火墙Dnat规则 */ async SetNatFwDnatRule( req: SetNatFwDnatRuleRequest, cb?: (error: string, rep: SetNatFwDnatRuleResponse) => void ): Promise<SetNatFwDnatRuleResponse> { return this.request("SetNatFwDnatRule", req, cb) } /** * 启用停用全部规则 */ async ModifyAllRuleStatus( req: ModifyAllRuleStatusRequest, cb?: (error: string, rep: ModifyAllRuleStatusResponse) => void ): Promise<ModifyAllRuleStatusResponse> { return this.request("ModifyAllRuleStatus", req, cb) } /** * 修改规则执行顺序 */ async ModifySequenceRules( req: ModifySequenceRulesRequest, cb?: (error: string, rep: ModifySequenceRulesResponse) => void ): Promise<ModifySequenceRulesResponse> { return this.request("ModifySequenceRules", req, cb) } /** * 删除互联网边界规则 */ async RemoveAcRule( req: RemoveAcRuleRequest, cb?: (error: string, rep: RemoveAcRuleResponse) => void ): Promise<RemoveAcRuleResponse> { return this.request("RemoveAcRule", req, cb) } /** * ModifyBlockTop取消置顶接口 */ async ModifyBlockTop( req: ModifyBlockTopRequest, cb?: (error: string, rep: ModifyBlockTopResponse) => void ): Promise<ModifyBlockTopResponse> { return this.request("ModifyBlockTop", req, cb) } /** * 查询规则表状态 */ async DescribeTableStatus( req: DescribeTableStatusRequest, cb?: (error: string, rep: DescribeTableStatusResponse) => void ): Promise<DescribeTableStatusResponse> { return this.request("DescribeTableStatus", req, cb) } /** * GetNatInstance 获取租户所有NAT实例及实例卡片信息 */ async DescribeNatFwInstancesInfo( req: DescribeNatFwInstancesInfoRequest, cb?: (error: string, rep: DescribeNatFwInstancesInfoResponse) => void ): Promise<DescribeNatFwInstancesInfoResponse> { return this.request("DescribeNatFwInstancesInfo", req, cb) } /** * 防火墙实例重新选择vpc或nat */ async ModifyNatFwReSelect( req: ModifyNatFwReSelectRequest, cb?: (error: string, rep: ModifyNatFwReSelectResponse) => void ): Promise<ModifyNatFwReSelectResponse> { return this.request("ModifyNatFwReSelect", req, cb) } /** * DescribeResourceGroup资产中心资产树信息 */ async DescribeResourceGroup( req: DescribeResourceGroupRequest, cb?: (error: string, rep: DescribeResourceGroupResponse) => void ): Promise<DescribeResourceGroupResponse> { return this.request("DescribeResourceGroup", req, cb) } /** * 查询防火墙弹性公网IP */ async DescribeCfwEips( req: DescribeCfwEipsRequest, cb?: (error: string, rep: DescribeCfwEipsResponse) => void ): Promise<DescribeCfwEipsResponse> { return this.request("DescribeCfwEips", req, cb) } /** * 同步资产-互联网&VPC */ async RunSyncAsset( req: RunSyncAssetRequest, cb?: (error: string, rep: RunSyncAssetResponse) => void ): Promise<RunSyncAssetResponse> { return this.request("RunSyncAsset", req, cb) } /** * 修改规则 */ async ModifyAcRule( req: ModifyAcRuleRequest, cb?: (error: string, rep: ModifyAcRuleResponse) => void ): Promise<ModifyAcRuleResponse> { return this.request("ModifyAcRule", req, cb) } /** * 删除规则 */ async DeleteSecurityGroupRule( req: DeleteSecurityGroupRuleRequest, cb?: (error: string, rep: DeleteSecurityGroupRuleResponse) => void ): Promise<DeleteSecurityGroupRuleResponse> { return this.request("DeleteSecurityGroupRule", req, cb) } /** * 企业安全组规则快速排序 */ async ModifySecurityGroupSequenceRules( req: ModifySecurityGroupSequenceRulesRequest, cb?: (error: string, rep: ModifySecurityGroupSequenceRulesResponse) => void ): Promise<ModifySecurityGroupSequenceRulesResponse> { return this.request("ModifySecurityGroupSequenceRules", req, cb) } /** * 修改NAT防火墙开关 */ async ModifyNatFwSwitch( req: ModifyNatFwSwitchRequest, cb?: (error: string, rep: ModifyNatFwSwitchResponse) => void ): Promise<ModifyNatFwSwitchResponse> { return this.request("ModifyNatFwSwitch", req, cb) } /** * DescribeTLogIpList告警中心IP柱形图 */ async DescribeTLogIpList( req: DescribeTLogIpListRequest, cb?: (error: string, rep: DescribeTLogIpListResponse) => void ): Promise<DescribeTLogIpListResponse> { return this.request("DescribeTLogIpList", req, cb) } /** * 启用停用单条企业安全组规则 */ async ModifySecurityGroupItemRuleStatus( req: ModifySecurityGroupItemRuleStatusRequest, cb?: (error: string, rep: ModifySecurityGroupItemRuleStatusResponse) => void ): Promise<ModifySecurityGroupItemRuleStatusResponse> { return this.request("ModifySecurityGroupItemRuleStatus", req, cb) } /** * 一键开启和关闭 */ async ModifyAllSwitchStatus( req: ModifyAllSwitchStatusRequest, cb?: (error: string, rep: ModifyAllSwitchStatusResponse) => void ): Promise<ModifyAllSwitchStatusResponse> { return this.request("ModifyAllSwitchStatus", req, cb) } /** * 销毁防火墙实例 */ async DeleteNatFwInstance( req: DeleteNatFwInstanceRequest, cb?: (error: string, rep: DeleteNatFwInstanceResponse) => void ): Promise<DeleteNatFwInstanceResponse> { return this.request("DeleteNatFwInstance", req, cb) } /** * 单个修改互联网边界防火墙开关 */ async ModifyPublicIPSwitchStatus( req: ModifyPublicIPSwitchStatusRequest, cb?: (error: string, rep: ModifyPublicIPSwitchStatusResponse) => void ): Promise<ModifyPublicIPSwitchStatusResponse> { return this.request("ModifyPublicIPSwitchStatus", req, cb) } /** * 同步资产状态查询-互联网&VPC */ async DescribeSyncAssetStatus( req: DescribeSyncAssetStatusRequest, cb?: (error: string, rep: DescribeSyncAssetStatusResponse) => void ): Promise<DescribeSyncAssetStatusResponse> { return this.request("DescribeSyncAssetStatus", req, cb) } /** * 防火墙垂直扩容 */ async ExpandCfwVertical( req: ExpandCfwVerticalRequest, cb?: (error: string, rep: ExpandCfwVerticalResponse) => void ): Promise<ExpandCfwVerticalResponse> { return this.request("ExpandCfwVertical", req, cb) } /** * DescribeBlockByIpTimesList 告警中心阻断IP折线图 */ async DescribeBlockByIpTimesList( req: DescribeBlockByIpTimesListRequest, cb?: (error: string, rep: DescribeBlockByIpTimesListResponse) => void ): Promise<DescribeBlockByIpTimesListResponse> { return this.request("DescribeBlockByIpTimesList", req, cb) } /** * DescribeBlockStaticList 告警中心柱形图 */ async DescribeBlockStaticList( req: DescribeBlockStaticListRequest, cb?: (error: string, rep: DescribeBlockStaticListResponse) => void ): Promise<DescribeBlockStaticListResponse> { return this.request("DescribeBlockStaticList", req, cb) } /** * 修改单个防火墙开关 */ async ModifyItemSwitchStatus( req: ModifyItemSwitchStatusRequest, cb?: (error: string, rep: ModifyItemSwitchStatusResponse) => void ): Promise<ModifyItemSwitchStatusResponse> { return this.request("ModifyItemSwitchStatus", req, cb) } }
the_stack
import './index.less'; import { remote, ipcRenderer } from 'electron'; import TypeWeibo from '@/../../src/type/namespace/weibo'; import { useState, useEffect } from 'react'; import { enableMapSet } from 'immer'; enableMapSet(); import produce from 'immer'; import { Table, Card, Select, Button } from 'antd'; import { PlusCircleOutlined } from '@ant-design/icons'; import Util from '@/library/util'; import moment from 'moment'; import path from 'path'; let Option = Select.Option; let MUser = remote.getGlobal('mUser'); let MBlog = remote.getGlobal('mBlog'); type BlogDistributionItem = { date: string; key: string; type: 'year' | 'month' | 'day'; startAt: number; count: number; childrenMap: BlogDistributionObj; }; type BlogDistributionObj = { [key: string]: BlogDistributionItem }; const Const_Default_Storage_Select: { year: string; month: string; day: string; yearList: string[]; monthList: string[]; blogList: TypeWeibo.TypeMblog[]; } = { year: '', month: '', day: '', yearList: [], monthList: [], blogList: [], }; export default function IndexPage() { let [$$userDatabase, set$$UserDatabase] = useState< Map<string, TypeWeibo.TypeWeiboUserInfo> >(produce(new Map(), (raw) => raw)); let [ blogDistributionObj, setBlogDistributionObj, ] = useState<BlogDistributionObj>({}); let [isLoading, setIsLoading] = useState<boolean>(false); let [selectUserId, setSelectUserId] = useState<string>(''); let [selectWeiboListPageNo, setSelectWeiboListPageNo] = useState<number>(1); let [selectDateListPageNo, setSelectDateListPageNo] = useState<number>(1); let [$$storageSelect, set$$StorageSelect] = useState<{ year: string; month: string; day: string; yearList: string[]; monthList: string[]; blogList: TypeWeibo.TypeMblog[]; }>(produce(Const_Default_Storage_Select, (raw) => raw)); /** * 获取用户信息列表 */ async function asyncFetchUserInfoList() { let userInfoList: TypeWeibo.TypeWeiboUserInfo[] = await MUser.asyncGetUserList(); for (let record of userInfoList) { set$$UserDatabase(($$oldDatabase) => { return produce($$oldDatabase, (raw) => { raw.set(`${record.id}`, record); }); }); } } async function asyncGetDistribute() { setIsLoading(true); let distributionObj: BlogDistributionObj = await MBlog.asyncGetWeiboDistribution( selectUserId, ); setIsLoading(false); setBlogDistributionObj(distributionObj); set$$StorageSelect( produce(Const_Default_Storage_Select, (raw) => { raw.yearList = Object.keys(distributionObj); }), ); } /** * 获取当天微博数据列表 */ async function asyncGetBlogListInRange(startAt: number, endAt: number) { let blogList = (await MBlog.asyncGetMblogList( selectUserId, startAt, endAt, )) as TypeWeibo.TypeMblog[]; return blogList; } // 支持点选 async function asyncHandleStorageSelectInTable( selectDate: string, type: 'year' | 'month' | 'day', ) { if (type === 'year') { let rowItem = blogDistributionObj[selectDate]; set$$StorageSelect(($$storageSelect) => { return produce($$storageSelect, (raw) => { raw.year = rowItem.date; let rawMonthItemList: BlogDistributionItem[] = []; for (let key of Object.keys(rowItem.childrenMap)) { rawMonthItemList.push(rowItem.childrenMap[key]); } rawMonthItemList.sort( (a: BlogDistributionItem, b: BlogDistributionItem) => { // 从object中取出的数据顺序是乱的, 手工排序一下 return a.startAt - b.startAt; }, ); raw.monthList = rawMonthItemList.map((item) => item.date); raw.month = ''; raw.blogList = []; }); }); } if (type === 'month') { let rowItem = blogDistributionObj[$$storageSelect.year].childrenMap[selectDate]; set$$StorageSelect(($$storageSelect) => { return produce($$storageSelect, (raw) => { raw.month = rowItem.date; raw.blogList = []; }); }); } if (type === 'day') { let row = blogDistributionObj[$$storageSelect.year].childrenMap[ $$storageSelect.month ].childrenMap[selectDate]; let startAt = row.startAt; let endAt = row.startAt + 86400 - 1; let blogList = await asyncGetBlogListInRange(startAt, endAt); set$$StorageSelect(($$storageSelect) => { return produce($$storageSelect, (raw) => { raw.day = row.date; raw.blogList = blogList; }); }); } } /** * 重置选择 */ function resetSelect() { setSelectDateListPageNo(1); setSelectWeiboListPageNo(1); set$$StorageSelect(() => { return produce(Const_Default_Storage_Select, (raw) => raw); }); } /** * 重置选择数据 */ async function asyncRefreshData() { set$$UserDatabase(produce(new Map(), (raw) => raw)); setBlogDistributionObj({}); set$$StorageSelect(produce(Const_Default_Storage_Select, (raw) => raw)); setSelectUserId(''); setSelectDateListPageNo(1); setSelectWeiboListPageNo(1); setIsLoading(false); await asyncFetchUserInfoList(); } /** * 导出数据 */ async function asyncDataTransferExport(config: { screen_name: string; exportUri: string; uid: string; exportStartAt: number; exportEndAt: number; }) { let currentUserInfo = $$userDatabase.get(selectUserId); let exportStartAtStr = moment.unix(exportStartAt).format('YYYY-MM'); let exportEndAtStr = moment.unix(exportEndAt).format('YYYY-MM'); let exportRangeStr = `从${exportStartAtStr}到${exportEndAtStr}`; let saveUri = await remote.dialog.showSaveDialogSync({ title: '文件保存地址', filters: [ { // name: `稳部落导出的用户_${config.screen_name}_微博记录`, name: `稳部落数据导出`, extensions: ['json'], }, ], defaultPath: `${ currentUserInfo?.screen_name || '' }-${exportRangeStr}-v1.0.0-稳部落数据导出记录`, }); if (!config.uid || !saveUri) { // 没有uid, 无法导出 return; } let finalConfig = { uid: config.uid, exportStartAt: config.exportStartAt, exportEndAt: config.exportEndAt, exportUri: path.resolve(saveUri), }; setIsLoading(true); await Util.asyncSleepMs(500); ipcRenderer.sendSync('dataTransferExport', finalConfig); setIsLoading(false); } /** * 导入数据 */ async function asyncDataTransferImport() { let importUriList = await remote.dialog.showOpenDialogSync({ title: '选择导入文件', filters: [ { // name: `稳部落导出的用户_${config.screen_name}_微博记录`, name: `稳部落数据导出`, extensions: ['json'], }, ], defaultPath: `${ currentUserInfo?.screen_name || '' }-v1.0.0-稳部落数据导出记录`, }); let importUri = importUriList?.[0]; console.log('importUri => ', importUri); if (!importUri) { // 没有uid, 无法导出 return; } let finalConfig = { importUri: importUri, }; setIsLoading(true); await Util.asyncSleepMs(500); ipcRenderer.sendSync('dataTransferImport', finalConfig); await asyncRefreshData(); setIsLoading(false); } useEffect(() => { asyncFetchUserInfoList(); }, []); useEffect(() => { if ($$userDatabase.has(selectUserId)) { asyncGetDistribute(); resetSelect(); } }, [selectUserId]); let userInfoList: TypeWeibo.TypeWeiboUserInfo[] = []; for (let key of $$userDatabase.keys()) { let record = $$userDatabase.get(key); userInfoList.push({ ...record, // @ts-ignore key: `${key}`, }); } let currentUserInfo = $$userDatabase.get(selectUserId); let yearOptionEleList = $$storageSelect.yearList.map((item, index) => { return ( <Option value={item} key={index}> {item} </Option> ); }); let yearSelectEle = ( <Select className="year-select" value={$$storageSelect.year} onSelect={(selectDate: string) => { asyncHandleStorageSelectInTable(selectDate, 'year'); }} > {yearOptionEleList} </Select> ); let monthOptionEleList = $$storageSelect.monthList.map((item, index) => { return ( <Option value={item} key={index}> {item} </Option> ); }); let monthSelectEle = ( <Select className="month-select" value={$$storageSelect.month} onSelect={(selectDate: string) => { asyncHandleStorageSelectInTable(selectDate, 'month'); }} > {monthOptionEleList} </Select> ); function getSummaryList() { if (Object.keys(blogDistributionObj).length === 0) { return []; } const { year, month } = $$storageSelect; let summaryList: BlogDistributionItem[] = []; if (year === '') { // 按年展示 Object.keys(blogDistributionObj).forEach((year_str) => { let item = blogDistributionObj[year_str]; summaryList.push({ ...item, key: `${item.date}`, }); }); return summaryList; } if (month === '') { // 按月展示 let yearDistributionObj = blogDistributionObj[year]['childrenMap']; Object.keys(yearDistributionObj).forEach((month_str) => { let item = yearDistributionObj[month_str]; summaryList.push({ ...item, key: `${item.date}`, }); }); return summaryList; } // 按天展示 let monthDistributionObj = blogDistributionObj[year]['childrenMap'][month]['childrenMap']; Object.keys(monthDistributionObj).forEach((day_str) => { let item = monthDistributionObj[day_str]; summaryList.push({ ...item, key: `${item.date}`, }); }); return summaryList; } let rawSummaryList = getSummaryList(); rawSummaryList.sort((a, b) => { // 从object中取出的数据顺序是乱的, 手工排序一下 return a.startAt - b.startAt; }); let weiboStorageSummaryList = rawSummaryList; let blogListEle = null; if ($$storageSelect.blogList.length > 0) { blogListEle = ( <Card title={`${$$userDatabase.get(selectUserId)?.screen_name} 在${ $$storageSelect.year }${$$storageSelect.month}${$$storageSelect.day}发布的微博列表`} > <Table pagination={{ onChange: (page) => { setSelectWeiboListPageNo(page); }, current: selectWeiboListPageNo, }} dataSource={$$storageSelect.blogList} rowKey={(item) => item.id} columns={[ { title: '发布时间', width: '120px', render: (record) => { return ( <span title={'微博id:' + record.id} key={record.id}> {moment .unix(record.created_timestamp_at) .format('YYYY-MM-DD HH:mm:ss')} </span> ); }, }, { title: '发布内容', render: (record: TypeWeibo.TypeMblog) => { let picEleList = []; let picList = record?.pics || []; for (let picItem of picList) { picEleList.push(<img key={picItem.pid} src={picItem.url} />); } let retweetedEle = null; if (record.retweeted_status) { let picEleList = []; let picList = record?.retweeted_status?.pics || []; for (let picItem of picList) { picEleList.push( <img key={picItem.pid} src={picItem.url} />, ); } retweetedEle = ( <div className="weibo-repost-item" v-if="scope.row.retweeted_status" > <hr /> <div className="weibo-text" dangerouslySetInnerHTML={{ __html: record.retweeted_status.raw_text || record.retweeted_status.text, }} /> <div className="weibo-img-list">{picEleList}</div> </div> ); } return ( <div className="weibo" key={record.id}> <div className="weibo-raw-item"> <div className="weibo-text" dangerouslySetInnerHTML={{ __html: record.raw_text || record.text, }} /> <div className="weibo-img-list"> <div>{picEleList}</div> </div> {retweetedEle} </div> </div> ); }, }, ]} ></Table> </Card> ); } let uid = selectUserId; let exportUri = ''; let exportStartAt = moment('2009-01-01 00:00:00').unix(); let exportEndAt = moment().unix(); if ($$storageSelect.year) { if ($$storageSelect.month) { exportStartAt = moment( `${$$storageSelect.year}-${$$storageSelect.month}`, 'YYYY年-MM月', ) .startOf('month') .unix(); exportEndAt = moment( `${$$storageSelect.year}-${$$storageSelect.month}`, 'YYYY年-MM月', ) .endOf('month') .unix(); } else { exportStartAt = moment($$storageSelect.year, 'YYYY年') .startOf('year') .unix(); exportEndAt = moment($$storageSelect.year, 'YYYY年').endOf('year').unix(); } } let exportTip = `导出微博记录`; if (currentUserInfo?.screen_name) { if ($$storageSelect.year) { if ($$storageSelect.month) { exportTip = `导出${currentUserInfo?.screen_name}在${$$storageSelect.year}-${$$storageSelect.month}的所有微博记录`; } else { exportTip = `导出${currentUserInfo?.screen_name}在${$$storageSelect.year}的所有微博记录`; } } else { exportTip = `导出${currentUserInfo?.screen_name}的所有微博记录`; } } // 生成导出配置 let exportConfig = { screen_name: currentUserInfo?.screen_name || '', exportUri, uid, exportStartAt: exportStartAt, exportEndAt: exportEndAt, }; return ( <div className="manager-container"> <Card title={ <Button type="primary" onClick={() => { asyncDataTransferImport(); }} > <PlusCircleOutlined></PlusCircleOutlined>数据导入 </Button> } > <Table loading={isLoading} onRow={(record) => { return { onClick: () => { setSelectUserId(`${record.id}`); }, }; }} rowSelection={{ checkStrictly: false, selectedRowKeys: [selectUserId], type: 'radio', }} rowKey={(item) => { return `${item.id}`; }} columns={[ { title: '已缓存账号', dataIndex: 'screen_name', render: (text, record: TypeWeibo.TypeWeiboUserInfo, index) => { return ( <div className="user-info" key={record.id}> <img alt={record.screen_name} src={record.avatar_hd} className="avatar" /> <div className="name">{record.screen_name}</div> <div className="id">({record.id})</div> </div> ); }, }, { title: '已保存微博条数', dataIndex: 'mblog_save_count', key: 'mblog_save_count', }, { title: '个人简介', dataIndex: 'description', key: 'description', }, ]} dataSource={userInfoList} pagination={false} ></Table> </Card> <Card title={ currentUserInfo?.screen_name ? `${currentUserInfo?.screen_name} 已完成备份的微博列表` : '' } > {yearSelectEle} &nbsp; {monthSelectEle} &nbsp; <Button type="default" disabled={selectUserId === ''} onClick={() => { asyncDataTransferExport(exportConfig); }} > {exportTip} </Button> &nbsp; <Button type="default" onClick={() => { resetSelect(); }} > 重选 </Button> &nbsp; <Button type="primary" onClick={() => { asyncRefreshData(); }} > 刷新数据 </Button> &nbsp; <Table pagination={{ onChange: (page) => { setSelectDateListPageNo(page); }, current: selectDateListPageNo, }} loading={isLoading} rowSelection={{ selectedRowKeys: [$$storageSelect.day], type: 'radio', }} dataSource={weiboStorageSummaryList} columns={[ { title: '日期', dataIndex: 'date', key: 'date', }, { title: '微博数量', dataIndex: 'count', key: 'count', }, ]} onRow={(record, index) => { return { onClick: () => { let selectType = record.type; switch (selectType) { case 'year': asyncHandleStorageSelectInTable(record.date, 'year'); break; case 'month': asyncHandleStorageSelectInTable(record.date, 'month'); break; case 'day': asyncHandleStorageSelectInTable(record.date, 'day'); break; } }, }; }} ></Table> </Card> {blogListEle} </div> ); } // visible: (...) // created_at: (...) // id: (...) // mid: (...) // can_edit: (...) // show_additional_indication: (...) // text: (...) // source: (...) // favorited: (...) // pic_ids: (...) // pic_types: (...) // is_paid: (...) // mblog_vip_type: (...) // user: (...) // pid: (...) // pidstr: (...) // retweeted_status: (...) // reposts_count: (...) // comments_count: (...) // attitudes_count: (...) // pending_approval_count: (...) // isLongText: (...) // reward_exhibition_type: (...) // hide_flag: (...) // mlevel: (...) // darwin_tags: (...) // mblogtype: (...) // rid: (...) // more_info_type: (...) // extern_safe: (...) // number_display_strategy: (...) // enable_comment_guide: (...) // content_auth: (...) // pic_num: (...) // alchemy_params: (...) // mblog_menu_new_style: (...) // reads_count: (...) // title: (...) // raw_text: (...) // bid: (...) // created_timestamp_at: (...)
the_stack
import * as cl from 'node-opencl'; import { log, isUint8, isFloat32, isInt32, nullValForType, checkType, gpuTypeForType, typeForGPUType, stringifyVector3, isArray, isInteger } from './utils'; import { Type, GPUBufferDataType, TomType, GPUTypedArray, TomTypedArray } from './types'; import { closeSync, openSync, readFileSync } from 'fs'; import { BufferedTomDataR } from './BufferedTomDataR'; import { Vector3 } from 'three'; import { getBinDataType, getTomDataType, readBin } from './io'; import { BufferedTomDataW } from './BufferedTomDataW'; import MutableTypedArray from './MutableTypedArray'; type ReadWrite = 'read' | 'write' | 'readwrite'; type KernelVariableType = 'float' | 'int' | 'int2' | 'uchar'; interface GPUBuffer { buffer: any, length: number, bytesPerElement: number, readwrite: ReadWrite, dataType: GPUBufferDataType, bufferName: string, } interface compileArg { value: number, type: Type, } // TODO: node-opencl does not have type declarations. export default class GPUHelper { private gpuBuffers: { [key: string]: GPUBuffer; } = {}; private kernels: { [key: string]: any; } = {}; private events: any[] = []; private device: any; private context: any; private queue: any; constructor(DEVICE_NUM: number) { log('\nInitializing GPU...\n') // Choose platform. const platforms = cl.getPlatformIDs(); log('Available platforms:'); for (let i = 0; i < platforms.length; i++) { log(`\tPlatform ${i}: ${cl.getPlatformInfo(platforms[i], cl.PLATFORM_NAME)}`); } const platform = platforms[0]; log(`Using Platform: ${cl.getPlatformInfo(platform, cl.PLATFORM_NAME)}\n`); // Choose device. const devices = cl.getDeviceIDs(platform, cl.DEVICE_TYPE_ALL); log('Available devices:'); for (let i = 0; i < devices.length; i++) { log(`\tDevices ${i}: ${cl.getDeviceInfo(devices[i], cl.DEVICE_NAME)}`); } this.device = devices[DEVICE_NUM]; log(`Using Device: ${cl.getDeviceInfo(this.device, cl.DEVICE_NAME)}\n`); // Create context. this.context = cl.createContext([cl.CONTEXT_PLATFORM, platform], devices); // Create command queue. if (cl.createCommandQueueWithProperties !== undefined) { this.queue = cl.createCommandQueueWithProperties(this.context, this.device, []); // OpenCL 2 } else { this.queue = cl.createCommandQueue(this.context, this.device, null); // OpenCL 1.x } } initProgram(path: string, programName: string, programCompileArgs?: {[key: string]: compileArg}) { if (this.kernels[programName]) { throw new Error(`Program: ${programName} already inited.`); } const program = cl.createProgramWithSource(this.context, readFileSync(path, 'utf8')); // Init compile args. const globalCompileArgs: {[key: string]: compileArg} = { NULL_FLOAT32: { value: nullValForType('float32'), type: 'float32', }, NULL_INT32: { value: nullValForType('int32'), type: 'int32', }, }; // Check that compile args aren't overlapping. if (programCompileArgs) { Object.keys(globalCompileArgs).forEach(argKey => { if (Object.keys(programCompileArgs).indexOf(argKey) >= 0) { throw new Error(`Duplicate OpenCL compile arg ${argKey}.`) } }); } const compileArgs = {...globalCompileArgs, ...programCompileArgs}; // Check types. Object.keys(compileArgs).forEach(argKey => { const { value, type } = compileArgs[argKey]; if (!checkType(value, type)){ throw new Error(`Invalid type for compile arg ${argKey}: expected ${type}, got ${value}.`); } }); // Create args string. let compileArgsString = Object.keys(compileArgs).reduce((string, argKey) => { return string += `-D ${argKey}=${compileArgs[argKey].value} `; }, ''); // // Additional options. // // https://www.khronos.org/registry/OpenCL/sdk/1.2/docs/man/xhtml/clCompileProgram.html // compileArgsString += '-cl-single-precision-constant '; // compileArgsString += '-cl-fp32-correctly-rounded-divide-sqrt '; // compileArgsString += '-cl-opt-disable '; // Build and create kernel object try { cl.buildProgram(program, undefined, compileArgsString); this.kernels[programName] = cl.createKernel(program, programName); log(`\tBuild log for CL program ${programName}: ${cl.getProgramBuildInfo(program, this.device, cl.PROGRAM_BUILD_LOG)}`); } catch (err) { log(err); throw new Error(cl.getProgramBuildInfo(program, this.device, cl.PROGRAM_BUILD_LOG)); } } gpuBufferExists(bufferName: string) { return this.gpuBuffers[bufferName] !== undefined; } gpuProgramExists(programName: string) { return this.kernels[programName] !== undefined; } lengthForGPUBuffer(bufferName: string) { if (!this.gpuBufferExists(bufferName)) { return null; } return this.gpuBuffers[bufferName].length; } typeForGPUBuffer(bufferName: string) { if (!this.gpuBufferExists(bufferName)) { return null; } return this.gpuBuffers[bufferName].dataType; } //Create buffer on gpu memory. createGPUBuffer(bufferName: string, data: Float32Array | null, dataType: 'float*', readwrite: ReadWrite, length?: number, forceOverwrite?: boolean): void; createGPUBuffer(bufferName: string, data: Int32Array | null, dataType: 'int*', readwrite: ReadWrite, length?: number, forceOverwrite?: boolean): void; createGPUBuffer(bufferName: string, data: Uint8Array | null, dataType: 'uchar*', readwrite: ReadWrite, length?: number, forceOverwrite?: boolean): void; createGPUBuffer(bufferName: string, data: any, dataType: GPUBufferDataType, readwrite: ReadWrite, length = data.length, forceOverwrite = false) { let bytesPerElement; switch (dataType) { case 'float*': bytesPerElement = 4; break; case 'int*': bytesPerElement = 4; break; case 'uchar*': bytesPerElement = 1; break; default: throw new Error(`Unsupported type: ${dataType}`); } if (this.gpuBufferExists(bufferName)) { if (!forceOverwrite) log(`Buffer ${bufferName} already exists, use GPUHelper.copyDataToGPUBuffer() instead.`); this.releaseGPUBuffer(bufferName); } let readwriteCode; switch (readwrite) { case 'read': readwriteCode = cl.MEM_READ_ONLY; break; case 'write': readwriteCode = cl.MEM_WRITE; break; case 'readwrite': readwriteCode = cl.MEM_READ_WRITE; break; default: throw new Error(`Unsupported readwrite type: ${readwrite}`); } this.gpuBuffers[bufferName] = { buffer: cl.createBuffer(this.context, readwriteCode, length * bytesPerElement), length, bytesPerElement, readwrite, dataType, bufferName, }; if (data) { this.copyDataToGPUBuffer(bufferName, data, 0, length); } } createGpuBufferFromMutableTypedArray(bufferName: string, array: MutableTypedArray, readwrite: ReadWrite, length = array.getLength(), forceOverwrite?: boolean) { // @ts-ignore this.createGPUBuffer(bufferName, array.getData(), gpuTypeForType(array.type), readwrite, length * array.numElementsPerIndex, forceOverwrite); } createGPUBufferFromTom(bufferName: string, path: string, filename: string, readwrite: ReadWrite, forceOverwrite?: boolean) { const tom = new BufferedTomDataR(path, filename, 0); const { dim, type, numElementsPerVoxel } = tom; if (type !== 'int32' && type !== 'uint8' && type !== 'float32') { throw new Error(`Invalid tom type ${type} for gpuHelper.createGPUBufferFromTom().`) } // Init empty buffer. // @ts-ignore this.createGPUBuffer(bufferName, null, gpuTypeForType(type), readwrite, dim.x * dim.y * dim.z * numElementsPerVoxel, forceOverwrite); for (let z = 0; z < dim.z; z++) { const array = tom.getData(z); this.copyDataToGPUBuffer(bufferName, array as GPUTypedArray, z * array.length, array.length, true); } // Save and close file. tom.close(); } createFloat32GPUBufferFromTom(bufferName: string, path: string, filename: string, readwrite: ReadWrite, forceOverwrite?: boolean) { const type = getTomDataType(path, filename); if (type === 'float32') { return this.createGPUBufferFromTom(bufferName, path, filename, readwrite, forceOverwrite); } // We need to cast data to float32 before sending to gpu. const tom = new BufferedTomDataR(path, filename, 0); const { dim, numElementsPerVoxel } = tom; // Init empty buffer. // @ts-ignore this.createGPUBuffer(bufferName, null, 'float*', readwrite, dim.x * dim.y * dim.z * numElementsPerVoxel, forceOverwrite); // Init float32 buffer. const floatArray = new Float32Array(dim.x * dim.y * numElementsPerVoxel); for (let z = 0; z < dim.z; z++) { const array = tom.getData(z); for (let i = 0; i < floatArray.length; i++) { floatArray[i] = array[i]; } this.copyDataToGPUBuffer(bufferName, floatArray, z * floatArray.length, floatArray.length, true); } // Save and close file. tom.close(); } createGPUBufferFromBin(bufferName: string, path: string, filename: string, readwrite: ReadWrite, forceOverwrite?: boolean) { // Open file. const file = openSync(`${path}${filename}.bin`, 'r'); const type = getBinDataType(path, filename, file); if (type !== 'int32' && type !== 'uint8' && type !== 'float32') { throw new Error(`Invalid tom type ${type} for gpuHelper.createGPUBufferFromBin().`) } // Get contents. const data = readBin(path, filename, file); // Init empty buffer. // @ts-ignore this.createGPUBuffer(bufferName, data as GPUTypedArray, gpuTypeForType(type), readwrite, data.length, forceOverwrite); // Close file. closeSync(file); } writeTomFromGPUBuffer(bufferName: string, path: string, filename: string, dimensions: Vector3, numElements = 1, useNull = false) { const bufferInfo = this.gpuBuffers[bufferName]; if (!bufferInfo) { throw new Error(`Invalid GPU buffer name: ${bufferName}`); } if (dimensions.x * dimensions.y * dimensions.z * numElements != bufferInfo.length) { throw new Error(`Invalid dimensions ${stringifyVector3(dimensions)} for gpu buffer with type ${bufferInfo.dataType} and length ${bufferInfo.length}.`); } const tom = new BufferedTomDataW(path, filename, typeForGPUType(bufferInfo.dataType) as TomType, dimensions, numElements, useNull); for (let z = 0; z < dimensions.z; z++) { // Copy data into layer buffer and write to disk. const array = tom.getData(); this.copyDataFromGPUBuffer(bufferName, array as GPUTypedArray, z * array.length); tom.writeLayer(z); } // Save and close file. tom.close(); } mutableTypedArrayFromGPUBuffer(bufferName: string, type: Type, useNull: boolean, numElements: number) { const bufferInfo = this.gpuBuffers[bufferName]; if (!bufferInfo) { throw new Error(`Invalid GPU buffer name: ${bufferName}`); } let array; switch(type) { case 'uint8': array = new Uint8Array(bufferInfo.length); break; case 'int32': array = new Int32Array(bufferInfo.length); break; case 'float32': array = new Float32Array(bufferInfo.length); break; default: throw new Error(`Unsupported gpu buffer type ${type}.`); } this.copyDataFromGPUBuffer(bufferName, array); return new MutableTypedArray(array, useNull, numElements); } nullBuffer(bufferName: string) { this.setBufferValue(bufferName, null); } zeroBuffer(bufferName: string) { this.setBufferValue(bufferName, 0); } setBufferValue(bufferName: string, value: number | null) { const { dataType, length } = this.gpuBuffers[bufferName]; // if (isArray(value)) { // length / (value as number[]).length; // if (!isInteger(length)) { // throw new Error(`Invalid value ${value} for buffer of length ${this.gpuBuffers[bufferName].length}.`); // } // switch (dataType) { // case 'float*': // if (!this.gpuProgramExists('setFloatValue')) { // this.initProgram(`./src/common/gpu/setValueProgram.cl`, 'setFloatValue'); // } // this.setBufferArgument('setFloatValue', 0, bufferName); // if (val === null) val = nullValForType('float32'); // this.setKernelArgument('setFloatValue', 1, 'float', val); // this.setKernelArgument('setFloatValue', 1, 'float', val); // this.setKernelArgument('setFloatValue', 1, 'float', val); // this.runProgram('setFloatValue', length); // break; // default: // throw new Error(`Unsupported dataType for gpuHelper.setBufferValue: ${dataType}`); // } // } let val = value as number | null; switch (dataType) { case 'int*': if (!this.gpuProgramExists('setIntValue')) { this.initProgram(`./src/common/gpu/setValueProgram.cl`, 'setIntValue'); } this.setBufferArgument('setIntValue', 0, bufferName); if (val === null) val = nullValForType('int32'); this.setKernelArgument('setIntValue', 1, 'int', val); this.runProgram('setIntValue', length); break; case 'float*': if (!this.gpuProgramExists('setFloatValue')) { this.initProgram(`./src/common/gpu/setValueProgram.cl`, 'setFloatValue'); } this.setBufferArgument('setFloatValue', 0, bufferName); if (val === null) val = nullValForType('float32'); this.setKernelArgument('setFloatValue', 1, 'float', val); this.runProgram('setFloatValue', length); break; case 'uchar*': if (!this.gpuProgramExists('setUCharValue')) { this.initProgram(`./src/common/gpu/setValueProgram.cl`, 'setUCharValue'); } this.setBufferArgument('setUCharValue', 0, bufferName); if (val === null) val = nullValForType('uint8'); this.setKernelArgument('setUCharValue', 1, 'uchar', val); this.runProgram('setUCharValue', length); break; default: throw new Error(`Unsupported dataType for gpuHelper.setBufferValue: ${dataType}`); } } releaseGPUBuffer(bufferName: string) { const bufferInfo = this.gpuBuffers[bufferName]; cl.releaseMemObject(bufferInfo.buffer); delete this.gpuBuffers[bufferName]; // TODO: remove as variable arg. } copyDataToGPUBuffer(bufferName: string, data: GPUTypedArray, start = 0, length = data.length, blocking = true) { const bufferInfo = this.gpuBuffers[bufferName]; if (!bufferInfo) { throw new Error(`Invalid GPU buffer name: ${bufferName}`); } let events = []; // Use blocking copy and store last event. if (blocking) { ({ events } = this); this.events = []; } // try { this.events.push(cl.enqueueWriteBuffer(this.queue, bufferInfo.buffer, true, start * bufferInfo.bytesPerElement, length * bufferInfo.bytesPerElement, data, events, true)); // } catch(error) { // console.log(this.getErrorString(error)); // throw new Error(error); // } } copyDataFromGPUBuffer(bufferName: string, output: GPUTypedArray, start = 0, length = output.length) { const bufferInfo = this.gpuBuffers[bufferName]; if (!bufferInfo) { throw new Error(`Invalid GPU buffer name: ${bufferName}`); } // Use blocking copy and store last event. this.events = [cl.enqueueReadBuffer(this.queue, bufferInfo.buffer, true, start * bufferInfo.bytesPerElement, length * bufferInfo.bytesPerElement, output, this.events, true)]; this.finishAllEvents(); } copyDataToMutableTypedArray(bufferName: string, array: MutableTypedArray, start = 0, length = array.getLength()) { // @ts-ignore this.copyDataFromGPUBuffer(bufferName, array.getData(), start, length * array.numElementsPerIndex); } setKernelArgument(programName: string, num: number, type: KernelVariableType, value: number) { // Check values. switch(type) { case 'uchar': if (!isUint8(value as number)) { throw new Error(`Kernel argument ${value} is not a uint8.`); } break; case 'float': if (!isFloat32(value as number)) { throw new Error(`Kernel argument ${value} is not a float32.`); } break; case 'int': if (!isInt32(value as number)) { throw new Error(`Kernel argument ${value} is not a int32.`); } break; default: throw new Error('Unknown kernel variable type.'); } cl.setKernelArg(this.kernels[programName], num, type, value); } setBufferArgument(programName: string, num: number, bufferName: string) { const bufferInfo = this.gpuBuffers[bufferName]; if (!bufferInfo) { throw new Error(`Unknown buffer: ${bufferName}.`); } const kernel = this.kernels[programName]; if (!kernel) { throw new Error(`Unknown program: ${programName}.`); } cl.setKernelArg(kernel, num, bufferInfo.dataType, bufferInfo.buffer); } runProgram(programName: string, numThreads: number) { this.events = [cl.enqueueNDRangeKernel(this.queue, this.kernels[programName], 1, null, [numThreads], null, this.events, true)]; } finishAllEvents() { if (this.events.length === 0) { return; } cl.waitForEvents(this.events); this.events = []; } clear(gpuBuffersToKeep: string[] = []) { this.finishAllEvents(); Object.values(this.gpuBuffers).forEach((bufferInfo) => { if (gpuBuffersToKeep.indexOf(bufferInfo.bufferName) >= 0) { return; } cl.releaseMemObject(bufferInfo.buffer); delete this.gpuBuffers[bufferInfo.bufferName]; }); Object.values(this.kernels).forEach((kernel) => { cl.releaseKernel(kernel); }); this.events.forEach((event) => { cl.releaseEvent(event); }); cl.finish(this.queue); this.kernels = {}; this.events = []; } getErrorString(error: number) { switch(error){ // run-time and JIT compiler errors case 0: return "CL_SUCCESS"; case -1: return "CL_DEVICE_NOT_FOUND"; case -2: return "CL_DEVICE_NOT_AVAILABLE"; case -3: return "CL_COMPILER_NOT_AVAILABLE"; case -4: return "CL_MEM_OBJECT_ALLOCATION_FAILURE"; case -5: return "CL_OUT_OF_RESOURCES"; case -6: return "CL_OUT_OF_HOST_MEMORY"; case -7: return "CL_PROFILING_INFO_NOT_AVAILABLE"; case -8: return "CL_MEM_COPY_OVERLAP"; case -9: return "CL_IMAGE_FORMAT_MISMATCH"; case -10: return "CL_IMAGE_FORMAT_NOT_SUPPORTED"; case -11: return "CL_BUILD_PROGRAM_FAILURE"; case -12: return "CL_MAP_FAILURE"; case -13: return "CL_MISALIGNED_SUB_BUFFER_OFFSET"; case -14: return "CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST"; case -15: return "CL_COMPILE_PROGRAM_FAILURE"; case -16: return "CL_LINKER_NOT_AVAILABLE"; case -17: return "CL_LINK_PROGRAM_FAILURE"; case -18: return "CL_DEVICE_PARTITION_FAILED"; case -19: return "CL_KERNEL_ARG_INFO_NOT_AVAILABLE"; // compile-time errors case -30: return "CL_INVALID_VALUE"; case -31: return "CL_INVALID_DEVICE_TYPE"; case -32: return "CL_INVALID_PLATFORM"; case -33: return "CL_INVALID_DEVICE"; case -34: return "CL_INVALID_CONTEXT"; case -35: return "CL_INVALID_QUEUE_PROPERTIES"; case -36: return "CL_INVALID_COMMAND_QUEUE"; case -37: return "CL_INVALID_HOST_PTR"; case -38: return "CL_INVALID_MEM_OBJECT"; case -39: return "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR"; case -40: return "CL_INVALID_IMAGE_SIZE"; case -41: return "CL_INVALID_SAMPLER"; case -42: return "CL_INVALID_BINARY"; case -43: return "CL_INVALID_BUILD_OPTIONS"; case -44: return "CL_INVALID_PROGRAM"; case -45: return "CL_INVALID_PROGRAM_EXECUTABLE"; case -46: return "CL_INVALID_KERNEL_NAME"; case -47: return "CL_INVALID_KERNEL_DEFINITION"; case -48: return "CL_INVALID_KERNEL"; case -49: return "CL_INVALID_ARG_INDEX"; case -50: return "CL_INVALID_ARG_VALUE"; case -51: return "CL_INVALID_ARG_SIZE"; case -52: return "CL_INVALID_KERNEL_ARGS"; case -53: return "CL_INVALID_WORK_DIMENSION"; case -54: return "CL_INVALID_WORK_GROUP_SIZE"; case -55: return "CL_INVALID_WORK_ITEM_SIZE"; case -56: return "CL_INVALID_GLOBAL_OFFSET"; case -57: return "CL_INVALID_EVENT_WAIT_LIST"; case -58: return "CL_INVALID_EVENT"; case -59: return "CL_INVALID_OPERATION"; case -60: return "CL_INVALID_GL_OBJECT"; case -61: return "CL_INVALID_BUFFER_SIZE"; case -62: return "CL_INVALID_MIP_LEVEL"; case -63: return "CL_INVALID_GLOBAL_WORK_SIZE"; case -64: return "CL_INVALID_PROPERTY"; case -65: return "CL_INVALID_IMAGE_DESCRIPTOR"; case -66: return "CL_INVALID_COMPILER_OPTIONS"; case -67: return "CL_INVALID_LINKER_OPTIONS"; case -68: return "CL_INVALID_DEVICE_PARTITION_COUNT"; // extension errors case -1000: return "CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR"; case -1001: return "CL_PLATFORM_NOT_FOUND_KHR"; case -1002: return "CL_INVALID_D3D10_DEVICE_KHR"; case -1003: return "CL_INVALID_D3D10_RESOURCE_KHR"; case -1004: return "CL_D3D10_RESOURCE_ALREADY_ACQUIRED_KHR"; case -1005: return "CL_D3D10_RESOURCE_NOT_ACQUIRED_KHR"; default: return "Unknown OpenCL error"; } } destroy() { this.clear(); // Deallocate context, queue, device. cl.releaseContext(this.context); this.context = null; cl.releaseCommandQueue(this.queue); this.queue = null; // TODO: release device? // cl.releaseDevice(this.device); this.device = null; } }
the_stack
import React, { useState, useEffect } from 'react'; import * as actions from '../../actions'; import { connect } from "react-redux"; import { Dispatch } from 'redux'; import { FormComponentProps } from 'antd/lib/form'; import { Select, Form, Input, Switch, Radio, DatePicker, Row, Col, Collapse } from 'antd'; import { getServices, getHostListbyServiceId } from '../../api/agent'; import { IService, IHosts } from '../../interface/agent'; import { contentFormItemLayout } from './config'; import { regName, regText } from '../../constants/reg'; import { UpOutlined, DownOutlined } from '@ant-design/icons'; import moment from 'moment'; import { setHostNameList } from './dateRegAndGvar' import './index.less'; const { RangePicker } = DatePicker; const { TextArea } = Input; const { Panel } = Collapse; interface ICollectObjectProps extends FormComponentProps { collectMode: number; openHistory: boolean; historyFilter: string; hostRange: number; hostWhite: string; hostNames: string; setisNotLogPath: any; } const mapDispatchToProps = (dispatch: Dispatch) => ({ setCollectType: (collectType: number) => dispatch(actions.setCollectType(collectType)), }); type Props = ReturnType<typeof mapDispatchToProps>; const CollectObjectConfiguration = (props: Props & ICollectObjectProps) => { const { getFieldDecorator, getFieldValue, resetFields } = props.form; const editUrl = window.location.pathname.includes('/edit-task'); const [collectMode, setCollectMode] = useState(0); const [openHistory, setOpenHistory] = useState(false); const [historyFilter, setHistoryFilter] = useState('current'); const [hostRange, setHostRange] = useState(0); const [hostWhite, setHostWhite] = useState('hostname'); const [serviceList, setServiceList] = useState([] as IService[]); const [suHostList, setSuHostList] = useState<any>([]); const [activeKeys, setActiveKeys] = useState([] as string[]); const onModeChange = (e: any) => { setCollectMode(e.target.value); props.setCollectType(e.target.value); } const customPanelStyle = { border: 0, overflow: 'hidden', padding: '10px 0 0', background: '#fafafa', }; const openHistoryChange = (checked: any) => { setOpenHistory(checked); } const onHistoryFilterChange = (e: any) => { setHistoryFilter(e.target.value); } const onHostRangeChange = (e: any) => { setHostRange(e.target.value); } const onHostWhiteListChange = (e: any) => { setHostWhite(e.target.value); } const getServicesData = () => { getServices().then((res: IService[]) => { setServiceList(res); }).catch((err: any) => { // console.log(err); }); } const getSuHostlist = (appId: number) => { getHostListbyServiceId(appId).then((res: any) => { setSuHostList(res.hostList); setHostNameList(res.hostList) }).catch((err: any) => { // console.log(err); }); } const onAppSelectChange = (value: number) => { // resetFields(['step1_hostNames']) setSuHostList([]); setHostNameList([]) getSuHostlist(value); props.setisNotLogPath(false) } useEffect(() => { getServicesData(); if (editUrl) { setCollectMode(props.collectMode); setOpenHistory(props.openHistory); setHistoryFilter(props.historyFilter); setHostRange(props.hostRange); setHostWhite(props.hostWhite); setSuHostList([...props.hostNames]); } }, [props.collectMode, props.openHistory, props.openHistory, props.historyFilter, props.hostRange, props.hostWhite, props.hostNames]); const collapseCallBack = (key: any) => { setActiveKeys(key); } return ( <div className="set-up collection-object"> <Form {...contentFormItemLayout}> <Form.Item label="日志采集任务名"> {getFieldDecorator('step1_logCollectTaskName', { initialValue: '', rules: [{ required: true, message: '请输入日志采集任务名,支持大小写中英文字母、数字、下划线、点、短横线,32位限制', validator: (rule: any, value: string) => { return !!value && new RegExp(regName).test(value); }, }], })( <Input placeholder="请输入" />, )} </Form.Item> <Form.Item label="采集应用"> {getFieldDecorator('step1_serviceId', { // initialValue: '', rules: [{ required: true, message: '请选择采集应用' }], })( <Select className="select" showSearch={true} onChange={onAppSelectChange} filterOption={(input: string, option: any) => { if (typeof option.props.children === 'object') { const { props } = option.props.children as any; return (props.children + '').toLowerCase().indexOf(input.toLowerCase()) >= 0; } return (option.props.children + '').toLowerCase().indexOf(input.toLowerCase()) >= 0; }} placeholder="请选择应用" > {serviceList && serviceList.map((groupOption, index) => { return ( <Select.Option key={index} value={groupOption.id}> {groupOption.servicename} </Select.Option> ); })} </Select>, )} </Form.Item> {/* <Form.Item label="所属项目"> {getFieldDecorator('step1_project', { initialValue: '', })(<span />)} </Form.Item> */} {/*<Collapse bordered={false} expandIconPosition="right" onChange={collapseCallBack} activeKey={activeKeys?.length ? ['high'] : []} destroyInactivePanel style={{ background: 'none', padding: '0 50px' }} > <Panel header={<h2 style={{ display: 'inline-block', color: '#a2a2a5', marginLeft: '15px' }}>高级配置</h2>} extra={<a>{activeKeys?.length ? <>收起&nbsp;<UpOutlined /></> : <>展开&nbsp;<DownOutlined /></>}</a>} showArrow={false} key="high" style={customPanelStyle} > <Row className="form-row"> <Form.Item label="采集模式"> <Col span={4}> {getFieldDecorator('step1_logCollectTaskType', { initialValue: 0, rules: [{ required: true, message: '请选择采集模式' }], })( <Radio.Group onChange={onModeChange}> <Radio value={0}>流式</Radio> <Radio value={1}>时间段</Radio> </Radio.Group>, )} </Col> <Col span={8}> {collectMode === 1 && <Form.Item> {getFieldDecorator('step1_collectBusinessTime', { // collectStartBusinessTime collectEndBusinessTime initialValue: [], rules: [{ required: true, message: '请选择时间段' }], })(<RangePicker showTime format="YYYY/MM/DD HH:mm:ss" />)} </Form.Item>} </Col> </Form.Item> </Row> {collectMode === 0 && <Row className="form-row"> <Form.Item label="历史数据过滤"> <Col span={2}> {getFieldDecorator('step1_openHistory', { initialValue: false, valuePropName: 'checked', rules: [{ required: true, message: '是否开启历史数据过滤' }], })( <Switch onChange={openHistoryChange} />, )} </Col> <Col span={8}> {openHistory && <Form.Item> {getFieldDecorator('step1_historyFilter', { initialValue: 'current', rules: [{ required: true, message: '请选择历史数据过滤' }], })( <Radio.Group onChange={onHistoryFilterChange}> <Radio value={'current'}>从当前开始采集</Radio> <Radio value={'custom'}>自定义采集开始时间</Radio> </Radio.Group>, )} </Form.Item>} </Col> <Col span={8}> {openHistory && historyFilter === 'custom' && <Form.Item> {getFieldDecorator('step1_collectStartBusinessTime', { initialValue: moment(), rules: [{ required: true, message: '请选择时间' }], })( <DatePicker showTime placeholder="请选择时间" /> )} </Form.Item>} </Col> </Form.Item> </Row>} <Form.Item label="主机范围"> {getFieldDecorator('step1_needHostFilterRule', { initialValue: 0, rules: [{ required: true, message: '请选择主机范围' }], })( <Radio.Group onChange={onHostRangeChange}> <Radio value={0}>全部</Radio> <Radio value={1}>部分</Radio> </Radio.Group> )} </Form.Item> {hostRange === 1 && <Form.Item label="主机白名单"> {getFieldDecorator('step1_hostWhiteList', { initialValue: 'hostname', rules: [{ required: true, message: '请选择主机白名单' }], })( <Radio.Group onChange={onHostWhiteListChange}> <Row> <Col span={10} className="col-radio-host"> <Radio className="radio-host-name" value={'hostname'}> <span className="radio-host-span">主机名:</span> <Form.Item className="radio-form"> {getFieldDecorator('step1_hostNames', { initialValue: [], rules: [{ required: hostWhite === 'hostname', message: '请选择主机名' }], })( <Select className='w-300' showSearch={true} optionFilterProp="children" mode="multiple" filterOption={(input: string, option: any) => { return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0; }} > {suHostList && suHostList.map((groupOption: any, index: number) => { return ( <Select.Option key={index} value={groupOption.id}> {groupOption.hostName} </Select.Option> ); })} </Select> )} </Form.Item> </Radio> </Col> <Col span={10} className="col-radio-host"> <Radio className="radio-host-name" value={'sql'}> <span className="radio-host-span">SQL匹配:</span> <Form.Item className="radio-form"> {getFieldDecorator('step1_filterSQL', { initialValue: '', rules: [{ required: hostWhite === 'sql', message: '请输入SQL匹配' }], })(<Input className='w-300' placeholder='请输入' />)} </Form.Item> </Radio> </Col> </Row> </Radio.Group> )} </Form.Item>} </Panel> </Collapse>*/} {/* <Form.Item label="采集任务描述"> {getFieldDecorator('step1_logCollectTaskRemark', { initialValue: '', rules: [{ required: false, message: '请输入对该采集任务的描述,50位限制', validator: (rule: any, value: string) => { return new RegExp(regText).test(value); }, }], })(<TextArea placeholder="请输入对该采集任务的描述" rows={3} />)} </Form.Item> */} </Form> </div> ); }; export default connect(null, mapDispatchToProps)(CollectObjectConfiguration);
the_stack
import fse from 'fs-extra'; import path from 'path'; import winston from 'winston'; const logger = winston.createLogger({ level: 'verbose', defaultMeta: {service: 'user-service'}, format: winston.format.combine( winston.format.timestamp(), winston.format.json(), ), transports: [ new winston.transports.File({ filename: 'filter_group_error.log', level: 'error', dirname: 'logs', }), new winston.transports.File({ filename: 'filter_group_combined.log', dirname: 'logs', }), ], }); const rawPatchStore = 'E:\\github\\office-android-patches\\patches'; const filteredGroupedPatchStore = 'E:\\github\\office-android-patches\\patches-droid-office-grouped'; if (fse.existsSync(filteredGroupedPatchStore)) { logger.error('Output directory exists !'); process.exit(); } fse.ensureDirSync(filteredGroupedPatchStore); // Known groups const OfficeRNHostDir = 'OfficeRNHost'; const V8IntegrationDir = 'V8Integration'; const AccessibilityDir = 'Accessibility'; const UIScollChangesDir = 'UIScroll'; const UITextFontChangesDir = 'UITextFont'; const UIEditTextChangesDir = 'UIEditText'; const DialogModuleDir = 'DialogModule'; const AnnotationProcessingDir = 'AnnotationProcessing'; const BuildAndThirdPartyFixesDir = 'BuildAndThirdPartyFixes'; const SecurityFixesDir = 'SecurityFixes'; const processFile = ( patchFileRelativePath: string, groupName: string, ): void => { const patchFileName = path.basename(patchFileRelativePath); // Source path. const patchFileSourceAbsPath = path.resolve( rawPatchStore, patchFileRelativePath, ); // Create destination path. const patchFileRelativeDir = path.parse(patchFileRelativePath).dir; const groupDir = path.resolve(filteredGroupedPatchStore, groupName); const patchFileAbsDir = path.resolve(groupDir, patchFileRelativeDir); fse.ensureDirSync(patchFileAbsDir); const patchFileDestAbsPath = path.resolve(patchFileAbsDir, patchFileName); fse.copyFileSync(patchFileSourceAbsPath, patchFileDestAbsPath); }; // Annotation Processing processFile('settings.gradle.kts', AnnotationProcessingDir); processFile('processor\\build.gradle', AnnotationProcessingDir); processFile( 'processor\\libs\\infer-annotations-1.5.jar', AnnotationProcessingDir, ); processFile( 'processor\\src\\main\\resources\\META-INF\\services\\javax.annotation.processing.Processor', AnnotationProcessingDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\processing\\ReactNativeModuleProcessor.java', AnnotationProcessingDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\bridge\\AcJavaModuleWrapper.java', AnnotationProcessingDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\bridge\\JavaModuleWrapper.java', AnnotationProcessingDir, ); //OfficeRNHost processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\bridge\\CatalystInstance.java', OfficeRNHostDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\bridge\\CatalystInstanceImpl.java', OfficeRNHostDir, ); // processFile( // 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\bridge\\DynamicFromObject.java', // OfficeRNHostDir, // ); // processFile( // 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\bridge\\NativeModuleRegistry.java', // OfficeRNHostDir, // ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\bridge\\ReactBridge.java', OfficeRNHostDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\ReactInstanceManager.java', OfficeRNHostDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\ReactInstanceManagerBuilder.java', OfficeRNHostDir, ); processFile('ReactCommon\\cxxreact\\CxxNativeModule.cpp', OfficeRNHostDir); processFile('ReactCommon\\cxxreact\\CxxNativeModule.h', OfficeRNHostDir); processFile('ReactCommon\\cxxreact\\Instance.cpp', OfficeRNHostDir); processFile('ReactCommon\\cxxreact\\Instance.h', OfficeRNHostDir); processFile('ReactCommon\\cxxreact\\JSExecutor.h', OfficeRNHostDir); processFile('ReactCommon\\cxxreact\\NativeToJsBridge.cpp', OfficeRNHostDir); processFile('ReactCommon\\cxxreact\\NativeToJsBridge.h', OfficeRNHostDir); processFile('ReactCommon\\cxxreact\\PlatformBundleInfo.h', OfficeRNHostDir); processFile( 'ReactAndroid\\src\\main\\jni\\react\\jni\\CatalystInstanceImpl.cpp', OfficeRNHostDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\react\\jni\\CatalystInstanceImpl.h', OfficeRNHostDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\react\\jni\\JMessageQueueThread.cpp', OfficeRNHostDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\react\\jni\\JReactMarker.cpp', OfficeRNHostDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\react\\jni\\JReactMarker.h', OfficeRNHostDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\react\\jni\\JSLogging.h', OfficeRNHostDir, ); // DialogModule processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\modules\\datepicker\\DatePickerDialogModule.java', DialogModuleDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\modules\\dialog\\DialogModule.java', DialogModuleDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\modules\\dialog\\PlatformAlertFragment.java', DialogModuleDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\modules\\timepicker\\TimePickerDialogModule.java', DialogModuleDir, ); // UIScroll processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\views\\scroll\\ReactHorizontalScrollView.java', UIScollChangesDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\views\\scroll\\ReactScrollView.java', UIScollChangesDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\views\\scroll\\ReactScrollViewManager.java', UIScollChangesDir, ); // UITextFont processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\views\\text\\ReactFontManager.java', UITextFontChangesDir, ); // processFile( // 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\views\\text\\ReactTextShadowNode.java', // UITextFontChangesDir, // ); // processFile( // 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\views\\text\\ReactTextView.java', // UITextFontChangesDir, // ); //UIEditTextChanges processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\views\\textinput\\ReactEditText.java', UIEditTextChangesDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\views\\textinput\\ReactTextInputManager.java', UIEditTextChangesDir, ); processFile( 'Libraries\\Components\\TextInput\\TextInput.js', UIEditTextChangesDir, ); processFile( 'Libraries\\Components\\TextInput\\TextInputState.js', UIEditTextChangesDir, ); // Accessibility processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\views\\view\\ReactViewManager.java', AccessibilityDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\uimanager\\BaseViewManager.java', AccessibilityDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\uimanager\\NativeViewHierarchyManager.java', AccessibilityDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\uimanager\\UIImplementation.java', AccessibilityDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\uimanager\\UIManagerModule.java', AccessibilityDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\uimanager\\UIViewOperationQueue.java', AccessibilityDir, ); // processFile( // 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\uimanager\\ViewManager.java', // AccessibilityDir, // ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\uimanager\\ViewManagerRegistry.java', AccessibilityDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\views\\view\\ReactViewFocusEvent.java', AccessibilityDir, ); // V8Integration processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\v8executor\\Android.mk', V8IntegrationDir, ); // processFile( // 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\v8executor\\BUCK', // V8IntegrationDir, // ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\v8executor\\InstanceManager.cpp', V8IntegrationDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\v8executor\\InstanceManager.h', V8IntegrationDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\v8executor\\OnLoad.cpp', V8IntegrationDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\v8executor\\V8Executor.java', V8IntegrationDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\v8executor\\V8ExecutorFactory.cpp', V8IntegrationDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\v8executor\\V8ExecutorFactory.h', V8IntegrationDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\v8executor\\V8ExecutorFactory.java', V8IntegrationDir, ); processFile('ReactCommon\\jsi\\Android.mk', V8IntegrationDir); processFile('ReactCommon\\jsi\\FileUtils.cpp', V8IntegrationDir); processFile('ReactCommon\\jsi\\FileUtils.h', V8IntegrationDir); processFile('ReactCommon\\jsi\\V8Platform.cpp', V8IntegrationDir); processFile('ReactCommon\\jsi\\V8Platform.h', V8IntegrationDir); processFile('ReactCommon\\jsi\\V8Runtime.h', V8IntegrationDir); processFile('ReactCommon\\jsi\\V8Runtime_basic.cpp', V8IntegrationDir); processFile('ReactCommon\\jsi\\V8Runtime_droid.cpp', V8IntegrationDir); processFile('ReactCommon\\jsi\\V8Runtime_impl.h', V8IntegrationDir); processFile('ReactCommon\\jsi\\V8Runtime_shared.cpp', V8IntegrationDir); processFile('ReactCommon\\jsi\\V8Runtime_win.cpp', V8IntegrationDir); processFile( 'ReactAndroid\\src\\main\\jni\\react\\jni\\Android.mk', V8IntegrationDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\third-party\\v8\\Android.mk', V8IntegrationDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\third-party\\v8\\base.mk', V8IntegrationDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\third-party\\v8base\\Android.mk', V8IntegrationDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\third-party\\v8platform\\Android.mk', V8IntegrationDir, ); processFile( 'ReactAndroid\\src\\main\\java\\com\\facebook\\react\\bridge\\ReactMarkerConstants.java', V8IntegrationDir, ); processFile('ReactCommon\\cxxreact\\ReactMarker.h', V8IntegrationDir); // BuildAndThirdPartyFixes processFile( 'ReactAndroid\\src\\main\\jni\\Application.mk', BuildAndThirdPartyFixesDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\third-party\\boost\\Android.mk', BuildAndThirdPartyFixesDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\third-party\\double-conversion\\Android.mk', BuildAndThirdPartyFixesDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\third-party\\folly\\Android.mk', BuildAndThirdPartyFixesDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\third-party\\glog\\Android.mk', BuildAndThirdPartyFixesDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\third-party\\glog\\config.h', BuildAndThirdPartyFixesDir, ); // processFile( // 'ReactAndroid\\src\\main\\jni\\third-party\\jsc\\Android.mk', // BuildAndThirdPartyFixesDir, // ); processFile('ReactAndroid\\build.gradle', BuildAndThirdPartyFixesDir); processFile('ReactAndroid\\NuGet.Config', BuildAndThirdPartyFixesDir); processFile('ReactAndroid\\packages.config', BuildAndThirdPartyFixesDir); processFile('ReactAndroid\\ReactAndroid.nuspec', BuildAndThirdPartyFixesDir); // Security processFile( 'ReactAndroid\\src\\main\\jni\\first-party\\fb\\Android.mk', SecurityFixesDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\first-party\\fb\\assert.cpp', SecurityFixesDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\first-party\\fb\\CRTSafeAPIs.cpp', SecurityFixesDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\first-party\\fb\\log.cpp', SecurityFixesDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\first-party\\fb\\include\\fb\\CRTSafeAPIs.h', SecurityFixesDir, ); processFile( 'ReactAndroid\\src\\main\\jni\\first-party\\fb\\jni\\jni_helpers.cpp', SecurityFixesDir, ); // processFile( // 'ReactAndroid\\src\\main\\jni\\first-party\\yogajni\\Android.mk', // SecurityFixesDir, // ); processFile( 'ReactAndroid\\src\\main\\jni\\first-party\\yogajni\\jni\\YGJNI.cpp', SecurityFixesDir, );
the_stack
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { ParseTreeListener } from "antlr4ts/tree/ParseTreeListener"; import { ParenthesisExpContext } from "./ExpressionAntlrParser"; import { ArrayCreationExpContext } from "./ExpressionAntlrParser"; import { JsonCreationExpContext } from "./ExpressionAntlrParser"; import { NumericAtomContext } from "./ExpressionAntlrParser"; import { StringAtomContext } from "./ExpressionAntlrParser"; import { IdAtomContext } from "./ExpressionAntlrParser"; import { StringInterpolationAtomContext } from "./ExpressionAntlrParser"; import { MemberAccessExpContext } from "./ExpressionAntlrParser"; import { FuncInvokeExpContext } from "./ExpressionAntlrParser"; import { IndexAccessExpContext } from "./ExpressionAntlrParser"; import { UnaryOpExpContext } from "./ExpressionAntlrParser"; import { BinaryOpExpContext } from "./ExpressionAntlrParser"; import { TripleOpExpContext } from "./ExpressionAntlrParser"; import { PrimaryExpContext } from "./ExpressionAntlrParser"; import { FileContext } from "./ExpressionAntlrParser"; import { ExpressionContext } from "./ExpressionAntlrParser"; import { PrimaryExpressionContext } from "./ExpressionAntlrParser"; import { StringInterpolationContext } from "./ExpressionAntlrParser"; import { TextContentContext } from "./ExpressionAntlrParser"; import { ArgsListContext } from "./ExpressionAntlrParser"; import { LambdaContext } from "./ExpressionAntlrParser"; import { KeyValuePairListContext } from "./ExpressionAntlrParser"; import { KeyValuePairContext } from "./ExpressionAntlrParser"; import { KeyContext } from "./ExpressionAntlrParser"; /** * This interface defines a complete listener for a parse tree produced by * `ExpressionAntlrParser`. */ export interface ExpressionAntlrParserListener extends ParseTreeListener { /** * Enter a parse tree produced by the `parenthesisExp` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ enterParenthesisExp?: (ctx: ParenthesisExpContext) => void; /** * Exit a parse tree produced by the `parenthesisExp` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ exitParenthesisExp?: (ctx: ParenthesisExpContext) => void; /** * Enter a parse tree produced by the `arrayCreationExp` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ enterArrayCreationExp?: (ctx: ArrayCreationExpContext) => void; /** * Exit a parse tree produced by the `arrayCreationExp` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ exitArrayCreationExp?: (ctx: ArrayCreationExpContext) => void; /** * Enter a parse tree produced by the `jsonCreationExp` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ enterJsonCreationExp?: (ctx: JsonCreationExpContext) => void; /** * Exit a parse tree produced by the `jsonCreationExp` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ exitJsonCreationExp?: (ctx: JsonCreationExpContext) => void; /** * Enter a parse tree produced by the `numericAtom` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ enterNumericAtom?: (ctx: NumericAtomContext) => void; /** * Exit a parse tree produced by the `numericAtom` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ exitNumericAtom?: (ctx: NumericAtomContext) => void; /** * Enter a parse tree produced by the `stringAtom` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ enterStringAtom?: (ctx: StringAtomContext) => void; /** * Exit a parse tree produced by the `stringAtom` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ exitStringAtom?: (ctx: StringAtomContext) => void; /** * Enter a parse tree produced by the `idAtom` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ enterIdAtom?: (ctx: IdAtomContext) => void; /** * Exit a parse tree produced by the `idAtom` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ exitIdAtom?: (ctx: IdAtomContext) => void; /** * Enter a parse tree produced by the `stringInterpolationAtom` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ enterStringInterpolationAtom?: (ctx: StringInterpolationAtomContext) => void; /** * Exit a parse tree produced by the `stringInterpolationAtom` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ exitStringInterpolationAtom?: (ctx: StringInterpolationAtomContext) => void; /** * Enter a parse tree produced by the `memberAccessExp` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ enterMemberAccessExp?: (ctx: MemberAccessExpContext) => void; /** * Exit a parse tree produced by the `memberAccessExp` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ exitMemberAccessExp?: (ctx: MemberAccessExpContext) => void; /** * Enter a parse tree produced by the `funcInvokeExp` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ enterFuncInvokeExp?: (ctx: FuncInvokeExpContext) => void; /** * Exit a parse tree produced by the `funcInvokeExp` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ exitFuncInvokeExp?: (ctx: FuncInvokeExpContext) => void; /** * Enter a parse tree produced by the `indexAccessExp` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ enterIndexAccessExp?: (ctx: IndexAccessExpContext) => void; /** * Exit a parse tree produced by the `indexAccessExp` * labeled alternative in `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ exitIndexAccessExp?: (ctx: IndexAccessExpContext) => void; /** * Enter a parse tree produced by the `unaryOpExp` * labeled alternative in `ExpressionAntlrParser.expression`. * @param ctx the parse tree */ enterUnaryOpExp?: (ctx: UnaryOpExpContext) => void; /** * Exit a parse tree produced by the `unaryOpExp` * labeled alternative in `ExpressionAntlrParser.expression`. * @param ctx the parse tree */ exitUnaryOpExp?: (ctx: UnaryOpExpContext) => void; /** * Enter a parse tree produced by the `binaryOpExp` * labeled alternative in `ExpressionAntlrParser.expression`. * @param ctx the parse tree */ enterBinaryOpExp?: (ctx: BinaryOpExpContext) => void; /** * Exit a parse tree produced by the `binaryOpExp` * labeled alternative in `ExpressionAntlrParser.expression`. * @param ctx the parse tree */ exitBinaryOpExp?: (ctx: BinaryOpExpContext) => void; /** * Enter a parse tree produced by the `tripleOpExp` * labeled alternative in `ExpressionAntlrParser.expression`. * @param ctx the parse tree */ enterTripleOpExp?: (ctx: TripleOpExpContext) => void; /** * Exit a parse tree produced by the `tripleOpExp` * labeled alternative in `ExpressionAntlrParser.expression`. * @param ctx the parse tree */ exitTripleOpExp?: (ctx: TripleOpExpContext) => void; /** * Enter a parse tree produced by the `primaryExp` * labeled alternative in `ExpressionAntlrParser.expression`. * @param ctx the parse tree */ enterPrimaryExp?: (ctx: PrimaryExpContext) => void; /** * Exit a parse tree produced by the `primaryExp` * labeled alternative in `ExpressionAntlrParser.expression`. * @param ctx the parse tree */ exitPrimaryExp?: (ctx: PrimaryExpContext) => void; /** * Enter a parse tree produced by `ExpressionAntlrParser.file`. * @param ctx the parse tree */ enterFile?: (ctx: FileContext) => void; /** * Exit a parse tree produced by `ExpressionAntlrParser.file`. * @param ctx the parse tree */ exitFile?: (ctx: FileContext) => void; /** * Enter a parse tree produced by `ExpressionAntlrParser.expression`. * @param ctx the parse tree */ enterExpression?: (ctx: ExpressionContext) => void; /** * Exit a parse tree produced by `ExpressionAntlrParser.expression`. * @param ctx the parse tree */ exitExpression?: (ctx: ExpressionContext) => void; /** * Enter a parse tree produced by `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ enterPrimaryExpression?: (ctx: PrimaryExpressionContext) => void; /** * Exit a parse tree produced by `ExpressionAntlrParser.primaryExpression`. * @param ctx the parse tree */ exitPrimaryExpression?: (ctx: PrimaryExpressionContext) => void; /** * Enter a parse tree produced by `ExpressionAntlrParser.stringInterpolation`. * @param ctx the parse tree */ enterStringInterpolation?: (ctx: StringInterpolationContext) => void; /** * Exit a parse tree produced by `ExpressionAntlrParser.stringInterpolation`. * @param ctx the parse tree */ exitStringInterpolation?: (ctx: StringInterpolationContext) => void; /** * Enter a parse tree produced by `ExpressionAntlrParser.textContent`. * @param ctx the parse tree */ enterTextContent?: (ctx: TextContentContext) => void; /** * Exit a parse tree produced by `ExpressionAntlrParser.textContent`. * @param ctx the parse tree */ exitTextContent?: (ctx: TextContentContext) => void; /** * Enter a parse tree produced by `ExpressionAntlrParser.argsList`. * @param ctx the parse tree */ enterArgsList?: (ctx: ArgsListContext) => void; /** * Exit a parse tree produced by `ExpressionAntlrParser.argsList`. * @param ctx the parse tree */ exitArgsList?: (ctx: ArgsListContext) => void; /** * Enter a parse tree produced by `ExpressionAntlrParser.lambda`. * @param ctx the parse tree */ enterLambda?: (ctx: LambdaContext) => void; /** * Exit a parse tree produced by `ExpressionAntlrParser.lambda`. * @param ctx the parse tree */ exitLambda?: (ctx: LambdaContext) => void; /** * Enter a parse tree produced by `ExpressionAntlrParser.keyValuePairList`. * @param ctx the parse tree */ enterKeyValuePairList?: (ctx: KeyValuePairListContext) => void; /** * Exit a parse tree produced by `ExpressionAntlrParser.keyValuePairList`. * @param ctx the parse tree */ exitKeyValuePairList?: (ctx: KeyValuePairListContext) => void; /** * Enter a parse tree produced by `ExpressionAntlrParser.keyValuePair`. * @param ctx the parse tree */ enterKeyValuePair?: (ctx: KeyValuePairContext) => void; /** * Exit a parse tree produced by `ExpressionAntlrParser.keyValuePair`. * @param ctx the parse tree */ exitKeyValuePair?: (ctx: KeyValuePairContext) => void; /** * Enter a parse tree produced by `ExpressionAntlrParser.key`. * @param ctx the parse tree */ enterKey?: (ctx: KeyContext) => void; /** * Exit a parse tree produced by `ExpressionAntlrParser.key`. * @param ctx the parse tree */ exitKey?: (ctx: KeyContext) => void; }
the_stack
import * as sinon from 'sinon'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import Hls from '../../../src/hls'; import BufferOperationQueue from '../../../src/controller/buffer-operation-queue'; import BufferController from '../../../src/controller/buffer-controller'; import { BufferOperation, SourceBufferName } from '../../../src/types/buffer'; import { BufferAppendingData } from '../../../src/types/events'; import { Events } from '../../../src/events'; import { ErrorDetails, ErrorTypes } from '../../../src/errors'; import { ElementaryStreamTypes, Fragment } from '../../../src/loader/fragment'; import { PlaylistLevelType } from '../../../src/types/loader'; import { ChunkMetadata } from '../../../src/types/transmuxer'; import { LevelDetails } from '../../../src/loader/level-details'; chai.use(sinonChai); const expect = chai.expect; const sandbox = sinon.createSandbox(); class MockMediaSource { public readyState: string = 'open'; public duration: number = Infinity; addSourceBuffer(): MockSourceBuffer { return new MockSourceBuffer(); } addEventListener() {} removeEventListener() {} endOfStream() {} } class MockSourceBuffer extends EventTarget { public updating: boolean = false; public appendBuffer = sandbox.stub(); public remove = sandbox.stub(); public buffered = { start() { return this._start; }, end() { return this._end; }, length: 1, _start: 0, _end: 0, }; setBuffered(start, end) { this.buffered._start = start; this.buffered._end = end; this.buffered.length = start === end ? 0 : 1; } } class MockMediaElement { public currentTime: number = 0; public duration: number = Infinity; public textTracks: any[] = []; } const queueNames: Array<SourceBufferName> = ['audio', 'video']; describe('BufferController', function () { let hls; let bufferController; let operationQueue; let triggerSpy; let shiftAndExecuteNextSpy; let queueAppendBlockerSpy; let mockMedia; let mockMediaSource; beforeEach(function () { hls = new Hls({}); bufferController = new BufferController(hls); bufferController.media = mockMedia = new MockMediaElement(); bufferController.mediaSource = mockMediaSource = new MockMediaSource(); bufferController.createSourceBuffers({ audio: {}, video: {}, }); operationQueue = new BufferOperationQueue(bufferController.sourceBuffer); bufferController.operationQueue = operationQueue; triggerSpy = sandbox.spy(hls, 'trigger'); shiftAndExecuteNextSpy = sandbox.spy(operationQueue, 'shiftAndExecuteNext'); queueAppendBlockerSpy = sandbox.spy(operationQueue, 'appendBlocker'); }); afterEach(function () { sandbox.restore(); }); it('cycles the SourceBuffer operation queue on updateend', function () { const currentOnComplete = sandbox.spy(); const currentOperation: BufferOperation = { execute: () => {}, onStart: () => {}, onComplete: currentOnComplete, onError: () => {}, }; const nextExecute = sandbox.spy(); const nextOperation: BufferOperation = { execute: nextExecute, onStart: () => {}, onComplete: () => {}, onError: () => {}, }; queueNames.forEach((name, i) => { const currentQueue = operationQueue.queues[name]; currentQueue.push(currentOperation, nextOperation); bufferController.sourceBuffer[name].dispatchEvent(new Event('updateend')); expect( currentOnComplete, 'onComplete should have been called on the current operation' ).to.have.callCount(i + 1); expect( shiftAndExecuteNextSpy, 'The queue should have been cycled' ).to.have.callCount(i + 1); }); }); it('does not cycle the SourceBuffer operation queue on error', function () { const onError = sandbox.spy(); const operation: BufferOperation = { execute: () => {}, onStart: () => {}, onComplete: () => {}, onError, }; queueNames.forEach((name, i) => { const currentQueue = operationQueue.queues[name]; currentQueue.push(operation); const errorEvent = new Event('error'); bufferController.sourceBuffer[name].dispatchEvent(errorEvent); expect( onError, 'onError should have been called on the current operation' ).to.have.callCount(i + 1); expect( onError, 'onError should be called with the error event' ).to.have.been.calledWith(errorEvent); expect( triggerSpy, 'ERROR should have been triggered in response to the SourceBuffer error' ).to.have.been.calledWith(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false, }); expect(shiftAndExecuteNextSpy, 'The queue should not have been cycled').to .have.not.been.called; }); }); describe('onBufferAppending', function () { it('should enqueue and execute an append operation', function () { const queueAppendSpy = sandbox.spy(operationQueue, 'append'); const buffers = bufferController.sourceBuffer; queueNames.forEach((name, i) => { const buffer = buffers[name]; const segmentData = new Uint8Array(); const frag = new Fragment(PlaylistLevelType.MAIN, ''); const chunkMeta = new ChunkMetadata(0, 0, 0, 0); const data: BufferAppendingData = { parent: PlaylistLevelType.MAIN, type: name, data: segmentData, frag, part: null, chunkMeta, }; bufferController.onBufferAppending(Events.BUFFER_APPENDING, data); expect( queueAppendSpy, 'The append operation should have been enqueued' ).to.have.callCount(i + 1); buffer.dispatchEvent(new Event('updateend')); expect( buffer.ended, `The ${name} buffer should not be marked as true if an append occurred` ).to.be.false; expect( buffer.appendBuffer, 'appendBuffer should have been called with the remuxed data' ).to.have.been.calledWith(segmentData); expect( triggerSpy, 'BUFFER_APPENDED should be triggered upon completion of the operation' ).to.have.been.calledWith(Events.BUFFER_APPENDED, { parent: 'main', type: name, timeRanges: { audio: buffers.audio.buffered, video: buffers.video.buffered, }, frag, part: null, chunkMeta, }); expect( shiftAndExecuteNextSpy, 'The queue should have been cycled' ).to.have.callCount(i + 1); }); }); it('should cycle the SourceBuffer operation queue if the sourceBuffer does not exist while appending', function () { const queueAppendSpy = sandbox.spy(operationQueue, 'append'); queueNames.forEach((name, i) => { bufferController.sourceBuffer = {}; bufferController.onBufferAppending(Events.BUFFER_APPENDING, { type: name, data: new Uint8Array(), frag: new Fragment(PlaylistLevelType.MAIN, ''), chunkMeta: new ChunkMetadata(0, 0, 0, 0), }); expect( queueAppendSpy, 'The append operation should have been enqueued' ).to.have.callCount(i + 1); expect( shiftAndExecuteNextSpy, 'The queue should have been cycled' ).to.have.callCount(i + 1); }); expect(triggerSpy, 'No event should have been triggered').to.have.not.been .called; }); }); describe('onFragParsed', function () { it('should trigger FRAG_BUFFERED when all audio/video data has been buffered', function () { const frag = new Fragment(PlaylistLevelType.MAIN, ''); frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, 0, 0, 0, 0); frag.setElementaryStreamInfo(ElementaryStreamTypes.VIDEO, 0, 0, 0, 0); bufferController.onFragParsed(Events.FRAG_PARSED, { frag }); expect(queueAppendBlockerSpy).to.have.been.calledTwice; return new Promise<void>((resolve, reject) => { hls.on(Events.FRAG_BUFFERED, (event, data) => { try { expect( data.frag, 'The frag emitted in FRAG_BUFFERED should be the frag passed in onFragParsed' ).to.equal(frag); expect( data.id, 'The id of the event should be equal to the frag type' ).to.equal(frag.type); // TODO: remove stats from event & place onto frag // expect(data.stats).to.equal({}); } catch (e) { reject(e); } resolve(); }); }).then(() => { expect(shiftAndExecuteNextSpy, 'The queues should have been cycled').to .have.been.calledTwice; }); }); }); describe('onBufferFlushing', function () { let queueAppendSpy; beforeEach(function () { queueAppendSpy = sandbox.spy(operationQueue, 'append'); queueNames.forEach((name) => { const sb = bufferController.sourceBuffer[name]; sb.setBuffered(0, 10); }); }); it('flushes audio and video buffers if no type arg is specified', function () { bufferController.onBufferFlushing(Events.BUFFER_FLUSHING, { startOffset: 0, endOffset: 10, }); expect( queueAppendSpy, 'A remove operation should have been appended to each queue' ).to.have.been.calledTwice; queueNames.forEach((name, i) => { const buffer = bufferController.sourceBuffer[name]; expect( buffer.remove, `Remove should have been called once on the ${name} SourceBuffer` ).to.have.been.calledOnce; expect( buffer.remove, 'Remove should have been called with the expected range' ).to.have.been.calledWith(0, 10); buffer.dispatchEvent(new Event('updateend')); expect( triggerSpy, 'The BUFFER_FLUSHED event should be called once per buffer' ).to.have.callCount(i + 1); expect( triggerSpy, 'BUFFER_FLUSHED should be the only event fired' ).to.have.been.calledWith(Events.BUFFER_FLUSHED); expect( shiftAndExecuteNextSpy, 'The queue should have been cycled' ).to.have.callCount(i + 1); }); }); it('Does not queue remove operations when there are no SourceBuffers', function () { bufferController.sourceBuffer = {}; bufferController.onBufferFlushing(Events.BUFFER_FLUSHING, { startOffset: 0, endOffset: Infinity, }); expect( queueAppendSpy, 'No remove operations should have been appended' ).to.have.callCount(0); }); it('Only queues remove operations for existing SourceBuffers', function () { bufferController.sourceBuffer = { audiovideo: {}, }; bufferController.onBufferFlushing(Events.BUFFER_FLUSHING, { startOffset: 0, endOffset: Infinity, }); expect( queueAppendSpy, 'Queue one remove for muxed "audiovideo" SourceBuffer' ).to.have.been.calledOnce; }); it('dequeues the remove operation if the requested remove range is not valid', function () { // Does not flush if start greater than end bufferController.onBufferFlushing(Events.BUFFER_FLUSHING, { startOffset: 9001, endOffset: 9000, }); expect( queueAppendSpy, 'Two remove operations should have been appended' ).to.have.callCount(2); expect( shiftAndExecuteNextSpy, 'The queues should have been cycled' ).to.have.callCount(2); queueNames.forEach((name) => { const buffer = bufferController.sourceBuffer[name]; expect( buffer.remove, `Remove should not have been called on the ${name} buffer` ).to.have.not.been.called; }); expect(triggerSpy, 'No event should have been triggered').to.have.not.been .called; }); }); describe('flushBackBuffer', function () { beforeEach(function () { bufferController.details = { levelTargetDuration: 10, }; hls.config.backBufferLength = 10; queueNames.forEach((name) => { const sb = bufferController.sourceBuffer[name]; sb.setBuffered(0, 30); }); mockMedia.currentTime = 30; }); it('exits early if no media is defined', function () { delete bufferController.media; bufferController.flushBackBuffer(); expect(triggerSpy, 'BUFFER_FLUSHING should not have been triggered').to .have.not.been.called; }); it('exits early if the backBufferLength config is not a finite number, or less than 0', function () { hls.config.backBufferLength = null; bufferController.flushBackBuffer(); hls.config.backBufferLength = -1; bufferController.flushBackBuffer(); hls.config.backBufferLength = Infinity; bufferController.flushBackBuffer(); expect(triggerSpy, 'BUFFER_FLUSHING should not have been triggered').to .have.not.been.called; }); it('should execute a remove operation if flushing a valid backBuffer range', function () { bufferController.flushBackBuffer(); expect(triggerSpy.withArgs(Events.BUFFER_FLUSHING)).to.have.callCount(2); queueNames.forEach((name) => { expect( triggerSpy, `BUFFER_FLUSHING should have been triggered for the ${name} SourceBuffer` ).to.have.been.calledWith(Events.BUFFER_FLUSHING, { startOffset: 0, endOffset: 20, type: name, }); }); }); it('should support the deprecated liveBackBufferLength for live content', function () { bufferController.details.live = true; hls.config.backBufferLength = Infinity; hls.config.liveBackBufferLength = 10; bufferController.flushBackBuffer(); expect( triggerSpy.withArgs(Events.LIVE_BACK_BUFFER_REACHED) ).to.have.callCount(2); }); it('removes a maximum of one targetDuration from currentTime at intervals of targetDuration', function () { mockMedia.currentTime = 25; hls.config.backBufferLength = 5; bufferController.flushBackBuffer(); queueNames.forEach((name) => { expect( triggerSpy, `BUFFER_FLUSHING should have been triggered for the ${name} SourceBuffer` ).to.have.been.calledWith(Events.BUFFER_FLUSHING, { startOffset: 0, endOffset: 10, type: name, }); }); }); it('removes nothing if no buffered range intersects with back buffer limit', function () { mockMedia.currentTime = 15; queueNames.forEach((name) => { const buffer = bufferController.sourceBuffer[name]; buffer.setBuffered(10, 30); }); bufferController.flushBackBuffer(); expect(triggerSpy, 'BUFFER_FLUSHING should not have been triggered').to .have.not.been.called; }); it('does not remove if the buffer does not exist', function () { queueNames.forEach((name) => { const buffer = bufferController.sourceBuffer[name]; buffer.setBuffered(0, 0); }); bufferController.flushBackBuffer(); bufferController.sourceBuffer = {}; bufferController.flushBackBuffer(); expect(triggerSpy, 'BUFFER_FLUSHING should not have been triggered').to .have.not.been.called; }); }); describe('onLevelUpdated', function () { let data; beforeEach(function () { const details = Object.assign(new LevelDetails(''), { averagetargetduration: 6, totalduration: 5, fragments: [{ start: 5 }], }); mockMediaSource.duration = Infinity; data = { details }; }); it('exits early if the fragments array is empty', function () { data.details.fragments = []; bufferController.onLevelUpdated(Events.LEVEL_UPDATED, data); expect(bufferController.details, 'details').to.be.null; }); it('updates class properties based on level data', function () { bufferController.onLevelUpdated(Events.LEVEL_UPDATED, data); expect(bufferController.details).to.equal(data.details); }); it('enqueues a blocking operation which updates the MediaSource duration', function () { bufferController.onLevelUpdated(Events.LEVEL_UPDATED, data); expect(queueAppendBlockerSpy).to.have.been.calledTwice; // Updating the duration is aync and has no event to signal completion, so we are unable to test for it directly }); it('synchronously sets media duration if no SourceBuffers exist', function () { bufferController.sourceBuffer = {}; bufferController.onLevelUpdated(Events.LEVEL_UPDATED, data); expect(queueAppendBlockerSpy).to.have.not.been.called; expect(mockMediaSource.duration, 'mediaSource.duration').to.equal(10); }); it('sets media duration when attaching after level update', function () { bufferController.sourceBuffer = {}; const media = bufferController.media; // media is null prior to attaching bufferController.media = null; expect(mockMediaSource.duration, 'mediaSource.duration').to.equal( Infinity ); bufferController.onLevelUpdated(Events.LEVEL_UPDATED, data); expect(mockMediaSource.duration, 'mediaSource.duration').to.equal( Infinity ); // simulate attach and open source buffers bufferController.media = media; bufferController._onMediaSourceOpen(); expect(mockMediaSource.duration, 'mediaSource.duration').to.equal(10); }); }); describe('onBufferEos', function () { it('marks the ExtendedSourceBuffer as ended', function () { // No type arg ends both SourceBuffers bufferController.onBufferEos(Events.BUFFER_EOS, {}); expect(queueAppendBlockerSpy).to.have.been.calledTwice; queueNames.forEach((type) => { const buffer = bufferController.sourceBuffer[type]; expect(buffer.ended, 'ExtendedSourceBuffer.ended').to.be.true; }); }); }); });
the_stack
import '../../../test/common-test-setup-karma'; import './gr-textarea'; import {GrTextarea} from './gr-textarea'; import {html} from '@polymer/polymer/lib/utils/html-tag'; import * as MockInteractions from '@polymer/iron-test-helpers/mock-interactions'; import {ItemSelectedEvent} from '../gr-autocomplete-dropdown/gr-autocomplete-dropdown'; const basicFixture = fixtureFromElement('gr-textarea'); const monospaceFixture = fixtureFromTemplate(html` <gr-textarea monospace="true"></gr-textarea> `); const hideBorderFixture = fixtureFromTemplate(html` <gr-textarea hide-border="true"></gr-textarea> `); suite('gr-textarea tests', () => { let element: GrTextarea; setup(() => { element = basicFixture.instantiate(); sinon.stub(element.reporting, 'reportInteraction'); }); test('monospace is set properly', () => { assert.isFalse(element.classList.contains('monospace')); }); test('hideBorder is set properly', () => { assert.isFalse(element.$.textarea.classList.contains('noBorder')); }); test('emoji selector is not open with the textarea lacks focus', () => { element.$.textarea.selectionStart = 1; element.$.textarea.selectionEnd = 1; element.text = ':'; assert.isFalse(!element.$.emojiSuggestions.isHidden); }); test('emoji selector is not open when a general text is entered', () => { MockInteractions.focus(element.$.textarea); element.$.textarea.selectionStart = 9; element.$.textarea.selectionEnd = 9; element.text = 'some text'; assert.isFalse(!element.$.emojiSuggestions.isHidden); }); test('emoji selector opens when a colon is typed & the textarea has focus', () => { MockInteractions.focus(element.$.textarea); // Needed for Safari tests. selectionStart is not updated when text is // updated. element.$.textarea.selectionStart = 1; element.$.textarea.selectionEnd = 1; element.text = ':'; flush(); assert.isFalse(element.$.emojiSuggestions.isHidden); assert.equal(element._colonIndex, 0); assert.isFalse(element._hideEmojiAutocomplete); assert.equal(element._currentSearchString, ''); }); test('emoji selector opens when a colon is typed after space', () => { MockInteractions.focus(element.$.textarea); // Needed for Safari tests. selectionStart is not updated when text is // updated. element.$.textarea.selectionStart = 2; element.$.textarea.selectionEnd = 2; element.text = ' :'; flush(); assert.isFalse(element.$.emojiSuggestions.isHidden); assert.equal(element._colonIndex, 1); assert.isFalse(element._hideEmojiAutocomplete); assert.equal(element._currentSearchString, ''); }); test('emoji selector doesn`t open when a colon is typed after character', () => { MockInteractions.focus(element.$.textarea); // Needed for Safari tests. selectionStart is not updated when text is // updated. element.$.textarea.selectionStart = 5; element.$.textarea.selectionEnd = 5; element.text = 'test:'; flush(); assert.isTrue(element.$.emojiSuggestions.isHidden); assert.isTrue(element._hideEmojiAutocomplete); }); test('emoji selector opens when a colon is typed and some substring', () => { MockInteractions.focus(element.$.textarea); // Needed for Safari tests. selectionStart is not updated when text is // updated. element.$.textarea.selectionStart = 1; element.$.textarea.selectionEnd = 1; element.text = ':'; element.$.textarea.selectionStart = 2; element.$.textarea.selectionEnd = 2; element.text = ':t'; flush(); assert.isFalse(element.$.emojiSuggestions.isHidden); assert.equal(element._colonIndex, 0); assert.isFalse(element._hideEmojiAutocomplete); assert.equal(element._currentSearchString, 't'); }); test('emoji selector opens when a colon is typed in middle of text', () => { MockInteractions.focus(element.$.textarea); // Needed for Safari tests. selectionStart is not updated when text is // updated. element.$.textarea.selectionStart = 1; element.$.textarea.selectionEnd = 1; // Since selectionStart is on Chrome set always on end of text, we // stub it to 1 const text = ': hello'; sinon.stub(element.$, 'textarea').value({ selectionStart: 1, value: text, textarea: { focus: () => {}, }, }); element.text = text; flush(); assert.isFalse(element.$.emojiSuggestions.isHidden); assert.equal(element._colonIndex, 0); assert.isFalse(element._hideEmojiAutocomplete); assert.equal(element._currentSearchString, ''); }); test('emoji selector closes when text changes before the colon', () => { const resetStub = sinon.stub(element, '_resetEmojiDropdown'); MockInteractions.focus(element.$.textarea); flush(); element.$.textarea.selectionStart = 10; element.$.textarea.selectionEnd = 10; element.text = 'test test '; element.$.textarea.selectionStart = 12; element.$.textarea.selectionEnd = 12; element.text = 'test test :'; element.$.textarea.selectionStart = 15; element.$.textarea.selectionEnd = 15; element.text = 'test test :smi'; assert.equal(element._currentSearchString, 'smi'); assert.isFalse(resetStub.called); element.text = 'test test test :smi'; assert.isTrue(resetStub.called); }); test('_resetEmojiDropdown', () => { const closeSpy = sinon.spy(element, 'closeDropdown'); element._resetEmojiDropdown(); assert.equal(element._currentSearchString, ''); assert.isTrue(element._hideEmojiAutocomplete); assert.equal(element._colonIndex, null); element.$.emojiSuggestions.open(); flush(); element._resetEmojiDropdown(); assert.isTrue(closeSpy.called); }); test('_determineSuggestions', () => { const emojiText = 'tear'; const formatSpy = sinon.spy(element, '_formatSuggestions'); element._determineSuggestions(emojiText); assert.isTrue(formatSpy.called); assert.isTrue( formatSpy.lastCall.calledWithExactly([ { dataValue: '😂', value: '😂', match: "tears :')", text: "😂 tears :')", }, {dataValue: '😢', value: '😢', match: 'tear', text: '😢 tear'}, ]) ); }); test('_formatSuggestions', () => { const matchedSuggestions = [ {value: '😢', match: 'tear'}, {value: '😂', match: 'tears'}, ]; element._formatSuggestions(matchedSuggestions); assert.deepEqual( [ {value: '😢', dataValue: '😢', match: 'tear', text: '😢 tear'}, {value: '😂', dataValue: '😂', match: 'tears', text: '😂 tears'}, ], element._suggestions ); }); test('_handleEmojiSelect', () => { element.$.textarea.selectionStart = 16; element.$.textarea.selectionEnd = 16; element.text = 'test test :tears'; element._colonIndex = 10; const selectedItem = {dataset: {value: '😂'}} as unknown as HTMLElement; const event = new CustomEvent<ItemSelectedEvent>('item-selected', { detail: {trigger: 'click', selected: selectedItem}, }); element._handleEmojiSelect(event); assert.equal(element.text, 'test test 😂'); }); test('_updateCaratPosition', () => { element.$.textarea.selectionStart = 4; element.$.textarea.selectionEnd = 4; element.text = 'test'; element._updateCaratPosition(); assert.deepEqual( element.$.hiddenText.innerHTML, element.text + element.$.caratSpan.outerHTML ); }); test('newline receives matching indentation', async () => { const indentCommand = sinon.stub(document, 'execCommand'); element.$.textarea.value = ' a'; element._handleEnterByKey( new KeyboardEvent('keydown', {key: 'Enter', keyCode: 13}) ); await flush(); assert.deepEqual(indentCommand.args[0], ['insertText', false, '\n ']); }); test('emoji dropdown is closed when iron-overlay-closed is fired', () => { const resetSpy = sinon.spy(element, '_resetEmojiDropdown'); element.$.emojiSuggestions.dispatchEvent( new CustomEvent('dropdown-closed', { composed: true, bubbles: true, }) ); assert.isTrue(resetSpy.called); }); test('_onValueChanged fires bind-value-changed', () => { const listenerStub = sinon.stub(); const eventObject = new CustomEvent('bind-value-changed', { detail: {currentTarget: {focused: false}, value: ''}, }); element.addEventListener('bind-value-changed', listenerStub); element._onValueChanged(eventObject); assert.isTrue(listenerStub.called); }); suite('keyboard shortcuts', () => { function setupDropdown() { MockInteractions.focus(element.$.textarea); element.$.textarea.selectionStart = 1; element.$.textarea.selectionEnd = 1; element.text = ':'; element.$.textarea.selectionStart = 1; element.$.textarea.selectionEnd = 2; element.text = ':1'; flush(); } test('escape key', () => { const resetSpy = sinon.spy(element, '_resetEmojiDropdown'); MockInteractions.pressAndReleaseKeyOn( element.$.textarea, 27, null, 'Escape' ); assert.isFalse(resetSpy.called); setupDropdown(); MockInteractions.pressAndReleaseKeyOn( element.$.textarea, 27, null, 'Escape' ); assert.isTrue(resetSpy.called); assert.isFalse(!element.$.emojiSuggestions.isHidden); }); test('up key', () => { const upSpy = sinon.spy(element.$.emojiSuggestions, 'cursorUp'); MockInteractions.pressAndReleaseKeyOn( element.$.textarea, 38, null, 'ArrowUp' ); assert.isFalse(upSpy.called); setupDropdown(); MockInteractions.pressAndReleaseKeyOn( element.$.textarea, 38, null, 'ArrowUp' ); assert.isTrue(upSpy.called); }); test('down key', () => { const downSpy = sinon.spy(element.$.emojiSuggestions, 'cursorDown'); MockInteractions.pressAndReleaseKeyOn( element.$.textarea, 40, null, 'ArrowDown' ); assert.isFalse(downSpy.called); setupDropdown(); MockInteractions.pressAndReleaseKeyOn( element.$.textarea, 40, null, 'ArrowDown' ); assert.isTrue(downSpy.called); }); test('enter key', () => { const enterSpy = sinon.spy(element.$.emojiSuggestions, 'getCursorTarget'); MockInteractions.pressAndReleaseKeyOn( element.$.textarea, 13, null, 'Enter' ); assert.isFalse(enterSpy.called); setupDropdown(); MockInteractions.pressAndReleaseKeyOn( element.$.textarea, 13, null, 'Enter' ); assert.isTrue(enterSpy.called); flush(); assert.equal(element.text, '💯'); }); test('enter key - ignored on just colon without more information', () => { const enterSpy = sinon.spy(element.$.emojiSuggestions, 'getCursorTarget'); MockInteractions.pressAndReleaseKeyOn(element.$.textarea, 13); assert.isFalse(enterSpy.called); MockInteractions.focus(element.$.textarea); element.$.textarea.selectionStart = 1; element.$.textarea.selectionEnd = 1; element.text = ':'; flush(); MockInteractions.pressAndReleaseKeyOn(element.$.textarea, 13); assert.isFalse(enterSpy.called); }); }); suite('gr-textarea monospace', () => { // gr-textarea set monospace class in the ready() method. // In Polymer2, ready() is called from the fixture(...) method, // If ready() is called again later, some nested elements doesn't // handle it correctly. A separate test-fixture is used to set // properties before ready() is called. let element: GrTextarea; setup(() => { element = monospaceFixture.instantiate() as GrTextarea; }); test('monospace is set properly', () => { assert.isTrue(element.classList.contains('monospace')); }); }); suite('gr-textarea hideBorder', () => { // gr-textarea set noBorder class in the ready() method. // In Polymer2, ready() is called from the fixture(...) method, // If ready() is called again later, some nested elements doesn't // handle it correctly. A separate test-fixture is used to set // properties before ready() is called. let element: GrTextarea; setup(() => { element = hideBorderFixture.instantiate() as GrTextarea; }); test('hideBorder is set properly', () => { assert.isTrue(element.$.textarea.classList.contains('noBorder')); }); }); });
the_stack
import { Builder } from '../../api/clients/IOClients/apps/Builder' import { ChangeSizeLimitError, ChangeToSend, ProjectSizeLimitError, ProjectUploader, } from '../../api/modules/apps/ProjectUploader' import { checkBuilderHubMessage, showBuilderHubMessage, continueAfterReactTermsAndConditions, validateAppAction, } from '../../api/modules/utils' import { createFlowIssueError } from '../../api/error/utils' import { concat, intersection, isEmpty, map, pipe, prop } from 'ramda' import { createInterface } from 'readline' import { createPathToFileObject } from '../../api/files/ProjectFilesManager' import { default as setup } from '../setup' import { fixPinnedDependencies, PinnedDeps } from '../../api/pinnedDependencies' import { formatNano, runYarnIfPathExists } from '../utils' import { ManifestEditor } from '../../api/manifest' import { getAppRoot } from '../../api/manifest/ManifestUtil' import { getIgnoredPaths, listLocalFiles } from '../../api/modules/apps/file' import { join, resolve as resolvePath, sep } from 'path' import { listenBuild } from '../../api/modules/build' import { randomBytes } from 'crypto' import { readFileSync } from 'fs' import { SessionManager } from '../../api/session/SessionManager' import { YarnFilesManager } from '../../api/files/YarnFilesManager' import authLogin, { LoginOptions } from '../auth/login' import chalk from 'chalk' import chokidar from 'chokidar' import debounce from 'debounce' import log from '../../api/logger' import moment from 'moment' import retry from 'async-retry' import startDebuggerTunnel from './debugger' import workspaceUse from '../../api/modules/workspace/use' import { BatchStream } from '../../api/typings/types' import { Messages } from '../../lib/constants/Messages' import { NewStickyHostError } from '../../api/error/errors' let nodeNotifier if (process.platform !== 'win32') { // eslint-disable-next-line @typescript-eslint/no-require-imports nodeNotifier = require('node-notifier') } interface LinkOptions { account?: string workspace?: string unsafe?: boolean clean?: boolean setup?: boolean noWatch?: boolean } const DELETE_SIGN = chalk.red('D') const UPDATE_SIGN = chalk.blue('U') const INITIAL_LINK_CODE = 'initial_link_required' const stabilityThreshold = process.platform === 'darwin' ? 100 : 200 const linkID = randomBytes(8).toString('hex') const buildersToStartDebugger = ['node'] const buildersToRunLocalYarn = ['react', 'node'] const RETRY_OPTS_INITIAL_LINK = { retries: 2, minTimeout: 1000, factor: 2, } const RETRY_OPTS_DEBUGGER = { retries: 2, minTimeout: 1000, factor: 2, } const shouldStartDebugger = (manifest: ManifestEditor) => { const buildersThatWillUseDebugger = intersection(manifest.builderNames, buildersToStartDebugger) return buildersThatWillUseDebugger.length > 0 } const performInitialLink = async ( root: string, projectUploader: ProjectUploader, extraData: { yarnFilesManager: YarnFilesManager }, unsafe: boolean ): Promise<void> => { const yarnFilesManager = await YarnFilesManager.createFilesManager(root) extraData.yarnFilesManager = yarnFilesManager yarnFilesManager.logSymlinkedDependencies() const linkApp = async (bail: any, tryCount: number) => { // wrapper for builder.linkApp to be used with the retry function below. const [localFiles, linkedFiles] = await Promise.all([ listLocalFiles(root).then(paths => map(createPathToFileObject(root), paths)), yarnFilesManager.getYarnLinkedFiles(), ]) const filesWithContent = concat(localFiles, linkedFiles) as BatchStream[] if (tryCount === 1) { const linkedFilesInfo = linkedFiles.length ? `(${linkedFiles.length} from linked node modules)` : '' log.info(`Sending ${filesWithContent.length} file${filesWithContent.length > 1 ? 's' : ''} ${linkedFilesInfo}`) log.debug('Sending files') filesWithContent.forEach(p => log.debug(p.path)) } if (tryCount > 1) { log.info(`Retrying...${tryCount - 1}`) } try { log.info(`Link ID: ${linkID}`) const { code } = await projectUploader.sendToLink(filesWithContent, linkID, { tsErrorsAsWarnings: unsafe }) if (code !== 'build.accepted') { bail(new Error('Please, update your builder-hub to the latest version!')) } } catch (err) { if (err instanceof ProjectSizeLimitError) { log.error(err.message) process.exit(1) } const data = err?.response?.data if (data?.code === 'bad_toolbelt_version') { const errMsg = `${data.message}\n${Messages.UPDATE_TOOLBELT()}` log.error(errMsg) process.exit(1) } if (err.status) { const { response } = err const { status } = response const { message } = data const statusMessage = status ? `: Status ${status}` : '' log.error(`Error linking app${statusMessage} (try: ${tryCount})`) if (message) { log.error(`Message: ${message}`) } if (status && status < 500) { return } } throw err } } await retry(linkApp, RETRY_OPTS_INITIAL_LINK) } const warnAndLinkFromStart = ( root: string, projectUploader: ProjectUploader, unsafe: boolean, extraData: { yarnFilesManager: YarnFilesManager } = { yarnFilesManager: null } ) => { log.warn('Initial link requested by builder') performInitialLink(root, projectUploader, extraData, unsafe) return null } const watchAndSendChanges = async ( root: string, appId: string, projectUploader: ProjectUploader, { yarnFilesManager }: { yarnFilesManager: YarnFilesManager }, unsafe: boolean ): Promise<any> => { const changeQueue: ChangeToSend[] = [] const onInitialLinkRequired = err => { const data = err.response && err.response.data if (data?.code === INITIAL_LINK_CODE || err?.code === INITIAL_LINK_CODE) { return warnAndLinkFromStart(root, projectUploader, unsafe, { yarnFilesManager }) } throw err } const defaultPatterns = ['*/**', 'manifest.json', 'policies.json', 'cypress.json'] const linkedDepsPatterns = map(path => join(path, '**'), yarnFilesManager.symlinkedDepsDirs) const pathModifier = pipe( (path: string) => yarnFilesManager.maybeMapLocalYarnLinkedPathToProjectPath(path, root), path => path.split(sep).join('/') ) const pathToChange = (path: string, remove?: boolean): ChangeToSend => { const content = remove ? null : readFileSync(resolvePath(root, path)).toString('base64') const byteSize = remove ? 0 : Buffer.byteLength(content) return { content, byteSize, path: pathModifier(path), } } const sendChanges = debounce(async () => { try { log.info(`Link ID: ${linkID}`) return await projectUploader.sendToRelink(changeQueue.splice(0, changeQueue.length), linkID, { tsErrorsAsWarnings: unsafe, }) } catch (err) { const commandType = err instanceof NewStickyHostError ? err.command : 'link' nodeNotifier?.notify({ title: appId, message: `${commandType} died`, }) if (err instanceof ChangeSizeLimitError) { log.error(err.message) process.exit(1) } onInitialLinkRequired(err) } }, 1000) const queueChange = (path: string, remove?: boolean) => { console.log(`${chalk.gray(moment().format('HH:mm:ss:SSS'))} - ${remove ? DELETE_SIGN : UPDATE_SIGN} ${path}`) changeQueue.push(pathToChange(path, remove)) sendChanges() } const addIgnoreNodeModulesRule = (paths: Array<string | ((path: string) => boolean)>) => paths.concat((path: string) => path.includes('node_modules')) const watcher = chokidar.watch([...defaultPatterns, ...linkedDepsPatterns], { atomic: stabilityThreshold, awaitWriteFinish: { stabilityThreshold, }, cwd: root, ignoreInitial: true, ignored: addIgnoreNodeModulesRule(getIgnoredPaths(root)), persistent: true, usePolling: process.platform === 'win32', }) return new Promise((resolve, reject) => { watcher .on('add', file => queueChange(file)) .on('change', file => queueChange(file)) .on('unlink', file => queueChange(file, true)) .on('error', reject) .on('ready', resolve) }) } async function handlePreLinkLogin({ account, workspace }: { account?: string; workspace?: string }) { const postLoginOps: LoginOptions['postLoginOps'] = ['releaseNotify'] if (!SessionManager.getSingleton().checkValidCredentials()) { return authLogin({ account, workspace, allowUseCachedToken: true, postLoginOps }) } if (account && workspace) { return authLogin({ account, workspace, allowUseCachedToken: true, postLoginOps }) } if (workspace) { return workspaceUse(workspace) } } export async function appLink(options: LinkOptions) { await handlePreLinkLogin({ account: options.account, workspace: options.workspace }) await validateAppAction('link') const unsafe = !!options.unsafe const root = getAppRoot() const manifest = await ManifestEditor.getManifestEditor() await manifest.writeSchema() const mustContinue = await continueAfterReactTermsAndConditions(manifest) if (!mustContinue) { return } const builderHubMessage = await checkBuilderHubMessage('link') if (!isEmpty(builderHubMessage)) { await showBuilderHubMessage(builderHubMessage.message, builderHubMessage.prompt, manifest) } const appId = manifest.appLocator const builder = Builder.createClient({}, { timeout: 60000, retries: 3 }) const projectUploader = ProjectUploader.getProjectUploader(appId, builder) if (options.setup) { await setup({ 'ignore-linked': false }) } try { const pinnedDeps: PinnedDeps = await builder.getPinnedDependencies() await fixPinnedDependencies(pinnedDeps, buildersToRunLocalYarn, manifest.builders) } catch (e) { log.info('Failed to check for pinned dependencies') log.debug(e) } // Always run yarn locally for some builders map(runYarnIfPathExists, buildersToRunLocalYarn) if (options.clean) { log.info('Requesting to clean cache in builder.') const { timeNano } = await builder.clean(appId) log.info(`Cache cleaned successfully in ${formatNano(timeNano)}`) } const onError = { // eslint-disable-next-line @typescript-eslint/camelcase build_failed: () => { log.error(`App build failed. Waiting for changes...`) }, // eslint-disable-next-line @typescript-eslint/camelcase initial_link_required: () => warnAndLinkFromStart(root, projectUploader, unsafe), } let debuggerStarted = false const onBuild = async () => { if (debuggerStarted) { return } const startDebugger = async () => { const port = await startDebuggerTunnel(manifest) if (!port) { throw new Error('Failed to start debugger.') } return port } if (shouldStartDebugger(manifest)) { try { const debuggerPort = await retry(startDebugger, RETRY_OPTS_DEBUGGER) // eslint-disable-next-line require-atomic-updates debuggerStarted = true log.info( `Debugger tunnel listening on ${chalk.green(`:${debuggerPort}`)}. Go to ${chalk.blue( 'chrome://inspect' )} in Google Chrome to debug your running application.` ) } catch (e) { log.error(e.message) } } } log.info(`Linking app ${appId}`) let unlistenBuild const extraData = { yarnFilesManager: null } try { const buildTrigger = performInitialLink.bind(this, root, projectUploader, extraData, unsafe) const [subject] = appId.split('@') if (options.noWatch) { await listenBuild(subject, buildTrigger, { waitCompletion: true }) return } unlistenBuild = await listenBuild(subject, buildTrigger, { waitCompletion: false, onBuild, onError }).then( prop('unlisten') ) } catch (e) { if (e.response) { const { data } = e.response if (data.code === 'routing_error' && /app_not_found.*vtex\.builder-hub/.test(data.message)) { return log.error( 'Please install vtex.builder-hub in your account to enable app linking (vtex install vtex.builder-hub)' ) } if (data.code === 'link_on_production') { throw createFlowIssueError( `Please use a dev workspace to link apps. Create one with (${chalk.blue( 'vtex use <workspace> -rp' )}) to be able to link apps` ) } if (data.code === 'bad_toolbelt_version') { const errMsg = `${data.message}\n${Messages.UPDATE_TOOLBELT}` return log.error(errMsg) } } throw e } createInterface({ input: process.stdin, output: process.stdout }).on('SIGINT', () => { if (unlistenBuild) { unlistenBuild() } log.info('Your app is still in development mode.') log.info(`You can unlink it with: 'vtex unlink ${appId}'`) process.exit() }) await watchAndSendChanges(root, appId, projectUploader, extraData, unsafe) }
the_stack
import { Dimension, FontSize, Glue, MacroDictionary, Registers, RegisterValue, Style, } from '../public/core'; import { highlight } from './color'; import { FontMetrics, FONT_SCALE } from './font-metrics'; import { D, Dc, Mathstyle, MathstyleName, MATHSTYLES } from './mathstyle'; import { Box } from './box'; import { convertDimensionToEm } from './registers-utils'; import { PlaceholderAtom } from '../core-atoms/placeholder'; // Using boxes and glue in TeX and LaTeX: // https://www.math.utah.edu/~beebe/reports/2009/boxes.pdf export interface ContextInterface { macros?: MacroDictionary; registers: Registers; atomIdsSettings?: { overrideID?: string; groupNumbers: boolean; seed: string | number; }; smartFence?: boolean; isSelected?: boolean; renderPlaceholder?: (context: Context, placeholder: PlaceholderAtom) => Box; } export type PrivateStyle = Style & { verbatimColor?: string; verbatimBackgroundColor?: string; mathStyle?: MathstyleName; }; /** * This structure contains the rendering context of the current parse level. * * It keeps a reference to the parent context which is necessary to calculate * the proper scaling/fontsize since all sizes are specified in em and the * absolute value of an em depends of the fontsize of the parent context. * * When a new context is entered, a clone of the context is created with * `new()` so that any further changes remain local to the scope. * * When a context is exited, a 'wrapper' box is created to adjust the * fontsize on entry, and adjust the height/depth of the box to account for * the new fontsize (if applicable). * * The effective font size is determined by: * - the 'size' property, which represent a size set by a sizing command * (e.g. `\Huge`, `\tiny`, etc...) * - a size delta from the mathstyle (-1 for scriptstyle for example) * * * A context is defined for example by: * - an explicit group enclosed in braces `{...}` * - a semi-simple group enclosed in `\bgroup...\endgroup` * - the cells of a tabular environment * - the numerator or denominator of a fraction * - the root and radix of a fraction * */ export class Context implements ContextInterface { macros: MacroDictionary; // If not undefined, unique IDs should be generated for each box so they can // be mapped back to an atom. // The `seed` field should be a number to generate a specific range of // IDs or the string "random" to generate a random number. // Optionally, if a `groupNumbers` property is set to true, an additional // box will enclose strings of digits. This is used by read aloud to properly // pronounce (and highlight) numbers in expressions. atomIdsSettings?: { overrideID?: string; groupNumbers: boolean; seed: string | number; }; smartFence: boolean; renderPlaceholder?: (context: Context, placholder: PlaceholderAtom) => Box; isSelected: boolean; // Rendering to construct a phantom: don't bind the box. readonly isPhantom: boolean; // Inherithed from `Style`: size, letterShapeStyle, color and backgroundColor. // Size is the "base" font size (need to add mathstyle.sizeDelta to get effective size) readonly letterShapeStyle: 'tex' | 'french' | 'iso' | 'upright'; readonly color?: string; readonly backgroundColor?: string; readonly _size?: FontSize; private _mathstyle?: Mathstyle; registers: Registers; parent?: Context; constructor( parent: Context | ContextInterface, style?: Style & { isSelected?: boolean; isPhantom?: boolean; }, inMathstyle?: | 'cramp' | 'superscript' | 'subscript' | 'numerator' | 'denominator' | MathstyleName | '' | 'auto' ) { // If we don't have a parent context, we must provide an initial // mathstyle and fontsize console.assert(parent instanceof Context || style?.fontSize !== undefined); console.assert(parent instanceof Context || inMathstyle !== undefined); if (parent instanceof Context) this.parent = parent; if (!(parent instanceof Context)) this.registers = parent.registers ?? {}; this.isSelected = style?.isSelected ?? parent?.isSelected ?? false; this.isPhantom = style?.isPhantom ?? this.parent?.isPhantom ?? false; const from: { -readonly [key in keyof Context]?: Context[key] } = { ...parent, }; if (style) { let size: FontSize | undefined = undefined; if ( style.fontSize && style.fontSize !== 'auto' && style.fontSize !== this.parent?._size ) { size = style.fontSize; } if (style.letterShapeStyle && style.letterShapeStyle !== 'auto') { from.letterShapeStyle = style.letterShapeStyle; } if (style.color && style.color !== 'none') from.color = style.color; if (style.backgroundColor && style.backgroundColor !== 'none') { from.backgroundColor = this.isSelected ? highlight(style.backgroundColor) : style.backgroundColor; } this._size = size; } this.letterShapeStyle = from.letterShapeStyle ?? 'tex'; this.color = from.color; this.backgroundColor = from.backgroundColor; let mathstyle: Mathstyle | undefined; if (typeof inMathstyle === 'string') { if (parent instanceof Context) { switch (inMathstyle) { case 'cramp': mathstyle = parent.mathstyle.cramp; break; case 'superscript': mathstyle = parent.mathstyle.sup; break; case 'subscript': mathstyle = parent.mathstyle.sub; break; case 'numerator': mathstyle = parent.mathstyle.fracNum; break; case 'denominator': mathstyle = parent.mathstyle.fracDen; break; } } switch (inMathstyle) { case 'textstyle': mathstyle = MATHSTYLES.textstyle; break; case 'displaystyle': mathstyle = MATHSTYLES.displaystyle; break; case 'scriptstyle': mathstyle = MATHSTYLES.scriptstyle; break; case 'scriptscriptstyle': mathstyle = MATHSTYLES.scriptscriptstyle; break; case '': case 'auto': break; } } this._mathstyle = mathstyle; this.atomIdsSettings = parent.atomIdsSettings; this.macros = from.macros ?? {}; this.smartFence = from.smartFence ?? false; this.renderPlaceholder = from.renderPlaceholder; console.assert( !(parent instanceof Context) || this.atomIdsSettings === parent.atomIdsSettings ); } get mathstyle(): Mathstyle { let result = this._mathstyle; let parent = this.parent; while (!result) { result = parent!._mathstyle; parent = parent!.parent; } return result; } getRegister(name: string): undefined | RegisterValue { if (this.registers?.[name]) return this.registers[name]; if (this.parent) return this.parent.getRegister(name); return undefined; } getRegisterAsGlue(name: string): Glue | undefined { if (this.registers?.[name]) { const value = this.registers[name]; if (typeof value === 'object' && 'glue' in value) { return value; } else if (typeof value === 'object' && 'dimension' in value) { return { glue: { dimension: value.dimension } }; } else if (typeof value === 'number') { return { glue: { dimension: value } }; } return undefined; } if (this.parent) return this.parent.getRegisterAsGlue(name); return undefined; } getRegisterAsEm(name: string): number { return convertDimensionToEm(this.getRegisterAsDimension(name)); } getRegisterAsDimension(name: string): Dimension | undefined { if (this.registers?.[name]) { const value = this.registers[name]; if (typeof value === 'object' && 'glue' in value) { return value.glue; } else if (typeof value === 'object' && 'dimension' in value) { return value; } else if (typeof value === 'number') { return { dimension: value }; } return undefined; } if (this.parent) return this.parent.getRegisterAsDimension(name); return undefined; } setRegister(name: string, value: RegisterValue | undefined): void { if (value === undefined) { delete this.registers[name]; return; } this.registers[name] = value; } setGlobalRegister(name: string, value: RegisterValue): void { // eslint-disable-next-line @typescript-eslint/no-this-alias let root: Context = this; while (root.parent) { root.setRegister(name, undefined); root = root.parent; } root.setRegister(name, value); } get size(): FontSize { let result = this._size; let parent = this.parent; while (!result) { result = parent!._size; parent = parent!.parent; } return result; } makeID(): string | undefined { if (!this.atomIdsSettings) return undefined; if (typeof this.atomIdsSettings.seed !== 'number') { return ( Date.now().toString(36).slice(-2) + Math.floor(Math.random() * 0x186a0).toString(36) ); } const result = this.atomIdsSettings.overrideID ? this.atomIdsSettings.overrideID : this.atomIdsSettings.seed.toString(36); this.atomIdsSettings.seed += 1; return result; } // Scale a value, in em, to account for the fontsize and mathstyle // of this context scale(value: number): number { return value * this.effectiveFontSize; } get scalingFactor(): number { if (!this.parent) return 1.0; return this.effectiveFontSize / this.parent.effectiveFontSize; } get isDisplayStyle(): boolean { return this.mathstyle.id === D || this.mathstyle.id === Dc; } get isCramped(): boolean { return this.mathstyle.cramped; } get isTight(): boolean { return this.mathstyle.isTight; } // Return the font size, in em relative to the mathfield fontsize, // accounting both for the base font size and the mathstyle get effectiveFontSize(): number { return FONT_SCALE[ Math.max(1, this.size + this.mathstyle.sizeDelta) as FontSize ]; } get computedColor(): string { let result = this.color; let parent = this.parent; if (!result && parent) { result = parent.color; parent = parent.parent; } return result ?? ''; } get computedBackgroundColor(): string { let result = this.backgroundColor; let parent = this.parent; if (!result && parent) { result = parent.backgroundColor; parent = parent.parent; } return result ?? ''; } get metrics(): FontMetrics { return this.mathstyle.metrics; } }
the_stack
import { Loki } from "../../src/loki"; import { MemoryStorage } from "../../../memory-storage/src/memory_storage"; import { Collection } from "../../src/collection"; import { StorageAdapter } from "../../../common/types"; import { AvlTreeIndex } from "../../src/avl_index"; import { CreateJavascriptComparator } from "../../src/comparators"; interface AB { a: number; b: number; } interface Test { name: string; val: number; } interface User { name: string; owner?: string; maker?: string; } describe("testing unique index serialization", () => { let db: Loki; interface AUser { username: string; } let users: Collection<AUser>; beforeEach(() => { db = new Loki(); users = db.addCollection<AUser>("users"); users.insert([{ username: "joe" }, { username: "jack" }, { username: "john" }, { username: "jim" }]); users.ensureUniqueIndex("username"); }); it("should have a unique index", () => { const ser = db.serialize(), reloaded = new Loki(); reloaded.loadJSON(ser); const coll = reloaded.getCollection<AUser>("users"); expect(coll.count()).toEqual(4); expect(coll._constraints.unique["username"]).toBeDefined(); const joe = coll.by("username", "joe"); expect(joe).toBeDefined(); expect(joe.username).toEqual("joe"); expect(reloaded["_serializationMethod"]).toBe("normal"); expect(reloaded["_destructureDelimiter"]).toBe("$<\n"); }); }); describe("testing nested avl index serialization", () => { let db: Loki; interface AUser { user: { id: number; }; } interface Nested { "user.id": number; } let users: Collection<AUser, Nested>; beforeEach(() => { db = new Loki(); users = db.addCollection<AUser, Nested>("users", { nestedProperties: ["user.id"], rangedIndexes: { "user.id": { indexTypeName: "avl", comparatorName: "js" } } }); users.insert([ { user: { id: 1 } }, { user: { id: 2 } }, { user: { id: 3 } }, { user: { id: 4 } } ]); }); it("should have a ranged index", function () { /* const ser = db.serialize(); const reloaded = new Loki(); reloaded.loadJSON(ser); const coll = reloaded.getCollection<AUser, Nested>("users"); expect(coll.count()).toEqual(4); const joe = coll.findOne({ "user.id": 1 }); expect(joe).toBeDefined(); expect(joe.user.id).toEqual(1); */ expect(users.find().length).toEqual(4); }); }); describe("testing avl index serialization", function () { it("collection find ops on avl index work", (done) => { interface TestUserType { name: string; age: number; location: string; } const memAdapter = new MemoryStorage(); const db = new Loki("idxtest"); db.initializePersistence({ adapter: memAdapter }); const items = db.addCollection<TestUserType>("users", { rangedIndexes: { name: { indexTypeName: "avl", comparatorName: "js" } } }); items.insert([ { name: "patterson", age: 10, location: "a" }, { name: "gilbertson", age: 20, location: "b" }, { name: "smith", age: 30, location: "c" }, { name: "donaldson", age: 40, location: "d" }, { name: "harrison", age: 50, location: "e" }, { name: "thompson", age: 60, location: "f" }, { name: "albertson", age: 70, location: "g" }, { name: "fiset", age: 80, location: "h" } ]); db.saveDatabase().then(() => { // now deserialize via loadDatabase() and ensure index is functional const db2 = new Loki("idxtest"); db2.initializePersistence({ adapter: memAdapter }); db2.loadDatabase({}).then(() => { let items2 = db.getCollection<TestUserType>("users"); // $eq let results: TestUserType[] = items2.find({ name: "donaldson" }); expect(results.length).toEqual(1); expect(results[0].name).toEqual("donaldson"); expect(results[0].age).toEqual(40); expect(results[0].location).toEqual("d"); // $lt results = items2.find({ name: { $lt: "giraffe" } }); expect(results.length).toEqual(4); expect(results[0].name).toEqual("albertson"); expect(results[1].name).toEqual("donaldson"); expect(results[2].name).toEqual("fiset"); expect(results[3].name).toEqual("gilbertson"); // $lte results = items2.find({ name: { $lte: "fiset" } }); expect(results.length).toEqual(3); expect(results[0].name).toEqual("albertson"); expect(results[1].name).toEqual("donaldson"); expect(results[2].name).toEqual("fiset"); // $gt results = items2.find({ name: { $gt: "giraffe" } }); expect(results.length).toEqual(4); expect(results[0].name).toEqual("harrison"); expect(results[1].name).toEqual("patterson"); expect(results[2].name).toEqual("smith"); expect(results[3].name).toEqual("thompson"); // $gte results = items2.find({ name: { $gte: "patterson" } }); expect(results.length).toEqual(3); expect(results[0].name).toEqual("patterson"); expect(results[1].name).toEqual("smith"); expect(results[2].name).toEqual("thompson"); // $between results = items2.find({ name: { $between: ["faraday", "samuel"] } }); expect(results.length).toEqual(4); expect(results[0].name).toEqual("fiset"); expect(results[1].name).toEqual("gilbertson"); expect(results[2].name).toEqual("harrison"); expect(results[3].name).toEqual("patterson"); // make sure we are acutally using avl tree index expect(items2._rangedIndexes["name"].indexTypeName).toEqual("avl"); expect(items2._rangedIndexes["name"].comparatorName).toEqual("js"); expect(typeof items2._rangedIndexes["name"].index.rangeRequest).toEqual("function"); expect(items2._rangedIndexes["name"].index.constructor.name).toEqual("AvlTreeIndex"); done(); }); }); }); it("avl backup and restore work correctly", function () { let bst = new AvlTreeIndex("test", CreateJavascriptComparator()); bst.insert(1, "f"); bst.insert(2, "b"); bst.insert(3, "c"); bst.insert(4, "a"); bst.insert(5, "d"); let bkp = bst.backup(); // add another to original to ensure backup does not include it bst.insert(6, "g"); let bst2 = new AvlTreeIndex("test", CreateJavascriptComparator()); bst2.restore(JSON.parse(JSON.stringify(bkp))); let results = bst2.rangeRequest(); expect(results.length).toEqual(5); expect(results[0]).toEqual(4); expect(results[1]).toEqual(2); expect(results[2]).toEqual(3); expect(results[3]).toEqual(5); expect(results[4]).toEqual(1); }); }); describe("testing disable meta serialization", function () { it("should have meta disabled", function () { const db = new Loki(); db.addCollection<User>("users", { disableMeta: true }); const ser = db.serialize(); const reloaded = new Loki(); reloaded.loadJSON(ser); const coll = reloaded.getCollection("users"); expect(coll["_disableMeta"]).toEqual(true); }); }); describe("testing destructured serialization/deserialization", () => { it("verify default (D) destructuring works as expected", () => { const ddb = new Loki("test.db", { serializationMethod: "destructured" }); const coll = ddb.addCollection<Test>("testcoll"); coll.insert({ name: "test1", val: 100 }); coll.insert({ name: "test2", val: 101 }); coll.insert({ name: "test3", val: 102 }); const coll2 = ddb.addCollection<AB>("another"); coll2.insert({ a: 1, b: 2 }); const destructuredJson = ddb.serialize(); const cddb = new Loki("test.db", { serializationMethod: "destructured" }); cddb.loadJSON(destructuredJson); expect(cddb["_serializationMethod"]).toEqual("destructured"); expect(cddb["_collections"].length).toEqual(2); expect(cddb["_collections"][0].count()).toEqual(3); expect(cddb["_collections"][0]._data[0]["val"]).toEqual(ddb["_collections"][0]._data[0]["val"]); expect(cddb["_collections"][1].count()).toEqual(1); expect(cddb["_collections"][1]._data[0]["a"]).toEqual(ddb["_collections"][1]._data[0]["a"]); }); // Destructuring Formats : // D : one big Delimited string { partitioned: false, delimited : true } // DA : Delimited Array of strings [0] db [1] collection [n] collection { partitioned: true, delimited: true } // NDA : Non-Delimited Array : one iterable array with empty string collection partitions { partitioned: false, delimited: false } // NDAA : Non-Delimited Array with subArrays. db at [0] and collection subarrays at [n] { partitioned: true, delimited : false } it("verify custom destructuring works as expected", () => { const methods = ["D", "DA", "NDA", "NDAA"]; let idx, options, result; let cddb; const ddb = new Loki("test.db"); const coll = ddb.addCollection<Test>("testcoll"); coll.insert({ name: "test1", val: 100 }); coll.insert({ name: "test2", val: 101 }); coll.insert({ name: "test3", val: 102 }); const coll2 = ddb.addCollection<AB>("another"); coll2.insert({ a: 1, b: 2 }); for (idx = 0; idx < methods.length; idx++) { switch (methods[idx]) { case "D": options = { partitioned: false, delimited: true }; break; case "DA": options = { partitioned: true, delimited: true }; break; case "NDA": options = { partitioned: false, delimited: false }; break; case "NDAA": options = { partitioned: true, delimited: false }; break; default: options = {}; break; } // do custom destructuring result = ddb.serializeDestructured(options); // reinflate from custom destructuring cddb = new Loki("test.db"); const reinflatedDatabase = cddb.deserializeDestructured(result, options); cddb.loadJSONObject(reinflatedDatabase); // assert expectations on reinflated database expect(cddb["_collections"].length).toEqual(2); expect(cddb["_collections"][0]._data.length).toEqual(3); expect(cddb["_collections"][0]._data[0]["val"]).toEqual(ddb["_collections"][0]._data[0]["val"]); expect(cddb["_collections"][0]._data[0].$loki).toEqual(ddb["_collections"][0]._data[0].$loki); expect(cddb["_collections"][0]._data[2].$loki).toEqual(ddb["_collections"][0]._data[2].$loki); expect(cddb["_collections"][1].count()).toEqual(1); expect(cddb["_collections"][1]._data[0]["a"]).toEqual(ddb["_collections"][1]._data[0]["a"]); } }); it("verify individual partitioning works correctly", () => { let result; let cddb; const ddb = new Loki("test.db"); const coll = ddb.addCollection<Test>("testcoll"); coll.insert({ name: "test1", val: 100 }); coll.insert({ name: "test2", val: 101 }); coll.insert({ name: "test3", val: 102 }); const coll2 = ddb.addCollection<AB>("another"); coll2.insert({ a: 1, b: 2 }); // Verify db alone works correctly using NDAA format result = ddb.serializeDestructured({ partitioned: true, delimited: false, partition: -1 // indicates to get serialized db container only }); cddb = new Loki("test"); cddb.loadJSON(result); expect(cddb["_collections"].length).toEqual(2); expect(cddb["_collections"][0].count()).toEqual(0); expect(cddb["_collections"][1].count()).toEqual(0); expect(cddb["_collections"][0].name).toEqual(ddb["_collections"][0]["name"]); expect(cddb["_collections"][1].name).toEqual(ddb["_collections"][1]["name"]); // Verify collection alone works correctly using NDAA format result = ddb.serializeDestructured({ partitioned: true, delimited: false, partition: 0 // collection [0] only }); // we dont need to test all components of reassembling whole database // so we will just call helper function to deserialize just collection data let data = ddb.deserializeCollection<Test>(result, { partitioned: true, delimited: false }); expect(data.length).toEqual(ddb["_collections"][0].count()); expect(data[0]["val"]).toEqual(ddb["_collections"][0]._data[0]["val"]); expect(data[1]["val"]).toEqual(ddb["_collections"][0]._data[1]["val"]); expect(data[2]["val"]).toEqual(ddb["_collections"][0]._data[2]["val"]); expect(data[0].$loki).toEqual(ddb["_collections"][0]._data[0].$loki); expect(data[1].$loki).toEqual(ddb["_collections"][0]._data[1].$loki); expect(data[2].$loki).toEqual(ddb["_collections"][0]._data[2].$loki); // Verify collection alone works correctly using DA format (the other partitioned format) result = ddb.serializeDestructured({ partitioned: true, delimited: true, partition: 0 // collection [0] only }); // now reinflate from that interim DA format data = ddb.deserializeCollection<Test>(result, { partitioned: true, delimited: true }); expect(data.length).toEqual(ddb["_collections"][0].count()); expect(data[0]["val"]).toEqual(ddb["_collections"][0]._data[0]["val"]); expect(data[1]["val"]).toEqual(ddb["_collections"][0]._data[1]["val"]); expect(data[2]["val"]).toEqual(ddb["_collections"][0]._data[2]["val"]); expect(data[0].$loki).toEqual(ddb["_collections"][0]._data[0].$loki); expect(data[1].$loki).toEqual(ddb["_collections"][0]._data[1].$loki); expect(data[2].$loki).toEqual(ddb["_collections"][0]._data[2].$loki); }); }); describe("testing adapter functionality", () => { it("verify basic memory storage functionality works", (done) => { const memAdapter = new MemoryStorage(); const ddb = new Loki("test.db"); ddb.initializePersistence({ adapter: memAdapter }); const coll = ddb.addCollection<Test>("testcoll"); coll.insert({ name: "test1", val: 100 }); coll.insert({ name: "test2", val: 101 }); coll.insert({ name: "test3", val: 102 }); const coll2 = ddb.addCollection<AB>("another"); coll2.insert({ a: 1, b: 2 }); let dv = coll2.addDynamicView("test"); dv.applyFind({ "a": 1 }); dv.data(); const p1 = ddb.saveDatabase().then(() => { expect(memAdapter.hashStore.hasOwnProperty("test.db")).toEqual(true); expect(memAdapter.hashStore["test.db"].savecount).toEqual(1); }); const cdb = new Loki("test.db"); cdb.initializePersistence({ adapter: memAdapter }); const p2 = cdb.loadDatabase().then(() => { expect(cdb["_collections"].length).toEqual(2); expect(cdb.getCollection<Test>("testcoll").findOne({ name: "test2" })["val"]).toEqual(101); expect(cdb["_collections"][0].count()).toEqual(3); expect(cdb["_collections"][1].count()).toEqual(1); expect(cdb.getCollection<AB>("another").getDynamicView("test").data()).toEqual(coll2.find({ "a": 1 })); }); Promise.all([p1, p2]).then(done, done.fail); }); it("verify loki deleteDatabase works", (done) => { const memAdapter = new MemoryStorage(); const ddb = new Loki("test.db"); ddb.initializePersistence({ adapter: memAdapter }); const coll = ddb.addCollection<Test>("testcoll"); coll.insert({ name: "test1", val: 100 }); coll.insert({ name: "test2", val: 101 }); coll.insert({ name: "test3", val: 102 }); ddb.saveDatabase().then(() => { expect(memAdapter.hashStore.hasOwnProperty("test.db")).toEqual(true); expect(memAdapter.hashStore["test.db"].savecount).toEqual(1); return ddb.deleteDatabase(); }).then(() => { expect(memAdapter.hashStore.hasOwnProperty("test.db")).toEqual(false); }).then(done, done.fail); }); it("verify reference adapters get db reference which is copy and serializable-safe", (done) => { // Current loki functionality with regards to reference mode adapters: // Since we don't use serializeReplacer on reference mode adapters, we make // lightweight clone, cloning only db container and collection containers (object refs are same). interface MN { m: number; n: number; } class MyFakeReferenceAdapter implements StorageAdapter { mode = "reference"; loadDatabase(dbname: string) { expect(typeof (dbname)).toEqual("string"); const result = new Loki("new db"); const n1 = result.addCollection<MN>("n1"); const n2 = result.addCollection<MN>("n2"); n1.insert({ m: 9, n: 8 }); n2.insert({ m: 7, n: 6 }); return Promise.resolve(result); } saveDatabase() { return Promise.resolve(); } deleteDatabase() { return Promise.resolve(); } exportDatabase(dbname: string, dbref: Loki) { expect(typeof (dbname)).toEqual("string"); expect(dbref.constructor.name).toEqual("Loki"); expect(dbref["_persistenceAdapter"]).toEqual(null); expect(dbref["_collections"].length).toEqual(2); // these changes should not affect original database dbref["filename"] = "somethingelse"; dbref["_collections"][0].name = "see1"; return Promise.resolve(); } } const adapter = new MyFakeReferenceAdapter(); const db = new Loki("rma test"); let db2: Loki; db.initializePersistence({ adapter: adapter }); const c1 = db.addCollection<AB>("c1"); const c2 = db.addCollection<AB>("c2"); c1.insert({ a: 1, b: 2 }); c2.insert({ a: 3, b: 4 }); db.saveDatabase().then(() => { expect(db["persistenceAdapter"]).not.toEqual(null); expect(db["filename"]).toEqual("rma test"); expect(db["_collections"][0].name).toEqual("c1"); expect(db.getCollection<AB>("c1").findOne({ a: 1 }).b).toEqual(2); db2 = new Loki("other name"); db2.initializePersistence({ adapter: adapter }); return db2.loadDatabase(); }).then(() => { expect(db2["_collections"].length).toEqual(2); expect(db2["_collections"][0].name).toEqual("n1"); expect(db2["_collections"][1].name).toEqual("n2"); expect(db2.getCollection<MN>("n1").findOne({ m: 9 }).n).toEqual(8); }).then(done, done.fail); }); }); describe("async adapter tests", () => { it("verify throttled async drain", (done) => { const mem = new MemoryStorage({ asyncResponses: true, asyncTimeout: 50 }); const db = new Loki("sandbox.db"); db.initializePersistence({ adapter: mem, throttledSaves: true }); // Add a collection to the database const items = db.addCollection<User>("items"); items.insert({ name: "mjolnir", owner: "thor", maker: "dwarves" }); items.insert({ name: "gungnir", owner: "odin", maker: "elves" }); const tyr = items.insert({ name: "tyrfing", owner: "Svafrlami", maker: "dwarves" }); const drau = items.insert({ name: "draupnir", owner: "odin", maker: "elves" }); const another = db.addCollection<AB>("another"); const ai = another.insert({ a: 1, b: 2 }); // this should immediately kick off the first save db.saveDatabase(); // the following saves (all async) should coalesce into one save ai.b = 3; another.update(ai); db.saveDatabase(); tyr.owner = "arngrim"; items.update(tyr); db.saveDatabase(); drau.maker = "dwarves"; items.update(drau); db.saveDatabase(); db.throttledSaveDrain().then(() => { // Wait until saves are complete and then loading the database and make // sure all saves are complete and includes their changes const db2 = new Loki("sandbox.db"); db2.initializePersistence({ adapter: mem }); db2.loadDatabase().then(() => { // total of 2 saves should have occurred expect(mem.hashStore["sandbox.db"].savecount).toEqual(2); // verify the saved database contains all expected changes expect(db2.getCollection<AB>("another").findOne({ a: 1 }).b).toEqual(3); expect(db2.getCollection<User>("items").findOne({ name: "tyrfing" }).owner).toEqual("arngrim"); expect(db2.getCollection<User>("items").findOne({ name: "draupnir" }).maker).toEqual("dwarves"); done(); }); }); }); it("verify throttledSaveDrain with duration timeout works", (done) => { const mem = new MemoryStorage({ asyncResponses: true, asyncTimeout: 200 }); const db = new Loki("sandbox.db"); db.initializePersistence({ adapter: mem }); // Add a collection to the database const items = db.addCollection<User>("items"); items.insert({ name: "mjolnir", owner: "thor", maker: "dwarves" }); items.insert({ name: "gungnir", owner: "odin", maker: "elves" }); const tyr = items.insert({ name: "tyrfing", owner: "Svafrlami", maker: "dwarves" }); const drau = items.insert({ name: "draupnir", owner: "odin", maker: "elves" }); const another = db.addCollection<AB>("another"); const ai = another.insert({ a: 1, b: 2 }); // this should immediately kick off the first save (~200ms) db.saveDatabase(); // now queue up a sequence to be run one after the other, at ~50ms each (~300ms total) when first completes ai.b = 3; another.update(ai); db.saveDatabase().then(() => { tyr.owner = "arngrim"; items.update(tyr); return db.saveDatabase(); }).then(() => { drau.maker = "dwarves"; items.update(drau); return db.saveDatabase(); }); expect(db["_throttledSaveRunning"]).not.toEqual(null); expect(db["_throttledSavePending"]).not.toEqual(null); // we want this to fail so above they should be bootstrapping several // saves which take about 400ms to complete. // The full drain can take one save/callback cycle longer than duration (~200ms). db.throttledSaveDrain({ recursiveWaitLimit: true, recursiveWaitLimitDuration: 200 }) .then(() => { expect(true).toEqual(false); done(); }, () => { expect(true).toEqual(true); done(); }); }); it("verify throttled async throttles", (done) => { const mem = new MemoryStorage({ asyncResponses: true, asyncTimeout: 50 }); const db = new Loki("sandbox.db"); db.initializePersistence({ adapter: mem }); // Add a collection to the database const items = db.addCollection<User>("items"); items.insert({ name: "mjolnir", owner: "thor", maker: "dwarves" }); items.insert({ name: "gungnir", owner: "odin", maker: "elves" }); const tyr = items.insert({ name: "tyrfing", owner: "Svafrlami", maker: "dwarves" }); const drau = items.insert({ name: "draupnir", owner: "odin", maker: "elves" }); const another = db.addCollection<AB>("another"); const ai = another.insert({ a: 1, b: 2 }); // this should immediately kick off the first save db.saveDatabase(); // the following saves (all async) should coalesce into one save ai.b = 3; another.update(ai); db.saveDatabase(); tyr.owner = "arngrim"; items.update(tyr); db.saveDatabase(); drau.maker = "dwarves"; items.update(drau); db.saveDatabase(); // give all async saves time to complete and then verify outcome setTimeout(() => { // total of 2 saves should have occurred expect(mem.hashStore["sandbox.db"].savecount).toEqual(2); // verify the saved database contains all expected changes const db2 = new Loki("sandbox.db"); db2.initializePersistence({ adapter: mem }); db2.loadDatabase().then(() => { expect(db2.getCollection<AB>("another").findOne({ a: 1 }).b).toEqual(3); expect(db2.getCollection<User>("items").findOne({ name: "tyrfing" }).owner).toEqual("arngrim"); expect(db2.getCollection<User>("items").findOne({ name: "draupnir" }).maker).toEqual("dwarves"); done(); }); }, 200); }); it("verify there is no race condition with dirty-checking", (done) => { const mem = new MemoryStorage({ asyncResponses: true, asyncTimeout: 50 }); const db = new Loki("sandbox.db"); db.initializePersistence({ adapter: mem }); const items = db.addCollection<User & { foo?: string }>("items"); items.insert({ name: "mjolnir", owner: "thor", maker: "dwarves" }); const gungnir = items.insert({ name: "gungnir", owner: "odin", maker: "elves" }); expect(db["_autosaveDirty"]()).toBe(true); db.saveDatabase().then(() => { // since an update happened after calling saveDatabase (but before save was commited), db should still be dirty expect(db["_autosaveDirty"]()).toBe(true); done(); }); // this happens immediately after saveDatabase is called gungnir.foo = "bar"; items.update(gungnir); }); it("verify loadDatabase in the middle of throttled saves will wait for queue to drain first", (done) => { const mem = new MemoryStorage({ asyncResponses: true, asyncTimeout: 75 }); const db = new Loki("sandbox.db"); db.initializePersistence({ adapter: mem }); // Add a collection to the database const items = db.addCollection<User>("items"); items.insert({ name: "mjolnir", owner: "thor", maker: "dwarves" }); items.insert({ name: "gungnir", owner: "odin", maker: "elves" }); const tyr = items.insert({ name: "tyrfing", owner: "Svafrlami", maker: "dwarves" }); const drau = items.insert({ name: "draupnir", owner: "odin", maker: "elves" }); const another = db.addCollection<AB>("another"); const ai = another.insert({ a: 1, b: 2 }); // this should immediately kick off the first save (~100ms) db.saveDatabase(); // now queue up a sequence to be run one after the other, at ~50ms each (~300ms total) when first completes ai.b = 3; another.update(ai); db.saveDatabase().then(() => { tyr.owner = "arngrim"; items.update(tyr); db.saveDatabase().then(() => { drau.maker = "dwarves"; items.update(drau); db.saveDatabase(); }); }); expect(db["_throttledSaveRunning"]).not.toEqual(null); expect(db["_throttledSavePending"]).not.toEqual(null); // at this point, several rounds of saves should be triggered... // a load at this scope (possibly simulating script run from different code path) // should wait until any pending saves are complete, then freeze saves (queue them ) while loading, // then re-enable saves db.loadDatabase().then(() => { expect(db.getCollection<AB>("another").findOne({ a: 1 }).b).toEqual(3); expect(db.getCollection<User>("items").findOne({ name: "tyrfing" }).owner).toEqual("arngrim"); expect(db.getCollection<User>("items").findOne({ name: "draupnir" }).maker).toEqual("dwarves"); }); setTimeout(() => { done(); }, 600); }); }); describe("autosave/autoload", () => { it("verify autosave works", (done) => { class DummyStorage implements StorageAdapter { public counter = 0; loadDatabase(_0: string): Promise<any> { return undefined; } saveDatabase(_0: string, _1: string): Promise<void> { this.counter++; return Promise.resolve(); } } const dummyStorage = new DummyStorage(); const db = new Loki("sandbox.db"); const items = db.addCollection<User>("items"); db.initializePersistence({ adapter: dummyStorage, autosave: true, autosaveInterval: 1 }) .then(() => { items.insert({ name: "mjolnir", owner: "thor", maker: "dwarves" }); expect(dummyStorage.counter).toEqual(0); return new Promise(resolve => setTimeout(resolve, 2)); }) .then(() => { items.insert({ name: "gungnir", owner: "odin", maker: "elves" }); expect(dummyStorage.counter).toEqual(1); return new Promise(resolve => setTimeout(resolve, 2)); }) .then(() => { items.insert({ name: "gungnir", owner: "odin", maker: "elves" }); expect(dummyStorage.counter).toEqual(2); return db.close(); }) .then(() => { expect(dummyStorage.counter).toEqual(3); }) .then(done) .catch(done.fail); }); it("verify autosave with autoload works", (done) => { const mem = new MemoryStorage({ asyncResponses: true, asyncTimeout: 1 }); const db = new Loki("sandbox.db"); const db2 = new Loki("sandbox.db"); const items = db.addCollection<User>("items"); db.initializePersistence({ adapter: mem, autosave: true, autosaveInterval: 1 }) .then(() => { items.insert({ name: "mjolnir", owner: "thor", maker: "dwarves" }); return new Promise(resolve => setTimeout(resolve, 2)); }) .then(() => { return db2.initializePersistence({ adapter: mem, autoload: true }); }) .then(() => { expect(db2.getCollection("items")).toBeDefined(); return db.close(); }) .then(done) .catch(done.fail); }); }); describe("testing changesAPI", () => { it("verify pending changes persist across save/load cycle", (done) => { const mem = new MemoryStorage(); const db = new Loki("sandbox.db"); let db2: Loki; db.initializePersistence({ adapter: mem }); // Add a collection to the database const items = db.addCollection<User>("items", { disableChangesApi: false }); // Add some documents to the collection items.insert({ name: "mjolnir", owner: "thor", maker: "dwarves" }); items.insert({ name: "gungnir", owner: "odin", maker: "elves" }); items.insert({ name: "tyrfing", owner: "Svafrlami", maker: "dwarves" }); items.insert({ name: "draupnir", owner: "odin", maker: "elves" }); // Find and update an existing document const tyrfing = items.findOne({ "name": "tyrfing" }); tyrfing.owner = "arngrim"; items.update(tyrfing); // memory storage is synchronous so i will not bother with callbacks db.saveDatabase().then(() => { db2 = new Loki("sandbox.db"); db2.initializePersistence({ adapter: mem }); return db2.loadDatabase(); }).then(() => { const result = JSON.parse(db2.serializeChanges()); expect(result.length).toEqual(5); expect(result[0].name).toEqual("items"); expect(result[0].operation).toEqual("I"); expect(result[0].obj.name).toEqual("mjolnir"); expect(result[4].name).toEqual("items"); expect(result[4].operation).toEqual("U"); expect(result[4].obj.name).toEqual("tyrfing"); }).then(done, done.fail); }); });
the_stack
'use strict'; import { getAbsolutUrl } from "chord/base/node/url"; import { ISong } from "chord/music/api/song"; import { ILyric } from 'chord/music/api/lyric'; import { IAlbum } from "chord/music/api/album"; import { IArtist } from "chord/music/api/artist"; import { ITag } from "chord/music/api/tag"; import { ICollection } from "chord/music/api/collection"; import { IAudio } from "chord/music/api/audio"; import { IUserProfile, IAccount } from "chord/music/api/user"; import { getSongUrl, getAlbumUrl, getArtistUrl, getCollectionUrl, getUserUrl, getSongId, getAlbumId, getArtistId, getCollectionId, getUserId, } from "chord/music/common/origin"; import { makeLyric } from 'chord/music/utils/lyric'; const _staticResourceBasicUrl = 'http://img.xiami.net'; const _origin = 'xiami'; const _getSongUrl: (id: string) => string = getSongUrl.bind(null, _origin); const _getSongId: (id: string) => string = getSongId.bind(null, _origin); const _getAlbumUrl: (id: string) => string = getAlbumUrl.bind(null, _origin); const _getAlbumId: (id: string) => string = getAlbumId.bind(null, _origin); const _getArtistUrl: (id: string) => string = getArtistUrl.bind(null, _origin); const _getArtistId: (id: string) => string = getArtistId.bind(null, _origin); const _getCollectionUrl: (id: string) => string = getCollectionUrl.bind(null, _origin); const _getCollectionId: (id: string) => string = getCollectionId.bind(null, _origin); const _getUserUrl: (id: string) => string = getUserUrl.bind(null, _origin); const _getUserId: (id: string) => string = getUserId.bind(null, _origin); /** * All images from 'http://img.xiami.net' and 'http://pic.xiami.net/' * can be resize by adding follow params * ?x-oss-process=image/resize,m_fill,w_382,h_382/format,webp */ export function makeSong(info: any): ISong { let songInfo = info['songDetail'] || info; let songExtInfo = info['songExt'] || info; let lyricUrl = songInfo['lyricInfo'] ? songInfo['lyricInfo']['lyricFile'] : songInfo['lyric']; let audios = []; if (songInfo['listenFiles'] && songInfo['listenFiles'].length > 0) { audios = songInfo['listenFiles'].map(a => makeAudio(a)).sort((x, y) => y.kbps - x.kbps); } else { // block song audio may be at here let backupSong = songInfo['bakSong']; if (backupSong && backupSong['listenFiles'] && backupSong['listenFiles'].length > 0) { audios = backupSong['listenFiles'].map(a => makeAudio(a)).sort((x, y) => y.kbps - x.kbps); } } let styles = songExtInfo['songStyle'] ? (songExtInfo['songStyle']['styles'] || []).map(i => ({ id: i['id'].toString(), name: i['title'] })) : []; let tags = songExtInfo['songTag'] ? (songExtInfo['songTag']['tags'] || []).map(i => ({ id: i['id'].toString(), name: i['name'] })) : []; let songOriginalId = songInfo['songId']; let song: ISong = { songId: _getSongId(songOriginalId), type: 'song', origin: _origin, songOriginalId, url: _getSongUrl(songOriginalId), songName: songInfo['songName'], subTitle: songInfo['subName'], songWriters: songInfo['songwriters'], singers: songInfo['singers'], albumId: _getAlbumId(songInfo['albumId']), albumOriginalId: (songInfo['albumId'] || '').toString(), albumName: songInfo['albumName'], albumCoverUrl: songInfo['albumLogo'], artistId: _getArtistId(songInfo['artistId']), artistOriginalId: (songInfo['artistId'] || '').toString(), artistName: songInfo['artistName'], artistAvatarUrl: songInfo['artistLogo'], composer: info['composer'], styles, tags, lyricUrl, track: songInfo['track'], cdSerial: songInfo['cdSerial'], // millisecond duration: songInfo['length'], // millisecond releaseDate: songInfo['gmtPublish'] || songInfo['gmtCreate'] || (songExtInfo['album'] ? songExtInfo['album']['gmtPublish'] : null), playCountWeb: info['playCount'] || null, playCount: 0, audios, }; return song; } export function makeSongs(info: any): Array<ISong> { return (info || []).map(songInfo => makeSong(songInfo)); } export function makeAliLyric(songId: string, info: any): ILyric { let lyric = makeLyric(info); lyric.songId = _getSongId(songId); return lyric; } export function makeAlbum(info: any): IAlbum { let albumOriginalId = info['albumId'].toString(); let albumId = _getAlbumId(albumOriginalId); let albumCoverUrl = getAbsolutUrl(info['albumLogo'], _staticResourceBasicUrl); let albumName = info['albumName']; let artistOriginalId = info['artistId'].toString(); let artistId = _getArtistId(artistOriginalId); let artistName = info['artistName']; let releaseDate = info['gmtPublish'] || info['gmtCreate']; let duration: number = 0; let songs = (info['songs'] || []).map(i => makeSong(i)); songs.forEach(song => { duration += song.duration; if (!song.albumOriginalId) { song.albumOriginalId = albumOriginalId; song.albumId = albumId; song.albumCoverUrl = albumCoverUrl; } if (!song.artistOriginalId) { song.artistOriginalId = artistOriginalId; song.artistId = artistId; } }); let album: IAlbum = { albumId: _getAlbumId(albumOriginalId), type: 'album', origin: _origin, albumOriginalId: albumOriginalId, url: _getAlbumUrl(albumOriginalId), albumName, albumCoverUrl, artistId, artistOriginalId, artistName, duration: duration, releaseDate, songs: songs, songCount: songs.length, }; return album; } export function makeAlbums(info: any): Array<IAlbum> { return (info || []).map(albumInfo => makeAlbum(albumInfo)); } export function makeCollection(info: any): ICollection { let collectionOriginalId = info['listId']; let collectionId = _getCollectionId(collectionOriginalId); let collectionName = info['collectName']; let collectionCoverUrl = getAbsolutUrl(info['collectLogo'], _staticResourceBasicUrl); let tags: Array<ITag> = (info['tags'] || []).map(tag => ({ name: tag })); let songs: Array<ISong> = (info['songs'] || []).map(songInfo => makeAliSong(songInfo)); let duration = songs.length != 0 ? songs.map(s => s.duration).reduce((x, y) => x + y) : null; let collection: ICollection = { collectionId, type: 'collection', origin: _origin, collectionOriginalId, url: _getCollectionUrl(collectionOriginalId), collectionName, collectionCoverUrl, userId: _getUserId((info['userId'] || '').toString()), userName: info['userName'], // TODO: updateDate // updateDate: info['gmtModify'], releaseDate: info['gmtCreate'], description: info['description'], tags, duration, songs, songCount: info['songCount'], playCount: info['playCount'], likeCount: info['collects'], }; return collection; } export function makeCollections(info: any): Array<ICollection> { return (info || []).map(collectionInfo => makeCollection(collectionInfo)); } export function makeArtist(info: any): IArtist { let artistOriginalId = info['artistId']; let artistId = _getArtistId(artistOriginalId); let artistAvatarUrl = getAbsolutUrl(info['artistLogo'], _staticResourceBasicUrl); let artistAlias = info['alias'].split('/').filter(a => a.trim() != '').map(a => a.trim()); let artist: IArtist = { artistId, type: 'artist', origin: _origin, artistOriginalId: artistOriginalId, url: _getArtistUrl(artistOriginalId), artistName: info['artistName'], artistAlias: artistAlias, artistAvatarUrl: artistAvatarUrl, area: info['area'], description: info['description'], songs: [], albums: [], playCount: info['playCount'], likeCount: info['countLikes'], }; return artist; } export function makeArtists(info: any): Array<IArtist> { return (info || []).map(artistInfo => makeArtist(artistInfo)); } function getKbps(str: string): number { let r = /\/\/\w(\d{2,3})\./.exec(str.slice(0, 20)); if (r) { return parseInt(r[1]); } else { return 128; } } function makeAudio(info: any): IAudio { let url = info['listenFile'] || info['url']; let audio: IAudio = { format: info['format'], size: info['fileSize'] || info['filesize'], kbps: getKbps(url), url, } return audio; } export function makeAliSong(info: any): ISong { let lyricUrl: string; if (!!info['lyricInfo']) { lyricUrl = getAbsolutUrl(info['lyricInfo']['lyricFile'], _staticResourceBasicUrl); } let albumCoverUrl: string = getAbsolutUrl(info['albumLogo'], _staticResourceBasicUrl); let artistAvatarUrl: string = getAbsolutUrl(info['artistLogo'], _staticResourceBasicUrl); let songOriginalId = info['songId'].toString(); let audios = []; if (info['listenFiles'] && info['listenFiles'].length > 0) { audios = info['listenFiles'].map(a => makeAudio(a)).sort((x, y) => y.kbps - x.kbps); } else { // block song audio may be at here let backupSong = info['bakSong']; if (backupSong && backupSong['listenFiles'] && backupSong['listenFiles'].length > 0) { audios = backupSong['listenFiles'].map(a => makeAudio(a)).sort((x, y) => y.kbps - x.kbps); } } let song: ISong = { songId: _getSongId(songOriginalId), type: 'song', origin: _origin, songOriginalId, url: _getSongUrl(songOriginalId), songName: info['songName'], subTitle: info['subName'], songWriters: info['songwriters'], singers: info['singers'], albumId: _getAlbumId(info['albumId']), albumOriginalId: info['albumId'].toString(), albumName: info['albumName'], albumCoverUrl: albumCoverUrl, artistId: _getArtistId(info['artistId']), artistOriginalId: (info['artistId'] || '').toString(), artistName: info['artistName'], artistAvatarUrl: artistAvatarUrl, composer: info['composer'], lyricUrl: lyricUrl, track: info['track'], cdSerial: info['cdSerial'], duration: info['length'], releaseDate: info['gmtCreate'], playCountWeb: info['playCount'], playCount: info['playCount'], description: info['description'], audios: audios, }; return song; } export function makeAliSongs(info: any): Array<ISong> { let songs: Array<ISong> = (info || []).map(songInfo => makeAliSong(songInfo)); return songs; } export function makeAliAlbum(info: any): IAlbum { let albumOriginalId: string = info['albumId'].toString(); let albumCoverUrl: string = getAbsolutUrl(info['albumLogo'], _staticResourceBasicUrl); let tags: Array<ITag> = [{ id: info['categoryId'], name: info['albumCategory'] }]; let songs: Array<ISong> = (info['songs'] || []).map(song => makeAliSong(song)); let album: IAlbum = { albumId: _getAlbumId(albumOriginalId), type: 'album', origin: _origin, albumOriginalId: albumOriginalId, url: _getAlbumUrl(albumOriginalId), albumName: info['albumName'], albumCoverUrl: albumCoverUrl, subTitle: info['subName'], artistId: _getArtistId(info['artistId']), artistOriginalId: info['artistId'].toString(), artistName: info['artistName'], tags: tags, description: info['description'], releaseDate: info['gmtPublish'], company: info['company'], songs: songs, songCount: info['songCount'], playCount: info['playCount'], likeCount: info['collects'], }; return album; } export function makeAliAlbums(info: any): Array<IAlbum> { let albums: Array<IAlbum> = (info || []).map(albumInfo => makeAliAlbum(albumInfo)); return albums; } export function makeAliArtist(info: any): IArtist { let artistOriginalId = info['artistId'].toString(); let artistAvatarUrl = getAbsolutUrl(info['artistLogo'], _staticResourceBasicUrl); let artistAlias = info['alias'] && info['alias'].split('/').filter(a => a.trim() != '').map(a => a.trim()); let artist: IArtist = { artistId: _getArtistId(artistOriginalId), type: 'artist', origin: _origin, artistOriginalId: artistOriginalId, url: _getArtistUrl(artistOriginalId), artistName: info['artistName'], artistAlias: artistAlias, artistAvatarUrl: artistAvatarUrl, area: info['area'], description: info['description'], songs: [], albums: [], playCount: info['playCount'], likeCount: info['countLikes'], }; return artist; } export function makeAliArtists(info: any): Array<IArtist> { let artists: Array<IArtist> = (info || []).map(artistInfo => makeAliArtist(artistInfo)); return artists; } export function makeAliCollection(info: any): ICollection { let collectionOriginalId = info['listId'].toString(); let collectionCoverUrl = getAbsolutUrl(info['collectLogo'], _staticResourceBasicUrl); let tags: Array<ITag> = (info['tags'] || []).map(tag => ({ name: tag })); let songs: Array<ISong> = (info['songs'] || []).map(songInfo => makeAliSong(songInfo)); let duration = songs.length != 0 ? songs.map(s => s.duration).reduce((x, y) => x + y) : null; let collection: ICollection = { collectionId: _getCollectionId(collectionOriginalId), type: 'collection', origin: _origin, collectionOriginalId, url: _getCollectionUrl(collectionOriginalId), collectionName: info['collectName'], collectionCoverUrl, userId: _getUserId((info['userId'] || '').toString()), userName: info['userName'], releaseDate: info['gmtCreate'], description: info['description'], tags, duration, songs, songCount: info['songCount'], playCount: info['playCount'], likeCount: info['collects'], }; return collection; } export function makeAliCollections(info: any): Array<ICollection> { let collections = (info || []).map(collectionInfo => makeAliCollection(collectionInfo)); return collections; } export function makeUserProfile(info: any): IUserProfile { let userOriginalId = info['userId'].toString(); let userAvatarUrl = (info['avatar'] || '').split('@')[0]; let user = { userId: _getUserId(userOriginalId), type: 'userProfile', origin: _origin, userOriginalId, url: _getUserUrl(userOriginalId), userName: info['nickName'], userAvatarUrl, followerCount: info['fans'] || null, followingCount: info['followers'] || null, listenCount: info['listens'] || null, description: info['description'], }; return user; } export function makeUserProfiles(info: any): Array<IUserProfile> { return info.map(userProfile => makeUserProfile(userProfile)); } export function makeUserProfileMore(info: any): IUserProfile { let userFavoriteInfo = info['userFavoriteInfo']; let user = { userId: null, origin: _origin, type: 'userProfile', artistCount: userFavoriteInfo['artistCount'], albumCount: userFavoriteInfo['albumCount'], favoriteCollectionCount: info['userFavouriteCollectCount'], }; return user; } export function makeAccount(info: any): IAccount { let userOriginalId = info['userId'].toString(); let user: IUserProfile = { userId: _getUserId(userOriginalId), type: 'userProfile', origin: _origin, userOriginalId, userName: info['nickName'], }; return { user, type: 'account', accessToken: info['accessToken'], refreshToken: info['refreshToken'], }; }
the_stack
export enum KeyEnum { /** * The user agent wasn't able to map the event's virtual keycode to a * specific key value. * This can happen due to hardware or software constraints, or because of * constraints around the platform on which the user agent is running. */ Unidentified = "Unidentified", /** The Alt (Alternative) key. */ Alt = "Alt", /** * The AltGr or AltGraph (Alternate Graphics) key. * Enables the ISO Level 3 shift modifier (where Shift is the * level 2 modifier). */ AltGraph = "AltGraph", /** * The Caps Lock key. Toggles the capital character lock on and * off for subsequent input. */ CapsLock = "CapsLock", /** * The Control, Ctrl, or Ctl key. Allows * typing control characters. */ Control = "Control", /** * The Fn (Function modifier) key. Used to allow generating * function key (F1–F15, for instance) characters on * keyboards without a dedicated function key area. Often handled in * hardware so that events aren't generated for this key. */ Fn = "Fn", /** * The FnLock or F-Lock (Function Lock) key.Toggles * the function key mode described by "Fn" on and off. Often * handled in hardware so that events aren't generated for this key. */ FnLock = "FnLock", /** The Hyper key. */ Hyper = "Hyper", /** * The Meta key. Allows issuing special command inputs. This is * the Windows logo key, or the Command or * ⌘ key on Mac keyboards. */ Meta = "Meta", /** * The NumLock (Number Lock) key. Toggles the numeric keypad * between number entry some other mode (often directional arrows). */ NumLock = "NumLock", /** * The Scroll Lock key. Toggles between scrolling and cursor * movement modes. */ ScrollLock = "ScrollLock", /** * The Shift key. Modifies keystrokes to allow typing upper (or * other) case letters, and to support typing punctuation and other special * characters. */ Shift = "Shift", /** The Super key. */ Super = "Super", /** The Symbol modifier key (found on certain virtual keyboards). */ Symbol = "Symbol", /** The Symbol Lock key. */ SymbolLock = "SymbolLock", /** * The Enter or ↵ key (sometimes labeled * Return). */ Enter = "Enter", /** The Horizontal Tab key, Tab. */ Tab = "Tab", /** The down arrow key. */ ArrowDown = "ArrowDown", /** The left arrow key. */ ArrowLeft = "ArrowLeft", /** The right arrow key. */ ArrowRight = "ArrowRight", /** The up arrow key. */ ArrowUp = "ArrowUp", /** The End key. Moves to the end of content. */ End = "End", /** The Home key. Moves to the start of content. */ Home = "Home", /** * The Page Down (or PgDn) key. Scrolls down or * displays the next page of content. */ PageDown = "PageDown", /** * The Page Up (or PgUp) key. Scrolls up or displays * the previous page of content. */ PageUp = "PageUp", /** * The Backspace key. This key is labeled Delete on * Mac keyboards. */ Backspace = "Backspace", /** The Clear key. Removes the currently selected input. */ Clear = "Clear", /** The Copy key (on certain extended keyboards). */ Copy = "Copy", /** The Cursor Select key, CrSel. */ CrSel = "CrSel", /** The Cut key (on certain extended keyboards). */ Cut = "Cut", /** The Delete key, Del. */ Delete = "Delete", /** * Erase to End of Field. Deletes all characters from the current cursor * position to the end of the current field. */ EraseEof = "EraseEof", /** The ExSel (Extend Selection) key. */ ExSel = "ExSel", /** * The Insert key, Ins. Toggles between inserting and * overwriting text. */ Insert = "Insert", /** Paste from the clipboard. */ Paste = "Paste", /** Redo the last action. */ Redo = "Redo", /** Undo the last action. */ Undo = "Undo", /** * The Accept, Commit, or OK key or * button. Accepts the currently selected option or input method sequence * conversion. */ Accept = "Accept", /** The Again key. Redoes or repeats a previous action. */ Again = "Again", /** The Attn (Attention) key. */ Attn = "Attn", /** The Cancel key. */ Cancel = "Cancel", /** * Shows the context menu. Typically found between the * Windows (or OS) key and the Control key * on the right side of the keyboard. */ ContextMenu = "ContextMenu", /** * The Esc (Escape) key. Typically used as an exit, cancel, or * "escape this operation" button. Historically, the Escape character was * used to signal the start of a special control sequence of characters * called an "escape sequence." */ Escape = "Escape", /** The Execute key. */ Execute = "Execute", /** * The Find key. Opens an interface (typically a dialog box) for * performing a find/search operation. */ Find = "Find", /** The Finish key. */ Finish = "Finish", /** * The Help key. Opens or toggles the display of help * information. */ Help = "Help", /** * The Pause key. Pauses the current application or state, if * applicable. * Note: This shouldn't be confused with the * "MediaPause" key value, which is used for media * controllers, rather than to control applications and processes. */ Pause = "Pause", /** * The Play key. Resumes a previously paused application, if * applicable. * Note: This shouldn't be confused with the * "MediaPlay" key value, which is used for media * controllers, rather than to control applications and processes. */ Play = "Play", /** The Props (Properties) key. */ Props = "Props", /** The Select key. */ Select = "Select", /** The ZoomIn key. */ ZoomIn = "ZoomIn", /** The ZoomOut key. */ ZoomOut = "ZoomOut", /** * The Brightness Down key. Typically used to reduce the brightness of the * display. */ BrightnessDown = "BrightnessDown", /** * The Brightness Up key. Typically increases the brightness of the * display. */ BrightnessUp = "BrightnessUp", /** * The Eject key. Ejects removable media (or toggles an optical * storage device tray open and closed). */ Eject = "Eject", /** The LogOff key. */ LogOff = "LogOff", /** * The Power button or key, to toggle power on and off. * Note: Not all systems pass this key through to the * user agent. */ Power = "Power", /** * The PowerOff or PowerDown key. Shuts off the * system. */ PowerOff = "PowerOff", /** * The PrintScreen or PrtScr key. Sometimes * SnapShot. Captures the screen and prints it or saves it to * disk. */ PrintScreen = "PrintScreen", /** * The Hibernate key. This saves the state of the computer to * disk and then shuts down; the computer can be returned to its previous * state by restoring the saved state information. */ Hibernate = "Hibernate", /** * The Standby key. (Also known as Suspend or * Sleep.) This turns off the display and puts the computer in a * low power consumption mode, without completely powering off. */ Standby = "Standby", /** * The WakeUp key. Used to wake the computer from the * hibernation or standby modes. */ WakeUp = "WakeUp", /** * The All Candidates key, which starts multi-candidate mode, in * which multiple candidates are displayed for the ongoing input. */ AllCandidates = "AllCandidates", /** The Alphanumeric key. */ Alphanumeric = "Alphanumeric", /** * The Code Input key, which enables code input mode, which lets * the user enter characters by typing their code points (their Unicode * character numbers, typically). */ CodeInput = "CodeInput", /** The Compose key. */ Compose = "Compose", /** * The Convert key, which instructs the IME to convert the * current input method sequence into the resulting character. */ Convert = "Convert", /** * A dead "combining" key; that is, a key which is used in tandem with * other keys to generate accented and other modified characters. If * pressed by itself, it doesn't generate a character. * If you wish to identify which specific dead key was pressed (in cases * where more than one exists), you can do so by examining the * KeyboardEvent's associated * compositionupdate event's * data property. */ Dead = "Dead", /** * The Final (Final Mode) key is used on some Asian keyboards to * enter final mode when using IMEs. */ FinalMode = "FinalMode", /** * Switches to the first character group on an * ISO/IEC 9995 keyboard. Each key may have multiple groups of characters, each in its own * column. Pressing this key instructs the device to interpret keypresses * as coming from the first column on subsequent keystrokes. */ GroupFirst = "GroupFirst", /** * Switches to the last character group on an * ISO/IEC 9995 keyboard. */ GroupLast = "GroupLast", /** * Switches to the next character group on an * ISO/IEC 9995 keyboard. */ GroupNext = "GroupNext", /** * Switches to the previous character group on an * ISO/IEC 9995 keyboard. */ GroupPrevious = "GroupPrevious", /** The Mode Change key. Toggles or cycles among input modes of IMEs. */ ModeChange = "ModeChange", /** * The Next Candidate function key. Selects the next possible match for the * ongoing input. */ NextCandidate = "NextCandidate", /** * The NonConvert ("Don't convert") key. This accepts the * current input method sequence without running conversion when using an * IME. */ NonConvert = "NonConvert", /** * The Previous Candidate key. Selects the previous possible match for the * ongoing input. */ PreviousCandidate = "PreviousCandidate", /** The Process key. Instructs the IME to process the conversion. */ Process = "Process", /** * The Single Candidate key. Enables single candidate mode (as opposed to * multi-candidate mode); in this mode, only one candidate is displayed at * a time. */ SingleCandidate = "SingleCandidate", /** * The Hangul (Korean character set) mode key, which toggles * between Hangul and English entry modes. */ HangulMode = "HangulMode", /** * Selects the Hanja mode, for converting Hangul characters to the more * specific Hanja characters. */ HanjaMode = "HanjaMode", /** * Selects the Junja mode, in which Korean is represented using single-byte * Latin characters. */ JunjaMode = "JunjaMode", /** * The Eisu key. This key's purpose is defined by the IME, but * may be used to close the IME. */ Eisu = "Eisu", /** The Hankaku (half-width characters) key. */ Hankaku = "Hankaku", /** The Hiragana key; selects Kana characters mode. */ Hiragana = "Hiragana", /** Toggles between the Hiragana and Katakana writing systems. */ HiraganaKatakana = "HiraganaKatakana", /** The Kana Mode (Kana Lock) key. */ KanaMode = "KanaMode", /** * The Kanji Mode key. Enables entering Japanese text using the * ideographic characters of Chinese origin. */ KanjiMode = "KanjiMode", /** The Katakana key. */ Katakana = "Katakana", /** The Romaji key; selects the Roman character set. */ Romaji = "Romaji", /** The Zenkaku (full width) characters key. */ Zenkaku = "Zenkaku", /** The Zenkaku/Hankaku (full width/half width) toggle key. */ ZenkakuHanaku = "ZenkakuHanaku", /** The first general-purpose function key, F1. */ F1 = "F1", /** The F2 key. */ F2 = "F2", /** The F3 key. */ F3 = "F3", /** The F4 key. */ F4 = "F4", /** The F5 key. */ F5 = "F5", /** The F6 key. */ F6 = "F6", /** The F7 key. */ F7 = "F7", /** The F8 key. */ F8 = "F8", /** The F9 key. */ F9 = "F9", /** The F10 key. */ F10 = "F10", /** The F11 key. */ F11 = "F11", /** The F12 key. */ F12 = "F12", /** The F13 key. */ F13 = "F13", /** The F14 key. */ F14 = "F14", /** The F15 key. */ F15 = "F15", /** The F16 key. */ F16 = "F16", /** The F17 key. */ F17 = "F17", /** The F18 key. */ F18 = "F18", /** The F19 key. */ F19 = "F19", /** The F20 key. */ F20 = "F20", /** The first general-purpose virtual function key. */ Soft1 = "Soft1", /** The second general-purpose virtual function key. */ Soft2 = "Soft2", /** The third general-purpose virtual function key. */ Soft3 = "Soft3", /** The fourth general-purpose virtual function key. */ Soft4 = "Soft4", /** * Presents a list of recently-used applications which lets the user change * apps quickly. */ AppSwitch = "AppSwitch", /** The Call key. Dials the number which has been entered. */ Call = "Call", /** The Camera key. Activates the camera. */ Camera = "Camera", /** The Focus key. Focuses the camera. */ CameraFocus = "CameraFocus", /** The End Call or Hang Up button. */ EndCall = "EndCall", /** The Back button. */ GoBack = "GoBack", /** * The Home button. Returns the user to the phone's main screen * (usually an application launcher). */ GoHome = "GoHome", /** * The Headset Hook key. This is typically actually a button on * the headset which is used to hang up calls and play or pause media. */ HeadsetHook = "HeadsetHook", /** The Redial button. Redials the last-called number. */ LastNumberRedial = "LastNumberRedial", /** The Notification key. */ Notification = "Notification", /** * A button which cycles among the notification modes: silent, vibrate, * ring, and so forth. */ MannerMode = "MannerMode", /** The Voice Dial key. Initiates voice dialing. */ VoiceDial = "VoiceDial", /** Switches to the previous channel. */ ChannelDown = "ChannelDown", /** Switches to the next channel. */ ChannelUp = "ChannelUp", /** Starts, continues, or increases the speed of fast forwarding the media. */ MediaFastForward = "MediaFastForward", /** * Pauses the currently playing media. * Note: Some older applications use * "Pause", but this is not correct. */ MediaPause = "MediaPause", /** * Starts or continues playing media at normal speed, if not already doing * so. Has no effect otherwise. */ MediaPlay = "MediaPlay", /** Toggles between playing and pausing the current media. */ MediaPlayPause = "MediaPlayPause", /** Starts or resumes recording media. */ MediaRecord = "MediaRecord", /** Starts, continues, or increases the speed of rewinding the media. */ MediaRewind = "MediaRewind", /** * Stops the current media activity (such as playing, recording, pausing, * forwarding, or rewinding). Has no effect if the media is currently * stopped already. */ MediaStop = "MediaStop", /** Seeks to the next media or program track. */ MediaTrackNext = "MediaTrackNext", /** Seeks to the previous media or program track. */ MediaTrackPrevious = "MediaTrackPrevious", /** Adjusts audio balance toward the left. */ AudioBalanceLeft = "AudioBalanceLeft", /** Adjusts audio balance toward the right. */ AudioBalanceRight = "AudioBalanceRight", /** Decreases the amount of bass. */ AudioBassDown = "AudioBassDown", /** * Reduces bass boosting or cycles downward through bass boost modes or * states. */ AudioBassBoostDown = "AudioBassBoostDown", /** Toggles bass boosting on and off. */ AudioBassBoostToggle = "AudioBassBoostToggle", /** * Increases the amoung of bass boosting, or cycles upward through a set of * bass boost modes or states. */ AudioBassBoostUp = "AudioBassBoostUp", /** Increases the amount of bass. */ AudioBassUp = "AudioBassUp", /** Adjusts the audio fader toward the front. */ AudioFaderFront = "AudioFaderFront", /** Adjusts the audio fader toward the rear. */ AudioFaderRear = "AudioFaderRear", /** Selects the next available surround sound mode. */ AudioSurroundModeNext = "AudioSurroundModeNext", /** Decreases the amount of treble. */ AudioTrebleDown = "AudioTrebleDown", /** Increases the amount of treble. */ AudioTrebleUp = "AudioTrebleUp", /** Decreases the audio volume. */ AudioVolumeDown = "AudioVolumeDown", /** Mutes the audio. */ AudioVolumeMute = "AudioVolumeMute", /** Increases the audio volume. */ AudioVolumeUp = "AudioVolumeUp", /** Toggles the microphone on and off. */ MicrophoneToggle = "MicrophoneToggle", /** Decreases the microphone's input volume. */ MicrophoneVolumeDown = "MicrophoneVolumeDown", /** Mutes the microphone input. */ MicrophoneVolumeMute = "MicrophoneVolumeMute", /** Increases the microphone's input volume. */ MicrophoneVolumeUp = "MicrophoneVolumeUp", /** Switches into TV viewing mode. */ TV = "TV", /** Toggles 3D TV mode on and off. */ TV3DMode = "TV3DMode", /** Toggles between antenna and cable inputs. */ TVAntennaCable = "TVAntennaCable", /** Toggles audio description mode on and off. */ TVAudioDescription = "TVAudioDescription", /** * Decreases trhe audio description's mixing volume; reduces the volume of * the audio descriptions relative to the program sound. */ TVAudioDescriptionMixDown = "TVAudioDescriptionMixDown", /** * Increases the audio description's mixing volume; increases the volume of * the audio descriptions relative to the program sound. */ TVAudioDescriptionMixUp = "TVAudioDescriptionMixUp", /** * Displays or hides the media contents available for playback (this may be * a channel guide showing the currently airing programs, or a list of * media files to play). */ TVContentsMenu = "TVContentsMenu", /** Displays or hides the TV's data service menu. */ TVDataService = "TVDataService", /** Cycles the input mode on an external TV. */ TVInput = "TVInput", /** Switches to the input "Component 1." */ TVInputComponent1 = "TVInputComponent1", /** Switches to the input "Component 2." */ TVInputComponent2 = "TVInputComponent2", /** Switches to the input "Composite 1." */ TVInputComposite1 = "TVInputComposite1", /** Switches to the input "Composite 2." */ TVInputComposite2 = "TVInputComposite2", /** Switches to the input "HDMI 1." */ TVInputHDMI1 = "TVInputHDMI1", /** Switches to the input "HDMI 2." */ TVInputHDMI2 = "TVInputHDMI2", /** Switches to the input "HDMI 3." */ TVInputHDMI3 = "TVInputHDMI3", /** Switches to the input "HDMI 4." */ TVInputHDMI4 = "TVInputHDMI4", /** Switches to the input "VGA 1." */ TVInputVGA1 = "TVInputVGA1", /** The Media Context menu key. */ TVMediaContext = "TVMediaContext", /** Toggle the TV's network connection on and off. */ TVNetwork = "TVNetwork", /** Put the TV into number entry mode. */ TVNumberEntry = "TVNumberEntry", /** The device's power button. */ TVPower = "TVPower", /** Radio button. */ TVRadioService = "TVRadioService", /** Satellite button. */ TVSatellite = "TVSatellite", /** Broadcast Satellite button. */ TVSatelliteBS = "TVSatelliteBS", /** Communication Satellite button. */ TVSatelliteCS = "TVSatelliteCS", /** Toggles among available satellites. */ TVSatelliteToggle = "TVSatelliteToggle", /** * Selects analog terrestrial television service (analog cable or antenna * reception). */ TVTerrestrialAnalog = "TVTerrestrialAnalog", /** * Selects digital terrestrial television service (digital cable or antenna * receiption). */ TVTerrestrialDigital = "TVTerrestrialDigital", /** Timer programming button. */ TVTimer = "TVTimer", /** Changes the input mode on an external audio/video receiver (AVR) unit. */ AVRInput = "AVRInput", /** Toggles the power on an external AVR unit. */ AVRPower = "AVRPower", /** * General-purpose media function key, color-coded red. This has index * 0 among the colored keys. */ ColorF0Red = "ColorF0Red", /** * General-purpose media funciton key, color-coded green. This has index * 1 among the colored keys. */ ColorF1Green = "ColorF1Green", /** * General-purpose media funciton key, color-coded yellow. This has index * 2 among the colored keys. */ ColorF2Yellow = "ColorF2Yellow", /** * General-purpose media funciton key, color-coded blue. This has index * 3 among the colored keys. */ ColorF3Blue = "ColorF3Blue", /** * General-purpose media funciton key, color-coded grey. This has index * 4 among the colored keys. */ ColorF4Grey = "ColorF4Grey", /** * General-purpose media funciton key, color-coded brown. This has index * 5 among the colored keys. */ ColorF5Brown = "ColorF5Brown", /** Toggles closed captioning on and off. */ ClosedCaptionToggle = "ClosedCaptionToggle", /** * Adjusts the brightness of the device by toggling between two brightness * levels or by cycling among multiple brightness levels. */ Dimmer = "Dimmer", /** Cycles among video sources. */ DisplaySwap = "DisplaySwap", /** Switches the input source to the Digital Video Recorder (DVR). */ DVR = "DVR", /** The Exit button, which exits the curreent application or menu. */ Exit = "Exit", /** Clears the program or content stored in the first favorites list slot. */ FavoriteClear0 = "FavoriteClear0", /** Clears the program or content stored in the second favorites list slot. */ FavoriteClear1 = "FavoriteClear1", /** Clears the program or content stored in the third favorites list slot. */ FavoriteClear2 = "FavoriteClear2", /** Clears the program or content stored in the fourth favorites list slot. */ FavoriteClear3 = "FavoriteClear3", /** * Selects (recalls) the program or content stored in the first favorites * list slot. */ FavoriteRecall0 = "FavoriteRecall0", /** * Selects (recalls) the program or content stored in the second favorites * list slot. */ FavoriteRecall1 = "FavoriteRecall1", /** * Selects (recalls) the program or content stored in the third favorites * list slot. */ FavoriteRecall2 = "FavoriteRecall2", /** * Selects (recalls) the program or content stored in the fourth favorites * list slot. */ FavoriteRecall3 = "FavoriteRecall3", /** * Stores the current program or content into the first favorites list * slot. */ FavoriteStore0 = "FavoriteStore0", /** * Stores the current program or content into the second favorites list * slot. */ FavoriteStore1 = "FavoriteStore1", /** * Stores the current program or content into the third favorites list * slot. */ FavoriteStore2 = "FavoriteStore2", /** * Stores the current program or content into the fourth favorites list * slot. */ FavoriteStore3 = "FavoriteStore3", /** Toggles the display of the program or content guide. */ Guide = "Guide", /** * If the guide is currently displayed, this button tells the guide to * display the next day's content. */ GuideNextDay = "GuideNextDay", /** * If the guide is currently displayed, this button tells the guide to * display the previous day's content. */ GuidePreviousDay = "GuidePreviousDay", /** * Toggles the display of information about the currently selected content, * program, or media. */ Info = "Info", /** * Tells the device to perform an instant replay (typically some form of * jumping back a short amount of time then playing it again, possibly but * not usually in slow motion). */ InstantReplay = "InstantReplay", /** Opens content liniked to the current program, if available and possible. */ Link = "Link", /** Lists the current program. */ ListProgram = "ListProgram", /** Toggles a display listing currently available live content or programs. */ LiveContent = "LiveContent", /** Locks or unlocks the currently selected content or pgoram. */ Lock = "Lock", /** * Presents a list of media applications, such as photo viewers, audio and * video players, and games. [1] */ MediaApps = "MediaApps", /** The Audio Track key. */ MediaAudioTrack = "MediaAudioTrack", /** Jumps back to the last-viewed content, program, or other media. */ MediaLast = "MediaLast", /** Skips backward to the previous content or program. */ MediaSkipBackward = "MediaSkipBackward", /** Skips forward to the next content or program. */ MediaSkipForward = "MediaSkipForward", /** Steps backward to the previous content or program. */ MediaStepBackward = "MediaStepBackward", /** Steps forward to the next content or program. */ MediaStepForward = "MediaStepForward", /** * Top Menu button. Opens the media's main menu (e.g., for a DVD or Blu-Ray * disc). */ MediaTopMenu = "MediaTopMenu", /** Navigates into a submenu or option. */ NavigateIn = "NavigateIn", /** Navigates to the next item. */ NavigateNext = "NavigateNext", /** Navigates out of the current screen or menu. */ NavigateOut = "NavigateOut", /** Navigates to the previous item. */ NavigatePrevious = "NavigatePrevious", /** Cycles to the next channel in the favorites list. */ NextFavoriteChannel = "NextFavoriteChannel", /** * Cycles to the next saved user profile, if this feature is supported and * multiple profiles exist. */ NextUserProfile = "NextUserProfile", /** * Opens the user interface for selecting on demand content or programs to * watch. */ OnDemand = "OnDemand", /** Starts the process of pairing the remote with a device to be controlled. */ Pairing = "Pairing", /** A button to move the picture-in-picture view downward. */ PinPDown = "PinPDown", /** A button to control moving the picture-in-picture view. */ PinPMove = "PinPMove", /** Toggles display of th epicture-in-picture view on and off. */ PinPToggle = "PinPToggle", /** A button to move the picture-in-picture view upward. */ PinPUp = "PinPUp", /** Decreases the media playback rate. */ PlaySpeedDown = "PlaySpeedDown", /** Returns the media playback rate to normal. */ PlaySpeedReset = "PlaySpeedReset", /** Increases the media playback rate. */ PlaySpeedUp = "PlaySpeedUp", /** Toggles random media (also known as "shuffle mode") on and off. */ RandomToggle = "RandomToggle", /** * A code sent when the remote control's battery is low. This doesn't * actually correspond to a physical key at all. */ RcLowBattery = "RcLowBattery", /** Cycles among the available media recording speeds. */ RecordSpeedNext = "RecordSpeedNext", /** * Toggles radio frequency (RF) input bypass mode on and off. RF bypass * mode passes RF input directly to the RF output without any processing or * filtering. */ RfBypass = "RfBypass", /** * Toggles the channel scan mode on and off. This is a mode which flips * through channels automatically until the user stops the scan. */ ScanChannelsToggle = "ScanChannelsToggle", /** Cycles through the available screen display modes. */ ScreenModeNext = "ScreenModeNext", /** Toggles display of the device's settings screen on and off. */ Settings = "Settings", /** Toggles split screen display mode on and off. */ SplitScreenToggle = "SplitScreenToggle", /** Cycles among input modes on an external set-top box (STB). */ STBInput = "STBInput", /** Toggles on and off an external STB. */ STBPower = "STBPower", /** Toggles the display of subtitles on and off if they're available. */ Subtitle = "Subtitle", /** * Toggles display of teletext, * if available. */ Teletext = "Teletext", /** Cycles through the available video modes. */ VideoModeNext = "VideoModeNext", /** * Causes the device to identify itself in some fashion, such as by * flashing a light, briefly changing the brightness of indicator lights, * or emitting a tone. */ Wink = "Wink", /** * Toggles between full-screen and scaled content display, or otherwise * change the magnification level. */ ZoomToggle = "ZoomToggle", /** * Presents a list of possible corrections for a word which was incorrectly * identified. */ SpeechCorrectionList = "SpeechCorrectionList", /** * Toggles between dictation mode and command/control mode. This lets the * speech engine know whether to interpret spoken words as input text or as * commands. */ SpeechInputToggle = "SpeechInputToggle", /** Closes the current document or message. Must not exit the application. */ Close = "Close", /** Creates a new document or message. */ New = "New", /** Opens an existing document or message. */ Open = "Open", /** Prints the current document or message. */ Print = "Print", /** Saves the current document or message. */ Save = "Save", /** Starts spell checking the current document. */ SpellCheck = "SpellCheck", /** Opens the user interface to forward a message. */ MailForward = "MailForward", /** Opens the user interface to reply to a message. */ MailReply = "MailReply", /** Sends the current message. */ MailSend = "MailSend", /** * The Calculator key, often labeled with an icon. This is often * used as a generic application launcher key * (APPCOMMAND_LAUNCH_APP2). */ LaunchCalculator = "LaunchCalculator", /** The Calendar key. Often labeled with an icon. */ LaunchCalendar = "LaunchCalendar", /** The Contacts key. */ LaunchContacts = "LaunchContacts", /** The Mail key. Often labeled with an icon. */ LaunchMail = "LaunchMail", /** The Media Player key. */ LaunchMediaPlayer = "LaunchMediaPlayer", /** The Music Player key. Often labeled with an icon. */ LaunchMusicPlayer = "LaunchMusicPlayer", /** * The My Computer key on Windows keyboards. This is often used * as a generic application launcher key * (APPCOMMAND_LAUNCH_APP1). */ LaunchMyComputer = "LaunchMyComputer", /** * The Phone key. Opens the phone dialer application (if one is * present). */ LaunchPhone = "LaunchPhone", /** The Screen Saver key. */ LaunchScreenSaver = "LaunchScreenSaver", /** The Spreadsheet key. This key may be labeled with an icon. */ LaunchSpreadsheet = "LaunchSpreadsheet", /** * The Web Browser key. This key is frequently labeled with an * icon. */ LaunchWebBrowser = "LaunchWebBrowser", /** The WebCam key. Opens the webcam application. */ LaunchWebCam = "LaunchWebCam", /** * The Word Processor key. This may be an icon of a specific * word processor application, or a generic document icon. */ LaunchWordProcessor = "LaunchWordProcessor", /** The first generic application launcher button. */ LaunchApplication1 = "LaunchApplication1", /** The second generic application launcher button. */ LaunchApplication2 = "LaunchApplication2", /** The third generic application launcher button. */ LaunchApplication3 = "LaunchApplication3", /** The fourth generic application launcher button. */ LaunchApplication4 = "LaunchApplication4", /** The fifth generic application launcher button. */ LaunchApplication5 = "LaunchApplication5", /** The sixth generic application launcher button. */ LaunchApplication6 = "LaunchApplication6", /** The seventh generic application launcher button. */ LaunchApplication7 = "LaunchApplication7", /** The eighth generic application launcher button. */ LaunchApplication8 = "LaunchApplication8", /** The ninth generic application launcher button. */ LaunchApplication9 = "LaunchApplication9", /** The 10th generic application launcher button. */ LaunchApplication10 = "LaunchApplication10", /** The 11th generic application launcher button. */ LaunchApplication11 = "LaunchApplication11", /** The 12th generic application launcher button. */ LaunchApplication12 = "LaunchApplication12", /** The 13th generic application launcher button. */ LaunchApplication13 = "LaunchApplication13", /** The 14th generic application launcher button. */ LaunchApplication14 = "LaunchApplication14", /** The 15th generic application launcher button. */ LaunchApplication15 = "LaunchApplication15", /** The 16th generic application launcher button. */ LaunchApplication16 = "LaunchApplication16", /** * Navigates to the previous content or page in the current Web view's * history. */ BrowserBack = "BrowserBack", /** Opens the user's list of bookmarks/favorites. */ BrowserFavorites = "BrowserFavorites", /** Navigates to the next content or page in the current Web view's history. */ BrowserForward = "BrowserForward", /** Navigates to the user's preferred home page. */ BrowserHome = "BrowserHome", /** Refreshes the current page or content. */ BrowserRefresh = "BrowserRefresh", /** * Activates the user's preferred search engine or the search interface * within their browser. */ BrowserSearch = "BrowserSearch", /** Stops loading the currently displayed Web view or content. */ BrowserStop = "BrowserStop", /** * The decimal point key (typically . or * , depending on the region). * In newer browsers, this value to be the character generated by the * decimal key (one of those two characters). [1] */ Decimal = "Decimal", /** The 11 key found on certain media numeric keypads. */ Key11 = "Key11", /** The 12 key found on certain media numeric keypads. */ Key12 = "Key12", /** The numeric keypad's multiplication key, *. */ Multiply = "Multiply", /** The numeric keypad's addition key, +. */ Add = "Add", /** The numeric keypad's division key, /. */ Divide = "Divide", /** The numeric keypad's subtraction key, -. */ Subtract = "Subtract", /** * The numeric keypad's places separator character. * (In the United States this is a comma, but elsewhere it is frequently * a period.) */ Separator = "Separator", Space = "(space character)", Key_0 = "0", Key_1 = "1", Key_2 = "2", Key_3 = "3", Key_4 = "4", Key_5 = "5", Key_6 = "6", Key_7 = "7", Key_8 = "8", Key_9 = "9", A = "a", B = "b", C = "c", D = "d", E = "e", F = "f", G = "g", H = "h", I = "i", J = "j", K = "k", L = "l", M = "m", N = "n", O = "o", P = "p", Q = "q", R = "r", S = "s", T = "t", U = "u", V = "v", W = "w", X = "x", Y = "y", Z = "z", } type KeyCodes = { [key in KeyEnum]?: number } export let keyCodes: KeyCodes = { [KeyEnum.Enter]: 13, [KeyEnum.ArrowLeft]: 37, [KeyEnum.ArrowUp]: 38, [KeyEnum.ArrowRight]: 39, [KeyEnum.ArrowDown]: 40, [KeyEnum.Escape]: 27, [KeyEnum.Space]: 32, [KeyEnum.Backspace]: 8, [KeyEnum.Tab]: 9, [KeyEnum.Delete]: 46, [KeyEnum.Insert]: 45, [KeyEnum.PageUp]: 33, [KeyEnum.PageDown]: 34, [KeyEnum.End]: 35, [KeyEnum.Home]: 36, [KeyEnum.CapsLock]: 20, [KeyEnum.NumLock]: 144, [KeyEnum.ScrollLock]: 145, [KeyEnum.PrintScreen]: 44, [KeyEnum.Pause]: 19, [KeyEnum.Key_0]: 48, [KeyEnum.Key_1]: 49, [KeyEnum.Key_2]: 50, [KeyEnum.Key_3]: 51, [KeyEnum.Key_4]: 52, [KeyEnum.Key_5]: 53, [KeyEnum.Key_6]: 54, [KeyEnum.Key_7]: 55, [KeyEnum.Key_8]: 56, [KeyEnum.Key_9]: 57, [KeyEnum.A]: 65, [KeyEnum.B]: 66, [KeyEnum.C]: 67, [KeyEnum.D]: 68, [KeyEnum.E]: 69, [KeyEnum.F]: 70, [KeyEnum.G]: 71, [KeyEnum.H]: 72, [KeyEnum.I]: 73, [KeyEnum.J]: 74, [KeyEnum.K]: 75, [KeyEnum.L]: 76, [KeyEnum.M]: 77, [KeyEnum.N]: 78, [KeyEnum.O]: 79, [KeyEnum.P]: 80, [KeyEnum.Q]: 81, [KeyEnum.R]: 82, [KeyEnum.S]: 83, [KeyEnum.T]: 84, [KeyEnum.U]: 85, [KeyEnum.V]: 86, [KeyEnum.W]: 87, [KeyEnum.X]: 88, [KeyEnum.Y]: 89, [KeyEnum.Z]: 90, [KeyEnum.F1]: 112, [KeyEnum.F2]: 113, [KeyEnum.F3]: 114, [KeyEnum.F4]: 115, [KeyEnum.F5]: 116, [KeyEnum.F6]: 117, [KeyEnum.F7]: 118, [KeyEnum.F8]: 119, [KeyEnum.F9]: 120, [KeyEnum.F10]: 121, [KeyEnum.F11]: 122, [KeyEnum.F12]: 123, [KeyEnum.F13]: 124, [KeyEnum.F14]: 125, [KeyEnum.F15]: 126, [KeyEnum.F16]: 127, [KeyEnum.F17]: 128, [KeyEnum.F18]: 129, [KeyEnum.F19]: 130, [KeyEnum.F20]: 131, } export let keyCodeFromKey = (key: KeyEnum) => { return ( Object.entries(keyCodes).find( ([keyName]) => keyName.toLowerCase() === key.toLowerCase() )?.[1] || -1 ) }
the_stack
import highlightJS from 'highlight.js/lib/core'; // Convert to imports // ^hljs\.registerLanguage\('(.+)', require\('\./languages\/(.+)'\)\);$ // import $1 from 'highlight.js/lib/languages/$2'; // import _1c from 'highlight.js/lib/languages/1c'; // import abnf from 'highlight.js/lib/languages/abnf'; // import accesslog from 'highlight.js/lib/languages/accesslog'; // import actionscript from 'highlight.js/lib/languages/actionscript'; // import ada from 'highlight.js/lib/languages/ada'; // import angelscript from 'highlight.js/lib/languages/angelscript'; // import apache from 'highlight.js/lib/languages/apache'; // import applescript from 'highlight.js/lib/languages/applescript'; // import arcade from 'highlight.js/lib/languages/arcade'; import cpp from 'highlight.js/lib/languages/cpp'; // import arduino from 'highlight.js/lib/languages/arduino'; // import armasm from 'highlight.js/lib/languages/armasm'; import xml from 'highlight.js/lib/languages/xml'; // import asciidoc from 'highlight.js/lib/languages/asciidoc'; // import aspectj from 'highlight.js/lib/languages/aspectj'; // import autohotkey from 'highlight.js/lib/languages/autohotkey'; // import autoit from 'highlight.js/lib/languages/autoit'; // import avrasm from 'highlight.js/lib/languages/avrasm'; import awk from 'highlight.js/lib/languages/awk'; // import axapta from 'highlight.js/lib/languages/axapta'; import bash from 'highlight.js/lib/languages/bash'; // import basic from 'highlight.js/lib/languages/basic'; // import bnf from 'highlight.js/lib/languages/bnf'; // import brainfuck from 'highlight.js/lib/languages/brainfuck'; import c from 'highlight.js/lib/languages/c'; // import cal from 'highlight.js/lib/languages/cal'; // import capnproto from 'highlight.js/lib/languages/capnproto'; // import ceylon from 'highlight.js/lib/languages/ceylon'; // import clean from 'highlight.js/lib/languages/clean'; import clojure from 'highlight.js/lib/languages/clojure'; // import clojureRepl from 'highlight.js/lib/languages/clojure-repl'; // import cmake from 'highlight.js/lib/languages/cmake'; // import coffeescript from 'highlight.js/lib/languages/coffeescript'; // import coq from 'highlight.js/lib/languages/coq'; // import cos from 'highlight.js/lib/languages/cos'; // import crmsh from 'highlight.js/lib/languages/crmsh'; import crystal from 'highlight.js/lib/languages/crystal'; import csharp from 'highlight.js/lib/languages/csharp'; import csp from 'highlight.js/lib/languages/csp'; import css from 'highlight.js/lib/languages/css'; // import d from 'highlight.js/lib/languages/d'; import markdown from 'highlight.js/lib/languages/markdown'; import dart from 'highlight.js/lib/languages/dart'; // import delphi from 'highlight.js/lib/languages/delphi'; import diff from 'highlight.js/lib/languages/diff'; // import django from 'highlight.js/lib/languages/django'; // import dns from 'highlight.js/lib/languages/dns'; import dockerfile from 'highlight.js/lib/languages/dockerfile'; // import dos from 'highlight.js/lib/languages/dos'; // import dsconfig from 'highlight.js/lib/languages/dsconfig'; // import dts from 'highlight.js/lib/languages/dts'; // import dust from 'highlight.js/lib/languages/dust'; // import ebnf from 'highlight.js/lib/languages/ebnf'; import elixir from 'highlight.js/lib/languages/elixir'; import elm from 'highlight.js/lib/languages/elm'; import ruby from 'highlight.js/lib/languages/ruby'; // import erb from 'highlight.js/lib/languages/erb'; // import erlangRepl from 'highlight.js/lib/languages/erlang-repl'; import erlang from 'highlight.js/lib/languages/erlang'; // import excel from 'highlight.js/lib/languages/excel'; // import fix from 'highlight.js/lib/languages/fix'; // import flix from 'highlight.js/lib/languages/flix'; // import fortran from 'highlight.js/lib/languages/fortran'; import fsharp from 'highlight.js/lib/languages/fsharp'; // import gams from 'highlight.js/lib/languages/gams'; // import gauss from 'highlight.js/lib/languages/gauss'; // import gcode from 'highlight.js/lib/languages/gcode'; // import gherkin from 'highlight.js/lib/languages/gherkin'; // import glsl from 'highlight.js/lib/languages/glsl'; // import gml from 'highlight.js/lib/languages/gml'; import go from 'highlight.js/lib/languages/go'; // import golo from 'highlight.js/lib/languages/golo'; import gradle from 'highlight.js/lib/languages/gradle'; import groovy from 'highlight.js/lib/languages/groovy'; // import haml from 'highlight.js/lib/languages/haml'; import handlebars from 'highlight.js/lib/languages/handlebars'; import haskell from 'highlight.js/lib/languages/haskell'; // import haxe from 'highlight.js/lib/languages/haxe'; // import hsp from 'highlight.js/lib/languages/hsp'; // import htmlbars from 'highlight.js/lib/languages/htmlbars'; // import http from 'highlight.js/lib/languages/http'; // import hy from 'highlight.js/lib/languages/hy'; // import inform7 from 'highlight.js/lib/languages/inform7'; import ini from 'highlight.js/lib/languages/ini'; // import irpf90 from 'highlight.js/lib/languages/irpf90'; // import isbl from 'highlight.js/lib/languages/isbl'; import java from 'highlight.js/lib/languages/java'; import javascript from 'highlight.js/lib/languages/javascript'; // import jbossCli from 'highlight.js/lib/languages/jboss-cli'; import json from 'highlight.js/lib/languages/json'; // import julia from 'highlight.js/lib/languages/julia'; // import juliaRepl from 'highlight.js/lib/languages/julia-repl'; import kotlin from 'highlight.js/lib/languages/kotlin'; // import lasso from 'highlight.js/lib/languages/lasso'; // import latex from 'highlight.js/lib/languages/latex'; // import ldif from 'highlight.js/lib/languages/ldif'; // import leaf from 'highlight.js/lib/languages/leaf'; import less from 'highlight.js/lib/languages/less'; import lisp from 'highlight.js/lib/languages/lisp'; // import livecodeserver from 'highlight.js/lib/languages/livecodeserver'; // import livescript from 'highlight.js/lib/languages/livescript'; // import llvm from 'highlight.js/lib/languages/llvm'; // import lsl from 'highlight.js/lib/languages/lsl'; import lua from 'highlight.js/lib/languages/lua'; import makefile from 'highlight.js/lib/languages/makefile'; // import mathematica from 'highlight.js/lib/languages/mathematica'; // import matlab from 'highlight.js/lib/languages/matlab'; // import maxima from 'highlight.js/lib/languages/maxima'; // import mel from 'highlight.js/lib/languages/mel'; // import mercury from 'highlight.js/lib/languages/mercury'; // import mipsasm from 'highlight.js/lib/languages/mipsasm'; // import mizar from 'highlight.js/lib/languages/mizar'; import perl from 'highlight.js/lib/languages/perl'; // import mojolicious from 'highlight.js/lib/languages/mojolicious'; // import monkey from 'highlight.js/lib/languages/monkey'; // import moonscript from 'highlight.js/lib/languages/moonscript'; // import n1ql from 'highlight.js/lib/languages/n1ql'; import nginx from 'highlight.js/lib/languages/nginx'; // import nim from 'highlight.js/lib/languages/nim'; // import nix from 'highlight.js/lib/languages/nix'; // import nsis from 'highlight.js/lib/languages/nsis'; import objectivec from 'highlight.js/lib/languages/objectivec'; // import ocaml from 'highlight.js/lib/languages/ocaml'; // import openscad from 'highlight.js/lib/languages/openscad'; // import oxygene from 'highlight.js/lib/languages/oxygene'; // import parser3 from 'highlight.js/lib/languages/parser3'; // import pf from 'highlight.js/lib/languages/pf'; import pgsql from 'highlight.js/lib/languages/pgsql'; import php from 'highlight.js/lib/languages/php'; // import phpTemplate from 'highlight.js/lib/languages/php-template'; import plaintext from 'highlight.js/lib/languages/plaintext'; // import pony from 'highlight.js/lib/languages/pony'; import powershell from 'highlight.js/lib/languages/powershell'; // import processing from 'highlight.js/lib/languages/processing'; // import profile from 'highlight.js/lib/languages/profile'; // import prolog from 'highlight.js/lib/languages/prolog'; import properties from 'highlight.js/lib/languages/properties'; import protobuf from 'highlight.js/lib/languages/protobuf'; // import puppet from 'highlight.js/lib/languages/puppet'; // import purebasic from 'highlight.js/lib/languages/purebasic'; import python from 'highlight.js/lib/languages/python'; // import pythonRepl from 'highlight.js/lib/languages/python-repl'; // import q from 'highlight.js/lib/languages/q'; // import qml from 'highlight.js/lib/languages/qml'; // import r from 'highlight.js/lib/languages/r'; // import reasonml from 'highlight.js/lib/languages/reasonml'; // import rib from 'highlight.js/lib/languages/rib'; // import roboconf from 'highlight.js/lib/languages/roboconf'; // import routeros from 'highlight.js/lib/languages/routeros'; // import rsl from 'highlight.js/lib/languages/rsl'; // import ruleslanguage from 'highlight.js/lib/languages/ruleslanguage'; import rust from 'highlight.js/lib/languages/rust'; // import sas from 'highlight.js/lib/languages/sas'; import scala from 'highlight.js/lib/languages/scala'; // import scheme from 'highlight.js/lib/languages/scheme'; // import scilab from 'highlight.js/lib/languages/scilab'; import scss from 'highlight.js/lib/languages/scss'; import shell from 'highlight.js/lib/languages/shell'; // import smali from 'highlight.js/lib/languages/smali'; // import smalltalk from 'highlight.js/lib/languages/smalltalk'; // import sml from 'highlight.js/lib/languages/sml'; // import sqf from 'highlight.js/lib/languages/sqf'; import sql from 'highlight.js/lib/languages/sql'; // import stan from 'highlight.js/lib/languages/stan'; // import stata from 'highlight.js/lib/languages/stata'; // import step21 from 'highlight.js/lib/languages/step21'; // import stylus from 'highlight.js/lib/languages/stylus'; // import subunit from 'highlight.js/lib/languages/subunit'; import swift from 'highlight.js/lib/languages/swift'; // import taggerscript from 'highlight.js/lib/languages/taggerscript'; import yaml from 'highlight.js/lib/languages/yaml'; // import tap from 'highlight.js/lib/languages/tap'; // import tcl from 'highlight.js/lib/languages/tcl'; // import thrift from 'highlight.js/lib/languages/thrift'; // import tp from 'highlight.js/lib/languages/tp'; // import twig from 'highlight.js/lib/languages/twig'; import typescript from 'highlight.js/lib/languages/typescript'; // import vala from 'highlight.js/lib/languages/vala'; // import vbnet from 'highlight.js/lib/languages/vbnet'; // import vbscript from 'highlight.js/lib/languages/vbscript'; // import vbscriptHtml from 'highlight.js/lib/languages/vbscript-html'; // import verilog from 'highlight.js/lib/languages/verilog'; // import vhdl from 'highlight.js/lib/languages/vhdl'; // import vim from 'highlight.js/lib/languages/vim'; // import x86asm from 'highlight.js/lib/languages/x86asm'; // import xl from 'highlight.js/lib/languages/xl'; // import xquery from 'highlight.js/lib/languages/xquery'; // import zephir from 'highlight.js/lib/languages/zephir'; // Convert to registerLanguage // ^hljs\.registerLanguage\('(.+)', require\('\./languages\/(.+)'\)\);$ // highlightJS.registerLanguage('$1', $1); // Separately require languages // highlightJS.registerLanguage('1c', _1c); // highlightJS.registerLanguage('abnf', abnf); // highlightJS.registerLanguage('accesslog', accesslog); // highlightJS.registerLanguage('actionscript', actionscript); // highlightJS.registerLanguage('ada', ada); // highlightJS.registerLanguage('angelscript', angelscript); // highlightJS.registerLanguage('apache', apache); // highlightJS.registerLanguage('applescript', applescript); // highlightJS.registerLanguage('arcade', arcade); highlightJS.registerLanguage('cpp', cpp); // highlightJS.registerLanguage('arduino', arduino); // highlightJS.registerLanguage('armasm', armasm); highlightJS.registerLanguage('xml', xml); // highlightJS.registerLanguage('asciidoc', asciidoc); // highlightJS.registerLanguage('aspectj', aspectj); // highlightJS.registerLanguage('autohotkey', autohotkey); // highlightJS.registerLanguage('autoit', autoit); // highlightJS.registerLanguage('avrasm', avrasm); highlightJS.registerLanguage('awk', awk); // highlightJS.registerLanguage('axapta', axapta); highlightJS.registerLanguage('bash', bash); // highlightJS.registerLanguage('basic', basic); // highlightJS.registerLanguage('bnf', bnf); // highlightJS.registerLanguage('brainfuck', brainfuck); highlightJS.registerLanguage('c', c); // highlightJS.registerLanguage('cal', cal); // highlightJS.registerLanguage('capnproto', capnproto); // highlightJS.registerLanguage('ceylon', ceylon); // highlightJS.registerLanguage('clean', clean); highlightJS.registerLanguage('clojure', clojure); // highlightJS.registerLanguage('clojure-repl', clojureRepl); // highlightJS.registerLanguage('cmake', cmake); // highlightJS.registerLanguage('coffeescript', coffeescript); // highlightJS.registerLanguage('coq', coq); // highlightJS.registerLanguage('cos', cos); // highlightJS.registerLanguage('crmsh', crmsh); highlightJS.registerLanguage('crystal', crystal); highlightJS.registerLanguage('csharp', csharp); highlightJS.registerLanguage('csp', csp); highlightJS.registerLanguage('css', css); // highlightJS.registerLanguage('d', d); highlightJS.registerLanguage('markdown', markdown); highlightJS.registerLanguage('dart', dart); // highlightJS.registerLanguage('delphi', delphi); highlightJS.registerLanguage('diff', diff); // highlightJS.registerLanguage('django', django); // highlightJS.registerLanguage('dns', dns); highlightJS.registerLanguage('dockerfile', dockerfile); // highlightJS.registerLanguage('dos', dos); // highlightJS.registerLanguage('dsconfig', dsconfig); // highlightJS.registerLanguage('dts', dts); // highlightJS.registerLanguage('dust', dust); // highlightJS.registerLanguage('ebnf', ebnf); highlightJS.registerLanguage('elixir', elixir); highlightJS.registerLanguage('elm', elm); highlightJS.registerLanguage('ruby', ruby); // highlightJS.registerLanguage('erb', erb); // highlightJS.registerLanguage('erlang-repl', erlangRepl); highlightJS.registerLanguage('erlang', erlang); // highlightJS.registerLanguage('excel', excel); // highlightJS.registerLanguage('fix', fix); // highlightJS.registerLanguage('flix', flix); // highlightJS.registerLanguage('fortran', fortran); highlightJS.registerLanguage('fsharp', fsharp); // highlightJS.registerLanguage('gams', gams); // highlightJS.registerLanguage('gauss', gauss); // highlightJS.registerLanguage('gcode', gcode); // highlightJS.registerLanguage('gherkin', gherkin); // highlightJS.registerLanguage('glsl', glsl); // highlightJS.registerLanguage('gml', gml); highlightJS.registerLanguage('go', go); // highlightJS.registerLanguage('golo', golo); highlightJS.registerLanguage('gradle', gradle); highlightJS.registerLanguage('groovy', groovy); // highlightJS.registerLanguage('haml', haml); highlightJS.registerLanguage('handlebars', handlebars); highlightJS.registerLanguage('haskell', haskell); // highlightJS.registerLanguage('haxe', haxe); // highlightJS.registerLanguage('hsp', hsp); // highlightJS.registerLanguage('htmlbars', htmlbars); // highlightJS.registerLanguage('http', http); // highlightJS.registerLanguage('hy', hy); // highlightJS.registerLanguage('inform7', inform7); highlightJS.registerLanguage('ini', ini); // highlightJS.registerLanguage('irpf90', irpf90); // highlightJS.registerLanguage('isbl', isbl); highlightJS.registerLanguage('java', java); highlightJS.registerLanguage('javascript', javascript); // highlightJS.registerLanguage('jboss-cli', jbossCli); highlightJS.registerLanguage('json', json); // highlightJS.registerLanguage('julia', julia); // highlightJS.registerLanguage('julia-repl', juliaRepl); highlightJS.registerLanguage('kotlin', kotlin); // highlightJS.registerLanguage('lasso', lasso); // highlightJS.registerLanguage('latex', latex); // highlightJS.registerLanguage('ldif', ldif); // highlightJS.registerLanguage('leaf', leaf); highlightJS.registerLanguage('less', less); highlightJS.registerLanguage('lisp', lisp); // highlightJS.registerLanguage('livecodeserver', livecodeserver); // highlightJS.registerLanguage('livescript', livescript); // highlightJS.registerLanguage('llvm', llvm); // highlightJS.registerLanguage('lsl', lsl); highlightJS.registerLanguage('lua', lua); highlightJS.registerLanguage('makefile', makefile); // highlightJS.registerLanguage('mathematica', mathematica); // highlightJS.registerLanguage('matlab', matlab); // highlightJS.registerLanguage('maxima', maxima); // highlightJS.registerLanguage('mel', mel); // highlightJS.registerLanguage('mercury', mercury); // highlightJS.registerLanguage('mipsasm', mipsasm); // highlightJS.registerLanguage('mizar', mizar); highlightJS.registerLanguage('perl', perl); // highlightJS.registerLanguage('mojolicious', mojolicious); // highlightJS.registerLanguage('monkey', monkey); // highlightJS.registerLanguage('moonscript', moonscript); // highlightJS.registerLanguage('n1ql', n1ql); highlightJS.registerLanguage('nginx', nginx); // highlightJS.registerLanguage('nim', nim); // highlightJS.registerLanguage('nix', nix); // highlightJS.registerLanguage('nsis', nsis); highlightJS.registerLanguage('objectivec', objectivec); // highlightJS.registerLanguage('ocaml', ocaml); // highlightJS.registerLanguage('openscad', openscad); // highlightJS.registerLanguage('oxygene', oxygene); // highlightJS.registerLanguage('parser3', parser3); // highlightJS.registerLanguage('pf', pf); highlightJS.registerLanguage('pgsql', pgsql); highlightJS.registerLanguage('php', php); // highlightJS.registerLanguage('php-template', phpTemplate); highlightJS.registerLanguage('plaintext', plaintext); // highlightJS.registerLanguage('pony', pony); highlightJS.registerLanguage('powershell', powershell); // highlightJS.registerLanguage('processing', processing); // highlightJS.registerLanguage('profile', profile); // highlightJS.registerLanguage('prolog', prolog); highlightJS.registerLanguage('properties', properties); highlightJS.registerLanguage('protobuf', protobuf); // highlightJS.registerLanguage('puppet', puppet); // highlightJS.registerLanguage('purebasic', purebasic); highlightJS.registerLanguage('python', python); // highlightJS.registerLanguage('python-repl', pythonRepl); // highlightJS.registerLanguage('q', q); // highlightJS.registerLanguage('qml', qml); // highlightJS.registerLanguage('r', r); // highlightJS.registerLanguage('reasonml', reasonml); // highlightJS.registerLanguage('rib', rib); // highlightJS.registerLanguage('roboconf', roboconf); // highlightJS.registerLanguage('routeros', routeros); // highlightJS.registerLanguage('rsl', rsl); // highlightJS.registerLanguage('ruleslanguage', ruleslanguage); highlightJS.registerLanguage('rust', rust); // highlightJS.registerLanguage('sas', sas); highlightJS.registerLanguage('scala', scala); // highlightJS.registerLanguage('scheme', scheme); // highlightJS.registerLanguage('scilab', scilab); highlightJS.registerLanguage('scss', scss); highlightJS.registerLanguage('shell', shell); // highlightJS.registerLanguage('smali', smali); // highlightJS.registerLanguage('smalltalk', smalltalk); // highlightJS.registerLanguage('sml', sml); // highlightJS.registerLanguage('sqf', sqf); highlightJS.registerLanguage('sql', sql); // highlightJS.registerLanguage('stan', stan); // highlightJS.registerLanguage('stata', stata); // highlightJS.registerLanguage('step21', step21); // highlightJS.registerLanguage('stylus', stylus); // highlightJS.registerLanguage('subunit', subunit); highlightJS.registerLanguage('swift', swift); // highlightJS.registerLanguage('taggerscript', taggerscript); highlightJS.registerLanguage('yaml', yaml); // highlightJS.registerLanguage('tap', tap); // highlightJS.registerLanguage('tcl', tcl); // highlightJS.registerLanguage('thrift', thrift); // highlightJS.registerLanguage('tp', tp); // highlightJS.registerLanguage('twig', twig); highlightJS.registerLanguage('typescript', typescript); // highlightJS.registerLanguage('vala', vala); // highlightJS.registerLanguage('vbnet', vbnet); // highlightJS.registerLanguage('vbscript', vbscript); // highlightJS.registerLanguage('vbscript-html', vbscriptHtml); // highlightJS.registerLanguage('verilog', verilog); // highlightJS.registerLanguage('vhdl', vhdl); // highlightJS.registerLanguage('vim', vim); // highlightJS.registerLanguage('x86asm', x86asm); // highlightJS.registerLanguage('xl', xl); // highlightJS.registerLanguage('xquery', xquery); // highlightJS.registerLanguage('zephir', zephir); export const hljs = highlightJS;
the_stack
import CustomError from "./Error"; import utils from "./utils"; import Internal from "./Internal"; import {Item, ItemObjectFromSchemaSettings} from "./Item"; import {Model, ModelIndexes} from "./Model"; import * as DynamoDB from "@aws-sdk/client-dynamodb"; import {ModelType, ObjectType} from "./General"; import {InternalPropertiesClass} from "./InternalPropertiesClass"; const {internalProperties} = Internal.General; type DynamoDBAttributeType = keyof DynamoDB.AttributeValue; // TODO: the interfaces below are so similar, we should consider combining them into one. We also do a lot of `DynamoDBTypeResult | DynamoDBSetTypeResult` in the code base. export interface DynamoDBSetTypeResult { name: string; dynamicName?: (() => string); dynamodbType: DynamoDBAttributeType; isOfType: (value: ValueType, type?: "toDynamo" | "fromDynamo", settings?: Partial<ItemObjectFromSchemaSettings>) => boolean; isSet: true; customType?: any; typeSettings?: AttributeDefinitionTypeSettings; toDynamo: (val: GeneralValueType[] | Set<GeneralValueType>) => Set<GeneralValueType>; } export interface DynamoDBTypeResult { name: string; dynamicName?: (() => string); dynamodbType: DynamoDBAttributeType | DynamoDBAttributeType[]; isOfType: (value: ValueType) => {value: ValueType; type: string}; isSet: false; customType?: any; typeSettings?: AttributeDefinitionTypeSettings; nestedType: boolean; set?: DynamoDBSetTypeResult; } interface DynamoDBTypeCreationObject { name: string; dynamicName?: ((typeSettings?: AttributeDefinitionTypeSettings) => string); dynamodbType?: DynamoDBAttributeType | DynamoDBAttributeType[] | DynamoDBType | ((typeSettings: AttributeDefinitionTypeSettings) => string | string[]); set?: boolean | ((typeSettings?: AttributeDefinitionTypeSettings) => boolean); jsType?: any; nestedType?: boolean; customType?: {functions: (typeSettings: AttributeDefinitionTypeSettings) => {toDynamo?: (val: ValueType) => ValueType; fromDynamo?: (val: ValueType) => ValueType; isOfType: (val: ValueType, type: "toDynamo" | "fromDynamo") => boolean}}; } class DynamoDBType implements DynamoDBTypeCreationObject { // TODO: since the code below will always be the exact same as DynamoDBTypeCreationObject we should see if there is a way to make it more DRY and not repeat it name: string; dynamicName?: ((typeSettings?: AttributeDefinitionTypeSettings) => string); dynamodbType?: DynamoDBAttributeType | DynamoDBAttributeType[] | DynamoDBType | ((typeSettings: AttributeDefinitionTypeSettings) => DynamoDBAttributeType | DynamoDBAttributeType[]); set?: boolean | ((typeSettings?: AttributeDefinitionTypeSettings) => boolean); jsType?: any; nestedType?: boolean; customType?: {functions: (typeSettings: AttributeDefinitionTypeSettings) => {toDynamo?: (val: ValueType) => ValueType; fromDynamo?: (val: ValueType) => ValueType; isOfType: (val: ValueType, type: "toDynamo" | "fromDynamo") => boolean}}; constructor (obj: DynamoDBTypeCreationObject) { Object.keys(obj).forEach((key) => { this[key] = obj[key]; }); } result (typeSettings?: AttributeDefinitionTypeSettings): DynamoDBTypeResult { // Can't use variable below to check type, see TypeScript issue link below for more information // https://github.com/microsoft/TypeScript/issues/37855 // const isSubType = this.dynamodbType instanceof DynamoDBType; // Represents underlying DynamoDB type for custom types const type = this.dynamodbType instanceof DynamoDBType ? this.dynamodbType : this; const dynamodbType: DynamoDBAttributeType | DynamoDBAttributeType[] = ((): DynamoDBAttributeType | DynamoDBAttributeType[] => { if (this.dynamodbType instanceof DynamoDBType) { return this.dynamodbType.dynamodbType as DynamoDBAttributeType; } else if (typeof this.dynamodbType === "function") { return this.dynamodbType(typeSettings); } else { return this.dynamodbType; } })(); const result: DynamoDBTypeResult = { "name": this.name, dynamodbType, "nestedType": this.nestedType, "isOfType": this.jsType.func ? (val) => this.jsType.func(val, typeSettings) : (val): {value: ValueType; type: string} => { return [{"value": this.jsType, "type": "main"}, {"value": this.dynamodbType instanceof DynamoDBType ? type.jsType : null, "type": "underlying"}].filter((a) => Boolean(a.value)).find((jsType) => typeof jsType.value === "string" ? typeof val === jsType.value : val instanceof jsType.value); }, "isSet": false, typeSettings }; if (this.dynamicName) { result.dynamicName = (): string => this.dynamicName(typeSettings); } if (this.customType) { const functions = this.customType.functions(typeSettings); result.customType = { ...this.customType, functions }; } const isSetAllowed = typeof type.set === "function" ? type.set(typeSettings) : type.set; if (isSetAllowed) { result.set = { "name": `${this.name} Set`, "isSet": true, "dynamodbType": `${dynamodbType}S` as DynamoDBAttributeType | DynamoDBAttributeType, "isOfType": (val: ValueType, type: "toDynamo" | "fromDynamo", settings: Partial<ItemObjectFromSchemaSettings> = {}): boolean => { if (type === "toDynamo") { return !settings.saveUnknown && Array.isArray(val) && val.every((subValue) => result.isOfType(subValue)) || val instanceof Set && [...val].every((subValue) => result.isOfType(subValue)); } else { return val instanceof Set; } }, "toDynamo": (val: GeneralValueType[] | Set<GeneralValueType>): Set<GeneralValueType> => Array.isArray(val) ? new Set(val) : val, typeSettings }; if (this.dynamicName) { result.set.dynamicName = (): string => `${this.dynamicName(typeSettings)} Set`; } if (this.customType) { result.set.customType = { "functions": { "toDynamo": (val: GeneralValueType[]): ValueType[] => val.map(result.customType.functions.toDynamo), "fromDynamo": (val: Iterator<GeneralValueType>): Set<GeneralValueType> => new Set([...val as any].map(result.customType.functions.fromDynamo)), "isOfType": (val: ValueType, type: "toDynamo" | "fromDynamo"): boolean => { if (type === "toDynamo") { return (val instanceof Set || Array.isArray(val) && new Set(val as any).size === val.length) && [...val].every((item) => result.customType.functions.isOfType(item, type)); } else { return val instanceof Set; } } } }; } } return result; } } const attributeTypesMain: DynamoDBType[] = ((): DynamoDBType[] => { const numberType = new DynamoDBType({"name": "Number", "dynamodbType": "N", "set": true, "jsType": "number"}); const stringType = new DynamoDBType({"name": "String", "dynamodbType": "S", "set": true, "jsType": "string"}); const booleanType = new DynamoDBType({"name": "Boolean", "dynamodbType": "BOOL", "jsType": "boolean"}); return [ new DynamoDBType({"name": "Any", "jsType": {"func": (): boolean => true}}), new DynamoDBType({"name": "Null", "dynamodbType": "NULL", "set": false, "jsType": {"func": (val): boolean => val === null}}), new DynamoDBType({"name": "Buffer", "dynamodbType": "B", "set": true, "jsType": Buffer}), booleanType, new DynamoDBType({"name": "Array", "dynamodbType": "L", "jsType": {"func": Array.isArray}, "nestedType": true}), new DynamoDBType({"name": "Object", "dynamodbType": "M", "jsType": {"func": (val): boolean => Boolean(val) && val.constructor === Object}, "nestedType": true}), numberType, stringType, new DynamoDBType({"name": "Date", "dynamodbType": numberType, "customType": { "functions": (typeSettings: AttributeDefinitionTypeSettings): {toDynamo: (val: Date) => number; fromDynamo: (val: number) => Date; isOfType: (val: Date, type: "toDynamo" | "fromDynamo") => boolean} => ({ "toDynamo": (val: Date): number => { if (typeSettings.storage === "seconds") { return Math.round(val.getTime() / 1000); } else { return val.getTime(); } }, "fromDynamo": (val: number): Date => { if (typeSettings.storage === "seconds") { return new Date(val * 1000); } else { return new Date(val); } }, "isOfType": (val: Date, type: "toDynamo" | "fromDynamo"): boolean => { return type === "toDynamo" ? val instanceof Date : typeof val === "number"; } }) }, "jsType": Date}), new DynamoDBType({"name": "Combine", "dynamodbType": stringType, "set": false, "jsType": String}), new DynamoDBType({"name": "Constant", "dynamicName": (typeSettings?: AttributeDefinitionTypeSettings): string => { return `constant ${typeof typeSettings.value} (${typeSettings.value})`; }, "customType": { "functions": (typeSettings: AttributeDefinitionTypeSettings): {isOfType: (val: string | boolean | number, type: "toDynamo" | "fromDynamo") => boolean} => ({ "isOfType": (val: string | boolean | number): boolean => typeSettings.value === val }) }, "jsType": {"func": (val, typeSettings): boolean => val === typeSettings.value}, "dynamodbType": (typeSettings?: AttributeDefinitionTypeSettings): string | string[] => { switch (typeof typeSettings.value) { case "string": return stringType.dynamodbType as any; case "boolean": return booleanType.dynamodbType as any; case "number": return numberType.dynamodbType as any; } }}), new DynamoDBType({"name": "Model", "dynamicName": (typeSettings?: AttributeDefinitionTypeSettings): string => typeSettings.model.Model.name, "dynamodbType": (typeSettings?: AttributeDefinitionTypeSettings): string | string[] => { const model = typeSettings.model.Model; const hashKey = model.getInternalProperties(internalProperties).getHashKey(); const rangeKey = model.getInternalProperties(internalProperties).getRangeKey(); return rangeKey ? "M" : model.getInternalProperties(internalProperties).schemas[0].getAttributeType(hashKey); }, "set": (typeSettings?: AttributeDefinitionTypeSettings): boolean => { return !typeSettings.model.Model.getInternalProperties(internalProperties).getRangeKey(); }, "jsType": {"func": (val): boolean => val.prototype instanceof Item}, "customType": { "functions": (typeSettings?: AttributeDefinitionTypeSettings): {toDynamo: (val: any) => any; fromDynamo: (val: any) => any; isOfType: (val: any, type: "toDynamo" | "fromDynamo") => boolean} => ({ "toDynamo": (val: any): any => { const model = typeSettings.model.Model; const hashKey = model.getInternalProperties(internalProperties).getHashKey(); const rangeKey = model.getInternalProperties(internalProperties).getRangeKey(); if (rangeKey) { return { [hashKey]: val[hashKey], [rangeKey]: val[rangeKey] }; } else { return val[hashKey] ?? val; } }, "fromDynamo": (val: any): any => val, "isOfType": (val: any, type: "toDynamo" | "fromDynamo"): boolean => { const model = typeSettings.model.Model; const hashKey = model.getInternalProperties(internalProperties).getHashKey(); const rangeKey = model.getInternalProperties(internalProperties).getRangeKey(); if (rangeKey) { return typeof val === "object" && val[hashKey] && val[rangeKey]; } else { return utils.dynamoose.getValueTypeCheckResult(model.getInternalProperties(internalProperties).schemas[0], val[hashKey] ?? val, hashKey, {type}, {}).isValidType; } } }) }}) ]; })(); const attributeTypes: (DynamoDBTypeResult | DynamoDBSetTypeResult)[] = utils.array_flatten(attributeTypesMain.filter((checkType) => !checkType.customType).map((checkType) => checkType.result()).map((a) => [a, a.set])).filter((a) => Boolean(a)); type GeneralValueType = string | boolean | number | Buffer | Date; export type ValueType = GeneralValueType | {[key: string]: ValueType} | ValueType[]; type AttributeType = string | StringConstructor | BooleanConstructor | NumberConstructor | typeof Buffer | DateConstructor | ObjectConstructor | ArrayConstructor | SetConstructor | symbol | Schema | ModelType<Item>; export interface TimestampObject { createdAt?: string | string[]; updatedAt?: string | string[]; } interface SchemaSettings { timestamps?: boolean | TimestampObject; saveUnknown?: boolean | string[]; set?: (value: ObjectType) => ObjectType; get?: (value: ObjectType) => ObjectType; validate?: (value: ObjectType) => boolean; } export enum IndexType { /** * A global secondary index (GSI) is a secondary index in a DynamoDB table that is not local to a single partition key value. */ global = "global", /** * A local secondary index (LSI) is a secondary index in a DynamoDB table that is local to a single partition key value. */ local = "local" } interface IndexDefinition { /** * The name of the index. * @default `${attribute}${type == "global" ? "GlobalIndex" : "LocalIndex"}` */ name?: string; /** * If the index should be a global index or local index. Attribute will be the hashKey for the index. * @default "global" */ type?: IndexType; /** * The range key attribute name for a global secondary index. */ rangeKey?: string; /** * Sets the attributes to be projected for the index. `true` projects all attributes, `false` projects only the key attributes, and an array of strings projects the attributes listed. * @default true */ project?: boolean | string[]; /** * Sets the throughput for the global secondary index. * @default undefined */ throughput?: "ON_DEMAND" | number | {read: number; write: number}; } interface AttributeDefinitionTypeSettings { storage?: "milliseconds" | "seconds"; model?: ModelType<Item>; attributes?: string[]; separator?: string; value?: string | boolean | number; } interface AttributeDefinition { /** * The type attribute can either be a type (ex. `Object`, `Number`, etc.) or an object that has additional information for the type. In the event you set it as an object you must pass in a `value` for the type, and can optionally pass in a `settings` object. * * ```js * { * "address": { * "type": Object * } * } * ``` * * ```js * { * "deletedAt": { * "type": { * "value": Date, * "settings": { * "storage": "seconds" // Default: milliseconds (as shown above) * } * } * } * } * ``` * * ```js * { * "data": { * "type": { * "value": "Constant", * "settings": { * "value": "Hello World" // Any `data` attribute must equal `Hello World` now. * } * } * } * } * ``` */ type: AttributeType | AttributeType[] | {value: DateConstructor; settings?: AttributeDefinitionTypeSettings} | {value: AttributeType | AttributeType[]}; /** * This property is only used for the `Object` or `Array` attribute types. It is used to define the schema for the underlying nested type. For `Array` attribute types, this value must be an `Array` with one element defining the schema. This element for `Array` attribute types can either be another raw Dynamoose type (ex. `String`), or an object defining a more detailed schema for the `Array` elements. For `Object` attribute types this value must be an object defining the schema. Some examples of this property in action can be found below. * * ```js * { * "address": { * "type": Object, * "schema": { * "zip": Number, * "country": { * "type": String, * "required": true * } * } * } * } * ``` * * ```js * { * "friends": { * "type": Array, * "schema": [String] * } * } * ``` * * ```js * { * "friends": { * "type": Array, * "schema": [{ * "type": Object, * "schema": { * "zip": Number, * "country": { * "type": String, * "required": true * } * } * }] * } * } * ``` * * You can also define an array attribute that accepts more than one data type. The following example will allow the `friends` attribute to be an array of strings, or an array of numbers, but the elements in the array must all be strings or must all be numbers. * * ```js * { * "friends": { * "type": Array, * "schema": [ * { * "type": Array, * "schema": [String] * }, * { * "type": Array, * "schema": [Number] * } * ] * } * } * ``` */ schema?: AttributeType | AttributeType[] | AttributeDefinition | AttributeDefinition[] | SchemaDefinition | SchemaDefinition[]; /** * You can set a default value for an attribute that will be applied upon save if the given attribute value is `null` or `undefined`. The value for the default property can either be a value or a function that will be executed when needed that should return the default value. By default there is no default value for attributes. * * Default values will only be applied if the parent object exists. This means for values where you apply a `default` value to a nested attribute, it will only be applied if the parent object exists. If you do not want this behavior, consider setting a `default` value for the parent object to an empty object (`{}`) or an empty array (`[]`). * * ```js * { * "age": { * "type": Number, * "default": 5 * } * } * ``` * * ```js * { * "age": { * "type": Number, * "default": () => 5 * } * } * ``` * * You can also pass in async functions or a function that returns a promise to the default property and Dynamoose will take care of waiting for the promise to resolve before saving the object. * * ```js * { * "age": { * "type": Number, * "default": async () => { * const networkResponse = await axios("https://myurl.com/config.json").data; * return networkResponse.defaults.age; * } * } * } * ``` * * ```js * { * "age": { * "type": Number, * "default": () => { * return new Promise((resolve) => { * setTimeout(() => resolve(5), 1000); * }); * } * } * } * ``` */ default?: ValueType | (() => ValueType); /** * You can set this property to always use the `default` value, even if a value is already set. This can be used for data that will be used as sort or secondary indexes. The default for this property is false. * * ```js * { * "age": { * "type": Number, * "default": 5, * "forceDefault": true * } * } * ``` */ forceDefault?: boolean; /** * You can set a validation on an attribute to ensure the value passes a given validation before saving the item. In the event you set this to be a function or async function, Dynamoose will pass in the value for you to validate as the parameter to your function. Validation will only be run if the item exists in the item. If you'd like to force validation to be run every time (even if the attribute doesn't exist in the item) you can enable `required`. * * ```js * { * "age": { * "type": Number, * "validate": 5 // Any object that is saved must have the `age` property === to 5 * } * } * ``` * * ```js * { * "id": { * "type": String, * "validate": /ID_.+/gu // Any object that is saved must have the `id` property start with `ID_` and have at least 1 character after it * } * } * ``` * * ```js * { * "age": { * "type": String, * "validate": (val) => val > 0 && val < 100 // Any object that is saved must have the `age` property be greater than 0 and less than 100 * } * } * ``` * * ```js * { * "email": { * "type": String, * "validate": async (val) => { * const networkRequest = await axios(`https://emailvalidator.com/${val}`); * return networkRequest.data.isValid; * } // Any object that is saved will call this function and run the network request with `val` equal to the value set for the `email` property, and only allow the item to be saved if the `isValid` property in the response is true * } * } * ``` */ validate?: ValueType | RegExp | ((value: ValueType) => boolean | Promise<boolean>); /** * You can set an attribute to be required when saving items to DynamoDB. By default this setting is `false`. * * In the event the parent object is undefined and `required` is set to `false` on that parent attribute, the required check will not be run on child attributes. * * ```js * { * "email": { * "type": String, * "required": true * } * } * ``` * * ```js * { * "data": { * "type": Object, * "schema": { * "name": { * "type": String, * "required": true // Required will only be checked if `data` exists and is not undefined * } * } * "required": false * } * } * ``` */ required?: boolean; /** * You can set an attribute to have an enum array, which means it must match one of the values specified in the enum array. By default this setting is undefined and not set to anything. * * This property is not a replacement for `required`. If the value is undefined or null, the enum will not be checked. If you want to require the property and also have an `enum` you must use both `enum` & `required`. * * ```js * { * "name": { * "type": String, * "enum": ["Tom", "Tim"] // `name` must always equal "Tom" or "Tim" * } * } * ``` */ enum?: ValueType[]; /** * You can use a get function on an attribute to be run whenever retrieving a item from DynamoDB. This function will only be run if the item exists in the item. Dynamoose will pass the DynamoDB value into this function and you must return the new value that you want Dynamoose to return to the application. * * ```js * { * "id": { * "type": String, * "get": (value) => `applicationid-${value}` // This will prepend `applicationid-` to all values for this attribute when returning from the database * } * } * ``` */ get?: (value: ValueType) => ValueType; /** * You can use a set function on an attribute to be run whenever saving a item to DynamoDB. It will also be used when retrieving an item based on this attribute (ie. `get`, `query`, `update`, etc). This function will only be run if the attribute exists in the item. Dynamoose will pass the value you provide into this function and you must return the new value that you want Dynamoose to save to DynamoDB. * * ```js * { * "name": { * "type": String, * "set": (value) => `${value.charAt(0).toUpperCase()}${value.slice(1)}` // Capitalize first letter of name when saving to database * } * } * ``` * * Unlike `get`, this method will additionally pass in the original value as the second parameter (if available). Internally Dynamoose uses the [`item.original()`](/guide/Item#itemoriginal) method to access the original value. This means that using [`Model.batchPut`](/guide/Model#modelbatchputitems-settings-callback), [`Model.update`](/guide/Model#modelupdatekey-updateobj-settings-callback) or any other item save method that does not have access to [`item.original()`](/guide/Item#itemoriginal) this second parameter will be `undefined`. * * ```js * { * "name": { * "type": String, * "set": (newValue, oldValue) => `${newValue.charAt(0).toUpperCase()}${newValue.slice(1)}-${oldValue.charAt(0).toUpperCase()}${oldValue.slice(1)}` // Prepend the newValue to the oldValue (split by a `-`) and capitalize first letter of each when saving to database * } * } * ``` */ set?: ((value: ValueType, oldValue?: ValueType) => ValueType | Promise<ValueType>); /** * Indexes on your DynamoDB tables must be defined in your Dynamoose schema. If you have the update option set to true on your model settings, and a Dynamoose schema index does not already exist on the DynamoDB table, it will be created on model initialization. Similarly, indexes on your DynamoDB table that do not exist in your Dynamoose schema will be deleted. * * If you pass in an array for the value of this setting it must be an array of index objects. By default no indexes are specified on the attribute. * * Your index object can contain the following properties: * * | Name | Type | Default | Notes | * |---|---|---|---| * | name | string | `${attribute}${type == "global" ? "GlobalIndex" : "LocalIndex"}` | The name of the index. | * | type | "global" \| "local" | "global" | If the index should be a global index or local index. Attribute will be the hashKey for the index. | * | rangeKey | string | undefined | The range key attribute name for a global secondary index. | * | project | boolean \| [string] | true | Sets the attributes to be projected for the index. `true` projects all attributes, `false` projects only the key attributes, and an array of strings projects the attributes listed. | * | throughput | number \| {read: number, write: number} | undefined | Sets the throughput for the global secondary index. | * * * If you set `index` to `true`, it will create an index with all of the default settings. * * ```js * { * "id": { * "hashKey": true, * "type": String, * }, * "email": { * "type": String, * "index": { * "name": "emailIndex", * "global": true * } // creates a global secondary index with the name `emailIndex` and hashKey `email` * } * } * ``` * * ```js * { * "id": { * "hashKey": true, * "type": String, * "index": { * "name": "emailIndex", * "rangeKey": "email", * "throughput": {"read": 5, "write": 10} * } // creates a local secondary index with the name `emailIndex`, hashKey `id`, rangeKey `email` * }, * "email": { * "type": String * } * } * ``` */ index?: boolean | IndexDefinition | IndexDefinition[]; /** * You can set this to true to overwrite what the `hashKey` for the Model will be. By default the `hashKey` will be the first key in the Schema object. * * `hashKey` is commonly called a `partition key` in the AWS documentation. * * ```js * { * "id": String, * "key": { * "type": String, * "hashKey": true * } * } * ``` */ hashKey?: boolean; /** * You can set this to true to overwrite what the `rangeKey` for the Model will be. By default the `rangeKey` won't exist. * * `rangeKey` is commonly called a `sort key` in the AWS documentation. * * ```js * { * "id": String, * "email": { * "type": String, * "rangeKey": true * } * } * ``` */ rangeKey?: boolean; /** * This property can be used to use a different attribute name in your internal application as opposed to DynamoDB. This is especially useful if you have a single table design with properties like (`pk` & `sk`) which don't have much human readable meaning. You can use this to map those attribute names to better human readable names that better represent the underlying data. You can also use it for aliases such as mapping `id` to `userID`. * * When retrieving data from DynamoDB, the attribute will be renamed to this property name, or the first element of the array if it is an array. If you want to change this behavior look at the [`defaultMap`](#defaultmap-string) property. * * When saving to DynamoDB, the attribute name will always be used. * * ```js * "pk": { * "type": String, * "map": "userId" * } * "sk": { * "type": String, * "map": "orderId" * } * ``` * * ```js * "id": { * "type": String, * "map": ["userID", "_id"] * } * ``` */ map?: string | string[]; /** * This property can be used to use a different attribute name in your internal application as opposed to DynamoDB. This is especially useful if you have a single table design with properties like (`pk` & `sk`) which don't have much human readable meaning. You can use this to map those attribute names to better human readable names that better represent the underlying data. You can also use it for aliases such as mapping `id` to `userID`. * * When retrieving data from DynamoDB, the attribute will be renamed to this property name, or the first element of the array if it is an array. If you want to change this behavior look at the `defaultMap` property. * * When saving to DynamoDB, the attribute name will always be used. * * ```js * "pk": { * "type": String, * "alias": "userId" * } * "sk": { * "type": String, * "alias": "orderId" * } * ``` * * ```js * "id": { * "type": String, * "alias": ["userID", "_id"] * } * ``` */ alias?: string | string[]; /** * This property can be used to use a different attribute name in your internal application as opposed to DynamoDB. This is especially useful if you have a single table design with properties like (`pk` & `sk`) which don't have much human readable meaning. You can use this to map those attribute names to better human readable names that better represent the underlying data. You can also use it for aliases such as mapping `id` to `userID`. * * When retrieving data from DynamoDB, the attribute will be renamed to this property name, or the first element of the array if it is an array. If you want to change this behavior look at the `defaultMap` property. * * When saving to DynamoDB, the attribute name will always be used. * * ```js * "pk": { * "type": String, * "aliases": "userId" * } * "sk": { * "type": String, * "aliases": "orderId" * } * ``` * * ```js * "id": { * "type": String, * "aliases": ["userID", "_id"] * } * ``` */ aliases?: string | string[]; /** * This property can be set to change the default attribute to be renamed to when retrieving data from DynamoDB. This can either be an element from the [`map`](#map-string--string) array or the attribute name. * * By default the attribute name will be used if no `map` property is set. If a `map` property is set, it will use that (or the first element of the array if it is an array). * * ```js * "id": { * "type": String, * "map": "userID", * "defaultMap": "id" * } * ``` */ defaultMap?: string; /** * This property can be set to change the default attribute to be renamed to when retrieving data from DynamoDB. This can either be an element from the `map` array or the attribute name. * * By default the attribute name will be used if no `map` property is set. If a `map` property is set, it will use that (or the first element of the array if it is an array). * * ```js * "id": { * "type": String, * "map": "userID", * "defaultAlias": "id" * } * ``` */ defaultAlias?: string; } export interface SchemaDefinition { [attribute: string]: AttributeType | AttributeType[] | AttributeDefinition | AttributeDefinition[]; } interface SchemaGetAttributeTypeSettings { unknownAttributeAllowed: boolean; } interface SchemaGetAttributeSettingValue { returnFunction: boolean; typeIndexOptionMap?: any; } interface SchemaInternalProperties { schemaObject: SchemaDefinition; settings: SchemaSettings; getMapSettingValuesForKey: (key: string, settingNames?: string[]) => string[]; getMapSettingObject: () => {[key: string]: string}; getDefaultMapAttribute: (attribute: string) => string; getIndexAttributes: () => {index: IndexDefinition; attribute: string}[]; } export class Schema extends InternalPropertiesClass<SchemaInternalProperties> { /** * You can use this method to create a schema. The `schema` parameter is an object defining your schema, each value should be a type or object defining the type with additional settings (listed below). * * The `options` parameter is an optional object with the following options: * * | Name | Type | Default | Information * |---|---|---|---| * | `saveUnknown` | array \| boolean | false | This setting lets you specify if the schema should allow properties not defined in the schema. If you pass `true` in for this option all unknown properties will be allowed. If you pass in an array of strings, only properties that are included in that array will be allowed. If you pass in an array of strings, you can use `*` to indicate a wildcard nested property one level deep, or `**` to indicate a wildcard nested property infinite levels deep (ex. `["person.*", "friend.**"]` will allow you store a property `person` with 1 level of unknown properties and `friend` with infinitely nested level unknown properties). If you retrieve items from DynamoDB with `saveUnknown` enabled, all custom Dynamoose types will be returned as the underlying DynamoDB type (ex. Dates will be returned as a Number representing number of milliseconds since Jan 1 1970). * | `timestamps` | boolean \| object | false | This setting lets you indicate to Dynamoose that you would like it to handle storing timestamps in your items for both creation and most recent update times. If you pass in an object for this setting you must specify two keys `createdAt` & `updatedAt`, each with a value of a string or array of strings being the name of the attribute(s) for each timestamp. If you pass in `null` for either of those keys that specific timestamp won't be added to the schema. If you set this option to `true` it will use the default attribute names of `createdAt` & `updatedAt`. * | `get` | function \| async function | undefined | You can use a get function on the schema to be run whenever retrieving a item from DynamoDB. Dynamoose will pass the entire item into this function and you must return the new value of the entire object you want Dynamoose to return to the application. This function will be run after all property `get` functions are run. * | `set` | function \| async function | undefined | You can use a set function on the schema to be run whenever saving a item to DynamoDB. It will also be used when retrieving an item (ie. `get`, `query`, `update`, etc). Dynamoose will pass the entire item into this function and you must return the new value of the entire object you want Dynamoose to save to DynamoDB. This function will be run after all property `set` functions are run. * | `validate` | function \| async function | undefined | You can use a validate function on the schema to ensure the value passes a given validation before saving the item. Dynamoose will pass the entire item into this function and you must return a boolean (`true` if validation passes or `false` if validation fails) or throw an error. This function will be run after all property `validate` functions are run. * * ```js * const dynamoose = require("dynamoose"); * const schema = new dynamoose.Schema({ * "id": String, * "age": Number * }, { * "saveUnknown": true, * "timestamps": true * }); * ``` * * ```js * const dynamoose = require("dynamoose"); * * const schema = new dynamoose.Schema({ * "id": String, * "person": Object, * "friend": Object * }, { * "saveUnknown": [ * "person.*", // store 1 level deep of nested properties in `person` property * "friend.**" // store infinite levels deep of nested properties in `friend` property * ], * }); * ``` * * ```js * const dynamoose = require("dynamoose"); * * const schema = new dynamoose.Schema({ * "id": String, * "age": { * "type": Number, * "default": 5 * } * }); * ``` * * ```js * const dynamoose = require("dynamoose"); * * const schema = new dynamoose.Schema({ * "id": String, * "name": String * }, { * "timestamps": { * "createdAt": "createDate", * "updatedAt": null // updatedAt will not be stored as part of the timestamp * } * }); * ``` * * ```js * const dynamoose = require("dynamoose"); * * const schema = new dynamoose.Schema({ * "id": String, * "name": String * }, { * "timestamps": { * "createdAt": ["createDate", "creation"], * "updatedAt": ["updateDate", "updated"] * } * }); * ``` * * ```js * const dynamoose = require("dynamoose"); * * const schema = new dynamoose.Schema({ * "id": String, * "name": String * }, { * "validate": (obj) => { * if (!obj.id.beginsWith(name[0])) { * throw new Error("id first letter of name."); * } * return true; * } * }); * ``` * @param object The schema object. * @param settings The settings to apply to the schema. */ constructor (object: SchemaDefinition, settings: SchemaSettings = {}) { super(); if (!object || typeof object !== "object" || Array.isArray(object)) { throw new CustomError.InvalidParameterType("Schema initialization parameter must be an object."); } if (Object.keys(object).length === 0) { throw new CustomError.InvalidParameter("Schema initialization parameter must not be an empty object."); } if (settings.timestamps === true) { settings.timestamps = { "createdAt": "createdAt", "updatedAt": "updatedAt" }; } if (settings.timestamps) { const createdAtArray = Array.isArray(settings.timestamps.createdAt) ? settings.timestamps.createdAt : [settings.timestamps.createdAt]; const updatedAtArray = Array.isArray(settings.timestamps.updatedAt) ? settings.timestamps.updatedAt : [settings.timestamps.updatedAt]; [...createdAtArray, ...updatedAtArray].forEach((prop) => { if (object[prop]) { throw new CustomError.InvalidParameter("Timestamp attributes must not be defined in schema."); } object[prop] = Date; }); } let parsedSettings = {...settings}; const parsedObject = {...object}; utils.object.entries(parsedObject).filter((entry) => entry[1] instanceof Schema).forEach((entry) => { const [key, value] = entry; let newValue = { "type": Object, "schema": (value as any).getInternalProperties(internalProperties).schemaObject }; if (key.endsWith(".schema")) { newValue = (value as any).getInternalProperties(internalProperties).schemaObject; } const subSettings = {...(value as any).getInternalProperties(internalProperties).settings}; Object.entries(subSettings).forEach((entry) => { const [settingsKey, settingsValue] = entry; switch (settingsKey) { case "saveUnknown": subSettings[settingsKey] = typeof subSettings[settingsKey] === "boolean" ? [`${key}.**`] : (settingsValue as any).map((val) => `${key}.${val}`); break; case "timestamps": subSettings[settingsKey] = Object.entries(subSettings[settingsKey]).reduce((obj, entity) => { const [subKey, subValue] = entity; obj[subKey] = Array.isArray(subValue) ? subValue.map((subValue) => `${key}.${subValue}`) : `${key}.${subValue}`; return obj; }, {}); break; } }); parsedSettings = utils.merge_objects.main({"combineMethod": "array_merge_new_array"})(parsedSettings, subSettings); utils.object.set(parsedObject, key, newValue); }); utils.object.entries(parsedObject).forEach((entry) => { const key = entry[0]; const value = entry[1] as any; if (!key.endsWith(".type") && !key.endsWith(".0")) { if (value && value.Model && value.Model instanceof Model) { utils.object.set(parsedObject, key, {"type": value}); } else if (value && Array.isArray(value)) { value.forEach((item, index) => { if (item && item.Model && item.Model instanceof Model) { utils.object.set(parsedObject, `${key}.${index}`, {"type": item}); } }); } } }); const mapSettingNames = [ "map", "alias", "aliases" ]; const defaultMapSettingNames = [ "defaultMap", "defaultAlias" ]; this.setInternalProperties(internalProperties, { "schemaObject": parsedObject, "settings": parsedSettings, "getMapSettingValuesForKey": (key: string, settingNames?: string[]): string[] => utils.array_flatten(mapSettingNames.filter((name) => !settingNames || settingNames.includes(name)).map((mapSettingName) => { const result = this.getAttributeSettingValue(mapSettingName, key); if (Array.isArray(result)) { const filteredArray = result.filter((item) => Boolean(item)); return filteredArray.length === 0 ? undefined : [...new Set(filteredArray)]; } return result; }).filter((v) => Boolean(v))), "getMapSettingObject": (): {[key: string]: string} => { const attributes = this.attributes(); return attributes.reduce((obj, attribute) => { const mapSettingValues: string[] = this.getInternalProperties(internalProperties).getMapSettingValuesForKey(attribute); mapSettingValues.forEach((val) => { obj[val] = attribute; }); return obj; }, {}); }, "getDefaultMapAttribute": (attribute: string): string => { for (const name of defaultMapSettingNames) { const result = this.getAttributeSettingValue(name, attribute); if (result) { return result; } } }, "getIndexAttributes": (): {index: IndexDefinition; attribute: string}[] => { return this.attributes() .map((attribute: string) => ({ "index": this.getAttributeSettingValue("index", attribute) as IndexDefinition, attribute })) .filter((obj) => Array.isArray(obj.index) ? obj.index.some((index) => Boolean(index)) : obj.index) .reduce((accumulator, currentValue) => { if (Array.isArray(currentValue.index)) { currentValue.index.forEach((currentIndex) => { accumulator.push({ ...currentValue, "index": currentIndex }); }); } else { accumulator.push(currentValue); } return accumulator; }, []); } }); const checkAttributeNameDots = (object: SchemaDefinition/*, existingKey = ""*/): void => { Object.keys(object).forEach((key) => { if (key.includes(".")) { throw new CustomError.InvalidParameter("Attributes must not contain dots."); } // TODO: lots of `as` statements in the two lines below. We should clean that up. if (typeof object[key] === "object" && object[key] !== null && (object[key] as AttributeDefinition).schema) { checkAttributeNameDots((object[key] as AttributeDefinition).schema as SchemaDefinition/*, key*/); } }); }; checkAttributeNameDots(this.getInternalProperties(internalProperties).schemaObject); const checkMultipleArraySchemaElements = (key: string): void => { let attributeType: string[] = []; try { const tmpAttributeType = this.getAttributeType(key); attributeType = Array.isArray(tmpAttributeType) ? tmpAttributeType : [tmpAttributeType]; } catch (e) {} // eslint-disable-line no-empty if (attributeType.some((type) => type === "L") && ((this.getAttributeValue(key).schema || []) as any).length > 1) { throw new CustomError.InvalidParameter("You must only pass one element into schema array."); } }; this.attributes().forEach((key) => checkMultipleArraySchemaElements(key)); const hashRangeKeys = this.attributes().reduce((val, key) => { const hashKey = this.getAttributeSettingValue("hashKey", key); const rangeKey = this.getAttributeSettingValue("rangeKey", key); const isHashKey = Array.isArray(hashKey) ? hashKey.every((item) => Boolean(item)) : hashKey; const isRangeKey = Array.isArray(rangeKey) ? rangeKey.every((item) => Boolean(item)) : rangeKey; if (isHashKey) { val.hashKeys.push(key); } if (isRangeKey) { val.rangeKeys.push(key); } if (isHashKey && isRangeKey) { val.hashAndRangeKeyAttributes.push(key); } return val; }, {"hashKeys": [], "rangeKeys": [], "hashAndRangeKeyAttributes": []}); const keyTypes = ["hashKey", "rangeKey"]; keyTypes.forEach((keyType) => { if (hashRangeKeys[`${keyType}s`].length > 1) { throw new CustomError.InvalidParameter(`Only one ${keyType} allowed per schema.`); } if (hashRangeKeys[`${keyType}s`].find((key) => key.includes("."))) { throw new CustomError.InvalidParameter(`${keyType} must be at root object and not nested in object or array.`); } }); if (hashRangeKeys.hashAndRangeKeyAttributes.length > 0) { throw new CustomError.InvalidParameter(`Attribute ${hashRangeKeys.hashAndRangeKeyAttributes[0]} must not be both hashKey and rangeKey`); } this.attributes().forEach((key) => { const attributeSettingValue = this.getAttributeSettingValue("index", key); if (key.includes(".") && (Array.isArray(attributeSettingValue) ? attributeSettingValue.some((singleValue) => Boolean(singleValue)) : attributeSettingValue)) { throw new CustomError.InvalidParameter("Index must be at root object and not nested in object or array."); } }); this.attributes().forEach((key) => { try { this.getAttributeType(key); } catch (e) { if (!e.message.includes("is not allowed to be a set")) { throw new CustomError.InvalidParameter(`Attribute ${key} does not have a valid type.`); } } }); this.attributes().forEach((key) => { const mapSettingValues = mapSettingNames.map((name) => this.getInternalProperties(internalProperties).getMapSettingValuesForKey(key, [name])).filter((v) => Boolean(v) && (!Array.isArray(v) || v.length > 0)); if (mapSettingValues.length > 1) { throw new CustomError.InvalidParameter("Only one of map, alias, or aliases can be specified per attribute."); } }); this.attributes().forEach((key) => { const defaultMapSettingValues = utils.array_flatten(defaultMapSettingNames.map((mapSettingName) => { const result = this.getAttributeSettingValue(mapSettingName, key); if (Array.isArray(result)) { const filteredArray = result.filter((item) => Boolean(item)); return filteredArray.length === 0 ? undefined : filteredArray; } return result; }).filter((v) => Boolean(v))); if (defaultMapSettingValues.length > 1) { throw new CustomError.InvalidParameter("Only defaultMap or defaultAlias can be specified per attribute."); } const defaultMapSettingValue = defaultMapSettingValues[0]; const defaultMapAttribute = defaultMapSettingNames.find((mapSettingName) => this.getAttributeSettingValue(mapSettingName, key)); if (defaultMapSettingValue) { if (!this.getInternalProperties(internalProperties).getMapSettingValuesForKey(key).includes(defaultMapSettingValue) && defaultMapSettingValue !== key) { throw new CustomError.InvalidParameter(`${defaultMapAttribute} must exist in map, alias, or aliases property or be equal to attribute name.`); } } }); const mapAttributes = this.attributes().map((key) => this.getInternalProperties(internalProperties).getMapSettingValuesForKey(key)); const mapAttributesFlattened = utils.array_flatten(mapAttributes); const mapAttributesSet = new Set(mapAttributesFlattened); if (mapAttributesSet.size !== mapAttributesFlattened.length) { throw new CustomError.InvalidParameter("Each properties map, alias, or aliases properties must be unique across the entire schema."); } if ([...mapAttributesSet].some((key) => this.attributes().includes(key))) { throw new CustomError.InvalidParameter("Each properties map, alias, or aliases properties must be not be used as a property name in the schema."); } } /** * This property returns an array of strings with each string being the name of an attribute. Only attributes that are indexes are returned. * * ```js * const schema = new Schema({ * "id": String, * "name": { * "type": String, * "index": true * } * }); * console.log(schema.indexAttributes); // ["name"] * ``` */ get indexAttributes (): string[] { return this.getInternalProperties(internalProperties).getIndexAttributes().map((key) => key.attribute); } attributes: (object?: ObjectType, settings?: SchemaAttributesMethodSettings) => string[]; async getCreateTableAttributeParams (model: Model<Item>): Promise<Pick<DynamoDB.CreateTableInput, "AttributeDefinitions" | "KeySchema" | "GlobalSecondaryIndexes" | "LocalSecondaryIndexes">> { const hashKey = this.hashKey; const AttributeDefinitions = [ { "AttributeName": hashKey, "AttributeType": this.getSingleAttributeType(hashKey) } ]; const AttributeDefinitionsNames = [hashKey]; const KeySchema = [ { "AttributeName": hashKey, "KeyType": "HASH" } ]; const rangeKey = this.rangeKey; if (rangeKey) { AttributeDefinitions.push({ "AttributeName": rangeKey, "AttributeType": this.getSingleAttributeType(rangeKey) }); AttributeDefinitionsNames.push(rangeKey); KeySchema.push({ "AttributeName": rangeKey, "KeyType": "RANGE" }); } utils.array_flatten(await Promise.all([this.getInternalProperties(internalProperties).getIndexAttributes(), this.getIndexRangeKeyAttributes()])).map((obj) => obj.attribute).forEach((index) => { if (AttributeDefinitionsNames.includes(index)) { return; } AttributeDefinitionsNames.push(index); AttributeDefinitions.push({ "AttributeName": index, "AttributeType": this.getSingleAttributeType(index) }); }); const response: any = { AttributeDefinitions, KeySchema }; const {GlobalSecondaryIndexes, LocalSecondaryIndexes} = await this.getIndexes(model); if (GlobalSecondaryIndexes) { response.GlobalSecondaryIndexes = GlobalSecondaryIndexes; } if (LocalSecondaryIndexes) { response.LocalSecondaryIndexes = LocalSecondaryIndexes; } return response; } // This function has the same behavior as `getAttributeType` except if the schema has multiple types, it will throw an error. This is useful for attribute definitions and keys for when you are only allowed to have one type for an attribute private getSingleAttributeType (key: string, value?: ValueType, settings?: SchemaGetAttributeTypeSettings): string { const attributeType = this.getAttributeType(key, value, settings); if (Array.isArray(attributeType)) { throw new CustomError.InvalidParameter(`You can not have multiple types for attribute definition: ${key}.`); } return attributeType; } getAttributeType (key: string, value?: ValueType, settings?: SchemaGetAttributeTypeSettings): string | string[] { try { const typeDetails = this.getAttributeTypeDetails(key); return Array.isArray(typeDetails) ? (typeDetails as any).map((detail) => detail.dynamodbType) : typeDetails.dynamodbType; } catch (e) { if (settings?.unknownAttributeAllowed && e.message === `Invalid Attribute: ${key}` && value) { return Object.keys(Item.objectToDynamo(value, {"type": "value"}))[0]; } else { throw e; } } } static attributeTypes = { "findDynamoDBType": (type): DynamoDBTypeResult | DynamoDBSetTypeResult => attributeTypes.find((checkType) => checkType.dynamodbType === type), "findTypeForValue": (...args): DynamoDBTypeResult | DynamoDBSetTypeResult => attributeTypes.find((checkType) => (checkType.isOfType as any)(...args)) }; /** * This property returns the property name of your schema's hash key. * * ```js * const schema = new dynamoose.Schema({"id": String}); * console.log(schema.hashKey); // "id" * ``` */ get hashKey (): string { return Object.keys(this.getInternalProperties(internalProperties).schemaObject).find((key) => (this.getInternalProperties(internalProperties).schemaObject[key] as AttributeDefinition).hashKey) || Object.keys(this.getInternalProperties(internalProperties).schemaObject)[0]; } /** * This property returns the property name of your schema's range key. It will return undefined if a range key does not exist for your schema. * ```js * const schema = new dynamoose.Schema({"id": String, "type": {"type": String, "rangeKey": true}}); * console.log(schema.rangeKey); // "type" * ``` * * ```js * const schema = new dynamoose.Schema({"id": String}); * console.log(schema.rangeKey); // undefined * ``` */ get rangeKey (): string | undefined { return Object.keys(this.getInternalProperties(internalProperties).schemaObject).find((key) => (this.getInternalProperties(internalProperties).schemaObject[key] as AttributeDefinition).rangeKey); } // This function will take in an attribute and value, and returns the default value if it should be applied. async defaultCheck (key: string, value: ValueType, settings: any): Promise<ValueType | void> { const isValueUndefined = typeof value === "undefined" || value === null; if (settings.defaults && isValueUndefined || settings.forceDefault && this.getAttributeSettingValue("forceDefault", key)) { const defaultValueRaw = this.getAttributeSettingValue("default", key); let hasMultipleTypes: boolean; try { hasMultipleTypes = Array.isArray(this.getAttributeType(key)); } catch (e) { hasMultipleTypes = false; } const defaultValue = Array.isArray(defaultValueRaw) && hasMultipleTypes ? defaultValueRaw[0] : defaultValueRaw; const isDefaultValueUndefined = typeof defaultValue === "undefined" || defaultValue === null; if (!isDefaultValueUndefined) { return defaultValue; } } } requiredCheck: (key: string, value: ValueType) => Promise<void>; getAttributeSettingValue (setting: string, key: string, settings: SchemaGetAttributeSettingValue = {"returnFunction": false}) { function func (attributeValue): any { const defaultPropertyValue = (attributeValue || {})[setting]; return typeof defaultPropertyValue === "function" && !settings.returnFunction ? defaultPropertyValue() : defaultPropertyValue; } const attributeValue = this.getAttributeValue(key, {"typeIndexOptionMap": settings.typeIndexOptionMap}); if (Array.isArray(attributeValue)) { return attributeValue.map(func); } else { return func(attributeValue); } } getTypePaths (object: ObjectType, settings: { type: "toDynamo" | "fromDynamo"; previousKey?: string; includeAllProperties?: boolean } = {"type": "toDynamo"}): ObjectType { return Object.entries(object).reduce((result, entry) => { const [key, value] = entry; const fullKey = [settings.previousKey, key].filter((a) => Boolean(a)).join("."); let typeCheckResult; try { typeCheckResult = utils.dynamoose.getValueTypeCheckResult(this, value, fullKey, settings, {}); } catch (e) { if (result && settings.includeAllProperties) { result[fullKey] = { "index": 0, "matchCorrectness": 0.5, "entryCorrectness": [0.5] }; } return result; } const {typeDetails, matchedTypeDetailsIndex, matchedTypeDetailsIndexes} = typeCheckResult; const hasMultipleTypes = Array.isArray(typeDetails); const isObject = typeof value === "object" && !(value instanceof Buffer) && value !== null; if (hasMultipleTypes) { if (matchedTypeDetailsIndexes.length > 1 && isObject) { result[fullKey] = matchedTypeDetailsIndexes.map((index: number) => { const entryCorrectness = utils.object.entries(value).map((entry) => { const [subKey, subValue] = entry; try { const {isValidType} = utils.dynamoose.getValueTypeCheckResult(this, subValue, `${fullKey}.${subKey}`, settings, {"typeIndexOptionMap": {[fullKey]: index}}); return isValidType ? 1 : 0; } catch (e) { return 0.5; } }); return { index, // 1 = full match // 0.5 = attributes don't exist // 0 = types don't match "matchCorrectness": Math.min(...entryCorrectness), entryCorrectness }; }).sort((a, b) => { if (a.matchCorrectness === b.matchCorrectness) { return b.entryCorrectness.reduce((a: number, b: number) => a + b, 0) - a.entryCorrectness.reduce((a: number, b: number) => a + b, 0); } else { return b.matchCorrectness - a.matchCorrectness; } }).map((a) => a.index)[0]; } if (result[fullKey] === undefined) { result[fullKey] = matchedTypeDetailsIndex; } } else if (settings.includeAllProperties) { const matchCorrectness: number = typeCheckResult.isValidType ? 1 : 0; result[fullKey] = { "index": 0, matchCorrectness, "entryCorrectness": [matchCorrectness] }; } if (isObject) { result = {...result, ...this.getTypePaths(value, {...settings, "previousKey": fullKey})}; } return result; }, {}); } getSettingValue: (setting: string) => any; getAttributeTypeDetails: (key: string, settings?: { standardKey?: boolean; typeIndexOptionMap?: {} }) => DynamoDBTypeResult | DynamoDBSetTypeResult | DynamoDBTypeResult[] | DynamoDBSetTypeResult[]; getAttributeValue: (key: string, settings?: { standardKey?: boolean; typeIndexOptionMap?: {} }) => AttributeDefinition; getIndexes: (model: Model<Item>) => Promise<ModelIndexes>; getIndexRangeKeyAttributes: () => Promise<{ attribute: string }[]>; } // This function will take in an attribute and value, and throw an error if the property is required and the value is undefined or null. Schema.prototype.requiredCheck = async function (this: Schema, key: string, value: ValueType): Promise<void> { const isRequired = this.getAttributeSettingValue("required", key); if ((typeof value === "undefined" || value === null) && (Array.isArray(isRequired) ? isRequired.some((val) => Boolean(val)) : isRequired)) { throw new CustomError.ValidationError(`${key} is a required property but has no value when trying to save item`); } }; Schema.prototype.getIndexRangeKeyAttributes = async function (this: Schema): Promise<{attribute: string}[]> { const indexes: ({index: IndexDefinition; attribute: string})[] = await this.getInternalProperties(internalProperties).getIndexAttributes(); return indexes.map((index) => index.index.rangeKey).filter((a) => Boolean(a)).map((a) => ({"attribute": a})); }; export interface TableIndex { KeySchema: ({AttributeName: string; KeyType: "HASH" | "RANGE"})[]; } export interface IndexItem { IndexName: string; KeySchema: ({AttributeName: string; KeyType: "HASH" | "RANGE"})[]; Projection: {ProjectionType: "KEYS_ONLY" | "INCLUDE" | "ALL"; NonKeyAttributes?: string[]}; ProvisionedThroughput?: {"ReadCapacityUnits": number; "WriteCapacityUnits": number}; // TODO: this was copied from get_provisioned_throughput. We should change this to be an actual interface } Schema.prototype.getIndexes = async function (this: Schema, model: Model<Item>): Promise<ModelIndexes> { const indexes: ModelIndexes = (await this.getInternalProperties(internalProperties).getIndexAttributes()).reduce((accumulator, currentValue) => { const indexValue = currentValue.index; const attributeValue = currentValue.attribute; const isGlobalIndex = indexValue.type === "global" || !indexValue.type; const dynamoIndexObject: IndexItem = { "IndexName": indexValue.name || `${attributeValue}${isGlobalIndex ? "GlobalIndex" : "LocalIndex"}`, "KeySchema": [], "Projection": {"ProjectionType": "KEYS_ONLY"} }; if (indexValue.project || typeof indexValue.project === "undefined" || indexValue.project === null) { dynamoIndexObject.Projection = Array.isArray(indexValue.project) ? {"ProjectionType": "INCLUDE", "NonKeyAttributes": indexValue.project} : {"ProjectionType": "ALL"}; } if (isGlobalIndex) { dynamoIndexObject.KeySchema.push({"AttributeName": attributeValue, "KeyType": "HASH"}); if (indexValue.rangeKey) { dynamoIndexObject.KeySchema.push({"AttributeName": indexValue.rangeKey, "KeyType": "RANGE"}); } const throughputObject = utils.dynamoose.get_provisioned_throughput(indexValue.throughput ? indexValue : model.getInternalProperties(internalProperties).table().getInternalProperties(internalProperties).options.throughput === "ON_DEMAND" ? {} : model.getInternalProperties(internalProperties).table().getInternalProperties(internalProperties).options); if ("ProvisionedThroughput" in throughputObject) { dynamoIndexObject.ProvisionedThroughput = throughputObject.ProvisionedThroughput; } } else { dynamoIndexObject.KeySchema.push({"AttributeName": this.hashKey, "KeyType": "HASH"}); dynamoIndexObject.KeySchema.push({"AttributeName": attributeValue, "KeyType": "RANGE"}); } const accumulatorKey = isGlobalIndex ? "GlobalSecondaryIndexes" : "LocalSecondaryIndexes"; if (!accumulator[accumulatorKey]) { accumulator[accumulatorKey] = []; } accumulator[accumulatorKey].push(dynamoIndexObject); return accumulator; }, {}); indexes.TableIndex = {"KeySchema": [{"AttributeName": this.hashKey, "KeyType": "HASH"}]}; const rangeKey = this.rangeKey; if (rangeKey) { indexes.TableIndex.KeySchema.push({"AttributeName": rangeKey, "KeyType": "RANGE"}); } return indexes; }; Schema.prototype.getSettingValue = function (this: Schema, setting: string): any { return this.getInternalProperties(internalProperties).settings[setting]; }; interface SchemaAttributesMethodSettings { includeMaps: boolean; } Schema.prototype.attributes = function (this: Schema, object?: ObjectType, settings?: SchemaAttributesMethodSettings): string[] { const typePaths = object && this.getTypePaths(object); const main = (object: SchemaDefinition, existingKey = ""): string[] => { return Object.keys(object).reduce((accumulator: string[], key) => { const keyWithExisting = `${existingKey ? `${existingKey}.` : ""}${key}`; accumulator.push(keyWithExisting); if (settings?.includeMaps) { accumulator.push(...this.getInternalProperties(internalProperties).getMapSettingValuesForKey(keyWithExisting)); } let attributeType: string[]; try { const tmpAttributeType = this.getAttributeType(keyWithExisting); attributeType = Array.isArray(tmpAttributeType) ? tmpAttributeType : [tmpAttributeType]; } catch (e) {} // eslint-disable-line no-empty // TODO: using too many `as` statements in the few lines below. Clean that up. function recursive (type, arrayTypeIndex): void { if ((type === "M" || type === "L") && ((object[key][arrayTypeIndex] || object[key]) as AttributeDefinition).schema) { accumulator.push(...main(((object[key][arrayTypeIndex] || object[key]) as AttributeDefinition).schema as SchemaDefinition, keyWithExisting)); } } if (attributeType) { if (typePaths && typePaths[keyWithExisting] !== undefined) { const index = typePaths[keyWithExisting]; const type = attributeType[index]; recursive(type, index); } else { attributeType.forEach(recursive); } } // ------------------------------ return accumulator; }, []); }; return main(this.getInternalProperties(internalProperties).schemaObject); }; Schema.prototype.getAttributeValue = function (this: Schema, key: string, settings?: {standardKey?: boolean; typeIndexOptionMap?: {}}): AttributeDefinition { const previousKeyParts = []; let result = (settings?.standardKey ? key : key.replace(/\.\d+/gu, ".0")).split(".").reduce((result, part) => { if (Array.isArray(result)) { const predefinedIndex = settings && settings.typeIndexOptionMap && settings.typeIndexOptionMap[previousKeyParts.join(".")]; if (predefinedIndex !== undefined) { result = result[predefinedIndex]; } else { result = result.find((item) => item.schema && item.schema[part]); } } previousKeyParts.push(part); return utils.object.get(result.schema, part); }, {"schema": this.getInternalProperties(internalProperties).schemaObject} as any); if (Array.isArray(result)) { const predefinedIndex = settings && settings.typeIndexOptionMap && settings.typeIndexOptionMap[previousKeyParts.join(".")]; if (predefinedIndex !== undefined) { result = result[predefinedIndex]; } } return result; }; function retrieveTypeInfo (type: string, isSet: boolean, key: string, typeSettings: AttributeDefinitionTypeSettings): DynamoDBTypeResult | DynamoDBSetTypeResult { const foundType = attributeTypesMain.find((checkType) => checkType.name.toLowerCase() === type.toLowerCase()); if (!foundType) { throw new CustomError.InvalidType(`${key} contains an invalid type: ${type}`); } const parentType = foundType.result(typeSettings); if (!parentType.set && isSet) { throw new CustomError.InvalidType(`${key} with type: ${type} is not allowed to be a set`); } return isSet ? parentType.set : parentType; } // TODO: using too many `as` statements in the function below. We should clean this up. Schema.prototype.getAttributeTypeDetails = function (this: Schema, key: string, settings: {standardKey?: boolean; typeIndexOptionMap?: {}} = {}): DynamoDBTypeResult | DynamoDBSetTypeResult | DynamoDBTypeResult[] | DynamoDBSetTypeResult[] { const standardKey = settings.standardKey ? key : key.replace(/\.\d+/gu, ".0"); const val = this.getAttributeValue(standardKey, {...settings, "standardKey": true}); if (typeof val === "undefined") { throw new CustomError.UnknownAttribute(`Invalid Attribute: ${key}`); } let typeVal = typeof val === "object" && !Array.isArray(val) && val.type ? val.type : val; let typeSettings: AttributeDefinitionTypeSettings = {}; if (typeof typeVal === "object" && !Array.isArray(typeVal)) { typeSettings = (typeVal as {value: DateConstructor; settings?: AttributeDefinitionTypeSettings}).settings || {}; typeVal = (typeVal as any).value; } const getType = (typeVal: AttributeType | AttributeDefinition): string => { let type: string; const isThisType = typeVal as any === Internal.Public.this; const isNullType = typeVal as any === Internal.Public.null; const isAnyType = typeVal as any === Internal.Public.any; if (typeof typeVal === "function" || isThisType) { if ((typeVal as any).prototype instanceof Item || isThisType) { type = "model"; if (isThisType) { const obj = { "getInternalProperties": () => ({ "schemas": [this], "getHashKey": () => this.hashKey, "getRangeKey": () => this.rangeKey }) }; typeSettings.model = {"Model": obj} as any; } else { typeSettings.model = typeVal as any; } } else { const regexFuncName = /^Function ([^(]+)\(/iu; [, type] = typeVal.toString().match(regexFuncName); } } else if (isNullType) { type = "null"; } else if (isAnyType) { type = "any"; } else if ((typeVal as string).toLowerCase() === "null") { throw new Error("Please use dynamoose.type.NULL instead of \"null\" for your type attribute."); } else if ((typeVal as string).toLowerCase() === "any") { throw new Error("Please use dynamoose.type.ANY instead of \"any\" for your type attribute."); } else { type = typeVal as string; } return type; }; const result: DynamoDBTypeResult[] | DynamoDBSetTypeResult[] = ((Array.isArray(typeVal) ? typeVal : [typeVal]) as any).map((item, index: number) => { item = typeof item === "object" && !Array.isArray(item) && item.type ? item.type : item; if (typeof item === "object" && !Array.isArray(item)) { typeSettings = (item as {value: DateConstructor; settings?: AttributeDefinitionTypeSettings}).settings || {}; item = item.value; } let type = getType(item); const isSet = type.toLowerCase() === "set"; if (isSet) { let schemaValue = this.getAttributeSettingValue("schema", key); if (Array.isArray(schemaValue[index])) { schemaValue = schemaValue[index]; } const subValue = schemaValue[0]; type = getType(typeof subValue === "object" && subValue.type ? subValue.type : subValue); } const returnObject = retrieveTypeInfo(type, isSet, key, typeSettings); return returnObject; }); const returnObject = result.length < 2 ? result[0] : result; return returnObject; };
the_stack
import { colors, Command, CompletionsCommand, debounce, deferred, fs, path, prettyBytes, RollupCache, Table, } from "./deps/mod.ts"; import { bundle } from "./src/bundle.ts"; import { dependencyList } from "./src/dependency_graph.ts"; import { exportCommand } from "./src/export.ts"; import { serve } from "./src/serve.ts"; import { findPages, printError } from "./src/util.ts"; const VERSION = "0.10.5"; try { await new Command() .throwErrors() .name("dext") .version(VERSION) .description("The Preact Framework for Deno") .action(function () { console.log(this.getHelp()); }) .command("build [root]") .option( "--typecheck [enabled:boolean]", "If TypeScript code should be typechecked.", { default: true }, ) .option( "--prerender [enabled:boolean]", "If static pages should be server side prerendered.", { default: true }, ) .option( "--debug [include:boolean]", "If preact/debug should be included in the bundle.", { default: false }, ) .option( "--sourcemap [enabled:boolean]", "If sourcemap should be generated", { default: true }, ) .option( "--minify [enabled:boolean]", "If the source should be minified", { default: true }, ) .description("Build your application.") .action(build) .command("start [root]") .option("-a --address <address>", "The address to listen on.", { default: ":3000", }) .option("--quiet", "If access logs should be printed.") .description("Start a built application.") .action(start) .command("dev [root]") .option("-a --address <address>", "The address to listen on.", { default: ":3000", }) .option( "--hot-refresh [enabled:boolean]", "If hot refresh should be disabled.", { default: true }, ) .option( "--hot-refresh-host <host:string>", "The hostname to use for the hot refresh websocket endpoint. Useful for proxies.", { depends: ["hot-refresh"] }, ) .option( "--typecheck [enabled:boolean]", "If TypeScript code should be typechecked.", { default: false }, ) .option( "--prerender [enabled:boolean]", "If static pages should be server side prerendered.", { default: false }, ) .option( "--debug [include:boolean]", "If preact/debug should be included in the bundle.", { default: true }, ) .description("Start your application in development mode.") .action(dev) .command("create [root]") .description("Scaffold new application.") .action(create) .command("export", exportCommand()) .description("Export a project for Netlify or other providers.") .command("completions", new CompletionsCommand()) .parse(Deno.args); } catch (err) { printError(err); Deno.exit(1); } async function build( options: { typecheck: boolean; prerender: boolean; debug: boolean; sourcemap: boolean; minify: boolean; }, root?: string, ) { root = path.resolve(Deno.cwd(), root ?? ""); const tsconfigPath = path.join(root, "tsconfig.json"); if (!(await fs.exists(tsconfigPath))) { console.log( colors.red(colors.bold("Error: ") + "Missing tsconfig.json file."), ); Deno.exit(1); } // Collect list of all pages const pagesDir = path.join(root, "pages"); const pages = await findPages(pagesDir); // Create .dext folder and emit page map const dextDir = path.join(root, ".dext"); await fs.ensureDir(dextDir); const pagemapPath = path.join(dextDir, "pagemap.json"); await Deno.writeTextFile( pagemapPath, JSON.stringify( pages.pages.map((page) => ({ name: page.name, route: page.route, hasGetStaticPaths: page.hasGetStaticPaths, })), ), ); // Do bundling const outDir = path.join(dextDir, "static"); const { stats } = await bundle(pages, { rootDir: root, outDir, tsconfigPath, minify: options.minify, sourcemap: options.sourcemap, hotRefresh: false, typecheck: options.typecheck, prerender: options.prerender, debug: options.debug, }); console.log(colors.green(colors.bold("Build success.\n"))); if (stats) { const sharedKeys = Object.keys(stats.shared); new Table() .header([ colors.bold("Page"), colors.bold("Size"), colors.bold("First Load JS"), ]) .body([ ...stats.routes.map((route, i) => { const prefix = stats.routes.length === 1 ? "-" : i === 0 ? "┌" : i === stats.routes.length - 1 ? "└" : "├"; return [ `${prefix} ${route.hasGetStaticData ? "●" : "○"} ${route.route}`, prettyBytes(route.size.brotli), prettyBytes(route.firstLoad.brotli), ]; }), [], [ "+ First Load JS shared by all", prettyBytes(stats.framework.brotli), "", ], ...sharedKeys.map((name, i) => { const size = stats.shared[name]; const isLast = i === sharedKeys.length - 1; return [ ` ${isLast ? "└" : "├"} ${name}`, prettyBytes(size.brotli), "", ]; }), ]) .padding(2) .render(); console.log(); console.log("○ (Static) automatically rendered as static HTML"); console.log( "● (SSG) automatically generated as static HTML + JSON (uses getStaticData)", ); console.log(); console.log( colors.gray("File sizes are measured after brotli compression."), ); } } async function start( options: { address: string; quiet: boolean }, root?: string, ) { root = path.resolve(Deno.cwd(), root ?? ""); const dextDir = path.join(root, ".dext"); const pagemapPath = path.join(dextDir, "pagemap.json"); if (!(await fs.exists(pagemapPath))) { console.log( colors.red( colors.bold("Error: ") + "Page map does not exist. Did you build the project?", ), ); Deno.exit(1); } const pagemap = JSON.parse(await Deno.readTextFile(pagemapPath)); const staticDir = path.join(dextDir, "static"); await serve(pagemap, { staticDir, address: options.address, quiet: options.quiet, }); } async function dev( options: { address: string; hotRefresh: boolean; hotRefreshHost: string; typecheck: boolean; prerender: boolean; debug: boolean; }, maybeRoot?: string, ) { const root = path.resolve(Deno.cwd(), maybeRoot ?? ""); const tsconfigPath = path.join(root, "tsconfig.json"); if (!(await fs.exists(tsconfigPath))) { console.log( colors.red(colors.bold("Error: ") + "Missing tsconfig.json file."), ); Deno.exit(1); } let cache: RollupCache = { modules: [] }; // Collect list of all pages const pagesDir = path.join(root, "pages"); const pages = await findPages(pagesDir); const dextDir = path.join(root, ".dext"); await fs.ensureDir(dextDir); const outDir = path.join(dextDir, "static"); let doHotRefresh = deferred(); const hotRefresh = (async function* () { while (true) { await doHotRefresh; doHotRefresh = deferred(); yield; } })(); const run = debounce(async function () { const start = new Date(); console.log(colors.cyan(colors.bold("Started build..."))); try { const out = await bundle(pages, { rootDir: root, outDir, tsconfigPath, cache, minify: false, sourcemap: true, hotRefresh: options.hotRefresh, hotRefreshHost: options.hotRefreshHost, typecheck: options.typecheck, prerender: options.prerender, debug: options.debug, }); cache = out.cache!; doHotRefresh.resolve(); console.log( colors.green( colors.bold( `Build success done ${ ( new Date().getTime() - start.getTime() ).toFixed(0) }ms`, ), ), ); } catch (err) { printError(err); } }, 100); const pagesPaths = pages.pages.map((page) => page.path); if (pages.app) pagesPaths.push(pages.app.path); if (pages.document) pagesPaths.push(pages.document.path); const deps = await dependencyList(pagesPaths); const toWatch = deps .filter((dep) => dep.startsWith(`file://`)) .map(path.fromFileUrl) .filter((dep) => dep.startsWith(root)); const publicDir = path.join(root, "public"); if (await fs.exists(publicDir)) toWatch.push(publicDir); (async () => { for await (const { kind } of Deno.watchFs(toWatch, { recursive: true })) { if (kind === "any" || kind === "access") continue; await run(); } })(); const server = serve(pages.pages, { staticDir: outDir, address: options.address, quiet: true, hotRefresh, }); await run(); await server; } async function create(_options: unknown, maybeRoot?: string) { const root = path.resolve(Deno.cwd(), maybeRoot ?? ""); await fs.ensureDir(root); const gitIgnorePath = path.join(root, ".gitignore"); await Deno.writeTextFile(gitIgnorePath, "/.dext\n"); const tsconfigPath = path.join(root, "tsconfig.json"); await Deno.writeTextFile( tsconfigPath, JSON.stringify({ compilerOptions: { lib: ["esnext", "dom", "deno.ns"], jsx: "react", jsxFactory: "h", jsxFragmentFactory: "Fragment", }, }), ); const pagesDir = path.join(root, "pages"); await fs.ensureDir(pagesDir); const depsPath = path.join(root, "deps.ts"); const depsText = `export { Fragment, h } from "https://deno.land/x/dext@${VERSION}/deps/preact/mod.ts"; export type { AppProps, GetStaticData, GetStaticDataContext, GetStaticPaths, PageProps, } from "https://deno.land/x/dext@${VERSION}/mod.ts"; `; await Deno.writeTextFile(depsPath, depsText); const indexPath = path.join(pagesDir, "index.tsx"); const indexText = `import { h, Fragment } from "../deps.ts"; import type { PageProps, GetStaticData } from "../deps.ts"; interface Data { random: string; } function IndexPage(props: PageProps<Data>) { return ( <> <h1>Hello World!!!</h1> <p>This is the index page.</p> <p>The random is {props.data.random}.</p> <p> <a href="/user/lucacasonato">Go to @lucacasonato</a> </p> </> ); } export const getStaticData = (): GetStaticData<Data> => { return { data: { random: Math.random().toString(), }, }; }; export default IndexPage; `; await Deno.writeTextFile(indexPath, indexText); const userDir = path.join(pagesDir, "user"); await fs.ensureDir(userDir); const userPath = path.join(userDir, "[name].tsx"); const userText = `import { h, Fragment } from "../../deps.ts"; import type { PageProps } from "../../deps.ts"; function UserPage(props: PageProps) { const name = props.route?.name ?? ""; return ( <> <h1>This is the page for {name}</h1> <p> <a href="/">Go home</a> </p> </> ); } export default UserPage; `; await Deno.writeTextFile(userPath, userText); console.log(colors.green(colors.bold(`New project created in ${root}`))); }
the_stack
require('source-map-support').install(); var falafel = require("falafel"); var XRegExp = require('xregexp').XRegExp; import Json = require('source-processor'); import error = require('source-processor'); import optimizer = require('../src/optimizer'); import globals = require('../src/globals'); //todo //implement explicit types rather than ad hoc string export class Function { identifier: string; //the function name signature: string; //the function name, and the number of params, e.g. f(x) signature is f(0) parameter_map: {[pos:number]:string;};//maps the position of the param to a string value expression: Expression; static DECLARATION_FORMAT = XRegExp( '(?<name>\\w+) \\s* # name is alphanumeric\n'+ '\\( \\s* #open brace for function args \n'+ '(?<paramlist> (\\w+\\s*(,\\s*\\w+\\s*)*)?) #comma seperated list of params\n'+ '\\) \\s* #close brace for function args \n', 'gx'); constructor(declaration: string, expression: Json.JString) { //break the function declaration into its parts var match = XRegExp.exec(declaration, Function.DECLARATION_FORMAT); var params = XRegExp.split(match.paramlist, /\s*,\s*/); //bug fix for weird split behaviour (preserved in XRegExp) //if the declaration has no parameters, the "paramlist" gets split as [''] for some reason if(params.length==1 && params[0] == '') params = []; //convert it to empty list as it should be this.identifier = match.name; this.signature = match.name + "(" + params.length + ")"; //now build up positional information of params this.parameter_map = params; this.expression = Expression.parseUser(expression); } static parse(json: Json.JValue): Function { //console.log("Function.parse:", json); var fun: Function; //there should only be one entry json.asObject().forEach(function(key: Json.JString, val: Json.JValue) { fun = new Function(key.asString().value, val.coerceString()); }); return fun } } /** * instances support indexing like arrays, which maps cannocal function declarations to Function definitions */ export class Functions { [index: string]: Function; static parse(json: Json.JValue): Functions{ //console.log("Functions.parse:", json); var functions = new Functions(); if (json == null) return functions; json.asArray().forEach(function(val: Json.JValue) { var fun: Function = Function.parse(val); functions[fun.identifier] = fun; }); return functions } } export class Symbols{ functions: {[index: string]: Function} = {}; variables: {[index: string]: any} = {}; //string->AST node clone():Symbols{ var clone: Symbols = new Symbols(); for(var p in this.functions) clone.functions[p] = this.functions[p]; for(var v in this.variables) clone.variables[v] = this.variables[v]; return clone; } loadFunction(functions: Functions) { for(var identifier in functions){ this.functions[identifier] = functions[identifier]; } } } export class Expression{ raw: string; source: Json.JString; //null source means the compiler generated it static FALSE: Expression = new Expression("false", null); static TRUE: Expression = new Expression("true", null); constructor (raw: string, source: Json.JString) { this.raw = raw; this.source = source; } static parse(raw: string): Expression{ return new Expression(raw, null); } static parseUser(json: Json.JString): Expression{ return new Expression(optimizer.sanitizeQuotes(json.value), json); } /** * changes next and prev references for next.parent() and prev.parent() */ rewriteForChild(): string { var falafel_visitor = function(node) { if(node.type == "Identifier"){ if(node.name == "next"){ node.update("next.parent()"); }else if(node.name == "prev"){ node.update("prev.parent()"); } } }; return falafel(this.raw, {}, falafel_visitor).toString(); } /** * changes next and prev references for next['child_name'] and prev['child_name'] * wildchild's can't be represented in their parents context, so wildchilds are conservatively * represented as "false" */ rewriteForParent(child_name): string{ if(child_name.indexOf("$") == 0) return "false"; //wildchilds can't be pushed up if(child_name.indexOf("~$") == 0) return "true"; //wilderchilds can be pushed up var falafel_visitor = function(node){ if(node.type == "Identifier"){ if(node.name == "next"){ node.update("next['" + child_name +"']"); }else if(node.name == "prev"){ node.update("prev['" + child_name +"']"); } } }; return <string>falafel(this.raw, {}, falafel_visitor).toString(); } expandFunctions(symbols: Symbols): string { var self: Expression = this; var falafel_visitor = function(node){ //console.log("type:", node.type); if(node.type == "Identifier"){ if(symbols.functions[node.name]){ node.expr_type = "pred" }else if(symbols.variables[node.name]){ node.update(symbols.variables[node.name].source()); node.expr_type = symbols.variables[node.name].expr_type } } else if(node.type == "CallExpression"){ if(node.callee.expr_type === "pred"){ //console.log(node) //we are calling a user defined function var fun: Function = symbols.functions[node.callee.name]; //clone the global symbol table and populate with binding to parameters var function_symbols = symbols.clone(); var params = node.arguments; for(var p_index in params){ var p_node = params[p_index]; var local_name = fun.parameter_map[p_index]; function_symbols.variables[local_name] = p_node; } var expansion = fun.expression.expandFunctions(function_symbols); node.update("(" + expansion + ")"); node.expr_type = "value"; } } }; var code: string = falafel(this.raw, {}, falafel_visitor).toString(); return optimizer.simplify(code); } generate(symbols: Symbols): string { var self: Expression = this; //the falafel visitor function replaces source with a different construction var falafel_visitor = function(node){ //console.log("type:", node.type); if(node.type == "Identifier"){ //console.log("identifier: ", node.name); if(node.name == "data"){ node.expr_type = "rule" }else if(node.name == "newData"){ node.expr_type = "rule" }else if(node.name == "next"){ node.update("newData"); node.expr_type = "rule" }else if(node.name == "prev"){ node.update("data"); node.expr_type = "rule" }else if(node.name == "root"){ node.expr_type = "rule" }else if(node.name.indexOf("$")==0){ node.expr_type = "value" }else if(node.name == "auth"){ node.expr_type = "map" }else if(symbols.functions[node.name]){ node.expr_type = "pred" }else if(symbols.variables[node.name]){ var label = node.name; node.update(symbols.variables[node.name].source()); node.expr_type = symbols.variables[node.name].expr_type node.label = label; } }else if(node.type == "Literal"){ //console.log("literal: ", node.value); if ((typeof node.value == 'string' || node.value instanceof String) && node.raw.indexOf('/') == 0){ node.expr_type = "regex"; } else { node.expr_type = "value"; } }else if(node.type == "ArrayExpression"){ //console.log("ArrayExpression", node); node.expr_type = "value"; }else if(node.type == "MemberExpression"){ //console.log("MemberExpression:", node); //if the object is a type (rules, map or value) it unlocks different valid properties if(node.object.expr_type == "rule"){ node.expr_type = null; if(node.property.type == 'Identifier'){ //reserved methods if(node.property.name == 'val'){ node.expr_type = "fun():value" }else if(node.property.name == 'parent'){ node.expr_type = "fun():rule" }else if(node.property.name == 'hasChildren'){ node.expr_type = "fun(array):value" }else if(node.property.name == 'hasChild'){ node.expr_type = "fun():value" }else if(node.property.name == 'isString'){ node.expr_type = "fun():value" }else if(node.property.name == 'isBoolean'){ node.expr_type = "fun():value" }else if(node.property.name == 'isNumber'){ node.expr_type = "fun():value" }else if(node.property.name == 'exists'){ node.expr_type = "fun():value" }else if(node.property.name == 'now'){ node.expr_type = "value" }else if(node.property.name == 'getPriority'){ node.expr_type = "fun():value" }else if(node.property.expr_type == 'rule'){ //not a recognised //cooertion from rule to value node.update(node.object.source() + ".child(" + node.property.source() + ".val())"); node.expr_type = "rule" }else if(node.property.expr_type == 'value'){ //not recognised member, so it must be an implicit child relation (without quotes in child) if (node.property.label && !isArraySyntaxMemberExpression(node)) { //data.a should stay as property.a, we don't want to use variable substitution in the property //so we use the orginal label node.update(node.object.source() + ".child('" + node.property.label + "')"); } else { //data[a] should stay as property.a, we don;t want to use variable substitution in the property //so we use the orginal label node.update(node.object.source() + ".child(" + node.property.source() + ")"); } node.expr_type = "rule" }else{ //not recognised member, so it must be an implicit child relation (with quotes in child) node.update(node.object.source() + ".child('" + node.property.source() + "')"); node.expr_type = "rule" } }else if(node.property.expr_type == 'rule'){ //not a recognised //cooertion from rule to value node.update(node.object.source() + ".child(" + node.property.source() + ".val())"); node.expr_type = "rule" }else if(node.property.expr_type == 'value'){ //not recognised member, so it must be an implicit child relation (without quotes in child) node.update(node.object.source() + ".child(" + node.property.source() + ")"); node.expr_type = "rule" } }else if(node.object.expr_type == "map"){//auth is a map, auth.* always goes to a value node.expr_type = "value" }else if(node.object.expr_type == "value"){ //inbuild methods for values node.expr_type = "value"; //inbuilt methods for value objects if(node.property.type == 'Identifier'){ if(node.property.name == 'contains'){ node.expr_type = "fun(value):value" }else if(node.property.name == 'replace'){ node.expr_type = "fun(value,value):value" }else if(node.property.name == 'toLowerCase'){ node.expr_type = "fun():value" }else if(node.property.name == 'toUpperCase'){ node.expr_type = "fun():value" }else if(node.property.name == 'beginsWith'){ node.expr_type = "fun():value" }else if(node.property.name == 'endsWith'){ node.expr_type = "fun():value" }else if(node.property.name == 'matches'){ node.expr_type = "fun(regex):value" } } } if(node.expr_type == null){ throw error.message("Bug: 3 Unexpected situation in type system " + node.object.expr_type + " " + node.property.expr_type).source(self.source).on(new Error()); } }else if(node.type == "CallExpression"){ if(node.callee.expr_type === "fun():rule"){ node.expr_type = "rule"; }else if(node.callee.expr_type === "fun():value"){ node.expr_type = "value"; }else if(node.callee.expr_type === "fun(array):rule"){ node.expr_type = "value"; }else if(node.callee.expr_type === "fun(value):value"){ node.expr_type = "value"; }else if(node.callee.expr_type === "fun(array):value"){ node.expr_type = "value"; }else if(node.callee.expr_type === "fun(regex):value"){ node.expr_type = "value"; }else if(node.callee.expr_type === "fun(value,value):value"){ node.expr_type = "value"; }else if(node.callee.expr_type === "pred"){ //console.log(node) //we are calling a user defined function var fun: Function = symbols.functions[node.callee.name]; //clone the global symbol table and populate with binding to parameters var function_symbols = symbols.clone(); var params = node.arguments; for(var p_index in params){ var p_node = params[p_index]; var local_name = fun.parameter_map[p_index]; function_symbols.variables[local_name] = p_node; } var expansion = fun.expression.generate(function_symbols); node.update("(" + expansion + ")"); node.expr_type = "value"; }else{ if (node.callee.type == 'MemberExpression' && node.callee.property.type == 'Identifier' && node.callee.property.name == 'child') { throw error.message("parent.child(<name>) syntax is not supported in Blaze, use parent.<name> or parent[<name>] instead").source(self.source).on(new Error()); } else { var uncoerced = [ 'contains', 'toLowerCase', 'replace', 'toUpperCase', 'beginsWith', 'endsWith', 'matches' ]; if (node.callee.property != null && uncoerced.indexOf(node.callee.property.name) >=0 ) { throw error.message("Unexpected situation in type system on '" + node.source() + "', (you probably forgot to use .val() before using an inbuilt method)").source(self.source).on(new Error()); } else { throw error.message("Bug: 4 Unexpected situation in type system on '" + node.callee.expr_type + "'").source(self.source).on(new Error()); } } } }else if(node.type == "BinaryExpression" || node.type == "BooleanExpression" || node.type == "LogicalExpression"){ //coersion to value, if a rule (i.e. appending .val() when in a binary operator as ruleSnapshots don't support any binary operators) if(node.left.expr_type === "rule"){ node.left.update(node.left.source() + ".val()"); } if(node.right.expr_type === "rule"){ node.right.update(node.right.source() + ".val()"); } node.expr_type = "value" }else if(node.type == "UnaryExpression"){ node.expr_type = node.argument.expr_type; }else if(node.type == "ExpressionStatement"){ }else if(node.type == "Program"){ }else{ throw error.message("Bug: 5 Unrecognised Type In Expression Parser: " + node.type).source(self.source).on(new Error()); } }; var code: string = falafel(this.raw, {}, falafel_visitor).toString(); return globals.optimize ? optimizer.optimizeAndTrim(code): optimizer.simplify(code); } } /** * figures out whether this is data.a or data[a] syntax * @param node */ function isArraySyntaxMemberExpression (node): boolean { return node.source().slice(node.object.source().length).trim().charAt(0) == '['; }
the_stack
import {CATEGORY_SOP} from './Category'; import {AddSopNode} from '../../../nodes/sop/Add'; import {AnimationCopySopNode} from '../../../nodes/sop/AnimationCopy'; import {AnimationMixerSopNode} from '../../../nodes/sop/AnimationMixer'; import {AttribAddMultSopNode} from '../../../nodes/sop/AttribAddMult'; import {AttribCastSopNode} from '../../../nodes/sop/AttribCast'; import {AttribCopySopNode} from '../../../nodes/sop/AttribCopy'; import {AttribCreateSopNode} from '../../../nodes/sop/AttribCreate'; import {AttribDeleteSopNode} from '../../../nodes/sop/AttribDelete'; import {AttribFromTextureSopNode} from '../../../nodes/sop/AttribFromTexture'; import {AttribNormalizeSopNode} from '../../../nodes/sop/AttribNormalize'; import {AttribPromoteSopNode} from '../../../nodes/sop/AttribPromote'; import {AttribRemapSopNode} from '../../../nodes/sop/AttribRemap'; import {AttribRenameSopNode} from '../../../nodes/sop/AttribRename'; import {AttribTransferSopNode} from '../../../nodes/sop/AttribTransfer'; import {BboxScatterSopNode} from '../../../nodes/sop/BboxScatter'; import {BlendSopNode} from '../../../nodes/sop/Blend'; import {BooleanSopNode} from '../../../nodes/sop/Boolean'; import {BoxSopNode} from '../../../nodes/sop/Box'; import {CacheSopNode} from '../../../nodes/sop/Cache'; import {CameraPlaneSopNode} from '../../../nodes/sop/CameraPlane'; import {CenterSopNode} from '../../../nodes/sop/Center'; import {CircleSopNode} from '../../../nodes/sop/Circle'; import {Circle3PointsSopNode} from '../../../nodes/sop/Circle3Points'; // import {CodeSopNode} from '../../../nodes/sop/Code'; import {ColorSopNode} from '../../../nodes/sop/Color'; import {ConeSopNode} from '../../../nodes/sop/Cone'; import {CopySopNode} from '../../../nodes/sop/Copy'; import {CSS2DObjectSopNode} from '../../../nodes/sop/CSS2DObject'; import {CSS3DObjectSopNode} from '../../../nodes/sop/CSS3DObject'; import {DataSopNode} from '../../../nodes/sop/Data'; import {DataUrlSopNode} from '../../../nodes/sop/DataUrl'; import {DecalSopNode} from '../../../nodes/sop/Decal'; import {DelaySopNode} from '../../../nodes/sop/Delay'; import {DeleteSopNode} from '../../../nodes/sop/Delete'; import {DrawRangeSopNode} from '../../../nodes/sop/DrawRange'; import {ExporterSopNode} from '../../../nodes/sop/Exporter'; import {FaceSopNode} from '../../../nodes/sop/Face'; import {FileSopNode} from '../../../nodes/sop/File'; import {FuseSopNode} from '../../../nodes/sop/Fuse'; import {HexagonsSopNode} from '../../../nodes/sop/Hexagons'; import {HierarchySopNode} from '../../../nodes/sop/Hierarchy'; import {HeightMapSopNode} from '../../../nodes/sop/HeightMap'; import {IcosahedronSopNode} from '../../../nodes/sop/Icosahedron'; import {InstanceSopNode} from '../../../nodes/sop/Instance'; import {InstancesCountSopNode} from '../../../nodes/sop/InstancesCount'; import {JitterSopNode} from '../../../nodes/sop/Jitter'; import {JsPointSopNode} from '../../../nodes/sop/JsPoint'; import {LayerSopNode} from '../../../nodes/sop/Layer'; import {LineSopNode} from '../../../nodes/sop/Line'; import {LodSopNode} from '../../../nodes/sop/Lod'; import {MaterialSopNode} from '../../../nodes/sop/Material'; import {MediapipeFaceMeshSopNode} from '../../../nodes/sop/MediapipeFaceMesh'; import {MergeSopNode} from '../../../nodes/sop/Merge'; import {NoiseSopNode} from '../../../nodes/sop/Noise'; import {NormalsSopNode} from '../../../nodes/sop/Normals'; import {NullSopNode} from '../../../nodes/sop/Null'; import {ObjectMergeSopNode} from '../../../nodes/sop/ObjectMerge'; import {ObjectPropertiesSopNode} from '../../../nodes/sop/ObjectProperties'; import {OperationsComposerSopNode} from '../../../nodes/sop/OperationsComposer'; import {ParticlesSystemGpuSopNode} from '../../../nodes/sop/ParticlesSystemGpu'; import {PeakSopNode} from '../../../nodes/sop/Peak'; import {PlaneSopNode} from '../../../nodes/sop/Plane'; import {PointSopNode} from '../../../nodes/sop/Point'; import {PointLightSopNode} from '../../../nodes/sop/PointLight'; import {PolarTransformSopNode} from '../../../nodes/sop/PolarTransform'; import {PolySopNode} from '../../../nodes/sop/Poly'; import {PolywireSopNode} from '../../../nodes/sop/Polywire'; import {RaySopNode} from '../../../nodes/sop/Ray'; import {ReflectorSopNode} from '../../../nodes/sop/Reflector'; import {ResampleSopNode} from '../../../nodes/sop/Resample'; import {RestAttributesSopNode} from '../../../nodes/sop/RestAttributes'; import {RoundedBoxSopNode} from '../../../nodes/sop/RoundedBox'; import {ScatterSopNode} from '../../../nodes/sop/Scatter'; import {ShearSopNode} from '../../../nodes/sop/Shear'; import {SkinSopNode} from '../../../nodes/sop/Skin'; import {SortSopNode} from '../../../nodes/sop/Sort'; import {SolverSopNode} from '../../../nodes/sop/Solver'; import {SolverPreviousFrameSopNode} from '../../../nodes/sop/SolverPreviousFrame'; import {SphereSopNode} from '../../../nodes/sop/Sphere'; import {SplitSopNode} from '../../../nodes/sop/Split'; import {SubdivideSopNode} from '../../../nodes/sop/Subdivide'; import {SubnetSopNode} from '../../../nodes/sop/Subnet'; import {SubnetInputSopNode} from '../../../nodes/sop/SubnetInput'; import {SubnetOutputSopNode} from '../../../nodes/sop/SubnetOutput'; import {SvgSopNode} from '../../../nodes/sop/Svg'; import {SwitchSopNode} from '../../../nodes/sop/Switch'; import {TetrahedronSopNode} from '../../../nodes/sop/Tetrahedron'; import {TextSopNode} from '../../../nodes/sop/Text'; import {TextureCopySopNode} from '../../../nodes/sop/TextureCopy'; import {TexturePropertiesSopNode} from '../../../nodes/sop/TextureProperties'; import {TorusSopNode} from '../../../nodes/sop/Torus'; import {TorusKnotSopNode} from '../../../nodes/sop/TorusKnot'; import {TransformSopNode} from '../../../nodes/sop/Transform'; import {TransformCopySopNode} from '../../../nodes/sop/TransformCopy'; import {TransformMultiSopNode} from '../../../nodes/sop/TransformMulti'; import {TransformResetSopNode} from '../../../nodes/sop/TransformReset'; import {TubeSopNode} from '../../../nodes/sop/Tube'; import {UvLayoutSopNode} from '../../../nodes/sop/UvLayout'; import {UvProjectSopNode} from '../../../nodes/sop/UvProject'; import {UvTransformSopNode} from '../../../nodes/sop/UvTransform'; import {UvUnwrapSopNode} from '../../../nodes/sop/UvUnwrap'; // networks import {AnimationsNetworkSopNode} from '../../../nodes/sop/AnimationsNetwork'; import {CopNetworkSopNode} from '../../../nodes/sop/CopNetwork'; import {EventsNetworkSopNode} from '../../../nodes/sop/EventsNetwork'; import {MaterialsNetworkSopNode} from '../../../nodes/sop/MaterialsNetwork'; import {PostProcessNetworkSopNode} from '../../../nodes/sop/PostProcessNetwork'; import {RenderersNetworkSopNode} from '../../../nodes/sop/RenderersNetwork'; export interface GeoNodeChildrenMap { add: AddSopNode; animationCopy: AnimationCopySopNode; animationMixer: AnimationMixerSopNode; attribAddMult: AttribAddMultSopNode; attribCast: AttribCastSopNode; attribCopy: AttribCopySopNode; attribCreate: AttribCreateSopNode; attribDelete: AttribDeleteSopNode; attribFromTexture: AttribFromTextureSopNode; attribNormalize: AttribNormalizeSopNode; attribPromote: AttribPromoteSopNode; attribRemap: AttribRemapSopNode; attribRename: AttribRenameSopNode; attribTransfer: AttribTransferSopNode; bboxScatter: BboxScatterSopNode; blend: BlendSopNode; boolean: BooleanSopNode; box: BoxSopNode; cache: CacheSopNode; cameraPlane: CameraPlaneSopNode; center: CenterSopNode; circle: CircleSopNode; circle3Points: Circle3PointsSopNode; // code: CodeSopNode; color: ColorSopNode; cone: ConeSopNode; copy: CopySopNode; CSS2DObject: CSS2DObjectSopNode; CSS3DObject: CSS3DObjectSopNode; data: DataSopNode; dataUrl: DataUrlSopNode; decal: DecalSopNode; delay: DelaySopNode; delete: DeleteSopNode; drawRange: DrawRangeSopNode; exporter: ExporterSopNode; face: FaceSopNode; file: FileSopNode; fuse: FuseSopNode; heightMap: HeightMapSopNode; hexagons: HexagonsSopNode; hierarchy: HierarchySopNode; icosahedron: IcosahedronSopNode; instance: InstanceSopNode; instancesCount: InstancesCountSopNode; jitter: JitterSopNode; jsPoint: JsPointSopNode; layer: LayerSopNode; line: LineSopNode; lod: LodSopNode; material: MaterialSopNode; mediapipeFaceMesh: MediapipeFaceMeshSopNode; merge: MergeSopNode; noise: NoiseSopNode; normals: NormalsSopNode; null: NullSopNode; objectMerge: ObjectMergeSopNode; objectProperties: ObjectPropertiesSopNode; operationsComposer: OperationsComposerSopNode; particlesSystemGpu: ParticlesSystemGpuSopNode; peak: PeakSopNode; plane: PlaneSopNode; point: PointSopNode; pointLight: PointLightSopNode; polarTransform: PolarTransformSopNode; poly: PolySopNode; polywire: PolywireSopNode; ray: RaySopNode; reflector: ReflectorSopNode; resample: ResampleSopNode; restAttributes: RestAttributesSopNode; roundedBox: RoundedBoxSopNode; scatter: ScatterSopNode; shear: ShearSopNode; skin: SkinSopNode; solver: SolverSopNode; solverPreviousFrame: SolverPreviousFrameSopNode; sort: SortSopNode; sphere: SphereSopNode; split: SplitSopNode; subdivide: SubdivideSopNode; subnet: SubnetSopNode; subnetInput: SubnetInputSopNode; subnetOutput: SubnetOutputSopNode; svg: SvgSopNode; switch: SwitchSopNode; tetrahedron: TetrahedronSopNode; text: TextSopNode; textureCopy: TextureCopySopNode; textureProperties: TexturePropertiesSopNode; torus: TorusSopNode; torusKnot: TorusKnotSopNode; transform: TransformSopNode; transformCopy: TransformCopySopNode; transformMulti: TransformMultiSopNode; transformReset: TransformResetSopNode; tube: TubeSopNode; uvLayout: UvProjectSopNode; uvProject: UvProjectSopNode; uvTransform: UvTransformSopNode; uvUnwrap: UvUnwrapSopNode; // networks animationsNetwork: AnimationsNetworkSopNode; copNetwork: CopNetworkSopNode; eventsNetwork: EventsNetworkSopNode; materialsNetwork: MaterialsNetworkSopNode; postProcessNetwork: PostProcessNetworkSopNode; renderersNetwork: RenderersNetworkSopNode; } import {AddSopOperation} from '../../../operations/sop/Add'; import {AttribAddMultSopOperation} from '../../../operations/sop/AttribAddMult'; import {AttribCastSopOperation} from '../../../operations/sop/AttribCast'; import {AttribCopySopOperation} from '../../../operations/sop/AttribCopy'; import {AttribCreateSopOperation} from '../../../operations/sop/AttribCreate'; import {AttribNormalizeSopOperation} from '../../../operations/sop/AttribNormalize'; import {AttribFromTextureSopOperation} from '../../../operations/sop/AttribFromTexture'; import {AttribPromoteSopOperation} from '../../../operations/sop/AttribPromote'; import {BooleanSopOperation} from '../../../operations/sop/Boolean'; import {BoxSopOperation} from '../../../operations/sop/Box'; import {CenterSopOperation} from '../../../operations/sop/Center'; import {CircleSopOperation} from '../../../operations/sop/Circle'; import {CSS2DObjectSopOperation} from '../../../operations/sop/CSS2DObject'; import {DecalSopOperation} from '../../../operations/sop/Decal'; import {FileSopOperation} from '../../../operations/sop/File'; import {HierarchySopOperation} from '../../../operations/sop/Hierarchy'; import {IcosahedronSopOperation} from '../../../operations/sop/Icosahedron'; import {InstanceSopOperation} from '../../../operations/sop/Instance'; import {JitterSopOperation} from '../../../operations/sop/Jitter'; import {MergeSopOperation} from '../../../operations/sop/Merge'; import {MaterialSopOperation} from '../../../operations/sop/Material'; import {NullSopOperation} from '../../../operations/sop/Null'; import {ObjectPropertiesSopOperation} from '../../../operations/sop/ObjectProperties'; import {PeakSopOperation} from '../../../operations/sop/Peak'; import {PlaneSopOperation} from '../../../operations/sop/Plane'; import {PolarTransformSopOperation} from '../../../operations/sop/PolarTransform'; import {PointLightSopOperation} from '../../../operations/sop/PointLight'; import {RaySopOperation} from '../../../operations/sop/Ray'; import {ReflectorSopOperation} from '../../../operations/sop/Reflector'; import {RestAttributesSopOperation} from '../../../operations/sop/RestAttributes'; import {RoundedBoxSopOperation} from '../../../operations/sop/RoundedBox'; import {ScatterSopOperation} from '../../../operations/sop/Scatter'; import {ShearSopOperation} from '../../../operations/sop/Shear'; import {SortSopOperation} from '../../../operations/sop/Sort'; import {SphereSopOperation} from '../../../operations/sop/Sphere'; import {SubdivideSopOperation} from '../../../operations/sop/Subdivide'; import {SvgSopOperation} from '../../../operations/sop/Svg'; import {TextureCopySopOperation} from '../../../operations/sop/TextureCopy'; import {TexturePropertiesSopOperation} from '../../../operations/sop/TextureProperties'; import {TorusSopOperation} from '../../../operations/sop/Torus'; import {TorusKnotSopOperation} from '../../../operations/sop/TorusKnot'; import {TransformSopOperation} from '../../../operations/sop/Transform'; import {UvLayoutSopOperation} from '../../../operations/sop/UvLayout'; import {UvTransformSopOperation} from '../../../operations/sop/UvTransform'; import {UvUnwrapSopOperation} from '../../../operations/sop/UvUnwrap'; import {PolyEngine} from '../../../Poly'; export class SopRegister { static run(poly: PolyEngine) { poly.registerOperation(AddSopOperation); poly.registerOperation(AttribAddMultSopOperation); poly.registerOperation(AttribCastSopOperation); poly.registerOperation(AttribCopySopOperation); poly.registerOperation(AttribCreateSopOperation); poly.registerOperation(AttribNormalizeSopOperation); poly.registerOperation(AttribFromTextureSopOperation); poly.registerOperation(AttribPromoteSopOperation); poly.registerOperation(BooleanSopOperation); poly.registerOperation(BoxSopOperation); poly.registerOperation(CenterSopOperation); poly.registerOperation(CircleSopOperation); poly.registerOperation(CSS2DObjectSopOperation); poly.registerOperation(DecalSopOperation); poly.registerOperation(FileSopOperation); poly.registerOperation(HierarchySopOperation); poly.registerOperation(IcosahedronSopOperation); poly.registerOperation(InstanceSopOperation); poly.registerOperation(JitterSopOperation); poly.registerOperation(MergeSopOperation); poly.registerOperation(MaterialSopOperation); poly.registerOperation(NullSopOperation); poly.registerOperation(ObjectPropertiesSopOperation); poly.registerOperation(PeakSopOperation); poly.registerOperation(PlaneSopOperation); poly.registerOperation(PointLightSopOperation); poly.registerOperation(PolarTransformSopOperation); poly.registerOperation(RaySopOperation); poly.registerOperation(ReflectorSopOperation); poly.registerOperation(RestAttributesSopOperation); poly.registerOperation(RoundedBoxSopOperation); poly.registerOperation(ScatterSopOperation); poly.registerOperation(ShearSopOperation); poly.registerOperation(SortSopOperation); poly.registerOperation(SphereSopOperation); poly.registerOperation(SubdivideSopOperation); poly.registerOperation(SvgSopOperation); poly.registerOperation(TextureCopySopOperation); poly.registerOperation(TexturePropertiesSopOperation); poly.registerOperation(TorusSopOperation); poly.registerOperation(TorusKnotSopOperation); poly.registerOperation(TransformSopOperation); poly.registerOperation(UvLayoutSopOperation); poly.registerOperation(UvTransformSopOperation); poly.registerOperation(UvUnwrapSopOperation); poly.registerNode(AddSopNode, CATEGORY_SOP.INPUT); poly.registerNode(AnimationCopySopNode, CATEGORY_SOP.ANIMATION); poly.registerNode(AnimationMixerSopNode, CATEGORY_SOP.ANIMATION); poly.registerNode(AttribAddMultSopNode, CATEGORY_SOP.ATTRIBUTE); poly.registerNode(AttribCastSopNode, CATEGORY_SOP.ATTRIBUTE); poly.registerNode(AttribCopySopNode, CATEGORY_SOP.ATTRIBUTE); poly.registerNode(AttribCreateSopNode, CATEGORY_SOP.ATTRIBUTE); poly.registerNode(AttribDeleteSopNode, CATEGORY_SOP.ATTRIBUTE); poly.registerNode(AttribFromTextureSopNode, CATEGORY_SOP.ATTRIBUTE); poly.registerNode(AttribNormalizeSopNode, CATEGORY_SOP.ATTRIBUTE); poly.registerNode(AttribPromoteSopNode, CATEGORY_SOP.ATTRIBUTE); poly.registerNode(AttribRemapSopNode, CATEGORY_SOP.ATTRIBUTE); poly.registerNode(AttribRenameSopNode, CATEGORY_SOP.ATTRIBUTE); poly.registerNode(AttribTransferSopNode, CATEGORY_SOP.ATTRIBUTE); poly.registerNode(BboxScatterSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(BlendSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(BooleanSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(BoxSopNode, CATEGORY_SOP.PRIMITIVES); poly.registerNode(CacheSopNode, CATEGORY_SOP.MISC); poly.registerNode(CameraPlaneSopNode, CATEGORY_SOP.PRIMITIVES); poly.registerNode(CenterSopNode, CATEGORY_SOP.PRIMITIVES); poly.registerNode(CircleSopNode, CATEGORY_SOP.PRIMITIVES); poly.registerNode(Circle3PointsSopNode, CATEGORY_SOP.PRIMITIVES); // poly.registerNode(CodeSopNode, CATEGORY_SOP.ADVANCED); poly.registerNode(ColorSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(ConeSopNode, CATEGORY_SOP.PRIMITIVES); poly.registerNode(CopySopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(CSS2DObjectSopNode, CATEGORY_SOP.PRIMITIVES); // poly.registerNode(Css3DObjectSopNode, CATEGORY_SOP.PRIMITIVES); // not working yet poly.registerNode(DataSopNode, CATEGORY_SOP.INPUT); poly.registerNode(DataUrlSopNode, CATEGORY_SOP.INPUT); poly.registerNode(DecalSopNode, CATEGORY_SOP.MISC); poly.registerNode(DelaySopNode, CATEGORY_SOP.MISC); poly.registerNode(DeleteSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(DrawRangeSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(ExporterSopNode, CATEGORY_SOP.ADVANCED); poly.registerNode(FaceSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(FileSopNode, CATEGORY_SOP.INPUT); poly.registerNode(FuseSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(HexagonsSopNode, CATEGORY_SOP.PRIMITIVES); poly.registerNode(HeightMapSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(HierarchySopNode, CATEGORY_SOP.MISC); poly.registerNode(IcosahedronSopNode, CATEGORY_SOP.PRIMITIVES); poly.registerNode(InstanceSopNode, CATEGORY_SOP.RENDER); poly.registerNode(InstancesCountSopNode, CATEGORY_SOP.RENDER); poly.registerNode(JitterSopNode, CATEGORY_SOP.MODIFIER); if (process.env.NODE_ENV == 'development') { poly.registerNode(JsPointSopNode, CATEGORY_SOP.ADVANCED); } poly.registerNode(LayerSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(LineSopNode, CATEGORY_SOP.PRIMITIVES); poly.registerNode(LodSopNode, CATEGORY_SOP.ADVANCED); poly.registerNode(MaterialSopNode, CATEGORY_SOP.RENDER); poly.registerNode(MediapipeFaceMeshSopNode, CATEGORY_SOP.ADVANCED); poly.registerNode(MergeSopNode, CATEGORY_SOP.MISC); poly.registerNode(NoiseSopNode, CATEGORY_SOP.MISC); poly.registerNode(NormalsSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(NullSopNode, CATEGORY_SOP.MISC); poly.registerNode(ObjectMergeSopNode, CATEGORY_SOP.INPUT); poly.registerNode(ObjectPropertiesSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(OperationsComposerSopNode, CATEGORY_SOP.ADVANCED, {userAllowed: false}); poly.registerNode(ParticlesSystemGpuSopNode, CATEGORY_SOP.DYNAMICS); poly.registerNode(PeakSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(PlaneSopNode, CATEGORY_SOP.PRIMITIVES); poly.registerNode(PolarTransformSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(PointSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(PointLightSopNode, CATEGORY_SOP.LIGHTS); poly.registerNode(PolySopNode, CATEGORY_SOP.ADVANCED); poly.registerNode(PolywireSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(RaySopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(ReflectorSopNode, CATEGORY_SOP.RENDER); poly.registerNode(ResampleSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(RestAttributesSopNode, CATEGORY_SOP.ATTRIBUTE); poly.registerNode(RoundedBoxSopNode, CATEGORY_SOP.INPUT); poly.registerNode(ScatterSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(SkinSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(ShearSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(SolverSopNode, CATEGORY_SOP.ADVANCED); poly.registerNode(SolverPreviousFrameSopNode, CATEGORY_SOP.ADVANCED); poly.registerNode(SortSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(SphereSopNode, CATEGORY_SOP.PRIMITIVES); poly.registerNode(SplitSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(SubdivideSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(SubnetSopNode, CATEGORY_SOP.MISC); poly.registerNode( SubnetInputSopNode, CATEGORY_SOP.MISC /*{ // TODO: use "except" so that it works inside PolyNodes // only: [`${NodeContext.SOP}/${SubnetSopNode.type()}`, `${NodeContext.SOP}/poly`], }*/ ); poly.registerNode( SubnetOutputSopNode, CATEGORY_SOP.MISC /*{ // only: [`${NodeContext.SOP}/${SubnetSopNode.type()}`, `${NodeContext.SOP}/poly`], }*/ ); poly.registerNode(SvgSopNode, CATEGORY_SOP.INPUT); poly.registerNode(SwitchSopNode, CATEGORY_SOP.MISC); poly.registerNode(TetrahedronSopNode, CATEGORY_SOP.PRIMITIVES); poly.registerNode(TextSopNode, CATEGORY_SOP.PRIMITIVES); poly.registerNode(TextureCopySopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(TexturePropertiesSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(TorusSopNode, CATEGORY_SOP.PRIMITIVES); poly.registerNode(TorusKnotSopNode, CATEGORY_SOP.PRIMITIVES); poly.registerNode(TransformSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(TransformCopySopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(TransformMultiSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(TransformResetSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(TubeSopNode, CATEGORY_SOP.PRIMITIVES); poly.registerNode(UvLayoutSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(UvProjectSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(UvTransformSopNode, CATEGORY_SOP.MODIFIER); poly.registerNode(UvUnwrapSopNode, CATEGORY_SOP.MODIFIER); // networks poly.registerNode(AnimationsNetworkSopNode, CATEGORY_SOP.NETWORK); poly.registerNode(CopNetworkSopNode, CATEGORY_SOP.NETWORK); poly.registerNode(EventsNetworkSopNode, CATEGORY_SOP.NETWORK); poly.registerNode(MaterialsNetworkSopNode, CATEGORY_SOP.NETWORK); poly.registerNode(PostProcessNetworkSopNode, CATEGORY_SOP.NETWORK); poly.registerNode(RenderersNetworkSopNode, CATEGORY_SOP.NETWORK); } }
the_stack
declare namespace WebAssembly { interface Module {} } declare namespace Emscripten { interface FileSystemType {} type EnvironmentType = "WEB" | "NODE" | "SHELL" | "WORKER"; type ValueType = "number" | "string" | "array" | "boolean"; type TypeCompatibleWithC = number | string | any[] | boolean; type WebAssemblyImports = Array<{ name: string; kind: string; }>; type WebAssemblyExports = Array<{ module: string; name: string; kind: string; }>; interface CCallOpts { async?: boolean; } } interface EmscriptenModule { print(str: string): void; printErr(str: string): void; arguments: string[]; environment: Emscripten.EnvironmentType; preInit: Array<{ (): void }>; preRun: Array<{ (): void }>; postRun: Array<{ (): void }>; onAbort: { (what: any): void }; onRuntimeInitialized: { (): void }; preinitializedWebGLContext: WebGLRenderingContext; noInitialRun: boolean; noExitRuntime: boolean; logReadFiles: boolean; filePackagePrefixURL: string; wasmBinary: ArrayBuffer; destroy(object: object): void; getPreloadedPackage( remotePackageName: string, remotePackageSize: number ): ArrayBuffer; instantiateWasm( imports: Emscripten.WebAssemblyImports, successCallback: (module: WebAssembly.Module) => void ): Emscripten.WebAssemblyExports; locateFile(url: string): string; onCustomMessage(event: MessageEvent): void; Runtime: any; ccall( ident: string, returnType: Emscripten.ValueType | null, argTypes: Emscripten.ValueType[], args: Emscripten.TypeCompatibleWithC[], opts?: Emscripten.CCallOpts ): any; cwrap( ident: string, returnType: Emscripten.ValueType | null, argTypes: Emscripten.ValueType[], opts?: Emscripten.CCallOpts ): (...args: any[]) => any; setValue(ptr: number, value: any, type: string, noSafe?: boolean): void; getValue(ptr: number, type: string, noSafe?: boolean): number; ALLOC_NORMAL: number; ALLOC_STACK: number; ALLOC_STATIC: number; ALLOC_DYNAMIC: number; ALLOC_NONE: number; allocate( slab: any, types: string | string[], allocator: number, ptr: number ): number; // USE_TYPED_ARRAYS == 1 HEAP: Int32Array; IHEAP: Int32Array; FHEAP: Float64Array; // USE_TYPED_ARRAYS == 2 HEAP8: Int8Array; HEAP16: Int16Array; HEAP32: Int32Array; HEAPU8: Uint8Array; HEAPU16: Uint16Array; HEAPU32: Uint32Array; HEAPF32: Float32Array; HEAPF64: Float64Array; TOTAL_STACK: number; TOTAL_MEMORY: number; FAST_MEMORY: number; addOnPreRun(cb: () => any): void; addOnInit(cb: () => any): void; addOnPreMain(cb: () => any): void; addOnExit(cb: () => any): void; addOnPostRun(cb: () => any): void; // Tools intArrayFromString( stringy: string, dontAddNull?: boolean, length?: number ): number[]; intArrayToString(array: number[]): string; writeStringToMemory(str: string, buffer: number, dontAddNull: boolean): void; writeArrayToMemory(array: number[], buffer: number): void; writeAsciiToMemory(str: string, buffer: number, dontAddNull: boolean): void; addRunDependency(id: any): void; removeRunDependency(id: any): void; preloadedImages: any; preloadedAudios: any; _malloc(size: number): number; _free(ptr: number): void; // Exported Functions - LB FS: EmscriptenFileSysten; UTF8ToString(ptr: number, maxBytesToRead?: number): string; getversion(ptr: number): number; geterror(errorCode: number, ptr: number): number; Epanet: EpanetProjectConstructable; } // EPANET interface EpanetProjectConstructable { new (): EpanetProject; } interface EpanetProject { // Generated methods //Project Functions open(inputFile: string, reportFile: string, outputFile: string): number; close(): number; runproject(inputFile: string, reportFile: string, outputFile: string): number; init( reportFile: string, outputFile: string, unitsType: number, headLossType: number ): number; getcount(obj: number, count: number): number; gettitle(out_line1: number, out_line2: number, out_line3: number): number; settitle(line1: string, line2: string, line3: string): number; saveinpfile(filename: string): number; // Hydraulic Analysis Functions solveH(): number; usehydfile(filename: string): number; openH(): number; initH(initFlag: number): number; runH(currentTime: number): number; nextH(tStep: number): number; saveH(): number; savehydfile(filename: string): number; closeH(): number; // Water Quality Analysis Functions solveQ(): number; openQ(): number; initQ(initFlag: number): number; runQ(currentTime: number): number; nextQ(tStep: number): number; stepQ(timeLeft: number): number; closeQ(): number; // Reporting Functions writeline(line: string): number; report(): number; copyreport(filename: string): number; clearreport(): number; resetreport(): number; setreport(format: string): number; setstatusreport(level: number): number; getstatistic(type: number, value: number): number; getresultindex(type: number, index: number, value: number): number; // Analysis Options Functions getflowunits(units: number): number; getoption(option: number, value: number): number; getqualinfo( qualType: number, out_chemName: number, out_chemUnits: number, traceNode: number ): number; getqualtype(qualType: number, traceNode: number): number; gettimeparam(param: number, value: number): number; setflowunits(units: number): number; setoption(option: number, value: number): number; setqualtype( qualType: number, chemName: string, chemUnits: string, traceNode: string ): number; settimeparam(param: number, value: number): number; // Network Node Functions addnode(id: string, nodeType: number, index: number): number; deletenode(index: number, actionCode: number): number; getnodeindex(id: string, index: number): number; getnodeid(index: number, out_id: number): number; setnodeid(index: number, newid: string): number; getnodetype(index: number, nodeType: number): number; getnodevalue(index: number, property: number, value: number): number; setnodevalue(index: number, property: number, value: number): number; setjuncdata( index: number, elev: number, dmnd: number, dmndpat: string ): number; settankdata( index: number, elev: number, initlvl: number, minlvl: number, maxlvl: number, diam: number, minvol: number, volcurve: string ): number; getcoord(index: number, x: number, y: number): number; setcoord(index: number, x: number, y: number): number; //Nodal Demand Functions adddemand( nodeIndex: number, baseDemand: number, demandPattern: string, demandName: string ): number; deletedemand(nodeIndex: number, demandIndex: number): number; getbasedemand( nodeIndex: number, demandIndex: number, baseDemand: number ): number; getdemandindex( nodeIndex: number, demandName: string, demandIndex: number ): number; getdemandmodel( type: number, pmin: number, preq: number, pexp: number ): number; getdemandname( nodeIndex: number, demandIndex: number, out_demandName: number ): number; getdemandpattern( nodeIndex: number, demandIndex: number, patIndex: number ): number; getnumdemands(nodeIndex: number, numDemands: number): number; setbasedemand( nodeIndex: number, demandIndex: number, baseDemand: number ): number; setdemandmodel( type: number, pmin: number, preq: number, pexp: number ): number; setdemandname( nodeIndex: number, demandIdx: number, demandName: string ): number; setdemandpattern( nodeIndex: number, demandIndex: number, patIndex: number ): number; // Network Link Functions addlink( id: string, linkType: number, fromNode: string, toNode: string, index: number ): number; deletelink(index: number, actionCode: number): number; getlinkindex(id: string, index: number): number; getlinkid(index: number, out_id: number): number; setlinkid(index: number, newid: string): number; getlinktype(index: number, linkType: number): number; setlinktype( inout_index: number, linkType: number, actionCode: number ): number; getlinknodes(index: number, node1: number, node2: number): number; setlinknodes(index: number, node1: number, node2: number): number; getlinkvalue(index: number, property: number, value: number): number; setlinkvalue(index: number, property: number, value: number): number; setpipedata( index: number, length: number, diam: number, rough: number, mloss: number ): number; getpumptype(linkIndex: number, pumpType: number): number; getheadcurveindex(linkIndex: number, curveIndex: number): number; setheadcurveindex(linkIndex: number, curveIndex: number): number; getvertexcount(index: number, count: number): number; getvertex(index: number, vertex: number, x: number, y: number): number; setvertices(index: number, x: number, y: number, count: number): number; // Time Pattern Functions addpattern(id: string): number; deletepattern(index: number): number; getpatternindex(id: string, index: number): number; getpatternid(index: number, out_id: number): number; setpatternid(index: number, id: string): number; getpatternlen(index: number, len: number): number; getpatternvalue(index: number, period: number, value: number): number; setpatternvalue(index: number, period: number, value: number): number; getaveragepatternvalue(index: number, value: number): number; setpattern(index: number, values: number, len: number): number; // Data Curve Functions addcurve(id: string): number; deletecurve(index: number): number; getcurveindex(id: string, index: number): number; getcurveid(index: number, out_id: number): number; setcurveid(index: number, id: string): number; getcurvelen(index: number, len: number): number; getcurvetype(index: number, type: number): number; getcurvevalue( curveIndex: number, pointIndex: number, x: number, y: number ): number; setcurvevalue( curveIndex: number, pointIndex: number, x: number, y: number ): number; setcurve( index: number, xValues: number, yValues: number, nPoints: number ): number; // Simple Control Functions addcontrol( type: number, linkIndex: number, setting: number, nodeIndex: number, level: number, index: number ): number; deletecontrol(index: number): number; getcontrol( index: number, type: number, linkIndex: number, setting: number, nodeIndex: number, level: number ): number; setcontrol( index: number, type: number, linkIndex: number, setting: number, nodeIndex: number, level: number ): number; // Rule-Based Control Functions addrule(rule: string): number; deleterule(index: number): number; getrule( index: number, nPremises: number, nThenActions: number, nElseActions: number, priority: number ): number; getruleID(index: number, out_id: number): number; getpremise( ruleIndex: number, premiseIndex: number, logop: number, object: number, objIndex: number, variable: number, relop: number, status: number, value: number ): number; setpremise( ruleIndex: number, premiseIndex: number, logop: number, object: number, objIndex: number, variable: number, relop: number, status: number, value: number ): number; setpremiseindex( ruleIndex: number, premiseIndex: number, objIndex: number ): number; setpremisestatus( ruleIndex: number, premiseIndex: number, status: number ): number; setpremisevalue( ruleIndex: number, premiseIndex: number, value: number ): number; getthenaction( ruleIndex: number, actionIndex: number, linkIndex: number, status: number, setting: number ): number; setthenaction( ruleIndex: number, actionIndex: number, linkIndex: number, status: number, setting: number ): number; getelseaction( ruleIndex: number, actionIndex: number, linkIndex: number, status: number, setting: number ): number; setelseaction( ruleIndex: number, actionIndex: number, linkIndex: number, status: number, setting: number ): number; setrulepriority(index: number, priority: number): number; } // By default Emscripten emits a single global Module. Users setting -s // MODULARIZE=1 -s EXPORT_NAME=MyMod should declare their own types, e.g. // declare var MyMod: EmscriptenModule; declare var Module: EmscriptenModule; interface EmscriptenFileSysten { readFile( path: string, opts?: { encoding?: "binary" | "utf8"; flags?: string } ): string | Uint8Array; writeFile( path: string, data: string | ArrayBufferView, opts?: { flags?: string } ): void; } declare namespace FS { interface Lookup { path: string; node: FSNode; } interface FSStream {} interface FSNode {} interface ErrnoError {} let ignorePermissions: boolean; let trackingDelegate: any; let tracking: any; let genericErrors: any; // // paths // function lookupPath(path: string, opts: any): Lookup; function getPath(node: FSNode): string; // // nodes // function isFile(mode: number): boolean; function isDir(mode: number): boolean; function isLink(mode: number): boolean; function isChrdev(mode: number): boolean; function isBlkdev(mode: number): boolean; function isFIFO(mode: number): boolean; function isSocket(mode: number): boolean; // // devices // function major(dev: number): number; function minor(dev: number): number; function makedev(ma: number, mi: number): number; function registerDevice(dev: number, ops: any): void; // // core // function syncfs(populate: boolean, callback: (e: any) => any): void; function syncfs(callback: (e: any) => any, populate?: boolean): void; function mount( type: Emscripten.FileSystemType, opts: any, mountpoint: string ): any; function unmount(mountpoint: string): void; function mkdir(path: string, mode?: number): any; function mkdev(path: string, mode?: number, dev?: number): any; function symlink(oldpath: string, newpath: string): any; function rename(old_path: string, new_path: string): void; function rmdir(path: string): void; function readdir(path: string): any; function unlink(path: string): void; function readlink(path: string): string; function stat(path: string, dontFollow?: boolean): any; function lstat(path: string): any; function chmod(path: string, mode: number, dontFollow?: boolean): void; function lchmod(path: string, mode: number): void; function fchmod(fd: number, mode: number): void; function chown( path: string, uid: number, gid: number, dontFollow?: boolean ): void; function lchown(path: string, uid: number, gid: number): void; function fchown(fd: number, uid: number, gid: number): void; function truncate(path: string, len: number): void; function ftruncate(fd: number, len: number): void; function utime(path: string, atime: number, mtime: number): void; function open( path: string, flags: string, mode?: number, fd_start?: number, fd_end?: number ): FSStream; function close(stream: FSStream): void; function llseek(stream: FSStream, offset: number, whence: number): any; function read( stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number ): number; function write( stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number, canOwn?: boolean ): number; function allocate(stream: FSStream, offset: number, length: number): void; function mmap( stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position: number, prot: number, flags: number ): any; function ioctl(stream: FSStream, cmd: any, arg: any): any; function readFile( path: string, opts?: { encoding?: "binary" | "utf8"; flags?: string } ): string | Uint8Array; function writeFile( path: string, data: string | ArrayBufferView, opts?: { flags?: string } ): void; // // module-level FS code // function cwd(): string; function chdir(path: string): void; function init( input: null | (() => number | null), output: null | ((c: number) => any), error: null | ((c: number) => any) ): void; function createLazyFile( parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean ): FSNode; function createPreloadedFile( parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean, onload?: () => void, onerror?: () => void, dontCreateFile?: boolean, canOwn?: boolean ): void; } declare var MEMFS: Emscripten.FileSystemType; declare var NODEFS: Emscripten.FileSystemType; declare var IDBFS: Emscripten.FileSystemType; declare function UTF8ToString(ptr: number, maxBytesToRead?: number): string; declare function stringToUTF8( str: string, outPtr: number, maxBytesToRead?: number ): void; declare function lengthBytesUTF8(str: string): number; declare function allocateUTF8(str: string): number; declare function UTF16ToString(ptr: number): string; declare function stringToUTF16( str: string, outPtr: number, maxBytesToRead?: number ): void; declare function lengthBytesUTF16(str: string): number; declare function UTF32ToString(ptr: number): string; declare function stringToUTF32( str: string, outPtr: number, maxBytesToRead?: number ): void; declare function lengthBytesUTF32(str: string): number; interface Math { imul(a: number, b: number): number; } declare module "@model-create/epanet-engine" { export var epanetEngine: EmscriptenModule; }
the_stack
import {ExportNs} from '../../esl-utils/environment/export-ns'; import {ESC} from '../../esl-utils/dom/keys'; import {CSSClassUtils} from '../../esl-utils/dom/class'; import {bind} from '../../esl-utils/decorators/bind'; import {defined, copyDefinedKeys} from '../../esl-utils/misc/object'; import {DeviceDetector} from '../../esl-utils/environment/device-detector'; import {DelayedTask} from '../../esl-utils/async/delayed-task'; import {ESLBaseElement, attr, jsonAttr, boolAttr} from '../../esl-base-element/core'; /** Default Toggleable action params type definition */ export interface ToggleableActionParams { /** Initiator string identifier */ initiator?: string; /** Delay timeout for both show and hide actions */ delay?: number; /** Show delay timeout */ showDelay?: number; /** Hide delay timeout */ hideDelay?: number; /** Force action independently of current state of the Toggleable */ force?: boolean; /** Do not throw events on action */ silent?: boolean; /** Activate hover tracking to hide Toggleable */ trackHover?: boolean; /** Element activator of the action */ activator?: HTMLElement | null; /** Event that initiates the action */ event?: Event; /** Custom user data */ [key: string]: any; } const activators: WeakMap<ESLToggleable, HTMLElement | undefined> = new WeakMap(); /** * ESLToggleable component * @author Julia Murashko, Alexey Stsefanovich (ala'n) * * ESLToggleable - a custom element, that is used as a base for "Popup-like" components creation */ @ExportNs('Toggleable') export class ESLToggleable extends ESLBaseElement { static is = 'esl-toggleable'; static get observedAttributes() { return ['open', 'group']; } /** CSS class to add on the body element */ @attr() public bodyClass: string; /** CSS class to add when the Toggleable is active */ @attr({defaultValue: 'open'}) public activeClass: string; /** Toggleable group meta information to organize groups */ @attr({name: 'group'}) public groupName: string; /** Selector to mark inner close triggers */ @attr({name: 'close-on'}) public closeTrigger: string; /** Close the Toggleable on ESC keyboard event */ @boolAttr() public closeOnEsc: boolean; /** Close the Toggleable on a click/tap outside */ @boolAttr() public closeOnOutsideAction: boolean; /** Initial params to pass to show/hide action on the start */ @jsonAttr<ToggleableActionParams>({defaultValue: {force: true, initiator: 'init'}}) public initialParams: ToggleableActionParams; /** Default params to merge into passed action params */ @jsonAttr<ToggleableActionParams>({defaultValue: {}}) public defaultParams: ToggleableActionParams; /** Hover params to pass from track hover listener */ @jsonAttr<ToggleableActionParams>({defaultValue: {}}) public trackHoverParams: ToggleableActionParams; /** Marker of initially opened toggleable instance */ public initiallyOpened: boolean; /** Inner state */ private _open: boolean = false; /** Inner show/hide task manager instance */ protected _task: DelayedTask = new DelayedTask(); /** Marker for current hover listener state */ protected _trackHover: boolean = false; /** Delay for track hover listeners actions */ protected _trackHoverDelay: number | undefined; protected connectedCallback() { super.connectedCallback(); this.initiallyOpened = this.hasAttribute('open'); this.bindEvents(); this.setInitialState(); } protected disconnectedCallback() { super.disconnectedCallback(); this.unbindEvents(); activators.delete(this); } protected attributeChangedCallback(attrName: string, oldVal: string, newVal: string) { if (!this.connected || newVal === oldVal) return; switch (attrName) { case 'open': if (this.open === this.hasAttribute('open')) return; this.toggle(this.open, {initiator: 'attribute', showDelay: 0, hideDelay: 0}); break; case 'group': this.$$fire('change:group', { detail: {oldGroupName: oldVal, newGroupName: newVal} }); break; } } /** Set initial state of the Toggleable */ protected setInitialState() { if (this.initialParams) { this.toggle(this.initiallyOpened, this.initialParams); } } protected bindEvents() { this.addEventListener('click', this._onClick); this.addEventListener('keydown', this._onKeyboardEvent); } protected unbindEvents() { this.removeEventListener('click', this._onClick); this.removeEventListener('keydown', this._onKeyboardEvent); this.bindOutsideEventTracking(false); this.bindHoverStateTracking(false); } /** Bind outside action event listeners */ protected bindOutsideEventTracking(track: boolean) { document.body.removeEventListener('mouseup', this._onOutsideAction, true); document.body.removeEventListener('touchend', this._onOutsideAction, true); if (track) { document.body.addEventListener('mouseup', this._onOutsideAction, true); document.body.addEventListener('touchend', this._onOutsideAction, true); } } /** Bind hover events listeners for the Toggleable itself */ protected bindHoverStateTracking(track: boolean, hideDelay?: number | string) { if (!DeviceDetector.hasHover) return; this._trackHoverDelay = track && hideDelay !== undefined ? +hideDelay : undefined; if (this._trackHover === track) return; this._trackHover = track; this.removeEventListener('mouseenter', this._onMouseEnter); this.removeEventListener('mouseleave', this._onMouseLeave); if (this._trackHover) { this.addEventListener('mouseenter', this._onMouseEnter); this.addEventListener('mouseleave', this._onMouseLeave); } } /** Function to merge the result action params */ protected mergeDefaultParams(params?: ToggleableActionParams): ToggleableActionParams { return Object.assign({}, this.defaultParams, copyDefinedKeys(params)); } /** Toggle the element state */ public toggle(state: boolean = !this.open, params?: ToggleableActionParams) { return state ? this.show(params) : this.hide(params); } /** Change the element state to active */ public show(params?: ToggleableActionParams) { params = this.mergeDefaultParams(params); this._task.put(this.showTask.bind(this, params), defined(params.showDelay, params.delay)); this.bindOutsideEventTracking(this.closeOnOutsideAction); this.bindHoverStateTracking(!!params.trackHover, defined(params.hideDelay, params.delay)); return this; } /** Change the element state to inactive */ public hide(params?: ToggleableActionParams) { params = this.mergeDefaultParams(params); this._task.put(this.hideTask.bind(this, params), defined(params.hideDelay, params.delay)); this.bindOutsideEventTracking(false); this.bindHoverStateTracking(!!params.trackHover, defined(params.hideDelay, params.delay)); return this; } /** Actual show task to execute by toggleable task manger ({@link DelayedTask} out of the box) */ protected showTask(params: ToggleableActionParams) { if (!params.force && this.open) return; if (!params.silent && !this.$$fire('before:show', {detail: {params}})) return; this.activator = params.activator; this.open = true; this.onShow(params); if (!params.silent) this.$$fire('show', {detail: {params}, cancelable: false}); } /** Actual hide task to execute by toggleable task manger ({@link DelayedTask} out of the box) */ protected hideTask(params: ToggleableActionParams) { if (!params.force && !this.open) return; if (!params.silent && !this.$$fire('before:hide', {detail: {params}})) return; this.open = false; this.onHide(params); this.bindOutsideEventTracking(false); if (!params.silent) this.$$fire('hide', {detail: {params}, cancelable: false}); } /** * Actions to execute on show toggleable. * Inner state and 'open' attribute are not affected and updated before `onShow` execution. * Adds CSS classes, update a11y and fire esl:refresh event by default. */ protected onShow(params: ToggleableActionParams) { CSSClassUtils.add(this, this.activeClass); CSSClassUtils.add(document.body, this.bodyClass, this); this.updateA11y(); this.$$fire('esl:refresh'); // To notify other components about content change } /** * Actions to execute on hide toggleable. * Inner state and 'open' attribute are not affected and updated before `onShow` execution. * Removes CSS classes and update a11y by default. */ protected onHide(params: ToggleableActionParams) { CSSClassUtils.remove(this, this.activeClass); CSSClassUtils.remove(document.body, this.bodyClass, this); this.updateA11y(); } /** Active state marker */ public get open() { return this._open; } public set open(value: boolean) { this.toggleAttribute('open', this._open = value); } /** Last component that has activated the element. Uses {@link ToggleableActionParams.activator}*/ public get activator(): HTMLElement | null | undefined { return activators.get(this); } public set activator(el: HTMLElement | null | undefined) { el ? activators.set(this, el) : activators.delete(this); } /** Returns the element to apply a11y attributes */ protected get $a11yTarget(): HTMLElement | null { const target = this.getAttribute('a11y-target'); if (target === 'none') return null; return target ? this.querySelector(target) : this; } /** Called on show and on hide actions to update a11y state accordingly */ protected updateA11y() { const targetEl = this.$a11yTarget; if (!targetEl) return; targetEl.setAttribute('aria-hidden', String(!this._open)); } @bind protected _onClick(e: MouseEvent) { const target = e.target as HTMLElement; if (this.closeTrigger && target.closest(this.closeTrigger)) { this.hide({initiator: 'close', activator: target, event: e}); } } @bind protected _onOutsideAction(e: MouseEvent) { const target = e.target as HTMLElement; if (this.contains(target)) return; if (this.activator && this.activator.contains(target)) return; // Used 0 delay to decrease priority of the request this.hide({initiator: 'outsideaction', hideDelay: 0, event: e}); } @bind protected _onKeyboardEvent(e: KeyboardEvent) { if (this.closeOnEsc && e.key === ESC) { this.hide({initiator: 'keyboard', event: e}); } } @bind protected _onMouseEnter(e: MouseEvent) { const hideDelay = this._trackHoverDelay; const baseParams: ToggleableActionParams = {initiator: 'mouseenter', trackHover: true, activator: this.activator, event: e, hideDelay}; this.show(Object.assign(baseParams, this.trackHoverParams)); } @bind protected _onMouseLeave(e: MouseEvent) { const hideDelay = this._trackHoverDelay; const baseParams: ToggleableActionParams = {initiator: 'mouseleave', trackHover: true, activator: this.activator, event: e, hideDelay}; this.hide(Object.assign(baseParams, this.trackHoverParams)); } } declare global { export interface ESLLibrary { Toggleable: typeof ESLToggleable; } export interface HTMLElementTagNameMap { 'esl-toggleable': ESLToggleable; } }
the_stack
import * as cp from 'child_process'; // eslint-disable-next-line import/no-extraneous-dependencies import * as which from 'which'; import { attach } from '../attach'; import { NeovimClient } from './client'; function wait(ms: number): Promise<void> { return new Promise(resolve => { setTimeout(() => { resolve(); }, ms); }); } try { which.sync('nvim'); } catch (e) { // eslint-disable-next-line no-console console.error( 'A Neovim installation is required to run the tests', '(see https://github.com/neovim/neovim/wiki/Installing)' ); process.exit(1); } describe('Buffer API', () => { let proc; let nvim: NeovimClient; // utility to allow each test to be run in its // own buffer function withBuffer(lines, test) { return async () => { await nvim.command('new!'); const buffer = await nvim.buffer; if (lines) { await buffer; await buffer.replace(lines, 0); } await test(buffer); await nvim.command(`bd! ${buffer.id}`); }; } beforeAll(async () => { proc = cp.spawn('nvim', ['-u', 'NONE', '--embed', '-n', '--noplugin'], { cwd: __dirname, }); nvim = await attach({ proc }); }); afterAll(() => { nvim.quit(); if (proc && proc.connected) { proc.disconnect(); } }); it( 'gets the current buffer', withBuffer([], async buffer => { expect(buffer).toBeInstanceOf(nvim.Buffer); }) ); it( 'get bufnr by id', withBuffer([], async buffer => { const bufnr = await nvim.call('bufnr', ['%']); expect(buffer.id).toBe(bufnr); }) ); describe('Normal API calls', () => { it( 'gets changedtick of buffer', withBuffer([], async buffer => { const initial = await buffer.changedtick; // insert a line buffer.append('hi'); expect(await buffer.changedtick).toBe(initial + 1); // clear buffer buffer.remove(0, -1, false); expect(await buffer.changedtick).toBe(initial + 2); }) ); it('sets/gets the current buffer name', async () => { (await nvim.buffers)[0].name = 'hello.txt'; const name = await (await nvim.buffers)[0].name; expect(name).toMatch('hello.txt'); }); it( 'is a valid buffer', withBuffer([], async buffer => { expect(await buffer.valid).toBe(true); }) ); it( 'sets current buffer name to "foo.txt"', withBuffer([], async buffer => { // eslint-disable-next-line no-param-reassign buffer.name = 'foo.txt'; expect(await buffer.name).toMatch('foo.txt'); // eslint-disable-next-line no-param-reassign buffer.name = 'test2.txt'; expect(await buffer.name).toMatch('test2.txt'); }) ); it( 'can replace first line of buffer with a string', withBuffer(['foo'], async buffer => { buffer.replace('test', 0); expect(await buffer.lines).toEqual(['test']); }) ); it( 'can insert lines at beginning of buffer', withBuffer(['test'], async buffer => { await buffer.insert(['test', 'foo'], 0); expect(await buffer.lines).toEqual(['test', 'foo', 'test']); }) ); it( 'replaces the right lines', withBuffer( ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], async buffer => { await buffer.replace(['a', 'b', 'c'], 2); expect(await buffer.lines).toEqual([ '0', '1', 'a', 'b', 'c', '5', '6', '7', '8', '9', ]); } ) ); it( 'inserts line at index 2', withBuffer(['test', 'bar', 'bar', 'bar'], async buffer => { buffer.insert(['foo'], 2); expect(await buffer.lines).toEqual([ 'test', 'bar', 'foo', 'bar', 'bar', ]); }) ); it( 'removes last 2 lines', withBuffer(['test', 'bar', 'foo', 'a', 'b'], async buffer => { buffer.remove(-3, -1); expect(await buffer.lines).toEqual(['test', 'bar', 'foo']); }) ); it('checks if buffer is loaded', async () => { await nvim.command('new'); const buffer = await nvim.buffer; expect(await buffer.loaded).toBe(true); await nvim.command('bunload!'); expect(await buffer.loaded).toBe(false); }); it( 'gets byte offset for a line', withBuffer(['test', 'bar', ''], async buffer => { expect(await buffer.getOffset(0)).toEqual(0); expect(await buffer.getOffset(1)).toEqual(5); // test\n expect(await buffer.getOffset(2)).toEqual(9); // test\n + bar\n expect(await buffer.getOffset(3)).toEqual(10); // test\n + bar\n + \n expect(buffer.getOffset(4)).rejects.toThrow(); }) ); it('returns -1 for byte offset of unloaded buffer', async () => { await nvim.command('new'); await nvim.command('bunload!'); expect(await nvim.buffer.getOffset(0)).toEqual(-1); }); it( 'append lines to end of buffer', withBuffer(['test', 'bar', 'foo'], async buffer => { await buffer.append(['test', 'test']); expect(await buffer.lines).toEqual([ 'test', 'bar', 'foo', 'test', 'test', ]); }) ); it( 'can clear the buffer', withBuffer(['foo'], async buffer => { buffer.remove(0, -1); // One empty line expect(await buffer.length).toEqual(1); expect(await buffer.lines).toEqual(['']); }) ); it( 'changes buffer options', withBuffer([], async buffer => { const initial = await buffer.getOption('copyindent'); buffer.setOption('copyindent', true); expect(await buffer.getOption('copyindent')).toBe(true); buffer.setOption('copyindent', false); expect(await buffer.getOption('copyindent')).toBe(false); // Restore option buffer.setOption('copyindent', initial); expect(await buffer.getOption('copyindent')).toBe(initial); }) ); it( 'returns null if variable is not found', withBuffer([], async buffer => { const test = await buffer.getVar('test'); expect(test).toBe(null); }) ); it( 'can set and delete a b: variable to an object', withBuffer([], async buffer => { buffer.setVar('test', { foo: 'testValue' }); expect(await buffer.getVar('test')).toEqual({ foo: 'testValue' }); expect(await nvim.eval('b:test')).toEqual({ foo: 'testValue' }); buffer.deleteVar('test'); expect(await nvim.eval('exists("b:test")')).toBe(0); expect(await buffer.getVar('test')).toBe(null); }) ); it('can get list of commands', async () => { expect(await nvim.buffer.commands).toEqual({}); }); it( 'sets virtual text and clears namespace', withBuffer(['test'], async buffer => { const ns = await nvim.createNamespace(); await buffer.setVirtualText(ns, 0, [['annotation']]); await buffer.clearNamespace({ nsId: ns }); }) ); // TODO: How do we run integration tests for add/clear highlights? and get mark }); describe('Chainable API calls', () => { it('sets/gets the current buffer name using api chaining', async () => { nvim.buffer.name = 'goodbye.txt'; expect(await nvim.buffer.name).toMatch('goodbye.txt'); }); it('can chain calls from Base class i.e. getOption', async () => { const initial = await nvim.buffer.getOption('copyindent'); nvim.buffer.setOption('copyindent', true); expect(await nvim.buffer.getOption('copyindent')).toBe(true); nvim.buffer.setOption('copyindent', false); expect(await nvim.buffer.getOption('copyindent')).toBe(false); // Restore option nvim.buffer.setOption('copyindent', initial); expect(await nvim.buffer.getOption('copyindent')).toBe(initial); }); it('sets current buffer name to "bar.js" using api chaining', async () => { await (nvim.buffer.name = 'bar.js'); expect(await nvim.buffer.name).toMatch('bar.js'); await (nvim.buffer.name = 'test2.js'); expect(await nvim.buffer.name).toMatch('test2.js'); }); it( 'can replace first line of nvim.buffer with a string', withBuffer([], async () => { await nvim.buffer.replace('test', 0); expect(await nvim.buffer.lines).toEqual(['test']); }) ); it( 'replaces the right lines', withBuffer( ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], async () => { await nvim.buffer.replace(['a', 'b', 'c'], 2); expect(await nvim.buffer.lines).toEqual([ '0', '1', 'a', 'b', 'c', '5', '6', '7', '8', '9', ]); } ) ); it( 'can insert lines at beginning of buffer', withBuffer(['test'], async () => { await nvim.buffer.insert(['test', 'foo'], 0); expect(await nvim.buffer.lines).toEqual(['test', 'foo', 'test']); }) ); it( 'can replace nvim.buffer starting at line 1', withBuffer(['test', 'foo'], async () => { await nvim.buffer.replace(['bar', 'bar', 'bar'], 1); expect(await nvim.buffer.lines).toEqual(['test', 'bar', 'bar', 'bar']); }) ); it( 'inserts line at index 2', withBuffer(['test', 'bar', 'bar', 'bar'], async () => { await nvim.buffer.insert(['foo'], 2); expect(await nvim.buffer.lines).toEqual([ 'test', 'bar', 'foo', 'bar', 'bar', ]); }) ); it( 'removes last 2 lines', withBuffer(['test', 'bar', 'foo', 'a', 'b'], async () => { await nvim.buffer.remove(-3, -1); expect(await nvim.buffer.lines).toEqual(['test', 'bar', 'foo']); }) ); it( 'append lines to end of buffer', withBuffer(['test', 'bar', 'foo'], async () => { await nvim.buffer.append(['test', 'test']); expect(await nvim.buffer.lines).toEqual([ 'test', 'bar', 'foo', 'test', 'test', ]); }) ); it( 'can clear the buffer', withBuffer(['foo'], async () => { await nvim.buffer.remove(0, -1); // One empty line expect(await nvim.buffer.length).toEqual(1); expect(await nvim.buffer.lines).toEqual(['']); }) ); }); }); describe('Buffer event updates', () => { let proc; let nvim; beforeAll(async () => { proc = cp.spawn('nvim', ['-u', 'NONE', '--embed', '-n', '--noplugin'], { cwd: __dirname, }); nvim = await attach({ proc }); }); afterAll(() => { nvim.quit(); if (proc && proc.connected) { proc.disconnect(); } }); beforeEach(async () => { await nvim.buffer.remove(0, -1); }); it('can listen and unlisten', async () => { const buffer = await nvim.buffer; const mock = jest.fn(); const unlisten = buffer.listen('lines', mock); await nvim.buffer.insert(['bar'], 1); expect(mock).toHaveBeenCalledTimes(1); unlisten(); await nvim.buffer.insert(['bar'], 1); expect(mock).toHaveBeenCalledTimes(1); }); it('can reattach for buffer events', async () => { const buffer = await nvim.buffer; let unlisten = buffer.listen('lines', jest.fn()); unlisten(); await wait(10); const mock = jest.fn(); unlisten = buffer.listen('lines', mock); await nvim.buffer.insert(['bar'], 1); expect(mock).toHaveBeenCalledTimes(1); unlisten(); }); it('should return attached state', async () => { const buffer = await nvim.buffer; const unlisten = buffer.listen('lines', jest.fn()); await wait(30); let attached = buffer.isAttached; expect(attached).toBe(true); unlisten(); await wait(30); attached = buffer.isAttached; expect(attached).toBe(false); }); it('only bind once for the same event and handler ', async () => { const buffer = await nvim.buffer; const mock = jest.fn(); buffer.listen('lines', mock); buffer.listen('lines', mock); await nvim.buffer.insert(['bar'], 1); expect(mock).toHaveBeenCalledTimes(1); }); it('can use `buffer.unlisten` to unlisten', async () => { const buffer = await nvim.buffer; const mock = jest.fn(); buffer.listen('lines', mock); await nvim.buffer.insert(['bar'], 1); expect(mock).toHaveBeenCalledTimes(1); buffer.unlisten('lines', mock); await nvim.buffer.insert(['bar'], 1); expect(mock).toHaveBeenCalledTimes(1); }); it('listens to line updates', async () => { const buffer = await nvim.buffer; const bufferName = await buffer.name; await buffer.insert(['test', 'foo'], 0); const promise = new Promise(resolve => { const unlisten = buffer.listen( 'lines', async (currentBuffer, tick, start, end, data) => { expect(await currentBuffer.name).toBe(bufferName); expect(start).toBe(1); expect(end).toBe(1); expect(data).toEqual(['bar']); unlisten(); resolve(); } ); }); await nvim.buffer.insert(['bar'], 1); await promise; }); it('has listener on multiple buffers ', async () => { await nvim.command('new!'); const buffers = await nvim.buffers; const foo = jest.fn(); const bar = jest.fn(); buffers[0].listen('lines', foo); buffers[1].listen('lines', bar); await nvim.buffer.insert(['bar'], 1); expect(foo).toHaveBeenCalledTimes(0); expect(bar).toHaveBeenCalledTimes(1); await nvim.command('q!'); await nvim.buffer.insert(['foo'], 0); expect(foo).toHaveBeenCalledTimes(1); expect(bar).toHaveBeenCalledTimes(1); buffers[0].unlisten('lines', foo); buffers[1].unlisten('lines', bar); }); it('has multiple listeners for same event, on same buffer', async () => { await nvim.command('new!'); const buffer = await nvim.buffer; const foo = jest.fn(); const bar = jest.fn(); const unlisten1 = buffer.listen('lines', foo); const unlisten2 = buffer.listen('lines', bar); await nvim.buffer.insert(['bar'], 1); expect(foo).toHaveBeenCalledTimes(1); expect(bar).toHaveBeenCalledTimes(1); unlisten2(); await nvim.buffer.insert(['foo'], 0); expect(foo).toHaveBeenCalledTimes(2); expect(bar).toHaveBeenCalledTimes(1); unlisten1(); await nvim.command('q!'); }); it('has multiple listeners for different events, on same buffer', async () => { await nvim.command('new!'); const buffer = await nvim.buffer; const foo = jest.fn(); const bar = jest.fn(); const unlisten1 = buffer.listen('lines', foo); const unlisten2 = buffer.listen('changedtick', bar); await nvim.buffer.insert(['bar'], 1); expect(foo).toHaveBeenCalledTimes(1); expect(bar).toHaveBeenCalledTimes(1); unlisten2(); await nvim.buffer.insert(['foo'], 0); expect(foo).toHaveBeenCalledTimes(2); expect(bar).toHaveBeenCalledTimes(1); unlisten1(); await nvim.command('q!'); }); });
the_stack