text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
namespace ts.projectSystem { describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { function verifyFiles(caption: string, actual: readonly string[], expected: readonly string[]) { assert.equal(actual.length, expected.length, `Incorrect number of ${caption}. Actual: ${actual} Expected: ${expected}`); const seen = new Map<string, true>(); forEach(actual, f => { assert.isFalse(seen.has(f), `${caption}: Found duplicate ${f}. Actual: ${actual} Expected: ${expected}`); seen.set(f, true); assert.isTrue(contains(expected, f), `${caption}: Expected not to contain ${f}. Actual: ${actual} Expected: ${expected}`); }); } function createVerifyInitialOpen(session: TestSession, verifyProjectsUpdatedInBackgroundEventHandler: (events: server.ProjectsUpdatedInBackgroundEvent[]) => void) { return (file: File) => { session.executeCommandSeq({ command: server.CommandNames.Open, arguments: { file: file.path } } as protocol.OpenRequest); verifyProjectsUpdatedInBackgroundEventHandler([]); }; } interface ProjectsUpdatedInBackgroundEventVerifier { session: TestSession; verifyProjectsUpdatedInBackgroundEventHandler(events: server.ProjectsUpdatedInBackgroundEvent[]): void; verifyInitialOpen(file: File): void; } function verifyProjectsUpdatedInBackgroundEvent(createSession: (host: TestServerHost) => ProjectsUpdatedInBackgroundEventVerifier) { it("when adding new file", () => { const commonFile1: File = { path: "/a/b/file1.ts", content: "export var x = 10;" }; const commonFile2: File = { path: "/a/b/file2.ts", content: "export var y = 10;" }; const commonFile3: File = { path: "/a/b/file3.ts", content: "export var z = 10;" }; const configFile: File = { path: "/a/b/tsconfig.json", content: `{}` }; const openFiles = [commonFile1.path]; const host = createServerHost([commonFile1, libFile, configFile]); const { verifyProjectsUpdatedInBackgroundEventHandler, verifyInitialOpen } = createSession(host); verifyInitialOpen(commonFile1); host.writeFile(commonFile2.path, commonFile2.content); host.runQueuedTimeoutCallbacks(); verifyProjectsUpdatedInBackgroundEventHandler([{ eventName: server.ProjectsUpdatedInBackgroundEvent, data: { openFiles } }]); host.writeFile(commonFile3.path, commonFile3.content); host.runQueuedTimeoutCallbacks(); verifyProjectsUpdatedInBackgroundEventHandler([{ eventName: server.ProjectsUpdatedInBackgroundEvent, data: { openFiles } }]); }); describe("with --out or --outFile setting", () => { function verifyEventWithOutSettings(compilerOptions: CompilerOptions = {}) { const config: File = { path: "/a/tsconfig.json", content: JSON.stringify({ compilerOptions }) }; const f1: File = { path: "/a/a.ts", content: "export let x = 1" }; const f2: File = { path: "/a/b.ts", content: "export let y = 1" }; const openFiles = [f1.path]; const files = [f1, config, libFile]; const host = createServerHost(files); const { verifyInitialOpen, verifyProjectsUpdatedInBackgroundEventHandler } = createSession(host); verifyInitialOpen(f1); host.writeFile(f2.path, f2.content); host.runQueuedTimeoutCallbacks(); verifyProjectsUpdatedInBackgroundEventHandler([{ eventName: server.ProjectsUpdatedInBackgroundEvent, data: { openFiles } }]); host.writeFile(f2.path, "export let x = 11"); host.runQueuedTimeoutCallbacks(); verifyProjectsUpdatedInBackgroundEventHandler([{ eventName: server.ProjectsUpdatedInBackgroundEvent, data: { openFiles } }]); } it("when both options are not set", () => { verifyEventWithOutSettings(); }); it("when --out is set", () => { const outJs = "/a/out.js"; verifyEventWithOutSettings({ out: outJs }); }); it("when --outFile is set", () => { const outJs = "/a/out.js"; verifyEventWithOutSettings({ outFile: outJs }); }); }); describe("with modules and configured project", () => { const file1Consumer1Path = "/a/b/file1Consumer1.ts"; const moduleFile1Path = "/a/b/moduleFile1.ts"; const configFilePath = "/a/b/tsconfig.json"; interface InitialStateParams { /** custom config file options */ configObj?: any; /** Additional files and folders to add */ getAdditionalFileOrFolder?(): File[]; /** initial list of files to reload in fs and first file in this list being the file to open */ firstReloadFileList?: string[]; } function getInitialState({ configObj = {}, getAdditionalFileOrFolder, firstReloadFileList }: InitialStateParams = {}) { const moduleFile1: File = { path: moduleFile1Path, content: "export function Foo() { };", }; const file1Consumer1: File = { path: file1Consumer1Path, content: `import {Foo} from "./moduleFile1"; export var y = 10;`, }; const file1Consumer2: File = { path: "/a/b/file1Consumer2.ts", content: `import {Foo} from "./moduleFile1"; let z = 10;`, }; const moduleFile2: File = { path: "/a/b/moduleFile2.ts", content: `export var Foo4 = 10;`, }; const globalFile3: File = { path: "/a/b/globalFile3.ts", content: `interface GlobalFoo { age: number }` }; const additionalFiles = getAdditionalFileOrFolder ? getAdditionalFileOrFolder() : []; const configFile = { path: configFilePath, content: JSON.stringify(configObj || { compilerOptions: {} }) }; const files: File[] = [file1Consumer1, moduleFile1, file1Consumer2, moduleFile2, ...additionalFiles, globalFile3, libFile, configFile]; const filesToReload = firstReloadFileList && getFiles(firstReloadFileList) || files; const host = createServerHost([filesToReload[0], configFile]); // Initial project creation const { session, verifyProjectsUpdatedInBackgroundEventHandler, verifyInitialOpen } = createSession(host); const openFiles = [filesToReload[0].path]; verifyInitialOpen(filesToReload[0]); // Since this is first event, it will have all the files filesToReload.forEach(f => host.ensureFileOrFolder(f)); if (!firstReloadFileList) host.runQueuedTimeoutCallbacks(); // Invalidated module resolutions to schedule project update verifyProjectsUpdatedInBackgroundEvent(); return { host, moduleFile1, file1Consumer1, file1Consumer2, moduleFile2, globalFile3, configFile, updateContentOfOpenFile, verifyNoProjectsUpdatedInBackgroundEvent, verifyProjectsUpdatedInBackgroundEvent }; function getFiles(filelist: string[]) { return map(filelist, getFile); } function getFile(fileName: string) { return find(files, file => file.path === fileName)!; } function verifyNoProjectsUpdatedInBackgroundEvent() { host.runQueuedTimeoutCallbacks(); verifyProjectsUpdatedInBackgroundEventHandler([]); } function verifyProjectsUpdatedInBackgroundEvent() { host.runQueuedTimeoutCallbacks(); verifyProjectsUpdatedInBackgroundEventHandler([{ eventName: server.ProjectsUpdatedInBackgroundEvent, data: { openFiles } }]); } function updateContentOfOpenFile(file: File, newContent: string) { session.executeCommandSeq<protocol.ChangeRequest>({ command: server.CommandNames.Change, arguments: { file: file.path, insertString: newContent, endLine: 1, endOffset: file.content.length, line: 1, offset: 1 } }); file.content = newContent; } } it("should contains only itself if a module file's shape didn't change, and all files referencing it if its shape changed", () => { const { host, moduleFile1, verifyProjectsUpdatedInBackgroundEvent } = getInitialState(); // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` host.writeFile(moduleFile1.path, `export var T: number;export function Foo() { };`); verifyProjectsUpdatedInBackgroundEvent(); // Change the content of moduleFile1 to `export var T: number;export function Foo() { console.log('hi'); };` host.writeFile(moduleFile1.path, `export var T: number;export function Foo() { console.log('hi'); };`); verifyProjectsUpdatedInBackgroundEvent(); }); it("should be up-to-date with the reference map changes", () => { const { host, moduleFile1, file1Consumer1, updateContentOfOpenFile, verifyProjectsUpdatedInBackgroundEvent, verifyNoProjectsUpdatedInBackgroundEvent } = getInitialState(); // Change file1Consumer1 content to `export let y = Foo();` updateContentOfOpenFile(file1Consumer1, "export let y = Foo();"); verifyNoProjectsUpdatedInBackgroundEvent(); // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` host.writeFile(moduleFile1.path, `export var T: number;export function Foo() { };`); verifyProjectsUpdatedInBackgroundEvent(); // Add the import statements back to file1Consumer1 updateContentOfOpenFile(file1Consumer1, `import {Foo} from "./moduleFile1";let y = Foo();`); verifyNoProjectsUpdatedInBackgroundEvent(); // Change the content of moduleFile1 to `export var T: number;export var T2: string;export function Foo() { };` host.writeFile(moduleFile1.path, `export var T: number;export var T2: string;export function Foo() { };`); verifyProjectsUpdatedInBackgroundEvent(); // Multiple file edits in one go: // Change file1Consumer1 content to `export let y = Foo();` // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` updateContentOfOpenFile(file1Consumer1, `export let y = Foo();`); host.writeFile(moduleFile1.path, `export var T: number;export function Foo() { };`); verifyProjectsUpdatedInBackgroundEvent(); }); it("should be up-to-date with deleted files", () => { const { host, moduleFile1, file1Consumer2, verifyProjectsUpdatedInBackgroundEvent } = getInitialState(); // Change the content of moduleFile1 to `export var T: number;export function Foo() { };` host.writeFile(moduleFile1.path, `export var T: number;export function Foo() { };`); // Delete file1Consumer2 host.deleteFile(file1Consumer2.path); verifyProjectsUpdatedInBackgroundEvent(); }); it("should be up-to-date with newly created files", () => { const { host, moduleFile1, verifyProjectsUpdatedInBackgroundEvent, } = getInitialState(); host.writeFile(moduleFile1.path, `export var T: number;export function Foo() { };`); host.writeFile("/a/b/file1Consumer3.ts", `import {Foo} from "./moduleFile1"; let y = Foo();`); verifyProjectsUpdatedInBackgroundEvent(); }); it("should detect changes in non-root files", () => { const { host, moduleFile1, verifyProjectsUpdatedInBackgroundEvent } = getInitialState({ configObj: { files: [file1Consumer1Path] }, }); host.writeFile(moduleFile1.path, `export var T: number;export function Foo() { };`); verifyProjectsUpdatedInBackgroundEvent(); // change file1 internal, and verify only file1 is affected host.writeFile(moduleFile1.path, moduleFile1.content + "var T1: number;"); verifyProjectsUpdatedInBackgroundEvent(); }); it("should return all files if a global file changed shape", () => { const { host, globalFile3, verifyProjectsUpdatedInBackgroundEvent } = getInitialState(); host.writeFile(globalFile3.path, globalFile3.content + "var T2: string;"); verifyProjectsUpdatedInBackgroundEvent(); }); it("should always return the file itself if '--isolatedModules' is specified", () => { const { host, moduleFile1, verifyProjectsUpdatedInBackgroundEvent } = getInitialState({ configObj: { compilerOptions: { isolatedModules: true } } }); host.writeFile(moduleFile1.path, `export var T: number;export function Foo() { };`); verifyProjectsUpdatedInBackgroundEvent(); }); it("should always return the file itself if '--out' or '--outFile' is specified", () => { const outFilePath = "/a/b/out.js"; const { host, moduleFile1, verifyProjectsUpdatedInBackgroundEvent } = getInitialState({ configObj: { compilerOptions: { module: "system", outFile: outFilePath } } }); host.writeFile(moduleFile1.path, `export var T: number;export function Foo() { };`); verifyProjectsUpdatedInBackgroundEvent(); }); it("should return cascaded affected file list", () => { const file1Consumer1Consumer1: File = { path: "/a/b/file1Consumer1Consumer1.ts", content: `import {y} from "./file1Consumer1";` }; const { host, moduleFile1, file1Consumer1, updateContentOfOpenFile, verifyNoProjectsUpdatedInBackgroundEvent, verifyProjectsUpdatedInBackgroundEvent } = getInitialState({ getAdditionalFileOrFolder: () => [file1Consumer1Consumer1] }); updateContentOfOpenFile(file1Consumer1, file1Consumer1.content + "export var T: number;"); verifyNoProjectsUpdatedInBackgroundEvent(); // Doesnt change the shape of file1Consumer1 host.writeFile(moduleFile1.path, `export var T: number;export function Foo() { };`); verifyProjectsUpdatedInBackgroundEvent(); // Change both files before the timeout updateContentOfOpenFile(file1Consumer1, file1Consumer1.content + "export var T2: number;"); host.writeFile(moduleFile1.path, `export var T2: number;export function Foo() { };`); verifyProjectsUpdatedInBackgroundEvent(); }); it("should work fine for files with circular references", () => { const file1: File = { path: "/a/b/file1.ts", content: ` /// <reference path="./file2.ts" /> export var t1 = 10;` }; const file2: File = { path: "/a/b/file2.ts", content: ` /// <reference path="./file1.ts" /> export var t2 = 10;` }; const { host, verifyProjectsUpdatedInBackgroundEvent } = getInitialState({ getAdditionalFileOrFolder: () => [file1, file2], firstReloadFileList: [file1.path, libFile.path, file2.path, configFilePath] }); host.writeFile(file2.path, file2.content + "export var t3 = 10;"); verifyProjectsUpdatedInBackgroundEvent(); }); it("should detect removed code file", () => { const referenceFile1: File = { path: "/a/b/referenceFile1.ts", content: ` /// <reference path="./moduleFile1.ts" /> export var x = Foo();` }; const { host, verifyProjectsUpdatedInBackgroundEvent } = getInitialState({ getAdditionalFileOrFolder: () => [referenceFile1], firstReloadFileList: [referenceFile1.path, libFile.path, moduleFile1Path, configFilePath] }); host.deleteFile(moduleFile1Path); verifyProjectsUpdatedInBackgroundEvent(); }); it("should detect non-existing code file", () => { const referenceFile1: File = { path: "/a/b/referenceFile1.ts", content: ` /// <reference path="./moduleFile2.ts" /> export var x = Foo();` }; const { host, moduleFile2, updateContentOfOpenFile, verifyNoProjectsUpdatedInBackgroundEvent, verifyProjectsUpdatedInBackgroundEvent } = getInitialState({ getAdditionalFileOrFolder: () => [referenceFile1], firstReloadFileList: [referenceFile1.path, libFile.path, configFilePath] }); updateContentOfOpenFile(referenceFile1, referenceFile1.content + "export var yy = Foo();"); verifyNoProjectsUpdatedInBackgroundEvent(); // Create module File2 and see both files are saved host.writeFile(moduleFile2.path, moduleFile2.content); verifyProjectsUpdatedInBackgroundEvent(); }); }); describe("resolution when resolution cache size", () => { function verifyWithMaxCacheLimit(useSlashRootAsSomeNotRootFolderInUserDirectory: boolean) { const rootFolder = useSlashRootAsSomeNotRootFolderInUserDirectory ? "/user/username/rootfolder/otherfolder/" : "/"; const file1: File = { path: rootFolder + "a/b/project/file1.ts", content: 'import a from "file2"' }; const file2: File = { path: rootFolder + "a/b/node_modules/file2.d.ts", content: "export class a { }" }; const file3: File = { path: rootFolder + "a/b/project/file3.ts", content: "export class c { }" }; const configFile: File = { path: rootFolder + "a/b/project/tsconfig.json", content: JSON.stringify({ compilerOptions: { typeRoots: [] } }) }; const projectFiles = [file1, file3, libFile, configFile]; const openFiles = [file1.path]; const watchedRecursiveDirectories = useSlashRootAsSomeNotRootFolderInUserDirectory ? // Folders of node_modules lookup not in changedRoot ["a/b/project", "a/b/project/node_modules", "a/b/node_modules", "a/node_modules", "node_modules"].map(v => rootFolder + v) : // Folder of tsconfig ["/a/b/project", "/a/b/project/node_modules"]; const host = createServerHost(projectFiles); const { session, verifyInitialOpen, verifyProjectsUpdatedInBackgroundEventHandler } = createSession(host); const projectService = session.getProjectService(); verifyInitialOpen(file1); checkNumberOfProjects(projectService, { configuredProjects: 1 }); const project = projectService.configuredProjects.get(configFile.path)!; verifyProject(); file3.content += "export class d {}"; host.writeFile(file3.path, file3.content); host.checkTimeoutQueueLengthAndRun(2); // Since this is first event verifyProject(); verifyProjectsUpdatedInBackgroundEventHandler([{ eventName: server.ProjectsUpdatedInBackgroundEvent, data: { openFiles } }]); projectFiles.push(file2); host.writeFile(file2.path, file2.content); host.runQueuedTimeoutCallbacks(); // For invalidation host.runQueuedTimeoutCallbacks(); // For actual update if (useSlashRootAsSomeNotRootFolderInUserDirectory) { watchedRecursiveDirectories.length = 3; } else { // file2 addition wont be detected projectFiles.pop(); assert.isTrue(host.fileExists(file2.path)); } verifyProject(); verifyProjectsUpdatedInBackgroundEventHandler(useSlashRootAsSomeNotRootFolderInUserDirectory ? [{ eventName: server.ProjectsUpdatedInBackgroundEvent, data: { openFiles } }] : []); function verifyProject() { checkProjectActualFiles(project, map(projectFiles, file => file.path)); checkWatchedDirectories(host, [], /*recursive*/ false); checkWatchedDirectories(host, watchedRecursiveDirectories, /*recursive*/ true); } } it("project is not at root level", () => { verifyWithMaxCacheLimit(/*useSlashRootAsSomeNotRootFolderInUserDirectory*/ true); }); it("project is at root level", () => { verifyWithMaxCacheLimit(/*useSlashRootAsSomeNotRootFolderInUserDirectory*/ false); }); }); } describe("when event handler is set in the session", () => { verifyProjectsUpdatedInBackgroundEvent(createSessionWithProjectChangedEventHandler); function createSessionWithProjectChangedEventHandler(host: TestServerHost): ProjectsUpdatedInBackgroundEventVerifier { const { session, events: projectChangedEvents } = createSessionWithEventTracking<server.ProjectsUpdatedInBackgroundEvent>(host, server.ProjectsUpdatedInBackgroundEvent); return { session, verifyProjectsUpdatedInBackgroundEventHandler, verifyInitialOpen: createVerifyInitialOpen(session, verifyProjectsUpdatedInBackgroundEventHandler) }; function eventToString(event: server.ProjectsUpdatedInBackgroundEvent) { return JSON.stringify(event && { eventName: event.eventName, data: event.data }); } function eventsToString(events: readonly server.ProjectsUpdatedInBackgroundEvent[]) { return "[" + map(events, eventToString).join(",") + "]"; } function verifyProjectsUpdatedInBackgroundEventHandler(expectedEvents: readonly server.ProjectsUpdatedInBackgroundEvent[]) { assert.equal(projectChangedEvents.length, expectedEvents.length, `Incorrect number of events Actual: ${eventsToString(projectChangedEvents)} Expected: ${eventsToString(expectedEvents)}`); forEach(projectChangedEvents, (actualEvent, i) => { const expectedEvent = expectedEvents[i]; assert.strictEqual(actualEvent.eventName, expectedEvent.eventName); verifyFiles("openFiles", actualEvent.data.openFiles, expectedEvent.data.openFiles); }); // Verified the events, reset them projectChangedEvents.length = 0; } } }); describe("when event handler is not set but session is created with canUseEvents = true", () => { describe("without noGetErrOnBackgroundUpdate, diagnostics for open files are queued", () => { verifyProjectsUpdatedInBackgroundEvent(createSessionThatUsesEvents); }); describe("with noGetErrOnBackgroundUpdate, diagnostics for open file are not queued", () => { verifyProjectsUpdatedInBackgroundEvent(host => createSessionThatUsesEvents(host, /*noGetErrOnBackgroundUpdate*/ true)); }); function createSessionThatUsesEvents(host: TestServerHost, noGetErrOnBackgroundUpdate?: boolean): ProjectsUpdatedInBackgroundEventVerifier { const { session, getEvents, clearEvents } = createSessionWithDefaultEventHandler<protocol.ProjectsUpdatedInBackgroundEvent>(host, server.ProjectsUpdatedInBackgroundEvent, { noGetErrOnBackgroundUpdate }); return { session, verifyProjectsUpdatedInBackgroundEventHandler, verifyInitialOpen: createVerifyInitialOpen(session, verifyProjectsUpdatedInBackgroundEventHandler) }; function verifyProjectsUpdatedInBackgroundEventHandler(expected: readonly server.ProjectsUpdatedInBackgroundEvent[]) { const expectedEvents: protocol.ProjectsUpdatedInBackgroundEventBody[] = map(expected, e => { return { openFiles: e.data.openFiles }; }); const events = getEvents(); assert.equal(events.length, expectedEvents.length, `Incorrect number of events Actual: ${map(events, e => e.body)} Expected: ${expectedEvents}`); forEach(events, (actualEvent, i) => { const expectedEvent = expectedEvents[i]; verifyFiles("openFiles", actualEvent.body.openFiles, expectedEvent.openFiles); }); // Verified the events, reset them clearEvents(); if (events.length) { host.checkTimeoutQueueLength(noGetErrOnBackgroundUpdate ? 0 : 1); // Error checking queued only if not noGetErrOnBackgroundUpdate } } } }); }); }
the_stack
import * as assert from 'assert' import * as sinon from 'sinon' import { Cache, credentialsRegionDataListMap, SchemasDataProvider, } from '../../../eventSchemas/providers/schemasDataProvider' import { MockSchemaClient } from '../../shared/clients/mockClients' import { asyncGenerator } from '../../utilities/collectionUtils' describe('schemasDataProvider', function () { let sandbox: sinon.SinonSandbox let dataProviderObject: SchemasDataProvider let cacheData: Cache beforeEach(async function () { sandbox = sinon.createSandbox() const regionDataWithCredentials: credentialsRegionDataListMap = { credentials: testCredentials, regionDataList: [], } cacheData = new Cache([regionDataWithCredentials]) dataProviderObject = new SchemasDataProvider(cacheData) const clientStubRegistry = sandbox.stub(schemaClient, 'listRegistries') clientStubRegistry.onCall(0).returns(asyncGenerator([registrySummary1, registrySummary2])) clientStubRegistry.onCall(1).returns(asyncGenerator([registrySummary1])) const clientStubSchema = sandbox.stub(schemaClient, 'listSchemas') clientStubSchema.onCall(0).returns(asyncGenerator([schemaSummary, schemaSummary2])) clientStubSchema.onCall(1).returns(asyncGenerator([schemaSummary])) }) afterEach(function () { sandbox.restore() }) const TEST_REGION = 'testRegion' const TEST_REGION2 = 'testRegion2' const TEST_REGISTRY = 'testRegistry' const TEST_REGISTRY2 = 'testRegistry2' const TEST_SCHEMA = 'testSchema' const TEST_SCHEMA2 = 'testSchema2' const registrySummary1 = { RegistryName: TEST_REGISTRY } const registrySummary2 = { RegistryName: TEST_REGISTRY2 } const schemaSummary = { SchemaName: TEST_SCHEMA } const schemaSummary2 = { SchemaName: TEST_SCHEMA2 } const schemaClient = new MockSchemaClient(TEST_REGION) const testCredentials = ({} as any) as AWS.Credentials const testCredentials2 = ({} as any) as AWS.Credentials describe('getRegistries', function () { it('should return registries for given region', async function () { const registryNames = await dataProviderObject.getRegistries(TEST_REGION, schemaClient, testCredentials) assert.ok(registryNames!.length === 2, 'unexpected number of registries returned') assert.strictEqual(registryNames![0], TEST_REGISTRY, 'TEST_REGISTRY name should match') assert.strictEqual(registryNames![1], TEST_REGISTRY2, 'TEST_REGISTRY2 name should match') }) it('should retain results when it is queried with same credentials ', async function () { await dataProviderObject.getRegistries(TEST_REGION, schemaClient, testCredentials) await dataProviderObject.getRegistries(TEST_REGION2, schemaClient, testCredentials) assert.ok( cacheData.credentialsRegionDataList.length === 1, 'Cache should contain data for a single credential' ) assert.strictEqual( cacheData.credentialsRegionDataList[0].credentials, testCredentials, 'Credentials key should match' ) assert.ok( cacheData.credentialsRegionDataList[0].regionDataList.length === 2, 'Single cache element should have two region data' ) const regionData1 = cacheData.credentialsRegionDataList[0].regionDataList[0] const regionData2 = cacheData.credentialsRegionDataList[0].regionDataList[1] assert.strictEqual(regionData1.region, TEST_REGION) assert.strictEqual(regionData2.region, TEST_REGION2) assert.ok(regionData1.registryNames.length === 2, 'First region should have two registryNames') assert.ok(regionData2.registryNames.length === 1, 'Second region should have one registryName') assert.deepStrictEqual( regionData1.registrySchemasMapList, [], 'First region should have an empty registrySchemasMapList' ) assert.deepStrictEqual( regionData2.registrySchemasMapList, [], 'Second region should have an empty registrySchemasMapList' ) }) it('should retain results when it is queried with different credentials ', async function () { await dataProviderObject.getRegistries(TEST_REGION, schemaClient, testCredentials) await dataProviderObject.getRegistries(TEST_REGION, schemaClient, testCredentials2) assert.ok(cacheData.credentialsRegionDataList.length === 2, 'Cache should contain data for two credentials') assert.strictEqual( cacheData.credentialsRegionDataList[0].credentials, testCredentials, 'First cache element should have a matching credentials key' ) assert.strictEqual( cacheData.credentialsRegionDataList[1].credentials, testCredentials2, 'Second cache element should have a matching credentials key' ) assert.ok( cacheData.credentialsRegionDataList[0].regionDataList.length === 1, 'First cache element should have a single region data' ) assert.ok( cacheData.credentialsRegionDataList[1].regionDataList.length === 1, 'Second cache element should have a single region data' ) }) it('should return undefined when error occurs', async function () { sandbox.restore() sandbox.stub(schemaClient, 'listRegistries').throws(new Error('Custom error')) const result = await dataProviderObject.getRegistries(TEST_REGION, schemaClient, testCredentials) assert.strictEqual(result, undefined) assert.ok( cacheData.credentialsRegionDataList[0].regionDataList.length === 0, 'No data should be cached when error occurs' ) }) }) describe('getSchemas', function () { it('should return schemas for given region', async function () { const schemas = await dataProviderObject.getSchemas( TEST_REGION, TEST_REGISTRY, schemaClient, testCredentials ) assert.ok(schemas!.length === 2, 'Unexpected number of schemas returned') assert.strictEqual(schemas![0], schemaSummary, 'schemaSummary should match') assert.strictEqual(schemas![1], schemaSummary2, 'schemaSummary2 should match') }) it('should retain results when it is queried with same credentials ', async function () { await dataProviderObject.getSchemas(TEST_REGION, TEST_REGISTRY, schemaClient, testCredentials) await dataProviderObject.getSchemas(TEST_REGION, TEST_REGISTRY2, schemaClient, testCredentials) assert.ok( cacheData.credentialsRegionDataList.length === 1, 'Cache should contain data for a single credential' ) assert.strictEqual( cacheData.credentialsRegionDataList[0].credentials, testCredentials, 'Credentials key should match' ) assert.ok( cacheData.credentialsRegionDataList[0].regionDataList.length === 1, 'Cache should contain data for a single region' ) const regionData = cacheData.credentialsRegionDataList[0].regionDataList[0] assert.ok( regionData.registrySchemasMapList.length === 2, 'There should be 2 elements in registrySchemasMapList' ) assert.deepStrictEqual( regionData.registrySchemasMapList[0].schemaList, [schemaSummary, schemaSummary2], 'First registry should have two schemas' ) assert.deepStrictEqual( regionData.registrySchemasMapList[1].schemaList, [schemaSummary], 'Second registry should have one schema' ) }) it('should retain results when it is queried with different credentials ', async function () { await dataProviderObject.getSchemas(TEST_REGION, TEST_REGISTRY, schemaClient, testCredentials) await dataProviderObject.getSchemas(TEST_REGION, TEST_REGISTRY, schemaClient, testCredentials2) assert.ok(cacheData.credentialsRegionDataList.length === 2, 'Cache should contain data for two credentials') assert.strictEqual( cacheData.credentialsRegionDataList[0].credentials, testCredentials, 'Credentials key should match for first element' ) assert.strictEqual( cacheData.credentialsRegionDataList[1].credentials, testCredentials2, 'Credentials key should match for second element' ) assert.ok( cacheData.credentialsRegionDataList[0].regionDataList.length === 1, 'First cache element should have a single region data' ) assert.ok( cacheData.credentialsRegionDataList[1].regionDataList.length === 1, 'Second cache element should have a single region data' ) }) it('should return undefined when error occurs ', async function () { sandbox.restore() sandbox.stub(schemaClient, 'listSchemas').throws(new Error('Custom error')) const result = await dataProviderObject.getSchemas( TEST_REGION, TEST_REGISTRY, schemaClient, testCredentials ) assert.strictEqual(result, undefined) assert.ok( cacheData.credentialsRegionDataList[0].regionDataList.length === 0, 'No data should be cached when error occurs' ) }) }) })
the_stack
import testdata from "./testdata"; import generateEntries from "../src/main/core/entry/en"; beforeAll(() => { testdata.load(); }); test("", () => { expect(generateEntries("Test")).toEqual(expect.arrayContaining(["Test", "test"])); }); test("", () => { let r; r = generateEntries("ladies-in-waiting"); expect(r.includes("ladies-in-waiting")).toBeTruthy(); expect(r.includes("lady-in-waiting")).toBeTruthy(); r = generateEntries("stands-by"); expect(r.includes("stands-by")).toBeTruthy(); expect(r.includes("stand-by")).toBeTruthy(); }); test("", () => { expect(generateEntries("thousand miles down")).toEqual( expect.arrayContaining([ "thousand miles down", "thousand miles", "thousand", "thousand ~ down", "thousand down", "thousand mile", ]) ); expect(generateEntries("american english")).toEqual(expect.arrayContaining(["american english", "american"])); expect(generateEntries("American English")).toEqual( expect.arrayContaining(["American English", "American", "american english", "american"]) ); expect(generateEntries("Announcement of Hoge")).toEqual( expect.arrayContaining([ "Announcement of Hoge", "Announcement of", "Announcement", "announcement ~ hoge", "announcement hoge", "announcement of hoge", "announcement of", "announcement", "announcement ~ hoge", "announcement hoge", ]) ); expect(generateEntries("wonder if I shall")).toEqual( expect.arrayContaining([ "wonder if i shall", "wonder if i", "wonder if", "wonder", "wonder ~ i", "wonder i", "wonder if ~ shall", "wonder ~ i shall", "wonder A i B", "wonder ~ shall", "wonder i shall", "wonder if shall", "wonder shall", "wond", "wonder if i shall", "wonder if i", "wonder ~ i", "wonder i", "wonder ~ i shall", "wonder A i B", "wonder i shall", ]) ); expect(generateEntries("in my favor")).toEqual(expect.arrayContaining(["in someone's favor"])); expect(generateEntries("in my best favor")).toEqual(expect.arrayContaining(["in someone's favor"])); }); test("", () => { expect(generateEntries("blue-gray")).toEqual( expect.arrayContaining(["blue-gray", "blue gray", "blue", "gray", "blue-", "-gray", "bluegray"]) ); expect(generateEntries("third-party")).toEqual( expect.arrayContaining(["third-party", "third party", "third", "party", "third-", "-party", "thirdparty"]) ); // non-breaking hyphen(U+2011) expect(generateEntries("blue‑gray")).toEqual( expect.arrayContaining([ "blue-gray", // "blue gray", "blue", "gray", "blue-", "-gray", "bluegray", ]) ); expect(generateEntries("third‑party")).toEqual( expect.arrayContaining(["third-party", "third party", "third", "party", "third-", "-party", "thirdparty"]) ); }); test("", () => { expect(generateEntries("folk tales")).toEqual( expect.arrayContaining([ "folk tales", // "folk", "folk tale", ]) ); }); test("", () => { expect(generateEntries("deal with")).toEqual( expect.arrayContaining([ "deal with", // "deal", ]) ); expect(generateEntries("dealt with")).toEqual( expect.arrayContaining([ "dealt with", // "dealt", "deal with", "deal", ]) ); expect(generateEntries("dealing with")).toEqual( expect.arrayContaining([ "dealing with", // "dealing", "deal with", "deal", ]) ); expect(generateEntries("run with")).toEqual( expect.arrayContaining([ "run with", // "run", ]) ); expect(generateEntries("ran with")).toEqual( expect.arrayContaining([ "ran with", // "ran", "run with", "run", ]) ); expect(generateEntries("running with")).toEqual( expect.arrayContaining([ "running with", // "running", "run with", "run", ]) ); expect(generateEntries("yelled at")).toEqual( expect.arrayContaining([ "yell at", // "yell", ]) ); expect(generateEntries("yelling at")).toEqual( expect.arrayContaining([ "yell at", // "yell", ]) ); expect(generateEntries("dealt dealt dealt")).toEqual( expect.arrayContaining([ "dealt dealt dealt", "dealt dealt", "dealt", "deal dealt dealt", "deal dealt", "deal", "dealt ~ dealt", "deal ~ dealt", ]) ); }); test("", () => { expect(generateEntries("cut back")).toEqual( expect.arrayContaining([ "cut back", // "cut", ]) ); expect(generateEntries("cutting back")).toEqual( expect.arrayContaining([ "cutting back", // "cutting", "cut back", "cut", ]) ); expect(generateEntries("die out")).toEqual( expect.arrayContaining([ "die out", // "die", ]) ); expect(generateEntries("dying out")).toEqual( expect.arrayContaining([ "dying out", // "dying", "die out", "die", ]) ); expect(generateEntries("play with")).toEqual( expect.arrayContaining([ "play with", // "play", ]) ); expect(generateEntries("played with")).toEqual( expect.arrayContaining([ "played with", // "played", "play with", "play", ]) ); expect(generateEntries("pop up")).toEqual( expect.arrayContaining([ "pop up", // "pop", ]) ); expect(generateEntries("popped up")).toEqual( expect.arrayContaining([ "popped up", // "popped", "pop up", "pop", ]) ); }); test("", () => { expect(generateEntries("aaa_bbb")).toEqual(expect.arrayContaining(["aaa_bbb", "aaa bbb", "aaa", "bbb"])); expect(generateEntries("worker_processes")).toEqual( expect.arrayContaining([ "worker_processes", "worker_process", "worker processes", "worker", "processes", "process", "work", ]) ); }); test("", () => { expect(generateEntries("on one's own")).toEqual( expect.arrayContaining([ "on one's own", // "on one's", "on", "on ~ own", "on own", "on one", ]) ); expect(generateEntries("on his own")).toEqual( expect.arrayContaining([ "on his own", "on his", "on", "on ~ own", "on own", "on one's own", "on one's", "on one", "on someone's own", "on someone's", "on someone", ]) ); expect(generateEntries("his only son")).toEqual( expect.arrayContaining([ "his only son", "his only", "his", "his ~ son", "his son", "one's only son", "one's only", "one' only son", "one' only", "one's ~ son", "one's son", "one' ~ son", "one' son", "someone's only son", "someone's only", "someone' only son", "someone' only", "someone's ~ son", "someone's son", "someone' ~ son", "someone' son", ]) ); expect(generateEntries("Senete's")).toEqual( expect.arrayContaining([ "Senete's", // "Senete'", "Senete", "senete's", "senete'", "senete", ]) ); expect(generateEntries("by oneself")).toEqual( expect.arrayContaining([ "by oneself", // "by", ]) ); expect(generateEntries("by myself")).toEqual( expect.arrayContaining([ "by myself", // "by", "by oneself", ]) ); expect(generateEntries("brush one's dog")).toEqual( expect.arrayContaining(["brush one's dog", "brush one's", "brush", "brush ~ dog", "brush dog", "brush one"]) ); expect(generateEntries("brush Taro's dog")).toEqual( expect.arrayContaining([ "brush Taro's dog", "brush Taro's", "brush", "brush ~ dog", "brush dog", "brush Taro", "brush one's dog", "brush one's", "brush one", "brush someone's dog", "brush someone's", "brush someone", "brush taro's dog", "brush taro's", "brush taro", ]) ); }); test("", () => { expect(generateEntries("colour")).toEqual(expect.arrayContaining(["colour", "color"])); expect(generateEntries("women")).toEqual(expect.arrayContaining(["women", "woman"])); }); test("", () => { expect(generateEntries("abc.")).toEqual(expect.arrayContaining(["abc"])); expect(generateEntries("abc.", true)).toEqual(expect.arrayContaining(["abc", "ABC"])); expect(generateEntries("abc.", false, true)).toEqual(expect.arrayContaining(["abc"])); expect(generateEntries("abc.", true, true)).toEqual(expect.arrayContaining(["abc", "ABC"])); }); test("", () => { expect(generateEntries("pros / cons")).toEqual( expect.arrayContaining([ "pros / cons", // "pros and cons", "pros or cons", ]) ); expect(generateEntries("pros/cons")).toEqual( expect.arrayContaining([ "pros/cons", // "pros / cons", "pros and cons", "pros or cons", ]) ); }); test("", () => { expect(generateEntries("in the wild. That is a pen.")).toEqual( expect.arrayContaining([ "in the wild", // ]) ); expect(generateEntries("in the wild, That is a pen.")).toEqual( expect.arrayContaining([ "in the wild", // ]) ); }); test("", () => { expect(generateEntries("self taught")).toEqual( expect.arrayContaining([ "self taught", // "selftaught", ]) ); }); test("", () => { expect(generateEntries("united kingdom")).toEqual( expect.arrayContaining([ "United", // "United Kingdom", ]) ); expect(generateEntries("canadian broadcasting corporation")).toEqual( expect.arrayContaining([ "Canadian", // "Canadian Broadcasting", "Canadian Broadcasting Corporation", ]) ); }); test("", () => { expect(generateEntries("craaaaaaaaaaaaaaazy")).toEqual( expect.arrayContaining([ "crazy", // "craazy", ]) ); expect(generateEntries("craaazy")).toEqual( expect.arrayContaining([ "crazy", // "craazy", ]) ); }); test("", () => { expect(generateEntries("")).toEqual(expect.arrayContaining([])); });
the_stack
import { testConfig } from 'houdini-common' // locals import { Cache, rootID } from '../cache' import { SubscriptionSelection } from '../../types' const config = testConfig() test('prepend linked lists update', function () { // instantiate the cache const cache = new Cache(config) const selection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, friends: { type: 'User', keyRaw: 'friends', update: 'prepend', fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, } as SubscriptionSelection // add some data to the cache cache.write({ selection, data: { viewer: { id: '1', firstName: 'bob', friends: [ { id: '2', firstName: 'jane', }, { id: '3', firstName: 'mary', }, ], }, }, applyUpdates: true, }) // make sure we can get the linked lists back expect( cache.internal .getRecord(cache.id('User', '1')!) ?.flatLinkedList('friends') .map((data) => data!.fields) ).toEqual([ { id: '2', firstName: 'jane', }, { id: '3', firstName: 'mary', }, ]) // add some data to the cache cache.write({ selection, data: { viewer: { id: '1', firstName: 'bob', friends: [ { id: '4', firstName: 'jane', }, { id: '5', firstName: 'mary', }, ], }, }, applyUpdates: true, }) // make sure we can get the linked lists back expect( cache.internal .getRecord(cache.id('User', '1')!) ?.flatLinkedList('friends') .map((data) => data!.fields) ).toEqual([ { id: '4', firstName: 'jane', }, { id: '5', firstName: 'mary', }, { id: '2', firstName: 'jane', }, { id: '3', firstName: 'mary', }, ]) }) test('append in list', function () { // instantiate a cache const cache = new Cache(config) const selection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, } // start off associated with one object cache.write({ selection, data: { viewer: { id: '1', friends: [ { id: '2', firstName: 'jane', }, ], }, }, }) // a function to spy on that will play the role of set const set = jest.fn() // subscribe to the fields cache.subscribe({ rootType: 'Query', set, selection, }) // insert an element into the list (no parent ID) cache.list('All_Users').append( { id: { type: 'ID', keyRaw: 'id' }, firstName: { type: 'String', keyRaw: 'firstName' } }, { id: '3', firstName: 'mary', } ) // make sure we got the new value expect(set).toHaveBeenCalledWith({ viewer: { id: '1', friends: [ { firstName: 'jane', id: '2', }, { firstName: 'mary', id: '3', }, ], }, }) }) test('prepend in list', function () { // instantiate a cache const cache = new Cache(config) const selection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, } // start off associated with one object cache.write({ selection, data: { viewer: { id: '1', friends: [ { id: '2', firstName: 'jane', }, ], }, }, }) // a function to spy on that will play the role of set const set = jest.fn() // subscribe to the fields cache.subscribe({ rootType: 'Query', set, selection, }) // insert an element into the list (no parent ID) cache.list('All_Users').prepend( { id: { type: 'ID', keyRaw: 'id' }, firstName: { type: 'String', keyRaw: 'firstName' } }, { id: '3', firstName: 'mary', } ) // make sure we got the new value expect(set).toHaveBeenCalledWith({ viewer: { id: '1', friends: [ { firstName: 'mary', id: '3', }, { firstName: 'jane', id: '2', }, ], }, }) }) test('remove from connection', function () { // instantiate a cache const cache = new Cache(config) const selection: SubscriptionSelection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: true, type: 'User', }, fields: { edges: { type: 'UserEdge', keyRaw: 'edges', fields: { node: { type: 'Node', keyRaw: 'node', abstract: true, fields: { __typename: { type: 'String', keyRaw: '__typename', }, id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, }, }, }, }, } // start off associated with one object cache.write({ selection, data: { viewer: { id: '1', friends: { edges: [ { node: { __typename: 'User', id: '2', firstName: 'jane', }, }, { node: { __typename: 'User', id: '3', firstName: 'jane', }, }, ], }, }, }, }) // a function to spy on that will play the role of set const set = jest.fn() // subscribe to the fields cache.subscribe({ rootType: 'Query', set, selection: selection, }) // remove user 2 from the list cache.list('All_Users').remove({ id: '2', }) // the first time set was called, a new entry was added. // the second time it's called, we get a new value for mary-prime expect(set).toHaveBeenCalledWith({ viewer: { id: '1', friends: { edges: [ { node: { __typename: 'User', id: '3', firstName: 'jane', }, }, ], }, }, }) // make sure we aren't subscribing to user 2 any more expect( cache.internal.getRecord(cache.id('User', '2')!)?.getSubscribers('firstName') ).toHaveLength(0) // but we're still subscribing to user 3 expect( cache.internal.getRecord(cache.id('User', '3')!)?.getSubscribers('firstName') ).toHaveLength(1) // make sure we deleted the edge holding onto this information expect(cache.internal.getRecord('User:1.friends.edges[0]#User:2')).toBeUndefined() }) test('append in connection', function () { // instantiate a cache const cache = new Cache(config) const selection: SubscriptionSelection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: true, type: 'User', }, fields: { edges: { type: 'UserEdge', keyRaw: 'edges', fields: { node: { type: 'Node', keyRaw: 'node', abstract: true, fields: { __typename: { type: 'String', keyRaw: '__typename', }, id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, }, }, }, }, } // start off associated with one object cache.write({ selection, data: { viewer: { id: '1', friends: { edges: [ { node: { __typename: 'User', id: '2', firstName: 'jane', }, }, ], }, }, }, }) // a function to spy on that will play the role of set const set = jest.fn() // subscribe to the fields cache.subscribe({ rootType: 'Query', set, selection, }) // insert an element into the list (no parent ID) cache.list('All_Users').append( { id: { type: 'ID', keyRaw: 'id' }, firstName: { type: 'String', keyRaw: 'firstName' } }, { id: '3', firstName: 'mary', } ) // make sure we got the new value expect(set).toHaveBeenCalledWith({ viewer: { id: '1', friends: { edges: [ { node: { __typename: 'User', id: '2', firstName: 'jane', }, }, { node: { __typename: 'User', id: '3', firstName: 'mary', }, }, ], }, }, }) }) test('inserting data with an update overwrites a record inserted with list.append', function () { // instantiate a cache const cache = new Cache(config) const selection: SubscriptionSelection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: true, type: 'User', }, fields: { edges: { type: 'UserEdge', keyRaw: 'edges', fields: { node: { type: 'Node', keyRaw: 'node', abstract: true, fields: { __typename: { type: 'String', keyRaw: '__typename', }, id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, }, }, }, }, } // start off associated with one object cache.write({ selection, data: { viewer: { id: '1', friends: { edges: [ { node: { __typename: 'User', id: '2', firstName: 'jane', }, }, ], }, }, }, }) // a function to spy on that will play the role of set const set = jest.fn() // subscribe to the fields cache.subscribe({ rootType: 'Query', set, selection, }) // insert an element into the list (no parent ID) cache.list('All_Users').append( { id: { type: 'ID', keyRaw: 'id' }, firstName: { type: 'String', keyRaw: 'firstName' } }, { id: '3', firstName: 'mary', } ) // insert a record with a query update cache.write({ applyUpdates: true, data: { viewer: { id: '1', firstName: 'John', friends: { edges: [ { cursor: '1234', node: { __typename: 'User', id: '3', firstName: 'mary', }, }, ], }, }, }, selection: { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, friends: { type: 'User', keyRaw: 'friends', fields: { edges: { type: 'UserEdge', keyRaw: 'edges', update: 'append', fields: { cursor: { type: 'String', keyRaw: 'cursor', }, node: { type: 'User', keyRaw: 'node', fields: { __typename: { type: 'String', keyRaw: '__typename', }, id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, }, }, }, }, } as SubscriptionSelection, }) // make sure the duplicate has been removed expect(set).toHaveBeenNthCalledWith(2, { viewer: { id: '1', friends: { edges: [ { node: { __typename: 'User', id: '2', firstName: 'jane', }, }, { node: { __typename: 'User', id: '3', firstName: 'mary', }, }, ], }, }, }) }) test('list filter - must_not positive', function () { // instantiate a cache const cache = new Cache(config) const selection: SubscriptionSelection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, filters: { foo: { kind: 'String', value: 'bar', }, }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, } // start off associated with one object cache.write({ selection, data: { viewer: { id: '1', friends: [ { id: '2', firstName: 'jane', }, ], }, }, }) // a function to spy on that will play the role of set const set = jest.fn() // subscribe to the fields cache.subscribe({ rootType: 'Query', set, selection, }) // insert an element into the list (no parent ID) cache .list('All_Users') .when({ must_not: { foo: 'not-bar' } }) .prepend( { id: { type: 'ID', keyRaw: 'id' }, firstName: { type: 'String', keyRaw: 'firstName' }, }, { id: '3', firstName: 'mary', } ) // make sure we got the new value expect(set).toHaveBeenCalledWith({ viewer: { id: '1', friends: [ { firstName: 'mary', id: '3', }, { firstName: 'jane', id: '2', }, ], }, }) }) test('list filter - must_not negative', function () { // instantiate a cache const cache = new Cache(config) const selection: SubscriptionSelection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, filters: { foo: { kind: 'String', value: 'bar', }, }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, } // start off associated with one object cache.write({ selection, data: { viewer: { id: '1', friends: [ { id: '2', firstName: 'jane', }, ], }, }, }) // a function to spy on that will play the role of set const set = jest.fn() // subscribe to the fields cache.subscribe({ rootType: 'Query', set, selection, }) // insert an element into the list (no parent ID) cache .list('All_Users') .when({ must_not: { foo: 'bar' } }) .prepend( { id: { type: 'ID', keyRaw: 'id' }, firstName: { type: 'String', keyRaw: 'firstName' }, }, { id: '3', firstName: 'mary', } ) // make sure we got the new value expect(set).not.toHaveBeenCalled() }) test('list filter - must positive', function () { // instantiate a cache const cache = new Cache(config) const selection: SubscriptionSelection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, filters: { foo: { kind: 'String', value: 'bar', }, }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, } // start off associated with one object cache.write({ selection, data: { viewer: { id: '1', friends: [ { id: '2', firstName: 'jane', }, ], }, }, }) // a function to spy on that will play the role of set const set = jest.fn() // subscribe to the fields cache.subscribe({ rootType: 'Query', set, selection, }) // insert an element into the list (no parent ID) cache .list('All_Users') .when({ must: { foo: 'bar' } }) .prepend( { id: { type: 'ID', keyRaw: 'id' }, firstName: { type: 'String', keyRaw: 'firstName' }, }, { id: '3', firstName: 'mary', } ) // make sure we got the new value expect(set).toHaveBeenCalledWith({ viewer: { id: '1', friends: [ { firstName: 'mary', id: '3', }, { firstName: 'jane', id: '2', }, ], }, }) }) test('list filter - must negative', function () { // instantiate a cache const cache = new Cache(config) const selection: SubscriptionSelection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, filters: { foo: { kind: 'String', value: 'bar', }, }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, } // start off associated with one object cache.write({ selection, data: { viewer: { id: '1', friends: [ { id: '2', firstName: 'jane', }, ], }, }, }) // a function to spy on that will play the role of set const set = jest.fn() // subscribe to the fields cache.subscribe({ rootType: 'Query', set, selection, }) // insert an element into the list (no parent ID) cache .list('All_Users') .when({ must: { foo: 'not-bar' } }) .prepend( { id: { type: 'ID', keyRaw: 'id' }, firstName: { type: 'String', keyRaw: 'firstName' }, }, { id: '3', firstName: 'mary', } ) // make sure we got the new value expect(set).not.toHaveBeenCalled() }) test('remove from list', function () { // instantiate a cache const cache = new Cache(config) const selection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, } // start off associated with one object cache.write({ selection, data: { viewer: { id: '1', friends: [ { id: '2', firstName: 'jane', }, ], }, }, }) // a function to spy on that will play the role of set const set = jest.fn() // subscribe to the fields cache.subscribe({ rootType: 'Query', set, selection: selection, }) // remove user 2 from the list cache.list('All_Users').remove({ id: '2', }) // the first time set was called, a new entry was added. // the second time it's called, we get a new value for mary-prime expect(set).toHaveBeenCalledWith({ viewer: { id: '1', friends: [], }, }) // make sure we aren't subscribing to user 2 any more expect( cache.internal.getRecord(cache.id('User', '2')!)?.getSubscribers('firstName') ).toHaveLength(0) }) test('delete node', function () { // instantiate a cache const cache = new Cache(config) const selection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, } // start off associated with one object cache.write({ selection, data: { viewer: { id: '1', friends: [ { id: '2', firstName: 'jane', }, ], }, }, }) // a function to spy on that will play the role of set const set = jest.fn() // subscribe to the fields cache.subscribe({ rootType: 'Query', set, selection, }) // remove user 2 from the list cache.delete( 'User', cache.id('User', { id: '2', })! ) // we should have been updated with an empty list expect(set).toHaveBeenCalledWith({ viewer: { id: '1', friends: [], }, }) // make sure its empty now expect(cache.internal.getRecord('User:2')).toBeFalsy() }) test('delete node from connection', function () { // instantiate a cache const cache = new Cache(config) const selection: SubscriptionSelection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: true, type: 'User', }, fields: { edges: { type: 'UserEdge', keyRaw: 'edges', fields: { node: { type: 'Node', keyRaw: 'node', abstract: true, fields: { __typename: { type: 'String', keyRaw: '__typename', }, id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, }, }, }, }, } // start off associated with one object cache.write({ selection, data: { viewer: { id: '1', friends: { edges: [ { node: { __typename: 'User', id: '2', firstName: 'jane', }, }, ], }, }, }, }) // a function to spy on that will play the role of set const set = jest.fn() // subscribe to the fields cache.subscribe({ rootType: 'Query', set, selection, }) // remove user 2 from the list cache.delete( 'User', cache.id('User', { id: '2', })! ) // we should have been updated with an empty list expect(set).toHaveBeenCalledWith({ viewer: { id: '1', friends: { edges: [], }, }, }) // make sure its empty now expect(cache.internal.getRecord('User:2')).toBeFalsy() }) test('append operation', function () { // instantiate a cache const cache = new Cache(config) // create a list we will add to cache.write({ selection: { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, }, }, }, data: { viewer: { id: '1', }, }, }) // subscribe to the data to register the list cache.subscribe( { rootType: 'User', selection: { friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, parentID: cache.id('User', '1')!, set: jest.fn(), }, {} ) // write some data to a different location with a new user // that should be added to the list cache.write({ selection: { newUser: { type: 'User', keyRaw: 'newUser', operations: [ { action: 'insert', list: 'All_Users', parentID: { kind: 'String', value: cache.id('User', '1')!, }, }, ], fields: { id: { type: 'ID', keyRaw: 'id', }, }, }, }, data: { newUser: { id: '3', }, }, }) // make sure we just added to the list expect([...cache.list('All_Users', cache.id('User', '1')!)]).toHaveLength(1) }) test('append from list', function () { // instantiate a cache const cache = new Cache(config) // create a list we will add to cache.write({ selection: { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, }, }, }, data: { viewer: { id: '1', }, }, }) // subscribe to the data to register the list cache.subscribe( { rootType: 'User', selection: { friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, parentID: cache.id('User', '1')!, set: jest.fn(), }, {} ) // write some data to a different location with a new user // that should be added to the list cache.write({ selection: { newUser: { type: 'User', keyRaw: 'newUser', operations: [ { action: 'insert', list: 'All_Users', parentID: { kind: 'String', value: cache.id('User', '1')!, }, }, ], fields: { id: { type: 'ID', keyRaw: 'id', }, }, }, }, data: { newUser: [{ id: '3' }, { id: '4' }], }, }) // make sure we just added to the list expect([...cache.list('All_Users', cache.id('User', '1')!)]).toHaveLength(2) }) test('append when operation', function () { // instantiate a cache const cache = new Cache(config) // create a list we will add to cache.write({ selection: { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, }, }, }, data: { viewer: { id: '1', }, }, }) // subscribe to the data to register the list cache.subscribe( { rootType: 'User', selection: { friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, filters: { value: { kind: 'String', value: 'foo', }, }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, parentID: cache.id('User', '1')!, set: jest.fn(), }, {} ) // write some data to a different location with a new user // that should be added to the list cache.write({ selection: { newUser: { type: 'User', keyRaw: 'newUser', operations: [ { action: 'insert', list: 'All_Users', parentID: { kind: 'String', value: cache.id('User', '1')!, }, when: { must: { value: 'not-foo', }, }, }, ], fields: { id: { type: 'ID', keyRaw: 'id', }, }, }, }, data: { newUser: { id: '3', }, }, }) // make sure we just added to the list expect([...cache.list('All_Users', cache.id('User', '1')!)]).toHaveLength(0) }) test('prepend when operation', function () { // instantiate a cache const cache = new Cache(config) // create a list we will add to cache.write({ selection: { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, }, }, }, data: { viewer: { id: '1', }, }, }) // subscribe to the data to register the list cache.subscribe( { rootType: 'User', selection: { friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, filters: { value: { kind: 'String', value: 'foo', }, }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, parentID: cache.id('User', '1')!, set: jest.fn(), }, {} ) // write some data to a different location with a new user // that should be added to the list cache.write({ selection: { newUser: { type: 'User', keyRaw: 'newUser', operations: [ { action: 'insert', list: 'All_Users', parentID: { kind: 'String', value: cache.id('User', '1')!, }, position: 'first', when: { must: { value: 'not-foo', }, }, }, ], fields: { id: { type: 'ID', keyRaw: 'id', }, }, }, }, data: { newUser: { id: '3', }, }, }) // make sure we just added to the list expect([...cache.list('All_Users', cache.id('User', '1')!)]).toHaveLength(0) }) test('prepend operation', function () { // instantiate a cache const cache = new Cache(config) // create a list we will add to cache.write({ selection: { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', fields: { id: { type: 'String', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, }, data: { viewer: { id: '1', friends: [ { id: '2', firstName: 'mary', }, ], }, }, }) // subscribe to the data to register the list cache.subscribe( { rootType: 'User', selection: { friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, parentID: cache.id('User', '1')!, set: jest.fn(), }, {} ) // write some data to a different location with a new user // that should be added to the list cache.write({ selection: { newUser: { type: 'User', keyRaw: 'newUser', operations: [ { action: 'insert', list: 'All_Users', parentID: { kind: 'String', value: cache.id('User', '1')!, }, position: 'first', }, ], fields: { id: { type: 'ID', keyRaw: 'id', }, }, }, }, data: { newUser: { id: '3', }, }, }) // make sure we just added to the list expect( [...cache.list('All_Users', cache.id('User', '1')!)].map((record) => record!.fields.id) ).toEqual(['3', '2']) }) test('remove operation', function () { // instantiate a cache const cache = new Cache(config) // create a list we will add to cache.write({ selection: { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, }, data: { viewer: { id: '1', friends: [{ id: '2', firstName: 'jane' }], }, }, }) // subscribe to the data to register the list cache.subscribe( { rootType: 'User', selection: { friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, parentID: cache.id('User', '1')!, set: jest.fn(), }, {} ) // write some data to a different location with a new user // that should be removed from the operation cache.write({ selection: { newUser: { type: 'User', keyRaw: 'newUser', operations: [ { action: 'remove', list: 'All_Users', parentID: { kind: 'String', value: cache.id('User', '1')!, }, }, ], fields: { id: { type: 'ID', keyRaw: 'id', }, }, }, }, data: { newUser: { id: '2', }, }, }) // make sure we removed the element from the list expect([...cache.list('All_Users', cache.id('User', '1')!)]).toHaveLength(0) }) test('remove operation from list', function () { // instantiate a cache const cache = new Cache(config) // create a list we will add to cache.write({ selection: { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, }, data: { viewer: { id: '1', friends: [ { id: '2', firstName: 'jane' }, { id: '3', firstName: 'Alfred' }, ], }, }, }) // subscribe to the data to register the list cache.subscribe( { rootType: 'User', selection: { friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, parentID: cache.id('User', '1')!, set: jest.fn(), }, {} ) // write some data to a different location with a new user // that should be removed from the operation cache.write({ selection: { newUser: { type: 'User', keyRaw: 'newUser', operations: [ { action: 'remove', list: 'All_Users', parentID: { kind: 'String', value: cache.id('User', '1')!, }, }, ], fields: { id: { type: 'ID', keyRaw: 'id', }, }, }, }, data: { newUser: [{ id: '2' }, { id: '3' }], }, }) // make sure we removed the element from the list expect([...cache.list('All_Users', cache.id('User', '1')!)]).toHaveLength(0) }) test('delete operation', function () { // instantiate a cache const cache = new Cache(config) // create a list we will add to cache.write({ selection: { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, }, data: { viewer: { id: '1', friends: [{ id: '2', firstName: 'jane' }], }, }, }) // subscribe to the data to register the list cache.subscribe( { rootType: 'User', selection: { friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, parentID: cache.id('User', '1')!, set: jest.fn(), }, {} ) // write some data to a different location with a new user // that should be added to the list cache.write({ selection: { deleteUser: { type: 'User', keyRaw: 'deleteUser', fields: { id: { type: 'ID', keyRaw: 'id', operations: [ { action: 'delete', type: 'User', }, ], }, }, }, }, data: { deleteUser: { id: '2', }, }, }) // make sure we removed the element from the list expect([...cache.list('All_Users', cache.id('User', '1')!)]).toHaveLength(0) expect(cache.internal.getRecord('User:2')).toBeFalsy() }) test('delete operation from list', function () { // instantiate a cache const cache = new Cache(config) // create a list we will add to cache.write({ selection: { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, friends: { type: 'User', keyRaw: 'friends', fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, }, data: { viewer: { id: '1', friends: [ { id: '2', firstName: 'jane' }, { id: '3', firstName: 'Alfred' }, ], }, }, }) // subscribe to the data to register the list cache.subscribe( { rootType: 'User', selection: { friends: { type: 'User', keyRaw: 'friends', list: { name: 'All_Users', connection: false, type: 'User', }, fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, parentID: cache.id('User', '1')!, set: jest.fn(), }, {} ) // write some data to a different location with a new user // that should be added to the list cache.write({ selection: { deleteUser: { type: 'User', keyRaw: 'deleteUser', fields: { id: { type: 'ID', keyRaw: 'id', operations: [ { action: 'delete', type: 'User', }, ], }, }, }, }, data: { deleteUser: { id: ['2', '3'], }, }, }) // make sure we removed the element from the list expect([...cache.list('All_Users', cache.id('User', '1')!)]).toHaveLength(0) expect(cache.internal.getRecord('User:2')).toBeFalsy() expect(cache.internal.getRecord('User:3')).toBeFalsy() }) test('disabled linked lists update', function () { // instantiate the cache const cache = new Cache(config) const selection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, friends: { type: 'User', keyRaw: 'friends', update: 'append', fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, } as SubscriptionSelection // add some data to the cache cache.write({ selection, data: { viewer: { id: '1', firstName: 'bob', friends: [ { id: '2', firstName: 'jane', }, { id: '3', firstName: 'mary', }, ], }, }, }) // make sure we can get the linked lists back expect( cache.internal .getRecord(cache.id('User', '1')!) ?.flatLinkedList('friends') .map((data) => data!.fields) ).toEqual([ { id: '2', firstName: 'jane', }, { id: '3', firstName: 'mary', }, ]) // add some data to the cache cache.write({ selection, data: { viewer: { id: '1', firstName: 'bob', friends: [ { id: '3', firstName: 'jane', }, { id: '4', firstName: 'mary', }, ], }, }, }) // make sure we can get the linked lists back expect( cache.internal .getRecord(cache.id('User', '1')!) ?.flatLinkedList('friends') .map((data) => data!.fields) ).toEqual([ { id: '3', firstName: 'jane', }, { id: '4', firstName: 'mary', }, ]) }) test('append linked lists update', function () { // instantiate the cache const cache = new Cache(config) const selection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, friends: { type: 'User', keyRaw: 'friends', update: 'append', fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, }, }, }, }, } as SubscriptionSelection // add some data to the cache cache.write({ selection, data: { viewer: { id: '1', firstName: 'bob', friends: [ { id: '2', firstName: 'jane', }, { id: '3', firstName: 'mary', }, ], }, }, }) // make sure we can get the linked lists back expect( cache.internal .getRecord(cache.id('User', '1')!) ?.flatLinkedList('friends') .map((data) => data!.fields) ).toEqual([ { id: '2', firstName: 'jane', }, { id: '3', firstName: 'mary', }, ]) // add some data to the cache cache.write({ selection, data: { viewer: { id: '1', firstName: 'bob', friends: [ { id: '4', firstName: 'jane', }, { id: '5', firstName: 'mary', }, ], }, }, applyUpdates: true, }) // make sure we can get the linked lists back expect( cache.internal .getRecord(cache.id('User', '1')!) ?.flatLinkedList('friends') .map((data) => data!.fields) ).toEqual([ { id: '2', firstName: 'jane', }, { id: '3', firstName: 'mary', }, { id: '4', firstName: 'jane', }, { id: '5', firstName: 'mary', }, ]) }) test('writing a scalar marked with a disabled update overwrites', function () { // instantiate the cache const cache = new Cache(config) const selection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, friends: { type: 'Int', keyRaw: 'friends', update: 'append', }, }, }, } as SubscriptionSelection // add some data to the cache cache.write({ selection, data: { viewer: { id: '1', firstName: 'bob', friends: [1], }, }, }) // make sure we can get the linked lists back expect(cache.internal.getData(cache.internal.record(rootID), selection, {})).toEqual({ viewer: { id: '1', firstName: 'bob', friends: [1], }, }) // add some data to the cache cache.write({ selection, data: { viewer: { id: '1', firstName: 'bob', friends: [2], }, }, }) // make sure we can get the updated lists back expect(cache.internal.getData(cache.internal.record(rootID), selection, {})).toEqual({ viewer: { id: '1', firstName: 'bob', friends: [2], }, }) }) test('writing a scalar marked with a prepend', function () { // instantiate the cache const cache = new Cache(config) const selection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, friends: { type: 'Int', keyRaw: 'friends', update: 'prepend', }, }, }, } as SubscriptionSelection // add some data to the cache cache.write({ selection, data: { viewer: { id: '1', firstName: 'bob', friends: [1], }, }, }) // make sure we can get the linked lists back expect(cache.internal.getData(cache.internal.record(rootID), selection, {})).toEqual({ viewer: { id: '1', firstName: 'bob', friends: [1], }, }) // add some data to the cache cache.write({ selection, data: { viewer: { id: '1', firstName: 'bob', friends: [2], }, }, applyUpdates: true, }) // make sure we can get the updated lists back expect(cache.internal.getData(cache.internal.record(rootID), selection, {})).toEqual({ viewer: { id: '1', firstName: 'bob', friends: [2, 1], }, }) }) test('writing a scalar marked with an append', function () { // instantiate the cache const cache = new Cache(config) const selection = { viewer: { type: 'User', keyRaw: 'viewer', fields: { id: { type: 'ID', keyRaw: 'id', }, firstName: { type: 'String', keyRaw: 'firstName', }, friends: { type: 'Int', keyRaw: 'friends', update: 'append', }, }, }, } as SubscriptionSelection // add some data to the cache cache.write({ selection, data: { viewer: { id: '1', firstName: 'bob', friends: [1], }, }, }) // make sure we can get the linked lists back expect(cache.internal.getData(cache.internal.record(rootID), selection, {})).toEqual({ viewer: { id: '1', firstName: 'bob', friends: [1], }, }) // add some data to the cache cache.write({ selection, data: { viewer: { id: '1', firstName: 'bob', friends: [2], }, }, applyUpdates: true, }) // make sure we can get the updated lists back expect(cache.internal.getData(cache.internal.record(rootID), selection, {})).toEqual({ viewer: { id: '1', firstName: 'bob', friends: [1, 2], }, }) })
the_stack
import { fetchAddr, fetchSize, genTensor, genTorchSize, sanitizeAddr } from '../../backend/backUtils'; import { Constraint } from '../../backend/constraintType'; import { Context, ContextSet } from '../../backend/context'; import { absExpIndexByLen, ceilDiv, isInstanceOf, reluLen, simplifyNum, simplifyShape } from '../../backend/expUtils'; import { CodeSource, ShValue, SVBool, SVFloat, SVInt, SVNotImpl, SVObject, SVSize, SVString, SVType, svTypeToString, } from '../../backend/sharpValues'; import { ExpBool, ExpNum, ExpShape, ExpString, NumBopType, NumOpType, NumUopType, ShapeOpType, } from '../../backend/symExpressions'; import { TorchBackend } from '../../backend/torchBackend'; import { LCImpl } from '..'; import { LCBase } from '../libcall'; export namespace TorchLCImpl { // return SVSize from args export function getInitShape( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 1) { return ctx .warnSizeWithMsg( `from 'LibCall.torch.getShape': got insufficient number of argument: ${params.length}`, source ) .toSet(); } const heap = ctx.heap; const argsAddr = params[0]; // tensorInit is always used in Tensor.__init__ -> force casting const args = fetchAddr(argsAddr, heap)! as SVObject; // if first argument is object that has 'shape' const firstArg = fetchAddr(args.getIndice(0), heap); if (firstArg?.type === SVType.Object) { // if first argument is shaped value, cast it to Tensor let mayShaped: ShValue | undefined = firstArg; if (!mayShaped.shape) { mayShaped = fetchAddr(firstArg.getAttr('shape'), heap); } if (mayShaped?.type === SVType.Object && mayShaped?.shape !== undefined) { return SVSize.createSize(ctx, mayShaped.shape, source).toSet(); } // else, check value is list of ... list of number const structure: (number | ExpNum)[] = []; let obj: ShValue | undefined = firstArg; let length = fetchAddr(firstArg.getAttr('$length'), heap); let shaped = true; if (length && length.type === SVType.Int) { // if argument is list of ... list of number, return that shape structure.push(length.value); obj = fetchAddr(obj.getIndice(0), heap); // simply fetch only first values while (obj?.type === SVType.Object) { length = fetchAddr(obj.getAttr('$length'), heap); if (length?.type === SVType.Int) { structure.push(length.value); obj = fetchAddr(obj.getIndice(0), heap); } else { shaped = false; break; } } // traversed list and ends with integer or float if (shaped && (obj?.type === SVType.Int || obj?.type === SVType.Float)) { const shape = ExpShape.fromConst(structure.length, structure, source); return SVSize.createSize(ctx, shape, source).toSet(); } } } // if varargs is list of integer, parseSize return ctx.parseSize(argsAddr, source).map((ctx) => { let shape: ExpShape; let newCtx: Context<any> = ctx; if (typeof ctx.retVal === 'string') { newCtx = ctx.warnWithMsg(ctx.retVal, source).genIntGte('tempRank', 0, source); shape = ExpShape.fromSymbol(newCtx.genSymShape('tempShape', newCtx.retVal, source)); } else { shape = ctx.retVal; } return SVSize.createSize(newCtx, shape, source); }); } // implementation slice of torch.Tensor.__getitem__ // axis range is already checked from tensor.__getitem__ // params: [inputShape, axis, index] export function tensorGetItem( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 3) { return ctx .warnWithMsg( `from 'LibCall.shape.tensorGetItem': got insufficient number of argument: ${params.length}`, source ) .toSet(); } const { env, heap } = ctx; const [sizeAddr, axisAddr, indexAddr] = params; const size = fetchAddr(sizeAddr, heap); const axis = fetchAddr(axisAddr, heap); const index = fetchAddr(indexAddr, heap); const mayTensorIndex = fetchSize(indexAddr, heap); if (!(size && size instanceof SVSize)) { return ctx.warnWithMsg(`from 'LibCall.shape.tensorGetItem': input is not a Size type`, source).toSet(); } if (!(axis && axis.type === SVType.Int && typeof axis.value === 'number')) { return ctx.warnWithMsg(`from 'LibCall.shape.tensorGetItem': axis is not a number`, source).toSet(); } if (!index) { return ctx.warnWithMsg(`from 'LibCall.shape.tensorGetItem': index is undefined`, source).toSet(); } const slice = sanitizeAddr(ctx.env.getId('slice'), heap); const shape = size.shape; const axisValue = axis.value; if (index.type === SVType.Int) { // index is contant int const indexNum = index.value; const indexDim = ExpNum.index(shape, axisValue, source); return ctx .require( [ ctx.genLte(ExpNum.bop(NumBopType.Sub, 0, indexDim, source), indexNum, source), ctx.genLte(indexNum, ExpNum.bop(NumBopType.Sub, indexDim, 1, source), source), ], `from 'LibCall.shape.tensorGetItem': index out of range`, source ) .flatMap((ctx) => { const left = ExpShape.slice(shape, undefined, axisValue, source); const right = ExpShape.slice( shape, ExpNum.bop(NumBopType.Add, axisValue, 1, source), undefined, source ); const result = simplifyShape(ctx.ctrSet, ExpShape.concat(left, right, source)); return genTorchSize(ctx, result, source); }); } else if (index.type === SVType.Object) { if (slice && isInstanceOf(index, slice, env, heap) === true) { const start = fetchAddr(index.getAttr('start'), heap); const end = fetchAddr(index.getAttr('stop'), heap); const step = fetchAddr(index.getAttr('step'), heap); const currDim = ExpNum.index(shape, axisValue, source); let hasError = false; let startN, endN, stepN: ExpNum | number | undefined; if (start?.type === SVType.Int) startN = start.value; else if (!(start?.type === SVType.None)) hasError = true; if (end?.type === SVType.Int) endN = end.value; else if (!(end?.type === SVType.None)) hasError = true; if (step?.type === SVType.Int) stepN = step.value; else if (!(step?.type === SVType.None)) hasError = true; if (hasError) { return ctx .warnWithMsg( `from 'LibCall.shape.tensorGetItem: slice value is not an integer or None.`, source ) .toSet(); } const ctrList: Constraint[] = []; if (startN !== undefined) { startN = absExpIndexByLen(startN, currDim, source, ctx.ctrSet); ctrList.push(ctx.genLte(0, startN, source)); } else { startN = 0; } if (endN !== undefined) { endN = absExpIndexByLen(endN, currDim, source, ctx.ctrSet); ctrList.push(ctx.genLte(0, endN, source)); } else { endN = currDim; } // return ceil((endN - startN) // stepN) let newDim = reluLen(startN, endN, source, ctx.ctrSet); if (stepN === undefined) stepN = 1; if (typeof stepN !== 'number' || stepN !== 1) { newDim = ExpNum.uop(NumUopType.Ceil, ExpNum.bop(NumBopType.TrueDiv, newDim, stepN, source), source); } const newShape = simplifyShape(ctx.ctrSet, ExpShape.setDim(shape, axisValue, newDim, source)); if (ctrList.length === 0) { return genTorchSize(ctx, newShape, source); } return ctx .require(ctrList, 'index out of range', source) .flatMap((ctx) => genTorchSize(ctx, newShape, source)); } else if (mayTensorIndex && mayTensorIndex instanceof SVSize) { // TOOD: distinguish dtype of tensor // TODO: Implement other advanced tensor indexing // https://numpy.org/doc/stable/reference/arrays.indexing.html // mask indexing const sizeNumel = ExpNum.numel(shape, source); const mask = mayTensorIndex; const maskCtx = ctx.genIntGte('maskIndex', 0, source); const maskNum = maskCtx.retVal; return maskCtx .require( [maskCtx.genLte(maskNum, sizeNumel, source), maskCtx.genEq(shape, mask.shape, source)], `from 'LibCall.tensor.getItem: Shape of mask must match.`, source ) .flatMap((ctx) => { return genTensor(ctx, ExpShape.fromConst(1, [maskNum], source), source); }); } } return ctx .warnWithMsg( `from 'LibCall.tensor.getItem: only indexing by integer, slice or bool tensor is supported currently.`, source ) .toSet(); } export function scalarTensor( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { return genTensor(ctx, ExpShape.fromConst(0, [], source), source); } export function identityShape( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 1) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.identityShape': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const inputAddr = params[0]; const inputSize = fetchSize(inputAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.identityShape': ${inputSize}`, source); } const inputShape = inputSize.shape; return genTensor(ctx, inputShape, source); } export function sameShape( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.sameShape': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [tensor1, tensor2] = params; const size1 = fetchSize(tensor1, heap); const size2 = fetchSize(tensor2, heap); if (typeof size1 === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.sameShape': ${size1}`, source); } if (typeof size2 === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.sameShape': ${size2}`, source); } return ctx .require( ctx.genEq(size1.shape, size2.shape, source), "from 'LibCall.torch.sameShape': not same shapes.", source ) .flatMap((ctx) => genTensor(ctx, size1.shape, source)); } // return broadcasted tensor export function broadcast( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.broadcast': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [leftAddr, rightAddr] = params; const leftSize = fetchSize(leftAddr, heap); const rightSize = fetchSize(rightAddr, heap); if (typeof leftSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.broadcast': ${leftSize}`, source); } else if (typeof rightSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.broadcast': ${rightSize}`, source); } const leftShape = leftSize.shape; const rightShape = rightSize.shape; return ctx.shBroadcast(leftShape, rightShape, source).flatMap((ctx) => genTensor(ctx, ctx.retVal, source)); } // implementation of torch.matmul export function matmul(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.matmul': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [leftAddr, rightAddr] = params; const leftSize = fetchSize(leftAddr, heap); const rightSize = fetchSize(rightAddr, heap); if (typeof leftSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.matmul': ${leftSize}`, source); } else if (typeof rightSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.matmul': ${rightSize}`, source); } const leftShape = leftSize.shape; const rightShape = rightSize.shape; const leftRank = leftSize.rank(); const rightRank = rightSize.rank(); return ctx .require( [ctx.genLte(1, leftRank, source), ctx.genLte(1, rightRank, source)], `from 'LibCall.torch.matmul': cannot do matmul with scalar tensor`, source ) .flatMap((ctx) => { const isLeftRankOne = ctx.genEq(1, leftRank, source); const [leftOnePath, leftTwoPath] = ctx.ifThenElse(isLeftRankOne, source); const leftPath = leftOnePath.flatMap((ctx) => { const isRightRankOne = ctx.genEq(1, rightRank, source); const [rightOnePath, rightTwoPath] = ctx.ifThenElse(isRightRankOne, source); const lr11 = rightOnePath .flatMap((ctx) => { const sameDim = ctx.genEq( ExpNum.index(leftShape, 0, source), ExpNum.index(rightShape, 0, source), source ); return ctx.require( [sameDim], `from 'LibCall.torch.matmul': dimension mismatch between rank-1 tensors`, source ); }) .flatMap((ctx) => genTensor(ctx, ExpShape.fromConst(0, [], source), source)); const rightAxis = ExpNum.bop(NumBopType.Sub, rightRank, 2, source); const lr12 = rightTwoPath .flatMap((ctx) => { const sameDim = ctx.genEq( ExpNum.index(leftShape, 0, source), ExpNum.index(rightShape, rightAxis, source), source ); return ctx.require( [sameDim], `from 'LibCall.torch.matmul: dimension mismatch between rank-1 @ rank-n`, source ); }) .flatMap((ctx) => ctx.shReduce(rightShape, rightAxis, source)) .flatMap((ctx) => genTensor(ctx, ctx.retVal, source)); return lr11.join(lr12); }); const rightPath = leftTwoPath.flatMap((ctx) => { const isRightRankOne = ctx.genEq(1, rightRank, source); const [rightOnePath, rightTwoPath] = ctx.ifThenElse(isRightRankOne, source); const leftAxis = ExpNum.bop(NumBopType.Sub, leftRank, 1, source); const lr21 = rightOnePath .flatMap((ctx) => { const sameDim = ctx.genEq( ExpNum.index(leftShape, leftAxis, source), ExpNum.index(rightShape, 0, source), source ); return ctx.require( [sameDim], `from 'LibCall.torch.matmul': dimension mismatch between rank-n @ rank-1`, source ); }) .flatMap((ctx) => ctx.shReduce(leftShape, leftAxis, source)) .flatMap((ctx) => genTensor(ctx, ctx.retVal, source)); const lr22 = rightTwoPath .flatMap((ctx) => ctx.shMatmul(leftShape, rightShape, source)) .flatMap((ctx) => genTensor(ctx, ctx.retVal, source)); return lr21.join(lr22); }); return leftPath.join(rightPath); }); } // implementation of torch.mm export function mm(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.mm': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [leftAddr, rightAddr] = params; const leftSize = fetchSize(leftAddr, heap); const rightSize = fetchSize(rightAddr, heap); if (typeof leftSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.mm': ${leftSize}`, source); } else if (typeof rightSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.mm': ${rightSize}`, source); } const leftShape = leftSize.shape; const rightShape = rightSize.shape; const leftRank = leftSize.rank(); const rightRank = rightSize.rank(); return ctx .require( [ctx.genEq(2, leftRank, source), ctx.genEq(2, rightRank, source)], `from 'LibCall.torch.mm': input must be 2-D tensors`, source ) .require( ctx.genEq(ExpNum.index(leftShape, 1, source), ExpNum.index(rightShape, 0, source), source), `from 'LibCall.torch.mm': dimension mismatch`, source ) .flatMap((ctx) => { const newShape = ExpShape.fromConst( 2, [ExpNum.index(leftShape, 0, source), ExpNum.index(rightShape, 1, source)], source ); return genTensor(ctx, newShape, source); }); } // implementation of torch.mm export function bmm(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.bmm': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [leftAddr, rightAddr] = params; const leftSize = fetchSize(leftAddr, heap); const rightSize = fetchSize(rightAddr, heap); if (typeof leftSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.bmm': ${leftSize}`, source); } else if (typeof rightSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.bmm': ${rightSize}`, source); } const leftShape = leftSize.shape; const rightShape = rightSize.shape; const leftRank = leftSize.rank(); const rightRank = rightSize.rank(); const leftBatch = ExpNum.index(leftShape, 0, source); const rightBatch = ExpNum.index(rightShape, 0, source); return ctx .require( [ctx.genEq(3, leftRank, source), ctx.genEq(3, rightRank, source)], `from 'LibCall.torch.bmm': input must be 3-D tensors`, source ) .require( [ctx.genEq(leftBatch, rightBatch, source)], `from 'LibCall.torch.bmm': batch size mismatch`, source ) .require( ctx.genEq(ExpNum.index(leftShape, 2, source), ExpNum.index(rightShape, 1, source), source), `from 'LibCall.torch.mm': dimension mismatch`, source ) .flatMap((ctx) => { const simplerBatch = leftShape.opType === ShapeOpType.Const ? leftBatch : rightBatch; const newShape = ExpShape.fromConst( 3, [simplerBatch, ExpNum.index(leftShape, 1, source), ExpNum.index(rightShape, 2, source)], source ); return genTensor(ctx, newShape, source); }); } export function item(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 1) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.item': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const selfAddr = params[0]; const self = fetchAddr(selfAddr, heap); const selfSize = fetchSize(selfAddr, heap); if (self?.type !== SVType.Object) { return ctx.failWithMsg(`from 'LibCall.torch.item': not a tensor object`, source).toSet(); } if (typeof selfSize === 'string') { return ctx .warnWithMsg(`from 'LibCall.torch.item': ${selfSize}; return symbolic value.`, source) .toSetWith(SVFloat.create(ExpNum.fromSymbol(ctx.genSymFloat('tensorItem', source)), source)); } const selfShape = selfSize.shape; const selfRank = selfSize.rank(); // Tensor.dtype is always given. force casting. const dtypeClass = fetchAddr(self.getAttr('dtype'), heap) as SVObject; const dtypeName = dtypeClass.getAttr('__name__') as SVString; const dtype = dtypeName.value as string; const isFloat = dtype === 'float16' || dtype === 'float32' || dtype === 'float64'; const isInt = dtype === 'int8' || dtype === 'int16' || dtype === 'int32' || dtype === 'int64' || dtype === 'uint8'; const isBool = dtype === 'bool'; const ctxSet = ctx.require( [ctx.genOr(ctx.genEq(0, selfRank, source), ctx.genEq(1, ExpNum.numel(selfShape, source), source), source)], `from 'LibCall.torch.item': tensor must have exacly one element`, source ); if (isFloat) { return ctxSet.return(SVFloat.create(ExpNum.fromSymbol(ctx.genSymFloat('tensorItem', source)), source)); } else if (isInt) { return ctxSet.return(SVInt.create(ExpNum.fromSymbol(ctx.genSymInt('tensorItem', source)), source)); } else if (isBool) { return ctxSet.return(SVBool.create(ExpBool.fromSymbol(ctx.genSymBool('tensorItem', source)), source)); } else { return ctx.failWithMsg(`from 'LibCall.torch.item': unknown dtype of tensor`, source).toSet(); } } // implementation of torch.Tensor.repeat export function repeat(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.repeat': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [selfAddr, sizes] = params; const selfSize = fetchSize(selfAddr, heap); const repeatSizes = fetchAddr(sizes, heap); if (typeof selfSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.repeat': ${selfSize}`, source); } else if (repeatSizes?.type !== SVType.Object) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.repeat': sizes is not iterable`, source); } const selfShape = selfSize.shape; const selfRank = selfSize.rank(); const tupleLenFetch = fetchAddr(repeatSizes.getAttr('$length'), heap); let sizeObj = fetchAddr(repeatSizes.getIndice(0), heap); // temporarily get first value if (!(sizeObj && tupleLenFetch && tupleLenFetch.type === SVType.Int)) { return ctx.failWithMsg(`from 'LibCall.torch.repeat': sizes is not iterable`, source).toSet(); } let tupleLenObj = tupleLenFetch.value; if (sizeObj.type === SVType.Object) { // first argument is object tupleLenObj = -1; } else if (typeof tupleLenObj === 'number' && tupleLenObj >= 2) { // size is given as vararg sizeObj = repeatSizes; } else if (sizeObj.type === SVType.Int) { // single dimension repeat const [size, sizeAddr, newHeap] = SVObject.create(heap, source); sizeObj = size.setIndice(0, sizeObj).setAttr('$length', SVInt.create(1, source)); ctx = ctx.setHeap(newHeap.setVal(sizeAddr, sizeObj)); } return ctx.parseSize(sizeObj, source).flatMap((ctx) => { const sizes = ctx.retVal; if (typeof sizes === 'string') { return ctx.warnTensorWithMsg(sizes, source); } const sizeRank = ExpShape.getRank(sizes); return ctx .require( ctx.genLte(selfRank, sizeRank, source), `from 'LibCall.torch.repeat': Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor`, source ) .flatMap((ctx) => { const selfRankRng = ctx.getCachedRange(selfRank); if (!selfRankRng) { return ctx.failWithMsg(`from 'LibCall.torch.repeat': invalid 'self' rank`, source).toSet(); } if (selfRankRng.isConst()) { const selfRank = selfRankRng.end; let shape = sizes; for (let i = 0; i < selfRank; i++) { const targetAxis = ExpNum.bop(NumBopType.Sub, sizeRank, i + 1, source); const newDim = ExpNum.bop( NumBopType.Mul, ExpNum.index(sizes, targetAxis, source), ExpNum.index(selfShape, selfRank - 1 - i, source), source ); shape = ExpShape.setDim(shape, targetAxis, newDim, source); } return genTensor(ctx, shape, source); } else { // if rank of self is not inferable, we have no choice but to make symbolic shape like broadcasting // that is right-aligned to self.shape and sizes, all the dimensions is gte than sizes return ctx.genRankedShape(sizeRank, source).flatMap((ctx) => { const symShape = ctx.retVal; const rankRng = ctx.getCachedRange(sizeRank); if (!rankRng) { return ctx .failWithMsg(`from 'LibCall.torch.repeat': invalid length of sizes`, source) .toSet(); } let newCtx: Context<any> = ctx; // set dimension lower bound for (let i = 0; i < rankRng.start; i++) { const dim = ExpNum.index(sizes, i, source); newCtx = newCtx.guarantee( newCtx.genLte(dim, ExpNum.index(symShape, i, source), source) ); } return genTensor(newCtx, symShape, source); }); } }); }); } // TODO: currently, assumed -1 is given only via constant rank tuple. export function expand(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.expand': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [selfAddr, sizeAddr] = params; const selfSize = fetchSize(selfAddr, heap); const expandSizes = fetchAddr(sizeAddr, heap); if (typeof selfSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.expand': ${selfSize}`, source); } else if (expandSizes?.type !== SVType.Object) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.expand': sizes is not iterable`, source); } const selfShape = selfSize.shape; const selfRank = selfSize.rank(); const sizeMap = expandSizes.extractIndexedNumber(ctx.heap); const sizeArr: ExpNum[] = []; for (let i = 0; i < sizeMap.count(); i++) { const dim = sizeMap.get(i); if (dim) sizeArr.push(dim); } const sizeRank = sizeArr.length; // TODO: check negativity of sizes return ctx .require( ctx.genEq(selfRank, sizeRank, source), `from 'LibCall.torch.expand': ranks must be matched each other`, source ) .flatMap((ctx) => { let modSize: ExpShape = ExpShape.fromConst(sizeRank, sizeArr, source); for (let i = 0; i < sizeRank; i++) { const ith = sizeArr[i]; if (ith.opType === NumOpType.Const && ith.value === -1) { modSize = simplifyShape( ctx.ctrSet, ExpShape.setDim(modSize, i, ExpNum.index(selfShape, i, source), source) ); } } let ctxSet = ctx.toSet(); for (let i = 0; i < sizeRank; i++) { ctxSet = ctxSet.require( ctx.genOr( ctx.genEq(ExpNum.index(selfShape, i, source), ExpNum.index(modSize, i, source), source), ctx.genEq(ExpNum.index(selfShape, i, source), 1, source), source ), `expanded size must match the existing size at non-singleton dimension ${i}`, source ); } return ctxSet.flatMap((ctx) => genTensor(ctx, modSize, source)); }); } export function expand_as( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.expand_as': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [selfAddr, sizeAddr] = params; const selfSize = fetchSize(selfAddr, heap); const expandSize = fetchSize(sizeAddr, heap); if (typeof selfSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.expand_as': ${selfSize}`, source); } else if (typeof expandSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.expand_as': ${expandSize}`, source); } const selfShape = selfSize.shape; const selfRank = selfSize.rank(); const expandShape = expandSize.shape; const expandRank = expandSize.rank(); // TODO: check negativity of sizes return ctx .require( ctx.genEq(selfRank, expandRank, source), `from 'LibCall.torch.expand_as': ranks must be matched each other`, source ) .flatMap((ctx) => { const rankRange = ctx.getCachedRange(expandRank); if (rankRange?.isConst()) { const rank = rankRange.start; let ctxSet = ctx.toSet(); for (let i = 0; i < rank; i++) { ctxSet = ctxSet.require( ctx.genOr( ctx.genEq( ExpNum.index(selfShape, i, source), ExpNum.index(expandShape, i, source), source ), ctx.genEq(ExpNum.index(selfShape, i, source), 1, source), source ), `from 'LibCall.torch.expand_as': expanded size must match the existing size at non-singleton dimension ${i}`, source ); } return ctxSet.flatMap((ctx) => genTensor(ctx, expandShape, source)); } else { const idx = ctx.genSymInt('expandIdx', source); const i = ExpNum.fromSymbol(idx); return ctx .require( ctx.genForall( idx, [0, ExpNum.bop(NumBopType.Sub, expandRank, 1, source)], ctx.genOr( ctx.genEq( ExpNum.index(selfShape, i, source), ExpNum.index(expandShape, i, source), source ), ctx.genEq(ExpNum.index(selfShape, i, source), 1, source), source ), source ), `from 'LibCall.torch.expand_as': expanded size must match the existing size at non-singleton dimension ${i.toString()}`, source ) .flatMap((ctx) => genTensor(ctx, expandShape, source)); } }); } export function copyOut(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx .warnWithMsg(`LibCall.torch.copyOut got insufficient number of argument: ${params.length}`, source) .toSet(); } const [tensorAddr, out] = params; if (out.type === SVType.None) { return ctx.toSetWith(out); } if (out.type !== SVType.Addr) { return ctx .warnWithMsg(`LibCall.torch.copyOut type error: out is not an address - got ${out.type}`, source) .toSet(); } const heap = ctx.heap; const tensor = fetchAddr(tensorAddr, heap); return (tensor ? ctx.setHeap(heap.setVal(out, tensor)) : ctx).setRetVal(out).toSet(); } export function callTensor( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { return TorchBackend.libClassInit(ctx, 'torch.Tensor', ctx.retVal.params, source); } export function transpose( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 3) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.transpose': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [selfAddr, dim0Addr, dim1Addr] = params; const selfSize = fetchSize(selfAddr, heap); if (typeof selfSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.transpose': ${selfSize}`, source); } const selfShape = selfSize.shape; const dim0 = fetchAddr(dim0Addr, heap); const dim1 = fetchAddr(dim1Addr, heap); if (dim0?.type !== SVType.Int) { return ctx.failWithMsg(`from 'LibCall.torch.transpose': cannot infer dim0 as integer`, source).toSet(); } if (dim1?.type !== SVType.Int) { return ctx.failWithMsg(`from 'LibCall.torch.transpose': cannot infer dim1 as integer`, source).toSet(); } const selfRank = ExpShape.getRank(selfShape); const negRank = ExpNum.bop(NumBopType.Sub, 0, selfRank, source); const [dim0Pos, dim0Neg] = ctx .require( [ ctx.genLte(negRank, dim0.value, source), ctx.genLt(dim0.value, selfRank, source), ctx.genLte(negRank, dim1.value, source), ctx.genLt(dim1.value, selfRank, source), ], `from 'LibCall.torch.transpose': dimension out of range`, source ) .ifThenElse(ctx.genLte(0, dim0.value, source), source); const [dimPP, dimPN] = dim0Pos.ifThenElse(ctx.genLte(0, dim1.value, source), source); const [dimNP, dimNN] = dim0Neg.ifThenElse(ctx.genLte(0, dim1.value, source), source); const dimPPNext = dimPP.flatMap((ctx) => genTensor( ctx, ExpShape.setDim( ExpShape.setDim(selfShape, dim0.value, ExpNum.index(selfShape, dim1.value, source), source), dim1.value, ExpNum.index(selfShape, dim0.value, source), source ), source ) ); const dimPNNext = dimPN.flatMap((ctx) => { const ndim1 = ExpNum.bop(NumBopType.Add, selfRank, dim1.value, source); return genTensor( ctx, ExpShape.setDim( ExpShape.setDim(selfShape, dim0.value, ExpNum.index(selfShape, ndim1, source), source), ndim1, ExpNum.index(selfShape, dim0.value, source), source ), source ); }); const dimNPNext = dimNP.flatMap((ctx) => { const ndim0 = ExpNum.bop(NumBopType.Add, selfRank, dim0.value, source); return genTensor( ctx, ExpShape.setDim( ExpShape.setDim(selfShape, ndim0, ExpNum.index(selfShape, dim1.value, source), source), dim1.value, ExpNum.index(selfShape, ndim0, source), source ), source ); }); const dimNNNext = dimNN.flatMap((ctx) => { const ndim0 = ExpNum.bop(NumBopType.Add, selfRank, dim0.value, source); const ndim1 = ExpNum.bop(NumBopType.Add, selfRank, dim1.value, source); return genTensor( ctx, ExpShape.setDim( ExpShape.setDim(selfShape, ndim0, ExpNum.index(selfShape, ndim1, source), source), ndim1, ExpNum.index(selfShape, ndim0, source), source ), source ); }); return dimPPNext.join(dimPNNext).join(dimNPNext).join(dimNNNext); } export function reduce(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 3) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.reduce': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [inputAddr, dimAddr, keepdimAddr] = params; const inputSize = fetchSize(inputAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.reduce': ${inputSize}`, source); } const dim = fetchAddr(dimAddr, heap); let keepdim = fetchAddr(keepdimAddr, heap); if (dim === undefined || (dim.type !== SVType.Int && dim.type !== SVType.None)) { return ctx.failWithMsg(`from 'LibCall.torch.reduce': cannot infer dim as integer`, source).toSet(); } if (keepdim === undefined || (keepdim.type !== SVType.Bool && keepdim.type !== SVType.None)) { return ctx.failWithMsg(`from 'LibCall.torch.reduce': cannot infer keepdim as boolean`, source).toSet(); } // if dim == None, return argmax of the flattend input.(scalar tensor) if (dim.type === SVType.None) { return ctx.genConstRankedShape(0, source).flatMap((ctx) => { const symShape = ctx.retVal; return genTensor(ctx, symShape, source); }); } // default value of keepdim is false. if (keepdim.type === SVType.None) { keepdim = SVBool.create(false, source); } const inputShape = inputSize.shape; const inputRank = inputSize.rank(); // check inputRank == 0 -> allows axis to [-1, 0] const rankRange = ctx.getCachedRange(inputRank); if (rankRange?.isConst() && rankRange.start === 0) { return ctx .require( [ctx.genLte(-1, dim.value, source), ctx.genLte(dim.value, 0, source)], `from 'LibCall.torch.reduce': dim must be within [0, 1] at scalar tensor `, source ) .flatMap((ctx) => { return genTensor(ctx, ExpShape.fromConst(0, [], source), source); }); } const axis = absExpIndexByLen(dim.value, inputRank, source, ctx.ctrSet); const shape1 = ExpShape.slice(inputShape, 0, axis, source); const shape2 = ExpShape.slice(inputShape, ExpNum.bop(NumBopType.Add, axis, 1, source), inputRank, source); return ctx .require( [ctx.genLte(0, axis, source), ctx.genLt(axis, inputRank, source)], `from 'LibCall.torch.reduce': dim must be within rank`, source ) .flatMap((ctx) => { const isKeepdimSet = ctx.genBool((keepdim as SVBool).value, source); const [keepdimPath, notKeepdimPath] = ctx.ifThenElse(isKeepdimSet, source); // keepdim=True : [..., d, ...] -> [..., 1, ...] const leftPath = keepdimPath.flatMap((ctx) => { const newDimShape = ExpShape.fromConst(1, [1], source); const newShape_ = ExpShape.concat(shape1, newDimShape, source); const newShape = ExpShape.concat(newShape_, shape2, source); return genTensor(ctx, newShape, source); }); // keepdim=False : [..., d, ...] -> [..., ...] const rightPath = notKeepdimPath.flatMap((ctx) => { const newShape = ExpShape.concat(shape1, shape2, source); return genTensor(ctx, newShape, source); }); return leftPath.join(rightPath); }); } export function topk(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 3) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.topk': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [inputAddr, kAddr, dimAddr] = params; const inputSize = fetchSize(inputAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.topk': ${inputSize}`, source); } const k = fetchAddr(kAddr, heap); const dim = fetchAddr(dimAddr, heap); if (k === undefined || k.type !== SVType.Int) { return ctx.failWithMsg(`from 'LibCall.torch.topk': cannot infer k as integer`, source).toSet(); } if (dim === undefined || dim.type !== SVType.Int) { return ctx.failWithMsg(`from 'LibCall.torch.topk': cannot infer dim as integer`, source).toSet(); } const inputShape = inputSize.shape; const inputRank = inputSize.rank(); const inputDim = ExpNum.index(inputShape, dim.value, source); return ctx .require( [ctx.genLte(0, dim.value, source), ctx.genLt(dim.value, inputRank, source)], `from 'LibCall.torch.topk': dim must be within rank`, source ) .require( [ctx.genLte(0, k.value, source), ctx.genLt(k.value, inputDim, source)], `from 'LibCall.torch.topk': k must be within 'dim'-th dimension of input`, source ) .flatMap((ctx) => genTensor(ctx, ExpShape.setDim(inputShape, dim.value, k.value, source), source)); } // TODO: currently, assumed -1 is given only via constant rank tuple. export function view(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.view': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [selfAddr, shapeAddr] = params; const selfSize = fetchSize(selfAddr, heap); if (typeof selfSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.view': ${selfSize}`, source); } const selfShape = selfSize.shape; const selfNumel = ExpNum.numel(selfShape, source); let shape: ExpShape = ExpShape.fromConst(0, [], source); const shapeObj = fetchAddr(shapeAddr, heap); if (shapeObj === undefined) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.view': ${shapeObj}`, source); } // if size is an integer. TODO: check integer input size go through this. else if (shapeObj.type === SVType.Int) { shape = ExpShape.fromConst(1, [shapeObj.value], source); } else if (shapeObj.type === SVType.Object) { // else if size is a tensor.size(). const firstArg = shapeObj.getIndice(0); const firstArgObj = fetchAddr(firstArg, heap); if (firstArgObj && firstArgObj.type === SVType.Object && firstArgObj?.shape !== undefined) { shape = firstArgObj.shape; } else if (firstArgObj && firstArgObj.type === SVType.Object) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.view': tensor size not found`, source); } // else size is an tuple of integers else { const shapeRank_ = fetchAddr(shapeObj.getAttr('$length'), heap); if (shapeRank_ === undefined) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.view': ${shapeRank_}`, source); } // tuple must have constant rank. if (shapeRank_.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.view': ${shapeRank_}`, source); } else { let shapeRank = -1; if (typeof shapeRank_.value === 'number') { shapeRank = shapeRank_.value; } else if (shapeRank_.value.opType === NumOpType.Const) { shapeRank = shapeRank_.value.value; } else { return ctx.warnTensorWithMsg(`from 'LibCall.torch.view': size must have constant rank`, source); } const dimsMap = shapeObj.extractIndexedNumber(heap); const dims: ExpNum[] = []; let wildCardIdx = -1; // index of -1 for (let i = 0; i < shapeRank; i++) { const dim = dimsMap.get(i); if (dim === undefined) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.view': input size must involve every dim ${shapeObj.toString()}`, source ); } dims.push(dim); if (dim.opType === NumOpType.Const && dim.value === -1) { wildCardIdx = i; } } // Special case: input size includes a -1. if (wildCardIdx !== -1) { const shapeL = ExpShape.fromConst(wildCardIdx, dims.slice(0, wildCardIdx), source); const shapeR = ExpShape.fromConst( shapeRank - wildCardIdx - 1, dims.slice(wildCardIdx + 1), source ); const numelL = ExpNum.numel(shapeL, source); const numelR = ExpNum.numel(shapeR, source); const isLeftRankZero = ctx.genEq(0, shapeL.rank, source); const isRightRankZero = ctx.genEq(0, shapeR.rank, source); const [leftZeroPath, leftNonzeroPath] = ctx.ifThenElse(isLeftRankZero, source); const pathL = leftZeroPath.flatMap((ctx) => { const [rightZeroPath, rightNonzeroPath] = ctx.ifThenElse(isRightRankZero, source); // path0: shape argument is [-1] const pathLL = rightZeroPath.flatMap((ctx) => { const newShape = ExpShape.fromConst(1, [selfNumel], source); return genTensor(ctx, newShape, source); }); // path1: shape argument is [-1, ...] const pathLR = rightNonzeroPath.flatMap((ctx) => { const wildCardDim = ExpNum.bop(NumBopType.FloorDiv, selfNumel, numelR, source); const wildCardDimShape = ExpShape.fromConst(1, [wildCardDim], source); const newShape = ExpShape.concat(wildCardDimShape, shapeR, source); const mod = ExpNum.bop(NumBopType.Mod, selfNumel, numelR, source); return ctx .require( [ctx.genEq(mod, 0, source)], `from 'LibCall.torch.view': numel mismatch. selfSize: ${selfNumel} must be dividable by ${numelR}`, source ) .flatMap((ctx) => genTensor(ctx, newShape, source)); }); return pathLL.join(pathLR); }); const pathR = leftNonzeroPath.flatMap((ctx) => { const [rightZeroPath, rightNonzeroPath] = ctx.ifThenElse(isRightRankZero, source); // path2: shape argument is [..., -1] const pathRL = rightZeroPath.flatMap((ctx) => { const wildCardDim = ExpNum.bop(NumBopType.FloorDiv, selfNumel, numelL, source); const wildCardDimShape = ExpShape.fromConst(1, [wildCardDim], source); const newShape = ExpShape.concat(shapeL, wildCardDimShape, source); const mod = ExpNum.bop(NumBopType.Mod, selfNumel, numelL, source); return ctx .require( [ctx.genEq(mod, 0, source)], `from 'LibCall.torch.view': numel mismatch. selfSize: ${selfNumel} must be dividable by ${numelL}`, source ) .flatMap((ctx) => genTensor(ctx, newShape, source)); }); // path3: shape argument is [..., -1, ...] const pathRR = rightNonzeroPath.flatMap((ctx) => { const numelLR = ExpNum.bop(NumBopType.Mul, numelL, numelR, source); const wildCardDim = ExpNum.bop(NumBopType.FloorDiv, selfNumel, numelLR, source); const wildCardDimShape = ExpShape.fromConst(1, [wildCardDim], source); const newShape_ = ExpShape.concat(shapeL, wildCardDimShape, source); const newShape = ExpShape.concat(newShape_, shapeR, source); const mod = ExpNum.bop(NumBopType.Mod, selfNumel, numelLR, source); return ctx .require( [ctx.genEq(mod, 0, source)], `from 'LibCall.torch.view': numel mismatch. selfSize: ${selfNumel} must be dividable by ${numelLR}`, source ) .flatMap((ctx) => genTensor(ctx, newShape, source)); }); return pathRL.join(pathRR); }); return pathL.join(pathR); } // input size doesn't include -1. else { shape = ExpShape.fromConst(shapeRank, dims, source); } } } } else { shape = ExpShape.fromConst(1, [100], source); } const shapeNumel = ExpNum.numel(shape, source); return ctx .require( [ // TODO: Commented out to avoid call stack excess // ctx.genForall(ctx.genSymInt('i', source), [0, shapeRank], ctx.genLt(0, i)), ctx.genEq(selfNumel, shapeNumel, source), ], `from 'LibCall.torch.view': numel mismatch`, source ) .flatMap((ctx) => genTensor(ctx, shape, source)); } export function conv2d(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 7) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.conv2d': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [inputAddr, weightAddr, biasAddr, strideAddr, paddingAddr, dilationAddr, groupsAddr] = params; const inputSize = fetchSize(inputAddr, heap); const weightSize = fetchSize(weightAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv2d: ${inputSize}`, source); } if (typeof weightSize === 'string') { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv2d: ${weightSize}`, source); } const inputShape = inputSize.shape; const inputRank = inputSize.rank(); const weightShape = weightSize.shape; const weightRank = weightSize.rank(); const out_channels = SVInt.create(ExpNum.index(weightShape, 0, source), source); const in_channels_div_g = ExpNum.index(weightShape, 1, source); const kernel_size_0 = SVInt.create(ExpNum.index(weightShape, 2, source), source); const kernel_size_1 = SVInt.create(ExpNum.index(weightShape, 3, source), source); // bias can be either None or (out_channels) shaped tensor let bias_channels: ExpNum | number; let biasRank: ExpNum | number; if (biasAddr.type === SVType.None) { bias_channels = -1; biasRank = 1; } else { const biasSize = fetchSize(biasAddr, heap); if (typeof biasSize === 'string') { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv2d: ${biasSize}`, source); } const biasShape = biasSize.shape; bias_channels = ExpNum.index(biasShape, 0, source); biasRank = biasSize.rank(); } const stride = fetchAddr(strideAddr, heap); let stride_0, stride_1: SVInt; if (stride === undefined) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv2d: stride is undefined`, source); } else if (stride.type !== SVType.Object && stride.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv2d: stride is not an int nor int pair`, source); } else if (stride.type === SVType.Object) { stride_0 = stride.getIndice(0) as SVInt; stride_1 = stride.getIndice(1) as SVInt; } else { stride_0 = stride; stride_1 = stride; } const padding = fetchAddr(paddingAddr, heap); let padding_0, padding_1: SVInt; if (padding === undefined) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv2d: padding is undefined`, source); } else if (padding.type !== SVType.Object && padding.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv2d: padding is not an int nor int pair`, source); } else if (padding.type === SVType.Object) { padding_0 = padding.getIndice(0) as SVInt; padding_1 = padding.getIndice(1) as SVInt; } else { padding_0 = padding; padding_1 = padding; } const dilation = fetchAddr(dilationAddr, heap); let dilation_0, dilation_1: SVInt; if (dilation === undefined) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv2d: dilation is undefined`, source); } else if (dilation.type !== SVType.Object && dilation.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv2d: dilation is not an int nor int pair`, source); } else if (dilation.type === SVType.Object) { dilation_0 = dilation.getIndice(0) as SVInt; dilation_1 = dilation.getIndice(1) as SVInt; } else { dilation_0 = dilation; dilation_1 = dilation; } const groups = fetchAddr(groupsAddr, heap); if (groups?.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv2d: groups is not an int nor int pair`, source); } const in_channels = SVInt.create(ExpNum.bop(NumBopType.Mul, in_channels_div_g, groups.value, source), source); // size1 = input[2] + 2 * padding - dilation * (kernel_size - 1) - 1 const exp1 = ExpNum.bop(NumBopType.Mul, 2, padding_0.value, source); const exp2 = ExpNum.bop(NumBopType.Sub, kernel_size_0.value, 1, source); const exp3 = ExpNum.bop(NumBopType.Mul, dilation_0.value, exp2, source); const exp4 = ExpNum.bop(NumBopType.Add, ExpNum.index(inputShape, 2, source), exp1, source); const exp5 = ExpNum.bop(NumBopType.Sub, exp4, exp3, source); const size1 = ExpNum.bop(NumBopType.Sub, exp5, 1, source); // size2 = input[3] + 2 * padding - dilation * (kernel_size - 1) - 1 const exp6 = ExpNum.bop(NumBopType.Mul, 2, padding_1.value, source); const exp7 = ExpNum.bop(NumBopType.Sub, kernel_size_1.value, 1, source); const exp8 = ExpNum.bop(NumBopType.Mul, dilation_1.value, exp7, source); const exp9 = ExpNum.bop(NumBopType.Add, ExpNum.index(inputShape, 3, source), exp6, source); const exp10 = ExpNum.bop(NumBopType.Sub, exp9, exp8, source); const size2 = ExpNum.bop(NumBopType.Sub, exp10, 1, source); // dims of return shape const dim0 = ExpNum.index(inputShape, 0, source); const dim1 = out_channels.value; const dim2 = ExpNum.bop( NumBopType.Add, ExpNum.bop(NumBopType.FloorDiv, size1, stride_0.value, source), 1, source ); const dim3 = ExpNum.bop( NumBopType.Add, ExpNum.bop(NumBopType.FloorDiv, size2, stride_1.value, source), 1, source ); return ctx .require( [ctx.genEq(4, inputRank, source), ctx.genEq(4, weightRank, source), ctx.genEq(1, biasRank, source)], `from 'LibCall.torch.conv2d': ranks of (input, weight, bias) are not (4, 4, 1)`, source ) .require( [ ctx.genOr( ctx.genEq(-1, bias_channels, source), ctx.genEq(out_channels.value, bias_channels, source), source ), ], `from 'LibCall.torch.conv2d': bias channel mismatch`, source ) .require( [ctx.genEq(ExpNum.index(inputShape, 1, source), in_channels.value, source)], `from 'LibCall.torch.conv2d': in-channel mismatch`, source ) .require( [ctx.genLte(0, size1, source), ctx.genLte(0, size2, source)], `from 'LibCall.torch.conv2d': output size should be non-negative`, source ) .require( ctx.genEq(0, ExpNum.bop(NumBopType.Mod, out_channels.value, groups.value, source), source), `from 'LibCall.torch.conv2d': out_channel size must be divisible by 'groups'`, source ) .flatMap((ctx) => genTensor(ctx, ExpShape.fromConst(4, [dim0, dim1, dim2, dim3], source), source)); } export function conv_transpose2d( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 8) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.conv_transpose2d': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [ inputAddr, weightAddr, biasAddr, strideAddr, paddingAddr, outputPaddingAddr, groupsAddr, dilationAddr, ] = params; const inputSize = fetchSize(inputAddr, heap); const weightSize = fetchSize(weightAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv_transpose2d: ${inputSize}`, source); } if (typeof weightSize === 'string') { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv_transpose2d: ${weightSize}`, source); } const inputShape = inputSize.shape; const inputRank = inputSize.rank(); const weightShape = weightSize.shape; const weightRank = weightSize.rank(); const in_channels = SVInt.create(ExpNum.index(weightShape, 0, source), source); const out_channels_div_g = ExpNum.index(weightShape, 1, source); const kernel_size_0 = SVInt.create(ExpNum.index(weightShape, 2, source), source); const kernel_size_1 = SVInt.create(ExpNum.index(weightShape, 3, source), source); // bias can be either None or (out_channels) shaped tensor let bias_channels: ExpNum | number; let biasRank: ExpNum | number; if (biasAddr.type === SVType.None) { bias_channels = -1; biasRank = 1; } else { const biasSize = fetchSize(biasAddr, heap); if (typeof biasSize === 'string') { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv_transpose2d: ${biasSize}`, source); } const biasShape = biasSize.shape; bias_channels = ExpNum.index(biasShape, 0, source); biasRank = biasSize.rank(); } const stride = fetchAddr(strideAddr, heap); let stride_0, stride_1: SVInt; if (stride === undefined) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv_transpose2d: stride is undefined`, source); } else if (stride.type !== SVType.Object && stride.type !== SVType.Int) { return ctx.warnTensorWithMsg( `from 'Libcall.torch.conv_transpose2d: stride is not an int nor int pair`, source ); } else if (stride.type === SVType.Object) { stride_0 = stride.getIndice(0) as SVInt; stride_1 = stride.getIndice(1) as SVInt; } else { stride_0 = stride; stride_1 = stride; } const padding = fetchAddr(paddingAddr, heap); let padding_0, padding_1: SVInt; if (padding === undefined) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv_transpose2d: padding is undefined`, source); } else if (padding.type !== SVType.Object && padding.type !== SVType.Int) { return ctx.warnTensorWithMsg( `from 'Libcall.torch.conv_transpose2d: padding is not an int nor int pair`, source ); } else if (padding.type === SVType.Object) { padding_0 = padding.getIndice(0) as SVInt; padding_1 = padding.getIndice(1) as SVInt; } else { padding_0 = padding; padding_1 = padding; } const outPadding = fetchAddr(outputPaddingAddr, heap); let outPadding_0, outPadding_1: SVInt; if (outPadding === undefined) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv_transpose2d: output_padding is undefined`, source); } else if (outPadding.type !== SVType.Object && outPadding.type !== SVType.Int) { return ctx.warnTensorWithMsg( `from 'Libcall.torch.conv_transpose2d: output_padding is not an int nor int pair`, source ); } else if (outPadding.type === SVType.Object) { outPadding_0 = outPadding.getIndice(0) as SVInt; outPadding_1 = outPadding.getIndice(1) as SVInt; } else { outPadding_0 = outPadding; outPadding_1 = outPadding; } const dilation = fetchAddr(dilationAddr, heap); let dilation_0, dilation_1: SVInt; if (dilation === undefined) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.conv_transpose2d: dilation is undefined`, source); } else if (dilation.type !== SVType.Object && dilation.type !== SVType.Int) { return ctx.warnTensorWithMsg( `from 'Libcall.torch.conv_transpose2d: dilation is not an int nor int pair`, source ); } else if (dilation.type === SVType.Object) { dilation_0 = dilation.getIndice(0) as SVInt; dilation_1 = dilation.getIndice(1) as SVInt; } else { dilation_0 = dilation; dilation_1 = dilation; } const groups = fetchAddr(groupsAddr, heap); if (groups?.type !== SVType.Int) { return ctx.warnTensorWithMsg( `from 'Libcall.torch.conv_transpose2d: groups is not an int nor int pair`, source ); } const out_channels = SVInt.create(ExpNum.bop(NumBopType.Mul, out_channels_div_g, groups.value, source), source); // size1 = (input[2] - 1) * stride[0] - 2 * padding[0] + dilation[0] * (kernel_size[0] - 1) + output_padding[0] + 1 const exp1 = ExpNum.bop(NumBopType.Sub, ExpNum.index(inputShape, 2, source), 1, source); const exp2 = ExpNum.bop(NumBopType.Mul, exp1, stride_0.value, source); const exp3 = ExpNum.bop(NumBopType.Mul, 2, padding_0.value, source); const exp4 = ExpNum.bop(NumBopType.Sub, exp2, exp3, source); const exp5 = ExpNum.bop( NumBopType.Mul, dilation_0.value, ExpNum.bop(NumBopType.Sub, kernel_size_0.value, 1, source), source ); const exp6 = ExpNum.bop(NumBopType.Add, exp4, exp5, source); const size1 = ExpNum.bop( NumBopType.Add, exp6, ExpNum.bop(NumBopType.Add, outPadding_0.value, 1, source), source ); // size2 = (input[3] - 1) * stride[1] - 2 * padding[1] + dilation[1] * (kernel_size[1] - 1) + output_padding[1] + 1 const exp12 = ExpNum.bop(NumBopType.Sub, ExpNum.index(inputShape, 3, source), 1, source); const exp22 = ExpNum.bop(NumBopType.Mul, exp12, stride_1.value, source); const exp32 = ExpNum.bop(NumBopType.Mul, 2, padding_1.value, source); const exp42 = ExpNum.bop(NumBopType.Sub, exp22, exp32, source); const exp52 = ExpNum.bop( NumBopType.Mul, dilation_1.value, ExpNum.bop(NumBopType.Sub, kernel_size_1.value, 1, source), source ); const exp62 = ExpNum.bop(NumBopType.Add, exp42, exp52, source); const size2 = ExpNum.bop( NumBopType.Add, exp62, ExpNum.bop(NumBopType.Add, outPadding_1.value, 1, source), source ); // dims of return shape const dim0 = ExpNum.index(inputShape, 0, source); const dim1 = out_channels.value; const dim2 = size1; const dim3 = size2; return ctx .require( [ctx.genEq(4, inputRank, source), ctx.genEq(4, weightRank, source), ctx.genEq(1, biasRank, source)], `from 'LibCall.torch.conv_transpose2d': ranks of (input, weight, bias) are not (4, 4, 1)`, source ) .require( [ ctx.genOr( ctx.genEq(-1, bias_channels, source), ctx.genEq(out_channels.value, bias_channels, source), source ), ], `from 'LibCall.torch.conv_transpose2d': bias channel mismatch`, source ) .require( [ctx.genEq(ExpNum.index(inputShape, 1, source), in_channels.value, source)], `from 'LibCall.torch.conv_transpose2d': in-channel mismatch`, source ) .require( [ctx.genLte(0, size1, source), ctx.genLte(0, size2, source)], `from 'LibCall.torch.conv_transpose2d': output size should be non-negative`, source ) .require( ctx.genEq(0, ExpNum.bop(NumBopType.Mod, in_channels.value, groups.value, source), source), `from 'LibCall.torch.conv_transpose2d': channel size must be divisible by groups`, source ) .flatMap((ctx) => genTensor(ctx, ExpShape.fromConst(4, [dim0, dim1, dim2, dim3], source), source)); } export function pool2d(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 6) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.pool2d': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [inputAddr, kernel_sizeAddr, strideAddr, paddingAddr, dilationAddr, ceil_modeAddr] = params; const inputSize = fetchSize(inputAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.pool2d': ${inputSize}`, source); } const kernel_size = fetchAddr(kernel_sizeAddr, heap); let kernel_size_0: SVInt; let kernel_size_1: SVInt; if (kernel_size === undefined) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.pool2d: kernel_size is undefined`, source); } else if (kernel_size.type !== SVType.Object && kernel_size.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.pool2d: kernel_size is not an int nor int pair`, source); } else if (kernel_size.type === SVType.Object) { kernel_size_0 = kernel_size.getIndice(0) as SVInt; kernel_size_1 = kernel_size.getIndice(1) as SVInt; } else { kernel_size_0 = kernel_size; kernel_size_1 = kernel_size; } const stride = fetchAddr(strideAddr, heap); let stride_0: SVInt; let stride_1: SVInt; if (stride === undefined) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.pool2d: stride is undefined`, source); } else if (stride.type !== SVType.Object && stride.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.pool2d: stride is not an int nor int pair`, source); } else if (stride.type === SVType.Object) { stride_0 = stride.getIndice(0) as SVInt; stride_1 = stride.getIndice(1) as SVInt; } else { stride_0 = stride; stride_1 = stride; } const padding = fetchAddr(paddingAddr, heap); let padding_0: SVInt; let padding_1: SVInt; if (padding === undefined) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.pool2d: padding is undefined`, source); } else if (padding.type !== SVType.Object && padding.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.pool2d: padding is not an int nor int pair`, source); } else if (padding.type === SVType.Object) { padding_0 = padding.getIndice(0) as SVInt; padding_1 = padding.getIndice(1) as SVInt; } else { padding_0 = padding; padding_1 = padding; } const dilation = fetchAddr(dilationAddr, heap); let dilation_0: SVInt; let dilation_1: SVInt; if (dilation === undefined) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.pool2d: dilation is undefined`, source); } else if (dilation.type !== SVType.Object && dilation.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'Libcall.torch.pool2d: dilation is not an int nor int pair`, source); } else if (dilation.type === SVType.Object) { dilation_0 = dilation.getIndice(0) as SVInt; dilation_1 = dilation.getIndice(1) as SVInt; } else { dilation_0 = dilation; dilation_1 = dilation; } const ceil_mode = fetchAddr(ceil_modeAddr, heap) as SVBool; const inputShape = inputSize.shape; const inputRank = inputSize.rank(); const height = ExpNum.index(inputShape, ExpNum.bop(NumBopType.Sub, inputRank, 2, source), source); const width = ExpNum.index(inputShape, ExpNum.bop(NumBopType.Sub, inputRank, 1, source), source); // size1 = height + 2 * padding - dilation * (kernel_size - 1) - 1 const exp1 = ExpNum.bop(NumBopType.Mul, 2, padding_0.value, source); const exp2 = ExpNum.bop(NumBopType.Sub, kernel_size_0.value, 1, source); const exp3 = ExpNum.bop(NumBopType.Mul, dilation_0.value, exp2, source); const exp4 = ExpNum.bop(NumBopType.Add, height, exp1, source); const exp5 = ExpNum.bop(NumBopType.Sub, exp4, exp3, source); const size1 = ExpNum.bop(NumBopType.Sub, exp5, 1, source); // size2 = width + 2 * padding - dilation * (kernel_size - 1) - 1 const exp6 = ExpNum.bop(NumBopType.Mul, 2, padding_1.value, source); const exp7 = ExpNum.bop(NumBopType.Sub, kernel_size_1.value, 1, source); const exp8 = ExpNum.bop(NumBopType.Mul, dilation_1.value, exp7, source); const exp9 = ExpNum.bop(NumBopType.Add, width, exp6, source); const exp10 = ExpNum.bop(NumBopType.Sub, exp9, exp8, source); const size2 = ExpNum.bop(NumBopType.Sub, exp10, 1, source); // return shape const frontShape = ExpShape.slice(inputShape, 0, ExpNum.bop(NumBopType.Sub, inputRank, 2, source), source); // ceil_mode option; common constraint const commonBranch = ctx.require( [ ctx.genOr(ctx.genEq(3, inputRank, source), ctx.genEq(4, inputRank, source), source), ctx.genLte(ExpNum.bop(NumBopType.Mul, 2, padding_0.value, source), kernel_size_0.value, source), ctx.genLte(ExpNum.bop(NumBopType.Mul, 2, padding_1.value, source), kernel_size_1.value, source), ctx.genLte(0, size1, source), ctx.genLte(0, size2, source), ], `from 'Libcall.torch.pool2d: common constraint error`, source ); const [ceilPath, floorPath] = commonBranch.ifThenElse(ctx.genBool(ceil_mode.value, source), source); // when ceil_mode=true const ceilOnePath = ceilPath.flatMap((ctx) => { const h_out = ExpNum.bop(NumBopType.Add, ceilDiv(size1, stride_0.value, source), 1, source); const w_out = ExpNum.bop(NumBopType.Add, ceilDiv(size2, stride_1.value, source), 1, source); const backShape = ExpShape.fromConst(2, [h_out, w_out], source); const returnShape = ExpShape.concat(frontShape, backShape, source); return genTensor(ctx, returnShape, source); }); // when ceil_mode=false const floorOnePath = floorPath.flatMap((ctx) => { const h_out = ExpNum.bop( NumBopType.Add, ExpNum.bop(NumBopType.FloorDiv, size1, stride_0.value, source), 1, source ); const w_out = ExpNum.bop( NumBopType.Add, ExpNum.bop(NumBopType.FloorDiv, size2, stride_1.value, source), 1, source ); const backShape = ExpShape.fromConst(2, [h_out, w_out], source); const returnShape = ExpShape.concat(frontShape, backShape, source); return genTensor(ctx, returnShape, source); }); return ceilOnePath.join(floorOnePath); } // TODO: Implement batch_norm and let BatchNormNd call it. export function batchnorm2d( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length < 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.batchnorm2d': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [inputAddr, num_featuresAddr] = params; const inputSize = fetchSize(inputAddr, heap); const num_features = fetchAddr(num_featuresAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.batchnorm2d': ${inputSize}`, source); } if (num_features?.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.batchnorm2d': num_features is not an integer`, source); } const inputShape = inputSize.shape; const inputRank = inputSize.rank(); return ctx .require( [ ctx.genEq(4, inputRank, source), ctx.genEq(num_features.value, ExpNum.index(inputShape, 1, source), source), ], `from 'LibCall.torch.batchnorm2d': rank must be 4 && num_features must match`, source ) .flatMap((ctx) => genTensor(ctx, inputShape, source)); } // conditions of elements in "target" is not considered. export function cross_entropy( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 3) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.cross_entropy': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [inputAddr, targetAddr, reductionAddr] = params; const inputSize = fetchSize(inputAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.cross_entropy': ${inputSize}`, source); } const inputShape = inputSize.shape; const inputRank = inputSize.rank(); const targetSize = fetchSize(targetAddr, heap); if (typeof targetSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.cross_entropy': ${targetSize}`, source); } const targetShape = targetSize.shape; const targetRank = ExpShape.getRank(targetShape); const reduction = fetchAddr(reductionAddr, heap); if (reduction === undefined || reduction.type !== SVType.Bool) { return ctx .failWithMsg(`from 'LibCall.torch.cross_entropy': cannot infer reduction as boolean`, source) .toSet(); } return ctx .require( [ ctx.genLte(2, inputRank, source), ctx.genEq(ExpNum.bop(NumBopType.Sub, inputRank, 1, source), targetRank, source), ctx.genEq(ExpNum.index(inputShape, 0, source), ExpNum.index(targetShape, 0, source), source), ctx.genEq( ExpShape.slice(inputShape, 2, inputRank, source), ExpShape.slice(targetShape, 1, targetRank, source), source ), ], `from 'LibCall.torch.cross_entropy': input target shapes mismatch`, source ) .flatMap((ctx) => { const isReductionSet = ctx.genBool((reduction as SVBool).value, source); const [reductionPath, noReductionPath] = ctx.ifThenElse(isReductionSet, source); // not(reduction='none') : output is a scalar tensor. const leftPath = reductionPath.flatMap((ctx) => { const newShape = ExpShape.fromConst(0, [], source); return genTensor(ctx, newShape, source); }); // reduction='none' : output shape is equal to target shape. const rightpath = noReductionPath.flatMap((ctx) => { return genTensor(ctx, targetShape, source); }); return leftPath.join(rightpath); }); } // Assumption: "tensors" is a constantRanked sequence, and each element is available. // TODO: handle empty tensor. export function cat(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.cat': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [tensorsAddr, dimAddr] = params; const tensors = fetchAddr(tensorsAddr, heap); const dim = fetchAddr(dimAddr, heap); if (tensors?.type !== SVType.Object) { if (tensors?.type === SVType.Error) { // propagate error return ctx.warnTensorWithMsg(`from 'LibCall.torch.cat': 'tensors' is not iterable`, source); } return ctx.failWithMsg(`from 'LibCall.torch.cat': 'tensors' is not iterable`, source).toSet(); } else if (dim?.type !== SVType.Int) { if (dim?.type === SVType.Error) { // propagate error return ctx.warnTensorWithMsg(`from 'LibCall.torch.cat': 'dim' is not an integer`, source); } return ctx.failWithMsg(`from 'LibCall.torch.cat': 'dim' is not an integer`, source).toSet(); } // Assumption: length of "tensors" is constant. const tensorsLen_ = fetchAddr(tensors.getAttr('$length'), heap); if (!(tensorsLen_?.type === SVType.Int && typeof tensorsLen_.value === 'number')) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.cat': length of tensors is unknown, cannot iterate.`, source ); } const tensorsLen = tensorsLen_.value; const tensor0 = fetchAddr(tensors.getIndice(0), heap); const size0 = fetchSize(tensor0, heap); if (typeof size0 === 'string') { if (tensor0?.type === SVType.Error) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.cat': ${size0}`, source); } return ctx.failWithMsg(`from 'LibCall.torch.cat': ${size0}`, source).toSet(); } const size0shape = size0.shape; const size0rank = size0.rank(); const shape0Front = ExpShape.slice(size0shape, 0, dim.value, source); const shape0Back = ExpShape.slice( size0shape, ExpNum.bop(NumBopType.Add, dim.value, 1, source), size0rank, source ); // TODO: handle negative index. const ctrs: Constraint[] = [ctx.genLte(0, dim.value, source), ctx.genLt(dim.value, size0rank, source)]; let thickness: ExpNum = ExpNum.index(size0shape, dim.value, source); for (let i = 1; i < tensorsLen; i++) { const tensorI = fetchAddr(tensors.getIndice(i), heap); const sizeI = fetchSize(tensorI, heap); if (typeof sizeI === 'string') { if (tensorI?.type === SVType.Error) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.cat': ${sizeI}`, source); } return ctx.failWithMsg(`from 'LibCall.torch.cat': ${sizeI}`, source).toSet(); } const sizeIshape = sizeI.shape; const shapeIFront = ExpShape.slice(sizeIshape, 0, dim.value, source); const shapeIBack = ExpShape.slice( sizeIshape, ExpNum.bop(NumBopType.Add, dim.value, 1, source), size0rank, source ); ctrs.push(ctx.genEq(shape0Front, shapeIFront, source)); ctrs.push(ctx.genEq(shape0Back, shapeIBack, source)); thickness = ExpNum.bop(NumBopType.Add, thickness, ExpNum.index(sizeIshape, dim.value, source), source); } const shapeThick = ExpShape.fromConst(1, [thickness], source); const returnShape_ = ExpShape.concat(shape0Front, shapeThick, source); const returnShape = ExpShape.concat(returnShape_, shape0Back, source); return ctx .require(ctrs, `from 'LibCall.torch.cat': tensor shapes must match, dim must be within rank`, source) .flatMap((ctx) => { return genTensor(ctx, returnShape, source); }); } // Assumption: "tensors" is a constantRanked sequence, and each element is available. // TODO: handle empty tensor. export function stack(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.stack': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [tensorsAddr, dimAddr] = params; const tensors = fetchAddr(tensorsAddr, heap); const dim_ = fetchAddr(dimAddr, heap); if (tensors?.type !== SVType.Object) { if (tensors?.type === SVType.Error) { // propagate error return ctx.warnTensorWithMsg(`from 'LibCall.torch.stack': 'tensors' is not iterable`, source); } return ctx.failWithMsg(`from 'LibCall.torch.stack': 'tensors' is not iterable`, source).toSet(); } else if (dim_?.type !== SVType.Int) { if (dim_?.type === SVType.Error) { // propagate error return ctx.warnTensorWithMsg(`from 'LibCall.torch.stack': 'dim' is not an integer`, source); } return ctx.failWithMsg(`from 'LibCall.torch.stack': 'dim' is not an integer`, source).toSet(); } if (typeof dim_.value !== 'number') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.stack': dim is unknown`, source); } // negative index handling // Assumption: length of "tensors" is constant. const tensorsLen_ = fetchAddr(tensors.getAttr('$length'), heap); if (!(tensorsLen_?.type === SVType.Int && typeof tensorsLen_.value === 'number')) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.stack': length of tensors is unknown, cannot iterate.`, source ); } const tensorsLen = tensorsLen_.value; const tensor0 = fetchAddr(tensors.getIndice(0), heap); const size0 = fetchSize(tensor0, heap); if (typeof size0 === 'string') { if (tensor0?.type === SVType.Error) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.stack': ${size0}`, source); } return ctx.failWithMsg(`from 'LibCall.torch.stack': ${size0}`, source).toSet(); } const size0shape = size0.shape; const size0rank = size0.rank(); let dim: ExpNum; if (dim_.value < 0) { dim = ExpNum.bop(NumBopType.Add, ExpNum.bop(NumBopType.Add, size0rank, 1, source), dim_.value, source); } else { dim = ExpNum.fromConst(dim_.value, source); } const shape0Front = ExpShape.slice(size0shape, 0, dim, source); const shape0Back = ExpShape.slice(size0shape, dim, size0rank, source); const ctrs: Constraint[] = [ctx.genLte(0, dim, source), ctx.genLte(dim, size0rank, source)]; for (let i = 1; i < tensorsLen; i++) { const tensorI = fetchAddr(tensors.getIndice(i), heap); const sizeI = fetchSize(tensorI, heap); if (typeof sizeI === 'string') { if (tensorI?.type === SVType.Error) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.stack': ${sizeI}`, source); } return ctx.failWithMsg(`from 'LibCall.torch.stack': ${sizeI}`, source).toSet(); } const sizeIshape = sizeI.shape; ctrs.push(ctx.genEq(size0shape, sizeIshape, source)); } const shapeThick = ExpShape.fromConst(1, [tensorsLen], source); const returnShape_ = ExpShape.concat(shape0Front, shapeThick, source); const returnShape = ExpShape.concat(returnShape_, shape0Back, source); return ctx .require( ctrs, `from 'LibCall.torch.stack': tensor shapes must all be the same, dim must be within rank`, source ) .flatMap((ctx) => { return genTensor(ctx, returnShape, source); }); } export function unsqueeze( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length < 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.unsqueeze': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [inputAddr, dimAddr] = params; const inputSize = fetchSize(inputAddr, heap); const dim = fetchAddr(dimAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.unsqueeze': ${inputSize}`, source); } if (dim?.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.unsqueeze': dimension is not an integer`, source); } const inputShape = inputSize.shape; const inputRank = inputSize.rank(); const shapeFront = ExpShape.slice(inputShape, 0, dim.value, source); const shapeBack = ExpShape.slice(inputShape, dim.value, inputRank, source); const shapeMid = ExpShape.fromConst(1, [1], source); const returnShape_ = ExpShape.concat(shapeFront, shapeMid, source); const returnShape = ExpShape.concat(returnShape_, shapeBack, source); return ctx .require( // TODO: handle negative index [ctx.genLte(0, dim.value, source), ctx.genLte(dim.value, inputRank, source)], `from 'LibCall.torch.unsqueeze': dim must be within rank`, source ) .flatMap((ctx) => genTensor(ctx, returnShape, source)); } export function squeeze(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.squeeze': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [inputAddr, dimAddr] = params; const inputSize = fetchSize(inputAddr, heap); const dim = fetchAddr(dimAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.squeeze': ${inputSize}`, source); } if (!(dim?.type === SVType.Int || dim?.type === SVType.None)) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.squeeze': dimension is not an int or none`, source); } const inputShape = inputSize.shape; let inputRank = inputSize.rank(); if (dim.type === SVType.None) { if (typeof inputRank !== 'number') { inputRank = simplifyNum(ctx.ctrSet, inputRank); const rankRange = ctx.ctrSet.getCachedRange(inputRank); if (!rankRange?.isConst()) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.squeeze: cannot squeeze non-constant ranked tensor. return random tensor.`, source ); } inputRank = rankRange.start; } const outShapes: (number | ExpNum)[] = []; const ctrs: Constraint[] = []; for (let i = 0; i < inputRank; i++) { const dim = simplifyNum(ctx.ctrSet, ExpNum.index(inputShape, i, source)); const dimRng = ctx.ctrSet.getCachedRange(dim); if (!(dimRng?.isConst() && dimRng.start === 1)) { outShapes.push(dim); ctrs.push(ctx.genLt(1, dim, source)); } } return ctx .require( ctrs, `from 'LibCall.torch.squeeze': non-constant dimension can be 1. This behavior is permitted but can lead to unexpected errors.`, source ) .flatMap((ctx) => { return genTensor(ctx, ExpShape.fromConst(outShapes.length, outShapes, source), source); }); } else { const index = simplifyNum(ctx.ctrSet, ExpNum.index(inputShape, dim.value, source)); const dimRng = ctx.ctrSet.getCachedRange(index); if (dimRng?.isConst() && dimRng.start === 1) { const left = ExpShape.slice(inputShape, undefined, dim.value, source); const right = ExpShape.slice( inputShape, ExpNum.bop(NumBopType.Add, dim.value, 1, source), undefined, source ); const newShape = simplifyShape(ctx.ctrSet, ExpShape.concat(left, right, source)); return genTensor(ctx, newShape, source); } else if (dimRng?.gt(1)) { return genTensor(ctx, inputShape, source); } return ctx .require( ctx.genLt(1, index, source), `from 'LibCall.torch.squeeze': non-constant dimension can be 1. This behavior is permitted but can lead to unexpected errors.`, source ) .flatMap((ctx) => { return genTensor(ctx, inputShape, source); }); } } export function diag(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length < 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.diag': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [inputAddr, diagonalAddr] = params; const inputSize = fetchSize(inputAddr, heap); const diagonal = fetchAddr(diagonalAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.diag': ${inputSize}`, source); } if (diagonal?.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.diag': ${diagonal}`, source); } const inputShape = inputSize.shape; const inputRank = inputSize.rank(); return ctx .require( [ctx.genOr(ctx.genEq(inputRank, 1, source), ctx.genEq(inputRank, 2, source), source)], `from 'LibCall.torch.diag': rank must be 1 or 2`, source ) .flatMap((ctx) => { const isRankOne = ctx.genEq(inputRank, 1, source); const [rankOnePath, rankTwoPath] = ctx.ifThenElse(isRankOne, source); const leftPath = rankOnePath.flatMap((ctx) => { const dim0 = ExpNum.index(inputShape, 0, source); const diagAbs = ExpNum.uop(NumUopType.Abs, diagonal.value, source); const newDim = ExpNum.bop(NumBopType.Add, dim0, diagAbs, source); const returnShape = ExpShape.fromConst(2, [newDim, newDim], source); return genTensor(ctx, returnShape, source); }); const rightPath = rankTwoPath.flatMap((ctx) => { const dim0 = ExpNum.index(inputShape, 0, source); const dim1 = ExpNum.index(inputShape, 1, source); const negDim0 = ExpNum.uop(NumUopType.Neg, dim0, source); const dim0diag = ExpNum.bop(NumBopType.Add, dim0, diagonal.value, source); const dim1diag = ExpNum.bop(NumBopType.Sub, dim1, diagonal.value, source); const minDim = ExpNum.min([dim0, dim1, dim0diag, dim1diag], source); const returnShape = ExpShape.fromConst(1, [minDim], source); return ctx .require( [ctx.genLte(negDim0, diagonal.value, source), ctx.genLte(diagonal.value, dim1, source)], `from 'LibCall.torch.diag': diagonal must be gte -d1 and lte d2`, source ) .flatMap((ctx) => { return genTensor(ctx, returnShape, source); }); }); return leftPath.join(rightPath); }); } export function flatten(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length < 1) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.flatten': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [inputAddr, startDimAddr, endDimAddr] = params; const inputSize = fetchSize(inputAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.flatten': ${inputSize}`, source); } const inputShape = inputSize.shape; const inputRank = inputSize.rank(); let startDim = fetchAddr(startDimAddr, heap); if (startDim === undefined) { startDim = SVInt.create(ExpNum.fromConst(0, source), source); } else if (startDim.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.flatten': start is not an integer`, source); } let endDim = fetchAddr(endDimAddr, heap); if (endDim === undefined) { endDim = SVInt.create(ExpNum.bop(NumBopType.Sub, inputRank, 1, source), source); } else if (endDim.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.flatten': end is not an integer`, source); } else if (endDim.value === -1 || endDim.value === ExpNum.fromConst(-1, source)) { endDim = SVInt.create(ExpNum.bop(NumBopType.Sub, inputRank, 1, source), source); } const frontShape = ExpShape.slice(inputShape, 0, startDim.value, source); const endShape = ExpShape.slice( inputShape, ExpNum.bop(NumBopType.Add, endDim.value, 1, source), inputRank, source ); const middleShape = ExpShape.slice( inputShape, startDim.value, ExpNum.bop(NumBopType.Add, endDim.value, 1, source), source ); const middleDim = ExpNum.numel(middleShape, source); const returnShape = ExpShape.concat( ExpShape.concat(frontShape, ExpShape.fromConst(1, [middleDim], source), source), endShape, source ); return ctx .require( [ctx.genLte(0, startDim.value, source), ctx.genLt(endDim.value, inputRank, source)], `from 'LibCall.torch.flatten': start_dim, end_dim range error`, source ) .flatMap((ctx) => genTensor(ctx, returnShape, source)); } export function narrow(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length < 1) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.narrow': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [inputAddr, dimAddr, startAddr, lengthAddr] = params; const inputSize = fetchSize(inputAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.narrow': ${inputSize}`, source); } const inputShape = inputSize.shape; const inputRank = inputSize.rank(); const dim = fetchAddr(dimAddr, heap); const start = fetchAddr(startAddr, heap); const length = fetchAddr(lengthAddr, heap); if (dim?.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.narrow': dim is not an integer`, source); } if (start?.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.narrow': start is not an integer`, source); } if (length?.type !== SVType.Int) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.narrow': length is not an integer`, source); } const endVal = ExpNum.bop(NumBopType.Add, start.value, length.value, source); const axisDim = ExpNum.index(inputShape, dim.value, source); return ctx .require( [ctx.genLte(0, dim.value, source), ctx.genLt(dim.value, inputRank, source)], `from 'LibCall.torch.narrow': 'dim' range error`, source ) .require( [ctx.genLte(0, start.value, source), ctx.genLte(endVal, axisDim, source)], `from 'LibCall.torch.narrow': narrowing range error`, source ) .flatMap((ctx) => genTensor(ctx, ExpShape.setDim(inputShape, dim.value, length.value, source), source)); } export function pixel_shuffle( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.pixel_shuffle': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [inputAddr, factorAddr] = params; const inputSize = fetchSize(inputAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.pixel_shuffle': ${inputSize}`, source); } const factor = fetchAddr(factorAddr, heap); if (factor?.type !== SVType.Int) { const svType = factor?.type ?? SVType.Undef; return ctx.warnTensorWithMsg( `from 'LibCall.torch.pixel_shuffle': upscale_factor is not an int type. got ${svTypeToString(svType)}`, source ); } const factorVal = factor.value; const factSquare = ExpNum.bop(NumBopType.Mul, factorVal, factorVal, source); const inputShape = inputSize.shape; const inputRank = inputSize.rank(); const r3 = ExpNum.bop(NumBopType.Sub, inputRank, 3, source); const channel = ExpNum.index(inputShape, r3, source); return ctx .require( [ctx.genLte(3, inputRank, source)], `from 'LibCall.torch.pixel_shuffle': input rank should be greater or equal than 3`, source ) .require( [ctx.genEq(ExpNum.bop(NumBopType.Mod, channel, factSquare, source), 0, source)], `from 'LibCall.torch.pixel_shuffle': input's 'channel' dimension to be divisible by the square of upscale_factor`, source ) .flatMap((ctx) => { let retShape = inputShape; const r1 = ExpNum.bop(NumBopType.Sub, inputRank, 1, source); const r2 = ExpNum.bop(NumBopType.Sub, inputRank, 2, source); const width = ExpNum.index(inputShape, r1, source); const height = ExpNum.index(inputShape, r2, source); retShape = ExpShape.setDim(retShape, r1, ExpNum.bop(NumBopType.Mul, width, factorVal, source), source); retShape = ExpShape.setDim(retShape, r2, ExpNum.bop(NumBopType.Mul, height, factorVal, source), source); retShape = ExpShape.setDim( retShape, r3, ExpNum.bop(NumBopType.FloorDiv, channel, factSquare, source), source ); return genTensor(ctx, retShape, source); }); } // TODO: `broadcastable` is not the sufficient condition for this code export function layer_norm( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length < 4) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.layer_norm': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [inputAddr, normAddr] = params; const inputSize = fetchSize(inputAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.embedding': ${inputSize}`, source); } const inputShape = inputSize.shape; const normSize = fetchSize(normAddr, heap); if (typeof normSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.embedding': ${normSize}`, source); } const normShape = normSize.shape; return ctx.shBroadcast(inputShape, normShape, source).flatMap((ctx) => genTensor(ctx, ctx.retVal, source)); } export function pad(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.pad': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [selfAddr, padsAddr] = params; const selfSize = fetchSize(selfAddr, heap); const pads = fetchAddr(padsAddr, heap); if (typeof selfSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.pad': ${selfSize}`, source); } else if (pads?.type !== SVType.Object) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.pad': pad is not iterable`, source); } const selfShape = selfSize.shape; const selfRank = selfSize.rank(); const tupleLenObj = fetchAddr(pads.getAttr('$length'), heap); if (tupleLenObj?.type !== SVType.Int || typeof tupleLenObj.value !== 'number') { return ctx.failWithMsg(`from 'LibCall.torch.pad': pad is not iterable`, source).toSet(); } const tupleLen = tupleLenObj.value; if (tupleLen % 2 === 1 || tupleLen <= 0) { return ctx.failWithMsg(`from 'LibCall.torch.pad': pad has an odd or invalid length`, source).toSet(); } let newCtx: Context<any> = ctx; const padSizes: (ExpNum | number)[] = []; for (let i = 0; i < tupleLen; i++) { const padDim = fetchAddr(pads.getIndice(i), heap); if (padDim?.type === SVType.Int) { padSizes.push(padDim.value); } else { const dimCtx = newCtx.genIntGte(`pad_dim${i}`, 0, source); newCtx = dimCtx; padSizes.push(dimCtx.retVal); } } return newCtx .require( newCtx.genLte(tupleLen / 2, selfRank, source), "from 'LibCall.torch.pad': input shape has rank shorter than pad count / 2", source ) .flatMap((ctx) => { let shape = selfShape; const rankN = tupleLen / 2; for (let i = 0; i < rankN; i++) { const padLeft = padSizes[i * 2]; const padRight = padSizes[i * 2 + 1]; shape = ExpShape.setDim( shape, ExpNum.bop(NumBopType.Sub, selfRank, i + 1, source), ExpNum.bop( NumBopType.Add, ExpNum.bop( NumBopType.Add, ExpNum.index(shape, ExpNum.bop(NumBopType.Sub, selfRank, i + 1, source), source), padLeft, source ), padRight, source ), source ); } return genTensor(ctx, shape, source); }); } export function adaptive(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.adaptive': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [selfAddr, padsAddr] = params; const selfSize = fetchSize(selfAddr, heap); const outputSize = fetchAddr(padsAddr, heap); if (typeof selfSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.adaptive': ${selfSize}`, source); } else if (outputSize?.type !== SVType.Object) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.adaptive': output size is not iterable`, source); } const selfShape = selfSize.shape; const selfRank = selfSize.rank(); const tupleLenObj = fetchAddr(outputSize.getAttr('$length'), heap); if (tupleLenObj?.type !== SVType.Int || typeof tupleLenObj.value !== 'number') { return ctx.failWithMsg(`from 'LibCall.torch.adaptive': output size is not iterable`, source).toSet(); } const tupleLen = tupleLenObj.value; if (tupleLen <= 0) { return ctx.failWithMsg(`from 'LibCall.torch.adaptive': invalid length of output size`, source).toSet(); } let newCtx: Context<any> = ctx; const outSizes: (ExpNum | number)[] = []; for (let i = 0; i < tupleLen; i++) { const outDim = fetchAddr(outputSize.getIndice(i), heap); if (outDim?.type === SVType.Int) { outSizes.push(outDim.value); } else { const dimCtx = newCtx.genIntGte(`out_dim${i}`, 0, source); newCtx = dimCtx; outSizes.push(dimCtx.retVal); } } return newCtx .require( newCtx.genLte(tupleLen, selfRank, source), "from 'LibCall.torch.adaptive': input shape has rank shorter than output size", source ) .flatMap((ctx) => { let shape = selfShape; const rankN = tupleLen; for (let i = 0; i < rankN; i++) { const outDim = outSizes[rankN - i - 1]; shape = ExpShape.setDim(shape, ExpNum.bop(NumBopType.Sub, selfRank, i + 1, source), outDim, source); } return genTensor(ctx, shape, source); }); } export function genDatasetLen( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 1) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.genDatasetLen': got insufficient number of argument: ${params.length}`, source ); } return ctx.setRetVal(SVNotImpl.create('not implemented', source)).toSet(); } export function datasetGetItem( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 2) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.genDatasetLen': got insufficient number of argument: ${params.length}`, source ); } return ctx.setRetVal(SVNotImpl.create('not implemented', source)).toSet(); } export function warnTensorWithMsg( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 1) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.warnTensorWithMsg': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const msg = fetchAddr(params[0], heap); if (msg?.type !== SVType.String) { return ctx.warnTensorWithMsg(`from 'LibCall.torch.warnTensorWithMsg': invalid message`, source); } return ctx.warnTensorWithMsg(typeof msg.value === 'string' ? msg.value : ExpString.toString(msg.value), source); } // implementation of torch.nn.functional.interpolate export function interpolate( ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined ): ContextSet<ShValue> { const params = ctx.retVal.params; if (params.length !== 3) { return ctx.warnTensorWithMsg( `from 'LibCall.torch.interpolate': got insufficient number of argument: ${params.length}`, source ); } const heap = ctx.heap; const [inputAddr, sizeAddr, scaleFactorAddr] = params; const inputSize = fetchSize(inputAddr, heap); const outSizeObj = fetchAddr(sizeAddr, heap); const scaleFactorObj = fetchAddr(scaleFactorAddr, heap); if (typeof inputSize === 'string') { return ctx.warnTensorWithMsg(`from 'LibCall.torch.interpolate': ${inputSize}`, source); } if (outSizeObj?.type === SVType.None && scaleFactorObj?.type === SVType.None) { return ctx .failWithMsg( `from 'LibCall.torch.interpolate': only one of size or scale_factor should be defined`, source ) .toSet(); } const outSize: (ExpNum | number)[] = []; let outSizeConst: ExpNum | number | undefined; if (outSizeObj?.type === SVType.Int) { outSizeConst = outSizeObj.value; outSize.push(outSizeConst); } else if (outSizeObj?.type === SVType.Object) { const dims = outSizeObj.extractIndexedNumber(ctx.heap); if (dims.has(0)) outSize.push(dims.get(0)!); if (dims.has(1)) outSize.push(dims.get(1)!); if (dims.has(2)) outSize.push(dims.get(2)!); } const scaleFactor: (ExpNum | number)[] = []; let scaleFactorConst: ExpNum | number | undefined; if (scaleFactorObj?.type === SVType.Float || scaleFactorObj?.type === SVType.Int) { scaleFactorConst = scaleFactorObj.value; scaleFactor.push(scaleFactorConst); } else if (scaleFactorObj?.type === SVType.Object) { const factors = scaleFactorObj.extractIndexedNumber(ctx.heap); if (factors.has(0)) scaleFactor.push(factors.get(0)!); if (factors.has(1)) scaleFactor.push(factors.get(1)!); if (factors.has(2)) scaleFactor.push(factors.get(2)!); } if (outSize.length === 0 && scaleFactor.length === 0) { return ctx .failWithMsg( `from 'LibCall.torch.interpolate': only one of size or scale_factor should be defined`, source ) .toSet(); } const inputShape = inputSize.shape; const inputRank = inputSize.rank(); if (outSizeConst !== undefined || scaleFactorConst !== undefined) { return ctx .require( [ctx.genLte(3, inputRank, source), ctx.genLte(inputRank, 5, source)], `from 'LibCall.torch.interpolate': expected inputs are 3, 4, or 5-D shape`, source ) .flatMap((ctx: Context<unknown>) => { const [rank3, rank45] = ctx.ifThenElse(ctx.genEq(3, inputRank, source), source); const [rank4, rank5] = rank45.ifThenElse(ctx.genEq(4, inputRank, source), source); const shapes: ExpShape[] = []; let newShape: ExpShape = inputShape; for (let dim = 2; dim <= 4; dim++) { if (outSizeConst !== undefined) { newShape = ExpShape.setDim(newShape, dim, outSizeConst, source); } else { newShape = ExpShape.setDim( newShape, dim, ExpNum.uop( NumUopType.Floor, ExpNum.bop( NumBopType.Mul, ExpNum.index(newShape, dim, source), scaleFactorConst!, source ), source ), source ); } shapes.push(newShape); } return rank3 .flatMap((ctx) => genTensor(ctx, shapes[0], source)) .join(rank4.flatMap((ctx) => genTensor(ctx, shapes[1], source))) .join(rank5.flatMap((ctx) => genTensor(ctx, shapes[2], source))); }); } else if (outSize.length > 0) { return ctx .require( ctx.genEq(inputRank, 2 + outSize.length, source), `from 'LibCall.torch.interpolate': size shape must match with input shape`, source ) .flatMap((ctx) => { let newShape: ExpShape = inputShape; outSize.forEach((size, dim) => { newShape = ExpShape.setDim(newShape, dim + 2, size, source); }); return genTensor(ctx, newShape, source); }); } else { return ctx .require( ctx.genEq(inputRank, 2 + scaleFactor.length, source), `from 'LibCall.torch.interpolate': scale_factor shape must match with input shape`, source ) .flatMap((ctx) => { let newShape: ExpShape = inputShape; scaleFactor.forEach((factor, dim) => { newShape = ExpShape.setDim( newShape, dim + 2, ExpNum.uop( NumUopType.Floor, ExpNum.bop(NumBopType.Mul, ExpNum.index(inputShape, dim + 2, source), factor, source), source ), source ); }); return genTensor(ctx, newShape, source); }); } } export const libCallImpls: { [key: string]: LCImpl } = { getInitShape, tensorGetItem, scalarTensor, callTensor, identityShape, sameShape, copyOut, broadcast, cat, stack, matmul, mm, bmm, item, repeat, expand, expand_as, transpose, reduce, view, topk, conv2d, conv_transpose2d, pool2d, batchnorm2d, interpolate, cross_entropy, unsqueeze, squeeze, diag, flatten, narrow, pixel_shuffle, layer_norm, pad, adaptive, genDatasetLen, datasetGetItem, warnTensorWithMsg, }; } export const libCallMap: Map<string, LCImpl> = new Map([...Object.entries(TorchLCImpl.libCallImpls)]);
the_stack
import { CheckCircledIcon, ClipboardIcon, DotsHorizontalIcon, ExclamationTriangleIcon, } from '@radix-ui/react-icons'; import { createEntriesFromVolume, findAllTokenFiles } from 'artkit-collection'; import { Button as RainbowButton, Code, FormRow, FormSection, Heading3, HStack, LinkChip, Regular, ScrollableStack, Small, SpacerHorizontal, VStack, } from 'components'; import { Button, InputField } from 'designsystem'; import { createCarBlob, FileData, fileDataToBytes } from 'files'; import { Node, Volume } from 'imfs'; import React, { ReactNode, useReducer, useRef, useState } from 'react'; import { PublishingState, publishingStateReducer } from 'state'; import { useTheme } from 'styled-components'; import { uploadToNFTStorage } from '../../../utils/nftStorage'; const inputStyle = { padding: '8px 12px', fontSize: '14px', fontFamily: 'monospace', }; function CopyableInputRow({ value }: { value: string }) { const ref = useRef<HTMLInputElement>(null); return ( <HStack gap={8} flex="1"> <InputField.Root id="input-row"> <InputField.Input ref={ref} value={value} type="text" style={inputStyle} onChange={() => {}} /> </InputField.Root> <Button onClick={() => { ref.current?.select(); document.execCommand('copy'); }} > <SpacerHorizontal size={4} inline /> <ClipboardIcon width={15} /> <SpacerHorizontal size={4} inline /> </Button> </HStack> ); } const uploadPath = async ( apiKey: string, volume: Node<FileData>, path: string, assetsRootCID?: string, ) => { const assets = Volume.getNode(volume, path); if (assets.type === 'file') { const blob = new Blob([fileDataToBytes(assets.data)]); return await uploadToNFTStorage({ apiKey, blob, isCar: false }); } const entries = createEntriesFromVolume(assets, assetsRootCID); const { blob } = await createCarBlob(entries); const cid = await uploadToNFTStorage({ apiKey, blob, isCar: true }); return cid; }; function ProgressItem({ children }: { children: ReactNode }) { return ( <HStack gap={6} alignItems="center" padding={10} background="rgba(0,0,0,0.1)" > {children} </HStack> ); } const LOCALSTORAGE_KEY_NFT_STORAGE = 'nftStorageApiKey'; export function PublishingTool({ volume, entry, }: { volume: Node<FileData>; entry: string; }) { const initialState: PublishingState = { type: 'ready' }; const [publishingState, dispatchPublishing] = useReducer( publishingStateReducer, initialState, ); const theme = useTheme(); const [nftStorageApiKey, setNftStorageApiKey] = useState( typeof localStorage !== 'undefined' ? localStorage.getItem(LOCALSTORAGE_KEY_NFT_STORAGE) ?? '' : '', ); return ( <VStack gap={20} minWidth={'600px'}> {publishingState.type === 'ready' && ( <> <Regular> Here you can upload your metadata files and any assets to IPFS, the distributed storage network. Files are hosted for free thanks to{' '} <LinkChip href="https://nft.storage" openInNewTab> https://nft.storage </LinkChip> . </Regular> <Regular> To upload using this tool, you'll first need to make an API key on their site. After you upload, you'll recieve an{' '} <code style={{ background: 'rgba(0,0,0,0.5)' }}>ipfs://...</code>{' '} URL that you can use in a smart contract. </Regular> <VStack paddingVertical={10} gap={30}> <FormSection title={<Heading3>Configuration</Heading3>}> <FormRow title="NFT Storage API Key"> <InputField.Root id="input-nft-storage-api-key"> <InputField.Input type="password" placeholder="Paste your API key..." value={nftStorageApiKey} onChange={(value) => { localStorage.setItem(LOCALSTORAGE_KEY_NFT_STORAGE, value); setNftStorageApiKey(value); }} /> </InputField.Root> </FormRow> </FormSection> </VStack> <HStack justifyContent="end"> <RainbowButton disabled={!nftStorageApiKey} onClick={async () => { let assetsCID: string | undefined; let metadataCID: string | undefined; if (hasAssetsToUpload(volume)) { console.log('has assets'); dispatchPublishing({ type: 'setUploadingAssets', value: { type: 'pending' }, }); try { assetsCID = await uploadPath( nftStorageApiKey, volume, '/assets', ); } catch (e) { dispatchPublishing({ type: 'setUploadingAssets', value: { type: 'failure', value: e as Error }, }); return; } dispatchPublishing({ type: 'setUploadingAssets', value: { type: 'success', value: assetsCID }, }); } console.log('ok!', assetsCID); dispatchPublishing({ type: 'setUploadingMetadata', value: { type: 'pending' }, rootAssetsCID: assetsCID, }); try { metadataCID = await uploadPath( nftStorageApiKey, volume, entry, assetsCID, ); } catch (e) { dispatchPublishing({ type: 'setUploadingMetadata', value: { type: 'failure', value: e as Error }, }); return; } dispatchPublishing({ type: 'setUploadingMetadata', value: { type: 'success', value: metadataCID }, }); }} > Publish to IPFS </RainbowButton> </HStack> </> )} {publishingState.type === 'uploadingAssets' && publishingState.value.type === 'pending' && ( <ProgressItem> <DotsHorizontalIcon width={20} height={20} className="flickerAnimation" /> <Regular>Uploading /assets...</Regular> </ProgressItem> )} {publishingState.type === 'uploadingAssets' && publishingState.value.type === 'failure' && ( <> <ProgressItem> <ExclamationTriangleIcon width={20} height={20} color="red" /> <Regular>Failed to upload /assets</Regular> </ProgressItem> <VStack height={200} background={theme.colors.inputBackground}> <ScrollableStack innerProps={{ padding: 10 }}> <Code>{publishingState.value.value.message}</Code> </ScrollableStack> </VStack> </> )} {((publishingState.type === 'uploadingAssets' && publishingState.value.type === 'success') || (publishingState.type === 'uploadingMetadata' && publishingState.rootAssetsCID)) && ( <> <ProgressItem> <CheckCircledIcon width={20} height={20} color="lightgreen" /> <Regular>Uploaded assets</Regular> {/* <SpacerHorizontal size={40} /> <InputField.Root> <InputField.Input value={`ipfs://${publishingState.value.value}`} onChange={() => {}} /> </InputField.Root> */} </ProgressItem> </> )} {publishingState.type === 'uploadingMetadata' && publishingState.value.type === 'pending' && ( <ProgressItem> <DotsHorizontalIcon width={20} height={20} className="flickerAnimation" /> <Regular>Uploading {entry}...</Regular> </ProgressItem> )} {publishingState.type === 'uploadingMetadata' && publishingState.value.type === 'failure' && ( <> <ProgressItem> <ExclamationTriangleIcon width={20} height={20} color="red" /> <Regular>Failed to upload {entry}</Regular> </ProgressItem> <VStack height={200} background={theme.colors.inputBackground}> <ScrollableStack innerProps={{ padding: 10 }}> <Code>{publishingState.value.value.message}</Code> </ScrollableStack> </VStack> </> )} {publishingState.type === 'uploadingMetadata' && publishingState.value.type === 'success' && ( <> <ProgressItem> <CheckCircledIcon width={20} height={20} color="lightgreen" /> <Regular>Uploaded metadata</Regular> <SpacerHorizontal size={40} /> </ProgressItem> <Heading3>Done!</Heading3> <VStack gap={10} background="#24562f" padding={10} borderRadius={2}> <Small> If you're creating a contract with Studio 721, use this URI as your Token URI: </Small> <CopyableInputRow value={`ipfs://${publishingState.value.value}/{tokenId}.token.json`} /> </VStack> <VStack gap={10} background="rgba(0,0,0,0.1)" padding={10} borderRadius={2} > <Small>Your metadata's IPFS URI:</Small> <CopyableInputRow value={`ipfs://${publishingState.value.value}`} /> </VStack> <VStack gap={10}> <Small> You may also browse your uploaded{' '} {publishingState.rootAssetsCID && ( <> <LinkChip style={{ padding: '0', background: 'none', }} href={`https://${publishingState.rootAssetsCID}.ipfs.dweb.link/`} openInNewTab > assets </LinkChip> {' and '} </> )} <LinkChip style={{ padding: '0', background: 'none', }} href={`https://${publishingState.value.value}.ipfs.dweb.link/`} openInNewTab > metadata </LinkChip> . </Small> </VStack> </> )} </VStack> ); } function hasAssetsToUpload(volume: Node<FileData>) { const tokensWithInternalFiles = findAllTokenFiles( volume, (_name, metadata) => (metadata.image?.startsWith('/') || metadata.animation_url?.startsWith('/') || metadata.external_url?.startsWith('/')) ?? false, ); console.log('has assets to upload?', { tokensWithInternalFiles }); return tokensWithInternalFiles.length > 0; }
the_stack
interface StyleMap { readonly [key: string]: string | number; } interface Rect extends ClientRect { readonly top: number; readonly bottom: number; readonly left: number; readonly right: number; readonly width: number; readonly height: number; readonly transform?: string; } export function getRect(element: HTMLElement, ancestor?: HTMLElement): Rect { const { top, bottom, left, right, width, height } = element.getBoundingClientRect(); const parentRect = ancestor ? ancestor.getBoundingClientRect() : undefined; return { top: top - (parentRect ? parentRect.top : 0), bottom, left: left - (parentRect ? parentRect.left : 0), right, width, height, get transform() { return getComputedStyle(element).transform || undefined; } }; } export function getStyles(element: HTMLElement): StyleMap { const computedStyle = getComputedStyle(element); return { radius: computedStyle.borderRadius || 0 }; } interface Delta extends Rect { x: number; y: number; widthRatio: number; heightRatio: number; } const NO_DELTA: Delta = { x: 0, y: 0, top: 0, bottom: 0, left: 0, right: 0, width: 0, height: 0, widthRatio: 1, heightRatio: 1 }; export function getDelta(firstRect: Rect, lastRect: Rect): Delta { const dx = lastRect.left - firstRect.left; const dy = lastRect.top - firstRect.top; const dw = lastRect.width - firstRect.width; const dh = lastRect.height - firstRect.height; return { x: dx, y: dy, top: dy, bottom: lastRect.bottom - firstRect.bottom, left: dx, right: lastRect.right - firstRect.right, width: dw, height: dh, widthRatio: lastRect.width / firstRect.width, heightRatio: lastRect.height / firstRect.height }; } export function getInverse(delta: Delta): Delta { return { x: -1 * delta.x, y: -1 * delta.y, top: -1 * delta.top, bottom: -1 * delta.bottom, left: -1 * delta.left, right: -1 * delta.right, width: -1 * delta.width, height: -1 * delta.height, widthRatio: 1 / delta.widthRatio, heightRatio: 1 / delta.heightRatio }; } type FlipData = { state: | 'read' | 'pre-enter' | 'enter' | 'pre-move' | 'move' | 'pre-exit' | 'exit'; key: string; element: HTMLElement | undefined; rect: Rect | undefined; styles: StyleMap | undefined; delta: Delta; inverse: Delta; previous: FlipData | undefined; }; type FlipElementMap = Record<string, HTMLElement | undefined>; type FlipListener = (data: FlipData) => void; export function isVisible(element?: HTMLElement) { if (!element) { return false; } const { width, height } = getRect(element); return !(width === 0 && height === 0); } interface FlippingConfig { getKey: ((element: HTMLElement) => string | null | undefined) | string; } export class Flipping { public data: Record<string, FlipData | undefined> = {}; public listeners: Map<string, FlipListener> = new Map(); public globalListeners: Set<FlipListener> = new Set(); public config: FlippingConfig; public static prefix = 'flip'; public static keyAttr = 'data-flip-key'; public static defaultConfig = { getKey(element: Element): string { const key = element.getAttribute(Flipping.keyAttr); if (!key) { // tslint:disable-next-line:no-console console.error(`No flip key found for element:`, element); throw new Error(`Missing flip key for element`); } return key; } }; public static create(config: FlippingConfig = Flipping.defaultConfig) { return new Flipping(config); } constructor(config: FlippingConfig = Flipping.defaultConfig) { this.config = { ...Flipping.defaultConfig, ...config }; } public onFlip(globalListener: FlipListener): void { this.globalListeners.add(globalListener); } private findAncestor(element: HTMLElement): HTMLElement | undefined { let currentParent = element.parentElement; while (currentParent && !currentParent.hasAttribute(Flipping.keyAttr)) { currentParent = currentParent.parentElement; } return currentParent || undefined; } private set(key: string, data: FlipData): void { this.data[key] = data; this.globalListeners.forEach(listener => { listener(data); }); if (data.element) { data.element.dataset.flipState = data.state; } else if (data.previous && data.previous.element) { data.previous.element.dataset.flipState = data.state; } if (!data.rect || !data.styles) { return; } const distX = Math.abs(data.delta.left); const distY = Math.abs(data.delta.top); // const h = Math.hypot(distX, distY); // const arm = h / 2 / Math.cos(Math.atan(distX / distY)); // const arm2 = (distX + distY) / 2; // const armRatio = arm / distY; // const theta = Math.asin(h / 2 / arm) * 2; const inverseXY = `translate(${data.inverse.left}px, ${ data.inverse.top }px)`; const inverseScale = `scale(${data.inverse.widthRatio}, ${ data.inverse.heightRatio })`; // const s = `translateY(${data.inverse.top * // armRatio}px) rotate(${-theta}rad) translateY(${data.delta.top * // armRatio}px) rotate(${theta}rad)`; // const ss = `translateY(${data.inverse.top * // armRatio}px) rotate(0deg) translateY(${data.delta.top * // armRatio}px) rotate(0deg)`; const a = `translate(${data.inverse.left + data.inverse.top}px, ${ data.inverse.top }px) rotate(-90deg) translateY(${ data.delta.top }px) rotate(90deg) ${inverseScale}`; const aa = `translate(${data.inverse.left + data.inverse.top}px, ${ data.inverse.top }px) rotate(0deg) translate(${data.delta.left + data.delta.top}px, ${ data.delta.top }px) rotate(0deg) scale(1)`; Flipping.style( data, { // position x: data.rect.left, y: data.rect.top, // delta dx: data.delta.left, dy: data.delta.top, // inverse delta ix: data.inverse.left, iy: data.inverse.top, 'inverse-xy': inverseXY, // scale iw: data.inverse.width, ih: data.inverse.height, 'iw-ratio': data.inverse.widthRatio, 'ih-ratio': data.inverse.heightRatio, 'inverse-scale': inverseScale, // distance 'distance-x': distX, 'distance-y': distY, distance: Math.hypot(distX, distY), // radius 'inverse-radius-x': `calc((${data.styles.radius} * ${ data.delta.widthRatio }))`, 'inverse-radius-y': `calc((${data.styles.radius} * ${ data.delta.heightRatio }))`, 'inverse-radius': `var(--flip-inverse-radius-x) / var(--flip-inverse-radius-y)`, // curve curve: a, fcurve: aa }, { px: true } ); } public static style( data: FlipData, styles: Record<string, number | string>, options?: Partial<{ px: boolean }> // TODO ): void { const { element } = data; if (!element) { return; } const resolvedOptions = { px: true, ...options }; Object.keys(styles).forEach(property => { const fullProperty = `--${Flipping.prefix + '-' + property}`; const value = `${styles[property]}`; element.style.setProperty(fullProperty, value); if (resolvedOptions.px && !isNaN(+fullProperty)) { element.style.setProperty(`${fullProperty}-px`, `${value}px`); } }); } private toElementMap( elements: HTMLElement[] | FlipElementMap | undefined ): FlipElementMap { if (!elements) { elements = (Array.from( document.querySelectorAll(`[${Flipping.keyAttr}]`) ) as HTMLElement[]).filter(el => isVisible(el)); } const map: FlipElementMap = {}; if (Array.isArray(elements)) { elements.forEach(element => { const key = typeof this.config.getKey === 'string' ? element.getAttribute(this.config.getKey) : this.config.getKey(element); if (!key) { return; } map[key] = element; }); return map; } return elements; } public read(elements?: HTMLElement[] | FlipElementMap): void { const elementMap = this.toElementMap(elements); Object.keys(elementMap).forEach(key => { const element = elementMap[key]; const previous = this.data[key]; if (!element) { return; } this.set(key, { key, element, state: 'read', rect: getRect(element, this.findAncestor(element)), styles: getStyles(element), delta: NO_DELTA, inverse: NO_DELTA, previous }); }); } public flip(elements?: HTMLElement[]) { const elementMap = this.toElementMap(elements); const allKeys = new Set( Object.keys(this.data).concat(Object.keys(elementMap)) ); allKeys.forEach(key => { const element = elementMap[key]; let data: FlipData; const existingData = this.data[key]; const visible = isVisible(element); if (!element || !visible) { data = { key, element, state: 'exit', rect: undefined, styles: undefined, delta: NO_DELTA, inverse: NO_DELTA, previous: existingData }; } else if (!existingData && element && visible) { data = { key, element, state: 'enter', rect: getRect(element, this.findAncestor(element)), styles: getStyles(element), delta: NO_DELTA, inverse: NO_DELTA, previous: undefined }; } else if (existingData && element && visible) { const delta = existingData.rect ? getDelta( existingData.rect, getRect(element, this.findAncestor(element)) ) : NO_DELTA; // console.log(existingData, getRect(element), delta); data = { key, element, state: existingData.state === 'exit' ? visible ? 'enter' : 'exit' : visible ? 'move' : 'exit', rect: getRect(element, this.findAncestor(element)), styles: getStyles(element), delta, inverse: getInverse(delta), previous: existingData }; } requestAnimationFrame(() => { this.set(key, { ...data, state: `pre-${data.state}` as 'pre-enter' | 'pre-move' | 'pre-exit' }); requestAnimationFrame(() => { this.set(key, data); }); }); }); } public wrap<T>( fn: (...args: any[]) => T, elements?: HTMLElement[] ): (...args: any[]) => T { return (...args) => { this.read(elements); const result = fn.apply(null, args) as T; this.flip(elements); return result; }; } public applyDefaultStyles() { const styles = ` [data-flip-state] { will-change: transform; } [data-flip-state="read"] { transition: none; } [data-flip-state="pre-move"] { transition: none; transform: var(--flip-inverse-xy); --clip-path: polygon(0% 0%, calc(var(--flip-iw-ratio) * 100%) 0, calc(var(--flip-iw-ratio) * 100%) calc(var(--flip-ih-ratio) * 100%), 0 calc(var(--flip-ih-ratio) * 100%)); } [data-flip-state="move"] { transition: all .6s ease; transform: none; --clip-path: polygon(0% 0%, 100% 0, 100% 100%, 0 100%); } `; const elStyle = document.createElement('style'); elStyle.innerHTML = styles; document.head.appendChild(elStyle); } } export const create = Flipping.create;
the_stack
import { Injectable, Inject, forwardRef } from "@nestjs/common"; import { InjectRepository, InjectConnection } from "@nestjs/typeorm"; import { Repository, Connection, QueryBuilder } from "typeorm"; import { ValidationError } from "class-validator"; import { v4 as uuid } from "uuid"; import moment from "moment-timezone"; import { logger } from "@/logger"; import { ProblemPermissionType, ProblemService } from "@/problem/problem.service"; import { UserEntity } from "@/user/user.entity"; import { ProblemEntity, ProblemType } from "@/problem/problem.entity"; import { JudgeQueueService, JudgeTaskType, JudgeTaskPriorityType, JudgeTask, JudgeTaskExtraInfo } from "@/judge/judge-queue.service"; import { JudgeTaskService } from "@/judge/judge-task-service.interface"; import { ProblemFileType } from "@/problem/problem-file.entity"; import { ProblemJudgeInfo } from "@/problem/problem-judge-info.interface"; import { UserService } from "@/user/user.service"; import { ProblemSampleData } from "@/problem/problem-sample-data.interface"; import { LockService } from "@/redis/lock.service"; import { JudgeGateway } from "@/judge/judge.gateway"; import { ProblemTypeFactoryService } from "@/problem-type/problem-type-factory.service"; import { AuditLogObjectType, AuditService } from "@/audit/audit.service"; import { AlternativeUrlFor, FileService } from "@/file/file.service"; import { ConfigService } from "@/config/config.service"; import { FileEntity } from "@/file/file.entity"; import { UserPrivilegeService, UserPrivilegeType } from "@/user/user-privilege.service"; import { SubmissionProgress, SubmissionProgressType } from "./submission-progress.interface"; import { SubmissionContent } from "./submission-content.interface"; import { SubmissionProgressService, SubmissionEventType } from "./submission-progress.service"; import { SubmissionStatisticsService } from "./submission-statistics.service"; import { SubmissionEntity } from "./submission.entity"; import { SubmissionDetailEntity } from "./submission-detail.entity"; import { SubmissionStatus } from "./submission-status.enum"; import { FileUploadInfoDto, SignedFileUploadRequestDto } from "@/file/dto"; import { SubmissionBasicMetaDto } from "./dto"; export enum SubmissionPermissionType { View = "View", Cancel = "Cancel", Rejudge = "Rejudge", ManagePublicness = "ManagePublicness", Delete = "Delete" } interface SubmissionTaskExtraInfo extends JudgeTaskExtraInfo { problemType: ProblemType; judgeInfo: ProblemJudgeInfo; samples?: ProblemSampleData; testData: Record<string, string>; // filename -> uuid submissionContent: SubmissionContent; file?: { uuid: string; url: string; }; } function makeSubmissionPriority( id: number, userPendingCount: number, userOccupiedTimeRecently: number, avgEveryUsersOccupiedTimeRecently: number, stdEveryUsersOccupiedTimeRecently: number, priorityType: JudgeTaskPriorityType ): number { // For any `x` > 1, the larger `x` is, the smaller `1 / x` will be, // so the less `priority - (1 / x)` will increase the priority // Let `x` = `t_1` * `t_2` * `t_3` .... // For some `t_i` in [1, `n_i`], the smaller `n_i`, the more significantly it will influence `x` // Because, with the same `t_i`, increasing other `t_j`s will influence `x` less significantly // A submission by a user with more pending submissions will have much lower priority const t1 = userPendingCount + 1; // Multiple submissions, with the same number of pending submissions by their users will be compared by their IDs // We should make ID much larger and increase much slower to prevent it from influencing the priority more than pending count const t2 = id + 1000000; // The more time the user occupied recently, the lower the submission' priority will be // We assume the total time occupied by each user fits normal distribution // k: the user's occupied time = average + k * standard deviation const k = (userOccupiedTimeRecently - avgEveryUsersOccupiedTimeRecently) / stdEveryUsersOccupiedTimeRecently; // We map k ** 2 to a number in [1, 100] to have a more significant influence than ID but less than pending count const T3_MIN = 1; const T3_MAX = 100; const K_MIN = 1; const K_MAX = 3; let t3: number; // All time occupied recently is by this user means no other users are submitting, no need to decrease its priority if (Number.isNaN(k) || k < 1) t3 = T3_MIN; // If a user's occupied time > average + 3 * standard deviation, we decrease its priotity to the lowest else if (k > 3) t3 = T3_MAX; // If a user's occupied time > average + 1 * standard deviation, we start decreasing its priority else t3 = ((k ** 2 - K_MIN) / (K_MAX - K_MIN)) * (T3_MAX - T3_MIN) + T3_MIN; // So a larger `x` will lead to a lower priority as we use `priority - (1 / x)` const x = t1 * t2 * t3; return priorityType - 1 / x; } @Injectable() export class SubmissionService implements JudgeTaskService<SubmissionProgress, SubmissionTaskExtraInfo> { constructor( @InjectConnection() private connection: Connection, @InjectRepository(SubmissionEntity) private readonly submissionRepository: Repository<SubmissionEntity>, @InjectRepository(SubmissionDetailEntity) private readonly submissionDetailRepository: Repository<SubmissionDetailEntity>, private readonly problemService: ProblemService, private readonly problemTypeFactoryService: ProblemTypeFactoryService, @Inject(forwardRef(() => UserService)) private readonly userService: UserService, private readonly judgeQueueService: JudgeQueueService, private readonly lockService: LockService, private readonly submissionProgressService: SubmissionProgressService, private readonly submissionStatisticsService: SubmissionStatisticsService, private readonly judgeGateway: JudgeGateway, private readonly auditService: AuditService, private readonly fileService: FileService, private readonly configService: ConfigService, @Inject(forwardRef(() => UserPrivilegeService)) private readonly userPrivilegeService: UserPrivilegeService ) { this.judgeQueueService.registerTaskType(JudgeTaskType.Submission, this); this.auditService.registerObjectTypeQueryHandler(AuditLogObjectType.Submission, async submissionId => { const submission = await this.findSubmissionById(submissionId); return !submission ? null : await this.getSubmissionBasicMeta(submission); }); } async findSubmissionById(submissionId: number): Promise<SubmissionEntity> { return await this.submissionRepository.findOne({ id: submissionId }); } async findSubmissionByTaskId(taskId: string): Promise<SubmissionEntity> { return await this.submissionRepository.findOne({ taskId }); } async findSubmissionsByExistingIds(submissionIds: number[]): Promise<SubmissionEntity[]> { if (submissionIds.length === 0) return []; const uniqueIds = Array.from(new Set(submissionIds)); const records = await this.submissionRepository.findByIds(uniqueIds); const map = Object.fromEntries(records.map(record => [record.id, record])); return submissionIds.map(submissionId => map[submissionId]); } async userHasPermission( user: UserEntity, submission: SubmissionEntity, type: SubmissionPermissionType, problem?: ProblemEntity, hasPrivilege?: boolean ): Promise<boolean> { switch (type) { // Everyone can read a public submission // Submitter and those who has the Modify permission of the submission's problem can View a non-public submission case SubmissionPermissionType.View: if (submission.isPublic) return true; if (!user) return false; if (user.id === submission.submitterId) return true; return await this.problemService.userHasPermission( user, problem ?? (await this.problemService.findProblemById(submission.problemId)), ProblemPermissionType.Modify, hasPrivilege ); // Submitter and those who has the Modify permission of the submission's problem can Cancel a submission case SubmissionPermissionType.Cancel: if (!user) return false; if (user.id === submission.submitterId) return true; return await this.problemService.userHasPermission( user, problem ?? (await this.problemService.findProblemById(submission.problemId)), ProblemPermissionType.Modify, hasPrivilege ); // Those who has the Modify permission of the submission's problem can Rejudge a submission case SubmissionPermissionType.Rejudge: return await this.problemService.userHasPermission( user, problem ?? (await this.problemService.findProblemById(submission.problemId)), ProblemPermissionType.Modify, hasPrivilege ); // Admins can manage a submission's publicness or delete a submission case SubmissionPermissionType.ManagePublicness: case SubmissionPermissionType.Delete: if (!user) return false; else if (user.isAdmin) return true; else if ( hasPrivilege ?? (await this.userPrivilegeService.userHasPrivilege(user, UserPrivilegeType.ManageProblem)) ) return true; else return false; default: return false; } } async querySubmissions( problemId: number, submitterId: number, codeLanguage: string, status: SubmissionStatus, minId: number, maxId: number, publicOnly: boolean, takeCount: number ): Promise<{ result: SubmissionEntity[]; hasSmallerId: boolean; hasLargerId: boolean }> { const queryBuilder = this.submissionRepository.createQueryBuilder(); if (publicOnly) { queryBuilder.andWhere("isPublic = :isPublic", { isPublic: true }); } if (problemId) { queryBuilder.andWhere("problemId = :problemId", { problemId }); } if (submitterId) { queryBuilder.andWhere("submitterId = :submitterId", { submitterId }); } if (codeLanguage) { queryBuilder.andWhere("codeLanguage = :codeLanguage", { codeLanguage }); } if (status) { queryBuilder.andWhere("status = :status", { status }); } const queryBuilderWithoutPagination = queryBuilder.clone(); let reversed = false; if (minId != null) { queryBuilder.andWhere("id >= :minId", { minId }); queryBuilder.orderBy("id", "ASC"); reversed = true; } else if (maxId != null) { queryBuilder.andWhere("id <= :maxId", { maxId }); queryBuilder.orderBy("id", "DESC"); } else { queryBuilder.orderBy("id", "DESC"); } queryBuilder.take(takeCount); const result = await queryBuilder.getMany(); if (reversed) result.reverse(); if (result.length === 0) return { result: [], hasSmallerId: false, hasLargerId: false }; const largestId = result[0].id; const smallestId = result[result.length - 1].id; const [hasSmallerId, hasLargerId] = await Promise.all([ queryBuilderWithoutPagination.clone().andWhere("id < :smallestId", { smallestId }).take(1).getCount(), queryBuilderWithoutPagination.clone().andWhere("id > :largestId", { largestId }).take(1).getCount() ]); return { result, hasSmallerId: !!hasSmallerId, hasLargerId: !!hasLargerId }; } /** * @param problem Should be locked by `ProblemService.lockProblemById(id, "Read")`. */ async createSubmission( submitter: UserEntity, problem: ProblemEntity, content: SubmissionContent, uploadInfo: FileUploadInfoDto ): Promise< [ errors: ValidationError[], fileUploadErrorOrRequest: | "FILE_UUID_EXISTS" | "FILE_NOT_UPLOADED" | "FILE_TOO_LARGE" | SignedFileUploadRequestDto, submission: SubmissionEntity ] > { const problemTypeService = this.problemTypeFactoryService.type(problem.type); const validationError = await problemTypeService.validateSubmissionContent(content); if (validationError && validationError.length > 0) return [validationError, null, null]; const [fileUploadErrorOrRequest, submission] = await this.connection.transaction< [ fileUploadErrorOrRequest: | "FILE_UUID_EXISTS" | "FILE_NOT_UPLOADED" | "FILE_TOO_LARGE" | SignedFileUploadRequestDto, submission: SubmissionEntity ] >("READ COMMITTED", async transactionalEntityManager => { let file: FileEntity = null; if (problemTypeService.shouldUploadAnswerFile()) { const result = await this.fileService.processUploadRequest( uploadInfo, size => (size <= this.configService.config.resourceLimit.submissionFileSize ? null : "FILE_TOO_LARGE"), transactionalEntityManager ); if (result instanceof FileEntity) file = result; else return [result, null]; } // eslint-disable-next-line @typescript-eslint/no-shadow const submission = new SubmissionEntity(); submission.isPublic = problem.isPublic; const pair = await problemTypeService.getCodeLanguageAndAnswerSizeFromSubmissionContentAndFile(content, file); submission.codeLanguage = pair.language; submission.answerSize = pair.answerSize; submission.score = null; submission.status = SubmissionStatus.Pending; submission.submitTime = new Date(); submission.problemId = problem.id; submission.submitterId = submitter.id; await transactionalEntityManager.save(submission); const submissionDetail = new SubmissionDetailEntity(); submissionDetail.submissionId = submission.id; submissionDetail.content = content; submissionDetail.fileUuid = uploadInfo?.uuid; submissionDetail.result = null; await transactionalEntityManager.save(submissionDetail); return [null, submission]; }); if (submission) { await this.problemService.updateProblemStatistics(problem.id, 1, 0); await this.userService.updateUserSubmissionCount(submitter.id, 1); try { await this.judgeSubmission(submission); } catch (e) { logger.error(`Failed to start judge for submission ${submission.id}: ${e}`); } return [null, null, submission]; } return [null, fileUploadErrorOrRequest, null]; } async getSubmissionBasicMeta(submission: SubmissionEntity): Promise<SubmissionBasicMetaDto> { return { id: submission.id, isPublic: submission.isPublic, codeLanguage: submission.codeLanguage, answerSize: submission.answerSize, score: submission.score, status: submission.status, submitTime: submission.submitTime, timeUsed: submission.timeUsed, memoryUsed: submission.memoryUsed }; } async getSubmissionDetail(submission: SubmissionEntity): Promise<SubmissionDetailEntity> { return await this.submissionDetailRepository.findOne({ submissionId: submission.id }); } async getUserRecentlySubmissionCountPerDay( user: UserEntity, days: number, timezone: string, now: string ): Promise<number[]> { if (!moment.tz.zone(timezone)) timezone = "UTC"; const startDate = moment(now) .tz(timezone) .startOf("day") .subtract(days - 1, "day"); const localTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone; const getConvertTimezoneExpression = (valueToBeConverted: string) => timezone === localTimezone ? valueToBeConverted : `CONVERT_TZ(${valueToBeConverted}, :localTimezone, :timezone)`; const queryResult: { submitDate: Date; count: string }[] = await this.submissionRepository .createQueryBuilder() .select(`DATE(${getConvertTimezoneExpression("submitTime")})`, "submitDate") .addSelect("COUNT(*)", "count") .where("submitterId = :submitterId", { submitterId: user.id }) .andWhere(`submitTime >= DATE_SUB(${getConvertTimezoneExpression(":now")}, INTERVAL :offsetDays DAY)`, { now, offsetDays: days - 1 }) .groupBy("submitDate") .setParameters({ localTimezone, timezone }) .getRawMany(); // The database doesn't support timezone if (queryResult.length === 1 && queryResult[0].submitDate === null) return new Array(days).fill(0); const map = new Map( queryResult.map(row => [ // Get the timestemp of result datetime // 1. Get the date string of result datetime // 2. Get the moment() object in requested timezone of the date // 3. Get its timestamp moment.tz(moment(row.submitDate).format("YYYY-MM-DD"), timezone).valueOf(), Number(row.count) ]) ); const result = [...new Array(days).keys()].map(i => map.get(startDate.clone().add(i, "day").valueOf()) || 0); return result; } /** * @param submission Must be locked (or just created, ID not exposed to user). */ async judgeSubmission(submission: SubmissionEntity, isRejudge?: boolean): Promise<void> { const oldSubmission = { ...submission }; if (submission.taskId) { this.judgeGateway.cancelTask(submission.taskId); } submission.taskId = uuid(); submission.score = null; submission.status = SubmissionStatus.Pending; submission.timeUsed = null; submission.memoryUsed = null; await this.submissionRepository.save(submission); const [ userPendingCount, userOccupiedTimeRecently, avgEveryUsersOccupiedTimeRecently, stdEveryUsersOccupiedTimeRecently ] = await (async () => { // For performance reasons, dynamic task priority could be disabled to reduce database stress if (!this.configService.config.preference.serverSideOnly.dynamicTaskPriority) return [0, 0, 0, 0]; // If we are rejudging some submission, don't consider the user's influence to judge queue for priority if (isRejudge) return [0, 0, 0, 0]; const selectTotalOccupiedTimeRecently = (qb: QueryBuilder<SubmissionEntity>) => qb.select("SUM(totalOccupiedTime)", "total").andWhere("submitTime >= NOW() - INTERVAL 15 MINUTE"); // eslint-disable-next-line @typescript-eslint/no-shadow const [userPendingCount, userOccupiedTimeRecently, avgAndStdEveryUsersOccupiedTimeRecently] = await Promise.all([ // userPendingCount this.submissionRepository.count({ status: SubmissionStatus.Pending, submitterId: submission.submitterId }), // userOccupiedTimeRecently selectTotalOccupiedTimeRecently(this.submissionRepository.createQueryBuilder()) .where({ submitterId: submission.submitterId }) .getRawOne<{ total: number }>() .then(result => result.total), // avgAndStdEveryUsersOccupiedTimeRecently this.connection .createQueryBuilder() .select("AVG(total)", "avg") .addSelect("STD(total)", "std") .from( qb => selectTotalOccupiedTimeRecently(qb.select().from(SubmissionEntity, "submission")).groupBy( "submission.submitterId" ), "totalResult" ) .getRawOne<{ avg: number; std: number }>() ]); return [ userPendingCount, userOccupiedTimeRecently, avgAndStdEveryUsersOccupiedTimeRecently.avg, avgAndStdEveryUsersOccupiedTimeRecently.std ]; })(); await this.judgeQueueService.pushTask( submission.taskId, JudgeTaskType.Submission, makeSubmissionPriority( submission.id, userPendingCount, userOccupiedTimeRecently, avgEveryUsersOccupiedTimeRecently, stdEveryUsersOccupiedTimeRecently, isRejudge ? JudgeTaskPriorityType.Medium : JudgeTaskPriorityType.High ) ); await this.onSubmissionUpdated(oldSubmission, submission); } async rejudgeSubmission(submission: SubmissionEntity): Promise<void> { // eslint-disable-next-line @typescript-eslint/no-shadow await this.lockSubmission(submission, true, async submission => { if (!submission) return; await this.judgeSubmission(submission, true); const submissionDetail = await this.getSubmissionDetail(submission); submissionDetail.result = null; await this.submissionDetailRepository.save(submissionDetail); }); } async cancelSubmission(submission: SubmissionEntity): Promise<void> { // eslint-disable-next-line @typescript-eslint/no-shadow const canceled = await this.lockSubmission(submission, true, async submission => { if (!submission || !submission.taskId) return false; this.judgeGateway.cancelTask(submission.taskId); const oldSubmission = { ...submission }; submission.taskId = null; submission.score = null; submission.status = SubmissionStatus.Canceled; submission.timeUsed = null; submission.memoryUsed = null; const submissionDetail = await this.getSubmissionDetail(submission); submissionDetail.result = null; await this.connection.transaction("READ COMMITTED", async transactionalEntityManager => { await transactionalEntityManager.save(submission); await transactionalEntityManager.save(submissionDetail); }); await this.onSubmissionUpdated(oldSubmission, submission); return true; }); if (!canceled) return; await this.submissionProgressService.emitSubmissionEvent(submission.id, SubmissionEventType.Canceled); } async setSubmissionPublic(submission: SubmissionEntity, isPublic: boolean): Promise<void> { submission.isPublic = isPublic; await this.submissionRepository.save(submission); } async deleteSubmission(submission: SubmissionEntity): Promise<void> { // This function updates related info, lock the problem for Read first, then lock the submission let deleteFileActually: () => void = null; // eslint-disable-next-line @typescript-eslint/no-shadow await this.lockSubmission(submission, true, async submission => { if (!submission) return; if (submission.taskId) { this.judgeGateway.cancelTask(submission.taskId); await this.submissionProgressService.emitSubmissionEvent(submission.id, SubmissionEventType.Deleted); } await this.connection.transaction("READ COMMITTED", async transactionalEntityManager => { const submissionDetail = await this.getSubmissionDetail(submission); if (submissionDetail.fileUuid) deleteFileActually = await this.fileService.deleteFile(submissionDetail.fileUuid, transactionalEntityManager); await transactionalEntityManager.remove(submission); }); await this.submissionStatisticsService.onSubmissionUpdated(submission, null); if (submission.status === SubmissionStatus.Accepted) { await this.problemService.updateProblemStatistics(submission.problemId, -1, -1); await this.userService.updateUserAcceptedCount(submission.submitterId, submission.problemId, "AC_TO_NON_AC"); } else { await this.problemService.updateProblemStatistics(submission.problemId, -1, 0); } }); if (deleteFileActually) deleteFileActually(); } /** * This function updates related info, the problem must be locked for Read first, then the submission must be locked. */ private async onSubmissionUpdated(oldSubmission: SubmissionEntity, submission: SubmissionEntity): Promise<void> { await this.submissionStatisticsService.onSubmissionUpdated(oldSubmission, submission); const oldAccepted = oldSubmission.status === SubmissionStatus.Accepted; const newAccepted = submission.status === SubmissionStatus.Accepted; if (!oldAccepted && newAccepted) { await this.problemService.updateProblemStatistics(submission.problemId, 0, 1); await this.userService.updateUserAcceptedCount(submission.submitterId, submission.problemId, "NON_AC_TO_AC"); } else if (oldAccepted && !newAccepted) { await this.problemService.updateProblemStatistics(submission.problemId, 0, -1); await this.userService.updateUserAcceptedCount(submission.submitterId, submission.problemId, "AC_TO_NON_AC"); } } /** * This function updates related info, the problem must be locked for Read first, then the submission must be locked. */ private async onSubmissionFinished( submission: SubmissionEntity, problem: ProblemEntity, progress: SubmissionProgress ): Promise<void> { const oldSubmission = { ...submission }; const submissionDetail = await this.getSubmissionDetail(submission); submissionDetail.result = progress; submission.taskId = null; submission.status = progress.status; submission.score = progress.score; submission.totalOccupiedTime = progress.totalOccupiedTime; const timeAndMemory = this.problemTypeFactoryService .type(problem.type) .getTimeAndMemoryUsedFromFinishedSubmissionProgress(submissionDetail.result); submission.timeUsed = timeAndMemory.timeUsed; submission.memoryUsed = timeAndMemory.memoryUsed; await this.connection.transaction(async transactionalEntityManager => { await transactionalEntityManager.save(submission); await transactionalEntityManager.save(submissionDetail); }); logger.log(`Submission ${submission.id} finished with status ${submission.status}`); await this.onSubmissionUpdated(oldSubmission, submission); } /** * @return `false` means the task is canceled. */ async onTaskProgress(taskId: string, progress: SubmissionProgress): Promise<boolean> { const submission = await this.findSubmissionByTaskId(taskId); if (!submission) { logger.warn(`Invalid task Id ${taskId} of task progress, maybe there's a too-early rejudge?`); return false; } const finished = progress.progressType === SubmissionProgressType.Finished; // Don't lock the problem if not finished since we don't modify the database. // eslint-disable-next-line @typescript-eslint/no-shadow await this.lockSubmission(submission, finished, async (submission, problem?) => { if (!submission || submission.taskId !== taskId) { logger.warn(`Invalid task Id ${taskId} of task progress, maybe there's a too-early rejudge?`); } // First update database, then report progress if (finished) { await this.onSubmissionFinished(submission, problem, progress); } await this.submissionProgressService.emitSubmissionEvent(submission.id, SubmissionEventType.Progress, progress); }); return true; } async getTaskToBeSentToJudgeByTaskId(taskId: string, priotity: number): Promise<JudgeTask<SubmissionTaskExtraInfo>> { try { const submission = await this.findSubmissionByTaskId(taskId); if (!submission) return null; const submissionDetail = await this.getSubmissionDetail(submission); const problem = await this.problemService.findProblemById(submission.problemId); const [preprocessedJudgeInfo] = await this.problemService.getProblemPreprocessedJudgeInfo(problem); const testData = await this.problemService.getProblemFiles(problem, ProblemFileType.TestData); const problemTypeService = this.problemTypeFactoryService.type(problem.type); return new JudgeTask<SubmissionTaskExtraInfo>( submission.taskId, JudgeTaskType.Submission, JudgeTaskPriorityType.High, priotity, { problemType: problem.type, judgeInfo: preprocessedJudgeInfo, samples: // eslint-disable-next-line @typescript-eslint/no-explicit-any preprocessedJudgeInfo && (preprocessedJudgeInfo as any).runSamples ? (await this.problemService.getProblemSamples(problem)).slice( 0, this.configService.config.resourceLimit.problemSamplesToRun ) : null, testData: Object.fromEntries(testData.map(problemFile => [problemFile.filename, problemFile.uuid])), submissionContent: submissionDetail.content, file: problemTypeService.shouldUploadAnswerFile() ? { uuid: submissionDetail.fileUuid, url: problemTypeService.shouldUploadAnswerFile() ? await this.fileService.signDownloadLink({ uuid: submissionDetail.fileUuid, downloadFilename: null, noExpire: true, useAlternativeEndpointFor: AlternativeUrlFor.Judge }) : null } : null } ); } catch (e) { logger.error(`Error in getTaskById("${taskId}"): ${e}`); return null; } } /** * Lock a submission and its problem (optionally). Ensure the submission's `taskId` is not changed and its problem exists. */ async lockSubmission<T>( submission: SubmissionEntity, lockProblem: boolean, callback: (submission: SubmissionEntity, problem?: ProblemEntity) => Promise<T> ): Promise<T> { if (lockProblem) { return await this.problemService.lockProblemById(submission.problemId, "Read", async problem => { if (!problem) return await callback(null); return await this.lockService.lock( `Submission_${submission.id}`, async () => await callback(await this.findSubmissionById(submission.id), problem) ); }); } return await this.lockService.lock( `Submission_${submission.id}`, async () => await callback(await this.findSubmissionById(submission.id)) ); } async getUserProblemAcceptedSubmissionCount(userId: number, problemId: number): Promise<number> { return await this.submissionRepository.count({ submitterId: userId, problemId, status: SubmissionStatus.Accepted }); } async getUserLatestSubmissionByProblems( user: UserEntity, problems: ProblemEntity[], acceptedOnly?: boolean ): Promise<Map<number, SubmissionEntity>> { if (problems.length === 0) return new Map(); const queryBuilder = this.submissionRepository .createQueryBuilder() .select("MAX(id)", "id") .where("submitterId = :submitterId", { submitterId: user.id }) .andWhere("problemId IN (:...problemIds)", { problemIds: problems.map(problem => problem.id) }) .groupBy("problemId"); const queryResult: { id: string }[] = await (acceptedOnly ? queryBuilder.andWhere("status = :status", { status: SubmissionStatus.Accepted }) : queryBuilder.andWhere("status != :status", { status: SubmissionStatus.Pending }) ).getRawMany(); const submissionIds = queryResult.map(result => Number(result.id)); const submissions = await this.findSubmissionsByExistingIds(submissionIds); return new Map(submissions.map(submission => [submission.problemId, submission])); } async problemHasAnySubmission(problem: ProblemEntity): Promise<boolean> { return ( (await this.submissionRepository.count({ problemId: problem.id })) !== 0 ); } /** * Cancel pending submissions when a problem is deleted. */ async onDeleteProblem(problemId: number): Promise<void> { const pendingSubmissions = await this.submissionRepository .createQueryBuilder() .select() .where("problemId = :problemId", { problemId }) .andWhere("taskId IS NOT NULL") .getMany(); await Promise.all( pendingSubmissions.map(async submission => { this.judgeGateway.cancelTask(submission.taskId); await this.submissionProgressService.emitSubmissionEvent(submission.id, SubmissionEventType.Deleted); }) ); } /** * Do some cleanups AFTER a problem is deleted. */ async onProblemDeleted(problemId: number): Promise<void> { await this.submissionStatisticsService.onProblemDeleted(problemId); } }
the_stack
import { ethers } from 'hardhat' import { evmWordToAddress, getLogs, publicAbi } from '../test-helpers/helpers' import { assert, expect } from 'chai' import { BigNumber, Contract, ContractFactory, ContractTransaction, } from 'ethers' import { Personas, getUsers } from '../test-helpers/setup' import { evmRevert } from '../test-helpers/matchers' let personas: Personas let validatorFactory: ContractFactory let acFactory: ContractFactory let flagsFactory: ContractFactory let aggregatorFactory: ContractFactory let compoundOracleFactory: ContractFactory before(async () => { personas = (await getUsers()).personas validatorFactory = await ethers.getContractFactory( 'src/v0.7/dev/CompoundPriceFlaggingValidator.sol:CompoundPriceFlaggingValidator', personas.Carol, ) acFactory = await ethers.getContractFactory( 'src/v0.6/SimpleWriteAccessController.sol:SimpleWriteAccessController', personas.Carol, ) flagsFactory = await ethers.getContractFactory( 'src/v0.6/Flags.sol:Flags', personas.Carol, ) aggregatorFactory = await ethers.getContractFactory( 'src/v0.7/tests/MockV3Aggregator.sol:MockV3Aggregator', personas.Carol, ) compoundOracleFactory = await ethers.getContractFactory( 'src/v0.7/tests/MockCompoundOracle.sol:MockCompoundOracle', personas.Carol, ) }) describe('CompoundPriceFlaggingVlidator', () => { let validator: Contract let aggregator: Contract let compoundOracle: Contract let flags: Contract let ac: Contract const aggregatorDecimals = 18 // 1000 const initialAggregatorPrice = BigNumber.from('1000000000000000000000') const compoundSymbol = 'ETH' const compoundDecimals = 6 // 1100 (10% deviation from aggregator price) const initialCompoundPrice = BigNumber.from('1100000000') // (50,000,000 / 1,000,000,000) = 0.05 = 5% deviation threshold const initialDeviationNumerator = 50_000_000 beforeEach(async () => { ac = await acFactory.connect(personas.Carol).deploy() flags = await flagsFactory.connect(personas.Carol).deploy(ac.address) aggregator = await aggregatorFactory .connect(personas.Carol) .deploy(aggregatorDecimals, initialAggregatorPrice) compoundOracle = await compoundOracleFactory .connect(personas.Carol) .deploy() await compoundOracle.setPrice( compoundSymbol, initialCompoundPrice, compoundDecimals, ) validator = await validatorFactory .connect(personas.Carol) .deploy(flags.address, compoundOracle.address) await validator .connect(personas.Carol) .setFeedDetails( aggregator.address, compoundSymbol, compoundDecimals, initialDeviationNumerator, ) await ac.connect(personas.Carol).addAccess(validator.address) }) it('has a limited public interface [ @skip-coverage ]', () => { publicAbi(validator, [ 'update', 'check', 'setFeedDetails', 'setFlagsAddress', 'setCompoundOpenOracleAddress', 'getFeedDetails', 'flags', 'compoundOpenOracle', // Upkeep methods: 'checkUpkeep', 'performUpkeep', // Owned methods: 'acceptOwnership', 'owner', 'transferOwnership', ]) }) describe('#constructor', () => { it('sets the owner', async () => { assert.equal(await validator.owner(), await personas.Carol.getAddress()) }) it('sets the arguments passed in', async () => { assert.equal(await validator.flags(), flags.address) assert.equal(await validator.compoundOpenOracle(), compoundOracle.address) }) }) describe('#setOpenOracleAddress', () => { let newCompoundOracle: Contract let tx: ContractTransaction beforeEach(async () => { newCompoundOracle = await compoundOracleFactory .connect(personas.Carol) .deploy() tx = await validator .connect(personas.Carol) .setCompoundOpenOracleAddress(newCompoundOracle.address) }) it('changes the compound oracke address', async () => { assert.equal( await validator.compoundOpenOracle(), newCompoundOracle.address, ) }) it('emits a log event', async () => { await expect(tx) .to.emit(validator, 'CompoundOpenOracleAddressUpdated') .withArgs(compoundOracle.address, newCompoundOracle.address) }) describe('when called by a non-owner', () => { it('reverts', async () => { await evmRevert( validator .connect(personas.Neil) .setCompoundOpenOracleAddress(newCompoundOracle.address), 'Only callable by owner', ) }) }) }) describe('#setFlagsAddress', () => { let newFlagsContract: Contract let tx: ContractTransaction beforeEach(async () => { newFlagsContract = await flagsFactory .connect(personas.Carol) .deploy(ac.address) tx = await validator .connect(personas.Carol) .setFlagsAddress(newFlagsContract.address) }) it('changes the flags address', async () => { assert.equal(await validator.flags(), newFlagsContract.address) }) it('emits a log event', async () => { await expect(tx) .to.emit(validator, 'FlagsAddressUpdated') .withArgs(flags.address, newFlagsContract.address) }) describe('when called by a non-owner', () => { it('reverts', async () => { await evmRevert( validator .connect(personas.Neil) .setFlagsAddress(newFlagsContract.address), 'Only callable by owner', ) }) }) }) describe('#setFeedDetails', () => { let mockAggregator: Contract let tx: ContractTransaction const symbol = 'BTC' const decimals = 8 const deviationNumerator = 50_000_000 // 5% beforeEach(async () => { await compoundOracle.connect(personas.Carol).setPrice('BTC', 1500000, 2) mockAggregator = await aggregatorFactory .connect(personas.Carol) .deploy(decimals, 4000000000000) tx = await validator .connect(personas.Carol) .setFeedDetails( mockAggregator.address, symbol, decimals, deviationNumerator, ) }) it('sets the correct state', async () => { const response = await validator .connect(personas.Carol) .getFeedDetails(mockAggregator.address) assert.equal(response[0], symbol) assert.equal(response[1], decimals) assert.equal(response[2].toString(), deviationNumerator.toString()) }) it('uses the existing symbol if one already exists', async () => { const newSymbol = 'LINK' await compoundOracle .connect(personas.Carol) .setPrice(newSymbol, 1500000, 2) tx = await validator .connect(personas.Carol) .setFeedDetails( mockAggregator.address, newSymbol, decimals, deviationNumerator, ) // Check the event await expect(tx) .to.emit(validator, 'FeedDetailsSet') .withArgs(mockAggregator.address, symbol, decimals, deviationNumerator) // Check the state const response = await validator .connect(personas.Carol) .getFeedDetails(mockAggregator.address) assert.equal(response[0], symbol) }) it('emits an event', async () => { await expect(tx) .to.emit(validator, 'FeedDetailsSet') .withArgs(mockAggregator.address, symbol, decimals, deviationNumerator) }) it('fails when given a 0 numerator', async () => { await evmRevert( validator .connect(personas.Carol) .setFeedDetails(mockAggregator.address, symbol, decimals, 0), 'Invalid threshold numerator', ) }) it('fails when given a numerator above 1 billion', async () => { await evmRevert( validator .connect(personas.Carol) .setFeedDetails( mockAggregator.address, symbol, decimals, 1_200_000_000, ), 'Invalid threshold numerator', ) }) it('fails when the compound price is invalid', async () => { await evmRevert( validator .connect(personas.Carol) .setFeedDetails( mockAggregator.address, 'TEST', decimals, deviationNumerator, ), 'Invalid Compound price', ) }) describe('when called by a non-owner', () => { it('reverts', async () => { await evmRevert( validator .connect(personas.Neil) .setFeedDetails( mockAggregator.address, symbol, decimals, deviationNumerator, ), 'Only callable by owner', ) }) }) }) describe('#check', () => { describe('with a single aggregator', () => { describe('with a deviated price exceding threshold', () => { it('returns the deviated aggregator', async () => { const aggregators = [aggregator.address] const response = await validator.check(aggregators) assert.equal(response.length, 1) assert.equal(response[0], aggregator.address) }) }) describe('with a price within the threshold', () => { const newCompoundPrice = BigNumber.from('1000000000') beforeEach(async () => { await compoundOracle.setPrice( 'ETH', newCompoundPrice, compoundDecimals, ) }) it('returns an empty array', async () => { const aggregators = [aggregator.address] const response = await validator.check(aggregators) assert.equal(response.length, 0) }) }) }) }) describe('#update', () => { describe('with a single aggregator', () => { describe('with a deviated price exceding threshold', () => { it('raises a flag on the flags contract', async () => { const aggregators = [aggregator.address] const tx = await validator.connect(personas.Carol).update(aggregators) const logs = await getLogs(tx) assert.equal(logs.length, 1) assert.equal(evmWordToAddress(logs[0].topics[1]), aggregator.address) }) }) describe('with a price within the threshold', () => { const newCompoundPrice = BigNumber.from('1000000000') beforeEach(async () => { await compoundOracle.setPrice( 'ETH', newCompoundPrice, compoundDecimals, ) }) it('does nothing', async () => { const aggregators = [aggregator.address] const tx = await validator.connect(personas.Carol).update(aggregators) const logs = await getLogs(tx) assert.equal(logs.length, 0) }) }) }) }) describe('#checkUpkeep', () => { describe('with a single aggregator', () => { describe('with a deviated price exceding threshold', () => { it('returns the deviated aggregator', async () => { const aggregators = [aggregator.address] const encodedAggregators = ethers.utils.defaultAbiCoder.encode( ['address[]'], [aggregators], ) const response = await validator .connect(personas.Carol) .checkUpkeep(encodedAggregators) const decodedResponse = ethers.utils.defaultAbiCoder.decode( ['address[]'], response?.[1], ) assert.equal(decodedResponse?.[0]?.[0], aggregators[0]) }) }) describe('with a price within the threshold', () => { const newCompoundPrice = BigNumber.from('1000000000') beforeEach(async () => { await compoundOracle.setPrice( 'ETH', newCompoundPrice, compoundDecimals, ) }) it('returns an empty array', async () => { const aggregators = [aggregator.address] const encodedAggregators = ethers.utils.defaultAbiCoder.encode( ['address[]'], [aggregators], ) const response = await validator .connect(personas.Carol) .checkUpkeep(encodedAggregators) const decodedResponse = ethers.utils.defaultAbiCoder.decode( ['address[]'], response?.[1], ) assert.equal(decodedResponse?.[0]?.length, 0) }) }) }) }) describe('#performUpkeep', () => { describe('with a single aggregator', () => { describe('with a deviated price exceding threshold', () => { it('raises a flag on the flags contract', async () => { const aggregators = [aggregator.address] const encodedAggregators = ethers.utils.defaultAbiCoder.encode( ['address[]'], [aggregators], ) const tx = await validator .connect(personas.Carol) .performUpkeep(encodedAggregators) const logs = await getLogs(tx) assert.equal(logs.length, 1) assert.equal(evmWordToAddress(logs[0].topics[1]), aggregator.address) }) }) describe('with a price within the threshold', () => { const newCompoundPrice = BigNumber.from('1000000000') beforeEach(async () => { await compoundOracle.setPrice( 'ETH', newCompoundPrice, compoundDecimals, ) }) it('does nothing', async () => { const aggregators = [aggregator.address] const encodedAggregators = ethers.utils.defaultAbiCoder.encode( ['address[]'], [aggregators], ) const tx = await validator .connect(personas.Carol) .performUpkeep(encodedAggregators) const logs = await getLogs(tx) assert.equal(logs.length, 0) }) }) }) }) })
the_stack
import React, { useRef, useState } from 'react'; import { Button } from '../button/Button'; import { TextArea } from '../textarea/TextArea'; import { TextInput } from '../textInput/TextInput'; import { Dialog } from './Dialog'; import { IconAlertCircle, IconInfoCircle, IconPlusCircle, IconTrash } from '../../icons'; export default { component: Dialog, title: 'Components/Dialog', parameters: { controls: { expanded: true }, loki: { skip: true }, }, args: { id: 'example-dialog', }, }; export const Default = (args) => { const openButtonRef = useRef(null); const [open, setOpen] = useState<boolean>(false); const close = () => setOpen(false); const titleId = 'custom-dialog-title'; const descriptionId = 'custom-dialog-content'; return ( <> <Button ref={openButtonRef} onClick={() => setOpen(true)}> Open Dialog </Button> <Dialog id={args.id} aria-labelledby={titleId} aria-describedby={descriptionId} isOpen={open} focusAfterCloseRef={openButtonRef} close={close} closeButtonLabelText="Close" > <Dialog.Header id={titleId} title="Add new item" iconLeft={<IconPlusCircle aria-hidden="true" />} /> <Dialog.Content> <p id={descriptionId} className="text-body"> Add a new item by filling the information below. All fields are mandatory. </p> <TextInput id="item-name" label="Item name" placeholder="E.g. Item 1" helperText="Item's name must be unique." required /> <br /> <TextArea id="item-description" label="Item description" placeholder="E.g. Item 1 is the first item of the system." required /> </Dialog.Content> <Dialog.ActionButtons> <Button onClick={() => { // Add operations here close(); }} > Add item </Button> <Button onClick={close} variant="secondary"> Cancel </Button> </Dialog.ActionButtons> </Dialog> </> ); }; // This dialog story is part of Loki's visual regression tests. It is open by default, and it is not part of the Storybooks' docs section. export const Confirmation = (args) => { const dialogTargetElement = document.getElementById('root'); // Because of the story regression tests, we need to render the dialog into the root element const openConfirmationButtonRef = useRef(null); const [open, setOpen] = useState<boolean>(true); const close = () => setOpen(false); const titleId = 'confirmation-dialog-title'; const descriptionId = 'confirmation-dialog-description'; return ( <> <Button ref={openConfirmationButtonRef} onClick={() => setOpen(true)}> Open Confirmation Dialog </Button> <Dialog id={args.id} aria-labelledby={titleId} aria-describedby={descriptionId} isOpen={open} focusAfterCloseRef={openConfirmationButtonRef} targetElement={dialogTargetElement} > <Dialog.Header id={titleId} title="Confirm dialog" iconLeft={<IconAlertCircle aria-hidden="true" />} /> <Dialog.Content> <p id={descriptionId} className="text-body"> Are you sure you want to continue? </p> </Dialog.Content> <Dialog.ActionButtons> <Button onClick={() => { // Add confirm operations here close(); }} > Confirm </Button> <Button onClick={close} variant="secondary"> Cancel </Button> </Dialog.ActionButtons> </Dialog> </> ); }; Confirmation.storyName = 'Confirmation'; Confirmation.args = { id: 'confirmation-dialog', }; Confirmation.parameters = { previewTabs: { 'storybook/docs/panel': { hidden: true, }, }, docs: { disable: true, }, }; // This dialog story is part of Loki's visual regression tests. It is open by default, and it is not part of the Storybooks' docs section. export const Danger = (args) => { const dialogTargetElement = document.getElementById('root'); // Because of the story regression tests, we need to render the dialog into the root element const openDangerButtonRef = useRef(null); const [open, setOpen] = useState<boolean>(true); const close = () => setOpen(false); const titleId = 'danger-dialog-title'; const descriptionId = 'danger-dialog-description'; return ( <> <Button variant="danger" ref={openDangerButtonRef} onClick={() => setOpen(true)}> Open Danger Dialog </Button> <Dialog variant="danger" id={args.id} aria-labelledby={titleId} aria-describedby={descriptionId} isOpen={open} focusAfterCloseRef={openDangerButtonRef} targetElement={dialogTargetElement} > <Dialog.Header id={titleId} title="Delete item" iconLeft={<IconAlertCircle aria-hidden="true" />} /> <Dialog.Content> <p id={descriptionId} className="text-body"> Are you sure you want to delete the item? </p> </Dialog.Content> <Dialog.ActionButtons> <Button theme="black" variant="secondary" onClick={close}> Cancel </Button> <Button variant="danger" iconLeft={<IconTrash aria-hidden="true" />} onClick={() => { // Add confirm operations here close(); }} > Delete </Button> </Dialog.ActionButtons> </Dialog> </> ); }; Danger.storyName = 'Danger'; Danger.args = { id: 'danger-dialog', }; Danger.parameters = { previewTabs: { 'storybook/docs/panel': { hidden: true, }, }, docs: { disable: true, }, }; // This dialog story is part of Loki's visual regression tests. It is open by default, and it is not part of the Storybooks' docs section. export const ScrollableConfirmation = (args) => { const dialogTargetElement = document.getElementById('root'); // Because of the story regression tests, we need to render the dialog into the root element const openScrollableConfirmationButtonRef = useRef(null); const [open, setOpen] = useState<boolean>(true); const close = () => setOpen(false); const titleId = 'confirmation-scrollable-title'; const descriptionId = 'confirmation-scrollable-description'; return ( <> <Button ref={openScrollableConfirmationButtonRef} onClick={() => setOpen(true)}> Open Scrollable Confirmation Dialog </Button> <Dialog id={args.id} style={{ width: '800px' }} aria-labelledby={titleId} aria-describedby={descriptionId} isOpen={open} focusAfterCloseRef={openScrollableConfirmationButtonRef} targetElement={dialogTargetElement} scrollable > <Dialog.Header id={titleId} title="Confirm dialog" iconLeft={<IconAlertCircle aria-hidden="true" />} /> <Dialog.Content> <h3 id={descriptionId}>Are you sure you want to continue?</h3> <p className="text-body"> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </p> <p className="text-body"> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </p> <p className="text-body"> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </p> <p className="text-body"> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </p> <p> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </p> <p> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </p> </Dialog.Content> <Dialog.ActionButtons> <Button onClick={() => { // Add confirm operations here close(); }} > Confirm </Button> <Button onClick={close} variant="secondary"> Cancel </Button> </Dialog.ActionButtons> </Dialog> </> ); }; ScrollableConfirmation.storyName = 'Scrollable confirmation'; ScrollableConfirmation.args = { id: 'confirmation-scrollable-dialog', }; ScrollableConfirmation.parameters = { previewTabs: { 'storybook/docs/panel': { hidden: true, }, }, docs: { disable: true, }, }; // This dialog story is not part of the Storybooks' docs section. export const ConfirmationWithTerms = (args) => { const openConfirmationButtonRef = useRef(null); const [open, setOpen] = useState<boolean>(false); const [termsOpen, setTermsOpen] = useState<boolean>(false); const close = () => setOpen(false); const openTermsButtonRef = useRef(null); const closeTerms = () => setTermsOpen(false); const openTermsDialog = () => setTermsOpen(true); const confirmationTitleId = 'confirmation-title'; const confirmationDescriptionId = 'confirmation-description'; const termsTitleId = 'terms-title'; const termsDescriptionId = 'terms-description'; return ( <> <Button ref={openConfirmationButtonRef} onClick={() => setOpen(true)}> Open Accept Terms Dialog </Button> <Dialog id={args.id} style={{ width: '800px' }} aria-labelledby={confirmationTitleId} aria-describedby={confirmationDescriptionId} isOpen={open} focusAfterCloseRef={openConfirmationButtonRef} > <Dialog.Header id={confirmationTitleId} title="Accept terms dialog" iconLeft={<IconAlertCircle aria-hidden="true" />} /> <Dialog.Content> <p id={confirmationDescriptionId} className="text-body"> Do you want to accept terms of the service? <br /> <br /> <Button variant="secondary" iconLeft={<IconInfoCircle aria-hidden="true" />} ref={openTermsButtonRef} onClick={() => openTermsDialog()} > Open service terms dialog </Button> </p> </Dialog.Content> <Dialog.ActionButtons> <Button onClick={() => { // Add confirm operations here close(); }} > Accept terms </Button> <Button onClick={close} variant="secondary"> Cancel </Button> </Dialog.ActionButtons> </Dialog> <Dialog id={args.termsId} aria-labelledby={termsTitleId} aria-describedby={termsDescriptionId} isOpen={termsOpen} focusAfterCloseRef={openTermsButtonRef} close={closeTerms} closeButtonLabelText="Close terms dialog" > <Dialog.Header id={termsTitleId} title="Service terms" /> <Dialog.Content> <p id={termsDescriptionId} className="text-body"> These are the terms of the service. </p> <p className="text-body"> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </p> </Dialog.Content> <Dialog.ActionButtons> <Button onClick={() => { closeTerms(); }} > Close </Button> </Dialog.ActionButtons> </Dialog> </> ); }; ConfirmationWithTerms.storyName = 'Confirmation dialog with terms dialog'; ConfirmationWithTerms.parameters = { loki: { skip: true }, }; ConfirmationWithTerms.args = { id: 'confirmation-dialog', termsId: 'terms-dialog', }; ConfirmationWithTerms.parameters = { previewTabs: { 'storybook/docs/panel': { hidden: true, }, }, docs: { disable: true, }, };
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_bookingsetupmetadata_Information { interface Tabs { } interface Body { /** Date and time when the record was modified. */ ModifiedOn: DevKit.Controls.DateTime; msdyn_AvailableDurationMinimumPercentage: DevKit.Controls.Integer; /** A unique identifier that links bookings to a scheduling entity. */ msdyn_BookingRelationshipLogicalName: DevKit.Controls.String; /** An option set that is used to group and filter statuses. */ msdyn_BookingStatusFieldLogicalName: DevKit.Controls.String; /** Select whether, when moving open slots to the next day, to leave the old slots and change their status to "Cancel." */ msdyn_CancelBookingsWhenMoving: DevKit.Controls.Boolean; /** The default booking canceled status to use when a user can't select a status. */ msdyn_DefaultBookingCanceledStatus: DevKit.Controls.Lookup; /** The default booking committed status to use when a user can't select a status. */ msdyn_DefaultBookingCommittedStatus: DevKit.Controls.Lookup; /** The default booking duration to use when a duration is not provided. */ msdyn_DefaultBookingDuration: DevKit.Controls.Integer; /** The default requirement active status to use when a user can't select a status */ msdyn_DefaultRequirementActiveStatus: DevKit.Controls.Lookup; /** The default requirement canceled status to use when a user can't select a status. */ msdyn_DefaultRequirementCanceledStatus: DevKit.Controls.Lookup; /** The default requirement completed status to use when a user can't select a status. */ msdyn_DefaultRequirementCompletedStatus: DevKit.Controls.Lookup; msdyn_DisableRequirementAutoCreation: DevKit.Controls.Boolean; /** If yes, the book button on schedulable entities will launch the quick book experience. Otherwise, the book button will launch the pop-out scheduler. */ msdyn_enablequickbook: DevKit.Controls.Boolean; /** The name of the custom entity. */ msdyn_EntityLogicalName: DevKit.Controls.String; /** A unique identifier that links requirements to an enabled scheduling entity. */ msdyn_RequirementRelationshipLogicalName: DevKit.Controls.String; /** The maximum number of resources to retrieve and show in schedule assistant. */ msdyn_ResourceAvailabilityRetrievalLimit: DevKit.Controls.Integer; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; WebResource_ScheduleAttributeMapping: DevKit.Controls.WebResource; } } class Formmsdyn_bookingsetupmetadata_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_bookingsetupmetadata_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msdyn_bookingsetupmetadata_Information */ Body: DevKit.Formmsdyn_bookingsetupmetadata_Information.Body; } class msdyn_bookingsetupmetadataApi { /** * DynamicsCrm.DevKit msdyn_bookingsetupmetadataApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; msdyn_AvailableDurationMinimumPercentage: DevKit.WebApi.IntegerValue; /** A unique identifier that links bookings to a scheduling entity. */ msdyn_BookingRelationshipLogicalName: DevKit.WebApi.StringValue; /** A unique identifier for an entity instance. */ msdyn_bookingsetupmetadataId: DevKit.WebApi.GuidValue; /** An option set that is used to group and filter statuses. */ msdyn_BookingStatusFieldLogicalName: DevKit.WebApi.StringValue; /** Select whether, when moving open slots to the next day, to leave the old slots and change their status to "Cancel." */ msdyn_CancelBookingsWhenMoving: DevKit.WebApi.BooleanValue; /** Query for retrieving resource requirements for cloning. */ msdyn_CloneEntityQuery: DevKit.WebApi.LookupValue; /** The default booking canceled status to use when a user can't select a status. */ msdyn_DefaultBookingCanceledStatus: DevKit.WebApi.LookupValue; /** The default booking committed status to use when a user can't select a status. */ msdyn_DefaultBookingCommittedStatus: DevKit.WebApi.LookupValue; /** The default booking duration to use when a duration is not provided. */ msdyn_DefaultBookingDuration: DevKit.WebApi.IntegerValue; /** The default requirement active status to use when a user can't select a status */ msdyn_DefaultRequirementActiveStatus: DevKit.WebApi.LookupValue; /** The default requirement canceled status to use when a user can't select a status. */ msdyn_DefaultRequirementCanceledStatus: DevKit.WebApi.LookupValue; /** The default requirement completed status to use when a user can't select a status. */ msdyn_DefaultRequirementCompletedStatus: DevKit.WebApi.LookupValue; msdyn_DisableRequirementAutoCreation: DevKit.WebApi.BooleanValue; /** If yes, the book button on schedulable entities will launch the quick book experience. Otherwise, the book button will launch the pop-out scheduler. */ msdyn_enablequickbook: DevKit.WebApi.BooleanValue; /** The name of the custom entity. */ msdyn_EntityLogicalName: DevKit.WebApi.StringValue; /** A unique identifier that links requirements to an enabled scheduling entity. */ msdyn_RequirementRelationshipLogicalName: DevKit.WebApi.StringValue; /** The maximum number of resources to retrieve and show in schedule assistant. */ msdyn_ResourceAvailabilityRetrievalLimit: DevKit.WebApi.IntegerValue; msdyn_RetrieveConstraintsQuery: DevKit.WebApi.LookupValue; msdyn_RetrieveResourcesQuery: DevKit.WebApi.LookupValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Status of the Booking Setup Metadata */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Booking Setup Metadata */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_bookingsetupmetadata { enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import yaml=require("yaml-ast-parser") import highlevel=require("./highLevelAST") import {IParseResult} from "../index"; import resolversApi=require("./jsyaml/resolversApi") import path=require("path") import URL=require("url") import util=require("../util/index") import linter=require("./ast.core/linter") let messageRegistry = require("../../resources/errorMessages"); export interface ICompilationUnit{ contents():string path():string absolutePath():string isTopLevel():boolean ast():ILowLevelASTNode; clone():ICompilationUnit; isDirty():boolean; isRAMLUnit():boolean project():IProject; lexerErrors():Error[]; resolve(p:string):ICompilationUnit; resolveAsync(p:string):Promise<ICompilationUnit>; /** * gathers includes over ast without actual resolving of units; */ getIncludeNodes(): { includePath(): string}[] updateContent(newContent:string);//unsafe remove later lineMapper():LineMapper; highLevel():IParseResult; expandedHighLevel():highlevel.IParseResult /** * Returns true if this unit is overlay or extension, false otherwise. */ isOverlayOrExtension() : boolean; /** * Returns master reference if presents, null otherwise. */ getMasterReferenceNode() : ILowLevelASTNode; //ramlVersion():string } export interface IProject{ units():ICompilationUnit[];//returns units with apis in this folder unit(path:string,absolute?:boolean):ICompilationUnit unitAsync(path:string,absolute?:boolean):Promise<ICompilationUnit> lexerErrors():Error[] deleteUnit(n:string); cloneWithResolver(r:any):IProject cloneWithResolver(newResolver:resolversApi.FSResolver,httpResolver?:resolversApi.HTTPResolver):IProject; getRootPath(): string execute(cmd:CompositeCommand) executeTextChange(textCommand:TextChangeCommand);//this may result in broken nodes? addListener(listener:IASTListener); removeListener(listener:IASTListener) addTextChangeListener(listener:ITextChangeCommandListener); removeTextChangeListener(listener:ITextChangeCommandListener); setCachedUnitContent(path:string,content?:string) fsEnabled(): boolean; getMainUnit(): ICompilationUnit; } export interface IASTListener{ (delta:ASTDelta) } export interface ITextChangeCommandListener{ (delta:TextChangeCommand) } export class ASTDelta{ commands:ASTChangeCommand[] } export interface ASTVisitor{ (node:ILowLevelASTNode):boolean } export interface IncludeReference { getFragments(): string[]; getIncludePath(): string; asString(): string; encodedName(): string; } export interface ILowLevelASTNode{ start():number end():number value(toString?:boolean):any hasInnerIncludeError():boolean includeErrors():string[] includePath():string includeReference(): IncludeReference key():string optional():boolean actual(): any children():ILowLevelASTNode[]; parent():ILowLevelASTNode; unit():ICompilationUnit /** * Returns a unit, which is a base for include reference. * This method should be called when a node may potentially hbe defined in several units * at once (in case of expansion) and caller needs a unit, which is a base for this node's * include statement. * * If this node has no include statement, return value of the method should be equal to the result of * unit() method call. */ includeBaseUnit():ICompilationUnit anchorId():string errors():Error[] anchoredFrom():ILowLevelASTNode;//back link in anchorId includedFrom():ILowLevelASTNode;//back link in includepath visit(v:ASTVisitor) addChild(n:ILowLevelASTNode, pos?: number) execute(cmd:CompositeCommand) isAnnotatedScalar():boolean dump():string dumpToObject(full?:boolean):any keyStart():number; keyEnd():number; valueStart():number; valueEnd():number; isValueLocal():boolean; /** * Returns kind of the underlying YAML node */ kind(): yaml.Kind; /** * Returns kind of the value YAML node */ valueKind(): yaml.Kind; /** * Returns value kind for AST with resolved includes and anchors */ resolvedValueKind(): yaml.Kind; /** * For anchor returns kind of anchored node. * For the rest of the nodes returns null. */ anchorValueKind():yaml.Kind; /** * Returns kind of the key YAML node */ keyKind(): yaml.Kind; show(msg: string, lev?: number, text?: string); markup(json?: boolean): string; highLevelParseResult():highlevel.IParseResult setHighLevelParseResult(highLevel:highlevel.IParseResult) highLevelNode():highlevel.IHighLevelNode setHighLevelNode(highLevelParseResult:highlevel.IHighLevelNode) text(unitText: string): string; copy(): ILowLevelASTNode nodeDefinition(): highlevel.INodeDefinition; /** * Indicates that contents of this node are !included */ includesContents() : boolean; containingUnit():ICompilationUnit; } export enum CommandKind{ ADD_CHILD, REMOVE_CHILD, MOVE_CHILD, CHANGE_KEY, CHANGE_VALUE, INIT_RAML_FILE } export class TextChangeCommand{ offset:number; constructor(offset:number, replacementLength:number, text:string, unit:ICompilationUnit, target: ILowLevelASTNode = null) { this.offset = offset; this.replacementLength = replacementLength; this.text = text; this.unit = unit; this.target = target; } replacementLength:number; text:string; unit:ICompilationUnit; target: ILowLevelASTNode; isUndefined: boolean; } export class CompositeCommand{ source:any; timestamp:number; commands:ASTChangeCommand[]=[] } export enum InsertionPointType { NONE, START, END, POINT } export interface InsertionPoint { type:InsertionPointType; point:ILowLevelASTNode; } export class ASTChangeCommand{ constructor(kind:CommandKind, target:ILowLevelASTNode, value:string|ILowLevelASTNode, position:number) { this.kind = kind; this.target = target; this.value = value; this.position = position; } toSeq:boolean=false; insertionPoint:ILowLevelASTNode|InsertionPoint; kind:CommandKind; target:ILowLevelASTNode; value: string|ILowLevelASTNode; position:number;//only relevant for children modification } export function setAttr(t:ILowLevelASTNode,value:string):ASTChangeCommand{ return new ASTChangeCommand(CommandKind.CHANGE_VALUE,t,value,-1) } export function setAttrStructured(t:ILowLevelASTNode,value:highlevel.IStructuredValue):ASTChangeCommand{ return new ASTChangeCommand(CommandKind.CHANGE_VALUE,t,value.lowLevel(),-1) } export function setKey(t:ILowLevelASTNode,value:string):ASTChangeCommand{ return new ASTChangeCommand(CommandKind.CHANGE_KEY,t,value,-1) } export function removeNode(t:ILowLevelASTNode,child:ILowLevelASTNode):ASTChangeCommand{ return new ASTChangeCommand(CommandKind.REMOVE_CHILD,t,child,-1) } export function insertNode(t:ILowLevelASTNode,child:ILowLevelASTNode,insertAfter:ILowLevelASTNode|InsertionPoint=null,toSeq:boolean=false):ASTChangeCommand{ var s= new ASTChangeCommand(CommandKind.ADD_CHILD,t,child,-1); s.insertionPoint=insertAfter; s.toSeq=toSeq; return s; } export function initRamlFile(root:ILowLevelASTNode, newroot:ILowLevelASTNode):ASTChangeCommand{ return new ASTChangeCommand(CommandKind.INIT_RAML_FILE,root,newroot,-1); } export interface ILowLevelEnvironment{ createProject(path:string):IProject } export interface TextPosition{ /** * Line number, starting from one */ line: number /** * Column number, starting from one */ column: number /** * Character index in whole text, starting from zero */ position: number } export interface LineMapper{ position(pos:number):TextPosition toPosition(line:number,column:number):TextPosition; } export class LineMapperImpl implements LineMapper{ constructor(private content:string, private absPath:string){} private mapping: number[]; position(_pos:number):TextPosition{ var pos = _pos; this.initMapping(); for(var i = 0 ; i < this.mapping.length; i++){ var lineLength = this.mapping[i]; if(pos < lineLength){ return { line: i, column: pos, position: _pos } } pos -= lineLength; } if(pos==0){ return { line: this.mapping.length-1, column: this.mapping[this.mapping.length-1], position: this.content.length } } if (pos == 1) { //sometimes YAML library reports an error at a position of document length + 1, no idea what they want //to tell us that way return { line: this.mapping.length - 1, column: this.mapping[this.mapping.length-1]-1, position: _pos-1 } } throw new Error(linter.applyTemplate(messageRegistry.POSITION_EXCEEDS_TEXT_LENGTH, {pos:_pos, length:this.content.length, absPath:this.absPath})); } initMapping(){ if(this.mapping!=null){ return; } if(this.content==null){ throw new Error(linter.applyTemplate(messageRegistry.LINE_MAPPER_HAS_NULL_CONTENT,{path:this.absPath!=null ?('. Path: ' + this.absPath): ' and null path.'})); } this.mapping = []; var ind = 0; var l = this.content.length; for(var i = 0 ; i < l; i++){ if(this.content.charAt(i)=='\r'){ if(i < l-1 && this.content.charAt(i+1)=='\n'){ this.mapping.push(i-ind + 2); ind = i+2; i++; } else{ this.mapping.push(i-ind + 1); ind = i+1; } } else if(this.content.charAt(i)=='\n'){ this.mapping.push(i-ind + 1); ind = i+1; } } this.mapping.push(l-ind); } toPosition(line:number,_column:number):TextPosition{ let column = _column; this.initMapping(); for(var i = line ; i < this.mapping.length ; i++){ let lineLength = this.mapping[i]; if(column < lineLength){ let pos = column; for(var j = 0 ; j < i ; j++){ pos += this.mapping[j]; } return { line: i, column: column, position: pos } } column -= lineLength; } return { line: i, column: column, position: this.content.length }; } } /** * Canonic way of resolving references in RAML specs: * * relative reference is regarded as relative to containing unit * * absolute local path (starting with slash) is regarderd as relative to root RAML * * absolute web paths are regarded as such * * @param reference reference to be resolved * @param unitPath path of unit containing the reference, absolute or relative to root * @param rootPath path to root RAML * @returns resolved path */ export function buildPath(reference, unitPath, rootPath) { if (path.isAbsolute(reference)){ var e=path.extname(unitPath); if (/*e!=".json"&&*/e!=".xsd") { //SUPPORTING 0.8 style resolving due to compatiblity reasons reference = reference.substr(1); unitPath = toAbsolutePath(rootPath, path.basename(unitPath)); } } if(isWebPath(reference)||path.isAbsolute(reference)){ return reference; } if(isWebPath(unitPath)||path.isAbsolute(unitPath)){ return toAbsolutePath(path.dirname(unitPath),reference); } return toAbsolutePath(path.dirname(toAbsolutePath(rootPath, unitPath)), reference); } /** * Resolving reference against context * * absolute local and web references are regarded as such * * relative references are regarded as relative to the context * @param context absolute local or web path * @param reference * @returns resolved reference */ export function toAbsolutePath(context:string,reference:string) { if (isWebPath(reference)){ return reference; } var apath:string; if (isWebPath(context)) { var rp = util.stringEndsWith(context,"/") ? context : context + "/"; apath = URL.resolve(rp,reference).replace(/\\/g,"/"); } else { apath = path.resolve(context, reference).replace(/\\/g,"/"); } return apath; } /** * Check if reference points to web resource * @param reference * @returns {boolean} */ export function isWebPath(reference):boolean { if (reference == null) return false; return util.stringStartsWith(reference,"http://") || util.stringStartsWith(reference,"https://"); } export function isLowLevelNode(object : any) : object is ILowLevelASTNode { return object.start && object.end && object.unit && object.key && object.value && object.children && object.includePath; }
the_stack
export default class ChromePromise { constructor(options?: { chrome?: object; Promise?: Function; }); accessibilityFeatures: chromepApi.accessibilityFeatures.AccessibilityFeatures; alarms: chromepApi.alarms.Alarms; browser: chromepApi.browser.Browser; bookmarks: chromepApi.bookmarks.Bookmarks; browserAction: chromepApi.browserAction.BrowserAction; browsingData: chromepApi.browsingData.BrowsingData; commands: chromepApi.commands.Commands; contentSettings: chromepApi.contentSettings.ContentSettings; contextMenus: chromepApi.contextMenus.ContextMenus; cookies: chromepApi.cookies.Cookies; declarativeContent: chromepApi.declarativeContent.DeclarativeContent; declarativeWebRequest: chromepApi.declarativeWebRequest.DeclarativeWebRequest; desktopCapture: chromepApi.desktopCapture.DesktopCapture; documentScan: chromepApi.documentScan.DocumentScan; downloads: chromepApi.downloads.Downloads; events: chromepApi.events.Events; extension: chromepApi.extension.Extension; fileBrowserHandler: chromepApi.fileBrowserHandler.FileBrowserHandler; fileSystemProvider: chromepApi.fileSystemProvider.FileSystemProvider; fontSettings: chromepApi.fontSettings.FontSettings; gcm: chromepApi.gcm.Gcm; history: chromepApi.history.History; i18n: chromepApi.i18n.I18n; identity: chromepApi.identity.Identity; idle: chromepApi.idle.Idle; management: chromepApi.management.Management; notifications: chromepApi.notifications.Notifications; omnibox: chromepApi.omnibox.Omnibox; pageAction: chromepApi.pageAction.PageAction; pageCapture: chromepApi.pageCapture.PageCapture; permissions: chromepApi.permissions.Permissions; platformKeys: chromepApi.platformKeys.PlatformKeys; power: chromepApi.power.Power; printerProvider: chromepApi.printerProvider.PrinterProvider; privacy: chromepApi.privacy.Privacy; proxy: chromepApi.proxy.Proxy; serial: chromepApi.serial.Serial; runtime: chromepApi.runtime.Runtime; scriptBadge: chromepApi.scriptBadge.ScriptBadge; sessions: chromepApi.sessions.Sessions; storage: chromepApi.storage.Storage; socket: chromepApi.socket.Socket; tabCapture: chromepApi.tabCapture.TabCapture; tabs: chromepApi.tabs.Tabs; topSites: chromepApi.topSites.TopSites; tts: chromepApi.tts.Tts; ttsEngine: chromepApi.ttsEngine.TtsEngine; types: chromepApi.types.Types; vpnProvider: chromepApi.vpnProvider.VpnProvider; wallpaper: chromepApi.wallpaper.Wallpaper; webNavigation: chromepApi.webNavigation.WebNavigation; webRequest: chromepApi.webRequest.WebRequest; webstore: chromepApi.webstore.Webstore; windows: chromepApi.windows.Windows; } declare namespace chromepApi.accessibilityFeatures { export interface AccessibilityFeaturesSetting { /** * Gets the value of a setting. * @param details Which setting to consider. * @param callback The callback parameter should be a function that looks like this: * function(object details) {...}; */ get(details: chrome.accessibilityFeatures.AccessibilityFeaturesGetArg): Promise<chrome.accessibilityFeatures.AccessibilityFeaturesCallbackArg>; /** * Sets the value of a setting. * @param details Which setting to change. * @param callback Called at the completion of the set operation. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ set(details: chrome.accessibilityFeatures.AccessibilityFeaturesSetArg): Promise<void>; /** * Clears the setting, restoring any default value. * @param details Which setting to clear. * @param callback Called at the completion of the clear operation. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ clear(details: chrome.accessibilityFeatures.AccessibilityFeaturesClearArg): Promise<void>; } export interface AccessibilityFeatures { spokenFeedback: AccessibilityFeaturesSetting; largeCursor: AccessibilityFeaturesSetting; stickyKeys: AccessibilityFeaturesSetting; highContrast: AccessibilityFeaturesSetting; screenMagnifier: AccessibilityFeaturesSetting; autoclick: AccessibilityFeaturesSetting; virtualKeyboard: AccessibilityFeaturesSetting; animationPolicy: AccessibilityFeaturesSetting; } } declare namespace chromepApi.alarms { export interface AlarmEvent extends chrome.events.Event<(alarm: chrome.alarms.Alarm) => void> { } export interface Alarms { /** * Gets an array of all the alarms. * @param callback The callback parameter should be a function that looks like this: * function(array of Alarm alarms) {...}; */ getAll(): Promise<chrome.alarms.Alarm[]>; /** * Clears all alarms. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function(boolean wasCleared) {...}; */ clearAll(): Promise<boolean>; /** * Clears the alarm with the given name. * @param name The name of the alarm to clear. Defaults to the empty string. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function(boolean wasCleared) {...}; */ clear(name?: string): Promise<boolean>; /** * Clears the alarm without a name. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function(boolean wasCleared) {...}; */ clear(): Promise<boolean>; /** * Retrieves details about the specified alarm. * @param callback The callback parameter should be a function that looks like this: * function( Alarm alarm) {...}; */ get(): Promise<chrome.alarms.Alarm>; /** * Retrieves details about the specified alarm. * @param name The name of the alarm to get. Defaults to the empty string. * @param callback The callback parameter should be a function that looks like this: * function( Alarm alarm) {...}; */ get(name: string): Promise<chrome.alarms.Alarm>; onAlarm: AlarmEvent; } } declare namespace chromepApi.browser { export interface Browser { /** * Opens a new tab in a browser window associated with the current application * and Chrome profile. If no browser window for the Chrome profile is opened, * a new one is opened prior to creating the new tab. * @param options Configures how the tab should be opened. * @param callback Called when the tab was successfully * created, or failed to be created. If failed, runtime.lastError will be set. */ openTab(options: chrome.browser.Options): Promise<void>; } } declare namespace chromepApi.bookmarks { export interface BookmarkRemovedEvent extends chrome.events.Event<(id: string, removeInfo: chrome.bookmarks.BookmarkRemoveInfo) => void> { } export interface BookmarkImportEndedEvent extends chrome.events.Event<() => void> { } export interface BookmarkImportBeganEvent extends chrome.events.Event<() => void> { } export interface BookmarkChangedEvent extends chrome.events.Event<(id: string, changeInfo: chrome.bookmarks.BookmarkChangeInfo) => void> { } export interface BookmarkMovedEvent extends chrome.events.Event<(id: string, moveInfo: chrome.bookmarks.BookmarkMoveInfo) => void> { } export interface BookmarkCreatedEvent extends chrome.events.Event<(id: string, bookmark: chrome.bookmarks.BookmarkTreeNode) => void> { } export interface BookmarkChildrenReordered extends chrome.events.Event<(id: string, reorderInfo: chrome.bookmarks.BookmarkReorderInfo) => void> { } export interface Bookmarks { /** * Searches for BookmarkTreeNodes matching the given query. Queries specified with an object produce BookmarkTreeNodes matching all specified properties. * @param query A string of words and quoted phrases that are matched against bookmark URLs and titles. * @param callback The callback parameter should be a function that looks like this: * function(array of BookmarkTreeNode results) {...}; */ search(query: string): Promise<chrome.bookmarks.BookmarkTreeNode[]>; /** * Searches for BookmarkTreeNodes matching the given query. Queries specified with an object produce BookmarkTreeNodes matching all specified properties. * @param query An object with one or more of the properties query, url, and title specified. Bookmarks matching all specified properties will be produced. * @param callback The callback parameter should be a function that looks like this: * function(array of BookmarkTreeNode results) {...}; */ search(query: chrome.bookmarks.BookmarkSearchQuery): Promise<chrome.bookmarks.BookmarkTreeNode[]>; /** * Retrieves the entire Bookmarks hierarchy. * @param callback The callback parameter should be a function that looks like this: * function(array of BookmarkTreeNode results) {...}; */ getTree(): Promise<chrome.bookmarks.BookmarkTreeNode[]>; /** * Retrieves the recently added bookmarks. * @param numberOfItems The maximum number of items to return. * @param callback The callback parameter should be a function that looks like this: * function(array of BookmarkTreeNode results) {...}; */ getRecent(numberOfItems: number): Promise<chrome.bookmarks.BookmarkTreeNode[]>; /** * Retrieves the specified BookmarkTreeNode. * @param id A single string-valued id * @param callback The callback parameter should be a function that looks like this: * function(array of BookmarkTreeNode results) {...}; */ get(id: string): Promise<chrome.bookmarks.BookmarkTreeNode[]>; /** * Retrieves the specified BookmarkTreeNode. * @param idList An array of string-valued ids * @param callback The callback parameter should be a function that looks like this: * function(array of BookmarkTreeNode results) {...}; */ get(idList: string[]): Promise<chrome.bookmarks.BookmarkTreeNode[]>; /** * Creates a bookmark or folder under the specified parentId. If url is NULL or missing, it will be a folder. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function( BookmarkTreeNode result) {...}; */ create(bookmark: chrome.bookmarks.BookmarkCreateArg): Promise<chrome.bookmarks.BookmarkTreeNode>; /** * Moves the specified BookmarkTreeNode to the provided location. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function( BookmarkTreeNode result) {...}; */ move(id: string, destination: chrome.bookmarks.BookmarkDestinationArg): Promise<chrome.bookmarks.BookmarkTreeNode>; /** * Updates the properties of a bookmark or folder. Specify only the properties that you want to change; unspecified properties will be left unchanged. Note: Currently, only 'title' and 'url' are supported. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function( BookmarkTreeNode result) {...}; */ update(id: string, changes: chrome.bookmarks.BookmarkChangesArg): Promise<chrome.bookmarks.BookmarkTreeNode>; /** * Removes a bookmark or an empty bookmark folder. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ remove(id: string): Promise<void>; /** * Retrieves the children of the specified BookmarkTreeNode id. * @param callback The callback parameter should be a function that looks like this: * function(array of BookmarkTreeNode results) {...}; */ getChildren(id: string): Promise<chrome.bookmarks.BookmarkTreeNode[]>; /** * Since Chrome 14. * Retrieves part of the Bookmarks hierarchy, starting at the specified node. * @param id The ID of the root of the subtree to retrieve. * @param callback The callback parameter should be a function that looks like this: * function(array of BookmarkTreeNode results) {...}; */ getSubTree(id: string): Promise<chrome.bookmarks.BookmarkTreeNode[]>; /** * Recursively removes a bookmark folder. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removeTree(id: string): Promise<void>; onRemoved: BookmarkRemovedEvent; onImportEnded: BookmarkImportEndedEvent; onImportBegan: BookmarkImportBeganEvent; onChanged: BookmarkChangedEvent; onMoved: BookmarkMovedEvent; onCreated: BookmarkCreatedEvent; onChildrenReordered: BookmarkChildrenReordered; } } declare namespace chromepApi.browserAction { export interface BrowserClickedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> { } export interface BrowserAction { /** * Since Chrome 22. * Enables the browser action for a tab. By default, browser actions are enabled. * @param tabId The id of the tab for which you want to modify the browser action. * @param callback Supported since Chrome 67 */ enable(tabId?: number): Promise<void>; /** * Sets the background color for the badge. * @param callback Supported since Chrome 67 */ setBadgeBackgroundColor(details: chrome.browserAction.BadgeBackgroundColorDetails): Promise<void>; /** * Sets the badge text for the browser action. The badge is displayed on top of the icon. * @param callback Supported since Chrome 67 */ setBadgeText(details: chrome.browserAction.BadgeTextDetails): Promise<void>; /** * Sets the title of the browser action. This shows up in the tooltip. * @param callback Supported since Chrome 67 */ setTitle(details: chrome.browserAction.TitleDetails): Promise<void>; /** * Since Chrome 19. * Gets the badge text of the browser action. If no tab is specified, the non-tab-specific badge text is returned. * @param callback Supported since Chrome 67 */ getBadgeText(details: chrome.browserAction.TabDetails): Promise<string>; /** * Sets the html document to be opened as a popup when the user clicks on the browser action's icon. * @param callback Supported since Chrome 67 */ setPopup(details: chrome.browserAction.PopupDetails): Promise<void>; /** * Since Chrome 22. * Disables the browser action for a tab. * @param tabId The id of the tab for which you want to modify the browser action. * @param callback Supported since Chrome 67 */ disable(tabId?: number): Promise<void>; /** * Since Chrome 19. * Gets the title of the browser action. * @param callback The callback parameter should be a function that looks like this: * function(string result) {...}; */ getTitle(details: chrome.browserAction.TabDetails): Promise<string>; /** * Since Chrome 19. * Gets the background color of the browser action. * @param callback The callback parameter should be a function that looks like this: * function( ColorArray result) {...}; */ getBadgeBackgroundColor(details: chrome.browserAction.TabDetails): Promise<chrome.browserAction.ColorArray>; /** * Since Chrome 19. * Gets the html document set as the popup for this browser action. * @param callback The callback parameter should be a function that looks like this: * function(string result) {...}; */ getPopup(details: chrome.browserAction.TabDetails): Promise<string>; /** * Sets the icon for the browser action. The icon can be specified either as the path to an image file or as the pixel data from a canvas element, or as dictionary of either one of those. Either the path or the imageData property must be specified. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ setIcon(details: chrome.browserAction.TabIconDetails): Promise<void>; onClicked: BrowserClickedEvent; } } declare namespace chromepApi.browsingData { export interface BrowsingData { /** * Since Chrome 26. * Reports which types of data are currently selected in the 'Clear browsing data' settings UI. Note: some of the data types included in this API are not available in the settings UI, and some UI settings control more than one data type listed here. * @param callback The callback parameter should be a function that looks like this: * function(object result) {...}; */ settings(): Promise<chrome.browsingData.SettingsCallback>; /** * Clears plugins' data. * @param callback Called when plugins' data has been cleared. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removePluginData(options: chrome.browsingData.RemovalOptions): Promise<void>; /** * Clears the browser's stored form data (autofill). * @param callback Called when the browser's form data has been cleared. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removeFormData(options: chrome.browsingData.RemovalOptions): Promise<void>; /** * Clears websites' file system data. * @param callback Called when websites' file systems have been cleared. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removeFileSystems(options: chrome.browsingData.RemovalOptions): Promise<void>; /** * Clears various types of browsing data stored in a user's profile. * @param dataToRemove The set of data types to remove. * @param callback Called when deletion has completed. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ remove(options: chrome.browsingData.RemovalOptions, dataToRemove: chrome.browsingData.DataTypeSet): Promise<void>; /** * Clears the browser's stored passwords. * @param callback Called when the browser's passwords have been cleared. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removePasswords(options: chrome.browsingData.RemovalOptions): Promise<void>; /** * Clears the browser's cookies and server-bound certificates modified within a particular timeframe. * @param callback Called when the browser's cookies and server-bound certificates have been cleared. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removeCookies(options: chrome.browsingData.RemovalOptions): Promise<void>; /** * Clears websites' WebSQL data. * @param callback Called when websites' WebSQL databases have been cleared. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removeWebSQL(options: chrome.browsingData.RemovalOptions): Promise<void>; /** * Clears websites' appcache data. * @param callback Called when websites' appcache data has been cleared. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removeAppcache(options: chrome.browsingData.RemovalOptions): Promise<void>; /** * Clears the browser's list of downloaded files (not the downloaded files themselves). * @param callback Called when the browser's list of downloaded files has been cleared. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removeDownloads(options: chrome.browsingData.RemovalOptions): Promise<void>; /** * Clears websites' local storage data. * @param callback Called when websites' local storage has been cleared. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removeLocalStorage(options: chrome.browsingData.RemovalOptions): Promise<void>; /** * Clears the browser's cache. * @param callback Called when the browser's cache has been cleared. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removeCache(options: chrome.browsingData.RemovalOptions): Promise<void>; /** * Clears the browser's history. * @param callback Called when the browser's history has cleared. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removeHistory(options: chrome.browsingData.RemovalOptions): Promise<void>; /** * Clears websites' IndexedDB data. * @param callback Called when websites' IndexedDB data has been cleared. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removeIndexedDB(options: chrome.browsingData.RemovalOptions): Promise<void>; } } declare namespace chromepApi.commands { export interface CommandEvent extends chrome.events.Event<(command: string) => void> { } export interface Commands { /** * Returns all the registered extension commands for this extension and their shortcut (if active). * @param callback Called to return the registered commands. * If you specify the callback parameter, it should be a function that looks like this: * function(array of Command commands) {...}; */ getAll(): Promise<chrome.commands.Command[]>; onCommand: CommandEvent; } } declare namespace chromepApi.contentSettings { export interface CookieContentSetting extends chrome.contentSettings.ContentSetting { set(details: chrome.contentSettings.CookieSetDetails): Promise<void>; } export interface PopupsContentSetting extends chrome.contentSettings.ContentSetting { set(details: chrome.contentSettings.PopupsSetDetails): Promise<void>; } export interface JavascriptContentSetting extends chrome.contentSettings.ContentSetting { set(details: chrome.contentSettings.JavascriptSetDetails): Promise<void>; } export interface NotificationsContentSetting extends chrome.contentSettings.ContentSetting { set(details: chrome.contentSettings.NotificationsSetDetails): Promise<void>; } export interface PluginsContentSetting extends chrome.contentSettings.ContentSetting { set(details: chrome.contentSettings.PluginsSetDetails): Promise<void>; } export interface ImagesContentSetting extends chrome.contentSettings.ContentSetting { set(details: chrome.contentSettings.ImagesSetDetails): Promise<void>; } export interface LocationContentSetting extends chrome.contentSettings.ContentSetting { set(details: chrome.contentSettings.LocationSetDetails): Promise<void>; } export interface FullscreenContentSetting extends chrome.contentSettings.ContentSetting { set(details: chrome.contentSettings.FullscreenSetDetails): Promise<void>; } export interface MouselockContentSetting extends chrome.contentSettings.ContentSetting { set(details: chrome.contentSettings.MouselockSetDetails): Promise<void>; } export interface MicrophoneContentSetting extends chrome.contentSettings.ContentSetting { set(details: chrome.contentSettings.MicrophoneSetDetails): Promise<void>; } export interface CameraContentSetting extends chrome.contentSettings.ContentSetting { set(details: chrome.contentSettings.CameraSetDetails): Promise<void>; } export interface PpapiBrokerContentSetting extends chrome.contentSettings.ContentSetting { set(details: chrome.contentSettings.PpapiBrokerSetDetails): Promise<void>; } export interface MultipleAutomaticDownloadsContentSetting extends chrome.contentSettings.ContentSetting { set(details: chrome.contentSettings.MultipleAutomaticDownloadsSetDetails): Promise<void>; } export interface ContentSettings { cookies: CookieContentSetting; popups: PopupsContentSetting; javascript: JavascriptContentSetting; notifications: NotificationsContentSetting; plugins: PluginsContentSetting; images: ImagesContentSetting; location: LocationContentSetting; fullscreen: FullscreenContentSetting; mouselock: MouselockContentSetting; microphone: MicrophoneContentSetting; camera: CameraContentSetting; unsandboxedPlugins: PpapiBrokerContentSetting; automaticDownloads: MultipleAutomaticDownloadsContentSetting; } } declare namespace chromepApi.contextMenus { export interface MenuClickedEvent extends chrome.events.Event<(info: chrome.contextMenus.OnClickData, tab?: chrome.tabs.Tab) => void> { } export interface ContextMenus { /** * Removes all context menu items added by this extension. * @param callback Called when removal is complete. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removeAll(): Promise<void>; /** * Creates a new context menu item. Note that if an error occurs during creation, you may not find out until the creation callback fires (the details will be in chrome.runtime.lastError). * @param callback Called when the item has been created in the browser. If there were any problems creating the item, details will be available in chrome.runtime.lastError. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ create(createProperties: chrome.contextMenus.CreateProperties): Promise<void>; /** * Updates a previously created context menu item. * @param id The ID of the item to update. * @param updateProperties The properties to update. Accepts the same values as the create function. * @param callback Called when the context menu has been updated. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ update(id: string, updateProperties: chrome.contextMenus.UpdateProperties): Promise<void>; /** * Updates a previously created context menu item. * @param id The ID of the item to update. * @param updateProperties The properties to update. Accepts the same values as the create function. * @param callback Called when the context menu has been updated. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ update(id: number, updateProperties: chrome.contextMenus.UpdateProperties): Promise<void>; /** * Removes a context menu item. * @param menuItemId The ID of the context menu item to remove. * @param callback Called when the context menu has been removed. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ remove(menuItemId: string): Promise<void>; /** * Removes a context menu item. * @param menuItemId The ID of the context menu item to remove. * @param callback Called when the context menu has been removed. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ remove(menuItemId: number): Promise<void>; onClicked: MenuClickedEvent; } } declare namespace chromepApi.cookies { export interface CookieChangedEvent extends chrome.events.Event<(changeInfo: chrome.cookies.CookieChangeInfo) => void> { } export interface Cookies { /** * Lists all existing cookie stores. * @param callback The callback parameter should be a function that looks like this: * function(array of CookieStore cookieStores) {...}; * Parameter cookieStores: All the existing cookie stores. */ getAllCookieStores(): Promise<chrome.cookies.CookieStore[]>; /** * Retrieves all cookies from a single cookie store that match the given information. The cookies returned will be sorted, with those with the longest path first. If multiple cookies have the same path length, those with the earliest creation time will be first. * @param details Information to filter the cookies being retrieved. * @param callback The callback parameter should be a function that looks like this: * function(array of Cookie cookies) {...}; * Parameter cookies: All the existing, unexpired cookies that match the given cookie info. */ getAll(details: chrome.cookies.GetAllDetails): Promise<chrome.cookies.Cookie[]>; /** * Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. * @param details Details about the cookie being set. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function( Cookie cookie) {...}; * Optional parameter cookie: Contains details about the cookie that's been set. If setting failed for any reason, this will be "null", and "chrome.runtime.lastError" will be set. */ set(details: chrome.cookies.SetDetails): Promise<chrome.cookies.Cookie | null>; /** * Deletes a cookie by name. * @param details Information to identify the cookie to remove. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function(object details) {...}; */ remove(details: chrome.cookies.Details): Promise<chrome.cookies.Details>; /** * Retrieves information about a single cookie. If more than one cookie of the same name exists for the given URL, the one with the longest path will be returned. For cookies with the same path length, the cookie with the earliest creation time will be returned. * @param details Details to identify the cookie being retrieved. * @param callback The callback parameter should be a function that looks like this: * function( Cookie cookie) {...}; * Parameter cookie: Contains details about the cookie. This parameter is null if no such cookie was found. */ get(details: chrome.cookies.Details): Promise<chrome.cookies.Cookie | null>; onChanged: CookieChangedEvent; } } declare namespace chromepApi.declarativeContent { export interface PageChangedEvent extends chrome.events.Event<() => void> { } export interface DeclarativeContent { onPageChanged: PageChangedEvent; } } declare namespace chromepApi.declarativeWebRequest { export interface RequestedEvent extends chrome.events.Event<Function> { } export interface DeclarativeWebRequest { onRequest: RequestedEvent; } } declare namespace chromepApi.desktopCapture { export interface DesktopCapture { /** * Shows desktop media picker UI with the specified set of sources. * @param sources Set of sources that should be shown to the user. * @param callback The callback parameter should be a function that looks like this: * function(string streamId) {...}; * Parameter streamId: An opaque string that can be passed to getUserMedia() API to generate media stream that corresponds to the source selected by the user. If user didn't select any source (i.e. canceled the prompt) then the callback is called with an empty streamId. The created streamId can be used only once and expires after a few seconds when it is not used. */ chooseDesktopMedia(sources: string[]): Promise<string>; /** * Shows desktop media picker UI with the specified set of sources. * @param sources Set of sources that should be shown to the user. * @param targetTab Optional tab for which the stream is created. If not specified then the resulting stream can be used only by the calling extension. The stream can only be used by frames in the given tab whose security origin matches tab.url. * @param callback The callback parameter should be a function that looks like this: * function(string streamId) {...}; * Parameter streamId: An opaque string that can be passed to getUserMedia() API to generate media stream that corresponds to the source selected by the user. If user didn't select any source (i.e. canceled the prompt) then the callback is called with an empty streamId. The created streamId can be used only once and expires after a few seconds when it is not used. */ chooseDesktopMedia(sources: string[], targetTab: chrome.tabs.Tab): Promise<string>; } } declare namespace chromepApi.documentScan { export interface DocumentScan { /** * Performs a document scan. On success, the PNG data will be sent to the callback. * @param options Object containing scan parameters. * @param callback Called with the result and data from the scan. * The callback parameter should be a function that looks like this: * function(object result) {...}; */ scan(options: chrome.documentScan.DocumentScanOptions): Promise<chrome.documentScan.DocumentScanCallbackArg>; } } declare namespace chromepApi.downloads { export interface DownloadChangedEvent extends chrome.events.Event<(downloadDelta: chrome.downloads.DownloadDelta) => void> { } export interface DownloadCreatedEvent extends chrome.events.Event<(downloadItem: chrome.downloads.DownloadItem) => void> { } export interface DownloadErasedEvent extends chrome.events.Event<(downloadId: number) => void> { } export interface DownloadDeterminingFilenameEvent extends chrome.events.Event<(downloadItem: chrome.downloads.DownloadItem, suggest: (suggestion?: chrome.downloads.DownloadFilenameSuggestion) => void) => void> { } export interface Downloads { /** * Find DownloadItem. Set query to the empty object to get all DownloadItem. To get a specific DownloadItem, set only the id field. To page through a large number of items, set orderBy: ['-startTime'], set limit to the number of items per page, and set startedAfter to the startTime of the last item from the last page. * @param callback The callback parameter should be a function that looks like this: * function(array of DownloadItem results) {...}; */ search(query: chrome.downloads.DownloadQuery): Promise<chrome.downloads.DownloadItem[]>; /** * Pause the download. If the request was successful the download is in a paused state. Otherwise runtime.lastError contains an error message. The request will fail if the download is not active. * @param downloadId The id of the download to pause. * @param callback Called when the pause request is completed. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ pause(downloadId: number): Promise<void>; /** * Retrieve an icon for the specified download. For new downloads, file icons are available after the onCreated event has been received. The image returned by this function while a download is in progress may be different from the image returned after the download is complete. Icon retrieval is done by querying the underlying operating system or toolkit depending on the platform. The icon that is returned will therefore depend on a number of factors including state of the download, platform, registered file types and visual theme. If a file icon cannot be determined, runtime.lastError will contain an error message. * @param downloadId The identifier for the download. * @param callback A URL to an image that represents the download. * The callback parameter should be a function that looks like this: * function(string iconURL) {...}; */ getFileIcon(downloadId: number): Promise<string>; /** * Retrieve an icon for the specified download. For new downloads, file icons are available after the onCreated event has been received. The image returned by this function while a download is in progress may be different from the image returned after the download is complete. Icon retrieval is done by querying the underlying operating system or toolkit depending on the platform. The icon that is returned will therefore depend on a number of factors including state of the download, platform, registered file types and visual theme. If a file icon cannot be determined, runtime.lastError will contain an error message. * @param downloadId The identifier for the download. * @param callback A URL to an image that represents the download. * The callback parameter should be a function that looks like this: * function(string iconURL) {...}; */ getFileIcon(downloadId: number, options: chrome.downloads.GetFileIconOptions): Promise<string>; /** * Resume a paused download. If the request was successful the download is in progress and unpaused. Otherwise runtime.lastError contains an error message. The request will fail if the download is not active. * @param downloadId The id of the download to resume. * @param callback Called when the resume request is completed. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ resume(downloadId: number): Promise<void>; /** * Cancel a download. When callback is run, the download is cancelled, completed, interrupted or doesn't exist anymore. * @param downloadId The id of the download to cancel. * @param callback Called when the cancel request is completed. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ cancel(downloadId: number): Promise<void>; /** * Download a URL. If the URL uses the HTTP[S] protocol, then the request will include all cookies currently set for its hostname. If both filename and saveAs are specified, then the Save As dialog will be displayed, pre-populated with the specified filename. If the download started successfully, callback will be called with the new DownloadItem's downloadId. If there was an error starting the download, then callback will be called with downloadId=undefined and runtime.lastError will contain a descriptive string. The error strings are not guaranteed to remain backwards compatible between releases. Extensions must not parse it. * @param options What to download and how. * @param callback Called with the id of the new DownloadItem. * If you specify the callback parameter, it should be a function that looks like this: * function(integer downloadId) {...}; */ download(options: chrome.downloads.DownloadOptions): Promise<number>; /** * Erase matching DownloadItem from history without deleting the downloaded file. An onErased event will fire for each DownloadItem that matches query, then callback will be called. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function(array of integer erasedIds) {...}; */ erase(query: chrome.downloads.DownloadQuery): Promise<number[]>; /** * Remove the downloaded file if it exists and the DownloadItem is complete; otherwise return an error through runtime.lastError. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removeFile(downloadId: number): Promise<void>; /** * Prompt the user to accept a dangerous download. Can only be called from a visible context (tab, window, or page/browser action popup). Does not automatically accept dangerous downloads. If the download is accepted, then an onChanged event will fire, otherwise nothing will happen. When all the data is fetched into a temporary file and either the download is not dangerous or the danger has been accepted, then the temporary file is renamed to the target filename, the |state| changes to 'complete', and onChanged fires. * @param downloadId The identifier for the DownloadItem. * @param callback Called when the danger prompt dialog closes. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ acceptDanger(downloadId: number): Promise<void>; onChanged: DownloadChangedEvent; onCreated: DownloadCreatedEvent; onErased: DownloadErasedEvent; onDeterminingFilename: DownloadDeterminingFilenameEvent; } } declare namespace chromepApi.events { export interface Events { } } declare namespace chromepApi.extension { export interface LastError { } export interface Extension { lastError: LastError; /** * Retrieves the state of the extension's access to the 'file://' scheme (as determined by the user-controlled 'Allow access to File URLs' checkbox. * Since Chrome 12. * @param callback The callback parameter should be a function that looks like this: * function(boolean isAllowedAccess) {...}; * Parameter isAllowedAccess: True if the extension can access the 'file://' scheme, false otherwise. */ isAllowedFileSchemeAccess(): Promise<boolean>; /** * Retrieves the state of the extension's access to Incognito-mode (as determined by the user-controlled 'Allowed in Incognito' checkbox. * Since Chrome 12. * @param callback The callback parameter should be a function that looks like this: * function(boolean isAllowedAccess) {...}; * Parameter isAllowedAccess: True if the extension has access to Incognito mode, false otherwise. */ isAllowedIncognitoAccess(): Promise<boolean>; } } declare namespace chromepApi.fileBrowserHandler { export interface FileBrowserHandlerExecuteEvent extends chrome.events.Event<(id: string, details: chrome.fileBrowserHandler.FileHandlerExecuteEventDetails) => void> { } export interface FileBrowserHandler { /** * Prompts user to select file path under which file should be saved. When the file is selected, file access permission required to use the file (read, write and create) are granted to the caller. The file will not actually get created during the function call, so function caller must ensure its existence before using it. The function has to be invoked with a user gesture. * Since Chrome 21. * @param selectionParams Parameters that will be used while selecting the file. * @param callback Function called upon completion. * The callback parameter should be a function that looks like this: * function(object result) {...}; * Parameter result: Result of the method. */ selectFile(selectionParams: chrome.fileBrowserHandler.SelectionParams): Promise<chrome.fileBrowserHandler.SelectionResult>; onExecute: FileBrowserHandlerExecuteEvent; } } declare namespace chromepApi.fileSystemProvider { export interface RequestedEvent extends chrome.events.Event<(options: chrome.fileSystemProvider.RequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } export interface MetadataRequestedEvent extends chrome.events.Event<(options: chrome.fileSystemProvider.MetadataRequestedEventOptions, successCallback: (metadata: chrome.fileSystemProvider.EntryMetadata) => void, errorCallback: (error: string) => void) => void> { } export interface DirectoryPathRequestedEvent extends chrome.events.Event<(options: chrome.fileSystemProvider.DirectoryPathRequestedEventOptions, successCallback: (entries: chrome.fileSystemProvider.EntryMetadata[], hasMore: boolean) => void, errorCallback: (error: string) => void) => void> { } export interface OpenFileRequestedEvent extends chrome.events.Event<(options: chrome.fileSystemProvider.OpenFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } export interface OpenedFileRequestedEvent extends chrome.events.Event<(options: chrome.fileSystemProvider.OpenedFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } export interface OpenedFileOffsetRequestedEvent extends chrome.events.Event<(options: chrome.fileSystemProvider.OpenedFileOffsetRequestedEventOptions, successCallback: (data: ArrayBuffer, hasMore: boolean) => void, errorCallback: (error: string) => void) => void> { } export interface DirectoryPathRecursiveRequestedEvent extends chrome.events.Event<(options: chrome.fileSystemProvider.DirectoryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } export interface EntryPathRecursiveRequestedEvent extends chrome.events.Event<(options: chrome.fileSystemProvider.EntryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } export interface FilePathRequestedEvent extends chrome.events.Event<(options: chrome.fileSystemProvider.FilePathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } export interface SourceTargetPathRequestedEvent extends chrome.events.Event<(options: chrome.fileSystemProvider.SourceTargetPathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } export interface FilePathLengthRequestedEvent extends chrome.events.Event<(options: chrome.fileSystemProvider.FilePathLengthRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } export interface OpenedFileIoRequestedEvent extends chrome.events.Event<(options: chrome.fileSystemProvider.OpenedFileIoRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } export interface OperationRequestedEvent extends chrome.events.Event<(options: chrome.fileSystemProvider.OperationRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } export interface OptionlessRequestedEvent extends chrome.events.Event<(successCallback: Function, errorCallback: (error: string) => void) => void> { } export interface FileSystemProvider { /** * Mounts a file system with the given fileSystemId and displayName. displayName will be shown in the left panel of Files.app. displayName can contain any characters including '/', but cannot be an empty string. displayName must be descriptive but doesn't have to be unique. The fileSystemId must not be an empty string. * Depending on the type of the file system being mounted, the source option must be set appropriately. * In case of an error, runtime.lastError will be set with a corresponding error code. * @param callback A generic result callback to indicate success or failure. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ mount(options: chrome.fileSystemProvider.MountOptions): Promise<void>; /** * Unmounts a file system with the given fileSystemId. It must be called after onUnmountRequested is invoked. Also, the providing extension can decide to perform unmounting if not requested (eg. in case of lost connection, or a file error). * In case of an error, runtime.lastError will be set with a corresponding error code. * @param callback A generic result callback to indicate success or failure. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ unmount(options: chrome.fileSystemProvider.UnmountOptions): Promise<void>; /** * Returns all file systems mounted by the extension. * @param callback Callback to receive the result of getAll function. * The callback parameter should be a function that looks like this: * function(array of FileSystemInfo fileSystems) {...}; */ getAll(): Promise<chrome.fileSystemProvider.FileSystemInfo[]>; /** * Returns information about a file system with the passed fileSystemId. * @since Since Chrome 42. * @param callback Callback to receive the result of get function. * The callback parameter should be a function that looks like this: * function(FileSystemInfo fileSystem) {...}; */ get(fileSystemId: string): Promise<chrome.fileSystemProvider.FileSystemInfo>; /** * Notifies about changes in the watched directory at observedPath in recursive mode. If the file system is mounted with supportsNofityTag, then tag must be provided, and all changes since the last notification always reported, even if the system was shutdown. The last tag can be obtained with getAll. * To use, the file_system_provider.notify manifest option must be set to true. * Value of tag can be any string which is unique per call, so it's possible to identify the last registered notification. Eg. if the providing extension starts after a reboot, and the last registered notification's tag is equal to "123", then it should call notify for all changes which happened since the change tagged as "123". It cannot be an empty string. * Not all providers are able to provide a tag, but if the file system has a changelog, then the tag can be eg. a change number, or a revision number. * Note that if a parent directory is removed, then all descendant entries are also removed, and if they are watched, then the API must be notified about the fact. Also, if a directory is renamed, then all descendant entries are in fact removed, as there is no entry under their original paths anymore. * In case of an error, runtime.lastError will be set will a corresponding error code. * @param callback A generic result callback to indicate success or failure. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ notify(options: chrome.fileSystemProvider.NotificationOptions): Promise<void>; onUnmountRequested: RequestedEvent; onGetMetadataRequested: MetadataRequestedEvent; onReadDirectoryRequested: DirectoryPathRequestedEvent; onOpenFileRequested: OpenFileRequestedEvent; onCloseFileRequested: OpenedFileRequestedEvent; onReadFileRequested: OpenedFileOffsetRequestedEvent; onCreateDirectoryRequested: DirectoryPathRecursiveRequestedEvent; onDeleteEntryRequested: EntryPathRecursiveRequestedEvent; onCreateFileRequested: FilePathRequestedEvent; onCopyEntryRequested: SourceTargetPathRequestedEvent; onMoveEntryRequested: SourceTargetPathRequestedEvent; onTruncateRequested: FilePathLengthRequestedEvent; onWriteFileRequested: OpenedFileIoRequestedEvent; onAbortRequested: OperationRequestedEvent; onConfigureRequested: RequestedEvent; onMountRequested: OptionlessRequestedEvent; onAddWatcherRequested: EntryPathRecursiveRequestedEvent; onRemoveWatcherRequested: EntryPathRecursiveRequestedEvent; } } declare namespace chromepApi.fontSettings { export interface DefaultFixedFontSizeChangedEvent extends chrome.events.Event<(details: chrome.fontSettings.FontSizeDetails) => void> { } export interface DefaultFontSizeChangedEvent extends chrome.events.Event<(details: chrome.fontSettings.FontSizeDetails) => void> { } export interface MinimumFontSizeChangedEvent extends chrome.events.Event<(details: chrome.fontSettings.FontSizeDetails) => void> { } export interface FontChangedEvent extends chrome.events.Event<(details: chrome.fontSettings.FullFontDetails) => void> { } export interface FontSettings { /** * Sets the default font size. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ setDefaultFontSize(details: chrome.fontSettings.DefaultFontSizeDetails): Promise<void>; /** * Gets the font for a given script and generic font family. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function(object details) {...}; */ getFont(details: chrome.fontSettings.FontDetails): Promise<chrome.fontSettings.FontDetailsResult>; /** * Gets the default font size. * @param details This parameter is currently unused. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function(object details) {...}; */ getDefaultFontSize(details?: Object): Promise<chrome.fontSettings.FontSizeDetails>; /** * Gets the minimum font size. * @param details This parameter is currently unused. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function(object details) {...}; */ getMinimumFontSize(details?: chrome.fontSettings.FontSizeDetails): Promise<chrome.fontSettings.FontSizeDetails>; /** * Sets the minimum font size. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ setMinimumFontSize(details: chrome.fontSettings.SetFontSizeDetails): Promise<void>; /** * Gets the default size for fixed width fonts. * @param details This parameter is currently unused. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function(object details) {...}; */ getDefaultFixedFontSize(details?: Object): Promise<chrome.fontSettings.FontSizeDetails>; /** * Clears the default font size set by this extension, if any. * @param details This parameter is currently unused. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ clearDefaultFontSize(details?: Object): Promise<void>; /** * Sets the default size for fixed width fonts. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ setDefaultFixedFontSize(details: chrome.fontSettings.SetFontSizeDetails): Promise<void>; /** * Clears the font set by this extension, if any. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ clearFont(details: chrome.fontSettings.FontDetails): Promise<void>; /** * Sets the font for a given script and generic font family. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function(object details) {...}; */ setFont(details: chrome.fontSettings.SetFontDetails): Promise<void>; /** * Clears the minimum font size set by this extension, if any. * @param details This parameter is currently unused. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ clearMinimumFontSize(details?: Object): Promise<void>; /** * Gets a list of fonts on the system. * @param callback The callback parameter should be a function that looks like this: * function(array of FontName results) {...}; */ getFontList(): Promise<chrome.fontSettings.FontName[]>; /** * Clears the default fixed font size set by this extension, if any. * @param details This parameter is currently unused. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ clearDefaultFixedFontSize(details: Object): Promise<void>; onDefaultFixedFontSizeChanged: DefaultFixedFontSizeChangedEvent; onDefaultFontSizeChanged: DefaultFontSizeChangedEvent; onMinimumFontSizeChanged: MinimumFontSizeChangedEvent; onFontChanged: FontChangedEvent; } } declare namespace chromepApi.gcm { export interface MessageReceptionEvent extends chrome.events.Event<(message: chrome.gcm.IncomingMessage) => void> { } export interface MessageDeletionEvent extends chrome.events.Event<() => void> { } export interface GcmErrorEvent extends chrome.events.Event<(error: chrome.gcm.GcmError) => void> { } export interface Gcm { /** * Registers the application with GCM. The registration ID will be returned by the callback. If register is called again with the same list of senderIds, the same registration ID will be returned. * @param senderIds A list of server IDs that are allowed to send messages to the application. It should contain at least one and no more than 100 sender IDs. * @param callback Function called when registration completes. It should check runtime.lastError for error when registrationId is empty. * The callback parameter should be a function that looks like this: * function(string registrationId) {...}; * Parameter registrationId: A registration ID assigned to the application by the GCM. */ register(senderIds: string[]): Promise<string>; /** * Unregisters the application from GCM. * @param callback A function called after the unregistration completes. Unregistration was successful if runtime.lastError is not set. * The callback parameter should be a function that looks like this: * function() {...}; */ unregister(): Promise<void>; /** * Sends a message according to its contents. * @param message A message to send to the other party via GCM. * @param callback A function called after the message is successfully queued for sending. runtime.lastError should be checked, to ensure a message was sent without problems. * The callback parameter should be a function that looks like this: * function(string messageId) {...}; * Parameter messageId: The ID of the message that the callback was issued for. */ send(message: chrome.gcm.OutgoingMessage): Promise<string>; onMessage: MessageReceptionEvent; onMessagesDeleted: MessageDeletionEvent; onSendError: GcmErrorEvent; } } declare namespace chromepApi.history { export interface HistoryVisitedEvent extends chrome.events.Event<(result: chrome.history.HistoryItem) => void> { } export interface HistoryVisitRemovedEvent extends chrome.events.Event<(removed: chrome.history.RemovedResult) => void> { } export interface History { /** * Searches the history for the last visit time of each page matching the query. * @param callback The callback parameter should be a function that looks like this: * function(array of HistoryItem results) {...}; */ search(query: chrome.history.HistoryQuery): Promise<chrome.history.HistoryItem[]>; /** * Adds a URL to the history at the current time with a transition type of "link". * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ addUrl(details: chrome.history.Url): Promise<void>; /** * Removes all items within the specified date range from the history. Pages will not be removed from the history unless all visits fall within the range. * @param callback The callback parameter should be a function that looks like this: * function() {...}; */ deleteRange(range: chrome.history.Range): Promise<void>; /** * Deletes all items from the history. * @param callback The callback parameter should be a function that looks like this: * function() {...}; */ deleteAll(): Promise<void>; /** * Retrieves information about visits to a URL. * @param callback The callback parameter should be a function that looks like this: * function(array of VisitItem results) {...}; */ getVisits(details: chrome.history.Url): Promise<chrome.history.VisitItem[]>; /** * Removes all occurrences of the given URL from the history. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ deleteUrl(details: chrome.history.Url): Promise<void>; onVisited: HistoryVisitedEvent; onVisitRemoved: HistoryVisitRemovedEvent; } } declare namespace chromepApi.i18n { export interface I18n { /** * Gets the accept-languages of the browser. This is different from the locale used by the browser; to get the locale, use i18n.getUILanguage. * @param callback The callback parameter should be a function that looks like this: * function(array of string languages) {...}; * Parameter languages: Array of the accept languages of the browser, such as en-US,en,zh-CN */ getAcceptLanguages(): Promise<string[]>; /** Detects the language of the provided text using CLD. * @param text User input string to be translated. * @param callback The callback parameter should be a function that looks like this: function(object result) {...}; */ detectLanguage(text: string): Promise<chrome.i18n.LanguageDetectionResult>; } } declare namespace chromepApi.identity { export interface SignInChangeEvent extends chrome.events.Event<(account: chrome.identity.AccountInfo, signedIn: boolean) => void> { } export interface Identity { /** * Retrieves a list of AccountInfo objects describing the accounts present on the profile. * getAccounts is only supported on dev channel. * Dev channel only. */ getAccounts(): Promise<chrome.identity.AccountInfo[]>; /** * Gets an OAuth2 access token using the client ID and scopes specified in the oauth2 section of manifest.json. * The Identity API caches access tokens in memory, so it's ok to call getAuthToken non-interactively any time a token is required. The token cache automatically handles expiration. * For a good user experience it is important interactive token requests are initiated by UI in your app explaining what the authorization is for. Failing to do this will cause your users to get authorization requests, or Chrome sign in screens if they are not signed in, with with no context. In particular, do not use getAuthToken interactively when your app is first launched. * @param details Token options. * @param callback Called with an OAuth2 access token as specified by the manifest, or undefined if there was an error. * If you specify the callback parameter, it should be a function that looks like this: * function(string token) {...}; */ getAuthToken(details: chrome.identity.TokenDetails): Promise<string>; /** * Retrieves email address and obfuscated gaia id of the user signed into a profile. * This API is different from identity.getAccounts in two ways. The information returned is available offline, and it only applies to the primary account for the profile. * @since Chrome 37. */ getProfileUserInfo(): Promise<chrome.identity.UserInfo>; /** * Removes an OAuth2 access token from the Identity API's token cache. * If an access token is discovered to be invalid, it should be passed to removeCachedAuthToken to remove it from the cache. The app may then retrieve a fresh token with getAuthToken. * @param details Token information. * @param callback Called when the token has been removed from the cache. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removeCachedAuthToken(details: chrome.identity.TokenInformation): Promise<void>; /** * Starts an auth flow at the specified URL. * This method enables auth flows with non-Google identity providers by launching a web view and navigating it to the first URL in the provider's auth flow. When the provider redirects to a URL matching the pattern https://<app-id>.chromiumapp.org/*, the window will close, and the final redirect URL will be passed to the callback function. * For a good user experience it is important interactive auth flows are initiated by UI in your app explaining what the authorization is for. Failing to do this will cause your users to get authorization requests with no context. In particular, do not launch an interactive auth flow when your app is first launched. * @param details WebAuth flow options. * @param callback Called with the URL redirected back to your application. * The callback parameter should be a function that looks like this: * function(string responseUrl) {...}; */ launchWebAuthFlow(details: chrome.identity.WebAuthFlowOptions): Promise<string>; onSignInChanged: SignInChangeEvent; } } declare namespace chromepApi.idle { export interface IdleStateChangedEvent extends chrome.events.Event<(newState: string) => void> { } export interface Idle { /** * Returns "locked" if the system is locked, "idle" if the user has not generated any input for a specified number of seconds, or "active" otherwise. * @param detectionIntervalInSeconds The system is considered idle if detectionIntervalInSeconds seconds have elapsed since the last user input detected. * Since Chrome 25. * @param callback The callback parameter should be a function that looks like this: * function( IdleState newState) {...}; */ queryState(detectionIntervalInSeconds: number): Promise<string>; onStateChanged: IdleStateChangedEvent; } } declare namespace chromepApi.management { export interface ManagementDisabledEvent extends chrome.events.Event<(info: chrome.management.ExtensionInfo) => void> { } export interface ManagementUninstalledEvent extends chrome.events.Event<(id: string) => void> { } export interface ManagementInstalledEvent extends chrome.events.Event<(info: chrome.management.ExtensionInfo) => void> { } export interface ManagementEnabledEvent extends chrome.events.Event<(info: chrome.management.ExtensionInfo) => void> { } export interface Management { /** * Enables or disables an app or extension. * @param id This should be the id from an item of management.ExtensionInfo. * @param enabled Whether this item should be enabled or disabled. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ setEnabled(id: string, enabled: boolean): Promise<void>; /** * Returns a list of permission warnings for the given extension id. * @since Chrome 15. * @param id The ID of an already installed extension. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function(array of string permissionWarnings) {...}; */ getPermissionWarningsById(id: string): Promise<string[]>; /** * Returns information about the installed extension, app, or theme that has the given ID. * @since Chrome 9. * @param id The ID from an item of management.ExtensionInfo. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function( ExtensionInfo result) {...}; */ get(id: string): Promise<chrome.management.ExtensionInfo>; /** * Returns a list of information about installed extensions and apps. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function(array of ExtensionInfo result) {...}; */ getAll(): Promise<chrome.management.ExtensionInfo[]>; /** * Returns a list of permission warnings for the given extension manifest string. Note: This function can be used without requesting the 'management' permission in the manifest. * @since Chrome 15. * @param manifestStr Extension manifest JSON string. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function(array of string permissionWarnings) {...}; */ getPermissionWarningsByManifest(manifestStr: string): Promise<string[]>; /** * Launches an application. * @param id The extension id of the application. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ launchApp(id: string): Promise<void>; /** * Uninstalls a currently installed app or extension. * @since Chrome 21. * @param id This should be the id from an item of management.ExtensionInfo. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ uninstall(id: string, options?: chrome.management.UninstallOptions): Promise<void>; /** * Uninstalls a currently installed app or extension. * @deprecated since Chrome 21. The options parameter was added to this function. * @param id This should be the id from an item of management.ExtensionInfo. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ uninstall(id: string): Promise<void>; /** * Returns information about the calling extension, app, or theme. Note: This function can be used without requesting the 'management' permission in the manifest. * @since Chrome 39. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function( ExtensionInfo result) {...}; */ getSelf(): Promise<chrome.management.ExtensionInfo>; /** * Uninstalls the calling extension. * Note: This function can be used without requesting the 'management' permission in the manifest. * @since Chrome 26. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ uninstallSelf(options?: chrome.management.UninstallOptions): Promise<void>; /** * Uninstalls the calling extension. * Note: This function can be used without requesting the 'management' permission in the manifest. * @since Chrome 26. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ uninstallSelf(): Promise<void>; /** * Display options to create shortcuts for an app. On Mac, only packaged app shortcuts can be created. * @since Chrome 37. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ createAppShortcut(id: string): Promise<void>; /** * Set the launch type of an app. * @since Chrome 37. * @param id This should be the id from an app item of management.ExtensionInfo. * @param launchType The target launch type. Always check and make sure this launch type is in ExtensionInfo.availableLaunchTypes, because the available launch types vary on different platforms and configurations. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ setLaunchType(id: string, launchType: string): Promise<void>; /** * Generate an app for a URL. Returns the generated bookmark app. * @since Chrome 37. * @param url The URL of a web page. The scheme of the URL can only be "http" or "https". * @param title The title of the generated app. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function( ExtensionInfo result) {...}; */ generateAppForLink(url: string, title: string): Promise<chrome.management.ExtensionInfo>; onDisabled: ManagementDisabledEvent; onUninstalled: ManagementUninstalledEvent; onInstalled: ManagementInstalledEvent; onEnabled: ManagementEnabledEvent; } } declare namespace chromepApi.notifications { export interface NotificationClosedEvent extends chrome.events.Event<(notificationId: string, byUser: boolean) => void> { } export interface NotificationClickedEvent extends chrome.events.Event<(notificationId: string) => void> { } export interface NotificationButtonClickedEvent extends chrome.events.Event<(notificationId: string, buttonIndex: number) => void> { } export interface NotificationPermissionLevelChangedEvent extends chrome.events.Event<(level: string) => void> { } export interface NotificationShowSettingsEvent extends chrome.events.Event<() => void> { } export interface Notifications { onClosed: NotificationClosedEvent; onClicked: NotificationClickedEvent; onButtonClicked: NotificationButtonClickedEvent; onPermissionLevelChanged: NotificationPermissionLevelChangedEvent; onShowSettings: NotificationShowSettingsEvent; /** * Creates and displays a notification. * @param notificationId Identifier of the notification. If not set or empty, an ID will automatically be generated. If it matches an existing notification, this method first clears that notification before proceeding with the create operation. * The notificationId parameter is required before Chrome 42. * @param options Contents of the notification. * @param callback Returns the notification id (either supplied or generated) that represents the created notification. * The callback is required before Chrome 42. * If you specify the callback parameter, it should be a function that looks like this: * function(string notificationId) {...}; */ create(notificationId: string, options: chrome.notifications.NotificationOptions): Promise<string>; /** * Creates and displays a notification. * @param notificationId Identifier of the notification. If not set or empty, an ID will automatically be generated. If it matches an existing notification, this method first clears that notification before proceeding with the create operation. * The notificationId parameter is required before Chrome 42. * @param options Contents of the notification. * @param callback Returns the notification id (either supplied or generated) that represents the created notification. * The callback is required before Chrome 42. * If you specify the callback parameter, it should be a function that looks like this: * function(string notificationId) {...}; */ create(options: chrome.notifications.NotificationOptions): Promise<string>; /** * Updates an existing notification. * @param notificationId The id of the notification to be updated. This is returned by notifications.create method. * @param options Contents of the notification to update to. * @param callback Called to indicate whether a matching notification existed. * The callback is required before Chrome 42. * If you specify the callback parameter, it should be a function that looks like this: * function(boolean wasUpdated) {...}; */ update(notificationId: string, options: chrome.notifications.NotificationOptions): Promise<boolean>; /** * Clears the specified notification. * @param notificationId The id of the notification to be cleared. This is returned by notifications.create method. * @param callback Called to indicate whether a matching notification existed. * The callback is required before Chrome 42. * If you specify the callback parameter, it should be a function that looks like this: * function(boolean wasCleared) {...}; */ clear(notificationId: string): Promise<boolean>; /** * Retrieves all the notifications. * @since Chrome 29. * @param callback Returns the set of notification_ids currently in the system. * The callback parameter should be a function that looks like this: * function(object notifications) {...}; */ getAll(): Promise<Object>; /** * Retrieves whether the user has enabled notifications from this app or extension. * @since Chrome 32. * @param callback Returns the current permission level. * The callback parameter should be a function that looks like this: * function( PermissionLevel level) {...}; */ getPermissionLevel(): Promise<string>; } } declare namespace chromepApi.omnibox { export interface OmniboxInputEnteredEvent extends chrome.events.Event<(text: string, disposition: chrome.omnibox.OnInputEnteredDisposition) => void> { } export interface OmniboxInputChangedEvent extends chrome.events.Event<(text: string, suggest: (suggestResults: chrome.omnibox.SuggestResult[]) => void) => void> { } export interface OmniboxInputStartedEvent extends chrome.events.Event<() => void> { } export interface OmniboxInputCancelledEvent extends chrome.events.Event<() => void> { } export interface OmniboxSuggestionDeletedEvent extends chrome.events.Event<(text: string) => void> { } export interface Omnibox { onInputEntered: OmniboxInputEnteredEvent; onInputChanged: OmniboxInputChangedEvent; onInputStarted: OmniboxInputStartedEvent; onInputCancelled: OmniboxInputCancelledEvent; onDeleteSuggestion: OmniboxSuggestionDeletedEvent; } } declare namespace chromepApi.pageAction { export interface PageActionClickedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> { } export interface PageAction { /** * Shows the page action. The page action is shown whenever the tab is selected. * @param tabId The id of the tab for which you want to modify the page action. * @param callback Supported since Chrome 67 */ hide(tabId: number): Promise<void>; /** * Shows the page action. The page action is shown whenever the tab is selected. * @param tabId The id of the tab for which you want to modify the page action. * @param callback Supported since Chrome 67 */ show(tabId: number): Promise<void>; /** * Sets the title of the page action. This is displayed in a tooltip over the page action. * @param callback Supported since Chrome 67 */ setTitle(details: chrome.pageAction.TitleDetails): Promise<void>; /** * Sets the html document to be opened as a popup when the user clicks on the page action's icon. * @param callback Supported since Chrome 67 */ setPopup(details: chrome.pageAction.PopupDetails): Promise<void>; /** * Gets the title of the page action. * @since Chrome 19. * @param callback The callback parameter should be a function that looks like this: * function(string result) {...}; */ getTitle(details: chrome.pageAction.GetDetails): Promise<string>; /** * Gets the html document set as the popup for this page action. * @since Chrome 19. * @param callback The callback parameter should be a function that looks like this: * function(string result) {...}; */ getPopup(details: chrome.pageAction.GetDetails): Promise<string>; /** * Sets the icon for the page action. The icon can be specified either as the path to an image file or as the pixel data from a canvas element, or as dictionary of either one of those. Either the path or the imageData property must be specified. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ setIcon(details: chrome.pageAction.IconDetails): Promise<void>; onClicked: PageActionClickedEvent; } } declare namespace chromepApi.pageCapture { export interface PageCapture { /** * Saves the content of the tab with given id as MHTML. * @param callback Called when the MHTML has been generated. * The callback parameter should be a function that looks like this: * function(binary mhtmlData) {...}; * Parameter mhtmlData: The MHTML data as a Blob. */ saveAsMHTML(details: chrome.pageCapture.SaveDetails): Promise<any>; } } declare namespace chromepApi.permissions { export interface PermissionsRemovedEvent { /** * @param callback The callback parameter should be a function that looks like this: * function( Permissions permissions) {...}; * Parameter permissions: The permissions that have been removed. */ addListener(): Promise<chrome.permissions.Permissions>; } export interface PermissionsAddedEvent { /** * @param callback The callback parameter should be a function that looks like this: * function( Permissions permissions) {...}; * Parameter permissions: The newly acquired permissions. */ addListener(): Promise<chrome.permissions.Permissions>; } export interface Permissions { /** * Checks if the extension has the specified permissions. * @param callback The callback parameter should be a function that looks like this: * function(boolean result) {...}; * Parameter result: True if the extension has the specified permissions. */ contains(permissions: chrome.permissions.Permissions): Promise<boolean>; /** * Gets the extension's current set of permissions. * @param callback The callback parameter should be a function that looks like this: * function( Permissions permissions) {...}; * Parameter permissions: The extension's active permissions. */ getAll(): Promise<chrome.permissions.Permissions>; /** * Requests access to the specified permissions. These permissions must be defined in the optional_permissions field of the manifest. If there are any problems requesting the permissions, runtime.lastError will be set. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function(boolean granted) {...}; * Parameter granted: True if the user granted the specified permissions. */ request(permissions: chrome.permissions.Permissions): Promise<boolean>; /** * Removes access to the specified permissions. If there are any problems removing the permissions, runtime.lastError will be set. * @param callback If you specify the callback parameter, it should be a function that looks like this: * function(boolean removed) {...}; * Parameter removed: True if the permissions were removed. */ remove(permissions: chrome.permissions.Permissions): Promise<boolean>; onRemoved: PermissionsRemovedEvent; onAdded: PermissionsAddedEvent; } } declare namespace chromepApi.platformKeys { export interface PlatformKeys { /** * This function filters from a list of client certificates the ones that are known to the platform, match request and for which the extension has permission to access the certificate and its private key. If interactive is true, the user is presented a dialog where he can select from matching certificates and grant the extension access to the certificate. The selected/filtered client certificates will be passed to callback. * @param callback The callback parameter should be a function that looks like this: * function(array of Match matches) {...}; * Parameter matches: The list of certificates that match the request, that the extension has permission for and, if interactive is true, that were selected by the user. */ selectClientCertificates(details: chrome.platformKeys.ClientCertificateSelectDetails): Promise<chrome.platformKeys.Match[]>; /** * Passes the key pair of certificate for usage with platformKeys.subtleCrypto to callback. * @param certificate The certificate of a Match returned by selectClientCertificates. * @param parameters Determines signature/hash algorithm parameters additionally to the parameters fixed by the key itself. The same parameters are accepted as by WebCrypto's importKey function, e.g. RsaHashedImportParams for a RSASSA-PKCS1-v1_5 key. For RSASSA-PKCS1-v1_5 keys, additionally the parameters { 'hash': { 'name': 'none' } } are supported. The sign function will then apply PKCS#1 v1.5 padding and but not hash the given data. * @param callback The public and private CryptoKey of a certificate which can only be used with platformKeys.subtleCrypto. * The callback parameter should be a function that looks like this: * function(object publicKey, object privateKey) {...}; * Optional parameter privateKey: Might be null if this extension does not have access to it. */ getKeyPair(certificate: ArrayBuffer, parameters: Object): Promise<[CryptoKey, CryptoKey | null]>; /** * Checks whether details.serverCertificateChain can be trusted for details.hostname according to the trust settings of the platform. Note: The actual behavior of the trust verification is not fully specified and might change in the future. The API implementation verifies certificate expiration, validates the certification path and checks trust by a known CA. The implementation is supposed to respect the EKU serverAuth and to support subject alternative names. * @param callback The callback parameter should be a function that looks like this: * function(object result) {...}; */ verifyTLSServerCertificate(details: chrome.platformKeys.ServerCertificateVerificationDetails): Promise<chrome.platformKeys.ServerCertificateVerificationResult>; } } declare namespace chromepApi.power { export interface Power { } } declare namespace chromepApi.printerProvider { export interface PrinterRequestedEvent extends chrome.events.Event<(resultCallback: (printerInfo: chrome.printerProvider.PrinterInfo[]) => void) => void> { } export interface PrinterInfoRequestedEvent extends chrome.events.Event<(device: any, resultCallback: (printerInfo?: chrome.printerProvider.PrinterInfo) => void) => void> { } export interface CapabilityRequestedEvent extends chrome.events.Event<(printerId: string, resultCallback: (capabilities: chrome.printerProvider.PrinterCapabilities) => void) => void> { } export interface PrintRequestedEvent extends chrome.events.Event<(printJob: chrome.printerProvider.PrintJob, resultCallback: (result: string) => void) => void> { } export interface PrinterProvider { onGetPrintersRequested: PrinterRequestedEvent; onGetUsbPrinterInfoRequested: PrinterInfoRequestedEvent; onGetCapabilityRequested: CapabilityRequestedEvent; onPrintRequested: PrintRequestedEvent; } } declare namespace chromepApi.privacy { export interface Services { } export interface Network { } export interface Websites { } export interface Privacy { services: Services; network: Network; websites: Websites; } } declare namespace chromepApi.proxy { export interface ProxyErrorEvent extends chrome.events.Event<(details: chrome.proxy.ErrorDetails) => void> { } export interface Proxy { onProxyError: ProxyErrorEvent; } } declare namespace chromepApi.serial { export interface Serial { /** * @since Chrome 33. * @description Returns information about available serial devices on the system. The list is regenerated each time this method is called. * @export * @param callback Called with the list of DeviceInfo objects. * The callback parameter should be a function that looks like this: * function(array of object ports) {...}; */ getDevices(): Promise<chrome.serial.DeviceInfo[]>; /** * @since Chrome 33. * @description Connects to a given serial port. * @export * @param path The system path of the serial port to open. * @param options Port configuration options. * @param callback Called when the connection has been opened. * The callback parameter should be a function that looks like this: * function( ConnectionInfo connectionInfo) {...}; */ connect(path: string, options: chrome.serial.ConnectionOptions): Promise<chrome.serial.ConnectionInfo>; /** * @since Chrome 33. * @description Update the option settings on an open serial port connection. * @export * @param connectionId The id of the opened connection. * @param options Port configuration options. * @param callback Called when the configuation has completed. * The callback parameter should be a function that looks like this: * function(boolean result) {...}; */ update(connectionId: number, options: chrome.serial.ConnectionOptions): Promise<boolean>; /** * @since Chrome 33. * @description Disconnects from a serial port. * @export * @param connectionId The id of the opened connection. * @param callback Called when the connection has been closed. * The callback parameter should be a function that looks like this: * function(boolean result) {...}; */ disconnect(connectionId: number): Promise<boolean>; /** * @since Chrome 33. * @description Pauses or unpauses an open connection. * @export * @param connectionId The id of the opened connection. * @param paused Flag to indicate whether to pause or unpause. * @param callback Called when the connection has been successfully paused or unpaused. * The callback parameter should be a function that looks like this: * function() {...}; */ setPaused(connectionId: number, paused: boolean): Promise<void>; /** * @since Chrome 33. * @description Retrieves the state of a given connection. * @export * @param callback Called with connection state information when available. * The callback parameter should be a function that looks like this: * function( ConnectionInfo connectionInfo) {...}; */ getInfo(): Promise<chrome.serial.ConnectionInfo[]>; /** * @since Chrome 33. * @description Retrieves the list of currently opened serial port connections owned by the application. * @export * @param callback Called with the list of connections when available. * The callback parameter should be a function that looks like this: * function(array of ConnectionInfo connectionInfos) {...}; */ getConnections(): Promise<chrome.serial.ConnectionInfo[]>; /** * @since Chrome 33. * @description Writes data to the given connection. * @export * @param connectionId The id of the connection. * @param data The data to send. * @param callback Called when the operation has completed. * The callback parameter should be a function that looks like this: * function(object sendInfo) {...}; */ send(connectionId: number, data: ArrayBuffer): Promise<object>; /** * @description Flushes all bytes in the given connection's input and output buffers. * @export * @param connectionId The id of the connection. * @param callback * The callback parameter should be a function that looks like this: * function(boolean result) {...}; */ flush(connectionId: number): Promise<boolean>; /** * @description Retrieves the state of control signals on a given connection. * @export * @param connectionId The id of the connection. * @param callback Called when the control signals are available. * The callback parameter should be a function that looks like this: * function(object signals) {...}; */ getControlSignals(connectionId: number): Promise<object>; /** * @description Sets the state of control signals on a given connection. * @export * @param connectionId The id of the connection. * @param signals The set of signal changes to send to the device: * boolean: (optional) dtr - DTR (Data Terminal Ready). * boolean: (optional) rts - RTS (Request To Send). * @param callback Called once the control signals have been set. * The callback parameter should be a function that looks like this: * function(boolean result) {...}; */ setControlSignals(connectionId: number, signals: object): Promise<boolean>; /** * @since Chrome 45. * @description Suspends character transmission on a given connection and places the transmission line in a break state until the clearBreak is called. * @export * @param connectionId The id of the connection. * @param callback * The callback parameter should be a function that looks like this: * function(boolean result) {...}; */ setBreak(connectionId: number): Promise<boolean>; /** * @since Chrome 45. * @description Restore character transmission on a given connection and place the transmission line in a nonbreak state. * @export * @param connectionId The id of the connection. * @param callback * The callback parameter should be a function that looks like this: * function(boolean result) {...}; */ clearBreak(connectionId: number): Promise<boolean>; } } declare namespace chromepApi.runtime { export interface ExtensionConnectEvent extends chrome.events.Event<(port: chrome.runtime.Port) => void> { } export interface RuntimeEvent extends chrome.events.Event<() => void> { } export interface RuntimeInstalledEvent extends chrome.events.Event<(details: chrome.runtime.InstalledDetails) => void> { } export interface ExtensionMessageEvent extends chrome.events.Event<(message: any, sender: chrome.runtime.MessageSender, sendResponse: (response?: any) => void) => void> { } export interface RuntimeRestartRequiredEvent extends chrome.events.Event<(reason: string) => void> { } export interface RuntimeUpdateAvailableEvent extends chrome.events.Event<(details: chrome.runtime.UpdateAvailableDetails) => void> { } export interface Runtime { /** Retrieves the JavaScript 'window' object for the background page running inside the current extension/app. If the background page is an event page, the system will ensure it is loaded before calling the callback. If there is no background page, an error is set. */ getBackgroundPage(): Promise<Window>; /** * Returns a DirectoryEntry for the package directory. * @since Chrome 29. */ getPackageDirectoryEntry(): Promise<DirectoryEntry>; /** * Returns information about the current platform. * @since Chrome 29. * @param callback Called with results */ getPlatformInfo(): Promise<chrome.runtime.PlatformInfo>; /** * Requests an update check for this app/extension. * @since Chrome 25. * @param callback * Parameter status: Result of the update check. One of: "throttled", "no_update", or "update_available" * Optional parameter details: If an update is available, this contains more information about the available update. */ requestUpdateCheck(): Promise<[chrome.runtime.RequestUpdateCheckStatus, chrome.runtime.UpdateCheckDetails]>; /** * Sets the URL to be visited upon uninstallation. This may be used to clean up server-side data, do analytics, and implement surveys. Maximum 255 characters. * @since Chrome 41. * @param url Since Chrome 34. * URL to be opened after the extension is uninstalled. This URL must have an http: or https: scheme. Set an empty string to not open a new tab upon uninstallation. * @param callback Called when the uninstall URL is set. If the given URL is invalid, runtime.lastError will be set. */ setUninstallURL(url: string): Promise<void>; /** * Open your Extension's options page, if possible. * The precise behavior may depend on your manifest's options_ui or options_page key, or what Chrome happens to support at the time. For example, the page may be opened in a new tab, within chrome://extensions, within an App, or it may just focus an open options page. It will never cause the caller page to reload. * If your Extension does not declare an options page, or Chrome failed to create one for some other reason, the callback will set lastError. * @since Chrome 42. */ openOptionsPage(): Promise<void>; onConnect: ExtensionConnectEvent; onConnectExternal: ExtensionConnectEvent; onSuspend: RuntimeEvent; onStartup: RuntimeEvent; onInstalled: RuntimeInstalledEvent; onSuspendCanceled: RuntimeEvent; onMessage: ExtensionMessageEvent; onMessageExternal: ExtensionMessageEvent; onRestartRequired: RuntimeRestartRequiredEvent; onUpdateAvailable: RuntimeUpdateAvailableEvent; onBrowserUpdateAvailable: RuntimeEvent; } } declare namespace chromepApi.scriptBadge { export interface ScriptBadgeClickedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> { } export interface ScriptBadge { getPopup(details: chrome.scriptBadge.GetPopupDetails): Promise<void>; onClicked: ScriptBadgeClickedEvent; } } declare namespace chromepApi.sessions { export interface SessionChangedEvent extends chrome.events.Event<() => void> { } export interface Sessions { /** * Gets the list of recently closed tabs and/or windows. * @param callback * Parameter sessions: The list of closed entries in reverse order that they were closed (the most recently closed tab or window will be at index 0). The entries may contain either tabs or windows. */ getRecentlyClosed(filter: chrome.sessions.Filter): Promise<chrome.sessions.Session[]>; /** * Gets the list of recently closed tabs and/or windows. * @param callback * Parameter sessions: The list of closed entries in reverse order that they were closed (the most recently closed tab or window will be at index 0). The entries may contain either tabs or windows. */ getRecentlyClosed(): Promise<chrome.sessions.Session[]>; /** * Retrieves all devices with synced sessions. * @param callback * Parameter devices: The list of sessions.Device objects for each synced session, sorted in order from device with most recently modified session to device with least recently modified session. tabs.Tab objects are sorted by recency in the windows.Window of the sessions.Session objects. */ getDevices(filter: chrome.sessions.Filter): Promise<chrome.sessions.Device[]>; /** * Retrieves all devices with synced sessions. * @param callback * Parameter devices: The list of sessions.Device objects for each synced session, sorted in order from device with most recently modified session to device with least recently modified session. tabs.Tab objects are sorted by recency in the windows.Window of the sessions.Session objects. */ getDevices(): Promise<chrome.sessions.Device[]>; /** * Reopens a windows.Window or tabs.Tab, with an optional callback to run when the entry has been restored. * @param sessionId Optional. * The windows.Window.sessionId, or tabs.Tab.sessionId to restore. If this parameter is not specified, the most recently closed session is restored. * @param callback Optional. * Parameter restoredSession: A sessions.Session containing the restored windows.Window or tabs.Tab object. */ restore(sessionId?: string): Promise<chrome.sessions.Session>; onChanged: SessionChangedEvent; } } declare namespace chromepApi.storage { export interface LocalStorageArea extends StorageArea { } export interface SyncStorageArea extends StorageArea { } export interface StorageArea { /** * Gets the amount of space (in bytes) being used by one or more items. * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). * Parameter bytesInUse: Amount of space being used in storage, in bytes. */ getBytesInUse(): Promise<number>; /** * Gets the amount of space (in bytes) being used by one or more items. * @param keys A single key or list of keys to get the total usage for. An empty list will return 0. Pass in null to get the total usage of all of storage. * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). * Parameter bytesInUse: Amount of space being used in storage, in bytes. */ getBytesInUse(keys: string | string[] | null): Promise<number>; /** * Removes all items from storage. * @param callback Optional. * Callback on success, or on failure (in which case runtime.lastError will be set). */ clear(): Promise<void>; /** * Sets multiple items. * @param items An object which gives each key/value pair to update storage with. Any other key/value pairs in storage will not be affected. * Primitive values such as numbers will serialize as expected. Values with a typeof "object" and "function" will typically serialize to {}, with the exception of Array (serializes as expected), Date, and Regex (serialize using their String representation). * @param callback Optional. * Callback on success, or on failure (in which case runtime.lastError will be set). */ set(items: Object): Promise<void>; /** * Removes one or more items from storage. * @param A single key or a list of keys for items to remove. * @param callback Optional. * Callback on success, or on failure (in which case runtime.lastError will be set). */ remove(keys: string | string[]): Promise<void>; /** * Gets one or more items from storage. * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). * Parameter items: Object with items in their key-value mappings. */ get(): Promise<{ [key: string]: any; }>; /** * Gets one or more items from storage. * @param keys A single key to get, list of keys to get, or a dictionary specifying default values. * An empty list or object will return an empty result object. Pass in null to get the entire contents of storage. * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). * Parameter items: Object with items in their key-value mappings. */ get(keys: string | string[] | Object | null): Promise<{ [key: string]: any; }>; } export interface StorageChangedEvent extends chrome.events.Event<(changes: { [key: string]: chrome.storage.StorageChange; }, areaName: string) => void> { } export interface Storage { local: LocalStorageArea; sync: SyncStorageArea; managed: StorageArea; onChanged: StorageChangedEvent; } } declare namespace chromepApi.socket { export interface Socket { create(type: string, options?: Object): Promise<chrome.socket.CreateInfo>; connect(socketId: number, hostname: string, port: number): Promise<number>; bind(socketId: number, address: string, port: number): Promise<number>; read(socketId: number, bufferSize?: number): Promise<chrome.socket.ReadInfo>; write(socketId: number, data: ArrayBuffer): Promise<chrome.socket.WriteInfo>; recvFrom(socketId: number, bufferSize?: number): Promise<chrome.socket.RecvFromInfo>; sendTo(socketId: number, data: ArrayBuffer, address: string, port: number): Promise<chrome.socket.WriteInfo>; listen(socketId: number, address: string, port: number, backlog?: number): Promise<number>; accept(socketId: number): Promise<chrome.socket.AcceptInfo>; setKeepAlive(socketId: number, enable: boolean, delay?: number): Promise<boolean>; setNoDelay(socketId: number, noDelay: boolean): Promise<boolean>; getInfo(socketId: number): Promise<chrome.socket.SocketInfo>; getNetworkList(): Promise<chrome.socket.NetworkInterface[]>; } } declare namespace chromepApi.system.cpu { /** Queries basic CPU information of the system. */ export function getInfo(): Promise<chrome.system.cpu.CpuInfo>; } declare namespace chromepApi.system.memory { /** Get physical memory information. */ export function getInfo(): Promise<chrome.system.memory.MemoryInfo>; } declare namespace chromepApi.system.storage { /** Get the storage information from the system. The argument passed to the callback is an array of StorageUnitInfo objects. */ export function getInfo(): Promise<chrome.system.storage.StorageUnitInfo[]>; /** * Ejects a removable storage device. * @param callback * Parameter result: success: The ejection command is successful -- the application can prompt the user to remove the device; in_use: The device is in use by another application. The ejection did not succeed; the user should not remove the device until the other application is done with the device; no_such_device: There is no such device known. failure: The ejection command failed. */ export function ejectDevice(id: string): Promise<string>; /** * Get the available capacity of a specified |id| storage device. The |id| is the transient device ID from StorageUnitInfo. * @since Dev channel only. */ export function getAvailableCapacity(id: string): Promise<chrome.system.storage.StorageCapacityInfo>; } declare namespace chromepApi.system.display { /** * Requests the information for all attached display devices. * @param callback The callback to invoke with the results. */ export function getInfo(): Promise<chrome.system.display.DisplayInfo[]>; /** * Requests the information for all attached display devices. * @since Chrome 59 * @param flags Options affecting how the information is returned. * @param callback The callback to invoke with the results. */ export function getInfo(flags: chrome.system.display.DisplayInfoFlags): chrome.system.display.DisplayInfo[]; /** * @requires(CrOS Kiosk apps | WebUI) This is only available to Chrome OS Kiosk apps and Web UI. * @description Requests the layout info for all displays. * @since Chrome 53 * @export * @param callback The callback to invoke with the results. */ export function getDisplayLayout(): Promise<chrome.system.display.DisplayLayout[]>; /** * @requires(CrOS Kiosk apps | WebUI) This is only available to Chrome OS Kiosk apps and Web UI. * @description * Updates the properties for the display specified by **id**, * according to the information provided in **info**. * On failure, runtime.lastError will be set. * @param {string} id The display's unique identifier. * @param {DisplayPropertiesInfo} info The information about display properties that should be changed. A property will be changed only if a new value for it is specified in |info|. * @param {() => void} [callback] Empty function called when the function finishes. To find out whether the function succeeded, runtime.lastError should be queried. */ export function setDisplayProperties(id: string, info: chrome.system.display.DisplayPropertiesInfo): Promise<void>; /** * @requires(CrOS Kiosk apps | WebUI) This is only available to Chrome OS Kiosk apps and Web UI. * @description * Set the layout for all displays. * Any display not included will use the default layout. * If a layout would overlap or be otherwise invalid it will be adjusted to a valid layout. * After layout is resolved, an onDisplayChanged event will be triggered. * @since Chrome 53 * @param layouts The layout information, required for all displays except the primary display. * @param callback Empty function called when the function finishes. To find out whether the function succeeded, runtime.lastError should be queried. */ export function setDisplayLayout(layouts: chrome.system.display.DisplayLayout[]): Promise<void>; /** * Displays the native touch calibration UX for the display with **id** as display id. * This will show an overlay on the screen with required instructions on how to proceed. * The callback will be invoked in case of successful calibraion only. * If the calibration fails, this will throw an error. * @since Chrome 57 * @param id The display's unique identifier. * @param callback Optional callback to inform the caller that the touch calibration has ended. The argument of the callback informs if the calibration was a success or not. */ export function showNativeTouchCalibration(id: string): Promise<boolean>; /** * @requires(CrOS Kiosk app) Chrome OS Kiosk apps only * @since Chrome 65. * @description * Sets the display mode to the specified mirror mode. * Each call resets the state from previous calls. * Calling setDisplayProperties() will fail for the * mirroring destination displays. */ export function setMirrorMode(info: chrome.system.display.MirrorModeInfo | chrome.system.display.MirrorModeInfoMixed): Promise<void>; } declare namespace chromepApi.tabCapture { export interface CaptureStatusChangedEvent extends chrome.events.Event<(info: chrome.tabCapture.CaptureInfo) => void> { } export interface TabCapture { /** * Captures the visible area of the currently active tab. Capture can only be started on the currently active tab after the extension has been invoked. Capture is maintained across page navigations within the tab, and stops when the tab is closed, or the media stream is closed by the extension. * @param options Configures the returned media stream. * @param callback Callback with either the tab capture stream or null. */ capture(options: chrome.tabCapture.CaptureOptions): Promise<MediaStream | null>; /** * Returns a list of tabs that have requested capture or are being captured, i.e. status != stopped and status != error. This allows extensions to inform the user that there is an existing tab capture that would prevent a new tab capture from succeeding (or to prevent redundant requests for the same tab). * @param callback Callback invoked with CaptureInfo[] for captured tabs. */ getCapturedTabs(): Promise<chrome.tabCapture.CaptureInfo[]>; onStatusChanged: CaptureStatusChangedEvent; } } declare namespace chromepApi.tabs { export interface TabHighlightedEvent extends chrome.events.Event<(highlightInfo: chrome.tabs.TabHighlightInfo) => void> { } export interface TabRemovedEvent extends chrome.events.Event<(tabId: number, removeInfo: chrome.tabs.TabRemoveInfo) => void> { } export interface TabUpdatedEvent extends chrome.events.Event<(tabId: number, changeInfo: chrome.tabs.TabChangeInfo, tab: chrome.tabs.Tab) => void> { } export interface TabAttachedEvent extends chrome.events.Event<(tabId: number, attachInfo: chrome.tabs.TabAttachInfo) => void> { } export interface TabMovedEvent extends chrome.events.Event<(tabId: number, moveInfo: chrome.tabs.TabMoveInfo) => void> { } export interface TabDetachedEvent extends chrome.events.Event<(tabId: number, detachInfo: chrome.tabs.TabDetachInfo) => void> { } export interface TabCreatedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> { } export interface TabActivatedEvent extends chrome.events.Event<(activeInfo: chrome.tabs.TabActiveInfo) => void> { } export interface TabReplacedEvent extends chrome.events.Event<(addedTabId: number, removedTabId: number) => void> { } export interface TabSelectedEvent extends chrome.events.Event<(tabId: number, selectInfo: chrome.tabs.TabWindowInfo) => void> { } export interface TabZoomChangeEvent extends chrome.events.Event<(ZoomChangeInfo: chrome.tabs.ZoomChangeInfo) => void> { } export interface Tabs { /** * Injects JavaScript code into a page. For details, see the programmatic injection section of the content scripts doc. * @param details Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. * @param callback Optional. Called after all the JavaScript has been executed. * Parameter result: The result of the script in every injected frame. */ executeScript(details: chrome.tabs.InjectDetails): Promise<any[]>; /** * Injects JavaScript code into a page. For details, see the programmatic injection section of the content scripts doc. * @param tabId Optional. The ID of the tab in which to run the script; defaults to the active tab of the current window. * @param details Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. * @param callback Optional. Called after all the JavaScript has been executed. * Parameter result: The result of the script in every injected frame. */ executeScript(tabId: number, details: chrome.tabs.InjectDetails): Promise<any[]>; /** Retrieves details about the specified tab. */ get(tabId: number): Promise<chrome.tabs.Tab>; /** * Gets details about all tabs in the specified window. * @deprecated since Chrome 33. Please use tabs.query {windowId: windowId}. */ getAllInWindow(): Promise<chrome.tabs.Tab>; /** * Gets details about all tabs in the specified window. * @deprecated since Chrome 33. Please use tabs.query {windowId: windowId}. * @param windowId Optional. Defaults to the current window. */ getAllInWindow(windowId: number): Promise<chrome.tabs.Tab>; /** Gets the tab that this script call is being made from. May be undefined if called from a non-tab context (for example: a background page or popup view). */ getCurrent(): Promise<chrome.tabs.Tab>; /** * Gets the tab that is selected in the specified window. * @deprecated since Chrome 33. Please use tabs.query {active: true}. */ getSelected(): Promise<chrome.tabs.Tab>; /** * Gets the tab that is selected in the specified window. * @deprecated since Chrome 33. Please use tabs.query {active: true}. * @param windowId Optional. Defaults to the current window. */ getSelected(windowId: number): Promise<chrome.tabs.Tab>; /** * Creates a new tab. * @param callback Optional. * Parameter tab: Details about the created tab. Will contain the ID of the new tab. */ create(createProperties: chrome.tabs.CreateProperties): Promise<chrome.tabs.Tab>; /** * Moves one or more tabs to a new position within its window, or to a new window. Note that tabs can only be moved to and from normal (window.type === "normal") windows. * @param tabId The tab to move. * @param callback Optional. * Parameter tab: Details about the moved tab. */ move(tabId: number, moveProperties: chrome.tabs.MoveProperties): Promise<chrome.tabs.Tab>; /** * Moves one or more tabs to a new position within its window, or to a new window. Note that tabs can only be moved to and from normal (window.type === "normal") windows. * @param tabIds The tabs to move. * @param callback Optional. * Parameter tabs: Details about the moved tabs. */ move(tabIds: number[], moveProperties: chrome.tabs.MoveProperties): Promise<chrome.tabs.Tab[]>; /** * Modifies the properties of a tab. Properties that are not specified in updateProperties are not modified. * @param callback Optional. * Optional parameter tab: Details about the updated tab. The tabs.Tab object doesn't contain url, title and favIconUrl if the "tabs" permission has not been requested. */ update(updateProperties: chrome.tabs.UpdateProperties): Promise<chrome.tabs.Tab>; /** * Modifies the properties of a tab. Properties that are not specified in updateProperties are not modified. * @param tabId Defaults to the selected tab of the current window. * @param callback Optional. * Optional parameter tab: Details about the updated tab. The tabs.Tab object doesn't contain url, title and favIconUrl if the "tabs" permission has not been requested. */ update(tabId: number, updateProperties: chrome.tabs.UpdateProperties): Promise<chrome.tabs.Tab>; /** * Closes a tab. * @param tabId The tab to close. */ remove(tabId: number): Promise<void>; /** * Closes several tabs. * @param tabIds The list of tabs to close. */ remove(tabIds: number[]): Promise<void>; /** * Captures the visible area of the currently active tab in the specified window. You must have <all_urls> permission to use this method. * @param callback * Parameter dataUrl: A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. */ captureVisibleTab(): Promise<string>; /** * Captures the visible area of the currently active tab in the specified window. You must have <all_urls> permission to use this method. * @param windowId Optional. The target window. Defaults to the current window. * @param callback * Parameter dataUrl: A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. */ captureVisibleTab(windowId: number): Promise<string>; /** * Captures the visible area of the currently active tab in the specified window. You must have <all_urls> permission to use this method. * @param options Optional. Details about the format and quality of an image. * @param callback * Parameter dataUrl: A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. */ captureVisibleTab(options: chrome.tabs.CaptureVisibleTabOptions): Promise<string>; /** * Captures the visible area of the currently active tab in the specified window. You must have <all_urls> permission to use this method. * @param windowId Optional. The target window. Defaults to the current window. * @param options Optional. Details about the format and quality of an image. * @param callback * Parameter dataUrl: A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. */ captureVisibleTab(windowId: number, options: chrome.tabs.CaptureVisibleTabOptions): Promise<string>; /** * Reload a tab. * @since Chrome 16. * @param tabId The ID of the tab to reload; defaults to the selected tab of the current window. */ reload(tabId: number, reloadProperties?: chrome.tabs.ReloadProperties): Promise<void>; /** * Reload the selected tab of the current window. * @since Chrome 16. */ reload(reloadProperties: chrome.tabs.ReloadProperties): Promise<void>; /** * Reload the selected tab of the current window. * @since Chrome 16. */ reload(): Promise<void>; /** * Duplicates a tab. * @since Chrome 23. * @param tabId The ID of the tab which is to be duplicated. * @param callback Optional. * Optional parameter tab: Details about the duplicated tab. The tabs.Tab object doesn't contain url, title and favIconUrl if the "tabs" permission has not been requested. */ duplicate(tabId: number): Promise<chrome.tabs.Tab>; /** * Injects CSS into a page. For details, see the programmatic injection section of the content scripts doc. * @param details Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. * @param callback Optional. Called when all the CSS has been inserted. */ insertCSS(details: chrome.tabs.InjectDetails): Promise<void>; /** * Injects CSS into a page. For details, see the programmatic injection section of the content scripts doc. * @param tabId Optional. The ID of the tab in which to insert the CSS; defaults to the active tab of the current window. * @param details Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. * @param callback Optional. Called when all the CSS has been inserted. */ insertCSS(tabId: number, details: chrome.tabs.InjectDetails): Promise<void>; /** * Highlights the given tabs. * @since Chrome 16. * @param callback Optional. * Parameter window: Contains details about the window whose tabs were highlighted. */ highlight(highlightInfo: chrome.tabs.HighlightInfo): Promise<chrome.windows.Window>; /** * Gets all tabs that have the specified properties, or all tabs if no properties are specified. * @since Chrome 16. */ query(queryInfo: chrome.tabs.QueryInfo): Promise<chrome.tabs.Tab[]>; /** * Detects the primary language of the content in a tab. * @param callback * Parameter language: An ISO language code such as en or fr. For a complete list of languages supported by this method, see kLanguageInfoTable. The 2nd to 4th columns will be checked and the first non-NULL value will be returned except for Simplified Chinese for which zh-CN will be returned. For an unknown language, und will be returned. */ detectLanguage(): Promise<string>; /** * Detects the primary language of the content in a tab. * @param tabId Optional. Defaults to the active tab of the current window. * @param callback * Parameter language: An ISO language code such as en or fr. For a complete list of languages supported by this method, see kLanguageInfoTable. The 2nd to 4th columns will be checked and the first non-NULL value will be returned except for Simplified Chinese for which zh-CN will be returned. For an unknown language, und will be returned. */ detectLanguage(tabId: number): Promise<string>; /** * Zooms a specified tab. * @since Chrome 42. * @param zoomFactor The new zoom factor. Use a value of 0 here to set the tab to its current default zoom factor. Values greater than zero specify a (possibly non-default) zoom factor for the tab. * @param callback Optional. Called after the zoom factor has been changed. */ setZoom(zoomFactor: number): Promise<void>; /** * Zooms a specified tab. * @since Chrome 42. * @param tabId Optional. The ID of the tab to zoom; defaults to the active tab of the current window. * @param zoomFactor The new zoom factor. Use a value of 0 here to set the tab to its current default zoom factor. Values greater than zero specify a (possibly non-default) zoom factor for the tab. * @param callback Optional. Called after the zoom factor has been changed. */ setZoom(tabId: number, zoomFactor: number): Promise<void>; /** * Gets the current zoom factor of a specified tab. * @since Chrome 42. * @param callback Called with the tab's current zoom factor after it has been fetched. * Parameter zoomFactor: The tab's current zoom factor. */ getZoom(): Promise<number>; /** * Gets the current zoom factor of a specified tab. * @since Chrome 42. * @param tabId Optional. The ID of the tab to get the current zoom factor from; defaults to the active tab of the current window. * @param callback Called with the tab's current zoom factor after it has been fetched. * Parameter zoomFactor: The tab's current zoom factor. */ getZoom(tabId: number): Promise<number>; /** * Sets the zoom settings for a specified tab, which define how zoom changes are handled. These settings are reset to defaults upon navigating the tab. * @since Chrome 42. * @param zoomSettings Defines how zoom changes are handled and at what scope. * @param callback Optional. Called after the zoom settings have been changed. */ setZoomSettings(zoomSettings: chrome.tabs.ZoomSettings): Promise<void>; /** * Sets the zoom settings for a specified tab, which define how zoom changes are handled. These settings are reset to defaults upon navigating the tab. * @since Chrome 42. * @param tabId Optional. The ID of the tab to change the zoom settings for; defaults to the active tab of the current window. * @param zoomSettings Defines how zoom changes are handled and at what scope. * @param callback Optional. Called after the zoom settings have been changed. */ setZoomSettings(tabId: number, zoomSettings: chrome.tabs.ZoomSettings): Promise<void>; /** * Gets the current zoom settings of a specified tab. * @since Chrome 42. * @param callback Called with the tab's current zoom settings. * Paramater zoomSettings: The tab's current zoom settings. */ getZoomSettings(): Promise<chrome.tabs.ZoomSettings>; /** * Gets the current zoom settings of a specified tab. * @since Chrome 42. * @param tabId Optional. The ID of the tab to get the current zoom settings from; defaults to the active tab of the current window. * @param callback Called with the tab's current zoom settings. * Paramater zoomSettings: The tab's current zoom settings. */ getZoomSettings(tabId: number): Promise<chrome.tabs.ZoomSettings>; /** * Discards a tab from memory. Discarded tabs are still visible on the tab strip and are reloaded when activated. * @since Chrome 54. * @param tabId Optional. The ID of the tab to be discarded. If specified, the tab will be discarded unless it's active or already discarded. If omitted, the browser will discard the least important tab. This can fail if no discardable tabs exist. * @param callback Called after the operation is completed. */ discard(tabId?: number): Promise<chrome.tabs.Tab>; onHighlighted: TabHighlightedEvent; onRemoved: TabRemovedEvent; onUpdated: TabUpdatedEvent; onAttached: TabAttachedEvent; onMoved: TabMovedEvent; onDetached: TabDetachedEvent; onCreated: TabCreatedEvent; onActivated: TabActivatedEvent; onReplaced: TabReplacedEvent; onSelectionChanged: TabSelectedEvent; onActiveChanged: TabSelectedEvent; onHighlightChanged: TabHighlightedEvent; onZoomChange: TabZoomChangeEvent; } } declare namespace chromepApi.topSites { export interface TopSites { /** Gets a list of top sites. */ get(): Promise<chrome.topSites.MostVisitedURL[]>; } } declare namespace chromepApi.tts { export interface Tts { /** Checks whether the engine is currently speaking. On Mac OS X, the result is true whenever the system speech engine is speaking, even if the speech wasn't initiated by Chrome. */ isSpeaking(): Promise<boolean>; /** Gets an array of all available voices. */ getVoices(): Promise<chrome.tts.TtsVoice[]>; /** * Speaks text using a text-to-speech engine. * @param utterance The text to speak, either plain text or a complete, well-formed SSML document. Speech engines that do not support SSML will strip away the tags and speak the text. The maximum length of the text is 32,768 characters. * @param callback Optional. Called right away, before speech finishes. Check chrome.runtime.lastError to make sure there were no errors. Use options.onEvent to get more detailed feedback. */ speak(utterance: string): Promise<void>; /** * Speaks text using a text-to-speech engine. * @param utterance The text to speak, either plain text or a complete, well-formed SSML document. Speech engines that do not support SSML will strip away the tags and speak the text. The maximum length of the text is 32,768 characters. * @param options Optional. The speech options. * @param callback Optional. Called right away, before speech finishes. Check chrome.runtime.lastError to make sure there were no errors. Use options.onEvent to get more detailed feedback. */ speak(utterance: string, options: chrome.tts.SpeakOptions): Promise<void>; } } declare namespace chromepApi.ttsEngine { export interface TtsEngineSpeakEvent extends chrome.events.Event<(utterance: string, options: chrome.ttsEngine.SpeakOptions, sendTtsEvent: (event: chrome.tts.TtsEvent) => void) => void> { } export interface TtsEngine { onSpeak: TtsEngineSpeakEvent; } } declare namespace chromepApi.types { export interface Types { } } declare namespace chromepApi.vpnProvider { export interface VpnPlatformMessageEvent extends chrome.events.Event<(id: string, message: string, error: string) => void> { } export interface VpnPacketReceptionEvent extends chrome.events.Event<(data: ArrayBuffer) => void> { } export interface VpnConfigRemovalEvent extends chrome.events.Event<(id: string) => void> { } export interface VpnConfigCreationEvent extends chrome.events.Event<(id: string, name: string, data: Object) => void> { } export interface VpnUiEvent extends chrome.events.Event<(event: string, id?: string) => void> { } export interface VpnProvider { /** * Creates a new VPN configuration that persists across multiple login sessions of the user. * @param name The name of the VPN configuration. * @param callback Called when the configuration is created or if there is an error. * Parameter id: A unique ID for the created configuration, empty string on failure. */ createConfig(name: string): Promise<string>; /** * Destroys a VPN configuration created by the extension. * @param id ID of the VPN configuration to destroy. * @param callback Optional. Called when the configuration is destroyed or if there is an error. */ destroyConfig(id: string): Promise<void>; /** * Sets the parameters for the VPN session. This should be called immediately after "connected" is received from the platform. This will succeed only when the VPN session is owned by the extension. * @param parameters The parameters for the VPN session. * @param callback Called when the parameters are set or if there is an error. */ setParameters(parameters: chrome.vpnProvider.VpnSessionParameters): Promise<void>; /** * Sends an IP packet through the tunnel created for the VPN session. This will succeed only when the VPN session is owned by the extension. * @param data The IP packet to be sent to the platform. * @param callback Optional. Called when the packet is sent or if there is an error. */ sendPacket(data: ArrayBuffer): Promise<void>; /** * Notifies the VPN session state to the platform. This will succeed only when the VPN session is owned by the extension. * @param state The VPN session state of the VPN client. * connected: VPN connection was successful. * failure: VPN connection failed. * @param callback Optional. Called when the notification is complete or if there is an error. */ notifyConnectionStateChanged(state: string): Promise<void>; onPlatformMessage: VpnPlatformMessageEvent; onPacketReceived: VpnPacketReceptionEvent; onConfigRemoved: VpnConfigRemovalEvent; onConfigCreated: VpnConfigCreationEvent; onUIEvent: VpnUiEvent; } } declare namespace chromepApi.wallpaper { export interface Wallpaper { /** * Sets wallpaper to the image at url or wallpaperData with the specified layout * @param callback * Optional parameter thumbnail: The jpeg encoded wallpaper thumbnail. It is generated by resizing the wallpaper to 128x60. */ setWallpaper(details: chrome.wallpaper.WallpaperDetails): Promise<any>; } } declare namespace chromepApi.webNavigation { export interface WebNavigationTransitionalEvent extends chrome.webNavigation.WebNavigationEvent<chrome.webNavigation.WebNavigationTransitionCallbackDetails> { } export interface WebNavigationFramedEvent extends chrome.webNavigation.WebNavigationEvent<chrome.webNavigation.WebNavigationFramedCallbackDetails> { } export interface WebNavigationSourceEvent extends chrome.webNavigation.WebNavigationEvent<chrome.webNavigation.WebNavigationSourceCallbackDetails> { } export interface WebNavigationReplacementEvent extends chrome.webNavigation.WebNavigationEvent<chrome.webNavigation.WebNavigationReplacementCallbackDetails> { } export interface WebNavigationParentedEvent extends chrome.webNavigation.WebNavigationEvent<chrome.webNavigation.WebNavigationParentedCallbackDetails> { } export interface WebNavigationFramedErrorEvent extends chrome.webNavigation.WebNavigationEvent<chrome.webNavigation.WebNavigationFramedErrorCallbackDetails> { } export interface WebNavigation { /** * Retrieves information about the given frame. A frame refers to an <iframe> or a <frame> of a web page and is identified by a tab ID and a frame ID. * @param details Information about the frame to retrieve information about. * @param callback * Optional parameter details: Information about the requested frame, null if the specified frame ID and/or tab ID are invalid. */ getFrame(details: chrome.webNavigation.GetFrameDetails): Promise<chrome.webNavigation.GetFrameResultDetails | null>; /** * Retrieves information about all frames of a given tab. * @param details Information about the tab to retrieve all frames from. * @param callback * Optional parameter details: A list of frames in the given tab, null if the specified tab ID is invalid. */ getAllFrames(details: chrome.webNavigation.GetAllFrameDetails): Promise<chrome.webNavigation.GetAllFrameResultDetails[] | null>; onReferenceFragmentUpdated: WebNavigationTransitionalEvent; onCompleted: WebNavigationFramedEvent; onHistoryStateUpdated: WebNavigationTransitionalEvent; onCreatedNavigationTarget: WebNavigationSourceEvent; onTabReplaced: WebNavigationReplacementEvent; onBeforeNavigate: WebNavigationParentedEvent; onCommitted: WebNavigationTransitionalEvent; onDOMContentLoaded: WebNavigationFramedEvent; onErrorOccurred: WebNavigationFramedErrorEvent; } } declare namespace chromepApi.webRequest { export interface WebRequestBodyEvent extends chrome.events.Event<(details: chrome.webRequest.WebRequestBodyDetails) => void> { } export interface WebRequestHeadersEvent extends chrome.events.Event<(details: chrome.webRequest.WebRequestHeadersDetails) => void> { } export interface WebResponseHeadersEvent extends chrome.webRequest._WebResponseHeadersEvent<chrome.webRequest.WebResponseHeadersDetails> { } export interface WebAuthenticationChallengeEvent extends chrome.events.Event<(details: chrome.webRequest.WebAuthenticationChallengeDetails, callback?: (response: chrome.webRequest.BlockingResponse) => void) => void> { } export interface WebResponseCacheEvent extends chrome.webRequest._WebResponseHeadersEvent<chrome.webRequest.WebResponseCacheDetails> { } export interface WebRedirectionResponseEvent extends chrome.webRequest._WebResponseHeadersEvent<chrome.webRequest.WebRedirectionResponseDetails> { } export interface WebResponseErrorEvent extends chrome.webRequest._WebResponseHeadersEvent<chrome.webRequest.WebResponseErrorDetails> { } export interface WebRequest { /** Needs to be called when the behavior of the webRequest handlers has changed to prevent incorrect handling due to caching. This function call is expensive. Don't call it often. */ handlerBehaviorChanged(): Promise<void>; onBeforeRequest: WebRequestBodyEvent; onBeforeSendHeaders: WebRequestHeadersEvent; onSendHeaders: WebRequestHeadersEvent; onHeadersReceived: WebResponseHeadersEvent; onAuthRequired: WebAuthenticationChallengeEvent; onResponseStarted: WebResponseCacheEvent; onBeforeRedirect: WebRedirectionResponseEvent; onCompleted: WebResponseCacheEvent; onErrorOccurred: WebResponseErrorEvent; } } declare namespace chromepApi.webstore { export interface InstallationStageEvent extends chrome.events.Event<(stage: string) => void> { } export interface DownloadProgressEvent extends chrome.events.Event<(percentDownloaded: number) => void> { } export interface Webstore { onInstallStageChanged: InstallationStageEvent; onDownloadProgress: DownloadProgressEvent; } } declare namespace chromepApi.windows { export interface WindowIdEvent extends chrome.events.Event<(windowId: number, filters?: chrome.windows.WindowEventFilter) => void> { } export interface WindowReferenceEvent extends chrome.events.Event<(window: chrome.windows.Window, filters?: chrome.windows.WindowEventFilter) => void> { } export interface Windows { /** Gets details about a window. */ get(windowId: number): Promise<chrome.windows.Window>; /** * Gets details about a window. * @since Chrome 18. */ get(windowId: number, getInfo: chrome.windows.GetInfo): Promise<chrome.windows.Window>; /** * Gets the current window. */ getCurrent(): Promise<chrome.windows.Window>; /** * Gets the current window. * @since Chrome 18. */ getCurrent(getInfo: chrome.windows.GetInfo): Promise<chrome.windows.Window>; /** * Creates (opens) a new browser with any optional sizing, position or default URL provided. * @param callback * Optional parameter window: Contains details about the created window. */ create(): Promise<chrome.windows.Window>; /** * Creates (opens) a new browser with any optional sizing, position or default URL provided. * @param callback * Optional parameter window: Contains details about the created window. */ create(createData: chrome.windows.CreateData): Promise<chrome.windows.Window>; /** * Gets all windows. */ getAll(): Promise<chrome.windows.Window[]>; /** * Gets all windows. * @since Chrome 18. */ getAll(getInfo: chrome.windows.GetInfo): Promise<chrome.windows.Window[]>; /** Updates the properties of a window. Specify only the properties that you want to change; unspecified properties will be left unchanged. */ update(windowId: number, updateInfo: chrome.windows.UpdateInfo): Promise<chrome.windows.Window>; /** Removes (closes) a window, and all the tabs inside it. */ remove(windowId: number): Promise<void>; /** * Gets the window that was most recently focused — typically the window 'on top'. */ getLastFocused(): Promise<chrome.windows.Window>; /** * Gets the window that was most recently focused — typically the window 'on top'. * @since Chrome 18. */ getLastFocused(getInfo: chrome.windows.GetInfo): Promise<chrome.windows.Window>; onRemoved: WindowIdEvent; onCreated: WindowReferenceEvent; onFocusChanged: WindowIdEvent; } } /// <reference types="filesystem" /> /// <reference types="chrome" />
the_stack
// The MIT License (MIT) // // vs-deploy (https://github.com/mkloubert/vs-deploy) // Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. import * as deploy_contracts from './contracts'; import * as deploy_helpers from './helpers'; import * as deploy_objects from './objects'; import * as deploy_res_css from './resources/css'; import * as deploy_res_html from './resources/html'; import * as deploy_res_javascript from './resources/javascript'; import * as deploy_urls from './urls'; import * as deploy_values from './values'; import * as FS from 'fs'; import * as HTTP from 'http'; import * as HTTPs from 'https'; import * as i18 from './i18'; import * as Marked from 'marked'; const MergeDeep = require('merge-deep'); import * as Path from 'path'; import * as URL from 'url'; import * as vs_deploy from './deploy'; import * as vscode from 'vscode'; import * as Workflows from 'node-workflows'; interface ActionQuickPickItem extends vscode.QuickPickItem { action: () => any; icon: string; itemOrder?: any; sortOrder: any; } type BrowserContentProvider = () => any; interface TemplateItemWithName extends deploy_contracts.TemplateItem { name?: string; } interface TemplateStackItem { items: TemplateItemWithName[]; parent?: TemplateItemWithName; } const REGEX_HTTP_URL = new RegExp("^([\\s]*)(https?:\\/\\/)", 'i'); const REGEX_SPECIAL_PROPERTY = new RegExp("^(\\$)(.*)(\\$)$", 'i'); function checkForExtensionVersion(requiredVersion: string, packageFile: deploy_contracts.PackageFile): boolean { requiredVersion = deploy_helpers.toStringSafe(requiredVersion).trim(); if ('' !== requiredVersion) { if (packageFile) { // packageFile.version >= requiredVersion return deploy_helpers.compareVersions(packageFile.version, requiredVersion) >= 0; } return false; } return true; } /** * Checks for new versions * of the official template repositories. */ export function checkOfficialRepositoryVersions() { let me: vs_deploy.Deployer = this; let lastUrl: string; let logError = (nr: number, err: any): void => { let errCat = `templates.checkOfficialRepositoryVersion(${nr})`; if (!deploy_helpers.isNullUndefinedOrEmptyString(lastUrl)) { errCat += `(${lastUrl})`; } deploy_helpers.log(i18.t('errors.withCategory', errCat, err)); }; let wf = Workflows.create(); deploy_urls.OFFICIAL_TEMPLATE_REPOSITORIES.forEach(u => { wf.next((ctx) => { lastUrl = u; return loadFromSource(deploy_urls.OFFICIAL_TEMPLATE_REPOSITORIES[0]).then((data) => { try { const KEY_LAST_KNOWN_VERSION = 'vsdLastKnownTemplateRepoVersion'; let downloadedList: deploy_contracts.TemplateItemList = JSON.parse(data.toString('utf8')); if (downloadedList) { let version = deploy_helpers.normalizeString(downloadedList['$version$']); if ('' !== version) { let updateLastVersion = true; try { let lastVersion = deploy_helpers.normalizeString(me.context.globalState.get(KEY_LAST_KNOWN_VERSION, '')); if ('' === lastVersion) { lastVersion = '0.0.0'; } if (deploy_helpers.compareVersions(version, lastVersion) > 0) { ctx.finish(); let msg = i18.t('templates.officialRepositories.newAvailable'); // [BUTTON] open templates let openBtn: deploy_contracts.PopupButton = new deploy_objects.SimplePopupButton(); openBtn.action = () => { vscode.commands.executeCommand('extension.deploy.openTemplate').then(() => { }, (err) => { logError(6, err); // could not open list of templates }); }; openBtn.title = i18.t('templates.officialRepositories.openTemplates'); vscode.window.showInformationMessage('[vs-deploy] ' + msg, openBtn).then((btn) => { try { if (btn) { btn.action(); } } catch (e) { logError(5, e); // button action failed } }, (err) => { logError(4, err); // could not show popup }); } } finally { if (updateLastVersion) { me.context.globalState.update(KEY_LAST_KNOWN_VERSION, version).then(() => { }, (err) => { logError(3, err); // update error }); } } } } } catch (e) { logError(2, e); // could not load memento value } }); }); }); wf.start().then(() => { }).catch((err) => { logError(1, err); // "global" error }); } function extractTemplateItems(list: deploy_contracts.TemplateItemList, packageFile: deploy_contracts.PackageFile): TemplateItemWithName[] { let items: TemplateItemWithName[] = []; if (list) { if (checkForExtensionVersion(<any>list['$requires$'], packageFile)) { for (let name in list) { if (REGEX_SPECIAL_PROPERTY.test(name)) { continue; // ignore } let i = list[name]; let iwn: TemplateItemWithName = deploy_helpers.cloneObject(i); if (iwn) { iwn.name = deploy_helpers.toStringSafe(name).trim(); items.push(iwn); } } } } return items.filter(i => i).filter(i => { return checkForExtensionVersion(i.requires, packageFile); }); } function getMarkdownContentProvider(markdown: string, additionalHtmlHeader: string, additionalHtmlFooter: string): BrowserContentProvider { markdown = deploy_helpers.toStringSafe(markdown); additionalHtmlFooter = deploy_helpers.toStringSafe(additionalHtmlFooter); additionalHtmlHeader = deploy_helpers.toStringSafe(additionalHtmlHeader); return () => { let header = deploy_res_html.getContentSync('header_markdown_template.html').toString('utf8'); let footer = deploy_res_html.getContentSync('footer_markdown_template.html').toString('utf8'); let jquery = deploy_res_javascript.getContentSync('jquery.min.js').toString('utf8'); let script = deploy_res_javascript.getContentSync('script.js').toString('utf8'); let highlightJS = deploy_res_javascript.getContentSync('highlight.pack.js').toString('utf8'); let css_highlightJS_css = deploy_res_css.getContentSync('highlight.darkula.css').toString('utf8'); let css_highlightJS_css_default = deploy_res_css.getContentSync('highlight.default.css').toString('utf8'); let css = deploy_res_css.getContentSync('styles.css').toString('utf8'); let html = header + footer; let values: deploy_values.ValueBase[] = []; values.push(new deploy_values.StaticValue({ name: 'vsDeploy-jQuery', value: JSON.stringify(stringToBase64(jquery)), })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-CSS', value: css, })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-highlightjs-CSS', value: css_highlightJS_css, })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-highlightjs-CSS-default', value: css_highlightJS_css_default, })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-highlightjs', value: JSON.stringify(stringToBase64(highlightJS)), })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-content', value: JSON.stringify(stringToBase64(Marked(markdown, { breaks: true, gfm: true, tables: true, }))), })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-header', value: deploy_helpers.toStringSafe(additionalHtmlHeader), })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-footer', value: deploy_helpers.toStringSafe(additionalHtmlFooter), })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-project-page', value: deploy_urls.PROJECT_PAGE, })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-script', value: JSON.stringify(stringToBase64(script)), })); html = deploy_values.replaceWithValues(values, html); return html; }; } function getSourceCodeContentProvider(code: string, mime?: string, additionalHtmlHeader?: string, additionalHtmlFooter?: string): BrowserContentProvider { code = deploy_helpers.toStringSafe(code); mime = deploy_helpers.normalizeString(mime); if ('' === mime) { mime = 'text/plain'; } additionalHtmlFooter = deploy_helpers.toStringSafe(additionalHtmlFooter); additionalHtmlHeader = deploy_helpers.toStringSafe(additionalHtmlHeader); return () => { let header = deploy_res_html.getContentSync('header_simple_template.html').toString('utf8'); let footer = deploy_res_html.getContentSync('footer_simple_template.html').toString('utf8'); let jquery = deploy_res_javascript.getContentSync('jquery.min.js').toString('utf8'); let script = deploy_res_javascript.getContentSync('script.js').toString('utf8'); let highlightJS = deploy_res_javascript.getContentSync('highlight.pack.js').toString('utf8'); let css_highlightJS_css = deploy_res_css.getContentSync('highlight.darkula.css').toString('utf8'); let css_highlightJS_css_default = deploy_res_css.getContentSync('highlight.default.css').toString('utf8'); let css = deploy_res_css.getContentSync('styles.css').toString('utf8'); let html = header + footer; let values: deploy_values.ValueBase[] = []; values.push(new deploy_values.StaticValue({ name: 'vsDeploy-jQuery', value: JSON.stringify(stringToBase64(jquery)), })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-CSS', value: css, })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-highlightjs-CSS', value: css_highlightJS_css, })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-highlightjs-CSS-default', value: css_highlightJS_css_default, })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-highlightjs', value: JSON.stringify(stringToBase64(highlightJS)), })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-code', value: JSON.stringify(stringToBase64(code)), })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-mime', value: JSON.stringify(mime), })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-header', value: deploy_helpers.toStringSafe(additionalHtmlHeader), })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-footer', value: deploy_helpers.toStringSafe(additionalHtmlFooter), })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-project-page', value: deploy_urls.PROJECT_PAGE, })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-script', value: JSON.stringify(stringToBase64(script)), })); html = deploy_values.replaceWithValues(values, html); return html; }; } function loadFromSource(src: string): Promise<Buffer> { return new Promise<Buffer>((resolve, reject) => { deploy_helpers.loadFrom(src).then((result) => { resolve(result.data); }).catch((err) => { reject(err); }); }); } /** * Opens a template. */ export function openTemplate() { let me: vs_deploy.Deployer = this; try { let cfg = me.config; let allowUnparsedDocuments: boolean; let footerFile: string; let headerFile: string; let showDefaults: boolean; let sources: deploy_contracts.TemplateSource[] = []; // normalize to object list if (cfg.templates) { sources = deploy_helpers.asArray<string | deploy_contracts.TemplateSource>(cfg.templates.sources).map(t => { let obj: deploy_contracts.TemplateSource; if ('object' !== typeof t) { if (!deploy_helpers.isEmptyString(t)) { obj = { source: deploy_helpers.toStringSafe(t), }; } } return obj; }).filter(t => t); allowUnparsedDocuments = cfg.templates.allowUnparsedDocuments; showDefaults = cfg.templates.showDefaults; footerFile = me.replaceWithValues(cfg.templates.footer); headerFile = me.replaceWithValues(cfg.templates.header); } else { sources = []; } allowUnparsedDocuments = deploy_helpers.toBooleanSafe(allowUnparsedDocuments); showDefaults = deploy_helpers.toBooleanSafe(showDefaults, true); if (showDefaults) { deploy_urls.OFFICIAL_TEMPLATE_REPOSITORIES.forEach(u => { sources.unshift({ source: u, }); }); } if (sources.length > 0) { let wf = Workflows.create(); // create empty list wf.next((ctx) => { ctx.result = {}; }); // create a merged list // from each source sources.forEach(ts => { wf.next((ctx) => { return new Promise<any>((resolve, reject) => { let completedInvoked = false; let completed = (err: any) => { if (completedInvoked) { return; } completedInvoked = true; if (err) { vscode.window.showErrorMessage(`[vs-deploy]: ${deploy_helpers.toStringSafe(err)}`); } resolve(); }; try { let src = me.replaceWithValues(ts.source); loadFromSource(src).then((data) => { try { let downloadedList: deploy_contracts.TemplateItemList = JSON.parse(data.toString('utf8')); if (downloadedList) { ctx.result = MergeDeep(ctx.result, downloadedList); } completed(null); } catch (e) { completed(e); } }).catch((e) => { completed(e); }); } catch (e) { completed(e); } }); }); }); let allCompleted = (err: any) => { if (err) { vscode.window.showErrorMessage(`[vs-deploy]: ${deploy_helpers.toStringSafe(err)}`); } }; let itemStack: TemplateStackItem[] = []; let showItems: (items: TemplateItemWithName[], parent?: TemplateItemWithName) => void; showItems = (items, parent?) => { try { items = deploy_helpers.cloneObject(items); items = (items || []).filter(i => i); let newStackItem: TemplateStackItem = { items: items, parent: parent, }; let appendStackItem = () => { itemStack.push(newStackItem); }; let createQuickPick = (i: TemplateItemWithName) => { let qp: ActionQuickPickItem; let customIcon = deploy_helpers.toStringSafe(i.icon).trim(); let detail: string; let description: string; let type = deploy_helpers.normalizeString(i.type); if ('' === type) { if (!deploy_helpers.isNullOrUndefined(i['children'])) { type = 'c'; // category } else { type = 'f'; // file } } switch (type) { case 'f': case 'file': detail = deploy_helpers.toStringSafe((<deploy_contracts.TemplateFile>i).source).trim(); qp = { icon: '' === customIcon ? 'file-code' : customIcon, label: deploy_helpers.toStringSafe(i.name), description: deploy_helpers.toStringSafe((<deploy_contracts.TemplateFile>i).description), action: () => { return new Promise<any>((res, rej) => { try { let file = <deploy_contracts.TemplateFile>i; if (deploy_helpers.isEmptyString(file.source)) { res(); } else { deploy_helpers.loadFrom(file.source).then((downloadResult) => { try { let mime = downloadResult.mime; let fileName = deploy_helpers.toStringSafe(downloadResult.name).trim(); if ('' !== fileName) { try { let ext = Path.extname(fileName); switch (ext) { case '.ts': mime = 'typescript'; break; } } catch (e) { deploy_helpers.log(i18.t('errors.withCategory', 'templates.openTemplate.showItems(1)', e)); } } let toBase64 = (str: any): string => { str = deploy_helpers.toStringSafe(str); return (new Buffer(str, 'utf8')).toString('base64'); }; let browserTitle = deploy_helpers.toStringSafe(i.name).trim(); if ('' === browserTitle) { browserTitle = deploy_helpers.toStringSafe(file.source).trim(); } let additionalHtmlHeader: string; let additionalHtmlFooter: string; let getBrowserContent: BrowserContentProvider; switch (mime) { case 'text/x-markdown': // markdown getBrowserContent = getMarkdownContentProvider(downloadResult.data.toString('utf8'), additionalHtmlHeader, additionalHtmlFooter); break; case 'text/html': // HTML if (allowUnparsedDocuments) { if (deploy_helpers.toBooleanSafe(file.isDocument)) { // handle as unparsed HTML document getBrowserContent = () => { return downloadResult.data.toString('utf8'); }; } } break; } let openWorkflow = Workflows.create(); // HTML header openWorkflow.next((ctx) => { return new Promise<any>((res2, rej2) => { if (deploy_helpers.isNullUndefinedOrEmptyString(headerFile)) { res2(); } else { loadFromSource(headerFile).then((header) => { try { res2(header.toString('utf8')); } catch (e) { rej2(e); } }).catch((err) => { rej2(err); }); } }); }); // HTML footer openWorkflow.next((ctx) => { additionalHtmlHeader = ctx.previousValue; return new Promise<any>((res2, rej2) => { if (deploy_helpers.isNullUndefinedOrEmptyString(footerFile)) { res2(); } else { loadFromSource(footerFile).then((footer) => { try { res2(footer.toString('utf8')); } catch (e) { rej2(e); } }).catch((err) => { rej2(err); }); } }); }); // generate content // and open browser openWorkflow.next((ctx) => { additionalHtmlFooter = ctx.previousValue; return new Promise<any>((res2, rej2) => { try { let bcp = getBrowserContent; if (!bcp) { bcp = getSourceCodeContentProvider(downloadResult.data.toString('utf8'), mime, additionalHtmlHeader, additionalHtmlFooter); } Promise.resolve(bcp()).then((h) => { let html = deploy_helpers.toStringSafe(h); deploy_helpers.openHtmlDocument(me.htmlDocuments, html, '[vs-deploy] ' + i18.t('templates.browserTitle', browserTitle)) .then(() => { res(); }) .catch((err) => { rej2(err); }); }).catch((err) => { rej2(err); }); } catch (e) { rej2(e); } }); }); openWorkflow.start().then(() => { res(); }).catch((err) => { rej(err); }); } catch (e) { rej(e); } }).catch((err) => { rej(err); }); } } catch (e) { rej(e); } }); }, sortOrder: 1, }; break; case 'c': case 'cat': case 'category': qp = { icon: '' === customIcon ? 'file-directory' : customIcon, label: deploy_helpers.toStringSafe(i.name), description: '', action: () => { let cat = <deploy_contracts.TemplateCategory>i; appendStackItem(); showItems(extractTemplateItems(cat.children, me.packageFile), cat); }, sortOrder: 0, }; break; case 'r': case 'repo': case 'repository': detail = deploy_helpers.toStringSafe((<deploy_contracts.TemplateRepository>i).source).trim(); qp = { icon: '' === customIcon ? 'database' : customIcon, label: deploy_helpers.toStringSafe(i.name), description: deploy_helpers.toStringSafe((<deploy_contracts.TemplateRepository>i).description), action: () => { let repo = <deploy_contracts.TemplateRepository>i; return new Promise<any>((res, rej) => { try { loadFromSource(repo.source).then((data) => { try { let downloadedList: deploy_contracts.TemplateItemList = JSON.parse(data.toString('utf8')); let downloadedItems: TemplateItemWithName[]; if (downloadedList) { downloadedItems = extractTemplateItems(downloadedList, me.packageFile); } appendStackItem(); showItems(downloadedItems, repo); } catch (e) { rej(e); } }).catch((err) => { rej(err); }); } catch (e) { rej(e); } }); }, sortOrder: 1, }; break; case 'l': case 'link': case 'u': case 'url': detail = deploy_helpers.toStringSafe((<deploy_contracts.TemplateLink>i).source).trim(); qp = { icon: '' === customIcon ? 'link-external' : customIcon, label: deploy_helpers.toStringSafe(i.name), description: deploy_helpers.toStringSafe((<deploy_contracts.TemplateLink>i).description), action: () => { let link = <deploy_contracts.TemplateLink>i; return deploy_helpers.open(deploy_helpers.toStringSafe(link.source)); }, sortOrder: 1, }; break; } if (qp) { // label if (deploy_helpers.isEmptyString(qp.label)) { qp.label = ''; } else { qp.label = me.replaceWithValues(qp.label); } // description if (deploy_helpers.isEmptyString(qp.description)) { qp.description = ''; } else { qp.description = me.replaceWithValues(qp.description); } // detail if (!deploy_helpers.isEmptyString(detail)) { qp.detail = detail; } qp.itemOrder = i.sortOrder; } return qp; }; let quickPicks = items.map(i => createQuickPick(i)).filter(qp => qp); let compareBySortableValue = (x: any, y: any): any => { return deploy_helpers.compareValuesBy(x, y, t => deploy_helpers.isNullOrUndefined(t) ? 0 : t); }; quickPicks = quickPicks.sort((x, y) => { // first sort by 'sortOrder' let comp0 = compareBySortableValue(x.sortOrder, y.sortOrder); if (0 !== comp0) { return comp0; } // then by item order let comp1 = compareBySortableValue(x.itemOrder, y.itemOrder); if (0 !== comp1) { return comp1; } // last but not least: by label return deploy_helpers.compareValuesBy(x, y, t => deploy_helpers.normalizeString(t.label)); }); // publish own template quickPicks.push({ icon: 'cloud-upload', itemOrder: Number.MAX_SAFE_INTEGER, label: i18.t('templates.publishOrRequest.label'), description: '', detail: deploy_urls.PUBLISH_TEMPLATE, sortOrder: Number.MAX_SAFE_INTEGER, action: () => deploy_helpers.open(deploy_urls.PUBLISH_TEMPLATE), }); if (itemStack.length > 0) { quickPicks.unshift({ icon: undefined, itemOrder: Number.MAX_SAFE_INTEGER, label: '..', description: '', sortOrder: Number.MIN_SAFE_INTEGER, action: () => { let stackItem = itemStack.pop(); showItems(stackItem.items, stackItem.parent); }, }); } // apply icons quickPicks.forEach(qp => { if (!deploy_helpers.isNullUndefinedOrEmptyString(qp.icon)) { qp.label = `$(${qp.icon}) ${qp.label}`; } }); let placeholder = i18.t('templates.placeholder'); let itemsForPath = itemStack.map(x => x); if (parent) { itemsForPath.push(newStackItem); } if (itemsForPath.length > 0) { let currentPath = itemsForPath.filter(x => x.parent) .map(x => x.parent.name) .join(' / '); placeholder = i18.t('templates.currentPath', currentPath); } vscode.window.showQuickPick(quickPicks, { placeHolder: placeholder, }).then((qp) => { if (qp) { let action = qp.action; if (!action) { action = () => { }; } try { Promise.resolve(action()).then(() => { allCompleted(null); }, (err) => { allCompleted(err); }); } catch (e) { allCompleted(e); } } else { allCompleted(null); } }, (err) => { allCompleted(err); }); } catch (e) { allCompleted(e); } }; wf.start().then((list: deploy_contracts.TemplateItemList) => { if (checkForExtensionVersion(<any>list['$requires$'], me.packageFile)) { showItems(extractTemplateItems(list, me.packageFile)); } else { let logError = (nr: number, err: any): void => { let errCat = `templates.checkOfficialRepositoryVersion(${nr})`; me.log(i18.t('errors.withCategory', errCat, err)); }; let msg = i18.t('extension.updateRequired'); // [BUTTON] open market place let openBtn: deploy_contracts.PopupButton = new deploy_objects.SimplePopupButton(); openBtn.action = () => { deploy_helpers.open(deploy_urls.MARKET_PLACE).then(() => { }).catch((err) => { logError(3, err); }); }; openBtn.title = i18.t('extension.update'); vscode.window.showWarningMessage('[vs-deploy] ' + msg, openBtn).then((btn) => { try { if (btn) { btn.action(); } } catch (e) { logError(2, e); } }, (err) => { logError(1, err); }); } }).catch((err) => { vscode.window.showErrorMessage(`[vs-deploy]: ${deploy_helpers.toStringSafe(err)}`); }); } else { vscode.window.showWarningMessage(`[vs-deploy]: ${i18.t('templates.noneDefined')}`); } } catch (e) { me.log(i18.t('errors.withCategory', 'templates.openTemplate()', e)); } } function stringToBase64(str: any): string { str = deploy_helpers.toStringSafe(str); return (new Buffer(str, 'utf8')).toString('base64'); }
the_stack
import * as React from 'react'; import {render, screen} from '@testing-library/react'; import {Theme} from '@twilio-paste/theme'; import {CustomizationProvider} from '@twilio-paste/customization'; // @ts-ignore typescript doesn't like js imports import axe from '../../../../../.jest/axe-helper'; import {Heading} from '../src'; describe('Heading', () => { describe('Render', () => { it('should render an H1 at fontSize90', (): void => { render( <Theme.Provider theme="default"> <Heading as="h1" variant="heading10"> This is an H1 </Heading> </Theme.Provider> ); const renderedHeading = screen.getByRole('heading', {level: 1}); expect(renderedHeading).not.toBeNull(); expect(renderedHeading).toHaveStyleRule('margin-bottom', '1.5rem'); expect(renderedHeading).toHaveStyleRule('font-size', '2rem'); expect(renderedHeading).toHaveStyleRule('font-weight', '700'); expect(renderedHeading).toHaveStyleRule('line-height', '2.75rem'); }); it('should render an H2 at fontSize70', (): void => { render( <Theme.Provider theme="default"> <Heading as="h2" variant="heading20"> This is an H2 </Heading> </Theme.Provider> ); const renderedHeading = screen.getByRole('heading', {level: 2}); expect(renderedHeading).not.toBeNull(); expect(renderedHeading).toHaveStyleRule('margin-bottom', '1.25rem'); expect(renderedHeading).toHaveStyleRule('font-size', '1.5rem'); expect(renderedHeading).toHaveStyleRule('font-weight', '700'); expect(renderedHeading).toHaveStyleRule('line-height', '2rem'); }); it('should render an H3 at fontSize60', (): void => { render( <Theme.Provider theme="default"> <Heading as="h3" variant="heading30"> This is an H3 </Heading> </Theme.Provider> ); const renderedHeading = screen.getByRole('heading', {level: 3}); expect(renderedHeading).not.toBeNull(); expect(renderedHeading).toHaveStyleRule('margin-bottom', '1rem'); expect(renderedHeading).toHaveStyleRule('font-size', '1.25rem'); expect(renderedHeading).toHaveStyleRule('font-weight', '700'); expect(renderedHeading).toHaveStyleRule('line-height', '1.75rem'); }); it('should render an H4 at fontSize40', (): void => { render( <Theme.Provider theme="default"> <Heading as="h4" variant="heading40"> This is an H4 </Heading> </Theme.Provider> ); const renderedHeading = screen.getByRole('heading', {level: 4}); expect(renderedHeading).not.toBeNull(); expect(renderedHeading).toHaveStyleRule('margin-bottom', '0.75rem'); expect(renderedHeading).toHaveStyleRule('font-size', '1rem'); expect(renderedHeading).toHaveStyleRule('font-weight', '700'); expect(renderedHeading).toHaveStyleRule('line-height', '1.5rem'); }); it('should render an H5 at fontSize30', (): void => { render( <Theme.Provider theme="default"> <Heading as="h5" variant="heading50"> This is an H5 </Heading> </Theme.Provider> ); const renderedHeading = screen.getByRole('heading', {level: 5}); expect(renderedHeading).not.toBeNull(); expect(renderedHeading).toHaveStyleRule('margin-bottom', '0.5rem'); expect(renderedHeading).toHaveStyleRule('font-size', '0.875rem'); expect(renderedHeading).toHaveStyleRule('font-weight', '700'); expect(renderedHeading).toHaveStyleRule('line-height', '1.25rem'); }); it('should render an H6 at fontSize20', (): void => { render( <Theme.Provider theme="default"> <Heading as="h6" variant="heading60"> This is an H6 </Heading> </Theme.Provider> ); const renderedHeading = screen.getByRole('heading', {level: 6}); expect(renderedHeading).not.toBeNull(); expect(renderedHeading).toHaveStyleRule('margin-bottom', '0.5rem'); expect(renderedHeading).toHaveStyleRule('font-size', '0.75rem'); expect(renderedHeading).toHaveStyleRule('font-weight', '700'); expect(renderedHeading).toHaveStyleRule('line-height', '1.25rem'); }); it('should render an italic H2 at fontSize50', (): void => { render( <Theme.Provider theme="default"> <Heading as="h2" variant="heading20"> <i>This is an italic H2</i> </Heading> </Theme.Provider> ); const renderedHeading = screen.getByRole('heading', {level: 2}); const renderedHeadingIdiomatic = screen.getByText('This is an italic H2').closest('i'); expect(renderedHeading).not.toBeNull(); expect(renderedHeadingIdiomatic).not.toBeNull(); expect(renderedHeading).toHaveStyleRule('margin-bottom', '1.25rem'); expect(renderedHeading).toHaveStyleRule('font-size', '1.5rem'); expect(renderedHeading).toHaveStyleRule('font-weight', '700'); expect(renderedHeading).toHaveStyleRule('line-height', '2rem'); }); it('should render with no margin', (): void => { render( <Theme.Provider theme="default"> <Heading as="h2" marginBottom="space0" variant="heading10"> no margin heading </Heading> </Theme.Provider> ); const renderedHeading = screen.getByRole('heading', {level: 2}); expect(renderedHeading).not.toBeNull(); expect(renderedHeading).toHaveStyleRule('margin-bottom', '0'); }); }); describe('HTML attributes', () => { it('should set a element data attribute for Heading', () => { render( <Heading as="h1" variant="heading10"> heading </Heading> ); expect(screen.getByRole('heading').getAttribute('data-paste-element')).toEqual('HEADING'); }); it('should set a custom element data attribute for Heading', () => { render( <Heading as="h1" variant="heading10" element="foo"> heading </Heading> ); expect(screen.getByRole('heading').getAttribute('data-paste-element')).toEqual('foo'); }); }); describe('Customization', () => { it('should add custom styles to Heading', (): void => { render( <CustomizationProvider baseTheme="default" // @ts-expect-error global test variable theme={TestTheme} elements={{HEADING: {color: 'colorTextWeak', backgroundColor: 'colorBackground'}}} > <Heading as="h1" variant="heading10"> Custom heading </Heading> </CustomizationProvider> ); const renderedHeading = screen.getByRole('heading'); expect(renderedHeading).toHaveStyleRule('background-color', 'rgb(244,244,246)'); expect(renderedHeading).toHaveStyleRule('color', 'rgb(96,107,133)'); }); it('should add custom styles to a Heading variant', (): void => { render( <CustomizationProvider baseTheme="default" // @ts-expect-error global test variable theme={TestTheme} elements={{ HEADING: { color: 'colorTextWeak', backgroundColor: 'colorBackground', variants: { heading20: { color: 'colorTextLink', textDecoration: 'underline', }, }, }, }} > <Heading as="h2" variant="heading20"> Custom heading </Heading> </CustomizationProvider> ); const renderedHeading = screen.getByRole('heading'); expect(renderedHeading).toHaveStyleRule('background-color', 'rgb(244,244,246)'); expect(renderedHeading).toHaveStyleRule('color', 'rgb(2,99,224)'); expect(renderedHeading).toHaveStyleRule('text-decoration', 'underline'); }); it('should add custom styles to Heading with a custom element data attribute', (): void => { render( <CustomizationProvider baseTheme="default" // @ts-expect-error global test variable theme={TestTheme} elements={{foo: {color: 'colorTextWeak', backgroundColor: 'colorBackground'}}} > <Heading as="h1" variant="heading10" element="foo"> Custom heading </Heading> </CustomizationProvider> ); const renderedHeading = screen.getByRole('heading'); expect(renderedHeading).toHaveStyleRule('background-color', 'rgb(244,244,246)'); expect(renderedHeading).toHaveStyleRule('color', 'rgb(96,107,133)'); }); it('should add custom styles to a Heading variant with a custom element data attribute', (): void => { render( <CustomizationProvider baseTheme="default" // @ts-expect-error global test variable theme={TestTheme} elements={{ foo: { color: 'colorTextWeak', backgroundColor: 'colorBackground', variants: { heading20: { color: 'colorTextLink', textDecoration: 'underline', }, }, }, }} > <Heading as="h2" variant="heading20" element="foo"> Custom heading </Heading> </CustomizationProvider> ); const renderedHeading = screen.getByRole('heading'); expect(renderedHeading).toHaveStyleRule('background-color', 'rgb(244,244,246)'); expect(renderedHeading).toHaveStyleRule('color', 'rgb(2,99,224)'); expect(renderedHeading).toHaveStyleRule('text-decoration', 'underline'); }); }); describe('Accessibility', () => { it('should have no accessibility violations', async () => { const {container} = render( <Theme.Provider theme="default"> <Heading as="h1" variant="heading10"> This is an H1 </Heading> <Heading as="h2" variant="heading20"> This is an H2 </Heading> <Heading as="h3" variant="heading30"> This is an H3 </Heading> <Heading as="h4" variant="heading40"> This is an H4 </Heading> <Heading as="h5" variant="heading50"> This is an H5 </Heading> <Heading as="h6" variant="heading60"> This is an H6 </Heading> </Theme.Provider> ); const results = await axe(container); expect(results).toHaveNoViolations(); }); }); });
the_stack
import ChromeDriver from './chrome_driver'; import {StepType, SnapshotSizeSummary, IProgressBar, OperationType, Log} from '../common/interfaces'; import BLeakConfig from './bleak_config'; import {wait} from '../common/util'; import HeapSnapshotParser from './heap_snapshot_parser'; import {InterceptorConfig, default as getInterceptor} from './mitmproxy_interceptor'; import BLeakResults from './bleak_results'; import {HeapGrowthTracker, HeapGraph, toPathTree} from './growth_graph'; import StackFrameConverter from './stack_frame_converter'; import PathToString from './path_to_string'; import NopLog from '../common/nop_log'; type SnapshotCb = (sn: HeapSnapshotParser, log: Log) => Promise<void>; export class OperationState { public results: BLeakResults = null; constructor( public chromeDriver: ChromeDriver, public progressBar: IProgressBar, public config: BLeakConfig) {} } const NEVER = Math.pow(2, 30); abstract class Operation { constructor(private readonly _timeout: number = NEVER) {} // Description of the task that the operation is performing. public abstract description: string; // Returns the size of the operations graph beginning with this node. // Default is 1 (no dependent operations) public size(): number { return 1; } // Returns 'true' if the operation is fulfilled and can be skipped. // Defaults to unskippable. public skip(opSt: OperationState): boolean { return false; } // Runs the operation. Promise is resolved/rejected when completed. public async run(opSt: OperationState): Promise<void> { opSt.progressBar.updateDescription(this.description); if (this.skip(opSt)) { const size = this.size(); for (let i = 0; i < size; i++) { opSt.progressBar.nextOperation(); } return; } if (this._timeout === NEVER) { await this._run(opSt); opSt.progressBar.nextOperation(); return; } return new Promise<void>((resolve, reject) => { const timer = setTimeout(() => { const e = new Error(`Operation timed out.`); this.cancel(e); reject(e); }, this._timeout); this._run(opSt).then(() => { clearTimeout(timer); opSt.progressBar.nextOperation(); resolve(); }).catch((e) => { clearTimeout(timer); reject(e); }); }); } // Called when a running operation is canceled. Operation should exit gracefully. public cancel(e: Error) {} // Internal function that really runs the operation. protected abstract _run(opSt: OperationState): Promise<void>; } class NavigateOperation extends Operation { constructor(timeout: number, private readonly _url: string) { super(timeout); } public get description(): string { return `Navigating to ${this._url}`; } protected _run(opSt: OperationState): Promise<void> { return opSt.progressBar.timeEvent(OperationType.NAVIGATE, () => { return opSt.chromeDriver.navigateTo(this._url); }); } } class CheckOperation extends Operation { private _cancelled = false; constructor(timeout: number, private readonly _stepType: StepType, private readonly _id: number) { super(timeout); } public get description(): string { return `Waiting for ${this._stepType}[${this._id}].check() === true`; } public cancel(e: Error) { this._cancelled = true; } public async _run(opSt: OperationState): Promise<void> { return opSt.progressBar.timeEvent(OperationType.WAIT_FOR_PAGE, async () => { // Wait until either the operation is canceled (timeout) or the check succeeds. while (!this._cancelled) { const success = await opSt.chromeDriver.runCode<boolean>(`typeof(BLeakConfig) !== "undefined" && BLeakConfig.${this._stepType}[${this._id}].check()`); if (success) { return; } await wait(100); } }); } } class NextOperation extends Operation { constructor(timeout: number, private readonly _stepType: StepType, private readonly _id: number) { super(timeout); } public get description(): string { return `Advancing to next state ${this._stepType}[${this._id}].next()`; } public async _run(opSt: OperationState): Promise<void> { return opSt.chromeDriver.runCode<void>(`BLeakConfig.${this._stepType}[${this._id}].next()`); } } class DelayOperation extends Operation { constructor(private readonly _delay: number) { super(); } public get description(): string { return `Waiting ${this._delay} ms before proceeding`; } public _run(opSt: OperationState): Promise<void> { return opSt.progressBar.timeEvent(OperationType.SLEEP, () => { return wait(this._delay); }); } } class TakeHeapSnapshotOperation extends Operation { constructor(timeout: number, private _snapshotCb: SnapshotCb) { super(timeout); } public get description(): string { return `Taking a heap snapshot`; } public async _run(opSt: OperationState): Promise<void> { const sn = opSt.chromeDriver.takeHeapSnapshot(); return this._snapshotCb(sn, opSt.progressBar); } } class ConfigureProxyOperation extends Operation { constructor(private _config: InterceptorConfig) { super(); } public get description(): string { return `Configuring the proxy`; } public async _run(opSt: OperationState): Promise<void> { this._config.log = opSt.progressBar; opSt.chromeDriver.mitmProxy.cb = getInterceptor(this._config); } } function countOperations(sumSoFar: number, next: Operation): number { return sumSoFar + next.size(); } abstract class CompositeOperation extends Operation { protected children: Operation[] = []; private _canceledError: Error = null; public size(): number { return this.children.reduce(countOperations, 1); } public cancel(e: Error): void { this._canceledError = e; } protected async _run(opSt: OperationState): Promise<void> { let promise = Promise.resolve(); let i = 0; const self = this; function runNext(): Promise<void> | void { if (self._canceledError) { throw self._canceledError; } if (i < self.children.length) { return self.children[i++].run(opSt); } } for (let i = 0; i < this.children.length; i++) { promise = promise.then(runNext); } return promise; } } class StepOperation extends CompositeOperation { constructor(config: BLeakConfig, stepType: StepType, id: number) { super(); this.children.push(new CheckOperation(config.timeout, stepType, id)); if (config.postCheckSleep) { this.children.push(new DelayOperation(config.postCheckSleep)); } this.children.push(new NextOperation(config.timeout, stepType, id)); if (config.postNextSleep) { this.children.push(new DelayOperation(config.postNextSleep)); } } public get description() { return ''; } } class InstrumentGrowingPathsOperation extends Operation { public get description() { return `Instrumenting growing objects`; } public _run(opSt: OperationState): Promise<void> { return opSt.chromeDriver.runCode<void>(`window.$$$INSTRUMENT_PATHS$$$(${JSON.stringify(toPathTree(opSt.results.leaks))})`); } } class StepSeriesOperation extends CompositeOperation { constructor(config: BLeakConfig, stepType: StepType) { super(); const steps = config[stepType]; for (let i = 0; i < steps.length; i++) { this.children.push( new StepOperation(config, stepType, i)); } } public get description(): string { return ''; } } class ProgramRunOperation extends CompositeOperation { constructor(config: BLeakConfig, runLogin: boolean, iterations: number, takeInitialSnapshot: boolean, snapshotCb?: SnapshotCb) { super(); this.children.push(new NavigateOperation(config.timeout, config.url)); if (runLogin && config.login.length > 0) { this.children.push( new StepSeriesOperation(config, 'login'), new DelayOperation(config.postLoginSleep), new NavigateOperation(config.timeout, config.url) ); } if (config.setup.length > 0) { this.children.push( new StepSeriesOperation(config, 'setup') ); } if (takeInitialSnapshot && snapshotCb) { this.children.push( // Make sure we're at step 0 before taking the snapshot. new CheckOperation(config.timeout, 'loop', 0)); if (config.postCheckSleep) { this.children.push(new DelayOperation(config.postCheckSleep)); } this.children.push(new TakeHeapSnapshotOperation(config.timeout, snapshotCb)); } for (let i = 0; i < iterations; i++) { this.children.push( new StepSeriesOperation(config, 'loop'), // Make sure we're at step 0 before taking the snapshot. new CheckOperation(config.timeout, 'loop', 0) ); if (config.postCheckSleep) { this.children.push(new DelayOperation(config.postCheckSleep)); } if (snapshotCb) { this.children.push( new TakeHeapSnapshotOperation(config.timeout, snapshotCb) ); } } } public get description() { return 'Running through the program'; } } class FindLeaks extends CompositeOperation { private readonly _growthTracker = new HeapGrowthTracker(); private _heapSnapshotSizeStats: SnapshotSizeSummary[] = []; constructor(config: BLeakConfig, private _snapshotCb: SnapshotCb, private _flushResults: (results: BLeakResults) => void) { super(); this.children.push( new ConfigureProxyOperation({ log: NopLog, rewrite: false, fixes: config.fixedLeaks, disableAllRewrites: false, fixRewriteFunction: config.rewrite, config: config.getBrowserInjection() }), new ProgramRunOperation(config, true, config.iterations, false, async (sn: HeapSnapshotParser, log: Log) => { this._snapshotCb(sn, log); await this._growthTracker.addSnapshot(sn, log); this._heapSnapshotSizeStats.push(this._growthTracker.getGraph().calculateSize()); }) ); } public get description() { return 'Locating leaks'; } public skip(opSt: OperationState): boolean { return !!opSt.results; } protected async _run(opSt: OperationState): Promise<void> { return opSt.progressBar.timeEvent(OperationType.LEAK_IDENTIFICATION_AND_RANKING, async () => { await super._run(opSt); opSt.results = new BLeakResults(this._growthTracker.findLeakPaths(opSt.progressBar), undefined, undefined, this._heapSnapshotSizeStats); this._flushResults(opSt.results); }); } } class GetGrowthStacksOperation extends Operation { constructor(timeout: number) { super(timeout); } public get description() { return 'Retrieving stack traces'; } protected async _run(opSt: OperationState): Promise<void> { return opSt.progressBar.timeEvent(OperationType.GET_GROWTH_STACKS, async () => { const traces = await opSt.chromeDriver.runCode<GrowingStackTraces>(`window.$$$GET_STACK_TRACES$$$()`); const growthStacks = StackFrameConverter.ConvertGrowthStacks(opSt.chromeDriver.mitmProxy, opSt.config.url, opSt.results, traces); opSt.results.leaks.forEach((lr) => { const index = lr.id; const stacks = growthStacks[index] || []; stacks.forEach((s) => { lr.addStackTrace(s); }); }); }); } } class DiagnoseLeaks extends CompositeOperation { constructor(config: BLeakConfig, isLoggedIn: boolean) { super(); this.children.push( new ConfigureProxyOperation({ log: NopLog, rewrite: true, fixes: config.fixedLeaks, config: config.getBrowserInjection(), fixRewriteFunction: config.rewrite }), // Warmup new ProgramRunOperation(config, !isLoggedIn, 1, false), new InstrumentGrowingPathsOperation(config.timeout), new StepSeriesOperation(config, 'loop'), new StepSeriesOperation(config, 'loop'), new GetGrowthStacksOperation(config.timeout) ); } public get description() { return 'Diagnosing leaks'; } public skip(opSt: OperationState): boolean { return opSt.results.leaks.length === 0; } protected async _run(opSt: OperationState): Promise<void> { return opSt.progressBar.timeEvent(OperationType.LEAK_DIAGNOSES, async () => { await super._run(opSt); opSt.results = opSt.results.compact(); }); } } /** * A specific BLeak configuration used during ranking metric evaluation. * Since metrics may share specific configurations, this contains a boolean * indicating which metrics this configuration applies to. */ class RankingEvalConfig { public leakShare: boolean = false; public retainedSize: boolean = false; public transitiveClosureSize: boolean = false; constructor(public readonly fixIds: number[]) {} public metrics(): string { let rv: string[] = []; for (let metric of ['leakShare', 'retainedSize', 'transitiveClosureSize']) { if (this[metric as 'leakShare']) { rv.push(metric); } } return rv.join(', '); } } /** * Given a set of leaks, return a unique key. * @param set */ function leakSetKey(set: number[]): string { // Canonicalize order, then produce string. return set.sort(increasingSort).join(','); } function increasingSort(a: number, b: number): number { return a - b; } class EvaluateRankingMetricProgramRunOperation extends CompositeOperation { private _buffer: SnapshotSizeSummary[] = []; constructor( config: BLeakConfig, private _rankingEvalConfig: RankingEvalConfig, private _runNumber: number, private _flushResults: (results: BLeakResults) => void, snapshotCb?: (ss: HeapSnapshotParser, metric: string, leaksFixed: number, iteration: number) => Promise<void>) { super(); const buffer = this._buffer; async function snapshotReport(sn: HeapSnapshotParser, log: Log): Promise<void> { const g = await HeapGraph.Construct(sn, log); const size = g.calculateSize(); buffer.push(size); } this.children.push( new ConfigureProxyOperation({ log: NopLog, rewrite: false, fixes: _rankingEvalConfig.fixIds, disableAllRewrites: true, fixRewriteFunction: config.rewrite, config: config.getBrowserInjection() }), new ProgramRunOperation(config, false, config.rankingEvaluationIterations, true, (sn, log) => { snapshotCb(sn, this._rankingEvalConfig.metrics(), this._rankingEvalConfig.fixIds.length, this._runNumber); return snapshotReport(sn, log); }) ); } public get description() { return 'Running program in a configuration...' } public skip(opSt: OperationState) { const len = this._rankingEvalConfig.fixIds.length; for (let metric of ['leakShare', 'retainedSize', 'transitiveClosureSize']) { if (this._rankingEvalConfig[metric as 'leakShare']) { const metricStats = opSt.results.rankingEvaluation[metric as 'leakShare']; if (!metricStats) { return false; } const configStats = metricStats[len]; if (!configStats) { return false; } const runStats = configStats[this._runNumber]; if (!runStats) { return false; } } } return true; } protected async _run(opSt: OperationState): Promise<void> { await super._run(opSt); // Update results w/ data from run. ['leakShare', 'retainedSize', 'transitiveClosureSize'].forEach((metric: 'leakShare') => { if (!this._rankingEvalConfig[metric]) { return; } const metricResults = opSt.results.rankingEvaluation[metric]; let configRuns = metricResults[this._rankingEvalConfig.fixIds.length]; if (!configRuns) { configRuns = metricResults[this._rankingEvalConfig.fixIds.length] = []; } configRuns[this._runNumber] = this._buffer.slice(0); }); this._flushResults(opSt.results); } } export class EvaluateRankingMetricsOperation extends CompositeOperation { constructor(config: BLeakConfig, results: BLeakResults, flushResults: (results: BLeakResults) => void, snapshotCb?: (ss: HeapSnapshotParser, metric: string, leaksFixed: number, iteration: number) => Promise<void>) { super(); function getSorter(rankBy: "transitiveClosureSize" | "leakShare" | "retainedSize" | "ownedObjects"): (a: number, b: number) => number { return (a, b) => { return results.leaks[b].scores[rankBy] - results.leaks[a].scores[rankBy]; }; } function fixMapper(leakId: number): number { const str = PathToString(results.leaks[leakId].paths[0]); const fixId = config.fixMap[str]; if (fixId === undefined || fixId === null) { throw new Error(`Unable to find fix ID for ${str}.`); } return fixId; } function removeDupes(unique: number[], fixId: number): number[] { if (unique.indexOf(fixId) === -1) { unique.push(fixId); } return unique; } // Figure out which runs are completed and in the results file, const configsToTest = new Map<string, RankingEvalConfig>(); const leaksById = results.leaks.map((l, i) => i); // Map from metric => list of fixes to apply, in-order. const orders = { 'leakShare': leaksById.sort(getSorter('leakShare')).map(fixMapper).reduce(removeDupes, []), 'retainedSize': leaksById.sort(getSorter('retainedSize')).map(fixMapper).reduce(removeDupes, []), 'transitiveClosureSize': leaksById.sort(getSorter('transitiveClosureSize')).map(fixMapper).reduce(removeDupes, []) }; for (let metric in orders) { if (orders.hasOwnProperty(metric)) { const metricCast = <'leakShare' | 'retainedSize' | 'transitiveClosureSize'> metric; const order = orders[metricCast]; for (let i = 0; i <= order.length; i++) { // Note: When i=0, this is the empty array -- the base case. const configOrder = order.slice(0, i); const key = leakSetKey(configOrder); let config = configsToTest.get(key); if (!config) { config = new RankingEvalConfig(configOrder); configsToTest.set(key, config); } config[metricCast] = true; } } } let configs: RankingEvalConfig[] = []; configsToTest.forEach((config) => { configs.push(config); }); // Now we can make these run! if (config.login) { this.children.push( new ConfigureProxyOperation({ log: NopLog, rewrite: false, fixes: [], disableAllRewrites: true, fixRewriteFunction: config.rewrite, config: config.getBrowserInjection() }), new NavigateOperation(config.timeout, config.url), new StepSeriesOperation(config, 'login'), new DelayOperation(config.postLoginSleep) ); } for (const rankingConfig of configs) { for (let i = 0; i < config.rankingEvaluationRuns; i++) { this.children.push( new EvaluateRankingMetricProgramRunOperation( config, rankingConfig, i, flushResults, snapshotCb) ); } } } public get description() { return 'Evaluating ranking metrics'; } public skip(opSt: OperationState) { if (!opSt.results.leaks || opSt.results.leaks.length < 2) { opSt.progressBar.log(`Unable to evaluate ranking metrics: BLeak results file does not contain more than 2 leak roots.`); return true; } return false; } } export class FindAndDiagnoseLeaks extends CompositeOperation { constructor(config: BLeakConfig, flushResults: (results: BLeakResults) => void, snapshotCb: SnapshotCb) { super(); this.children.push( new FindLeaks(config, snapshotCb, flushResults), new DiagnoseLeaks(config, true) ); } public get description() { return "Locating and diagnosing leaks"; } }
the_stack
import { debuglog as dlog } from "./util" import { ByteStr, strings } from "./bytestr" import { Num } from "./num" import { SInt64, UInt64 } from "./int64" import { NoPos } from "./pos" import { Type, BasicType, t_nil } from "./types" import * as utf8 from "./utf8" import * as ast from "./ast" import * as sexpr from "./sexpr" import { Package, File, Node, } from "./ast" function getFilledBuffer(ch :string, n :int) { let b = new Uint8Array(n) b.fill(ch.charCodeAt(0)) } const char = (s :string) => s.charCodeAt(0) const SP = char(" ") const LF = char("\n") const HYPHEN = char("-") const RPAREN = char(")") const linestr = "\n " interface Scope { } class Encoder1 implements ast.Encoder1 { buf = "" stack :Scope[] = [] types = new Map<Type,string>() write(s :string) { this.buf += s } newline() { this.write(linestr.substr(0, 1 + (this.stack.length * 2))) } stackPush() { this.stack.push({}) } stackPop() :Scope { assert(this.stack.length > 0) return this.stack.pop()! } startNode(n :Node) { this.newline() this.write("(" + n.constructor.name) this.stackPush() } endNode() { this.stackPop() this.write(")") } nullNode() { this.newline() this.write("null") } encodeValue(v :any) :string { if (v === null || v === undefined) { return "null" } if (v instanceof Type) { let typeid = this.types.get(v) if (typeid === undefined) { if (v instanceof BasicType) { // basic types have good, well-recognized names like "i32" typeid = String(v) } else { typeid = "t" + this.types.size } this.types.set(v, typeid) } return typeid } if (v instanceof Array) { return "[" + v.map(v2 => this.encodeValue(v2)).join(" ") + "]" } if (typeof v == "object") { if (v instanceof Uint8Array) { v = utf8.decodeToString(v) } else { v = String(v) } } if (typeof v == "string") { v = JSON.stringify(v.toString()) } return String(v) } writeField(name :string, v :any) { this.write(` [${name}`) this.write(" " + this.encodeValue(v)) this.write(`]`) } writeGroup(name :string, cont: ()=>any) { this.newline() this.write("(" + name) this.stackPush() cont() this.stackPop() this.write(")") } writeMetadata() { // write metadata to header let buf = this.buf this.buf = "" this.writeGroup("meta", () => { this.newline() this.write(`(version ${VERSION} ${VERSION_TAG})`) this.writeGroup("types", () => this.writeTypes()) }) this.buf += buf } writeTypes() { // sort types by name a-z let types = Array.from(this.types).sort((a, b) => a[1] < b[1] ? -1 : b[1] < a[1] ? 1 : 0 ) for (let [t, typeid] of types) { this.newline() this.write(`(${typeid} ${t.constructor.name} ${JSON.stringify(t.toString())}`) // TODO: write type this.write(`)`) } } } class NodeDecoder implements ast.Decoder { _props :Map<string,sexpr.Value> _children :(Node|null)[] _getType :(id:string)=>Type|null init(props :Map<string,sexpr.Value>, children :(Node|null)[], getType :(id:string)=>Type|null) { this._props = props this._children = children this._getType = getType } // field access that throws num(name :string) :Num { let v = this.maybeNum(name) if (v === null) { throw new Error(`expected Num for field ${name}`) } return v } num32(name :string) :number { let v = this.maybeNum32(name) if (v === null) { throw new Error(`expected number for field ${name}`) } return v } int32(name :string) :int { let v = this.maybeInt32(name) if (v === null) { throw new Error(`expected int for field ${name}`) } return v } bool(name :string) :bool { let v = this.maybeBool(name) if (v === null) { throw new Error(`expected bool for field ${name}`) } return v } str(name :string) :string { let v = this.maybeStr(name) if (v === null) { throw new Error(`expected string for field ${name}`) } return v } byteStr(name :string) :ByteStr { let v = this.maybeByteStr(name) if (v === null) { throw new Error(`expected ByteStr for field ${name}`) } return v } bytes(name :string) :Uint8Array { let v = this.maybeBytes(name) if (v === null) { throw new Error(`expected Uint8Array for field ${name}`) } return v } type(name :string) :Type { let v = this.maybeType(name) if (v === null) { throw new Error(`expected type for field ${name}`) } return v } ident(name :string) :ast.Ident { let v = this.maybeIdent(name) if (v === null) { throw new Error(`expected ident for field ${name}`) } return v } enumVal<T>(name :string, e :Record<string,any>) :T { let v = this.maybeEnumVal<T>(name, e) if (v === null) { throw new Error(`expected enum value for field ${name}`) } return v } // field access that never throws maybeStr(name :string) :string|null { let v = this._props.get(name) return v instanceof sexpr.Sym ? v.value : null } maybeNum(name :string) :Num|null { let v = this.maybeStr(name) if (v === null) { return null } // Number.MAX_SAFE_INTEGER = 9007199254740991 if (v.length < 16 || v.indexOf(".") != -1 || v.indexOf("e") != -1 || v.indexOf("E") != -1) { let n = Number(v) return isNaN(n) ? null : n } try { return v[0] == "-" ? SInt64.fromStr(v, 10) : UInt64.fromStr(v, 10) } catch (_) { return null } } maybeNum32(name :string) :number|null { let v = Number(this.maybeStr(name)) return isNaN(v) ? null : v } maybeInt32(name :string) :int|null { let s = this.maybeStr(name) if ( s === null || (s.charCodeAt(0) == HYPHEN ? s.length > 17 : s.length > 16) ) { // Number.MAX_SAFE_INTEGER = 9007199254740991 // Number.MIN_SAFE_INTEGER = -9007199254740991 return null } let v = Number(s) let i = v | 0 return (isNaN(i) || i !== v || i > Number.MAX_SAFE_INTEGER) ? null : i } maybeBool(name :string) :bool|null { let v = this.maybeStr(name) return v === "true" ? true : v === "false" ? false : null } maybeByteStr(name :string) :ByteStr|null { let v = this.maybeStr(name) return v !== null ? strings.get(utf8.encodeString(v)) : null } maybeBytes(name :string) :Uint8Array|null { let v = this.maybeStr(name) return v !== null ? utf8.encodeString(v) : null } maybeType(name :string) :Type|null { let v = this.maybeStr(name) return v ? this._getType(v) : null } maybeIdent(name :string) :ast.Ident|null { let s = this.maybeByteStr(name) if (!s) { return null } return new ast.Ident(NoPos, ast.nilScope, s) } maybeEnumVal<T>(name :string, e :Record<string,any>) :T|null { let s = this.maybeStr(name) if (s === null) { return null } let v = (e as any as {[k:string]:T})[s] return v === undefined ? null : v } // field access for arrays/lists strArray(name :string) :string[] { let v = this._props.get(name) return (v instanceof sexpr.List) ? v.map(String) : [] } int32Array(name :string) :int[] { let v = this._props.get(name) return v instanceof sexpr.List ? v.map(v => Number(v) | 0) : [] } num32Array(name :string) :number[] { let v = this._props.get(name) return v instanceof sexpr.List ? v.map(Number) : [] } boolArray(name :string) :bool[] { let v = this._props.get(name) return v instanceof sexpr.List ? v.map(s => s.toString() === "true") : [] } identArray(name :string) :ast.Ident[] { let v = this._props.get(name) return v instanceof sexpr.List ? v.map(v => { let str = v instanceof sexpr.Sym ? v.value : String(v) let s = strings.get(utf8.encodeString(str)) return new ast.Ident(NoPos, ast.nilScope, s) }) : [] } // children maybeChild<T extends Node=Node>() :T|null { return (this._children.shift() || null) as T|null } maybeChildOfType<T extends Node = Node>(ctor: { new (...args: any[]): T; }): T|null { for (let i = 0; i < this._children.length; i++) { let c = this._children[i] if (c instanceof ctor) { this._children.splice(i, 1) return c as T } } return null } children<T extends Node=Node>() :T[] { let v = this._children as T[] this._children = [] return v } maybeChildren<T extends Node=Node>() :T[]|null { let v = this.children<T>() return v.length == 0 ? null : v } child<T extends Node=Node>() :T { let c = this.maybeChild<T>() if (c === null) { throw new Error(`expected child`) } return c } childOfType<T extends Node = Node>(ctor: { new (...args: any[]): T; }): T { let c = this.maybeChildOfType<T>(ctor) if (c === null) { throw new Error(`expected child of type ${ctor.name}`) } return c } childrenOfType<T extends Node=Node>(ctor:{new(...args:any[]):T}): T[] { // TODO: move matches out of this._children return this._children.filter(n => n instanceof ctor) as T[] } childrenOfTypes<T extends Node=Node>(...ctor:{new(...args:any[]):T}[]): T[] { // TODO: move matches out of this._children return this._children.filter(n => { for (let c of ctor) { if (n instanceof c) { return true } } return false }) as T[] } maybeChildrenOfType<T extends Node=Node>(ctor:{new(...args:any[]):T}): T[]|null { let v = this.childrenOfType(ctor) return v.length == 0 ? null : v } maybeChildrenOfTypes<T extends Node=Node>(...ctor:{new(...args:any[]):T}[]): T[]|null { let v = this.childrenOfTypes(...ctor) return v.length == 0 ? null : v } } class Decoder { intypes :Map<string,sexpr.List>|null = null nodedecs :NodeDecoder[] = [] // free list getType = (id :string) :Type|null => { // TODO return t_nil // FIXME } decode(s :string, filename? :string) :Node[] { // parse as s-expressions let xs = sexpr.parse(s, { filename, brackAsList: true, // [...] are lists }) // find types and nodes in the tree we parsed let innodes :sexpr.List[] = [] this.intypes = null for (let [name, ls] of xs.asMap()) { if (name == "meta") { let v = ls.get('types') if (v) { this.intypes = v.asMap() } } else { innodes.push(ls) } } // print('intypes:', this.intypes) // print('innodes:', innodes) // decode nodes let nodes :Node[] = [] for (let ls of innodes) { let n = this.decodeNode(ls) if (n) { nodes.push(n) } } return nodes } decodeField(field :sexpr.List) :[string,sexpr.Value] { let namev = field[0] if (!namev || !namev.isSym()) { throw new Error(`missing field name ${field}`) } return [namev.value, field[1]] } decodeNode(info :sexpr.List) :Node|null { // find node constructor name let consnamev = info[0] if (!consnamev || !consnamev.isSym()) { panic(`missing typename in node def ${info}`) } let consname = (consnamev as sexpr.Sym).value // collect props and children let props = new Map<string,sexpr.Value>() let children :(Node|null)[] = [] for (let i = 1; i < info.length; i++) { let v = info[i] if (v.isList()) { if (v.type == "[") { let [name, value] = this.decodeField(v) props.set(name, value) } else { children.push(this.decodeNode(v)) } } else if (v.isSym()) { if (v.value != "null") { print('v:', v) panic(`unexpected sym when expecting node or null`) } children.push(null) } } // create a new node without calling its constructor let cons = (ast as {[k:string]:any})[consname] if (typeof cons != "function") { panic(`unknown node type ${consname}`) } let n = Object.create(cons.prototype) as Node // allocate a NodeDecoder let dec = this.nodedecs.pop() || new NodeDecoder() dec.init(props, children, this.getType) // restore the node try { n.restore(dec) } catch (err) { print( `${err} (when calling ${consname}.restore())\n` + `node data:`, {props, children, parsed: info} ) throw err } // free the NodeDecoder this.nodedecs.push() return n as Node } } export function encode(...nodes :Node[]) :string { let buf = "" let stack :Scope[] = [] let types = new Map<Type,string>() let wantSpace = false type GroupType = "()" | "[]" function write(s :string) { if (!wantSpace) { wantSpace = true } else { buf += " " } buf += s } function newline() { buf += linestr.substr(0, 1 + (stack.length * 2)) wantSpace = false } function stackPush() { stack.push({}) } function stackPop() :Scope { assert(stack.length > 0) ; return stack.pop()! } function startGroup(openstr :string, name? :string) { newline() buf += openstr if (name) { buf += name wantSpace = true } else { wantSpace = false } stackPush() } function endGroup(closestr :string) { stackPop() buf += closestr } function group(type :GroupType, name :string, c :()=>void) { newline() buf += type[0] + name wantSpace = name.length > 0 stackPush() c() stackPop() buf += type[1] } function eAny(v :any, inGroup :bool = false) { if (v === null || v === undefined) { return write("null") } let t = typeof v if (t == "object") { if (v instanceof Node) { return eNode(v) } if (v instanceof Type) { return eType(v) } if (v instanceof Array) { return eIterable(v, inGroup) } if (v instanceof Set) { return eIterable(v, inGroup) } } if (typeof v == "object") { if (v instanceof Uint8Array) { v = utf8.decodeToString(v) } else { v = String(v) } } if (typeof v == "string") { v = JSON.stringify(v.toString()) } write(String(v)) } function eIterable(v :Iterable<any>, inGroup :bool) { const f = () => { for (let v2 of v) { eAny(v2) } } if (!inGroup) { group("[]", "", f) } else { f() } } function eType(v :Type) { let typeid = types.get(v) if (typeid === undefined) { if (v instanceof BasicType) { // basic types have good, well-recognized names like "i32" typeid = String(v) } else { typeid = "t" + types.size } types.set(v, typeid) } write(typeid) } function eNode(n :Node) { group("()", n.constructor.name, () => n.encode(e)) } function e(...args :any[]) { assert(args.length % 2 == 0, `uneven number of args (missing a key or value?)`) for (let i = 0; i < args.length; i += 2) { let name = String(args[i]) group("()", name, () => eAny(args[i + 1], true)) } } for (let n of nodes) { eNode(n) } //e.writeMetadata() return buf } export function encode1(...nodes :Node[]) :string { let e = new Encoder1() for (let n of nodes) { n.encode1(e) } e.writeMetadata() return e.buf } export function decode(s :string, filename? :string) :Node[] { let d = new Decoder() return d.decode(s, filename) } // export function write(n :Node) :Uint8Array // export function write(n :Node, w :AppendBuffer) :Uint8Array // export function write(n :Node, w :ByteWriter) :null // export function write(n :Node, _w? :ByteWriter) :Uint8Array|null { // let e = new Encoder() // n.encode(e) // e.writeMetadata() // return utf8.encodeString(e.buf) // }
the_stack
import { SelectionModel } from '@angular/cdk/collections'; import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; import { FormControl } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { PopoverContentComponent } from 'ngx-smart-popover'; import { forkJoin } from 'rxjs'; import { Relationship } from 'src/app/classes/stix/relationship'; import { StixObject } from 'src/app/classes/stix/stix-object'; import { RestApiConnectorService } from 'src/app/services/connectors/rest-api/rest-api-connector.service'; import { EditorService } from 'src/app/services/editor/editor.service'; import { AddDialogComponent } from '../add-dialog/add-dialog.component'; import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component'; @Component({ selector: 'app-object-status', templateUrl: './object-status.component.html', styleUrls: ['./object-status.component.scss'], encapsulation: ViewEncapsulation.None }) export class ObjectStatusComponent implements OnInit { public loaded: boolean = false; public statusControl: FormControl; public select: SelectionModel<string>; public workflows: string[] = ["none", "work-in-progress", "awaiting-review", "reviewed"]; @ViewChild("objectStatus", {static: false}) public popover: PopoverContentComponent; public objects: StixObject[]; public object: StixObject; public relationships = []; public revoked: boolean = false; public deprecated: boolean = false; public get disabled(): boolean { return this.editorService.editing || this.editorService.type == "collection"; } constructor(public editorService: EditorService, private restAPIService: RestApiConnectorService, private dialog: MatDialog) { } ngOnInit(): void { this.statusControl = new FormControl(); // this.loadData(); } public loadData() { let data$: any; let options = { includeRevoked: true, includeDeprecated: true } if (this.editorService.stixId && this.editorService.stixId != "new") { // don't load if the object doesn't exist yet // retrieve object if (this.editorService.type == "software") data$ = this.restAPIService.getAllSoftware(options); else if (this.editorService.type == "group") data$ = this.restAPIService.getAllGroups(options); else if (this.editorService.type == "matrix") data$ = this.restAPIService.getAllMatrices(options); else if (this.editorService.type == "mitigation") data$ = this.restAPIService.getAllMitigations(options); else if (this.editorService.type == "tactic") data$ = this.restAPIService.getAllTactics(options); else if (this.editorService.type == "technique") data$ = this.restAPIService.getAllTechniques(options); else if (this.editorService.type == "collection") data$ = this.restAPIService.getAllCollections(options); else if (this.editorService.type == "data-source") data$ = this.restAPIService.getAllDataSources(options); else if (this.editorService.type == "data-component") data$ = this.restAPIService.getAllDataComponents(options); let objSubscription = data$.subscribe({ next: (data) => { this.objects = data.data; this.object = this.objects.find(object => object.stixID === this.editorService.stixId); if (this.object) { if (this.object.workflow && this.object.workflow.state) { this.statusControl.setValue(this.object.workflow.state); } this.revoked = this.object.revoked; this.deprecated = this.object.deprecated; } }, complete: () => { objSubscription.unsubscribe() } }); if (this.editorService.type == 'data-source') { // retrieve related data components & their relationships data$ = this.restAPIService.getAllRelatedToDataSource(this.editorService.stixId); let dataSubscription = data$.subscribe({ next: (results) => { this.relationships = this.relationships.concat(results); }, complete: () => { dataSubscription.unsubscribe(); } }); } // retrieve relationships with the object data$ = this.restAPIService.getRelatedTo({sourceOrTargetRef: this.editorService.stixId}); let relSubscription = data$.subscribe({ next: (data) => { let relationships = data.data as Relationship[]; this.relationships = this.relationships.concat(relationships) this.loaded = true; setTimeout(() => this.popover.updatePosition()); //after render cycle update popover position since it has new content }, complete: () => { relSubscription.unsubscribe() } }); } } private save() { let saveSubscription = this.object.save(this.restAPIService).subscribe({ complete: () => { this.editorService.onReload.emit(); saveSubscription.unsubscribe(); } }) } /** * Handle workflow state change * @param event workflow state selection */ public workflowChange(event) { if (event.isUserInput) { if (event.source.value == "none") this.object.workflow = undefined; else this.object.workflow = {state: event.source.value}; this.save(); } } public getLabel(status: string): string { return status.replace(/-/g, ' '); } /** * Handle the selection for revoking or un-revoking an object * @param event revoke selection */ public revoke(event) { if (event.checked) { // revoke object // prompt for revoking object this.select = new SelectionModel<string>(); let revokedDialog = this.dialog.open(AddDialogComponent, { maxWidth: "70em", maxHeight: "70em", data: { selectableObjects: this.objects.filter(object => { return object.stixID !== this.editorService.stixId}), type: this.editorService.type, select: this.select, selectionType: 'one', title: "Select the revoking object", buttonLabel: "revoke" } }); let revokedSubscription = revokedDialog.afterClosed().subscribe({ next: (result) => { if (result && this.select.selected.length) { // target object selected let target_id = this.select.selected[0]; this.deprecateObjects(true, target_id); } else { // user cancelled or no object selected this.revoked = false; } }, complete: () => { revokedSubscription.unsubscribe(); } }); } else { // deprecate the 'revoked-by' relationship let revokedRelationships = this.relationships.filter(relationship => relationship.relationship_type == 'revoked-by'); for (let relationship of revokedRelationships) { let other_obj: any; if (relationship.source_object.stix.id == this.object.stixID) other_obj = relationship.target_object.stix; else other_obj = relationship.source_object.stix; if (!this.isDeprecatedOrRevoked(other_obj)) { relationship.deprecated = true; relationship.save(this.restAPIService); } } // un-revoke object this.object.revoked = false; this.save(); } } /** * Check if the given object is deprecated or revoked * @param object source or target object of a relationship */ private isDeprecatedOrRevoked(object: any) { return ('x_mitre_deprecated' in object && object.x_mitre_deprecated) || ('revoked' in object && object.revoked); } /** * Handle the selection for deprecating or un-deprecating an object * @param event deprecate selection */ public deprecate(event) { if (event.checked) { this.deprecateObjects(false); } else { this.object.deprecated = false; this.save(); } } /** * Deprecates or revokes the object and deprecates all relationships of this object */ private deprecateObjects(revoked: boolean, revoked_by_id?:string) { let saves = []; // inform users of relationship changes let confirmationPrompt = this.dialog.open(ConfirmationDialogComponent, { maxWidth: "35em", data: { message: 'All relationships with this object will be deprecated. Do you want to continue?', } }); let confirmationSub = confirmationPrompt.afterClosed().subscribe({ next: (result) => { if (!result) { // user cancelled if (revoked) this.revoked = false; else this.deprecated = false; return; } // deprecate or revoke object if (revoked) this.object.revoked = true; else this.object.deprecated = true; saves.push(this.object.save(this.restAPIService)); // update relationships with the object for (let relationship of this.relationships) { if (!relationship.deprecated) { relationship.deprecated = true; saves.push(relationship.save(this.restAPIService)); } } if (revoked_by_id) { // create a new 'revoked-by' relationship let revokedRelationship = new Relationship(); revokedRelationship.relationship_type = 'revoked-by'; revokedRelationship.source_ref = this.object.stixID; revokedRelationship.target_ref = revoked_by_id; saves.push(revokedRelationship.save(this.restAPIService)); } // complete save calls let saveSubscription = forkJoin(saves).subscribe({ complete: () => { this.editorService.onReload.emit(); saveSubscription.unsubscribe(); } }); }, complete: () => { confirmationSub.unsubscribe(); } }); } }
the_stack
import { CommandData } from "../module.base"; import { TSAddOptions, TSCreateOptions, TSCreateRule, TSIncrbyDecrbyOptions, TSKeySet, TSLabel, TSMRangeOptions, TSRangeOptions } from "./rts.types"; export class RedisTimeSeriesCommander { /** * Creating a new TS key * @param key The key * @param options The 'TS.CREATE' optional parameter * @param options.retention The 'RETENTION' optional parameter * @param options.uncompressed The 'UNCOMPRESSED' optional parameter * @param options.chunkSize The 'CHUNK_SIZE' optional parameter * @param options.labels A list of 'LABELS' optional parameter * @param options.duplicatePolicy The 'DUPLICATE_POLICY' optional parameter * @returns "OK" */ create(key: string, options?: TSCreateOptions): CommandData { let args = [key]; if(options !== undefined && options.retention !== undefined) args = args.concat(['RETENTION', options.retention.toString()]); if(options !== undefined && options.uncompressed === true) args.push('UNCOMPRESSED') if(options !== undefined && options.chunkSize !== undefined) args = args.concat(['CHUNK_SIZE', options.chunkSize.toString()]) if(options !== undefined && options.duplicatePolicy !== undefined) args = args.concat(['DUPLICATE_POLICY', options.duplicatePolicy]) if(options !== undefined && options.labels !== undefined && options.labels.length > 0) { args.push('LABELS'); for(const label of options.labels) { args = args.concat([label.name, label.value]) } } return { command: 'TS.CREATE', args: args } } /** * Altering an existing TS key * @param key Required. The key * @param retention Optional. The retention time * @param labels Optional. The labels to update * */ alter(key: string, retention?: number, labels?: TSLabel[]): CommandData { let args = [key]; if(retention !== undefined) args = args.concat(['RETENTION', retention.toString()]); if(labels !== undefined && labels.length > 0) { args.push('LABELS') for(const label of labels) { args = args.concat([label.name, label.value]); } } return { command: 'TS.ALTER', args: args } } /** * Appending/creating a new sample to series * @param key The key * @param timestamp The timestamp * @param value The value * @param options The 'TS.ADD' command optional parameters * @param options.onDuplicate The 'ON_DUPLICATE' optional parameter * @param options.retention The 'RETENTION' optional parameter * @param options.uncompressed The 'UNCOMPRESSED' optional parameter * @param options.chunkSize The 'CHUNK_SIZE' optional parameter * @param options.labels A list of 'LABELS' optional parameter */ add(key: string, timestamp: string, value: string, options?: TSAddOptions): CommandData { let args = [key, timestamp, value]; if(options?.retention !== undefined) { args = args.concat(['RETENTION', `${options.retention}`]) } if(options?.uncompressed === true){ args.push('UNCOMPRESSED'); } if(options?.onDuplicate){ args = args.concat(['ON_DUPLICATE', options.onDuplicate]); } if(options?.chunkSize !== undefined){ args = args.concat(['CHUNK_SIZE', `${options.chunkSize}`]) } if(options?.labels !== undefined && options.labels.length > 0) { args.push('LABELS') for(const label of options.labels) { args = args.concat([label.name, label.value]); } } return { command: 'TS.ADD', args: args } } /** * Appending new samples to a list of series * @param keySets A list of key sets * @param keySets.key The key * @param keySets.timestamp The timestamp * @param keySets.value The value */ madd(keySets: TSKeySet[]): CommandData { let args: string[] = [] for(const keySet of keySets){ args = args.concat([keySet.key, keySet.timestamp, keySet.value]); } return { command: 'TS.MADD', args: args } } /** * Creating a new sample that increments the latest sample's value * @param key The key * @param value The value * @param options The 'TS.INCRBY' command optional parameters * @param options.timestamp The 'TIMESTAMP' optional parameter * @param options.retention The 'RETENTION' optional parameter * @param options.uncompressed The 'UNCOMPRESSED' optional parameter * @param options.chunkSize The 'CHUNK_SIZE' optional parameter * @param options.labels A list of 'LABELS' optional parameter */ incrby(key: string, value: string, options?: TSIncrbyDecrbyOptions): CommandData { let args = [key, value]; if(options !== undefined && options.retention !== undefined) args = args.concat(['RETENTION', options.retention.toString()]) if(options !== undefined && options.uncompressed === true) args.push('UNCOMPRESSED'); if(options !== undefined && options.chunkSize !== undefined) args = args.concat(['CHUNK_SIZE', options.chunkSize.toString()]) if(options !== undefined && options.labels !== undefined && options.labels.length > 0) { args.push('LABELS') for(const label of options.labels) { args = args.concat([label.name, label.value]); } } return { command: 'TS.INCRBY', args: args } } /** * Creating a new sample that decrements the latest sample's value * @param key The key * @param value The value * @param options The 'TS.DECRBY' command optional parameters * @param options.timestamp The 'TIMESTAMP' optional parameter * @param options.retention The 'RETENTION' optional parameter * @param options.uncompressed The 'UNCOMPRESSED' optional parameter * @param options.chunkSize The 'CHUNK_SIZE' optional parameter * @param options.labels A list of 'LABELS' optional parameter */ decrby(key: string, value: string, options?: TSIncrbyDecrbyOptions): CommandData { let args = [key, value]; if(options !== undefined && options.retention !== undefined) args = args.concat(['RETENTION', options.retention.toString()]) if(options !== undefined && options.uncompressed === true) args.push('UNCOMPRESSED'); if(options !== undefined && options.chunkSize !== undefined) args = args.concat(['CHUNK_SIZE', options.chunkSize.toString()]) if(options !== undefined && options.labels !== undefined && options.labels.length > 0) { args.push('LABELS') for(const label of options.labels) { args = args.concat([label.name, label.value]); } } return { command: 'TS.DECRBY', args: args } } /** * Creating a compaction rule * @param parameters The 'TS.CREATERULE' command optional parameters * @param options.sourceKey The source key * @param options.destKey The dest key * @param options.aggregation The aggregation type * @param options.timeBucket The time bucket */ createrule(parameters: TSCreateRule): CommandData { const args = [parameters.sourceKey, parameters.destKey, 'AGGREGATION', parameters.aggregation, parameters.timeBucket.toString()] return { command: 'TS.CREATERULE', args: args } } /** * Deleting a compaction rule * @param sourceKey The source key * @param destKey The dest key */ deleterule(sourceKey: string, destKey: string): CommandData { return { command: 'TS.DELETERULE', args: [sourceKey, destKey] } } /** * Querying a range in forward directions * @param key The key * @param fromTimestamp The starting timestamp * @param toTimestamp The ending timestamp * @param options The 'TS.Range' command optional parameters * @param options.count The 'COUNT' optional parameter * @param options.aggregation The 'AGGREGATION' optional parameter * @param options.aggregation.type The type of the 'AGGREGATION' command * @param options.aggregation.timeBucket The time bucket of the 'AGGREGATION' command */ range(key: string, fromTimestamp: string, toTimestamp: string, options?: TSRangeOptions): CommandData { const args = this.buildRangeCommand(key, fromTimestamp, toTimestamp, options); return { command: 'TS.RANGE', args: args } } /** * Querying a range in reverse directions * @param key The key * @param fromTimestamp The starting timestamp * @param toTimestamp The ending timestamp * @param options The 'TS.Range' command optional parameters * @param options.count The 'COUNT' optional parameter * @param options.aggregation The 'AGGREGATION' optional parameter * @param options.aggregation.type The type of the 'AGGREGATION' command * @param options.aggregation.timeBucket The time bucket of the 'AGGREGATION' command */ revrange(key: string, fromTimestamp: string, toTimestamp: string, options?: TSRangeOptions): CommandData { const args = this.buildRangeCommand(key, fromTimestamp, toTimestamp, options); return { command: 'TS.REVRANGE', args: args } } /** * Building the arguments for 'TS.RANGE'/'TS.REVRANGE' commands * @param key The key * @param fromTimestamp The starting timestamp * @param toTimestamp The ending timestamp * @param options The 'TS.RANGE'/'TS.REVRANGE' command optional parameters * @returns The arguments of the command */ private buildRangeCommand(key: string, fromTimestamp: string, toTimestamp: string, options?: TSRangeOptions): string[] { let args = [key, fromTimestamp, toTimestamp]; if(options?.filterByTS !== undefined) { args = args.concat(['FILTER_BY_TS', options.filterByTS.join(' ')]); } if(options?.filterByValue !== undefined) { args = args.concat(['FILTER_BY_VALUE', `${options.filterByValue.min}`, `${options.filterByValue.max}`]); } if(options?.count !== undefined){ args = args.concat(['COUNT', `${options.count}`]); } if(options?.align !== undefined){ args = args.concat(['ALIGN', `${options.align}`]); } if(options?.aggregation !== undefined){ args = args.concat(['AGGREGATION', options.aggregation.type, `${options.aggregation.timeBucket}`]); } return args; } /** * Querying a range across multiple time-series by filters in forward directions * @param fromTimestamp The starting timestamp * @param toTimestamp The ending timestamp * @param filter The filter * @param options The 'TS.MRange' command optional parameters * @param options.count The 'COUNT' optional parameter * @param options.aggregation The 'AGGREGATION' optional parameter * @param options.aggregation.type The type of the 'AGGREGATION' command * @param options.aggregation.timeBucket The time bucket of the 'AGGREGATION' command * @param options.withLabels The 'WITHLABELS' optional parameter */ mrange(fromTimestamp: string, toTimestamp: string, filter: string, options?: TSMRangeOptions): CommandData { const args = this.buildMultiRangeCommand(fromTimestamp, toTimestamp, filter, options); return { command: 'TS.MRANGE', args: args } } /** * Querying a range across multiple time-series by filters in reverse directions * @param fromTimestamp The starting timestamp * @param toTimestamp The ending timestamp * @param filter The filter * @param options The 'TS.MRange' command optional parameters * @param options.count The 'COUNT' optional parameter * @param options.aggregation The 'AGGREGATION' optional parameter * @param options.aggregation.type The type of the 'AGGREGATION' command * @param options.aggregation.timeBucket The time bucket of the 'AGGREGATION' command * @param options.withLabels The 'WITHLABELS' optional parameter */ mrevrange(fromTimestamp: string, toTimestamp: string, filter: string, options?: TSMRangeOptions): CommandData { const args = this.buildMultiRangeCommand(fromTimestamp, toTimestamp, filter, options); return { command: 'TS.MREVRANGE', args: args } } /** * Building the arguments for 'TS.MRANGE'/'TS.MREVRANGE' commands * @param fromTimestamp The starting timestamp * @param toTimestamp The ending timestamp * @param filter The filter * @param options The 'TS.MRANGE'/'TS.MREVRANGE' command optional parameters * @returns The arguments of the command */ private buildMultiRangeCommand(fromTimestamp: string, toTimestamp: string, filter: string, options?: TSMRangeOptions): string[] { let args = [fromTimestamp, toTimestamp]; if(options?.count !== undefined) { args = args.concat(['COUNT', `${options.count}`]); } if(options?.align !== undefined){ args = args.concat(['ALIGN', `${options.align}`]); } if(options?.aggregation){ args = args.concat(['AGGREGATION', `${options.aggregation.type}`, `${options.aggregation.timeBucket}`]); } if(options?.withLabels === true) { args.push('WITHLABELS') } args = args.concat(['FILTER', `${filter}`]) if(options?.groupBy){ args = args.concat(['GROUPBY', `${options.groupBy.label}`, 'REDUCE', `${options.groupBy.reducer}`]) } return args; } /** * Retrieving the last sample of a key * @param key The key */ get(key: string): CommandData { return { command: 'TS.GET', args: [key] } } /** * Retrieving the last sample of a key by filter * @param filter Required. The filter * @param withLabels Optional. If to add the 'WITHLABELS' Optional parameter */ mget(filter: string, withLabels?: boolean): CommandData { let args: string[] = []; if(withLabels === true){ args.push('WITHLABELS'); } args = args.concat(['FILTER'], filter.split(' ')) return { command: 'TS.MGET', args: args } } /** * Retrieving information and statistics on the time-series * @param key The key */ info(key: string): CommandData { return { command: 'TS.INFO', args: [key] } } /** * Retrieving all the keys matching the filter list * @param filter The filter */ queryindex(filter: string): CommandData { return { command: 'TS.QUERYINDEX', args: [filter] } } /** * Delete data points for a given timeseries and interval range in the form of start and end delete timestamps. * @param key Key name for timeseries * @param fromTimestamp Start timestamp for the range deletion. * @param toTimestamp End timestamp for the range deletion. * @returns The count of samples deleted */ del(key: string, fromTimestamp: string, toTimestamp: string): CommandData { return { command: 'TS.DEL', args: [key, fromTimestamp, toTimestamp] } } }
the_stack
import _ from 'lodash'; import { randomUUID } from 'crypto'; import { GetTableEntityResponse, odata, TableClient, TableEntityQueryOptions, TableEntityResult, TableServiceClient, TablesSharedKeyCredential } from '@azure/data-tables'; import { ICorporateLink, ICorporateLinkExtended, ICorporateLinkProperties, IProviders, IReposError } from '../../../interfaces'; import { CorporatePropertyNames } from '../../../business/corporateLink'; import { CorporateTableLink } from './tableLink'; import { ILinkProvider } from '..'; import tableEntity from '../../tableEntity'; import { ErrorHelper } from '../../../transitional'; import { decryptEntityAsync, encryptEntityAsync, IEncryptionOptions } from '../../encryption'; import { IKeyVaultSecretResolver } from '../../keyVaultResolver'; const defaultThirdPartyType = 'github'; // const defaultPageSize = 500; const defaultTableName = 'links'; const linkProviderInstantiationTypeProperty = '_i'; const dehydratedIdentityKey = '_lpi'; const dehydratedTableProviderName = 'xtable'; const dehydratedTableProviderVersion = '0'; const dehydratedTableProviderIdentitySeperator = '_'; const dehydratedTableProviderIdentity = `${dehydratedTableProviderName}${dehydratedTableProviderIdentitySeperator}${dehydratedTableProviderVersion}`; enum LinkInstantiatedType { AzureTableEntity, Rehydrated, } interface IAlreadyLinkedError extends IReposError { alreadyLinked?: boolean; } interface IMultipleResultsError extends IReposError { multipleResults?: boolean; } const defaultEncryptedPropertyNames = [ 'githubToken', 'githubTokenIncreasedScope', 'localDataKey', ]; export interface ITableLinkProperties extends ICorporateLinkProperties { linkId: string; created: string; } const linkInterfacePropertyMapping : ITableLinkProperties = { linkId: 'linkid', isServiceAccount: 'serviceAccount', serviceAccountMail: 'serviceAccountMail', corporateId: 'aadoid', corporateUsername: 'aadupn', corporateDisplayName: 'aadname', corporateMailAddress: 'corporateMailAddress', // NOTE: this was not part of the original table entity corporateAlias: 'corporateAlias', // NOTE: this was not part of the original table entity thirdPartyId: 'ghid', thirdPartyUsername: 'ghu', thirdPartyAvatar: 'ghavatar', created: 'Timestamp', }; const coreColumns = [ 'ghid', 'ghu', 'ghavatar', 'aadoid', 'aadupn', 'aadname', 'corporateMailAddress', 'serviceAccount', 'serviceAccountMail', 'linkid', ]; // const coreColumnsList = coreColumns.join(', '); interface ITableLinkProviderEncryptionOptions { encryptedPropertyNames: string[]; encryptionKeyId: string; keyEncryptionKeyResolver: IKeyVaultSecretResolver; tableDehydrator: (instance: any) => any; tableRehydrator: (partitionKey: string, rowKey: string, obj?: any, callback?: any) => any; } interface ITableLinkProviderOptions { encryption?: ITableLinkProviderEncryptionOptions; thirdPartyType?: string; account?: string; key?: string; tableName?: string; prefix?: string; throwIfTableMissing?: boolean; partitionKey?: string; } interface IQueryLinksOptions { pageSize?: number; columns?: string[]; wherePropertyName?: string; whereValue?: string; } export class TableLinkProvider implements ILinkProvider { private _tableName: string; private _tableNamePrefix: string; private _tableService: TableServiceClient; private _tableClient: TableClient; private _options: ITableLinkProviderOptions; private _thirdPartyType: string; private _encryptionOptions: IEncryptionOptions; public readonly propertyMapping: ITableLinkProperties = linkInterfacePropertyMapping; public readonly serializationIdentifierVersion: string = dehydratedTableProviderIdentity; constructor(providers: IProviders, options: ITableLinkProviderOptions) { options = options || {}; const thirdPartyType = options.thirdPartyType || defaultThirdPartyType; if (thirdPartyType !== 'github') { throw new Error('At this time only "github" is a supported third-party type.'); } const storageAccountName = options.account; if (!storageAccountName) { throw new Error('Must provide options.account with an Azure Table storage account name'); } const storageAccountKey = options.key; if (!storageAccountKey) { throw new Error('Must provide options.key with an Azure Table storage account key'); } this._options = options; } async initialize(): Promise<ILinkProvider> { const options = this._options || {}; const azureTableCredential = new TablesSharedKeyCredential(options.account, options.key); const serviceUrl = `https://${options.account}.table.core.windows.net`; this._tableService = new TableServiceClient(serviceUrl, azureTableCredential); this._tableNamePrefix = options.prefix || ''; this._tableName = options.tableName || `${this._tableNamePrefix}${defaultTableName}`; if (options.encryption) { const encryptionOptions = options.encryption; const encryptionKeyId = encryptionOptions.encryptionKeyId; if (!encryptionKeyId) { throw new Error('Encryption requires options.encryptionKeyId'); } const keyResolver = encryptionOptions.keyEncryptionKeyResolver; if (!keyResolver) { throw new Error('Encryption requires options.keyResolver'); } const encryptedPropertyNames = new Set<string>(encryptionOptions.encryptedPropertyNames || defaultEncryptedPropertyNames); this._encryptionOptions = { keyEncryptionKeyId: encryptionKeyId, keyResolver, encryptionResolver: undefined, keyEncryptionKeys: undefined, encryptedPropertyNames, binaryProperties: 'buffer', tableDehydrator: encryptionOptions.tableDehydrator || tableEntity.reduce, tableRehydrator: encryptionOptions.tableRehydrator || tableEntity.create, }; } this._tableClient = new TableClient(serviceUrl, this._tableName, azureTableCredential); if (options.throwIfTableMissing) { let tableExists = false; try { tableExists = await this.doesTableNameExist(this._tableName); } catch (tableError) { throw tableError; } if (!tableExists) { throw new Error(`The table named "${this._tableName}" does not exist. With options.throwIfTableMissing set, this error is thrown.`); } } else { await this.tableCreateIfNotExists(this._tableName); } return this as any as ILinkProvider; } get thirdPartyType() { return this._thirdPartyType; } getByThirdPartyUsername(username: string): Promise<CorporateTableLink> { username = username.toLowerCase(); // NOTE: this is not normalized in the current data set!!!!!!!! // TODO: NOT NORMALIZED // TODO: VALUES in the current table have usernames that are MIXED CASE!!!!!! return this.getSingleLinkByProperty(this.propertyMapping.thirdPartyUsername, username) as Promise<CorporateTableLink>; } async getByThirdPartyId(id: string): Promise<CorporateTableLink> { if (typeof(id) !== 'string') { id = (id as any).toString(); } // Legacy table design: this call actually can go direct; in the // original implementation, the partition key is fixed and the // row key is the string value of the GitHub user ID. // SLOW query equivalent: return getUserEntityByProperty(this, 'ghid', id, callback); const partitionKey = this._options.partitionKey; if (!partitionKey) { throw new Error('No table options.partitionKey provided with a fixed partition key at this time'); } const fullEntity = await this.tableRetrieveEntity(partitionKey, id); if (fullEntity === false) { return false as any as CorporateTableLink; } const row = tableEntity.reduce(fullEntity); const link = createLinkInstanceFromAzureTableEntity(this, row); return link; } queryByCorporateId(id: string): Promise<CorporateTableLink[]> { return this.getLinksByProperty('aadoid', id); } async getAll(): Promise<CorporateTableLink[]> { const queryOptions = { columns: [ 'aadoid', 'aadupn', 'aadname', 'ghu', 'ghid', 'ghavatar', 'serviceAccount', 'serviceAccountMail', 'PartitionKey', 'RowKey', 'Timestamp', ], }; const unsorted = await this.queryLinksTable(queryOptions); const sorted = _.sortBy(unsorted, ['aadupn', 'ghu']); const links = createLinkInstancesFromAzureTableEntityArray(this, sorted); return links; } async getAllCorporateIds(): Promise<string[]> { const queryOptions = { columns: [ 'aadoid', 'PartitionKey', 'RowKey', 'Timestamp', ], }; const results = await this.queryLinksTable(queryOptions); return results.map(row => String(row.aadoid)) as string[]; } queryByCorporateUsername(username: string): Promise<CorporateTableLink[]> { // ?? username = username.toLowerCase(); // TODO: not sure if this one is normalized or not... return this.getLinksByProperty('aadupn', username); } async createLink(link: ICorporateLink): Promise<string> { const generatedLinkId = randomUUID(); let entity = null; try { const initialEntity = {}; initialEntity[linkInterfacePropertyMapping.linkId] = generatedLinkId; for (let linkPropertyName of CorporatePropertyNames) { // linkInterfacePropertyMapping const tableColumnName = linkInterfacePropertyMapping[linkPropertyName]; if (!tableColumnName) { throw new Error(`Missing mapping from property ${linkPropertyName} to equivalent table column`); } initialEntity[tableColumnName] = link[linkPropertyName]; } const partitionKey = this._options.partitionKey; if (!partitionKey) { throw new Error('No table options.partitionKey provided with a fixed partition key at this time'); } entity = tableEntity.create(partitionKey, link.thirdPartyId, initialEntity); } catch (processingError) { throw processingError; } await this.tableInsertEntity(entity, 'This user is already linked'); return generatedLinkId; } updateLink(linkInstance: ICorporateLink): Promise<any> { const tl = linkInstance as CorporateTableLink; const replacementEntity = tl.internal().getDirectEntity(); if (linkInstance.thirdPartyId) { return this.updateLinkByThirdPartyIdLegacy(linkInstance.thirdPartyId, replacementEntity); } throw new Error('updateLink is not yet updated for linkId without a given thirdPartyId (ghid)'); } async deleteLink(linkInstance: ICorporateLink): Promise<any> { // This is inefficient at this time; with the newer design centering // around a link ID, this has to query first. const tl = linkInstance as CorporateTableLink; const linkId = tl.id; if (!linkId && linkInstance.thirdPartyId) { return this.deleteLinkByThirdPartyIdLegacy(linkInstance.thirdPartyId); } const link = this.getSingleLinkByProperty(this.propertyMapping.linkId, linkId) as any as CorporateTableLink; if (!link) { throw new Error(`No link found with ID ${linkId}`); } if (!link.thirdPartyId) { throw new Error(`Link ${linkId} is missing a valid thirdPartyId`); } return this.deleteLinkByThirdPartyIdLegacy(link.thirdPartyId); } async updateLinkByThirdPartyIdLegacy(thirdPartyId: string, replaceEntity: any): Promise<void> { const partitionKey = this._options.partitionKey; if (!partitionKey) { throw new Error('No table options.partitionKey provided with a fixed partition key at this time'); } if (typeof(thirdPartyId) !== 'string') { thirdPartyId = (thirdPartyId as any).toString(); } if (!replaceEntity.linkId) { console.log('Generated a new linkId as part of an update operation'); const newLinkId = randomUUID(); replaceEntity.linkId = newLinkId; } const entity = tableEntity.create(partitionKey, thirdPartyId, replaceEntity); await this.tableReplaceEntity(entity); } deleteLinkByThirdPartyIdLegacy(thirdPartyId: string): Promise<void> { const partitionKey = this._options.partitionKey; if (!partitionKey) { throw new Error('No table options.partitionKey provided with a fixed partition key at this time'); } if (typeof(thirdPartyId) !== 'string') { thirdPartyId = (thirdPartyId as any).toString(); } return this.tableDeleteEntity(partitionKey, thirdPartyId); } dehydrateLink(linkInstance: ICorporateLinkExtended): any { // CONSIDER: check whether the current link type feels appropriate to us (PGSQL) const tlink = linkInstance as CorporateTableLink; const entity = tlink.internal().getDirectEntity(); const shriveled = Object.assign({}, entity); shriveled[dehydratedIdentityKey] = dehydratedTableProviderIdentity; return shriveled; } rehydrateLink(jsonObject: any): ICorporateLink { if (!jsonObject) { throw new Error('No object provided to rehydrate'); } const identity = jsonObject[dehydratedIdentityKey] as string; if (!identity) { throw new Error('No stored link provider identity to validate'); } if (identity !== dehydratedTableProviderIdentity) { const sameProviderType = identity.startsWith(`${dehydratedTableProviderName}${dehydratedTableProviderIdentitySeperator}`); if (sameProviderType) { // Cross-version rehydration not supported throw new Error(`The hydrated link was created by the same ${dehydratedTableProviderName} provider, but a different version: ${identity}`); } else { throw new Error(`The hydrated link is incompatible with this runtime environment: ${identity}`); } } const clonedObject = Object.assign({}, jsonObject); delete clonedObject[dehydratedIdentityKey]; const pglink = this.createLinkInstanceFromHydratedEntity(clonedObject); return pglink; } dehydrateLinks(linkInstances: ICorporateLink[]): any[] { if (!Array.isArray(linkInstances)) { throw new Error('linkInstances must be an array'); } if (linkInstances.length > 0) { const first = linkInstances[0]; if (first[linkProviderInstantiationTypeProperty] === undefined) { throw new Error('linkInstances[0] does not appear to be a link instantiated by a provider'); } } // const arr: any[] = linkInstances.map(this.dehydrateLink.bind(this)); return arr; } rehydrateLinks(jsonArray: any): ICorporateLink[] { if (!Array.isArray(jsonArray)) { throw new Error('jsonArray must be an array'); } // const arr = jsonArray.map(this.rehydrateLink.bind(this)); return arr as any[] as ICorporateLink[]; } private createLinkInstanceFromHydratedEntity(jsonObject) { const linkInternalOptions = { provider: this, }; const newLink = new CorporateTableLink(linkInternalOptions, jsonObject); newLink[linkProviderInstantiationTypeProperty] = LinkInstantiatedType.Rehydrated; // in case this helps while debugging return newLink; } private async getTableEntitiesByProperty(propertyName: string, value): Promise<any[]> { const queryOptions = { wherePropertyName: propertyName, whereValue: value, }; return await this.queryLinksTable(queryOptions); } private async getLinksByProperty(propertyName, value): Promise<CorporateTableLink[]> { const rows = await this.getTableEntitiesByProperty(propertyName, value); const links = createLinkInstancesFromAzureTableEntityArray(this, rows); return links; } private async getSingleLinkByProperty(propertyName: string, value): Promise<CorporateTableLink | boolean> { const rows = await this.getTableEntitiesByProperty(propertyName, value); if (rows.length <= 0) { return false; } if (rows.length > 1) { const error: IMultipleResultsError = new Error(`More than a single result were returned by the query (${rows.length})`); error.multipleResults = rows.length > 0; throw error; } const entityRow = rows[0]; const link = createLinkInstanceFromAzureTableEntity(this, entityRow); return link; } private async tableInsertEntity(entity: any, entityAlreadyExistsErrorMessage: string): Promise<any> { try { let entityObject = entity; if (this._encryptionOptions) { const rowKey = entity.rowKey as string; const partitionKey = entity.partitionKey as string; const encryptedObject = await encryptEntityAsync(partitionKey, rowKey, entityObject, this._encryptionOptions); entityObject = this._encryptionOptions.tableRehydrator(partitionKey, rowKey, encryptedObject); } await this._tableClient.createEntity(entityObject); } catch (insertError) { if (ErrorHelper.IsConflict(insertError)) { const error: IAlreadyLinkedError = new Error(entityAlreadyExistsErrorMessage); error.alreadyLinked = true; error.innerError = insertError; throw error; } throw insertError; } } private async queryLinksTable(options: IQueryLinksOptions): Promise<any[]> { const query: TableEntityQueryOptions = { select: options.columns || undefined, }; if (options.wherePropertyName && options.whereValue) { const whereValue = odata`eq ${options.whereValue}`; query.filter = `${options.wherePropertyName} ${whereValue}`; } const rows = []; const pager = this._tableClient.listEntities({ queryOptions: query }).byPage(); for await (const page of pager) { for (let i = 0; i < page.length; i++) { let row = page[i]; if (this._encryptionOptions) { const { partitionKey, rowKey } = row; const reducedEntity = this._encryptionOptions.tableDehydrator(row); const decryptedEntity = await decryptEntityAsync(partitionKey, rowKey, reducedEntity, this._encryptionOptions); // CONSIDER: the original implementation called the rehydrator here... which seems unnecessary now. row = this._encryptionOptions.tableRehydrator(partitionKey, rowKey, decryptedEntity); } rows.push(row); } } return rows; } private async doesTableNameExist(tableName: string): Promise<boolean> { // The newer table client does not seem to have a simple "exist" check today... const iterateByPage = this._tableService.listTables().byPage(); for await (const page of iterateByPage) { const present = page.filter(p => p?.tableName === tableName); if (present.length > 0) { return true; } } return false; } private async tableCreateIfNotExists(tableName: string): Promise<void> { try { await this._tableService.createTable(tableName); } catch (error) { if (ErrorHelper.IsConflict(error)) { return; } else { throw error; } } } private async tableRetrieveEntity(partitionKey: string, rowKey: string): Promise<false | GetTableEntityResponse<TableEntityResult<object>>> { try { let entity = await this._tableClient.getEntity(partitionKey, rowKey); if (this._encryptionOptions) { const reducedEntity = this._encryptionOptions.tableDehydrator(entity); const decryptedEntity = await decryptEntityAsync(partitionKey, rowKey, reducedEntity, this._encryptionOptions); const hydrated = this._encryptionOptions.tableRehydrator(partitionKey, rowKey, decryptedEntity); entity = hydrated; } return entity; } catch (error) { if (ErrorHelper.IsNotFound(error)) { return false; } throw error; } } private async tableReplaceEntity(entity: any): Promise<any> { let replacementObject = entity; if (this._encryptionOptions) { const reducedEntity = this._encryptionOptions.tableDehydrator(entity); const rowKey = entity.rowKey as string; const partitionKey = entity.partitionKey as string; const encryptedEntity = await encryptEntityAsync(partitionKey, rowKey, reducedEntity, this._encryptionOptions); replacementObject = this._encryptionOptions.tableRehydrator(partitionKey, rowKey, encryptedEntity); } await this._tableClient.updateEntity(replacementObject, 'Replace'); } private async tableDeleteEntity(partitionKey: string, rowKey: string): Promise<any> { await this._tableClient.deleteEntity(partitionKey, rowKey); } } function createLinkInstancesFromAzureTableEntityArray(provider: TableLinkProvider, rows: any[]): CorporateTableLink[] { return rows.map(createLinkInstanceFromAzureTableEntity.bind(null, provider)); } function createLinkInstanceFromAzureTableEntity(provider: TableLinkProvider, row: any): CorporateTableLink { const linkInternalOptions = { provider, }; const newLink = new CorporateTableLink(linkInternalOptions, row); newLink[linkProviderInstantiationTypeProperty] = LinkInstantiatedType.AzureTableEntity; // in case this helps while debugging return newLink; }
the_stack
import { GraphQLSchema, graphql, print } from 'graphql'; import gql from 'graphql-tag'; import authenticationPlugin from '../../src/authentication'; import { GraphQLGenie } from 'graphql-genie'; import { isArray, isEmpty } from 'lodash'; let schema: GraphQLSchema; beforeAll(() => { const typeDefs = gql` enum Role { # Open to all requests ANY # Must be logged in USER # User must have created/be the type OWNER ADMIN } # Only users can create posts, anybody can read posts, only the person who created the post can update/delete it type Post @auth(create: USER, read: ANY, update: OWNER, delete: OWNER) { id: ID! @unique title: String! text: String # Set a rule of "SELF" here that we can look for in our authenticate function so users aren't allowed to change it to other users author: User! @relation(name: "posts") @auth(create: USER, read: ANY, update: OWNER, delete: OWNER, rules: "SELF") } # Anyone can create users (aka signup), be able to see user info by default, can only update yourself, and only admins can delete type User @auth(create: ANY, read: ANY, update: OWNER, delete: ADMIN) { id: ID! @unique username: String! @unique # only users can see their own email, it's not public email: String! @unique @auth(create: ANY, read: OWNER, update: OWNER, delete: ADMIN) # only admins can read password password: String! @auth(create: ANY, read: ADMIN, update: OWNER, delete: ADMIN) posts: [Post] @relation(name: "posts") # Only admins can alter roles, will need additional logic in authenticate function so users can only set themself to USER role # So we set only:USER in the rules so we can find that later in our authenticate function roles: [Role] @default(value: "USER") @auth(create: ANY, read: ADMIN, update: ADMIN, delete: ADMIN, rules: "only:USER") } `; const genie = new GraphQLGenie({ typeDefs, plugins: authenticationPlugin() }); schema = genie.getSchema(); }); const testData = { users: [], posts: [] }; const getUserIDsOfRequestedData = (records: object[], filterRecords: object[]): Set<string> => { const userIDs = new Set<string>(); records.push(filterRecords); try { records = isArray(records) ? records : [records]; records.forEach(record => { if (record['__typename'] === 'User') { userIDs.add(record['id']); } else if (record['__typename'] === 'Post' && record['author']) { userIDs.add(record['author']); } }); } catch (e) { // empty by design } return userIDs; }; const context = (currUser?, returnErr = true) => { currUser = currUser || { id: 1, roles: ['ADMIN'] }; return { authenticate: (method, requiredRoles, records, filterRecords, _updates, typeName, fieldName, _isFromFilter) => { const requiredRolesForMethod: string[] = requiredRoles[method]; const rules: string[] = requiredRoles.rules || []; const currRoles = !isEmpty(currUser) ? currUser['roles'] : []; if (currRoles.includes('ADMIN')) { return true; } records = records || []; // implement logic for our custom rules let passes = true; records.forEach(record => { rules.forEach(rule => { // we don't want users to be able to create themselves with any other role than USER if (['create', 'update'].includes(method) && rule.includes('only:')) { const allowedValue = rule.split(':')[1]; if (record[fieldName]) { if (isArray(record[fieldName])) { if (record[fieldName].length > 1 || record[fieldName][0] !== allowedValue) { if (returnErr) { throw new Error(`${fieldName} must be ${allowedValue}`); } else { passes = false; } } } else if (record[fieldName] !== allowedValue) { if (returnErr) { throw new Error(`${fieldName} must be ${allowedValue}`); } else { passes = false; } } } } else if (rule === 'SELF') { // users shouldn't be able to set posts author other than to themselves if (['create', 'update'].includes(method)) { if (isEmpty(currUser)) { if (returnErr) { throw new Error(`Must be logged in to set ${fieldName}`); } else { passes = false; } } else if (record[fieldName] && record[fieldName] !== currUser['id']) { if (returnErr) { throw new Error(`${fieldName} field must be set to logged in USER`); } else { passes = false; } } } } }); }); if (!passes) { return passes; } if (requiredRolesForMethod.includes('ANY')) { return true; } // the !isEmpty(record) may result in saying to permission even if it's actually just an empty result // but it could be a security flaw that allows people to see what "OWNER" fields don't exist otherwise if (requiredRolesForMethod.includes('OWNER') && !isEmpty(currUser) && !isEmpty(records)) { const userIds = getUserIDsOfRequestedData(records, filterRecords); if (userIds.size === 1 && userIds.values().next().value === currUser.id) { return true; } } // check if currRoles has any of the required Roles const hasNecessaryRole = requiredRolesForMethod.some((role) => { return currRoles.includes(role); }); if (!hasNecessaryRole) { if (fieldName) { if (returnErr) { throw new Error(`Not allowed to ${method} ${fieldName} on type ${typeName}`); } else { return false; } } else { if (returnErr) { throw new Error(`Not allowed to ${method} ${typeName}`); } else { return false; } } } return true; } }; }; const createUser = gql` mutation createUser($input: CreateUserMutationInput!) { createUser(input: $input) { data { id username email password roles } clientMutationId } } `; const createPost = gql` mutation createPost($input: CreatePostMutationInput!) { createPost(input: $input) { data { id title text author { id } } } } `; const updatePost = gql` mutation updatePost($input: UpdatePostMutationInput!) { updatePost(input: $input) { data { id title text author { id } } } } `; describe('authTest', () => { test('must have auth fn', async () => { const result = await graphql({ schema, source: print(createUser), variableValues: { input: { data: { username: 'Zain', password: 'pass', email: 'zain@example.com', roles: ['USER'] } } }, }); expect(result.errors).not.toBeNull(); expect(result.errors[0].message).toMatch(/must have an authenticate function/ig); }); test('create - user with posts', async () => { const zain = await graphql({ schema, source: print(createUser), variableValues: { input: { data: { username: 'Zain', password: 'pass', email: 'zain@example.com', roles: ['USER'] } } }, contextValue: context() }); const steve = await graphql({ schema, source: print(createUser), variableValues: { input: { data: { username: 'Steve', password: 'pass', email: 'steve@example.com', roles: ['USER'] } } }, contextValue: context() }); const pete = await graphql({ schema, source: print(createUser), variableValues: { input: { data: { username: 'Pete', password: 'pass', email: 'pete@example.com', roles: ['USER'] } } }, contextValue: context() }); testData.users.push(zain.data.createUser.data); testData.users.push(steve.data.createUser.data); testData.users.push(pete.data.createUser.data); const user = await graphql({ schema, contextValue: context(), source: print(gql` mutation { createUser( input: { data: { password: "pass" email: "zeus@example.com" username: "Zeus" posts: { create: [{ title: "Hello World" text: "This is my first blog post ever!" }, { title: "My Second Post" text: "My first post was good, but this one is better!" }, { title: "Solving World Hunger" text: "This is a draft..." }] } } } ) { data { id username email roles posts { id title text } } } } ` )}); testData.users.push(user.data.createUser.data); testData.posts = testData.posts.concat(user.data.createUser.data.posts); expect(user.data.createUser.data.username).toBe('Zeus'); expect(user.data.createUser.data.email).toBe('zeus@example.com'); expect(user.data.createUser.data.roles).toEqual(['USER']); expect(user.data.createUser.data.posts).toHaveLength(3); expect(user.data.createUser.data.posts[0].title).toBe('Hello World'); expect(user.data.createUser.data.posts[1].title).toBe('My Second Post'); expect(user.data.createUser.data.posts[2].title).toBe('Solving World Hunger'); }); test('make sure you can read own email', async () => { const user = testData.users[0]; const result = await graphql({ schema, contextValue: context(user), source: print(gql` query { user(id: "${user.id}") { id username email } } `) }); expect(result.errors).toBeUndefined(); expect(result.data.user.username).toBe(user.username); expect(result.data.user.email).toBe(user.email); }); test('make sure you can read others username', async () => { const currUser = testData.users[0]; const findUser = testData.users[1]; const result = await graphql({ schema, contextValue: context(currUser), source: print(gql` query { user(id: "${findUser.id}") { id username } } `) }); expect(result.errors).toBeUndefined(); expect(result.data.user.username).toBe(findUser.username); }); test('make sure you cant read others email', async () => { const currUser = testData.users[0]; const findUser = testData.users[1]; const result = await graphql({ schema, contextValue: context(currUser), source: print(gql` query { user(id: "${findUser.id}") { id username email } } `) }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not allowed/ig); }); test('make sure you cant read others email with a fragment', async () => { const currUser = testData.users[0]; const findUser = testData.users[1]; const result = await graphql({ schema, contextValue: context(currUser), source: print(gql` query { node(id: "${findUser.id}") { id ...on User { username email } } } `) }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not allowed/ig); }); test('make sure you can find yourself by email', async () => { const currUser = testData.users[0]; const result = await graphql({ schema, contextValue: context(currUser), source: print(gql` query { user(email: "${currUser.email}") { id username email } } `) }); expect(result.errors).toBeUndefined(); expect(result.data.user.username).toBe(currUser.username); expect(result.data.user.email).toBe(currUser.email); }); test('make sure you cant find others email', async () => { const currUser = testData.users[0]; const findUser = testData.users[1]; let result = await graphql({ schema, contextValue: context(currUser), source: print(gql` query { user(email: "${findUser.email}") { id username } } `) }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not allowed/ig); result = await graphql({ schema, contextValue: context(currUser), source: print(gql` query { user(email: "any value should say not allowed") { id username } } `) }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not allowed/ig); }); test('make sure you cant create yourself with admin role', async () => { const result = await graphql({ schema, contextValue: context({}), source: print(createUser), variableValues: { input: { data: { username: 'new', password: 'pass', email: 'new@example.com', roles: ['ADMIN'] } } }, }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toBe('roles must be USER'); }); test('make sure you need author to make a post', async () => { const currUser = testData.users[0]; const result = await graphql({ schema, contextValue: context(currUser), source: print(createPost), variableValues: { input: { data: { title: 'bam', text: 'bam' } } }, }); expect(result.errors).not.toBeUndefined(); }); test('make sure you have to be logged in to create a post', async () => { const currUser = testData.users[0]; const result = await graphql({ schema, contextValue: context({}), source: print(createPost), variableValues: { input: { data: { title: 'bam', text: 'bam', author: {connect: {id: currUser.id}} } } }, }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not allowed/gi); }); test('make sure you can create a post', async () => { const currUser = testData.users[0]; const result = await graphql({ schema, contextValue: context(currUser), source: print(createPost), variableValues: { input: { data: { title: 'bam', text: 'bam', author: {connect: {id: currUser.id}} } } }, }); expect(result.errors).toBeUndefined(); currUser.posts = [result.data.createPost.data]; expect(result.data.createPost.data.title).toBe('bam'); expect(result.data.createPost.data.text).toBe('bam'); expect(result.data.createPost.data.author.id).toBe(currUser.id); }); test('make sure you cant create a post on another user', async () => { const currUser = testData.users[0]; const otherUser = testData.users[1]; const result = await graphql({ schema, contextValue: context(currUser), source: print(createPost), variableValues: { input: { data: { title: 'bam', text: 'bam', author: {connect: {id: otherUser.id}} } } }, }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/field must be set to logged in USER/ig); }); test('make sure you can update your post', async () => { const currUser = testData.users[0]; const result = await graphql({ schema, contextValue: context(currUser), source: print(updatePost), variableValues: { input: {where: {id: currUser.posts[0].id}, data: { title: 'update' } } }, }); expect(result.errors).toBeUndefined(); expect(result.data.updatePost.data.title).toBe('update'); }); test('make sure you cant update another users post', async () => { const currUser = testData.users[0]; const result = await graphql({ schema, contextValue: context(currUser), source: print(updatePost), variableValues: { input: {where: {id: testData.posts[0].id}, data: { title: 'update' } } }, }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not allowed/ig); }); test('make sure you cant read own password', async () => { const user = testData.users[0]; const result = await graphql({ schema, contextValue: context(user), source: print(gql` query { user(id: "${user.id}") { id username email password } } `) }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not allowed/ig); }); test('make sure you can delete own post', async () => { const user = testData.users[0]; const result = await graphql({ schema, contextValue: context(user), source: print(gql` mutation { deletePost(input: {where: {id: "${user.posts[0].id}"}}) { data { id } } } `) }); expect(result.errors).toBeUndefined(); expect(result.data.deletePost.data.id).toBe(user.posts[0].id); }); }); describe('authTestBoolean', () => { test('make sure you cant read others email', async () => { const currUser = testData.users[0]; const findUser = testData.users[1]; const result = await graphql({ schema, contextValue: context(currUser, false), source: print(gql` query { user(id: "${findUser.id}") { id username email } } `) }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not authorized/ig); }); test('make sure you cant read others email with a fragment', async () => { const currUser = testData.users[0]; const findUser = testData.users[1]; const result = await graphql({ schema, contextValue: context(currUser, false), source: print(gql` query { node(id: "${findUser.id}") { id ...on User { username email } } } `) }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not authorized/ig); }); test('make sure you cant find others email', async () => { const currUser = testData.users[0]; const findUser = testData.users[1]; let result = await graphql({ schema, contextValue: context(currUser, false), source: print(gql` query { user(email: "${findUser.email}") { id username } } `) }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not authorized/ig); result = await graphql({ schema, contextValue: context(currUser, false), source: print(gql` query { user(email: "any value should say not authorized") { id username } } `) }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not authorized/ig); }); test('make sure you cant create yourself with admin role', async () => { const result = await graphql({ schema, contextValue: context({}, false), source: print(createUser), variableValues: { input: { data: { username: 'new', password: 'pass', email: 'new@example.com', roles: ['ADMIN'] } } }, }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not authorized/ig); }); test('make sure you need author to make a post', async () => { const currUser = testData.users[0]; const result = await graphql({ schema, contextValue: context(currUser, false), source: print(createPost), variableValues: { input: { data: { title: 'bam', text: 'bam' } } }, }); expect(result.errors).not.toBeUndefined(); }); test('make sure you have to be logged in to create a post', async () => { const currUser = testData.users[0]; const result = await graphql({ schema, contextValue: context({}, false), source: print(createPost), variableValues: { input: { data: { title: 'bam', text: 'bam', author: {connect: {id: currUser.id}} } } }, }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not authorized/gi); }); test('make sure you cant create a post on another user', async () => { const currUser = testData.users[0]; const otherUser = testData.users[1]; const result = await graphql({ schema, contextValue: context(currUser, false), source: print(createPost), variableValues: { input: { data: { title: 'bam', text: 'bam', author: {connect: {id: otherUser.id}} } } }, }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not authorized/gi); }); test('make sure you cant update another users post', async () => { const currUser = testData.users[0]; const result = await graphql({ schema, contextValue: context(currUser, false), source: print(updatePost), variableValues: { input: {where: {id: testData.posts[0].id}, data: { title: 'update' } } }, }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not authorized/ig); }); test('make sure you cant read own password', async () => { const user = testData.users[0]; const result = await graphql({ schema, contextValue: context(user, false), source: print(gql` query { user(id: "${user.id}") { id username email password } } `) }); expect(result.errors).not.toBeUndefined(); expect(result.errors[0].message).toMatch(/not authorized/ig); }); });
the_stack
import * as React from "react"; import { useTranslation } from "react-i18next"; import { Card, Col, Row, Skeleton, Switch, Tooltip, Typography } from "antd"; import { CheckOutlined, CloseOutlined } from "@ant-design/icons"; import { Pie } from "@antv/g2plot"; import BigNumber from "bignumber.js"; import forEach from "lodash/forEach"; import orderBy from "lodash/orderBy"; import { Theme, PreferencesContext } from "api/contexts/Preferences"; import { Representative, RepresentativesContext, } from "api/contexts/Representatives"; import { ConfirmationQuorumContext } from "api/contexts/ConfirmationQuorum"; import { KnownAccountsBalance } from "api/hooks/use-known-accounts-balance"; import QuestionCircle from "components/QuestionCircle"; const { Text, Title } = Typography; const getDelegatedEntity = async (): Promise<any[] | undefined> => { try { const res = await fetch("/api/delegated-entity"); const json = await res.json(); return json; } catch (err) {} }; let representativesChart: Pie | null = null; interface Props { isIncludeOfflineRepresentatives: boolean; setIsIncludeOfflineRepresentatives: Function; isGroupedByEntities: boolean; setIsGroupedByEntities: Function; } const Representatives: React.FC<Props> = ({ isIncludeOfflineRepresentatives, setIsIncludeOfflineRepresentatives, isGroupedByEntities, setIsGroupedByEntities, }) => { const { t } = useTranslation(); const { theme } = React.useContext(PreferencesContext); const { representatives, isLoading: isRepresentativesLoading, } = React.useContext(RepresentativesContext); const [nakamotoCoefficient, setNakamotoCoefficient] = React.useState( [] as Representative[], ); const [ principalRepresentatives, setPrincipalRepresentatives, ] = React.useState([] as Representative[]); const { confirmationQuorum: { principal_representative_min_weight: principalRepresentativeMinWeight = 0, online_weight_quorum_percent: onlineWeightQuorumPercent, }, isLoading: isConfirmationQuorumLoading, } = React.useContext(ConfirmationQuorumContext); const [delegatedEntities, setDelegatedEntities] = React.useState( [] as KnownAccountsBalance[], ); const representativesSkeletonProps = { active: true, paragraph: true, loading: isRepresentativesLoading, }; React.useEffect(() => { getDelegatedEntity().then(delegatedEntities => { setDelegatedEntities(delegatedEntities || []); }); }, []); React.useEffect(() => { if ( isRepresentativesLoading || isConfirmationQuorumLoading || !principalRepresentatives.length || !Array.isArray(delegatedEntities) ) return; const aliasSeparator = "|||"; // const stake = new BigNumber(rawToRai(onlineStakeTotal)).toNumber(); let filteredRepresentatives = isIncludeOfflineRepresentatives ? [...principalRepresentatives] : [...principalRepresentatives].filter(({ isOnline }) => isOnline); let stake = 0; forEach(filteredRepresentatives, representative => { stake = new BigNumber(stake).plus(representative.weight).toNumber(); }); if (isGroupedByEntities && delegatedEntities.length) { // @TODO find a more scalable option const groups: { [key: string]: number } = { "Nano Foundation": 0, Binance: 0, Kraken: 0, Huobi: 0, Kucoin: 0, }; // @ts-ignore added representative key delegatedEntities.forEach(({ alias, account, representative, total }) => { const accountIndex = filteredRepresentatives.findIndex( ({ account: representativeAccount }) => representativeAccount === account, ); const representativeIndex = filteredRepresentatives.findIndex( ({ account }) => account === representative, ); if (accountIndex > -1) { filteredRepresentatives[accountIndex] = { ...filteredRepresentatives[accountIndex], weight: filteredRepresentatives[accountIndex].weight + total, }; } else { filteredRepresentatives.push({ alias, account, isOnline: true, isPrincipal: true, weight: total, }); } if (representativeIndex > -1) { filteredRepresentatives[representativeIndex] = { ...filteredRepresentatives[representativeIndex], weight: filteredRepresentatives[representativeIndex].weight - total, }; } }); filteredRepresentatives = filteredRepresentatives.filter( ({ alias, weight }) => { const group = alias ? Object.keys(groups).find(group => alias.toLowerCase()?.includes(group.toLowerCase()), ) : null; if (group) { groups[group] = new BigNumber(groups[group]) .plus(weight) .toNumber(); } return !group; }, ); const groupedEntities = Object.entries(groups).map(([group, weight]) => ({ account: "", weight: weight, isOnline: true, isPrincipal: true, alias: group, })); filteredRepresentatives = filteredRepresentatives .concat(groupedEntities) .filter(({ weight }) => weight >= principalRepresentativeMinWeight); filteredRepresentatives = orderBy( filteredRepresentatives, ["weight"], ["desc"], ); } const nakamotoCoefficient: Representative[] = []; let nakamotoCoefficientWeight = 0; let totalWeight = 0; forEach(filteredRepresentatives, representative => { const nextWeight = new BigNumber(nakamotoCoefficientWeight) .plus(representative.weight) .toNumber(); totalWeight = new BigNumber(totalWeight) .plus(representative.weight) .toNumber(); const percent = new BigNumber(nextWeight) .times(100) .dividedBy(stake) .toNumber(); nakamotoCoefficientWeight = nextWeight; nakamotoCoefficient.push(representative); if (percent > parseInt(onlineWeightQuorumPercent)) { return false; } }); setNakamotoCoefficient(nakamotoCoefficient); const data = filteredRepresentatives.map(({ weight, account, alias }) => { const value = parseFloat( new BigNumber(weight).times(100).dividedBy(stake).toFixed(2), ); return { // @NOTE Remove symbol characters as they are causing the chart to crash // on latest Safari & mobile chrome. Re-enable once it's fixed alias: `${alias?.replace(/\W/g, "") || ""}${aliasSeparator}${account}`, value, }; }); const config = { data, angleField: "value", colorField: "alias", radius: 0.8, // theme: 'dark', label: { visible: true, type: "outer", style: theme === Theme.DARK ? { fill: "white", stroke: "none", } : { fill: "black", stroke: "#fff", }, }, legend: { visible: true, itemName: { // @ts-ignore formatter: (text: string) => { const [alias, account] = text.split(aliasSeparator); return alias || account || t("common.unknown"); }, }, }, tooltip: { showTitle: false, // @ts-ignore formatter: ({ value, alias: rawAlias }) => { const [alias, account] = rawAlias.split(aliasSeparator); return { name: alias || account || t("common.unknown"), value: `${value}%`, }; }, }, interactions: [{ type: "element-active" }], }; if (!representativesChart) { representativesChart = new Pie( document.getElementById("representatives-chart") as HTMLElement, // @ts-ignore config, ); representativesChart.render(); } else { // @ts-ignore representativesChart.update(config); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [ theme, principalRepresentatives, isRepresentativesLoading, isConfirmationQuorumLoading, isIncludeOfflineRepresentatives, isGroupedByEntities, delegatedEntities, ]); React.useEffect(() => { if (isRepresentativesLoading || !representatives.length) return; const filteredRepresentatives = representatives.filter( ({ isPrincipal }) => isPrincipal, ); setPrincipalRepresentatives(filteredRepresentatives); }, [representatives, isRepresentativesLoading]); React.useEffect(() => { return () => { representativesChart?.destroy(); representativesChart = null; }; }, []); return ( <> <Title level={3}>{t("pages.representatives.voteDistribution")}</Title> <Card size="small" bordered={false} className="detail-layout"> <Row gutter={6}> <Col xs={20} md={12}> {t("pages.representatives.includeOfflineRepresentatives")} </Col> <Col xs={4} md={12}> <Switch disabled={isRepresentativesLoading} checkedChildren={<CheckOutlined />} unCheckedChildren={<CloseOutlined />} onChange={(checked: boolean) => { setIsIncludeOfflineRepresentatives(checked); }} defaultChecked={isIncludeOfflineRepresentatives} /> </Col> </Row> <Row gutter={6}> <Col xs={20} md={12}> {t("pages.representatives.groupByEntities")} <Tooltip placement="right" title={t("tooltips.groupByEntities")}> <QuestionCircle /> </Tooltip> </Col> <Col xs={4} md={12}> <Switch disabled={isRepresentativesLoading || !delegatedEntities.length} checkedChildren={<CheckOutlined />} unCheckedChildren={<CloseOutlined />} onChange={(checked: boolean) => { setIsGroupedByEntities(checked); }} checked={ // Ensure the API returns delegatedEntities to enable the switch delegatedEntities.length ? isGroupedByEntities : false } /> </Col> </Row> <Row> <Col xs={24} md={12}> {t("pages.representatives.nakamotoCoefficient")} <Tooltip placement="right" title={t("tooltips.nakamotoCoefficient", { onlineWeightQuorumPercent: onlineWeightQuorumPercent || 0, })} > <QuestionCircle /> </Tooltip> </Col> <Col xs={24} md={12}> <Skeleton active paragraph={false} loading={!nakamotoCoefficient.length} > <Text>{nakamotoCoefficient.length}</Text> </Skeleton> </Col> </Row> <Row> <Col xs={24}> <Text style={{ fontSize: "12px" }}> {t("pages.representatives.voteDistributionDescription")} </Text> </Col> </Row> <Skeleton {...representativesSkeletonProps}> <div id="representatives-chart" /> </Skeleton> </Card> </> ); }; export default Representatives;
the_stack
import moment from "moment"; import * as Database from "./database"; import IRepo from "../interface/IRepo"; import GroupType from "../enum/GroupType"; import SearchType from "../enum/SearchType"; export default class DBHandler { private dbName: string; private RxDB; constructor(dbOrName) { if (typeof dbOrName === "string") { this.dbName = dbOrName; } else { this.RxDB = dbOrName; } } checkInstance = () => { if (!this.RxDB) { throw new Error("You must call `initDB()` first"); } }; initDB = async () => { if (!this.RxDB) { this.RxDB = await Database.get(this.dbName); } return this; }; upsertProfile = async profile => { this.checkInstance(); let meCollection = this.RxDB.me; const doc = await meCollection.upsert({ key: profile.id.toString(), id: profile.id, login: profile.login, avatarUrl: profile.avatar_url, gravatarId: profile.gravatar_id, url: profile.url, htmlUrl: profile.html_url, followersUrl: profile.followers_url, followingUrl: profile.following_url, gistsUrl: profile.gists_url, starredUrl: profile.starred_url, subscriptionsUrl: profile.subscriptions_url, organizationsUrl: profile.organizations_url, reposUrl: profile.repos_url, eventsUrl: profile.events_url, receivedEventsUrl: profile.received_events_url, type: profile.type, siteAdmin: profile.site_admin, name: profile.name, company: profile.company || "", blog: profile.blog, location: profile.location, hireable: !!profile.hireable, publicRepos: profile.public_repos, publicGists: profile.public_gists, followers: profile.followers, following: profile.following, createdAt: profile.created_at, createdTime: Math.floor(new Date(profile.created_at).getTime() / 1000), updatedAt: profile.updated_at, updatedTime: Math.floor(new Date(profile.updated_at).getTime() / 1000), privateGists: profile.private_gists, totalPrivateRepos: profile.total_private_repos, ownedPrivateRepos: profile.owned_private_repos, diskUsage: profile.disk_usage, collaborators: profile.collaborators, twoFactorAuthentication: profile.two_factor_authentication, plan: { name: profile.plan.name, space: profile.plan.space, collaborators: profile.plan.collaborators, privateRepos: profile.plan.private_repos } }); return doc; }; getProfile = async (username = "") => { this.checkInstance(); let meCollection = this.RxDB.me; let query = meCollection.findOne(); if (username) { query = query.where("login").eq(username); } let doc = await query.exec(); return doc.toJSON(); }; upsertRepos = async repos => { this.checkInstance(); let reposCollection = this.RxDB.repos; let inserts: any[] = []; let index = 0; let repoIds: string[] = []; repos.reverse(); repos.forEach(repo => { index++; repoIds.push(repo.id); inserts.push( reposCollection.upsertExcludeFields( { key: repo.id.toString(), id: repo.id, name: repo.name, fullName: repo.full_name, owner: repo.owner.id, private: repo.private, htmlUrl: repo.html_url, description: repo.description || "", fork: repo.fork, url: repo.url, forksUrl: repo.forks_url, keysUrl: repo.keys_url, collaboratorsUrl: repo.collaborators_url, teamsUrl: repo.teams_url, hooksUrl: repo.hooks_url, issueEventsUrl: repo.issue_events_url, eventsUrl: repo.events_url, assigneesUrl: repo.assignees_url, branchesUrl: repo.branches_url, tagsUrl: repo.tags_url, blobsUrl: repo.blobs_url, gitTagsUrl: repo.git_tags_url, gitRefsUrl: repo.git_refs_url, treesUrl: repo.trees_url, statusesUrl: repo.statuses_url, languagesUrl: repo.languages_url, stargazersUrl: repo.stargazers_url, contributorsUrl: repo.contributors_url, subscribersUrl: repo.subscribers_url, subscriptionUrl: repo.subscription_url, commitsUrl: repo.commits_url, gitCommitsUrl: repo.git_commits_url, commentsUrl: repo.comments_url, issueCommentUrl: repo.issue_comment_url, contentsUrl: repo.contents_url, compareUrl: repo.compare_url, mergesUrl: repo.merges_url, archiveUrl: repo.archive_url, downloadsUrl: repo.downloads_url, issuesUrl: repo.issues_url, pullsUrl: repo.pulls_url, milestonesUrl: repo.milestones_url, notificationsUrl: repo.notifications_url, labelsUrl: repo.labels_url, releasesUrl: repo.releases_url, deploymentsUrl: repo.deployments_url, createdAt: repo.created_at, createdTime: Math.floor(moment(repo.created_at).valueOf() / 1000), updatedAt: repo.updated_at, updatedTime: Math.floor(moment(repo.updated_at).valueOf() / 1000), pushedAt: repo.pushed_at, pushedTime: Math.floor(moment(repo.pushed_at).valueOf() / 1000), gitUrl: repo.git_url, sshUrl: repo.ssh_url, cloneUrl: repo.clone_url, svnUrl: repo.svn_url, homePage: repo.homepage || "", size: repo.size, stargazersCount: repo.stargazers_count, stars: repo.stargazers_count, watchersCount: repo.watchers_count, lang: repo.language || "Unknown", hasIssues: repo.has_issues, hasDownloads: repo.has_downloads, hasWiki: repo.has_wiki, hasPages: repo.has_pages, forksCount: repo.forks_count, // mirrorUrl: repo.mirror_url, openIssuesCount: repo.open_issues_count, forks: repo.forks, openIssues: repo.open_issues, watchers: repo.watchers, defaultBranch: repo.default_branch, permissions: repo.permissions, score: 0, flag: false, read: false, note: "", readme: "", defaultOrder: index }, ["score", "indexedScore", "flag", "read", "note", "readme"] ) ); }); // now remove some repos in db but not in fetched data(they were unstarred) await reposCollection.find({ id: { $nin: repoIds } }).remove(); const results: any[] = await Promise.all(inserts); return results.map(result => result.toJSON()); }; getRepos = async conditions => { this.checkInstance(); const reposCollection = this.RxDB.repos; let args: { [key: string]: any } = {}; if (conditions.group) { const id = conditions.group.id; // string switch (conditions.group.type) { case GroupType.GROUP_TYPE_LANGUAGE: args = { lang: { $eq: id } }; // query = reposCollection.find(args) break; case GroupType.GROUP_TYPE_CATEGORY: // we should go to category table to find the repos list const catsCollection = this.RxDB.categories; const category = await catsCollection.findOne({ key: { $eq: id } }).exec(); const repoIds = category.repos; args = { id: { $in: repoIds } }; // query = reposCollection.find(args) break; case GroupType.GROUP_TYPE_UNKNOWN: const catsCollection2 = this.RxDB.categories; const categories = await catsCollection2.find().exec(); let nrepoIds = []; categories.forEach(cat => { nrepoIds.concat(cat.repos); }); nrepoIds = Array.from(new Set(nrepoIds)); args = { id: { $nin: nrepoIds } }; // query = reposCollection.find(args) break; default: // query = reposCollection.find() } } if (conditions.filter) { if (conditions.filter.hasFlag) { args.flag = { $eq: true }; } if (conditions.filter.hasNote) { args.note = { $ne: "" }; } if (conditions.filter.unread) { args.read = { $eq: false }; } } if (conditions.search && conditions.search.key) { const key = conditions.search.key; switch (conditions.search.field) { case SearchType.SEARCH_FIELD_REPO_NAME: args.name = { $regex: new RegExp(key, "i") }; // query = query.find(searchArgs) break; case SearchType.SEARCH_FIELD_REPO_DESCRIPTION: args.description = { $regex: new RegExp(key, "i") }; // query = query.find(searchArgs) break; case SearchType.SEARCH_FIELD_REPO_NOTE: if (!args.note) { args.note = { $regex: new RegExp(key, "i") }; } else { args.note = Object.assign({}, args.note, { $regex: new RegExp(key, "i") }); } // query = query.find(searchArgs) break; case SearchType.SEARCH_FIELD_REPO_TAGS: const tag = await this.RxDB.tags .findOne({ name: { $regex: new RegExp("^" + key + "$", "i") } }) .exec(); const tagRepoIds = tag && tag.repos instanceof Array ? tag.repos : []; if (args.id) { const prevRepoIds = args.id.$in; const postRepoIds = tagRepoIds.filter( item => prevRepoIds.indexOf(item) > -1 ); args.id = { $in: postRepoIds }; } else { args.id = { $in: tagRepoIds }; } break; case SearchType.SEARCH_FIELD_ALL: // currently not include tags default: // query = query.find({$or: [{name: {$regex: new RegExp(key, 'i')}}, {description: {$regex: new RegExp(key, 'i')}}, {note: {$regex: new RegExp(key, 'i')}}]}) // TODO this does not work but no error // so use the bad way let tempRepoIds: string[] = []; const nameSearchDocs = await reposCollection .find( Object.assign({}, args, { name: { $regex: new RegExp(key, "i") } }) ) .exec(); nameSearchDocs.forEach(nameSearchDoc => { tempRepoIds.push(nameSearchDoc.id); }); const introSearchDocs = await reposCollection .find( Object.assign({}, args, { description: { $regex: new RegExp(key, "i") } }) ) .exec(); introSearchDocs.forEach(introSearchDoc => { tempRepoIds.push(introSearchDoc.id); }); const noteSearchDocs = await reposCollection .find( Object.assign({}, args, { note: { $regex: new RegExp(key, "i") } }) ) .exec(); noteSearchDocs.forEach(noteSearchDoc => { tempRepoIds.push(noteSearchDoc.id); }); tempRepoIds = Array.from(new Set(tempRepoIds)); if (args.id) { args.id.$in = Array.from( new Set(new Array().concat(args.id.$in, tempRepoIds)) ); } else { args.id = { $in: tempRepoIds }; } // query = reposCollection.find(searchArgs) } } let query = reposCollection.find(args); if (conditions.order) { const sc = conditions.order.desc ? -1 : 1; query = query.sort({ [conditions.order.by]: sc }); } let docs = await query.exec(); let repos: IRepo[] = []; docs.forEach(doc => { let repo = doc.toJSON(); repos.push(repo); }); return repos; }; upsertOwners = async repos => { this.checkInstance(); const authorsCollection = this.RxDB.authors; let owners = {}; repos.forEach(repo => { // we need this step to remove duplicatives // otherwise it will cause Document update conflict repo.owner.repoId = repo.id; owners["_" + repo.owner.id] = repo.owner; }); let ownerIds: string[] = []; let inserts: any[] = []; for (let key in owners) { if (!owners.hasOwnProperty(key)) { continue; } let owner = owners[key]; ownerIds.push(owner.id); inserts.push( authorsCollection.upsert({ key: owner.repoId + "_" + owner.id, id: owner.id, login: owner.login, avatarUrl: owner.avatar_url, gravatarId: owner.gravatar_id, url: owner.url, htmlUrl: owner.html_url, followersUrl: owner.followers_url, followingUrl: owner.following_url, gistsUrl: owner.gists_url, starredUrl: owner.starred_url, subscriptionsUrl: owner.subscriptions_url, organizationsUrl: owner.organizations_url, reposUrl: owner.repos_url, eventsUrl: owner.events_url, receivedEventsUrl: owner.received_events_url, type: owner.type, siteAdmin: owner.site_admin, isOwner: true, repoId: owner.repoId }) ); } // now remove some owners in db but not in fetched data await authorsCollection.find({ isOwner: { $eq: true }, id: { $nin: ownerIds } }).remove(); const results = await Promise.all(inserts); return results.map(result => result.toJSON()); }; upsertContributors = async (repoId, contributors) => { this.checkInstance(); const repo = await this.RxDB.repos.findOne({ id: { $eq: repoId } }).exec(); if (!repo) { return false; } const authorsCollection = this.RxDB.authors; let contributorIds: string[] = []; let inserts: any[] = []; contributors.forEach(contributor => { if (contributor.id !== repo.owner) { contributorIds.push(contributor.id); inserts.push( authorsCollection.upsert({ key: repoId + "_" + contributor.id, id: contributor.id, login: contributor.login, avatarUrl: contributor.avatar_url, gravatarId: contributor.gravatar_id, url: contributor.url, htmlUrl: contributor.html_url, followersUrl: contributor.followers_url, followingUrl: contributor.following_url, gistsUrl: contributor.gists_url, starredUrl: contributor.starred_url, subscriptionsUrl: contributor.subscriptions_url, organizationsUrl: contributor.organizations_url, reposUrl: contributor.repos_url, eventsUrl: contributor.events_url, receivedEventsUrl: contributor.received_events_url, type: contributor.type, siteAdmin: contributor.site_admin, isOwner: false, repoId // contributions }) ); } }); // now remove some contributors in db but not in fetched data await authorsCollection .find({ repoId: { $eq: repoId }, isOwner: { $eq: false }, id: { $nin: contributorIds } }) .remove(); await Promise.all(inserts); return await this.getRepoContributors(repoId); }; getRepoContributors = async repoId => { this.checkInstance(); const authorsCollection = this.RxDB.authors; const docs = await authorsCollection.find({ repoId: { $eq: repoId } }).exec(); return docs.map(doc => doc.toJSON()); }; recordReposCount = async count => { this.checkInstance(); const settingsCollection = this.RxDB.settings; const doc = await settingsCollection.findOne({ id: { $eq: "reposCount" } }).exec(); const oldCount = doc ? parseInt(doc.value, 10) : 0; if (doc) { doc.value = count.toString(); await doc.save(); } else { settingsCollection.upsert({ id: "reposCount", value: count.toString() }); } return count - oldCount; }; upsertLanguages = async repos => { this.checkInstance(); let langsCollection = this.RxDB.languages; // await langsCollection.find().remove() // clean the collection let langs: { [key: string]: string[] } = { _Unknown: [] }; repos.forEach(repo => { if (!repo.language) { langs._Unknown.push(repo.id); } else { if (langs["_" + repo.language]) { langs["_" + repo.language].push(repo.id); } else { langs["_" + repo.language] = [repo.id]; } } }); let inserts: any[] = []; let index = 1; for (let key in langs) { if (langs.hasOwnProperty(key)) { inserts.push( langsCollection.upsert({ key: key.substr(1).toLowerCase(), id: index, name: key.substr(1), repos: langs[key] }) ); index++; } } return Promise.all(inserts); }; getLanguages = async () => { this.checkInstance(); let langsCollection = this.RxDB.languages; let query = langsCollection.find(); let docs = await query.exec(); let languages: any[] = []; docs.forEach(doc => { let language = doc.toJSON(); language.reposCount = doc.countRepos(); languages.push(language); }); return languages; }; getCategories = async () => { this.checkInstance(); let catsCollection = this.RxDB.categories; let query = catsCollection.find(); let docs = await query.exec(); let categories: any[] = []; docs.forEach(doc => { let category = doc.toJSON(); category.reposCount = doc.countRepos(); categories.push(category); }); return categories; }; upsertCategory = async name => { this.checkInstance(); let catsCollection = this.RxDB.categories; // let exist = await catsCollection.findOne({name: {$eq: name}}).exec() const regKey = "^" + name + "$"; let exist = await catsCollection .findOne({ name: { $regex: new RegExp(regKey, "i") } }) .exec(); if (exist) { throw new Error("Duplicative category name"); } let docs = await catsCollection .find() .sort({ id: -1 }) .limit(1) .exec(); const start = docs instanceof Array && docs.length > 0 ? docs[0].id + 1 : 1; const date = new Date(); const category = { key: start.toString(), id: start, name: name, repos: [], createdAt: date.toISOString(), createdTime: Math.floor(date.getTime() / 1000) }; let upsert = await catsCollection.upsert(category); return upsert; }; deleteCategory = async id => { this.checkInstance(); let catsCollection = this.RxDB.categories; try { await catsCollection.find({ id: { $eq: id } }).remove(); return id; } catch (err) { throw new Error(err); } }; _upsertTag = async name => { // private, return RxDoc this.checkInstance(); let tagsCollection = this.RxDB.tags; const regKey = "^" + name + "$"; let exist = await tagsCollection .findOne({ name: { $regex: new RegExp(regKey, "i") } }) .exec(); if (exist) { return exist; } let docs = await tagsCollection .find() .sort({ id: -1 }) .limit(1) .exec(); const start = docs instanceof Array && docs.length > 0 ? docs[0].id + 1 : 1; const date = new Date(); const tag = { key: start.toString(), id: start, name: name, repos: [], createdAt: date.toISOString(), createdTime: Math.floor(date.getTime() / 1000) }; let upsert = await tagsCollection.upsert(tag); return upsert; }; getTags = async tagIds => { this.checkInstance(); const tagsCollection = this.RxDB.tags; const docs = await tagsCollection .find({ id: { $in: tagIds } }) .sort({ id: 1 }) .exec(); return docs.map(doc => doc.toJSON()); }; getRepoTags = async repoId => { this.checkInstance(); const tagsCollection = this.RxDB.tags; const docs = await tagsCollection .find({ repos: { $elemMatch: { $eq: repoId } } }) .sort({ id: 1 }) .exec(); return docs.map(doc => doc.toJSON()); }; getRepoCategories = async repoId => { this.checkInstance(); const catsCollection = this.RxDB.categories; const docs = await catsCollection .find({ repos: { $elemMatch: { $eq: repoId } } }) .sort({ id: 1 }) .exec(); return docs.map(doc => doc.toJSON()); }; updateRepo = async obj => { this.checkInstance(); if (!obj.id) { return false; } const reposCollection = this.RxDB.repos; const id = obj.id; let repo = await reposCollection.findOne({ id: { $eq: id } }).exec(); if (!repo) { throw new Error("The specified repo is not exist"); } for (let prop in obj) { if (prop !== "id" && obj.hasOwnProperty(prop)) { repo[prop] = obj[prop]; // TODO validate the prop existed in schema } } repo.rxChange = Math.floor(new Date().getTime() / 1000); await repo.save(); return repo.toJSON(); }; updateRepoCategories = async (id, catIds) => { this.checkInstance(); const catsCollection = this.RxDB.categories; const categoryDocs = await catsCollection .find({ id: { $in: catIds } }) .sort({ id: 1 }) .exec(); let updates: any[] = []; let categories: any[] = []; categoryDocs.forEach(categoryDoc => { if (categoryDoc.repos.indexOf(id) < 0) { let repoIds = categoryDoc.repos; repoIds.push(id); categoryDoc.repos = repoIds; categoryDoc.updatedTime = Math.floor(new Date().getTime() / 1000); updates.push(categoryDoc.save()); } categories.push(categoryDoc.toJSON()); }); await Promise.all(updates); const repo = await this.RxDB.repos.findOne({ id: { $eq: id } }).exec(); let repoObj = repo.toJSON(); repoObj._categories = categories; return repoObj; }; addRepoTag = async (id, tagName) => { this.checkInstance(); const reposCollection = this.RxDB.repos; let repo = await reposCollection.findOne({ id: { $eq: id } }).exec(); if (!repo) { throw new Error("The specified repo is not exist"); } // fisrt upsert this tag into tags collection let tag = await this._upsertTag(tagName); let repoIds = tag.repos; if (repoIds.indexOf(id) < 0) { repoIds.push(id); } tag.repos = repoIds; tag.updatedTime = Math.floor(new Date().getTime() / 1000); await tag.save(); const repoTags = await this.getRepoTags(id); let repoObj = repo.toJSON(); repoObj._tags = repoTags; return repoObj; }; removeRepoTag = async (id, tagName) => { this.checkInstance(); const reposCollection = this.RxDB.repos; let repo = await reposCollection.findOne({ id: { $eq: id } }).exec(); if (!repo) { throw new Error("The specified repo is not exist"); } // fisrt get the tag const tag = await this._upsertTag(tagName); let repoIds = tag.repos; if (repoIds instanceof Array) { const repoIdIndex = repoIds.indexOf(id); if (repoIdIndex > -1) { repoIds.splice(repoIdIndex, 1); } } tag.repos = repoIds; tag.updatedTime = Math.floor(new Date().getTime() / 1000); await tag.save(); const repoTags = await this.getRepoTags(id); let repoObj = repo.toJSON(); repoObj._tags = repoTags; return repoObj; }; }
the_stack
import { objectName, getLogger, Logger } from "extraterm-logging"; /** * Convert an array-like object to a real array. * * @param {Object} fakeArray An array-like object with get() and length support. * @return {Array} A real array object with the elements as fakeArray. */ export function toArray<T>(fakeArray: { [key: number]: T; length: number; }): T[] { const result: T[] = []; const len = fakeArray.length; for (let i=0; i<len; i++) { result.push(fakeArray[i]); } return result; } export interface LeftRightPair { left: Node[]; right: Node[]; } export function getShadowRoot(self: Element): ShadowRoot { return self.webkitShadowRoot ? self.webkitShadowRoot : self.shadowRoot; } export function getShadowId(el: HTMLElement, id: string): HTMLElement { const shadowRoot = getShadowRoot(el); if (shadowRoot === null) { return null; } return <HTMLElement> shadowRoot.querySelector('#' + id); } /** * Converts a node list to a real array. * * @param nodeList the node list to convert. * @return a new array holding the same contents as the node list. */ export function nodeListToArray(nodeList: NodeList): Node[] { let i = 0; const result: Node[] = []; const len = nodeList.length; for (i=0; i<len; i++) { result.push(nodeList[i]); } return result; } /** * Add an event listener which blocks an event and retransmits it. * * @param listenTarget the object on which to intercept the custom event * @param eventName the name of the Custom Event to intercept and retransmit * @param retransmitTarget (Optional) the element on which to retransmit the event */ export function addCustomEventResender(listenTarget: EventTarget, eventName: string, retransmitTarget: EventTarget=null): void { listenTarget.addEventListener(eventName, (ev: CustomEvent) => { const inflightResentEvent = inflightResentEvents.get(ev.target); if (inflightResentEvent === ev && inflightResentEvent.type === eventName) { return; } ev.stopPropagation(); const detail = ev.detail; const bubbles = ev.bubbles; const event = new CustomEvent(eventName, { bubbles: bubbles, detail: detail }); inflightResentEvents.set(listenTarget, event); (retransmitTarget === null ? listenTarget : retransmitTarget).dispatchEvent(event); inflightResentEvents.delete(listenTarget); }); } const inflightResentEvents = new Map<EventTarget, CustomEvent>(); //------------------------------------------------------------------------- const _log = getLogger("DomUtils.focusElement()"); const LOG_FOCUS_ELEMENT = false; const DEBUG_FOCUS_ELEMENT = false; /** * Focus an element * * This calls `focus()` on an element but also includes extra internal * facilities for logging calls and for checking that the `focus()` call was * successful. * * @param target the element to focus. * @param callerLogger Logger object from the caller. * @param preventScroll This corresponds to the `preventScroll` parameter to * `HTMLElement.focus()`. */ export function focusElement(target: HTMLElement, callerLogger: Logger=null, preventScroll=false): void { let targetName = ""; if (LOG_FOCUS_ELEMENT) { targetName = objectName(target); if (targetName == null) { targetName = target.tagName; } if (callerLogger != null) { _log.debug(`Calling focus() on ${targetName} from ${callerLogger.getName()}`); } else { _log.debug(`Calling focus() on ${targetName}`); } } target.focus({ preventScroll }); if (DEBUG_FOCUS_ELEMENT) { const pairs = findParentChildFocusPairs(target); if ( ! checkParentChildFocusPairs(pairs)) { debugParentChildFocusPairs(pairs); } } if (LOG_FOCUS_ELEMENT) { _log.debug(`Done focus() on ${targetName}`); } } interface TreeChildPair { child: HTMLElement; root: Document | ShadowRoot; } function findParentChildFocusPairs(target: HTMLElement): TreeChildPair[] { const parentNodes = nodePathToRoot(target); const pairs: TreeChildPair[] = []; let currentPair: TreeChildPair = { child: target, root: null }; for (let i=0; i<parentNodes.length; i++) { const node = parentNodes[i]; if (currentPair) { if (node instanceof ShadowRoot || node instanceof Document) { currentPair.root = node; pairs.push(currentPair); currentPair = null; } } else { currentPair = { child: <HTMLElement> node, root: null }; } } return pairs; } function checkParentChildFocusPairs(pairs: TreeChildPair[]): boolean { for (const pair of pairs) { if (pair.root.activeElement !== pair.child) { return false; } } return true; } function debugParentChildFocusPairs(pairs: TreeChildPair[]): void { const parts: string[] = []; parts.push("Deepest first"); for (const pair of pairs) { if (pair.root.activeElement !== pair.child) { parts.push(`! ${formatNodeName(pair.root)} active element != ${formatNodeName(pair.child)}`); } else { parts.push(` ${formatNodeName(pair.root)} active element == ${formatNodeName(pair.child)}`); } } _log.warn(parts.join("\n")); } /** * Get a human readable name for a node. * * @param node * @return human readable name */ function formatNodeName(node: Node): string { const name = objectName(node); if (name != null) { return name; } if (node instanceof HTMLElement) { return node.tagName; } if (node instanceof ShadowRoot) { return `ShadowRoot of ${formatNodeName(node.host)}`; } return "" + node; } function focusParents(pairs: TreeChildPair[]): void { for (let i=pairs.length-1; i>=0; i--) { const pair = pairs[i]; if (pair.root.activeElement !== pair.child) { pair.child.focus(); } } } /** * Prevent an Element from scrolling. * * @param el the element to prevent all scrolling on. */ export function preventScroll(el: HTMLElement): void { el.addEventListener('scroll', (ev) => { el.scrollTop = 0; }, true); el.addEventListener('scroll', (ev) => { el.scrollTop = 0; }); } /** * Convert a length with 'px' suffix to a plain float. * * @param length the length value as a string * @return the length as a number */ export function pixelLengthToFloat(length: string | number): number { if (typeof length === "string") { const lengthStr = length.indexOf("px") !== -1 ? length.substr(0, length.length-2) : length; return parseFloat(lengthStr); } else { return length; } } /** * Convert a length with 'px' suffix to a plain integer. * * @param length the length value as a string * @return the length as a number */ export function pixelLengthToInt(length: string | number): number { if (typeof length === "string") { return Math.floor(pixelLengthToFloat(length)); } else { return length; } } /** * Expand a HTML string into Document Fragment. * * @param {html} the HTML code to use. * @return A Document Fragment containing the nodes defined by the `html` parameter. */ export function htmlToFragment(html: string): DocumentFragment { const div = document.createElement("DIV"); div.innerHTML = html; const frag = document.createDocumentFragment(); while (div.childNodes.length !== 0) { frag.appendChild(div.childNodes[0]); } return frag; } /** * Update the list of children on an element. * * This function updates the children while trying to do as few changes on * the DOM as possible. * * @param el the Element to update. * @param targetChildrenList the desired list of child elements. */ export function setElementChildren(el: Element, targetChildrenList: Element[]): void { // Delete phase const unneededChildrenSet = new Set<Element>(toArray(el.children)); for (const kid of targetChildrenList) { unneededChildrenSet.delete(kid); } for (const kid of unneededChildrenSet) { el.removeChild(kid); } // Insert the missing children and fix the order. for (let i=0; i < targetChildrenList.length; i++) { if (el.children.length <= i) { el.appendChild(targetChildrenList[i]); } else { if (el.children.item(i) !== targetChildrenList[i]) { el.insertBefore(targetChildrenList[i], el.children.item(i)); } } } } /** * Test if a node is in the DOM tree. * * @param node the node to test * @return true if the node is attached somewhere inside its DOM tree. */ export function isNodeInDom(node: Node): boolean { let currentNode = node; let nextNode = node; while (true) { currentNode = nextNode; if (currentNode.parentNode != null) { nextNode = currentNode.parentNode; } else if (currentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE && (<ShadowRoot> currentNode).host != null) { nextNode = (<ShadowRoot> currentNode).host; } else { break; } } return currentNode.nodeType === Node.DOCUMENT_NODE; } /** * Remove all CSS classes from an element. */ export function removeAllClasses(el: Element): void { while (el.classList.length !== 0) { el.classList.remove(el.classList[0]); } } /** * Get the path from the node through its parents, to the root. * * This function will also traverse shadow DOM boundaries. * * @param node the node * @return the path from the node to its root parent with nodes closer to the * start node first and the ultimate parent node last. */ export function nodePathToRoot(node: Node): Node[] { let currentNode = node; let nextNode = node; const path: Node[] = []; while (true) { currentNode = nextNode; if (currentNode.parentNode != null) { nextNode = currentNode.parentNode; path.push(nextNode); } else if (currentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE && (<ShadowRoot> currentNode).host != null) { nextNode = (<ShadowRoot> currentNode).host; path.push(nextNode); } else { break; } } return path; } /** * Get the list of active/focused elements and their nested active elements. * * This function traverses Shadow DOM boundaries to find nested * active/focused elements starting from the top window. * * @returns list of active elements */ export function activeNestedElements(): Element[] { const result: Element[] = []; let activeElement = window.document.activeElement; if (activeElement != null) { while (true) { result.push(activeElement); const shadowRoot = getShadowRoot(<HTMLElement> activeElement); if (shadowRoot == null) { break; } const nextActiveElement = shadowRoot.activeElement; if (nextActiveElement == null) { break; } activeElement = nextActiveElement; } } return result; } export function findFixedPositionOffset(element: HTMLElement): { left: number, top: number } { const nodePath = nodePathToRoot(element); for (const node of nodePath) { if (node instanceof HTMLElement) { const style = window.getComputedStyle(node); if (style.position !== "static") { const pos = node.getBoundingClientRect(); return { left: pos.left, top: pos.top }; } } } return { left: 0, top: 0 }; } /** * Disassemble all of the node below a DOM subtree * * This removes all the child nodes from every child and grandchild etc in * the subtree. * * @param subtree The DOM tree to disassemble */ export function disassembleDOMTree(subtree: ChildNode | ShadowRoot): void { if (subtree == null) { return; } for (const node of subtree.childNodes) { disassembleDOMTree(node); subtree.removeChild(node); } }
the_stack
import {Injectable} from "@angular/core"; import { HttpEvent, HttpEventType, HttpHandler, HttpHeaders, HttpInterceptor, HttpProgressEvent, HttpRequest, HttpResponse } from "@angular/common/http"; import {Observable} from "rxjs"; import { v4 as uuidv4 } from 'uuid'; import {CommonUtils} from "../jigsaw/common/core/utils/common-utils"; import {RawTableData, TableData} from "../jigsaw/common/core/data/table-data"; import {PagingInfo} from "../jigsaw/common/core/data/component-data"; import {InternalUtils} from "../jigsaw/common/core/utils/internal-utils"; @Injectable() export class AjaxInterceptor implements HttpInterceptor { // 用于控制文件上传失败率,从而模拟出更逼真的上传效果,取值[0,100]越大失败的概率越高 public static uploadFailureRate = 30; private static _processors: any[] = []; public static registerProcessor(urlPattern: RegExp | string, processor: (req: HttpRequest<any>) => any, context?: any) { this._processors.push({urlPattern, processor, context}); } constructor() { AjaxInterceptor.registerProcessor('/rdk/service/app/common/paging', this.dealServerSidePagingRequest, this); AjaxInterceptor.registerProcessor(/\bmock-data\/.+$/, req => MockData.get(req.url)); } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { console.log('the ajax request is intercepted, here is the original request:'); console.log(req); const processor = AjaxInterceptor._processors.find(p => { const url = p.urlPattern; return url instanceof RegExp ? url.test(req.url) : url === req.url; }); if (processor) { const body = CommonUtils.safeInvokeCallback(processor.context, processor.processor, [req]); return this.createResult(body, req.url); } else if (req.url == '/rdk/service/common/upload') { return this.dealServerSideUploadRequest(req); } else { console.error('no mock data processor found, forwarding the request to the server...'); return next.handle(req); } } /** * Simulate XHR behavior which would provide this information in a ProgressEvent * @param req */ dealServerSideUploadRequest(req: HttpRequest<any>): Observable<HttpEvent<any>> { console.group('All additional fields within the current upload request:'); const entries = req.body.entries(); let entry = entries.next(); while (!entry.done) { console.log(entry.value[0], ':', entry.value[1]); entry = entries.next(); } console.groupEnd(); const filename = decodeURIComponent(req.body.get('filename')); const url = `upload_files/${uuidv4()}/${filename}`; const file = req.body.get('file'); if (!file) { return new Observable<HttpEvent<any>>(subscriber => { // simulate network latency setTimeout(() => { const resp = new HttpResponse({body: url, url: url, status: 200}); subscriber.next(resp); subscriber.complete(); }, InternalUtils.randomNumber(300, 2000)); }); } const total = file.size; const chunkSize = Math.ceil(total / 5); return new Observable<HttpEvent<any>>(observer => { // notify the event stream that the request was sent. observer.next({type: HttpEventType.Sent}); const random = InternalUtils.randomNumber(1, 99); if (random <= AjaxInterceptor.uploadFailureRate) { // 模拟失败 const statusTexts = [ "Bad Request", "Unauthorized", "Payment Required", "Forbidden", "Not Found", "Method Not Allowed", "Not Acceptable" ]; const r = InternalUtils.randomNumber(0, statusTexts.length - 1); observer.error({ error: 'Failed to upload, random = ' + random, headers: new HttpHeaders(), name: "HttpErrorResponse", message: 'Failed to upload, random = ' + random, ok: false, status: 500, statusText: statusTexts[r], url: '' }); return; } // 模拟成功 const uploadLoop = (loaded: number) => { // N.B.: Cannot use setInterval or rxjs delay (which uses setInterval) // because e2e test won't complete. A zone thing? // Use setTimeout and tail recursion instead. setTimeout(() => { // 模拟成功 loaded += InternalUtils.randomNumber(chunkSize * 0.5, chunkSize * 1.5); loaded = Math.min(loaded, total); const progressEvent: HttpProgressEvent = { type: HttpEventType.UploadProgress, loaded, total }; observer.next(progressEvent); if (loaded >= total) { const doneResponse = new HttpResponse({status: 200, body: url}); observer.next(doneResponse); observer.complete(); return; } uploadLoop(loaded); }, InternalUtils.randomNumber(300, 2000)); } uploadLoop(0); }); } dealServerSidePagingRequest(req: HttpRequest<any>): any { const params = req.method.toLowerCase() == 'post' ? 'body' : 'params'; const service = this.getParamValue(req, params, 'service'); let paging = this.getParamValue(req, params, 'paging') ? this.getParamValue(req, params, 'paging') : null; paging = typeof paging === 'string' ? JSON.parse(paging) : paging; let filter = this.getParamValue(req, params, 'filter') ? this.getParamValue(req, params, 'filter') : null; filter = typeof filter === 'string' ? JSON.parse(filter) : filter; let sort = this.getParamValue(req, params, 'sort') ? this.getParamValue(req, params, 'sort') : null; sort = typeof sort === 'string' ? JSON.parse(sort) : sort; return PageableData.get({service, paging, filter, sort}); } getParamValue(req: HttpRequest<any>, params: string, key: string): any { const p = req[params]; return req.method.toLowerCase() == 'post' ? p[key] : p.get(key); } createResult(body: any, url: string): Observable<HttpEvent<any>> { console.log('and here is the simulated response data:'); console.log(body); return new Observable<HttpEvent<any>>(subscriber => { // simulate network latency setTimeout(() => { if (CommonUtils.isDefined(body)) { const resp = new HttpResponse({body: body, url: url, status: 200}); subscriber.next(resp); subscriber.complete(); } else { subscriber.error({ error: '<!DOCTYPE html>\n' + '<html lang="en">\n<head>\n<meta charset="utf-8">\n' + '<title>Error</title>\n</head>\n<body>\n' + '<pre>Cannot GET ' + url + '</pre>\n</body>\n</html>\n', headers: new HttpHeaders(), name: "HttpErrorResponse", message: "ajax interceptor can not find data for " + url, ok: false, status: 404, statusText: "Not Found", url: url }); } }, InternalUtils.randomNumber(300, 2000)); }); } } class PageableData { static get(req) { const result: any = new TableData([], [], []); if (!req.service) { console.error('bad argument, need a "service" property!'); return result; } const dataTable = MockData.get(req.service); if (!dataTable) { return null; } let data; if (CommonUtils.isDefined(req.filter)) { data = this._filter(dataTable, req.filter); } else { //浅拷贝一份 data = dataTable.data.concat(); } if (CommonUtils.isDefined(req.sort)) { if (data.length > 0) { //sort会改变原数据 this._sort(data, dataTable.field.indexOf(req.sort.field), req.sort.as, req.sort.order === 'desc' ? -1 : 1); } else { console.warn('empty data array, unnecessary to sort'); } } const pagingInfo: PagingInfo = new PagingInfo(); pagingInfo.pageSize = this._fixPageSize(req.paging.pageSize); pagingInfo.totalRecord = data.length; pagingInfo.currentPage = this._fixCurrentPage(req.paging.currentPage, pagingInfo); if (CommonUtils.isDefined(req.paging)) { data = this._paging(data, pagingInfo); } else { console.error('need a "paging" property!'); data = []; } result.data = data; result.paging = pagingInfo.valueOf(); result.field = dataTable.field; result.header = dataTable.header; return result; } private static _sort(data, index, sortAs, order) { if (index == -1) { console.warn('unknown which field to sort!'); return; } console.log('sort param: index = [', index, '] sortAs = [', sortAs, '] order = [', order, ']'); let sortBy; if (sortAs == 'number' || sortAs == 'int' || sortAs == 'float') { sortBy = sortAsNumber; } else if (sortAs == 'string') { sortBy = sortAsString; } else if (sortAs == 'date') { sortBy = sortAsString; } else if (!sortAs) { //自动检测 sortBy = isNaN(Number(data[0][index])) ? sortAsString : sortAsNumber; } else { try { //应用自定义排序算法 sortBy = eval(sortAs); } catch (e) { } if (!(sortBy instanceof Function)) { console.warn('invalid sort function, sorting as string...'); sortBy = sortAsString; } } data.sort(sortBy); function sortAsNumber(a, b) { return order * (a[index] - b[index]); } function sortAsString(a, b) { return order * (a[index].localeCompare(b[index])); } } private static _filter(dataTable, filter) { return filter.hasOwnProperty('rawFunction') && !!filter.rawFunction ? this._filterWithFunction(dataTable.data, filter.rawFunction, filter.context) : this._filterWithKeyword(dataTable.data, filter.key, filter.field, dataTable.field); } private static _filterWithKeyword(data, key, field, allField) { if (!key) { console.warn('invalid filter key, need at least ONE char!'); return data.concat(); } key = key.toLowerCase(); field = !!field ? field : allField; field = field instanceof Array ? field : [field]; console.log('filter param: key = [', key, '] field = [', field.join(','), '] allField = [', allField.join(','), ']'); const indexes = []; for (let i = 0; i < field.length; i++) { let idx = allField.indexOf(field[i]); if (idx == -1) { console.warn('invalid filter field:', field[i]); continue; } indexes.push(idx); } return data.filter(item => { for (let i = 0, len = indexes.length; i < len; i++) { let cell = item[indexes[i]]; if (cell == null) { continue; } cell = String(cell); //模糊搜索大小写不敏感 cell = cell.toLowerCase(); if (cell.indexOf(key) != -1) { return true; } } return false; }); } private static _filterWithFunction(data, rawFunction, context) { let func; try { func = eval('(' + rawFunction + ')'); } catch (e) { console.error('eval raw filter function error, detail: ' + e.message); return data; } if (!(func instanceof Function)) { console.warn('invalid filter function, it is not a function.'); return data; } try { return data.filter(func.bind(context)); } catch (e) { console.error('filter width function error, detail: ' + e.message); return data; } } private static _paging(data, pagingInfo) { const currentPage = pagingInfo.currentPage; const pageSize = pagingInfo.pageSize; console.log('paging param: currentPage = [', currentPage, '] pageSize = [', pageSize, ']'); const page = []; for (let i = (currentPage - 1) * pageSize, size = currentPage * pageSize; i < size && i < data.length; i++) { page.push(data[i]); } return page; } private static _fixCurrentPage(currentPage, pagingInfo) { currentPage = typeof currentPage !== 'number' || currentPage < 1 ? 1 : currentPage; const pageSize = pagingInfo.pageSize; if (currentPage * pageSize - pageSize > pagingInfo.totalRecord) { //应用给的当前页过大,调整为最后一页 console.warn('adjust currentPage[' + currentPage + '] to lastPage[' + pagingInfo.totalPage + ']'); currentPage = pagingInfo.totalPage; } return currentPage; } private static _fixPageSize(pageSize) { return typeof pageSize !== 'number' || pageSize < 1 ? 100 : pageSize; } } export class MockData { static dataSet: any; static get(url): any { this.initDataSet(); const match = url.match(/\bmock-data\/(.*)$/); return match ? this.dataSet[match[1]] : null; } static initDataSet() { if (CommonUtils.isDefined(this.dataSet)) { return; } this.dataSet = {}; // 模拟rest服务的数据 this.dataSet['big-table-data'] = this.createBigTableData(); this.dataSet['cities'] = require('../mock-data/cities.json'); this.dataSet['core-members'] = require('../mock-data/core-members.json'); this.dataSet['countries'] = require('../mock-data/countries.json'); this.dataSet['marketing'] = require('../mock-data/marketing.json'); this.dataSet['hr-list-full'] = require('../mock-data/hr-list-full.json'); this.dataSet['hr-list'] = require('../mock-data/hr-list.json'); this.dataSet['hr-list-short'] = require('../mock-data/hr-list-short.json'); this.dataSet['hr-list-complex'] = require('../mock-data/hr-list-complex.json'); this.dataSet['fish-bone-1'] = require('../mock-data/fish-bone-1.json'); this.dataSet['fish-bone-2'] = require('../mock-data/fish-bone-2.json'); this.dataSet['tree-data'] = require('../mock-data/tree-data.json'); this.dataSet['soduku-puzzles'] = require('../mock-data/soduku-puzzles.json'); this.dataSet['map/shanghai'] = require('echarts/map/json/province/shanghai.json'); this.dataSet['map/china'] = require('echarts/map/json/china.json'); this.dataSet['big-data-for-paging'] = this.createBigTableData(50000, 4); // 静态文件引用数据 this.dataSet['provinces.json'] = require('mock-data/provinces.json'); this.dataSet['cities.json'] = require('mock-data/cities.json'); this.dataSet['districts.json'] = require('mock-data/districts.json'); } static createBigTableData(rowLength = 5000, colLength = 200): RawTableData { const rtd: RawTableData = {field: [], header: [], data: []}; for (let i = 0; i < colLength; i++) { rtd.field.push('field-' + i); rtd.header.push('header-' + i); } for (let i = 0; i < rowLength; i++) { const row = []; rtd.data.push(row); for (let j = 0; j < 200; j++) { row.push(`data-${i}-${j}`); } } return rtd; } }
the_stack
import produce from "immer"; import { getInitialState } from "../store/initialState"; import { TActions } from "../actions/inspectorActions"; import { IInspectorState, IContent, IDifference, IDOM, TPath, TCodeViewType, TGenericViewType } from "../model/types"; import { GetInfo } from "../classes/GetInfo"; import { addMoreKeys } from "../../shared/helpers"; import { Settings } from "../classes/Settings"; import { getDescriptorsListView } from "../selectors/inspectorSelectors"; import { getTreeDomInstance } from "../selectors/inspectorDOMSelectors"; import { cloneDeep, uniqBy } from "lodash"; import { TAtnActions } from "../../atnDecoder/actions/atnActions"; import { getSetByUUID, getTreePartUniversal, selectedActions, selectedCommands, selectedSets } from "../../atnDecoder/selectors/atnSelectors"; import { TExpandedItem, TSelectedItem } from "../../atnDecoder/types/model"; export const inspectorReducer = (state = getInitialState(), action: TActions | TAtnActions): IInspectorState => { console.log(JSON.stringify(action, null, "\t")); switch (action.type) { // OCCULTIST case "[ATN] CLEAR_ALL": { state = produce(state, draft => { draft.atnConverter.data = []; }); break; } case "[ATN] SET_DATA": { state = produce(state, draft => { draft.atnConverter.data.push(...action.payload); }); break; } case "[ATN] EXPAND_ACTION": { state = produce(state, draft => { const { expand, recursive, uuid } = action.payload; //const treePart = getTreePartUniversal(state, uuid); const indexOf = draft.atnConverter.expandedItems.findIndex(item => { if (item.length !== action.payload.uuid.length) { return false; } const res = (item[0] === action.payload.uuid[0] && item[1] === action.payload.uuid[1]); return res; }); if (expand) { if (indexOf === -1) { draft.atnConverter.expandedItems.push(uuid); if (recursive && uuid.length === 1) { const rest:TExpandedItem[] = getSetByUUID(state, uuid[0]).actionItems.map(item => [item.__uuidParentSet__, item.__uuid__]); draft.atnConverter.expandedItems.push(...rest); } } } else { if (indexOf !== -1) { draft.atnConverter.expandedItems.splice(indexOf, 1); if (recursive && uuid.length === 1) { const rest: string[] = getSetByUUID(state, uuid[0]).actionItems.map(item => [item.__uuidParentSet__, item.__uuid__].join("|")); rest.forEach(itm => { const index = draft.atnConverter.expandedItems.findIndex((a) => { return a.join("|") === itm; }); draft.atnConverter.expandedItems.splice(index, 1); }); } } } }); break; } case "[ATN] SET_DONT_SEND_DISABLED": { state = produce(state, draft => { draft.atnConverter.dontSendDisabled = action.payload; }); break; } case "[ATN] SELECT_ACTION": { state = produce(state, draft => { const { operation, uuid } = action.payload; const {data } = state.atnConverter; if (operation === "none") { draft.atnConverter.selectedItems = []; } else if (operation === "replace") { draft.atnConverter.selectedItems = addChilds([action.payload.uuid]); } else if (operation === "subtract") { const all = addChilds([action.payload.uuid]).map(item => item.join("|")); all.forEach((itemFromAll) => { const foundIndex = draft.atnConverter.selectedItems.findIndex(itemFromDraft => (itemFromDraft.join("|") === itemFromAll)); if (foundIndex > -1) { draft.atnConverter.selectedItems.splice(foundIndex, 1); } }); } else if (operation === "add") { draft.atnConverter.selectedItems = [...state.atnConverter.selectedItems,...addChilds([action.payload.uuid])]; } function addChilds(items:TSelectedItem[]):TSelectedItem[] { //let sorted = items.sort((a, b) => a.length - b.length); const sets = items.filter(i => i.length === 1); const actions = items.filter(i => i.length === 2); const commands = items.filter(i => i.length === 3); sets.forEach(s => { data.forEach(ss => { if (ss.__uuid__ === s[0]) { ss.actionItems.forEach(si => { actions.push([ss.__uuid__, si.__uuid__]); si.commands.forEach(sc => { commands.push([ss.__uuid__, si.__uuid__, sc.__uuid__]); }); }); } }); }); actions.forEach(a => { data.forEach(ss => ss.actionItems.forEach(si => { if (si.__uuid__ === a[1]) { si.commands.forEach(sc => { commands.push([ss.__uuid__, si.__uuid__, sc.__uuid__]); }); } })); }); const all = [...sets, ...actions, ...commands]; const allUnique = uniqBy(all, (i) => i.join("|")); return allUnique; } /* const found = draft.descriptors.find(d => d.id === uuid); if (found && operation !== "none") { if (operation === "add" || operation === "replace") { found.selected = true; } else if (operation === "subtract") { found.selected = false; } else if (operation === "addContinuous" || operation === "subtractContinuous") { const view = getDescriptorsListView({inspector:state}); const lastSelectedItemIndex = view.map(item => item.id).indexOf(state.settings.lastSelectedItem ?? "n/a"); const thisItemIndex = view.map(item => item.id).indexOf(uuid as string); if (lastSelectedItemIndex !== -1 && thisItemIndex !== -1) { const ids:string[] = []; for (let i = Math.min(lastSelectedItemIndex, thisItemIndex), end = Math.max(lastSelectedItemIndex, thisItemIndex); i <= end; i++){ ids.push(view[i].id); } ids.forEach(id => { const f = draft.descriptors.find(item => item.id === id); if (f) { f.selected = operation === "addContinuous";} }); } } } */ // draft.atnConverter.lastSelected = uuid || getInitialState().atnConverter.lastSelected; }); break; } /* case "[ATN] PASS_SELECTED": { state = produce(state, draft => { const commands = selectedCommands({ inspector: state }); }); break; } */ // ALCHEMIST case "SET_MAIN_TAB": { state = produce(state, draft => { draft.activeSection = action.payload; }); break; } case "SET_MODE_TAB": { state = produce(state, draft => { draft.inspector.activeTab = action.payload; }); break; } case "SET_TARGET_REFERENCE": { state = produce(state, draft => { const found = draft.targetReference.find(r => action.payload.type === r.type); if (found) { found.data = action.payload.data; } }); break; } case "ADD_DESCRIPTOR": { state = produce(state, draft => { if (state.descriptors.length >= state.settings.maximumItems) { for (let i = 0; i<draft.descriptors.length; i++){ if (!draft.descriptors[i].locked) { // in case that we downsized limit and more than 1 item has to be removed if (draft.descriptors.length < state.settings.maximumItems) { break; } draft.descriptors.splice(i, 1); } } } if (action.payload.replace) { draft.descriptors = [action.payload.arg]; } else { draft.descriptors.push(action.payload.arg); } }); break; } case "SELECT_DESCRIPTOR": { state = produce(state, draft => { const { operation, uuid } = action.payload; if (operation === "none") { draft.descriptors.forEach(d => d.selected = false); } else if (operation === "replace") { draft.descriptors.forEach(d => d.selected = false); } const found = draft.descriptors.find(d => d.id === uuid); if (found && operation !== "none") { if (operation === "add" || operation === "replace") { found.selected = true; } else if (operation === "subtract") { found.selected = false; } else if (operation === "addContinuous" || operation === "subtractContinuous") { const view = getDescriptorsListView({inspector:state}); const lastSelectedItemIndex = view.map(item => item.id).indexOf(state.settings.lastSelectedItem ?? "n/a"); const thisItemIndex = view.map(item => item.id).indexOf(uuid as string); if (lastSelectedItemIndex !== -1 && thisItemIndex !== -1) { const ids:string[] = []; for (let i = Math.min(lastSelectedItemIndex, thisItemIndex), end = Math.max(lastSelectedItemIndex, thisItemIndex); i <= end; i++){ ids.push(view[i].id); } ids.forEach(id => { const f = draft.descriptors.find(item => item.id === id); if (f) { f.selected = operation === "addContinuous";} }); } } } // draft.settings.lastSelectedItem = uuid || getInitialState().settings.lastSelectedItem; draft.inspector.content.expandedTree = []; draft.inspector.dom.expandedTree = []; draft.inspector.difference.expandedTree = []; }); break; } case "SET_SELECTED_REFERENCE_TYPE_ACTION": { state = produce(state, draft => { draft.selectedReferenceType = action.payload; }); break; } case "CLEAR_VIEW": { state = produce(state, draft => { const view = getDescriptorsListView({ inspector: state}); const ids = view.filter(item => !item.locked).map(item => item.id); draft.descriptors = state.descriptors.filter(item => { if (action.payload.keep) { return ids.includes(item.id); } else { return !ids.includes(item.id); } }, ); }); break; } case "CLEAR": { state = produce(state, draft => { draft.descriptors = draft.descriptors.filter(d => d.locked) || []; draft.inspector = getInitialState().inspector; }); break; } /* case "CLEAR_NON_EXISTENT": { state = produce(state, draft => { console.log("empty"); }); break; } */ case "LOCK_DESC": { state = produce(state, draft => { if (state.settings.groupDescriptors === "strict") { const selectedByID = state.descriptors.filter(d => (action.payload.uuids.includes(d.id))); const crcs = Array.from(new Set(selectedByID.map(d => d.crc))); draft.descriptors.filter(d => crcs.includes(d.crc)).forEach(d => d.locked = action.payload.lock); } else if (state.settings.groupDescriptors === "none") { draft.descriptors.filter(d => action.payload.uuids.includes(d.id)).forEach(d => d.locked = action.payload.lock); } }); break; } case "PIN_DESC": { state = produce(state, draft => { if (state.settings.groupDescriptors === "strict") { const selectedByID = state.descriptors.filter(d => (action.payload.uuids.includes(d.id))); const crcs = Array.from(new Set(selectedByID.map(d => d.crc))); draft.descriptors.filter(d => crcs.includes(d.crc)).forEach(d => d.pinned = action.payload.pin); } else if (state.settings.groupDescriptors === "none") { draft.descriptors.filter(d => action.payload.uuids.includes(d.id)).forEach(d => d.pinned = action.payload.pin); } }); break; } case "REMOVE_DESC": { state = produce(state, draft => { if (state.settings.groupDescriptors === "strict") { const selectedByID = state.descriptors.filter(d => (action.payload.includes(d.id) && !d.locked)); // remove by crc instead of ID. const crcs = Array.from(new Set(selectedByID.map(d => d.crc))); draft.descriptors = state.descriptors.filter(d => (crcs.includes(d.crc) === false || d.locked)); } else if (state.settings.groupDescriptors === "none") { draft.descriptors = state.descriptors.filter(d => (action.payload.includes(d.id) === false || d.locked)); } }); break; } case "SET_INSPECTOR_PATH_DIFF": { state = produce(state, draft => { if (action.payload.mode === "add") { draft.inspector.difference.treePath = [...state.inspector.difference.treePath, ...action.payload.path]; } else if (action.payload.mode === "replace") { draft.inspector.difference.treePath = action.payload.path; } }); break; } case "SET_INSPECTOR_PATH_CONTENT": { state = produce(state, draft => { if (action.payload.mode === "add") { draft.inspector.content.treePath = [...state.inspector.content.treePath, ...action.payload.path]; } else if (action.payload.mode === "replace") { draft.inspector.content.treePath = action.payload.path; } // draft.inspector.content.expandedTree = []; draft.inspector.dom.expandedTree = []; draft.inspector.difference.expandedTree = []; }); break; } case "SET_INSPECTOR_PATH_DOM": { state = produce(state, draft => { if (action.payload.mode === "add") { draft.inspector.dom.treePath = [...state.inspector.dom.treePath, ...action.payload.path]; } else if (action.payload.mode === "replace") { draft.inspector.dom.treePath = action.payload.path; } }); break; } case "IMPORT_STATE": { state = { ...action.payload.inspector, }; break; } case "IMPORT_ITEMS": { state = produce(state, draft => { if (action.payload.kind === "append") { action.payload.items.forEach(desc => desc.id = GetInfo.uuidv4()); draft.descriptors = [...state.descriptors,...action.payload.items]; } else if (action.payload.kind === "replace") { draft.descriptors = action.payload.items; } }); break; } /* case "EXPORT_SELECTED_DESC": { state = produce(state, draft => { console.log("empty"); }); break; } case "EXPORT_ALL_DESC": { state = produce(state, draft => { console.log("empty"); }); break; } case "EXPORT_STATE": { state = produce(state, draft => { console.log("empty"); }); break; } */ case "SET_FILTER_STATE": { state = produce(state, draft => { const { payload: { state, subType, type } } = action; const found = draft.targetReference.find(r => r.type === type); if (subType === "main") { if (state === "on") { draft.filterBySelectedReferenceType = "off"; } else { draft.filterBySelectedReferenceType = "on"; } found?.data.forEach(d => d.content.filterBy = "off"); } else { if (state === "on") { found?.data.forEach(d => d.content.filterBy = "off"); draft.filterBySelectedReferenceType = "off"; } else { let foundIndex: number | null = null; found?.data.forEach((d, i) => { if (d.subType === subType) { foundIndex = i; d.content.filterBy = "on"; draft.filterBySelectedReferenceType = "semi"; } else if (foundIndex === null) { d.content.filterBy = "semi"; } else { d.content.filterBy = "off"; } }); } } }); break; } case "SET_LISTENER": { state = produce(state, draft => { draft.settings.autoUpdateListener = action.payload; }); break; } case "SET_AUTO_INSPECTOR": { state = produce(state, draft => { draft.settings.autoUpdateInspector = action.payload; }); break; } case "SET_EXPANDED_PATH": { state = produce(state, draft => { const { expand, path, recursive, type } = action.payload; let { data } = action.payload; // gets port of the tree data where you clicked function getDataPart(d: any, tPath:TPath|undefined): any { if (!tPath) { return d; } let sub = d; for (const part of tPath) { sub = (sub)?.[part]; } return sub; } // prevents callstack exceeded error function isCyclical(tPath: TPath, toTest: any): boolean{ let sub = data; tPath = [...path,...tPath]; tPath.splice(tPath.length - 1, 1); for (const part of tPath) { sub = (sub)?.[part]; if (sub === toTest) { return true; } } return false; } // generates paths for all expandable item in passed object function generatePaths(d: any): TPath[]{ const paths: TPath[] = []; traverse(d); return paths; // recursion function traverse(d: any, tPath: TPath = []): void{ if (d && typeof d === "object" && !isCyclical(tPath,d)) { paths.push([...path, ...tPath]); const keys = Object.keys(d); if (type === "dom") { keys.push(...addMoreKeys("uxp", d)); keys.sort(); } for (const key of keys) { traverse(d[key],[...tPath,key]); } } } } let draftPart: IContent | IDifference | IDOM | null = null; switch (type) { case "content": draftPart = draft.inspector.content; break; case "difference": draftPart = draft.inspector.difference; break; case "dom": draftPart = draft.inspector.dom; break; default: console.warn("You shouldn't see this line logged in console"); } if (type === "dom") { data = getTreeDomInstance({ inspector: state}); } if (draftPart) { let index:number|null = null; const found = draftPart.expandedTree.find((item, i) => { index = i; return item.join("-") === path.join("-"); }); if (expand && !found) { if (recursive) { const parts = generatePaths(getDataPart(data, path));//.map(p=>([...path,...p])); draftPart.expandedTree.push(...parts); } else { draftPart.expandedTree.push(path); } } else if ((found || recursive) && index !== null) { if (recursive) { const parts = generatePaths(getDataPart(data, path));//.map(p => ([...path,...p,])); for (const part of parts) { let index: number | null = null; const partStr = part.join("-"); const found = draftPart.expandedTree.find((item, i) => { index = i; return item.join("-") === partStr; }); if (found && index !== null) { draftPart.expandedTree.splice(index, 1); } } } else { draftPart.expandedTree.splice(index, 1); } } } }); console.log(state.inspector); break; } case "SET_SEARCH_TERM_ACTION": { state = produce(state, draft => { draft.settings.searchTerm = action.payload; }); break; } case "SET_FILTER_TYPE": { state = produce(state, draft => { draft.settings.listenerFilterType = action.payload; }); break; } case "SET_INCLUDE_ACTION": { state = produce(state, draft => { draft.settings.listenerInclude = action.payload; }); break; } case "SET_EXCLUDE_ACTION": { state = produce(state, draft => { draft.settings.listenerExclude = action.payload; }); break; } case "REPLACE_WHOLE_STATE": { if (action.payload && getInitialState().version[0] === action.payload.version[0] // load only compatible version ) { action.payload.settings.autoUpdateListener = false; action.payload.settings.autoUpdateInspector = false; action.payload.amConvertor = cloneDeep(state.amConvertor); state = action.payload; } break; } case "SET_DISPATCHER_VALUE": { state = produce(state, draft => { draft.dispatcher.snippets[0].content = action.payload; }); break; } case "RENAME_DESCRIPTOR": { state = produce(state, draft => { const found = draft.descriptors.find(desc => desc.id === action.payload.uuid); if (found) { found.title = action.payload.name; } }); break; } case "SET_RENAME_MODE": { state = produce(state, draft => { const found = draft.descriptors.find(desc => desc.id === action.payload.uuid); if (found) { found.renameMode = action.payload.on; } }); break; } case "SET_DESCRIPTOR_OPTIONS": { state = produce(state, draft => { if (action.payload.uuids === "default") { draft.settings.initialDescriptorSettings = { ...state.settings.initialDescriptorSettings, ...action.payload.options, }; } else { for (let i = 0, len = action.payload.uuids.length; i < len; i++){ let foundIndex = 0; const found = draft.descriptors.find((desc, j) => { foundIndex = j; return desc.id === action.payload.uuids[i]; }); if (found) { found.descriptorSettings = { ...state.descriptors[foundIndex].descriptorSettings, ...action.payload.options, }; } } } }); break; } case "SET_INSPECTOR_VIEW_ACTION": { state = produce(state, draft => { const {inspectorType,viewType } = action.payload; switch (inspectorType) { case "code": draft.inspector.code.viewType = viewType as TCodeViewType; break; case "content": draft.inspector.content.viewType = viewType as TGenericViewType; break; case "diff": draft.inspector.difference.viewType = viewType as TGenericViewType; break; } }); break; } case "SET_COLUMN_SIZE_ACTION": { state = produce(state, draft => { draft.settings.leftColumnWidthPx = action.payload; }); break; } case "SET_RECORD_RAW": { state = produce(state, draft => { draft.settings.makeRawDataEasyToInspect = action.payload; }); break; } case "SET_AUTOEXPAND_LEVEL": { state = produce(state, draft => { switch (action.payload.part) { case "DOM": { draft.inspector.dom.autoExpandLevels = action.payload.level; break; } case "content": { draft.inspector.content.autoExpandLevels = action.payload.level; break; } case "diff": { draft.inspector.difference.autoExpandLevels = action.payload.level; break; } } }); break; } case "SET_MAXIMUM_ITEMS": { state = produce(state, draft => { let num = parseInt(action.payload); if (num < 3 || Number.isNaN(num)) { num = 3; } draft.settings.maximumItems = num; }); break; } case "DONT_SHOW_MARKETPLACE_INFO_ACTION": { state = produce(state, draft => { draft.settings.dontShowMarketplaceInfo = action.payload; }); break; } case "SET_CONVERTER": { state = produce(state, draft => { draft.amConvertor = { ...state.amConvertor, ...action.payload, }; }); break; } case "SET_FONT_SIZE": { state = produce(state, draft => { draft.settings.fontSize = action.payload; }); break; } case "SET_NEVER_RECORD_ACTION_NAMES_ACTION": { state = produce(state, draft => { draft.settings.neverRecordActionNames = action.payload; }); break; } case "TOGGLE_DESCRIPTORS_GROUPING": { state = produce(state, draft => { if (action.payload === null) { draft.settings.groupDescriptors = state.settings.groupDescriptors === "strict" ? "none" : "strict"; } else { draft.settings.groupDescriptors = action.payload; } }); break; } case "SET_SETTINGS": { state = produce(state, draft => { draft.settings = { ...state.settings, ...action.payload, }; }); break; } } Settings.saveSettings(state); return state; };
the_stack
// The MIT License (MIT) // // vs-deploy (https://github.com/mkloubert/vs-deploy) // Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. import * as deploy_buttons from './buttons'; import * as deploy_commands from './commands'; import * as deploy_config from './config'; import * as deploy_contracts from './contracts'; import * as deploy_diff from './diff'; import * as deploy_helpers from './helpers'; import * as deploy_globals from './globals'; import * as deploy_objects from './objects'; import * as deploy_operations from './operations'; import * as deploy_packages from './packages'; import * as deploy_plugins from './plugins'; import * as deploy_switch from './switch'; import * as deploy_sync from './sync'; import * as deploy_targets from './targets'; import * as deploy_templates from './templates'; import * as deploy_urls from './urls'; import * as deploy_values from './values'; import * as deploy_workspace from './workspace'; import { DeployHost } from './host'; import * as Events from 'events'; import * as FS from 'fs'; const Glob = require('glob'); import * as i18 from './i18'; import * as Moment from 'moment'; import * as OS from 'os'; import * as Path from 'path'; import * as TMP from 'tmp'; import * as vscode from 'vscode'; import * as Workflows from 'node-workflows'; const AFTER_DEPLOYMENT_BUTTON_COLORS = { 's': [ 'ffffff', 'eeeeee', 'dddddd', ], 'w': [ 'ffff00', 'eeee00', 'dddd00', ], 'e': [ '000000', '111111', '222222', ], }; let nextCancelDeployFileCommandId = Number.MAX_SAFE_INTEGER; let nextCancelDeployWorkspaceCommandId = Number.MAX_SAFE_INTEGER; let nextCancelPullFileCommandId = Number.MAX_SAFE_INTEGER; let nextCancelPullWorkspaceCommandId = Number.MAX_SAFE_INTEGER; interface EnvVarEntry { name: string; value: any; } interface EventEntry { event: deploy_contracts.Event; index: number; listener: Function; name: string; } /** * Deployer class. */ export class Deployer extends Events.EventEmitter implements vscode.Disposable { /** * Additional values. */ protected _additionalValues: deploy_values.ValueBase[]; /** * Information button that is shown after a deployment has been finished. */ protected readonly _AFTER_DEPLOYMENT_STATUS_ITEM: vscode.StatusBarItem; /** * Stores all known targets from config as copies. */ protected _allTargets: deploy_contracts.DeployTarget[]; /** * Stores the current configuration. */ protected _config: deploy_contracts.DeployConfiguration; /** * Stores the underlying extension context. */ protected readonly _CONTEXT: vscode.ExtensionContext; /** * Stores the current active text editor. */ protected _currentTextEditor: vscode.TextEditor; /** * The timeout for freezing 'deploy on change' feature. */ protected _deployOnChangeFreezer: NodeJS.Timer; /** * Stores the current list of global events. */ protected readonly _EVENTS: EventEntry[] = []; /** * The global file system watcher. */ protected _fileSystemWatcher: vscode.FileSystemWatcher; /** * The global state value for deploy operation scripts. */ protected _globalScriptOperationState: Object = {}; /** * Stores the current host. */ protected _host: DeployHost; /** * Stores the current list of HTML documents. */ protected _htmlDocs: deploy_contracts.Document[]; /** * Stores if 'deploy on change' feature is enabled or not. */ protected _isDeployOnChangeEnabled = true; /** * Stores if 'deploy on change' feature is freezed or not. */ protected _isDeployOnChangeFreezed = false; /** * Stores if 'deploy on save' feature is enabled or not. */ protected _isDeployOnSaveEnabled = true; /** * Stores if extension is reloading its configuration or not. */ protected _isReloadingConfig = false; /** * Stores if 'sync when open' feature is enabled or not. */ protected _isSyncWhenOpenEnabled = true; private readonly _NEXT_AFTER_DEPLOYMENT_BUTTON_COLORS = { 's': 0, 'w': 0, 'e': 0, }; /** * The ID of the last timeout that autmatically disapears * the deploy result button in the status bar. */ protected _lastAfterDeploymentButtonDisapearTimeout: NodeJS.Timer; /** * Stores the timestamp of the last config update. */ protected _lastConfigUpdate: Moment.Moment; /** * Stores the last list of environment vars. */ protected _oldEnvVars: EnvVarEntry[]; /** * Stores the global output channel. */ protected readonly _OUTPUT_CHANNEL: vscode.OutputChannel; /** * Stores the package file of that extension. */ protected readonly _PACKAGE_FILE: deploy_contracts.PackageFile; /** * Loaded plugins. */ protected _plugins: deploy_contracts.DeployPluginWithContext[]; /** * The "quick deploy button". */ protected readonly _QUICK_DEPLOY_STATUS_ITEM: vscode.StatusBarItem; /** * The states values for deploy operation scripts. */ protected _scriptOperationStates: Object = {}; /** * The current status item of the running server. */ protected _serverStatusItem: vscode.StatusBarItem; /** * Stores the extension's start time. */ protected _startTime: Moment.Moment; /** * Cache for deploy targets. */ protected _targetCache: deploy_objects.DeployTargetCache; /** * Stores the packages that are currently deploy. */ protected readonly _WORKSPACE_IN_PROGRESS: any = {}; /** * Initializes a new instance of that class. * * @param {vscode.ExtensionContext} context The underlying extension context. * @param {vscode.OutputChannel} outputChannel The global output channel to use. * @param {deploy_contracts.PackageFile} pkgFile The package file of that extension. */ constructor(context: vscode.ExtensionContext, outputChannel: vscode.OutputChannel, pkgFile: deploy_contracts.PackageFile) { super(); this._CONTEXT = context; this._OUTPUT_CHANNEL = outputChannel; this._PACKAGE_FILE = pkgFile; this._QUICK_DEPLOY_STATUS_ITEM = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); this._QUICK_DEPLOY_STATUS_ITEM.command = 'extension.deploy.quickDeploy'; this._AFTER_DEPLOYMENT_STATUS_ITEM = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); this._AFTER_DEPLOYMENT_STATUS_ITEM.command = 'extension.deploy.openOutputAfterDeploment'; this._AFTER_DEPLOYMENT_STATUS_ITEM.tooltip = 'Click here to open output...'; } /** * Invokes 'after deployed' operations for a target. * * @param {string[]} files The files that have been deployed. * @param {deploy_contracts.DeployTarget} target The target. * * @return {Promise<boolean>} The promise. */ protected afterDeployment(files: string[], target: deploy_contracts.DeployTarget): Promise<boolean> { let me = this; return new Promise<boolean>((resolve, reject) => { let afterDeployedOperations = deploy_helpers.asArray(target.deployed) .filter(x => x); let hasCancelled = false; let completed = (err: any) => { if (err) { reject(err); } else { resolve(hasCancelled); } }; me.onCancelling(() => hasCancelled = true); let workflow = Workflows.create(); afterDeployedOperations.forEach((currentOperation, i) => { workflow.next((ctx) => { return new Promise<any>((res, rej) => { let operationName = deploy_operations.getOperationName(currentOperation); me.outputChannel.append(`[AFTER DEPLOY #${i + 1}] '${operationName}' `); if (hasCancelled) { ctx.finish(); } else { me.handleCommonDeployOperation(currentOperation, deploy_contracts.DeployOperationKind.After, files, target).then((handled) => { if (handled) { me.outputChannel.appendLine(i18.t('deploy.operations.finished')); } else { me.outputChannel.appendLine(i18.t('deploy.operations.unknownType', currentOperation.type)); } res(); }).catch((err) => { me.outputChannel.appendLine(i18.t('deploy.operations.failed', err)); rej(err); }); } }); }); }); if (!hasCancelled) { workflow.start().then(() => { completed(null); }).catch((e) => { completed(e); }); } }); } /** * Returns all targets from config. */ public get allTargetsFromConfig(): deploy_contracts.DeployTarget[] { return this._allTargets; } /** * Invokes 'before deploy' operations for a target. * * @param {string[]} files The files to deploy. * @param {deploy_contracts.DeployTarget} target The target. * * @return {Promise<boolean>} The promise. */ protected beforeDeploy(files: string[], target: deploy_contracts.DeployTarget): Promise<boolean> { let me = this; return new Promise<boolean>((resolve, reject) => { let beforeDeployOperations = deploy_helpers.asArray(target.beforeDeploy) .filter(x => x); let hasCancelled = false; let completed = (err: any) => { if (err) { reject(err); } else { resolve(hasCancelled); } }; me.onCancelling(() => hasCancelled = true); let workflow = Workflows.create(); beforeDeployOperations.forEach((currentOperation, i) => { workflow.next((ctx) => { return new Promise<any>((res, rej) => { let operationName = deploy_operations.getOperationName(currentOperation); me.outputChannel.append(`[BEFORE DEPLOY #${i + 1}] '${operationName}' `); if (hasCancelled) { ctx.finish(); } else { me.handleCommonDeployOperation(currentOperation, deploy_contracts.DeployOperationKind.Before, files, target).then((handled) => { if (handled) { me.outputChannel.appendLine(i18.t('deploy.operations.finished')); } else { me.outputChannel.appendLine(i18.t('deploy.operations.unknownType', currentOperation.type)); } res(); }).catch((err) => { me.outputChannel.appendLine(i18.t('deploy.operations.failed', err)); rej(err); }); } }); }); }); if (!hasCancelled) { workflow.start().then(() => { completed(null); }).catch((e) => { completed(e); }); } }); } /** * Changes a switch target. */ public async changeSwitch() { return await deploy_switch.changeSwitch .apply(this, arguments); } /** * Clears the output on startup depending on the current configuration. */ public clearOutputOrNot() { if (deploy_helpers.toBooleanSafe(this.config.clearOutputOnStartup)) { this.outputChannel.clear(); } } /** * Compares a local file with a version from a target. * * @param {any} [uri] The URI of the file. * * @return {Promise<any>} The promise. */ public compareFiles(uri?: any): Promise<any> { let me = this; return new Promise<any>((resolve, reject) => { let completed = deploy_helpers.createSimplePromiseCompletedAction<any>(resolve, reject); let targets = this.getTargets() .filter(x => !deploy_helpers.toBooleanSafe(x.isHidden)); if (targets.length < 1) { vscode.window.showWarningMessage(i18.t('targets.noneDefined')); return; } let path: string; if (uri && uri.fsPath) { path = uri.fsPath; } else { let currentEditor = vscode.window.activeTextEditor; if (currentEditor) { let currentDocument = currentEditor.document; if (currentDocument) { path = currentDocument.fileName; } } } if (deploy_helpers.isEmptyString(path)) { completed(); return; } let startDownlods = (t: deploy_contracts.DeployTarget, files: string[]) => { let type = deploy_helpers.parseTargetType(t.type); let matchIngPlugins = me.pluginsWithContextes.filter(x => { return !type || (x.plugin.__type === type && deploy_helpers.toBooleanSafe(x.plugin.canPull) && x.plugin.downloadFile); }); if (matchIngPlugins.length > 0) { let nextPlugin: () => void; nextPlugin = () => { if (matchIngPlugins.length < 1) { completed(); return; // we have finished } let filesTODO = files.map(x => x); let mp = matchIngPlugins.shift(); let p = mp.plugin; let nextFile = () => { if (filesTODO.length < 1) { nextPlugin(); return; } let f = filesTODO.shift(); let diffFinished = (err: any) => { if (err) { completed(err); } else { nextFile(); } }; try { let doDiff = (downloadedData?: Buffer) => { // run "diff app" if (!downloadedData) { downloadedData = Buffer.alloc(0); } try { // save downloaded data // to temp file TMP.tmpName({ keep: true, prefix: 'vsd-', postfix: Path.extname(f), }, (err, tmpPath) => { if (err) { diffFinished(err); } else { FS.writeFile(tmpPath, downloadedData, (err) => { if (err) { diffFinished(err); } else { try { let realtivePath = deploy_helpers.toRelativePath(f); if (false === realtivePath) { realtivePath = f; } let titleSuffix = deploy_helpers.toStringSafe(t.name).trim(); let windowTitle = `[vs-deploy] Diff '${realtivePath}'`; if ('' === titleSuffix) { titleSuffix = deploy_helpers.normalizeString(t.type); } if ('' !== titleSuffix) { windowTitle += ` (${titleSuffix})`; } vscode.commands.executeCommand('vscode.diff', vscode.Uri.file(tmpPath), vscode.Uri.file(f), windowTitle).then(() => { diffFinished(null); }, (err) => { diffFinished(err); }); } catch (e) { diffFinished(e); } } }); } }); } catch (e) { diffFinished(e); } }; // download data let downloadResult = p.downloadFile(f, t); if (downloadResult) { if (Buffer.isBuffer(downloadResult)) { doDiff(downloadResult); } else { downloadResult.then((data) => { doDiff(data); }, (err) => { diffFinished(err); }); } } else { doDiff(); } } catch (e) { diffFinished(e); } }; nextFile(); // start with first file } nextPlugin(); // start with first plugin } else { // no matching plugin found if (type) { vscode.window.showWarningMessage(i18.t('compare.noPluginsForType', type)); } else { vscode.window.showWarningMessage(i18.t('compare.noPlugins')); } } } // startDownlods() let selectTarget = (files: string[]) => { // select the target / // source from where to download from let fileQuickPicks = targets.map((x, i) => deploy_helpers.createTargetQuickPick(x, i, me.getValues())); if (fileQuickPicks.length > 1) { vscode.window.showQuickPick(fileQuickPicks, { placeHolder: i18.t('compare.selectSource'), }).then((item) => { if (item) { startDownlods(item.target, files); } }, (err) => { completed(err); }); } else { // auto select startDownlods(fileQuickPicks[0].target, files); } } // selectTarget() // first check if file FS.lstat(path, (err, stats) => { if (err) { completed(i18.t('compare.failed', path, err)); } else { if (stats.isFile()) { selectTarget([ path ]); } else if (stats.isDirectory()) { Glob('**', { absolute: true, cwd: path, dot: true, ignore: [], nodir: true, root: path, }, (e: any, files: string[]) => { if (e) { completed(i18.t('compare.failed', path, e)); } else { selectTarget(files); } }); } else { // no file completed(i18.t('isNo.file', path)); } } }); }); } /** * Gets the current configuration. */ public get config(): deploy_contracts.DeployConfiguration { return this._config; } /** * Gets the extension context. */ public get context(): vscode.ExtensionContext { return this._CONTEXT; } /** * Deploys a file. * * @param {string} file The path of the file to deploy. */ protected deployFile(file: string) { let me = this; let targets = this.getTargets() .filter(x => !deploy_helpers.toBooleanSafe(x.isHidden)); if (targets.length < 1) { vscode.window.showWarningMessage(i18.t('targets.noneDefined')); return; } let quickPicks = targets.map((x, i) => deploy_helpers.createFileQuickPick(file, x, i, me.getValues())); let deploy = (item: deploy_contracts.DeployFileQuickPickItem) => { try { if (item) { let showError = (err: any, type: string) => { vscode.window.showErrorMessage(i18.t(`deploy.${type}.failed`, file, err)); }; me.beforeDeploy([ file ], item.target).then((canceled) => { if (canceled) { return; } me.deployFileTo(file, item.target).then((canceled) => { if (canceled) { return; } // DO NOT invoke me.afterDeployment() // this is done by me.deployFileTo()! }).catch((err) => { showError(err, 'file'); }); // deploy }).catch((err) => { showError(err, 'before'); }); // beforeDeploy } } catch (e) { vscode.window.showErrorMessage(i18.t('deploy.file.failed', file, e)); } }; if (quickPicks.length > 1 || deploy_helpers.toBooleanSafe(me.config.alwaysShowTargetList)) { vscode.window.showQuickPick(quickPicks, { placeHolder: i18.t('targets.select'), }).then((item) => { deploy(item); }); } else { // auto select deploy(quickPicks[0]); } } /** * Deploys a file or folder. * * @param {any} [uri] The URI of the file / folder to deploy. */ public deployFileOrFolder(uri?: any) { let me = this; let path: string; if (uri && uri.fsPath) { path = uri.fsPath; } else { let currentEditor = vscode.window.activeTextEditor; if (currentEditor) { let currentDocument = currentEditor.document; if (currentDocument) { path = currentDocument.fileName; } } } if (deploy_helpers.isEmptyString(path)) { return; } let showError = (err: any) => { vscode.window.showErrorMessage(i18.t('deploy.fileOrFolder.failed', path, err)); }; // check if file or folder FS.lstat(path, (err, stats) => { if (err) { showError(err); return; } try { if (stats.isDirectory()) { me.deployFolder(path); // folder } else if (stats.isFile()) { me.deployFile(path); // file } else { showError(new Error(i18.t('isNo.validItem', path))); } } catch (e) { showError(e); } }); } /** * Deploys a file to a target. * * @param {string} file The file to deploy. * @param {deploy_contracts.DeployTarget} target The target to deploy to. * * @return {Promise<boolean>} The promise. */ protected deployFileTo(file: string, target: deploy_contracts.DeployTarget): Promise<boolean> { let me = this; return new Promise<boolean>((resolve, reject) => { let hasCancelled = false; let completed = (err?: any) => { if (err) { reject(err); } else { resolve(hasCancelled); } }; if (me.isFileIgnored(file)) { if (deploy_helpers.toBooleanSafe(me.config.showWarningIfIgnored, true)) { // show warning vscode.window.showWarningMessage(i18.t('deploy.file.isIgnored', file)); } hasCancelled = true; completed(null); return; } me.onCancelling(() => hasCancelled = true); try { me.hideAfterDeploymentStatusBarItem(); let type = deploy_helpers.parseTargetType(target.type); let matchIngPlugins = me.pluginsWithContextes.filter(x => { return !type || (x.plugin.__type === type && x.plugin.deployFile); }); let relativePath = deploy_helpers.toRelativePath(file); if (false === relativePath) { relativePath = file; } if (matchIngPlugins.length > 0) { let deployNextPlugin: () => void; deployNextPlugin = () => { if (matchIngPlugins.length < 1) { completed(); return; } if (hasCancelled) { completed(); return; } let cancelCommand: vscode.Disposable; let currentPluginWithContext = matchIngPlugins.shift(); let contextToUse = deploy_plugins.createPluginContext(currentPluginWithContext.context); let currentPlugin = currentPluginWithContext.plugin; let statusBarItem: vscode.StatusBarItem; let cleanUps = () => { deploy_helpers.tryDispose(cancelCommand); deploy_helpers.tryDispose(statusBarItem); deploy_helpers.tryDispose(contextToUse); }; let deployPlugin = () => { try { statusBarItem = vscode.window.createStatusBarItem( vscode.StatusBarAlignment.Left, ); statusBarItem.color = '#ffffff'; statusBarItem.text = i18.t('deploy.button.prepareText'); statusBarItem.tooltip = i18.t('deploy.button.tooltip'); let cancelCommandName = 'extension.deploy.cancelFile' + (nextCancelDeployFileCommandId--); cancelCommand = vscode.commands.registerCommand(cancelCommandName, () => { if (hasCancelled) { return; } hasCancelled = true; try { contextToUse.emit(deploy_contracts.EVENT_CANCEL_DEPLOY); } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.deployFileTo().cancel', e)); } statusBarItem.text = i18.t('deploy.button.cancelling'); statusBarItem.tooltip = i18.t('deploy.button.cancelling'); }); statusBarItem.command = cancelCommandName; let showResult = (err?: any) => { let afterDeployButtonMsg = 'Deployment finished.'; try { cleanUps(); let targetExpr = deploy_helpers.toStringSafe(target.name).trim(); let resultMsg; if (err) { if (hasCancelled) { resultMsg = i18.t('deploy.canceledWithErrors'); } else { resultMsg = i18.t('deploy.finishedWithErrors'); } } else { if (deploy_helpers.toBooleanSafe(me.config.showPopupOnSuccess, true)) { if (targetExpr) { vscode.window.showInformationMessage(i18.t('deploy.file.succeededWithTarget', file, targetExpr)); } else { vscode.window.showInformationMessage(i18.t('deploy.file.succeeded', file)); } } if (hasCancelled) { resultMsg = i18.t('deploy.canceled'); } else { resultMsg = i18.t('deploy.finished2'); me.afterDeployment([ file ], target).catch((err) => { vscode.window.showErrorMessage(i18.t('deploy.after.failed', err)); }); } } if (resultMsg) { afterDeployButtonMsg = resultMsg; me.outputChannel.appendLine(resultMsg); } } finally { me.showStatusBarItemAfterDeployment(afterDeployButtonMsg, [ file ], err ? [] : [ file ], err ? [ file ] : []); completed(err); } }; try { statusBarItem.show(); currentPlugin.deployFile(file, target, { context: contextToUse, onBeforeDeploy: (sender, e) => { let destination = deploy_helpers.toStringSafe(e.destination); let targetName = deploy_helpers.toStringSafe(e.target.name); me.outputChannel.appendLine(''); let deployMsg: string; if (targetName) { targetName = ` ('${targetName}')`; } if (destination) { deployMsg = i18.t('deploy.file.deployingWithDestination', file, destination, targetName); } else { deployMsg = i18.t('deploy.file.deploying', file, targetName); } me.outputChannel.append(deployMsg); if (deploy_helpers.toBooleanSafe(me.config.openOutputOnDeploy, true)) { me.outputChannel.show(); } statusBarItem.text = i18.t('deploy.button.text'); }, onCompleted: (sender, e) => { if (e.error) { me.outputChannel.appendLine(i18.t('failed', e.error)); } else { me.outputChannel.appendLine(i18.t('ok')); } hasCancelled = hasCancelled || e.canceled; showResult(e.error); } }); } catch (e) { showResult(e); } } catch (e) { cleanUps(); completed(e); } }; let checkForNewer = () => { if (deploy_helpers.toBooleanSafe(target.checkBeforeDeploy)) { deploy_diff.checkForNewerFiles.apply(me, [ [ file ], target, currentPlugin ]).then((startDeploy: boolean) => { if (startDeploy) { deployPlugin(); } else { deployNextPlugin(); } }).catch((e) => { completed(e); }); } else { deployPlugin(); } }; if (deploy_helpers.toBooleanSafe(target.diffBeforeDeploy)) { if (deploy_helpers.toBooleanSafe(currentPlugin.canPull) && currentPlugin.downloadFile) { // make a diff and ask the // if (s)he really wants to deploy me.compareFiles(vscode.Uri.file(file)).then(() => { // [BUTTON] yes let yesBtn: deploy_contracts.PopupButton = new deploy_objects.SimplePopupButton(); yesBtn.action = () => { deployPlugin(); // user wants to deploy }; yesBtn.title = i18.t('yes'); vscode.window .showWarningMessage(i18.t('deploy.startQuestion'), yesBtn) .then((item) => { if (!item || !item.action) { return; } item.action(); }); }).catch((err) => { completed(err); }); } else { checkForNewer(); } } else { checkForNewer(); } }; deployNextPlugin(); } else { if (type) { vscode.window.showWarningMessage(i18.t('deploy.noPluginsForType', type)); } else { vscode.window.showWarningMessage(i18.t('deploy.noPlugins')); } completed(); } } catch (e) { completed(e); } }); } /** * Deploys a folder. * * @param {string} dir The path of the folder to deploy. */ protected deployFolder(dir: string) { let me = this; dir = Path.resolve(dir); let filesToDeploy: string[] = Glob.sync('**', { absolute: true, cwd: dir, dot: true, ignore: [], nodir: true, root: dir, }); let targets = this.getTargets() .filter(x => !deploy_helpers.toBooleanSafe(x.isHidden)); if (targets.length < 1) { vscode.window.showWarningMessage(i18.t('targets.noneDefined')); return; } // start deploy the folder // by selected target let deploy = (t: deploy_contracts.DeployTarget) => { me.beforeDeploy(filesToDeploy, t).then((canceled) => { if (canceled) { return; } if (filesToDeploy.length < 1) { vscode.window.showWarningMessage(i18.t('deploy.noFiles')); return; } me.deployWorkspaceTo(filesToDeploy, t).then(() => { //TODO }).catch((err) => { vscode.window.showErrorMessage(i18.t('deploy.folder.failed', dir, err)); }); }).catch((err) => { vscode.window.showErrorMessage(i18.t('deploy.before.failed', err)); }); }; // select the target let fileQuickPicks = targets.map((x, i) => deploy_helpers.createTargetQuickPick(x, i, me.getValues())); if (fileQuickPicks.length > 1) { vscode.window.showQuickPick(fileQuickPicks, { placeHolder: i18.t('deploy.folder.selectTarget'), }).then((item) => { if (item) { deploy(item.target); } }); } else { // auto select deploy(fileQuickPicks[0].target); } } /** * Deploys files of the workspace. * * @param {deploy_contracts.DeployPackage|deploy_contracts.DeployPackage[]} [packagesToDeploy] The package(s) to deploy. * @param {deploy_contracts.DeployTarget|deploy_contracts.DeployTarget[]} [targetsToDeployTo] The target(s) to deploy to. * * @return {Promise<number>} The promise. */ public deployWorkspace(packagesToDeploy?: deploy_contracts.DeployPackage | deploy_contracts.DeployPackage[], targetsToDeployTo?: deploy_contracts.DeployTarget | deploy_contracts.DeployTarget[]): Promise<number> { let me = this; return new Promise<number>((resolve, reject) => { let completed = (err: any, code?: any) => { if (err) { reject(err); } else { resolve(code); } }; let packages = deploy_helpers.asArray(packagesToDeploy).filter(x => x); if (packages.length < 1) { // no explicit packages found in method arguments // so read packages from config packages = me.getPackages() .filter(x => !deploy_helpers.toBooleanSafe(x.isHidden) && deploy_helpers.toBooleanSafe(x.showForDeploy, true)); } if (packages.length < 1) { vscode.window.showWarningMessage(i18.t('packages.noneDefined')); completed(null, 1); // no packages found return; } let packageQuickPicks = packages.map((x, i) => deploy_helpers.createPackageQuickPick(x, i, me.getValues())); let selectTarget = (pkg: deploy_contracts.DeployPackage) => { if (!pkg) { completed(null, 3); // aborted return; } let targets = deploy_helpers.asArray(targetsToDeployTo).filter(x => x); if (targets.length < 1) { // no explicit targets found in method arguments // so read targets from package targets = me.filterTargetsByPackage(pkg) .filter(x => !deploy_helpers.toBooleanSafe(x.isHidden)); } if (targets.length < 1) { vscode.window.showWarningMessage(i18.t('targets.noneDefined')); completed(null, 4); // no target found return; } let packageName = deploy_helpers.toStringSafe(pkg.name); let filesToDeploy = deploy_helpers.getFilesOfPackage(pkg, me.useGitIgnoreStylePatternsInFilter(pkg)); let deploy = (t: deploy_contracts.DeployTarget) => { try { if (!t) { completed(null, 6); // aborted return; } let targetName = deploy_helpers.toStringSafe(t.name); me.outputChannel.appendLine(''); let deployMsg: string; if (targetName) { deployMsg = i18.t('deploy.workspace.deployingWithTarget', packageName, targetName); } else { deployMsg = i18.t('deploy.workspace.deploying', packageName); } me.outputChannel.appendLine(deployMsg); if (deploy_helpers.toBooleanSafe(me.config.openOutputOnDeploy, true)) { me.outputChannel.show(); } me.beforeDeploy(filesToDeploy, t).then((canceled) => { if (canceled) { completed(null, 7); // canceled return; } filesToDeploy = deploy_helpers.getFilesOfPackage(pkg, me.useGitIgnoreStylePatternsInFilter(pkg)); // now update file list if (filesToDeploy.length < 1) { vscode.window.showWarningMessage(i18.t('deploy.noFiles')); completed(null, 8); // no files return; } me.deployWorkspaceTo(filesToDeploy, t).then(() => { completed(null, 0); // anthing finished }).catch((err) => { completed(new Error(i18.t('deploy.workspace.failedWithCategory', 2, err))); }); }).catch((err) => { completed(new Error(i18.t('deploy.before.failed', err))); }); } catch (e) { completed(new Error(i18.t('deploy.workspace.failedWithCategory', 1, e))); } }; let targetsOfPackage = me.getTargetsFromPackage(pkg); if (targetsOfPackage.length < 1) { // no explicit targets let fileQuickPicks = targets.map((x, i) => deploy_helpers.createTargetQuickPick(x, i, me.getValues())); if (fileQuickPicks.length > 1 || deploy_helpers.toBooleanSafe(me.config.alwaysShowTargetList)) { vscode.window.showQuickPick(fileQuickPicks, { placeHolder: i18.t('deploy.workspace.selectTarget'), }).then((item) => { if (item) { deploy(item.target); } else { completed(null, 5); // aborted } }, (err) => { completed(err); }); } else { // auto select deploy(fileQuickPicks[0].target); } } else { // we have explicit defined targets here if (1 === targetsOfPackage.length) { deploy(targetsOfPackage[0]); // deploy the one and only } else { // create a virtual "batch" target // for the underlying "real" targets let virtualPkgName: string; if (packageName) { virtualPkgName = i18.t('deploy.workspace.virtualTargetNameWithPackage', packageName); } else { virtualPkgName = i18.t('deploy.workspace.virtualTargetName'); } let batchTarget: any = { type: 'batch', name: virtualPkgName, targets: targetsOfPackage.map(x => x.name), }; deploy(batchTarget); } } }; if (packageQuickPicks.length > 1 || deploy_helpers.toBooleanSafe(me.config.alwaysShowPackageList)) { vscode.window.showQuickPick(packageQuickPicks, { placeHolder: i18.t('deploy.workspace.selectPackage'), }).then((item) => { if (item) { selectTarget(item.package); } else { completed(null, 2); // aborted } }, (err) => { completed(err); }); } else { // auto select selectTarget(packageQuickPicks[0].package); } }); } /** * Deploys files of the workspace to a target. * * @param {string[]} files The files to deploy. * @param {deploy_contracts.DeployTarget} target The target. * * @returns {Promise<boolean>} The promise. */ protected deployWorkspaceTo(files: string[], target: deploy_contracts.DeployTarget): Promise<boolean> { let me = this; let nameOfTarget = deploy_helpers.normalizeString(target.name); if (files) { files = files.filter(f => !me.isFileIgnored(f)); } return new Promise<boolean>((resolve, reject) => { let hasCancelled = false; let completed = (err?: any) => { delete me._WORKSPACE_IN_PROGRESS[nameOfTarget]; if (err) { reject(err); } else { resolve(hasCancelled); } }; me.onCancelling(() => hasCancelled = true); let startDeployment = () => { try { me.hideAfterDeploymentStatusBarItem(); let type = deploy_helpers.parseTargetType(target.type); let matchIngPlugins = me.pluginsWithContextes.filter(x => { return !type || (x.plugin.__type === type && x.plugin.deployWorkspace); }); if (matchIngPlugins.length > 0) { let deployNextPlugin: () => void; deployNextPlugin = () => { if (matchIngPlugins.length < 1) { completed(); return; } if (hasCancelled) { completed(); return; } let cancelCommand: vscode.Disposable; let currentPluginWithContext = matchIngPlugins.shift(); let contextToUse = deploy_plugins.createPluginContext(currentPluginWithContext.context); let currentPlugin = currentPluginWithContext.plugin; let statusBarItem: vscode.StatusBarItem; let cleanUps = () => { deploy_helpers.tryDispose(cancelCommand); deploy_helpers.tryDispose(statusBarItem); deploy_helpers.tryDispose(contextToUse); }; let deployPlugin = () => { try { statusBarItem = vscode.window.createStatusBarItem( vscode.StatusBarAlignment.Left, ); statusBarItem.color = '#ffffff'; statusBarItem.text = i18.t('deploy.button.prepareText'); statusBarItem.tooltip = i18.t('deploy.button.tooltip'); let cancelCommandName = 'extension.deploy.cancelWorkspace' + (nextCancelDeployWorkspaceCommandId--); cancelCommand = vscode.commands.registerCommand(cancelCommandName, () => { if (hasCancelled) { return; } hasCancelled = true; try { contextToUse.emit(deploy_contracts.EVENT_CANCEL_DEPLOY); } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.deployWorkspaceTo().cancel', e)); } statusBarItem.text = i18.t('deploy.button.cancelling'); statusBarItem.tooltip = i18.t('deploy.button.cancelling'); }); statusBarItem.command = cancelCommandName; let failed: string[] = []; let succeeded: string[] = []; let showResult = (err?: any) => { let afterDeployButtonMsg = 'Deployment finished.'; try { cleanUps(); let targetExpr = deploy_helpers.toStringSafe(target.name).trim(); if (err) { if (targetExpr) { vscode.window.showErrorMessage(i18.t('deploy.workspace.failedWithTarget', targetExpr, err)); } else { vscode.window.showErrorMessage(i18.t('deploy.workspace.failed', err)); } } else { if (failed.length > 0) { if (succeeded.length < 1) { if (targetExpr) { vscode.window.showErrorMessage(i18.t('deploy.workspace.allFailedWithTarget', targetExpr, err)); } else { vscode.window.showErrorMessage(i18.t('deploy.workspace.allFailed', err)); } } else { let allCount = succeeded.length + failed.length; if (targetExpr) { vscode.window.showErrorMessage(i18.t('deploy.workspace.someFailedWithTarget', failed.length, allCount , targetExpr)); } else { vscode.window.showErrorMessage(i18.t('deploy.workspace.someFailed', failed.length, allCount)); } } } else { let allCount = succeeded.length; if (allCount > 0) { if (deploy_helpers.toBooleanSafe(me.config.showPopupOnSuccess, true)) { if (targetExpr) { vscode.window.showInformationMessage(i18.t('deploy.workspace.allSucceededWithTarget', allCount , targetExpr)); } else { vscode.window.showInformationMessage(i18.t('deploy.workspace.allSucceeded', allCount)); } } } else { if (targetExpr) { vscode.window.showWarningMessage(i18.t('deploy.workspace.nothingDeployedWithTarget', targetExpr)); } else { vscode.window.showWarningMessage(i18.t('deploy.workspace.nothingDeployed')); } } } } let resultMsg: string; if (err || failed.length > 0) { if (hasCancelled) { resultMsg = i18.t('deploy.canceledWithErrors'); } else { resultMsg = i18.t('deploy.finishedWithErrors'); } } else { if (hasCancelled) { resultMsg = i18.t('deploy.canceled'); } else { resultMsg = i18.t('deploy.finished2'); me.afterDeployment(files, target).catch((err) => { vscode.window.showErrorMessage(i18.t('deploy.after.failed', err)); }); } } if (resultMsg) { afterDeployButtonMsg = resultMsg; me.outputChannel.appendLine(resultMsg); } } finally { me.showStatusBarItemAfterDeployment(afterDeployButtonMsg, files, succeeded, failed); completed(err); } }; statusBarItem.show(); currentPlugin.deployWorkspace(files, target, { context: contextToUse, onBeforeDeployFile: (sender, e) => { let relativePath = deploy_helpers.toRelativePath(e.file); if (false === relativePath) { relativePath = e.file; } let statusMsg: string; let destination = deploy_helpers.toStringSafe(e.destination); if (destination) { statusMsg = i18.t('deploy.workspace.statusWithDestination', relativePath, destination); } else { statusMsg = i18.t('deploy.workspace.status', relativePath); } statusBarItem.text = i18.t('deploy.button.text'); statusBarItem.tooltip = statusMsg + ` (${i18.t('deploy.workspace.clickToCancel')})`; me.outputChannel.append(statusMsg); }, onCompleted: (sender, e) => { hasCancelled = hasCancelled || e.canceled; showResult(e.error); }, onFileCompleted: (sender, e) => { if (e.error) { me.outputChannel.appendLine(i18.t('failed', e.error)); failed.push(e.file); } else { me.outputChannel.appendLine(i18.t('ok')); succeeded.push(e.file); } } }); } catch (e) { cleanUps(); vscode.window.showErrorMessage(i18.t('deploy.workspace.failed', e)); } }; let checkForNewer = () => { if (deploy_helpers.toBooleanSafe(target.checkBeforeDeploy)) { deploy_diff.checkForNewerFiles.apply(me, [ files, target, currentPlugin ]).then((startDeploy: boolean | null) => { if (startDeploy) { deployPlugin(); } else { deployNextPlugin(); } }).catch((e) => { completed(e); }); } else { deployPlugin(); } }; checkForNewer(); }; deployNextPlugin(); } else { if (type) { vscode.window.showWarningMessage(i18.t('deploy.noPluginsForType', type)); } else { vscode.window.showWarningMessage(i18.t('deploy.noPlugins')); } completed(); } } catch (e) { completed(e); } }; if (deploy_helpers.isNullOrUndefined(me._WORKSPACE_IN_PROGRESS[nameOfTarget])) { me._WORKSPACE_IN_PROGRESS[nameOfTarget] = { files: files, target: target, type: 'deploy', }; startDeployment(); } else { // there is currently something that is in progress for the target // [BUTTON] yes let yesBtn: deploy_contracts.PopupButton = new deploy_objects.SimplePopupButton(); yesBtn.action = () => { startDeployment(); }; yesBtn.title = i18.t('yes'); vscode.window .showWarningMessage(i18.t('deploy.workspace.alreadyStarted', target.name), yesBtn) .then((item) => { if (!item || !item.action) { return; } item.action(); }); } }); } /** * Displays information about the network of this machine. * * @param {boolean} [force] Force displaying information or not. */ public displayNetworkInfo(force = false) { let me = this; if (!force) { if (!deploy_helpers.toBooleanSafe(me.config.displayNetworkInfo, true)) { return; } } try { this.outputChannel.appendLine(i18.t('network.hostname', this.name)); let networkInterfaces = OS.networkInterfaces(); if (Object.keys(networkInterfaces).length > 0) { this.outputChannel.appendLine(i18.t('network.interfaces.list')); Object.keys(networkInterfaces).forEach((ifName) => { let ifaces = networkInterfaces[ifName].filter(x => { let addr = deploy_helpers.normalizeString(x.address); if ('IPv4' === x.family) { return !/^(127\.[\d.]+|[0:]+1|localhost)$/.test(addr); } if ('IPv6' === x.family) { return '::1' !== addr; } return true; }); if (ifaces.length > 0) { me.outputChannel.appendLine(`\t- '${ifName}':`); ifaces.forEach(x => { me.outputChannel.appendLine(`\t\t[${x.family}] '${x.address}' / '${x.netmask}' ('${x.mac}')`); }); me.outputChannel.appendLine(''); } }); } else { this.outputChannel.appendLine(''); } } catch (e) { this.log(i18.t('network.interfaces.failed', e)); } } /** @inheritdoc */ public dispose() { try { this.removeAllListeners(); } catch (e) { this.log(i18.t('errors.withCategory', 'Deployer.dispose(1)', e)); } } /** * Emits a global event. * * @param {string | symbol} event The event. * @param {any[]} args The arguments. */ public emitGlobal(event: string | symbol, ...args: any[]): boolean { return deploy_globals.EVENTS .emit .apply(deploy_globals.EVENTS, arguments); } /** * Executes the startup commands, defined in the config. */ protected executeStartupCommands() { let me = this; let cfg = me.config; try { if (cfg.startupCommands) { let cmds = deploy_helpers.asArray(<any[]>cfg.startupCommands) .map((x: string | deploy_contracts.StartupCommand) => { if ('object' !== typeof x) { x = { command: deploy_helpers.toStringSafe(x).trim(), }; if (deploy_helpers.isEmptyString(x.command)) { x = <deploy_contracts.StartupCommand>null; } } return x; }) .filter(x => x); let nextCommand: () => void; nextCommand = () => { if (cmds.length < 1) { return; } let c = cmds.shift(); let args = c.arguments; if (!args) { args = []; } args = [ c.command ].concat(args); vscode.commands.executeCommand.apply(null, args).then(() => { nextCommand(); }, (err) => { me.log(i18.t('errors.withCategory', 'Deployer.executeStartupCommands(2)', err)); nextCommand(); }); }; nextCommand(); } } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.executeStartupCommands(1)', e)); } } /** * Filters "conditional" items. * * @param {T|T[]} items The items to filter. * * @return {T[]} The filtered items. */ public filterConditionalItems<T extends deploy_contracts.ConditionalItem>(items: T | T[]): T[] { return deploy_helpers.filterConditionalItems<T>(items, this.getValues()); } /** * Filters the list of targets by a package. * * @param {deploy_contracts.DeployPackage} pkg The package. * * @return {deploy_contracts.DeployTarget[]} The filtered targets. */ public filterTargetsByPackage(pkg: deploy_contracts.DeployPackage): deploy_contracts.DeployTarget[] { let pkgName = deploy_helpers.normalizeString(pkg.name); return this.getTargets().filter(t => { let takeTarget = true; let excludeForPackages = deploy_helpers.asArray(t.hideIf) .map(x => deploy_helpers.normalizeString(x)) .filter(x => '' !== x); for (let i = 0; i < excludeForPackages.length; i++) { if (excludeForPackages[i] === pkgName) { return false; // exclude } } let showForPackages = deploy_helpers.asArray(t.showIf) .map(x => deploy_helpers.normalizeString(x)) .filter(x => '' !== x); if (showForPackages.length > 0) { takeTarget = false; // exclude by default now for (let i = 0; i < showForPackages.length; i++) { if (showForPackages[i] === pkgName) { takeTarget = true; // include break; } } } return takeTarget; }); } /** * Returns the global variables defined in settings. * * @return {deploy_contracts.GlobalVariables} The globals. */ public getGlobals(): deploy_contracts.GlobalVariables { let result: deploy_contracts.GlobalVariables = {}; let cfgGlobals = this.config.globals; if (cfgGlobals) { result = deploy_helpers.cloneObject(cfgGlobals); } return result; } /** * Returns the next color for the deploy result in the status bar * by category. * * @param {string} category The category. * * @return {string} The color. */ protected getNextAfterDeploymentButtonColor(category: string) { let index = this._NEXT_AFTER_DEPLOYMENT_BUTTON_COLORS[category]++; if (this._NEXT_AFTER_DEPLOYMENT_BUTTON_COLORS[category] > 2) { this._NEXT_AFTER_DEPLOYMENT_BUTTON_COLORS[category] = 0; } return '#' + AFTER_DEPLOYMENT_BUTTON_COLORS[category][index]; } /** * Returns the list of packages. * * @returns {DeployPackage[]} The packages. */ public getPackages(): deploy_contracts.DeployPackage[] { return deploy_packages.getPackages .apply(this); } /** * Returns the list of targets. * * @returns {DeployTarget[]} The targets. */ public getTargets(): deploy_contracts.DeployTarget[] { return deploy_targets.getTargets .apply(this); } /** * Returns the targets from a package. * * @param {deploy_contracts.DeployPackag} pkg The package. * * @return {deploy_contracts.DeployTarget[]} The found targets. */ protected getTargetsFromPackage(pkg: deploy_contracts.DeployPackage): deploy_contracts.DeployTarget[] { let pkgTargets: deploy_contracts.DeployTarget[] = []; let normalizeString = (val: any): string => { return deploy_helpers.toStringSafe(val) .toLowerCase().trim(); }; let targetNames = deploy_helpers.asArray(pkg.targets) .map(x => normalizeString(x)) .filter(x => '' !== x); let knownTargets = this.getTargets(); targetNames.forEach(tn => { let found = false; for (let i = 0; i < knownTargets.length; i++) { let kt = knownTargets[i]; if (normalizeString(kt.name) === tn) { found = true; pkgTargets.push(kt); } } if (!found) { // we have an unknown target here vscode.window.showWarningMessage(i18.t('packages.couldNotFindTarget', tn, pkg.name)); } }); return pkgTargets; } /** * Gets the current list of values. * * @return {ValueBase[]} The values. */ public getValues(): deploy_values.ValueBase[] { return deploy_values.getValues .apply(this, arguments); } /** * Handles a "common" deploy operation. * * @param {deploy_contracts.DeployOperation} operation The operation. * @param {deploy_contracts.DeployOperationKind} kind The kind of operation. * @param {string[]} files The files to deploy. * @param {deploy_contracts.DeployTarget} target The target. * * @return Promise<boolean> The promise. */ protected handleCommonDeployOperation(operation: deploy_contracts.DeployOperation, kind: deploy_contracts.DeployOperationKind, files: string[], target: deploy_contracts.DeployTarget): Promise<boolean> { let me = this; return new Promise<boolean>((resolve, reject) => { let handled = true; let completed = (err?: any) => { if (err) { reject(err); } else { resolve(handled); } }; let executor: deploy_operations.OperationExecutor<deploy_contracts.DeployOperation>; let executorThisArgs: any = me; try { let nextAction = completed; switch (deploy_helpers.toStringSafe(operation.type).toLowerCase().trim()) { case '': case 'open': executor = deploy_operations.open; break; case 'compile': executor = deploy_operations.compile; break; case 'http': executor = deploy_operations.http; break; case 'script': let scriptExecutor: deploy_contracts.DeployScriptOperationExecutor; let scriptOpts = <deploy_contracts.DeployScriptOperation>operation; let scriptFile = scriptOpts.script; if (!deploy_helpers.isEmptyString(scriptOpts.script)) { if (!Path.isAbsolute(scriptFile)) { scriptFile = Path.join(deploy_workspace.getRootPath(), scriptFile); } scriptFile = Path.resolve(scriptFile); let scriptModule = deploy_helpers.loadDeployScriptOperationModule(scriptOpts.script); if (scriptModule) { scriptExecutor = scriptModule.execute; } } nextAction = null; if (scriptExecutor) { let sym = Symbol("deploy.deploy.Deployer.handleCommonDeployOperation"); let allStates = me._scriptOperationStates; let scriptArgs: deploy_contracts.DeployScriptOperationArguments = { deployFiles: (files, targets) => { return deploy_helpers.deployFiles(files, targets, sym); }, emitGlobal: function() { return me.emitGlobal .apply(me, arguments); }, files: files, globals: me.getGlobals(), kind: kind, openHtml: function() { return me.openHtml .apply(me, arguments); }, options: deploy_helpers.cloneObject(scriptOpts.options), replaceWithValues: (v) => me.replaceWithValues(v), require: function(id) { return require(id); }, target: target, }; // scriptArgs.globalState Object.defineProperty(scriptArgs, 'globalState', { enumerable: true, get: () => { return me._globalScriptOperationState; }, }); // scriptArgs.state Object.defineProperty(scriptArgs, 'state', { enumerable: true, get: () => { return allStates[scriptFile]; }, set: (v) => { allStates[scriptFile] = v; }, }); Promise.resolve(<any>scriptExecutor(scriptArgs)).then(() => { completed(); }).catch((err) => { completed(err); }); } else { // execute() function not found in script! nextAction = () => { completed(new Error(i18.t('deploy.operations.noFunctionInScript', 'execute', scriptOpts.script))); }; } break; case 'sql': executor = deploy_operations.sql; break; case 'vscommand': executor = deploy_operations.vscommand; break; case 'wait': executor = deploy_operations.wait; break; case 'webdeploy': executor = deploy_operations.webdeploy; break; default: handled = false; break; } if (executor) { let ctx: deploy_operations.OperationContext<deploy_contracts.DeployOperation> = { config: me.config, files: files, globals: me.getGlobals(), handled: handled, kind: kind, operation: operation, outputChannel: me.outputChannel, }; let execRes = executor.apply(executorThisArgs, [ ctx ]); if ('object' === typeof execRes) { execRes.then((hasHandled) => { handled = deploy_helpers.toBooleanSafe(hasHandled, deploy_helpers.toBooleanSafe(ctx.handled, true)); completed(); }).catch((err) => { completed(err); }); } else { handled = deploy_helpers.toBooleanSafe(deploy_helpers.toBooleanSafe(execRes), deploy_helpers.toBooleanSafe(ctx.handled, true)); completed(ctx.error); } } else { if (nextAction) { nextAction(); } } } catch (e) { completed(e); } }); } /** * Hides the 'after deploy' status bar item. */ public hideAfterDeploymentStatusBarItem() { this._AFTER_DEPLOYMENT_STATUS_ITEM.hide(); } /** * Gets the list of HTML documents. */ public get htmlDocuments(): deploy_contracts.Document[] { return this._htmlDocs; } /** * Gets if the extension is currently active or not. */ public get isActive(): boolean { return !deploy_helpers.isEmptyString(deploy_workspace.getRootPath()); } /** * Checks if a file (or directory) path is ignored. * * @param {string} fileOrDir The file / directory to check. * * @return {boolean} Is ignored or not. */ public isFileIgnored(fileOrDir: string): boolean { return deploy_helpers.isFileIgnored(fileOrDir, this.config.ignore, this.config.useGitIgnoreStylePatterns, this.config.fastCheckForIgnores); } /** * Gets the timestamp of the last config update. */ public get lastConfigUpdate(): Moment.Moment { return this._lastConfigUpdate; } /** * Starts listening for files. */ public listen() { let me = this; let cfg = me.config; let dir: string; let port = deploy_contracts.DEFAULT_PORT; let showPopup = true; if (cfg.host) { dir = cfg.host.dir; port = parseInt(deploy_helpers.toStringSafe(cfg.host.port, '' + deploy_contracts.DEFAULT_PORT)); showPopup = deploy_helpers.toBooleanSafe(cfg.host.showPopupOnSuccess, true); } dir = deploy_helpers.toStringSafe(dir, deploy_contracts.DEFAULT_HOST_DIR); if (!Path.isAbsolute(dir)) { dir = Path.join(deploy_workspace.getRootPath(), dir); } // destroy old status bar item let statusItem = me._serverStatusItem; if (statusItem) { try { statusItem.dispose(); } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.listen()', e)); } statusItem = null; } me._serverStatusItem = null; let host = me._host; if (host) { // stop host.stop().then(() => { me._host = null; let successMsg = i18.t('host.stopped'); if (showPopup) { vscode.window.showInformationMessage(successMsg); } me.outputChannel.appendLine(successMsg); }).catch((err) => { let errMsg = i18.t('host.errors.couldNotStop', err); vscode.window.showErrorMessage(errMsg); me.outputChannel.appendLine(errMsg); }); } else { // start host = new DeployHost(me); host.start().then(() => { me._host = host; let successMsg = i18.t('host.started', port, dir); me.outputChannel.appendLine(successMsg); if (showPopup) { vscode.window.showInformationMessage(successMsg); } statusItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); statusItem.tooltip = ''; statusItem.command = 'extension.deploy.listen'; statusItem.text = i18.t('host.button.text'); statusItem.tooltip = i18.t('host.button.tooltip'); statusItem.show(); me._serverStatusItem = statusItem; }).catch((err) => { vscode.window.showErrorMessage(i18.t('host.errors.cannotListen', err)); }); } } /** * Logs a message. * * @param {any} msg The message to log. * * @chainable */ public log(msg: any): Deployer { let now = Moment(); msg = deploy_helpers.toStringSafe(msg); this.outputChannel .appendLine(`[${now.format('YYYY-MM-DD HH:mm:ss')}] ${msg}`); return this; } /** * Get the name that represents that machine. */ public get name(): string { let cfg = this.config; let name: string; if (cfg) { name = cfg.name; // use from config } if (deploy_helpers.isEmptyString(name)) { name = OS.hostname(); // default } return deploy_helpers.normalizeString(name); } /** * The 'on activated' event. */ public onActivated() { this._startTime = Moment(); this.registerGlobalEvents(); deploy_globals.EVENTS.emit( deploy_contracts.EVENT_WORKSPACE_CHANGED ); this.setupFileSystemWatcher(); } /** * Registers for a callback for a 'cancel' event that is called once. * * @param {deploy_contracts.EventHandler} callback The callback to register. */ public onCancelling(callback: deploy_contracts.EventHandler) { try { this.once(deploy_contracts.EVENT_CANCEL_DEPLOY, callback); } catch (e) { this.log(i18.t('errors.withCategory', 'Deployer.onCancelling()', e)); } } /** * The 'on deactivate' event. */ public onDeactivate() { if (deploy_helpers.tryDispose(this._fileSystemWatcher)) { this._fileSystemWatcher = null; } // freeze 'deploy on change' deploy_helpers.tryClearTimeout(this._deployOnChangeFreezer); this._isDeployOnChangeFreezed = true; // destroy buttons deploy_helpers.tryDispose(this._QUICK_DEPLOY_STATUS_ITEM); deploy_buttons.unloadPackageButtons(); } /** * Is invoked after active text editor has been changed. * * @param {vscode.TextEditor} editor The new editor. */ public onDidChangeActiveTextEditor(editor: vscode.TextEditor) { const ME = this; const CFG = ME.config; const PREVIOUS_EDITOR = ME._currentTextEditor; ME._currentTextEditor = editor; const AUTO_SELECT_WORKSPACE_COMPLETED = (err: any) => { if (err) { let errMsg = i18.t('workspace.autoSelect.failed', err); if (deploy_helpers.isEmptyString(errMsg)) { errMsg = `Could not auto-select workspace: '${deploy_helpers.toStringSafe(err)}'`; } vscode.window .showWarningMessage('[vs-deploy] ' + errMsg); } }; // auto select workspace try { const MATCHING_FOLDERS: vscode.WorkspaceFolder[] = []; const UPDATE_WORKSPACE = (newFolder: vscode.WorkspaceFolder) => { try { if (newFolder) { deploy_workspace.setWorkspace(newFolder); ME.reloadConfiguration(); } } catch (e) { AUTO_SELECT_WORKSPACE_COMPLETED(e); } }; if (editor) { if (CFG && deploy_helpers.toBooleanSafe( CFG.autoSelectWorkspace )) { const DOC = editor.document; if (DOC) { // only for document if (FS.existsSync( DOC.fileName )) { const FILE = Path.resolve( DOC.fileName ); const DIR = Path.resolve( Path.dirname(FILE) ); const CURRENT_DIR = Path.resolve( deploy_workspace.getRootPath() ); if (CURRENT_DIR !== DIR) { // folders are different const WORKSPACE_FOLDERS = (vscode.workspace.workspaceFolders || []).filter(wsf => { return wsf; }); // try to find matching folder // only there are at least 2 folders if (WORKSPACE_FOLDERS.length > 1) { for (let i = 0; i < WORKSPACE_FOLDERS.length; i++) { const WSF = WORKSPACE_FOLDERS[i]; const URI = WSF.uri; if (URI) { let wsfPath = URI.fsPath; if (!deploy_helpers.isEmptyString(wsfPath)) { wsfPath = Path.resolve(wsfPath); if (DIR.startsWith(wsfPath)) { MATCHING_FOLDERS.push(WSF); } } } } } } } } if (MATCHING_FOLDERS.length > 0) { if (1 === MATCHING_FOLDERS.length) { UPDATE_WORKSPACE( MATCHING_FOLDERS[0] ); } else { // more than one machting folders deploy_workspace.selectWorkspace().then((newWorkspaceFolder) => { UPDATE_WORKSPACE(newWorkspaceFolder); }).catch((err) => { AUTO_SELECT_WORKSPACE_COMPLETED(err); }); } } } } } catch (e) { AUTO_SELECT_WORKSPACE_COMPLETED(e); } } /** * Event after configuration changed. */ public onDidChangeConfiguration(e: vscode.ConfigurationChangeEvent) { if (!e.affectsConfiguration('deploy', vscode.Uri.file(this.settingsFile))) { return; } this.reloadConfiguration(); } /** * Event after list of workspace folders changed. * * @param {vscode.WorkspaceFoldersChangeEvent} e The event arguments. */ public onDidChangeWorkspaceFolders(e: vscode.WorkspaceFoldersChangeEvent) { deploy_globals.EVENTS.emit( deploy_contracts.EVENT_WORKSPACE_CHANGED, e ); } /** * Event after a document has been saved. * * @param {string} fileName The path of the file. * @param {deploy_contracts.DeployPackage[]} [packagesToDeploy] The custom package list. */ public onDidSaveFile(fileName: string, packagesToDeploy?: deploy_contracts.DeployPackage[]) { if (deploy_helpers.isEmptyString(fileName)) { return; } let me = this; let docFile = deploy_helpers.replaceAllStrings(fileName, Path.sep, '/'); let relativeDocFilePath = deploy_helpers.toRelativePath(docFile); if (false === relativeDocFilePath) { relativeDocFilePath = docFile; } try { let getTargetNamesByPackage = (pkg: deploy_contracts.DeployPackage) => { let useTargetLists = deploy_helpers.toBooleanSafe(me.config.useTargetListForDeployOnSave); let checkForPackageSpecificTargetListSetting = true; if (packagesToDeploy) { // we are in "deploy on change" context if (pkg.deployOnChange) { if (true !== pkg.deployOnChange) { if (!deploy_helpers.isNullOrUndefined(pkg.deployOnChange.useTargetList)) { // use "deploy on change" specific setting useTargetLists = deploy_helpers.toBooleanSafe(pkg.deployOnChange.useTargetList); checkForPackageSpecificTargetListSetting = false; } } } } if (checkForPackageSpecificTargetListSetting) { if (!deploy_helpers.isNullOrUndefined(pkg.useTargetListForDeployOnSave)) { // use package specific setting useTargetLists = deploy_helpers.toBooleanSafe(pkg.useTargetListForDeployOnSave); } } let targetSource: string[]; if (pkg) { if (useTargetLists) { // use targets from the 'targets' property // of package if (true !== pkg.deployOnSave) { targetSource = deploy_helpers.asArray(pkg.deployOnSave); } targetSource = deploy_helpers.asArray(pkg.targets); } else { // use targets from 'deployOnSave' property if (true === pkg.deployOnSave) { targetSource = me.getTargets() .map(x => x.name); } else { targetSource = deploy_helpers.asArray(pkg.deployOnSave); } } } return (targetSource || []).map(x => deploy_helpers.normalizeString(x)) .filter(x => '' !== x); }; if (!packagesToDeploy) { // find packages that would deploy the file packagesToDeploy = me.getPackages().filter(x => { if (!x.deployOnSave) { return false; // do NOT deploy on save } let fastFileCheck = x.fastCheckOnSave; if (deploy_helpers.isNullOrUndefined(fastFileCheck)) { // not defined in package => use global value fastFileCheck = deploy_helpers.toBooleanSafe(me.config.fastCheckOnSave); } if (fastFileCheck) { // use fast check by minimatch return deploy_helpers.doesFileMatchByFilter(docFile, x); } return deploy_helpers.getFilesOfPackage(x, me.useGitIgnoreStylePatternsInFilter(x)) .indexOf(docFile) > -1; }); } let targets = me.getTargets(); if (deploy_helpers.toBooleanSafe(me.config.showWarningsForNonExistingTargets)) { // check for non existing target names packagesToDeploy.forEach(pkg => { let packageName = deploy_helpers.normalizeString(pkg.name); getTargetNamesByPackage(pkg).forEach(tn => { let foundTarget = false; for (let i = 0; i < targets.length; i++) { if (deploy_helpers.normalizeString(targets[i].name) === tn) { foundTarget = true; break; } } if (!foundTarget) { vscode.window.showWarningMessage(i18.t('deploy.onSave.couldNotFindTarget', tn, packageName)); } }); }); } // find matching targets targets = targets.filter(t => { let targetName = deploy_helpers.normalizeString(t.name); for (let i = 0; i < packagesToDeploy.length; i++) { let pkg = packagesToDeploy[i]; if (getTargetNamesByPackage(pkg).indexOf(targetName) > -1) { // is part of the package return true; } } return false; }); // deploy file to targets targets.forEach(t => { let showError = (err: any) => { let targetName = deploy_helpers.toStringSafe(t.name).trim(); vscode.window.showWarningMessage(i18.t('deploy.onSave.failedTarget', relativeDocFilePath, targetName ? `'${targetName}'` : 'target', err)); }; me.beforeDeploy([ docFile ], t).then((canceled) => { if (canceled) { return; } me.deployFileTo(docFile, t).then((canceled) => { if (canceled) { return; } // DO NOT invoke me.afterDeployment() // this is done by me.deployFileTo()! }).catch((err) => { showError(err); }); // deploy }).catch((err) => { showError(err); }); // beforeDeploy }); } catch (e) { vscode.window.showErrorMessage(i18.t('deploy.onSave.failed', relativeDocFilePath, 2, e)); } } /** * Event after text document has been opened. * * @param {vscode.TextDocument} doc The document. */ public onDidOpenTextDocument(doc: vscode.TextDocument) { if (!doc) { return; } let me = this; if (!doc.isUntitled && !deploy_helpers.isEmptyString(doc.fileName)) { if (deploy_helpers.toBooleanSafe(this.config.syncWhenOpen, true) && this._isSyncWhenOpenEnabled) { // only if activated deploy_sync.syncDocumentWhenOpen.apply(me, [ doc ]).then(() => { //TODO }).catch((err) => { //TODO }); } } } /** * Event after a document has been saved. * * @param {vscode.TextDocument} doc The document. */ public onDidSaveTextDocument(doc: vscode.TextDocument) { if (!doc) { return; } if (!this.isActive) { return; // not active } if (deploy_helpers.toBooleanSafe(this.config.deployOnSave, true) && this._isDeployOnSaveEnabled) { // only if activated this.onDidSaveFile(doc.fileName); } } /** * Is invoked on a file / directory change. * * @param {vscode.Uri} e The URI of the item. * @param {string} type The type of change. */ protected onFileChange(e: vscode.Uri, type: string) { let me = this; if (!me.isActive) { return; // not active } if (deploy_helpers.toBooleanSafe(me._isDeployOnChangeFreezed)) { // freezed return; } if (!(deploy_helpers.toBooleanSafe(me.config.deployOnChange, true) && me._isDeployOnChangeEnabled)) { // deactivated return; } try { let filePath = Path.resolve(e.fsPath); let normalizePath = (str: string) => { return str ? deploy_helpers.replaceAllStrings(str, Path.sep, '/') : str; }; FS.exists(filePath, (exists) => { if (!exists) { return; } FS.lstat(filePath, (err, stats) => { if (err || !stats.isFile()) { return; } let packagesToDeploy: deploy_contracts.DeployPackage[] = []; let allPackages = me.getPackages(); for (let i = 0; i < allPackages.length; i++) { let pkg = allPackages[i]; if (deploy_helpers.isNullOrUndefined(pkg.deployOnChange)) { continue; } let doesFileMatch = false; let fastFileCheck = pkg.fastCheckOnChange; if (deploy_helpers.isNullOrUndefined(fastFileCheck)) { // not defined in package => use global value fastFileCheck = deploy_helpers.toBooleanSafe(me.config.fastCheckOnChange); } if (fastFileCheck) { // use minimatch if (true === pkg.deployOnChange) { doesFileMatch = deploy_helpers.doesFileMatchByFilter(filePath, pkg); } else { doesFileMatch = deploy_helpers.doesFileMatchByFilter(filePath, pkg.deployOnChange); } } else { // use Glob let matchingFiles: string[]; if (true === pkg.deployOnChange) { matchingFiles = deploy_helpers.getFilesOfPackage(pkg, me.useGitIgnoreStylePatternsInFilter(pkg)); } else { matchingFiles = deploy_helpers.getFilesByFilter(pkg.deployOnChange, me.useGitIgnoreStylePatternsInFilter(pkg.deployOnChange)) .filter(x => Path.resolve(x)); } doesFileMatch = matchingFiles.map(x => normalizePath(x)).indexOf(normalizePath(filePath)) > -1; } if (doesFileMatch) { packagesToDeploy.push(pkg); } } if (packagesToDeploy.length > 0) { me.onDidSaveFile(filePath, packagesToDeploy); } }); }); } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.onFileChange()', e)); } } /** * Opens the files that are defined in the config. */ protected openFiles() { let me = this; try { let cfg = me.config; if (cfg.open) { // cleanup filter list let filters = me.filterConditionalItems(cfg.open) .filter(x => { return deploy_helpers.asArray(x.files) .map(y => deploy_helpers.toStringSafe(y)) .filter(y => '' !== y) .length > 0; }); let closeOtherEditors = false; let filesToOpen: string[] = []; let completed = () => { // cleanup list of files to open filesToOpen = filesToOpen.map(x => Path.resolve(x)); filesToOpen = deploy_helpers.distinctArray(filesToOpen); if (closeOtherEditors) { // close other editors vscode.window.visibleTextEditors.forEach(x => { try { x.hide(); } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.openFiles(2)', e)); } }); } filesToOpen.forEach(x => { // try open... vscode.workspace.openTextDocument(x).then((doc) => { // try show... vscode.window.showTextDocument(doc).then(() => { //TODO }, (err) => { // could not SHOW text document me.log(i18.t('errors.withCategory', 'Deployer.openFiles(4)', err)); }); }, (err) => { // could not OPEN text document me.log(i18.t('errors.withCategory', 'Deployer.openFiles(3)', err)); }); }); }; let nextFilter: () => void; nextFilter = () => { if (filters.length < 1) { completed(); return; } let dir = deploy_workspace.getRootPath(); let f = filters.shift(); // hostname / machine filter(s) let isFor = deploy_helpers.asArray(f.isFor) .map(x => deploy_helpers.normalizeString(x)) .filter(x => x); if (isFor.length > 0) { let myName = deploy_helpers.normalizeString(me.name); if (isFor.indexOf(myName) < 0) { nextFilter(); // not for that machine return; } } closeOtherEditors = closeOtherEditors || deploy_helpers.toBooleanSafe(f.closeOthers); // patterns to search for let filesToSearchFor = deploy_helpers.asArray(f.files) .filter(x => x); filesToSearchFor = deploy_helpers.distinctArray(filesToSearchFor); if (filesToSearchFor.length > 0) { // files to exclude let filesToExclude = deploy_helpers.asArray(f.exclude) .filter(x => x); filesToExclude = deploy_helpers.distinctArray(filesToExclude); filesToSearchFor.forEach(x => { try { let foundFiles: string[] = Glob.sync(x, { absolute: true, cwd: dir, dot: true, ignore: filesToExclude, nodir: true, root: dir, }); filesToOpen = filesToOpen.concat(foundFiles); } catch (e) { // error while collecting files to open me.log(i18.t('errors.withCategory', 'Deployer.openFiles(5)', e)); } }); } nextFilter(); // next }; nextFilter(); // start } } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.openFiles(1)', e)); } } /** * Opens a HTML document in a new tab. * * @param {string} html The HTML document (source code). * @param {string} [title] The custom title for the tab. * @param {any} [id] The custom ID for the document in the storage. * * @returns {Promise<any>} The promise. */ public openHtml(html: string, title?: string, id?: any): Promise<any> { return deploy_helpers.openHtmlDocument(this.htmlDocuments, html, title, id); } /** * Action to open the output after an deployment. */ public openOutputAfterDeploment() { this.hideAfterDeploymentStatusBarItem(); this.outputChannel.show(); } /** * Opens a template. */ public openTemplate() { deploy_templates.openTemplate .apply(this, arguments); } /** * Gets the global output channel. */ public get outputChannel(): vscode.OutputChannel { return this._OUTPUT_CHANNEL; } /** * Gets the package file of that extension. */ public get packageFile(): deploy_contracts.PackageFile { return this._PACKAGE_FILE; } /** * Gets the list of plugins. */ public get plugins(): deploy_contracts.DeployPlugin[] { return this.pluginsWithContextes .map(x => x.plugin); } /** * Gets the list of plugins withs its contextes. */ public get pluginsWithContextes(): deploy_contracts.DeployPluginWithContext[] { return this._plugins; } /** * Pulls a file or folder. * * @param {any} [uri] The URI of the file / folder to deploy. */ public pullFileOrFolder(uri?: any) { let me = this; let path: string; if (uri && uri.fsPath) { path = uri.fsPath; } else { let currentEditor = vscode.window.activeTextEditor; if (currentEditor) { let currentDocument = currentEditor.document; if (currentDocument) { path = currentDocument.fileName; } } } if (deploy_helpers.isEmptyString(path)) { return; } let showError = (err: any) => { vscode.window.showErrorMessage(i18.t('pull.fileOrFolder.failed', path, err)); }; // check if file or folder FS.lstat(path, (err, stats) => { if (err) { showError(err); return; } try { if (stats.isDirectory()) { me.pullFolder(path); // folder } else if (stats.isFile()) { me.pullFile(path); // file } else { showError(new Error(i18.t('isNo.validItem', path))); } } catch (e) { showError(e); } }); } /** * Pulls a file. * * @param {string} file The path of the file to deploy. */ protected pullFile(file: string) { let me = this; let targets = this.getTargets() .filter(x => !deploy_helpers.toBooleanSafe(x.isHidden)); if (targets.length < 1) { vscode.window.showWarningMessage(i18.t('targets.noneDefined')); return; } let quickPicks = targets.map((x, i) => deploy_helpers.createFileQuickPick(file, x, i, me.getValues())); let pull = (item: deploy_contracts.DeployFileQuickPickItem) => { let showError = (err: any) => { vscode.window.showErrorMessage(i18.t(`pull.file.failed`, file, err)); }; try { me.pullFileFrom(file, item.target).then((canceled) => { if (canceled) { return; } // currently nothing to do here }).catch((err) => { showError(err); }); // pullFileFrom } catch (e) { showError(e); } }; if (quickPicks.length > 1) { vscode.window.showQuickPick(quickPicks, { placeHolder: i18.t('targets.selectSource'), }).then((item) => { pull(item); }); } else { // auto select pull(quickPicks[0]); } } /** * Pulls a file from a target. * * @param {string} file The file to pull. * @param {deploy_contracts.DeployTarget} target The target from where to pull. * * @return {Promise<boolean>} The promise. */ protected pullFileFrom(file: string, target: deploy_contracts.DeployTarget): Promise<boolean> { let me = this; return new Promise<boolean>((resolve, reject) => { let hasCancelled = false; let completed = (err?: any) => { if (err) { reject(err); } else { resolve(hasCancelled); } }; if (me.isFileIgnored(file)) { if (deploy_helpers.toBooleanSafe(me.config.showWarningIfIgnored, true)) { // show warning vscode.window.showWarningMessage(i18.t('deploy.file.isIgnored', file)); } hasCancelled = true; completed(null); return; } me.onCancelling(() => hasCancelled = true); try { let type = deploy_helpers.parseTargetType(target.type); let matchIngPlugins = me.pluginsWithContextes.filter(x => { return !type || (x.plugin.__type === type && deploy_helpers.toBooleanSafe(x.plugin.canPull) && x.plugin.pullFile); }); let relativePath = deploy_helpers.toRelativePath(file); if (false === relativePath) { relativePath = file; } if (matchIngPlugins.length > 0) { let pullNextPlugin: () => void; pullNextPlugin = () => { if (matchIngPlugins.length < 1) { completed(); return; } if (hasCancelled) { completed(); return; } let cancelCommand: vscode.Disposable; let currentPluginWithContext = matchIngPlugins.shift(); let contextToUse = deploy_plugins.createPluginContext(currentPluginWithContext.context); let currentPlugin = currentPluginWithContext.plugin; let statusBarItem: vscode.StatusBarItem; let cleanUps = () => { deploy_helpers.tryDispose(cancelCommand); deploy_helpers.tryDispose(statusBarItem); deploy_helpers.tryDispose(contextToUse); }; try { statusBarItem = vscode.window.createStatusBarItem( vscode.StatusBarAlignment.Left, ); statusBarItem.color = '#ffffff'; statusBarItem.text = i18.t('pull.button.prepareText'); statusBarItem.tooltip = i18.t('pull.button.tooltip'); let cancelCommandName = 'extension.deploy.cancelPullFile' + (nextCancelPullFileCommandId--); cancelCommand = vscode.commands.registerCommand(cancelCommandName, () => { if (hasCancelled) { return; } hasCancelled = true; try { contextToUse.emit(deploy_contracts.EVENT_CANCEL_PULL); } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.pullFileFrom().cancel', e)); } statusBarItem.text = i18.t('pull.button.cancelling'); statusBarItem.tooltip = i18.t('pull.button.cancelling'); }); statusBarItem.command = cancelCommandName; let showResult = (err?: any) => { try { cleanUps(); let targetExpr = deploy_helpers.toStringSafe(target.name).trim(); let resultMsg; if (err) { if (hasCancelled) { resultMsg = i18.t('pull.canceledWithErrors'); } else { resultMsg = i18.t('pull.finishedWithErrors'); } } else { if (deploy_helpers.toBooleanSafe(me.config.showPopupOnSuccess, true)) { if (targetExpr) { vscode.window.showInformationMessage(i18.t('pull.file.succeededWithTarget', file, targetExpr)); } else { vscode.window.showInformationMessage(i18.t('pull.file.succeeded', file)); } } if (hasCancelled) { resultMsg = i18.t('pull.canceled'); } else { resultMsg = i18.t('pull.finished2'); } } if (resultMsg) { me.outputChannel.appendLine(resultMsg); } } finally { completed(err); } }; try { statusBarItem.show(); currentPlugin.pullFile(file, target, { context: contextToUse, onBeforeDeploy: (sender, e) => { let destination = deploy_helpers.toStringSafe(e.destination); let targetName = deploy_helpers.toStringSafe(e.target.name); me.outputChannel.appendLine(''); let pullMsg: string; if (targetName) { targetName = ` ('${targetName}')`; } if (destination) { pullMsg = i18.t('pull.file.pullingWithDestination', file, destination, targetName); } else { pullMsg = i18.t('pull.file.pulling', file, targetName); } me.outputChannel.append(pullMsg); statusBarItem.text = i18.t('pull.button.text'); }, onCompleted: (sender, e) => { if (e.error) { me.outputChannel.appendLine(i18.t('failed', e.error)); } else { me.outputChannel.appendLine(i18.t('ok')); } hasCancelled = hasCancelled || e.canceled; showResult(e.error); } }); } catch (e) { showResult(e); } } catch (e) { cleanUps(); completed(e); } }; pullNextPlugin(); } else { if (type) { vscode.window.showWarningMessage(i18.t('pull.noPluginsForType', type)); } else { vscode.window.showWarningMessage(i18.t('pull.noPlugins')); } completed(); } } catch (e) { completed(e); } }); }; /** * Pulls a folder. * * @param {string} dir The path of the folder to pull. */ protected pullFolder(dir: string) { let me = this; dir = Path.resolve(dir); let filesToPull: string[] = Glob.sync('**', { absolute: true, cwd: dir, dot: true, ignore: [], nodir: true, root: dir, }); let targets = this.getTargets() .filter(x => !deploy_helpers.toBooleanSafe(x.isHidden)); if (targets.length < 1) { vscode.window.showWarningMessage(i18.t('targets.noneDefined')); return; } // start pull the folder // by selected target let pull = (t: deploy_contracts.DeployTarget) => { me.pullWorkspaceFrom(filesToPull, t).then(() => { //TODO }).catch((err) => { vscode.window.showErrorMessage(i18.t('deploy.folder.failed', dir, err)); }); }; // select the target let fileQuickPicks = targets.map((x, i) => deploy_helpers.createTargetQuickPick(x, i, me.getValues())); if (fileQuickPicks.length > 1) { vscode.window.showQuickPick(fileQuickPicks, { placeHolder: i18.t('deploy.folder.selectTarget'), }).then((item) => { if (item) { pull(item.target); } }); } else { // auto select pull(fileQuickPicks[0].target); } } /** * Pulls files to the workspace. */ public pullWorkspace() { let me = this; let packages = this.getPackages() .filter(x => !deploy_helpers.toBooleanSafe(x.isHidden) && deploy_helpers.toBooleanSafe(x.showForPull, true)); if (packages.length < 1) { vscode.window.showWarningMessage(i18.t('packages.noneDefined')); return; } let packageQuickPicks = packages.map((x, i) => deploy_helpers.createPackageQuickPick(x, i, me.getValues())); let selectTarget = (pkg: deploy_contracts.DeployPackage) => { if (!pkg) { return; } let targets = me.filterTargetsByPackage(pkg) .filter(x => !deploy_helpers.toBooleanSafe(x.isHidden)); if (targets.length < 1) { vscode.window.showWarningMessage(i18.t('targets.noneDefined')); return; } let packageName = deploy_helpers.toStringSafe(pkg.name); let filesToPull = deploy_helpers.getFilesOfPackage(pkg, me.useGitIgnoreStylePatternsInFilter(pkg)); let pull = (t: deploy_contracts.DeployTarget) => { try { if (!t) { return; } let targetName = deploy_helpers.toStringSafe(t.name); me.outputChannel.appendLine(''); let deployMsg: string; if (targetName) { deployMsg = i18.t('pull.workspace.pullingWithTarget', packageName, targetName); } else { deployMsg = i18.t('pull.workspace.pulling', packageName); } me.outputChannel.appendLine(deployMsg); if (deploy_helpers.toBooleanSafe(me.config.openOutputOnDeploy, true)) { me.outputChannel.show(); } me.pullWorkspaceFrom(filesToPull, t).then(() => { //TODO }).catch((err) => { vscode.window.showErrorMessage(i18.t('pull.workspace.failedWithCategory', 2, err)); }); } catch (e) { vscode.window.showErrorMessage(i18.t('pull.workspace.failedWithCategory', 1, e)); } }; let targetsOfPackage = me.getTargetsFromPackage(pkg); if (targetsOfPackage.length < 1) { // no explicit targets let fileQuickPicks = targets.map((x, i) => deploy_helpers.createTargetQuickPick(x, i, me.getValues())); if (fileQuickPicks.length > 1) { vscode.window.showQuickPick(fileQuickPicks, { placeHolder: i18.t('pull.workspace.selectSource'), }).then((item) => { if (item) { pull(item.target); } }); } else { // auto select pull(fileQuickPicks[0].target); } } else { // we have explicit defined targets here if (1 === targetsOfPackage.length) { pull(targetsOfPackage[0]); // pull the one and only } else { // create a virtual "batch" target // for the underlying "real" targets let virtualPkgName: string; if (packageName) { virtualPkgName = i18.t('pull.workspace.virtualTargetNameWithPackage', packageName); } else { virtualPkgName = i18.t('pull.workspace.virtualTargetName'); } let batchTarget: any = { type: 'batch', name: virtualPkgName, targets: targetsOfPackage.map(x => x.name), }; pull(batchTarget); } } }; if (packageQuickPicks.length > 1) { vscode.window.showQuickPick(packageQuickPicks, { placeHolder: i18.t('pull.workspace.selectPackage'), }).then((item) => { if (item) { selectTarget(item.package); } }); } else { // auto select selectTarget(packageQuickPicks[0].package); } } /** * Pulls files of the workspace from a target. * * @param {string[]} files The files to pull. * @param {deploy_contracts.DeployTarget} target The target from where to pull from. * * @returns {Promise<boolean>} The promise. */ protected pullWorkspaceFrom(files: string[], target: deploy_contracts.DeployTarget): Promise<boolean> { let me = this; let nameOfTarget = deploy_helpers.normalizeString(target.name); if (files) { files = files.filter(f => !me.isFileIgnored(f)); } return new Promise<boolean>((resolve, reject) => { let hasCancelled = false; let completed = (err?: any) => { delete me._WORKSPACE_IN_PROGRESS[nameOfTarget]; if (err) { reject(err); } else { resolve(hasCancelled); } }; me.onCancelling(() => hasCancelled = true); let startPulling = () => { try { let type = deploy_helpers.parseTargetType(target.type); let matchIngPlugins = me.pluginsWithContextes.filter(x => { return !type || (x.plugin.__type === type && deploy_helpers.toBooleanSafe(x.plugin.canPull) && x.plugin.pullWorkspace); }); if (matchIngPlugins.length > 0) { let pullNextPlugin: () => void; pullNextPlugin = () => { if (matchIngPlugins.length < 1) { completed(); return; } if (hasCancelled) { completed(); return; } let cancelCommand: vscode.Disposable; let currentPluginWithContext = matchIngPlugins.shift(); let contextToUse = deploy_plugins.createPluginContext(currentPluginWithContext.context); let currentPlugin = currentPluginWithContext.plugin; let statusBarItem: vscode.StatusBarItem; let cleanUps = () => { deploy_helpers.tryDispose(cancelCommand); deploy_helpers.tryDispose(statusBarItem); deploy_helpers.tryDispose(contextToUse); }; try { statusBarItem = vscode.window.createStatusBarItem( vscode.StatusBarAlignment.Left, ); statusBarItem.color = '#ffffff'; statusBarItem.text = i18.t('pull.button.prepareText'); statusBarItem.tooltip = i18.t('pull.button.tooltip'); let cancelCommandName = 'extension.deploy.cancelPullWorkspace' + (nextCancelPullWorkspaceCommandId--); cancelCommand = vscode.commands.registerCommand(cancelCommandName, () => { if (hasCancelled) { return; } hasCancelled = true; try { contextToUse.emit(deploy_contracts.EVENT_CANCEL_PULL); } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.pullWorkspaceFrom().cancel', e)); } statusBarItem.text = i18.t('pull.button.cancelling'); statusBarItem.tooltip = i18.t('pull.button.cancelling'); }); statusBarItem.command = cancelCommandName; let failed: string[] = []; let succeeded: string[] = []; let showResult = (err?: any) => { try { cleanUps(); let targetExpr = deploy_helpers.toStringSafe(target.name).trim(); if (err) { if (targetExpr) { vscode.window.showErrorMessage(i18.t('pull.workspace.failedWithTarget', targetExpr, err)); } else { vscode.window.showErrorMessage(i18.t('pull.workspace.failed', err)); } } else { if (failed.length > 0) { if (succeeded.length < 1) { if (targetExpr) { vscode.window.showErrorMessage(i18.t('pull.workspace.allFailedWithTarget', targetExpr, err)); } else { vscode.window.showErrorMessage(i18.t('pull.workspace.allFailed', err)); } } else { let allCount = succeeded.length + failed.length; if (targetExpr) { vscode.window.showErrorMessage(i18.t('pull.workspace.someFailedWithTarget', failed.length, allCount , targetExpr)); } else { vscode.window.showErrorMessage(i18.t('pull.workspace.someFailed', failed.length, allCount)); } } } else { let allCount = succeeded.length; if (allCount > 0) { if (deploy_helpers.toBooleanSafe(me.config.showPopupOnSuccess, true)) { if (targetExpr) { vscode.window.showInformationMessage(i18.t('pull.workspace.allSucceededWithTarget', allCount , targetExpr)); } else { vscode.window.showInformationMessage(i18.t('pull.workspace.allSucceeded', allCount)); } } } else { if (targetExpr) { vscode.window.showWarningMessage(i18.t('pull.workspace.nothingPulledWithTarget', targetExpr)); } else { vscode.window.showWarningMessage(i18.t('pull.workspace.nothingPulled')); } } } } let resultMsg: string; if (err || failed.length > 0) { if (hasCancelled) { resultMsg = i18.t('pull.canceledWithErrors'); } else { resultMsg = i18.t('pull.finishedWithErrors'); } } else { if (hasCancelled) { resultMsg = i18.t('pull.canceled'); } else { resultMsg = i18.t('pull.finished2'); } } if (resultMsg) { me.outputChannel.appendLine(resultMsg); } } finally { completed(err); } }; statusBarItem.show(); currentPlugin.pullWorkspace(files, target, { context: contextToUse, onBeforeDeployFile: (sender, e) => { let relativePath = deploy_helpers.toRelativePath(e.file); if (false === relativePath) { relativePath = e.file; } let statusMsg: string; let destination = deploy_helpers.toStringSafe(e.destination); if (destination) { statusMsg = i18.t('pull.workspace.statusWithDestination', relativePath, destination); } else { statusMsg = i18.t('pull.workspace.status', relativePath); } statusBarItem.text = i18.t('pull.button.text'); statusBarItem.tooltip = statusMsg + ` (${i18.t('pull.workspace.clickToCancel')})`; me.outputChannel.append(statusMsg); }, onCompleted: (sender, e) => { hasCancelled = hasCancelled || e.canceled; showResult(e.error); }, onFileCompleted: (sender, e) => { if (e.error) { me.outputChannel.appendLine(i18.t('failed', e.error)); failed.push(e.file); } else { me.outputChannel.appendLine(i18.t('ok')); succeeded.push(e.file); } } }); } catch (e) { cleanUps(); vscode.window.showErrorMessage(i18.t('pull.workspace.failed', e)); } }; pullNextPlugin(); } else { if (type) { vscode.window.showWarningMessage(i18.t('pull.noPluginsForType', type)); } else { vscode.window.showWarningMessage(i18.t('pull.noPlugins')); } completed(); } } catch (e) { completed(e); } }; if (deploy_helpers.isNullOrUndefined(me._WORKSPACE_IN_PROGRESS[nameOfTarget])) { me._WORKSPACE_IN_PROGRESS[nameOfTarget] = { files: files, target: target, type: 'pull', }; startPulling(); } else { // there is currently something that is in progress for the target // [BUTTON] yes let yesBtn: deploy_contracts.PopupButton = new deploy_objects.SimplePopupButton(); yesBtn.action = () => { startPulling(); }; yesBtn.title = i18.t('yes'); vscode.window .showWarningMessage(i18.t('pull.workspace.alreadyStarted', target.name), yesBtn) .then((item) => { if (!item || !item.action) { return; } item.action(); }); } }); } /** * Does a "quick deploy". */ public quickDeploy() { let me = this; try { let cfg = this.config; let packagesToDeploy: deploy_contracts.DeployPackage[] = []; if (cfg.button) { let normalizeString = (val: any): string => { return deploy_helpers.toStringSafe(val) .toLowerCase().trim(); }; let packageNames = deploy_helpers.asArray(cfg.button.packages) .map(x => normalizeString(x)) .filter(x => '' !== x); let knownPackages = this.getPackages(); packageNames.forEach(pn => { let found = false; for (let i = 0; i < knownPackages.length; i++) { let kp = knownPackages[i]; if (normalizeString(kp.name) === pn) { found = true; packagesToDeploy.push(kp); } } if (!found) { vscode.window.showWarningMessage(i18.t('packages.notFound', pn)); } }); } let hasCancelled = false; let completed = (err?: any) => { let cfg = me.config; if (cfg.button) { if (deploy_helpers.toBooleanSafe(cfg.button.enabled)) { me._QUICK_DEPLOY_STATUS_ITEM.show(); } } if (err) { vscode.window.showErrorMessage(i18.t('quickDeploy.failed', err)); } }; me.onCancelling(() => hasCancelled = true); if (packagesToDeploy.length < 1) { vscode.window.showWarningMessage(i18.t('packages.nothingToDeploy')); } else { me._QUICK_DEPLOY_STATUS_ITEM.hide(); if (deploy_helpers.toBooleanSafe(me.config.openOutputOnDeploy, true)) { me.outputChannel.show(); } let deployNextPackage: () => void; deployNextPackage = () => { if (packagesToDeploy.length < 1) { completed(); return; } if (hasCancelled) { completed(); return; } let currentPackage = packagesToDeploy.shift(); try { let files = deploy_helpers.getFilesOfPackage(currentPackage, me.useGitIgnoreStylePatternsInFilter(currentPackage)); let targets = me.getTargetsFromPackage(currentPackage); let deployNextTarget: () => void; deployNextTarget = () => { if (targets.length < 1) { deployNextPackage(); return; } if (hasCancelled) { completed(); return; } let currentTarget = targets.shift(); try { me.beforeDeploy(files, currentTarget).then(() => { // update package files files = deploy_helpers.getFilesOfPackage(currentPackage, me.useGitIgnoreStylePatternsInFilter(currentPackage)); me.deployWorkspaceTo(files, currentTarget).then(() => { deployNextTarget(); }).catch((err) => { completed(err); }); }).catch((err) => { completed(err); }); } catch (e) { completed(e); } }; deployNextTarget(); } catch (e) { completed(e); } }; deployNextPackage(); } } catch (e) { vscode.window.showErrorMessage(i18.t('quickDeploy.failed', e)); } } /** * Registers the global events. */ protected registerGlobalEvents() { let me = this; deploy_globals.EVENTS.on(deploy_contracts.EVENT_WORKSPACE_CHANGED, () => { me.reloadConfiguration(); }); // deploy.deployOnChange.* deploy_globals.EVENTS.on(deploy_contracts.EVENT_DEPLOYONCHANGE_DISABLE, function() { me._isDeployOnChangeEnabled = false; }); deploy_globals.EVENTS.on(deploy_contracts.EVENT_DEPLOYONCHANGE_ENABLE, function() { me._isDeployOnChangeEnabled = true; }); deploy_globals.EVENTS.on(deploy_contracts.EVENT_DEPLOYONCHANGE_TOGGLE, function() { me._isDeployOnChangeEnabled = !me._isDeployOnChangeEnabled; }); // deploy.deployOnSave.* deploy_globals.EVENTS.on(deploy_contracts.EVENT_DEPLOYONSAVE_DISABLE, function() { me._isDeployOnSaveEnabled = false; }); deploy_globals.EVENTS.on(deploy_contracts.EVENT_DEPLOYONSAVE_ENABLE, function() { me._isDeployOnSaveEnabled = true; }); deploy_globals.EVENTS.on(deploy_contracts.EVENT_DEPLOYONSAVE_TOGGLE, function() { me._isDeployOnSaveEnabled = !me._isDeployOnSaveEnabled; }); // deploy.syncWhenOpen.* deploy_globals.EVENTS.on(deploy_contracts.EVENT_SYNCWHENOPEN_DISABLE, function() { me._isSyncWhenOpenEnabled = false; }); deploy_globals.EVENTS.on(deploy_contracts.EVENT_SYNCWHENOPEN_ENABLE, function() { me._isSyncWhenOpenEnabled = true; }); deploy_globals.EVENTS.on(deploy_contracts.EVENT_SYNCWHENOPEN_TOGGLE, function() { me._isSyncWhenOpenEnabled = !me._isSyncWhenOpenEnabled; }); // deploy.deployFiles deploy_globals.EVENTS.on(deploy_contracts.EVENT_DEPLOYFILES, function(files: string | string[], targets: deploy_contracts.DeployTargetList, sym?: symbol) { let filesToDeploy: string[]; let targetObjects: deploy_contracts.DeployTarget[]; let completed = (err?: any) => { try { let args: deploy_contracts.DeployFilesEventArguments = { error: err, files: filesToDeploy, targets: targetObjects, symbol: sym, }; if (args.error) { deploy_globals.EVENTS.emit(deploy_contracts.EVENT_DEPLOYFILES_ERROR, args); } else { deploy_globals.EVENTS.emit(deploy_contracts.EVENT_DEPLOYFILES_SUCCESS, args); } deploy_globals.EVENTS.emit(deploy_contracts.EVENT_DEPLOYFILES_COMPLETE, args); } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.registerGlobalEvents()', e)); } }; try { let allKnownTargets = me.getTargets(); // convert to 'DeployTarget' objects targetObjects = deploy_helpers.asArray<string | deploy_contracts.DeployTarget>(targets).map(x => { let t: deploy_contracts.DeployTarget; if (x) { if ('object' === typeof x) { t = x; } else { let targetName = deploy_helpers.normalizeString(x); if (!deploy_helpers.isEmptyString(targetName)) { t = { name: targetName, }; // default "dummy" // try find known target for (let i = 0; i < allKnownTargets.length; i++) { let kt = allKnownTargets[i]; if (deploy_helpers.normalizeString(kt.name) === targetName) { t = kt; // found break; } } } } } return t; }).filter(x => x); // collect file list filesToDeploy = deploy_helpers.asArray(files).map(x => { return deploy_helpers.toStringSafe(x); }).filter(x => !deploy_helpers.isEmptyString(x)) .map(x => { if (!Path.isAbsolute(x)) { x = Path.join(deploy_workspace.getRootPath(), x); } return Path.resolve(x); }); filesToDeploy = deploy_helpers.distinctArray(filesToDeploy); if (targetObjects.length > 0 && filesToDeploy.length > 0) { let batchTarget: any = { type: 'batch', name: i18.t('deploy.workspace.virtualTargetName'), targets: targetObjects.map(x => x.name), }; me.deployWorkspaceTo(filesToDeploy, batchTarget).then(() => { completed(); }).catch((err) => { completed(err); }); } else { completed(); } } catch (e) { completed(e); } }); } /** * Reloads the defined commands from the config. */ protected reloadCommands() { deploy_commands.reloadCommands .apply(this, arguments); } /** * Reloads configuration. */ public reloadConfiguration() { const ME = this; if (ME._isReloadingConfig) { return; } if (!ME.isActive) { ME._config = null; return; } ME._isReloadingConfig = true; const DOES_NOT_RELOAD_CONFIG_ANYMORE = (err?: any) => { ME._isReloadingConfig = false; if (err) { throw err; } }; try { const SETTINGS_FILE = ME.settingsFile; const LOADED_CFG: deploy_contracts.DeployConfiguration = vscode.workspace.getConfiguration('deploy', vscode.Uri.file(SETTINGS_FILE)) || <any>{}; const FINISHED = (err: any, cfg: deploy_contracts.DeployConfiguration) => { try { let showDefaultTemplateRepos = true; if (cfg.templates) { showDefaultTemplateRepos = deploy_helpers.toBooleanSafe(cfg.templates.showDefaults, true); } ME.displayNetworkInfo(); ME.showExtensionInfoPopups(); ME.clearOutputOrNot(); // deploy.config.reloaded deploy_globals.EVENTS.emit(deploy_contracts.EVENT_CONFIG_RELOADED, cfg); ME.executeStartupCommands(); ME.openFiles(); deploy_buttons.reloadPackageButtons .apply(ME, []); if (cfg.host) { if (deploy_helpers.toBooleanSafe(cfg.host.autoStart)) { // auto start host const AUTOSTART_COMPLETED = (err: any) => { if (err) { vscode.window.showErrorMessage(`[vs-deploy]: ${deploy_helpers.toStringSafe(err)}`); } }; try { const START_LISTENING = () => { try { ME.listen(); AUTOSTART_COMPLETED(null); } catch (e) { AUTOSTART_COMPLETED(e); } }; const CURRENT_HOST = ME._host; if (CURRENT_HOST) { CURRENT_HOST.stop().then(() => { ME._host = null; START_LISTENING(); }).catch((err) => { AUTOSTART_COMPLETED(err); }); } else { START_LISTENING(); } } catch (e) { AUTOSTART_COMPLETED(e); } } } const AFTER_GIT_PULL = (err: any) => { try { deploy_config.runBuildTask .apply(ME); if (showDefaultTemplateRepos) { // check official repo version deploy_templates.checkOfficialRepositoryVersions .apply(ME, []); } deploy_switch.reloadButtons.apply(ME, []); deploy_switch.printSwitchStates.apply(ME, []); } finally { DOES_NOT_RELOAD_CONFIG_ANYMORE(); } }; deploy_config.runGitPull.apply(ME).then(() => { AFTER_GIT_PULL(null); }).catch((err) => { AFTER_GIT_PULL(err); }); } catch (e) { DOES_NOT_RELOAD_CONFIG_ANYMORE(e); } }; const NEXT = (cfg: deploy_contracts.DeployConfiguration) => { ME._config = cfg; try { deploy_switch.reloadTargetStates .apply(ME, []); try { ME._QUICK_DEPLOY_STATUS_ITEM.hide(); if (cfg.button) { if (deploy_helpers.toBooleanSafe(cfg.button.enabled)) { ME._QUICK_DEPLOY_STATUS_ITEM.show(); } } if (deploy_helpers.toBooleanSafe(cfg.openOutputOnStartup)) { ME.outputChannel.show(); } } catch (e) { ME.log(`[ERROR :: vs-deploy] Deploy.reloadConfiguration(3): ${deploy_helpers.toStringSafe(e)}`); } try { const TIME_TO_WAIT_BEFORE_ACTIVATE_DEPLOY_ON_CHANGE = parseInt( deploy_helpers.toStringSafe(cfg.timeToWaitBeforeActivateDeployOnChange).trim() ); if (!isNaN(TIME_TO_WAIT_BEFORE_ACTIVATE_DEPLOY_ON_CHANGE)) { // deactivate 'deploy on change' // for a while ME._isDeployOnChangeFreezed = true; ME._deployOnChangeFreezer = setTimeout(() => { ME._isDeployOnChangeFreezed = false; }, TIME_TO_WAIT_BEFORE_ACTIVATE_DEPLOY_ON_CHANGE); } } catch (e) { ME._isDeployOnChangeFreezed = false; } deploy_values.reloadAdditionalValues .apply(ME, []); ME.reloadEnvironmentVars(); ME.reloadEvents(); ME.reloadPlugins(); ME.reloadCommands(); deploy_operations.resetOperations(); ME.startExternalExtensions().then(() => { FINISHED(null, cfg); }).catch((err) => { FINISHED(err, cfg); }); } catch (e) { DOES_NOT_RELOAD_CONFIG_ANYMORE(e); } }; const APPLY_CONFIG = (cfg: deploy_contracts.DeployConfiguration) => { try { deploy_helpers.tryClearTimeout(ME._deployOnChangeFreezer); ME._lastConfigUpdate = Moment(); ME._allTargets = deploy_helpers.asArray(cfg.targets) .filter(x => x) .map((x, i) => { let clonedTarget = deploy_helpers.cloneObject(x); clonedTarget.__id = i; return clonedTarget; }); ME._globalScriptOperationState = {}; ME._htmlDocs = []; ME._isDeployOnChangeFreezed = false; ME._scriptOperationStates = {}; ME._targetCache = new deploy_objects.DeployTargetCache(); deploy_values.resetScriptStates(); ME._QUICK_DEPLOY_STATUS_ITEM.text = 'Quick deploy!'; ME._QUICK_DEPLOY_STATUS_ITEM.tooltip = 'Start a quick deploy...'; i18.init(cfg.language).then(() => { if (cfg.button) { let txt = deploy_helpers.toStringSafe(cfg.button.text); txt = ME.replaceWithValues(txt).trim(); if ('' === txt) { txt = i18.t('quickDeploy.caption'); } ME._QUICK_DEPLOY_STATUS_ITEM.text = txt; } ME._QUICK_DEPLOY_STATUS_ITEM.tooltip = i18.t('quickDeploy.start'); NEXT(cfg); }).catch((err) => { ME.log(`[ERROR :: vs-deploy] Deploy.reloadConfiguration(1): ${deploy_helpers.toStringSafe(err)}`); NEXT(cfg); }); } catch (e) { DOES_NOT_RELOAD_CONFIG_ANYMORE(e); } } deploy_config.mergeConfig(LOADED_CFG).then((cfg) => { APPLY_CONFIG(cfg); }).catch((err) => { ME.log(`[ERROR :: vs-deploy] Deploy.reloadConfiguration(2): ${deploy_helpers.toStringSafe(err)}`); APPLY_CONFIG(LOADED_CFG); }); } catch (e) { DOES_NOT_RELOAD_CONFIG_ANYMORE(e); } } /** * Reloads the list of variables for the current process. */ protected reloadEnvironmentVars() { let me = this; try { let oev = this._oldEnvVars; // restore old values... if (oev) { oev.forEach(x => { process[x.name] = x.value; }); } oev = null; let cfg = this.config; if (cfg.env) { let noPlaceholdersForTheseVars = cfg.env.noPlaceholdersForTheseVars; if (false !== noPlaceholdersForTheseVars && true !== noPlaceholdersForTheseVars) { noPlaceholdersForTheseVars = deploy_helpers.asArray(<string | string[]>cfg.env.noPlaceholdersForTheseVars) .map(x => deploy_helpers.toStringSafe(x).trim()) .filter(x => '' !== x); } if (cfg.env.vars) { // now set additional variables // for this process oev = []; for (let p in cfg.env.vars) { let name = deploy_helpers.toStringSafe(p).trim(); let oldValue: EnvVarEntry = { name: name, value: cfg.env.vars[p], }; let value = deploy_helpers.toStringSafe(oldValue.value); let usePlaceholders = true; if (Array.isArray(noPlaceholdersForTheseVars)) { usePlaceholders = noPlaceholdersForTheseVars.indexOf(name) < 0; } else { usePlaceholders = !deploy_helpers.toBooleanSafe(noPlaceholdersForTheseVars); } if (usePlaceholders) { value = me.replaceWithValues(value); // use placeholders } if ('' === value) { value = undefined; } process.env[name] = value; oev.push(oldValue); } } } this._oldEnvVars = oev; } catch (e) { me.log(i18.t('errors.withCategory', `Deployer.reloadEnvironmentVars()`, e)); } } /** * Reloads the global events defined in the config file. */ protected reloadEvents() { let me = this; let myName = me.name; // unregister old events while (me._EVENTS.length > 0) { let ev = me._EVENTS.shift(); try { deploy_globals.EVENTS.removeListener(ev.name, ev.listener); } catch (e) { me.log(i18.t('errors.withCategory', `Deployer.reloadEvents()`, e)); } } let allEvents = deploy_helpers.asArray(this.config.events).filter(x => x); // isFor allEvents = allEvents.filter(p => { let validHosts = deploy_helpers.asArray(p.isFor) .map(x => deploy_helpers.toStringSafe(x).toLowerCase().trim()) .filter(x => x); if (validHosts.length < 1) { return true; } return validHosts.indexOf(myName) > -1; }); // platforms allEvents = deploy_helpers.filterPlatformItems(allEvents); // if allEvents = deploy_helpers.filterConditionalItems(allEvents); // sort allEvents = allEvents.sort((x, y) => { return deploy_helpers.compareValuesBy(x, y, t => deploy_helpers.getSortValue(t, () => myName)); }); let globalEventState = {}; allEvents.forEach((e, idx) => { let eventState = deploy_helpers.cloneObject(e.state); let entry: EventEntry; entry = { event: e, index: undefined, name: deploy_helpers.toStringSafe(e.name), listener: function() { let eventCompleted = (err: any, exitCode?: number) => { if (err) { me.log(i18.t('errors.withCategory', `Deployer.reloadEvents(${entry.name}#${idx}.2)`, err)); } else { exitCode = parseInt(deploy_helpers.toStringSafe(exitCode).trim()); if (isNaN(exitCode)) { exitCode = 0; } if (0 !== exitCode) { me.log(i18.t('errors.withCategory', `Deployer.reloadEvents(${entry.name}#${idx}.3)`, new Error(`Exit code: ${exitCode}`))); } } }; try { // path to script let moduleScript = deploy_helpers.toStringSafe(e.script); moduleScript = me.replaceWithValues(moduleScript); if (!Path.isAbsolute(moduleScript)) { moduleScript = Path.join(deploy_workspace.getRootPath(), moduleScript); } moduleScript = Path.resolve(moduleScript); let scriptModule = deploy_helpers.loadModule<deploy_contracts.EventModule>(moduleScript); if (scriptModule) { if (scriptModule.raiseEvent) { let args: deploy_contracts.EventModuleExecutorArguments = { arguments: arguments, emitGlobal: function() { return deploy_globals.EVENTS.emit .apply(null, arguments); }, globals: me.getGlobals(), globalState: undefined, name: e.name, openHtml: function() { return me.openHtml .apply(me, arguments); }, options: deploy_helpers.cloneObject(e.options), remove: function() { if (isNaN(entry.index)) { return false; } deploy_globals.EVENTS.removeListener(entry.name, entry.listener); me._EVENTS.splice(entry.index, 1); entry.index = null; return true; }, replaceWithValues: (val) => { return me.replaceWithValues(val); }, require: (id) => { return require(deploy_helpers.toStringSafe(id)); }, state: undefined, }; // args.globalState Object.defineProperty(args, 'globalState', { enumerable: true, get: () => { return globalEventState; }, }); // args.state Object.defineProperty(args, 'state', { enumerable: true, get: () => { return eventState; }, set: (newValue) => { eventState = newValue; } }); Promise.resolve(<any>scriptModule.raiseEvent(args)).then((ec) => { eventCompleted(null, ec); }).catch((err) => { eventCompleted(err); }); } } } catch (e) { eventCompleted(e); } }, }; if (deploy_helpers.isEmptyString(entry.name)) { entry.name = 'vscdEvent' + idx; } let registrator: (event: string | Symbol, listener: Function) => Events.EventEmitter; let registratorThisArgs: any = deploy_globals.EVENTS; if (deploy_helpers.toBooleanSafe(e.once)) { registrator = deploy_globals.EVENTS.once; } else { registrator = deploy_globals.EVENTS.on; } try { if (registrator) { registrator.apply(registratorThisArgs, [ entry.name, entry.listener ]); entry.index = me._EVENTS.push(entry) - 1; } } catch (e) { me.log(i18.t('errors.withCategory', `Deployer.reloadEvents(${entry.name}#${idx}.1)`, e)); } }); } /** * Reloads plugins. * * @param {boolean} [forceDisplay] Force displaying loaded plugins or not. */ public reloadPlugins(forceDisplay = false) { let me = this; let oldPlugins = me._plugins; try { let loadedPlugins: deploy_contracts.DeployPluginWithContext[] = []; let pluginDir = Path.join(__dirname, './plugins'); if (FS.existsSync(pluginDir)) { if (FS.lstatSync(pluginDir).isDirectory()) { // modules from plugin directory let moduleFiles = FS.readdirSync(pluginDir).filter(x => { try { if ('.' !== x && '..' !== x) { let fullPath = Path.join(pluginDir, x); if (FS.lstatSync(fullPath).isFile()) { if (fullPath.length >= 3) { return '.js' === fullPath.substring(fullPath.length - 3); } } } } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.reloadPlugins(1)', e)); } return false; }).filter(x => x) .map(x => Path.join(pluginDir, x)); // additional modules defined? if (me.config.modules) { let additionalModuleFiles = deploy_helpers.asArray(me.config.modules) .map(x => deploy_helpers.toStringSafe(x)) .filter(x => x) .map(x => { if (!Path.isAbsolute(x)) { x = Path.join(deploy_workspace.getRootPath(), x); } return x; }); moduleFiles = moduleFiles.concat(additionalModuleFiles); } moduleFiles = deploy_helpers.distinctArray(moduleFiles.map(x => Path.resolve(x))); // remove existing plugins if (oldPlugins) { oldPlugins.filter(x => x).forEach(x => { if (x.plugin.dispose) { deploy_helpers.tryDispose(<any>x.plugin); } deploy_helpers.tryDispose(x.context); }); } moduleFiles.forEach(x => { delete require.cache[x]; }); let createPluginContext: () => deploy_contracts.DeployContext = () => { let ctx = deploy_plugins.createPluginContext(); ctx.config = () => me.config; ctx.deployFiles = (files, target) => { let sym = Symbol("deploy.deploy.Deployer.reloadPlugins.createPluginContext"); return deploy_helpers.deployFiles(files, target, sym); }; ctx.emitGlobal = function() { return me.emitGlobal .apply(me, arguments); }; ctx.filterConditionalItems = (items) => me.filterConditionalItems(items); ctx.globals = () => me.getGlobals(); ctx.isActive = () => me.isActive; ctx.log = function(msg) { me.log(msg); return this; }; ctx.openHtml = function() { return me.openHtml .apply(me, arguments); }; ctx.outputChannel = () => me.outputChannel; ctx.packageFile = () => me.packageFile; ctx.packages = () => me.getPackages(); ctx.replaceWithValues = (v) => me.replaceWithValues(v); ctx.targetCache = () => me._targetCache; ctx.targets = () => me.getTargets(); ctx.values = () => me.getValues(); return ctx; }; let nextPluginIndex = -1; moduleFiles.forEach(x => { try { let pluginModule: deploy_contracts.DeployPluginModule = require(x); if (pluginModule) { if (pluginModule.createPlugin) { let ctx = createPluginContext(); let newPlugin = pluginModule.createPlugin(ctx); if (newPlugin) { let pluginIndex = ++nextPluginIndex; ctx.plugins = function() { return loadedPlugins.filter(x => x.plugin.__index !== pluginIndex) .map(x => x.plugin); }; newPlugin.__file = deploy_helpers.parseTargetType(Path.basename(x)); newPlugin.__filePath = x; newPlugin.__index = pluginIndex; newPlugin.__type = deploy_helpers.parseTargetType(Path.basename(x, '.js')); loadedPlugins.push({ context: ctx, plugin: newPlugin, }); } } } } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.reloadPlugins(2)', e)); } }); } } this._plugins = loadedPlugins; if (forceDisplay || deploy_helpers.toBooleanSafe(this.config.displayLoadedPlugins, true)) { // display loaded plugins if (loadedPlugins.length > 0) { loadedPlugins.forEach(x => { try { me.outputChannel.append(`- ${x.plugin.__file}`); } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.reloadPlugins(3)', e)); } me.outputChannel.appendLine(''); }); this.outputChannel.appendLine(''); if (loadedPlugins.length !== 1) { this.outputChannel.appendLine(i18.t('__plugins.reload.loaded.more', loadedPlugins.length)); } else { this.outputChannel.appendLine(i18.t('__plugins.reload.loaded.one')); } } else { this.outputChannel.appendLine(i18.t('__plugins.reload.loaded.none')); } this.outputChannel.appendLine(''); this.showVSCodeDeployReloadedInfo(); } } catch (e) { vscode.window.showErrorMessage(i18.t('__plugins.reload.failed', e)); } finally { oldPlugins = null; } } private showVSCodeDeployReloadedInfo() { try { this.outputChannel.appendLine(''); this.outputChannel.appendLine('New, recoded version of that extension (vscode-deploy-reloaded) has been released:'); this.outputChannel.appendLine('- https://github.com/mkloubert/vscode-deploy-reloaded'); this.outputChannel.appendLine(''); this.outputChannel.appendLine(''); } catch (e) { console.log(e, 'deploy.Deployer.showVSCodeDeployReloadedInfo()'); } } /** * Handles a value as string and replaces placeholders. * * @param {any} val The value to parse. * * @return {string} The parsed value. */ public replaceWithValues(val: any): string { return deploy_values.replaceWithValues(this.getValues(), val); } /** * Gets the underlying settings file. */ public get settingsFile() { return Path.resolve( Path.join( deploy_workspace.getRootPath(), './.vscode/settings.json' ) ); } /** * Set ups the file system watcher. */ protected setupFileSystemWatcher() { let me = this; let createWatcher = () => { me._fileSystemWatcher = null; let newWatcher: vscode.FileSystemWatcher; try { newWatcher = vscode.workspace.createFileSystemWatcher('**', false, false, true); newWatcher.onDidChange((e) => { me.onFileChange(e, 'change'); }, newWatcher); newWatcher.onDidCreate((e) => { me.onFileChange(e, 'create'); }, newWatcher); me._fileSystemWatcher = newWatcher; } catch (e) { deploy_helpers.tryDispose(newWatcher); me.log(i18.t('errors.withCategory', 'Deployer.setupFileSystemWatcher(2)', e)); } }; try { if (deploy_helpers.tryDispose(me._fileSystemWatcher)) { createWatcher(); } } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.setupFileSystemWatcher(1)', e)); } } /** * Shows info popups of / for this extension. */ protected showExtensionInfoPopups() { this.showNewVersionPopup(); } /** * Shows the popup of for new version. */ protected showNewVersionPopup() { let me = this; const KEY_LAST_KNOWN_VERSION = 'vsdLastKnownVersion'; if (this._PACKAGE_FILE) { let currentVersion = this._PACKAGE_FILE.version; if (currentVersion) { // update last known version let updateCurrentVersion = false; try { let lastKnownVersion: any = this._CONTEXT.globalState.get(KEY_LAST_KNOWN_VERSION, false); if (lastKnownVersion != currentVersion) { if (!deploy_helpers.toBooleanSafe(this.config.disableNewVersionPopups)) { // tell the user that it runs on a new version updateCurrentVersion = true; // [BUTTON] show change log let changeLogBtn: deploy_contracts.PopupButton = new deploy_objects.SimplePopupButton(); changeLogBtn.action = () => { deploy_helpers.open(deploy_urls.CHANGELOG); }; changeLogBtn.title = i18.t('popups.newVersion.showChangeLog'); vscode.window .showInformationMessage(i18.t('popups.newVersion.message', currentVersion), changeLogBtn) .then((item) => { if (!item || !item.action) { return; } try { item.action(); } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.showExtensionInfoPopups(3)', e)); } }); } } } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.showExtensionInfoPopups(2)', e)); } if (updateCurrentVersion) { // update last known version try { this._CONTEXT.globalState.update(KEY_LAST_KNOWN_VERSION, currentVersion); } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.showExtensionInfoPopups(1)', e)); } } } } } /** * Shows the 'after deploy' status bar item based of the current settings. * * @param {string} text The text for the item. * @param {string[]} files The list of all files. * @param {string[]} succeeded The list of succeeded files. * @param {string[]} failed The list of failed files. */ protected showStatusBarItemAfterDeployment(text: string, files: string[], succeeded: string[], failed: string[]) { let me = this; try { let now = Moment().format('HH:mm:ss'); let icon = ''; let color = '#ffffff'; let suffix = ''; let fileCount = files.length; let failedCount = failed.length; let succeededCount = succeeded.length; if (succeededCount < 1) { if (failedCount < 1) { failedCount = fileCount; } } if (files.length > 0) { if (1 === files.length) { suffix = ` (${Path.basename(files[0])})`; } else { if (failedCount > 0) { suffix = ` (${failedCount} / {fileCount})`; } else { suffix = ` (${fileCount})`; } } } if (failedCount >= succeededCount) { // all failed icon = '$(flame) '; color = me.getNextAfterDeploymentButtonColor('e'); } else { if (failedCount < 1) { icon = '$(rocket) '; color = me.getNextAfterDeploymentButtonColor('s'); } else { // at least one failed icon = '$(alert) '; color = me.getNextAfterDeploymentButtonColor('w'); } } me._AFTER_DEPLOYMENT_STATUS_ITEM.color = color; me._AFTER_DEPLOYMENT_STATUS_ITEM.text = i18.t('deploy.after.button.text', text, now, icon, suffix); me._AFTER_DEPLOYMENT_STATUS_ITEM.tooltip = i18.t('deploy.after.button.tooltip'); let cfg = me.config; if (deploy_helpers.toBooleanSafe(cfg.showDeployResultInStatusBar)) { me._AFTER_DEPLOYMENT_STATUS_ITEM.show(); let hideAfter = parseFloat(deploy_helpers.toStringSafe(cfg.hideDeployResultInStatusBarAfter).trim()); if (!isNaN(hideAfter)) { hideAfter = Math.round(hideAfter); if (hideAfter >= 0) { let thisTimer: NodeJS.Timer; me._lastAfterDeploymentButtonDisapearTimeout = thisTimer = setTimeout(() => { if (thisTimer === me._lastAfterDeploymentButtonDisapearTimeout) { me._AFTER_DEPLOYMENT_STATUS_ITEM.hide(); } }, hideAfter * 1000); } } } else { me.hideAfterDeploymentStatusBarItem(); } } catch (e) { me.log(i18.t('errors.withCategory', 'Deployer.showStatusBarItemAfterDeployment()', e)); } } /** * Shows a warning message if extension is currently active or not. * * @param ifActive */ public async showWarningIfNotActive(ifActive?: () => any): Promise<boolean> { const ME = this; if (ME.isActive) { if (ifActive) { await Promise.resolve( ifActive() ); } return true; } else { vscode.window.showWarningMessage( "[vs-deploy] The extension is currently not active! Please open a workspace, before you continue." ).then(() => {}, (err) => { ME.log(i18.t('errors.withCategory', 'Deployer.showWarningIfNotActive()', err)); }); return false; } } /** * Starts external extensions. * * @return {Promise<any>} The promise. */ protected startExternalExtensions(): Promise<any> { let me = this; let cfg = me.config; let startApi = deploy_helpers.toBooleanSafe(cfg.startApi); let startCronJobs = deploy_helpers.toBooleanSafe(cfg.startCronJobs); return new Promise<any>((resolve, reject) => { let wf = Workflows.create(); let showExtensionInstallWindow = function(extensionName: string) { let author = 'mkloubert'; let itemName = author + '.' + extensionName; let installBtn: deploy_contracts.PopupButton = new deploy_objects.SimplePopupButton(); installBtn.action = () => { deploy_helpers.open(`https://marketplace.visualstudio.com/items?itemName=${encodeURIComponent(itemName)}`).then(() => { }).catch((err) => { me.log(i18.t('errors.withCategory', `Deployer.startExternalExtensions().showExtensionInstallWindow(${itemName}).1`, err)); }); }; installBtn.title = i18.t('install'); vscode.window.showWarningMessage(i18.t('extensions.notInstalled', extensionName), installBtn) .then((item) => { if (item) { item.action(); } }, (err) => { me.log(i18.t('errors.withCategory', `Deployer.startExternalExtensions().showExtensionInstallWindow(${itemName}).2`, err)); }); }; // prepare things wf.next((ctx) => { ctx.value = {}; ctx.value.loadCommands = startApi || startCronJobs; }); // collect all required data // before we start wf.next((ctx) => { return new Promise<any>((res, rej) => { try { if (ctx.value.loadCommands) { ctx.value.commands = []; // list of available VSCode commands vscode.commands.getCommands(false).then((commands) => { if (commands) { commands.forEach(x => ctx.value.commands.push(x)); } res(); }, () => { res(); }); } else { res(); // nothing to do here } } catch (e) { rej(e); } }); }); // vs-rest-api if (startApi) { wf.next((ctx) => { let commands: string[] = ctx.value.commands; return new Promise<any>((res, rej) => { try { let cmdName = 'extension.restApi.startHost'; if (commands.indexOf(cmdName) > -1) { vscode.commands.executeCommand(cmdName).then(() => { res(); }, (err) => { vscode.window.showErrorMessage('[vs-deploy.vs-rest-api] ' + deploy_helpers.toStringSafe(err)); res(); }); } else { // extension NOT installed showExtensionInstallWindow('vs-rest-api'); res(); } } catch (e) { rej(e); } }); }); } // vs-cron if (startCronJobs) { wf.next((ctx) => { let commands: string[] = ctx.value.commands; return new Promise<any>((res, rej) => { try { let cmdName = 'extension.cronJons.restartRunningJobs'; if (commands.indexOf(cmdName) > -1) { vscode.commands.executeCommand(cmdName).then(() => { res(); }, (err) => { vscode.window.showErrorMessage('[vs-deploy.vs-cron] ' + deploy_helpers.toStringSafe(err)); res(); }); } else { // extension NOT installed showExtensionInstallWindow('vs-cron'); res(); } } catch (e) { rej(e); } }); }); } wf.start().then(() => { resolve(); }).catch((err) => { reject(err); }); }); } /** * Gets the start time of the extension. */ public get startTime(): Moment.Moment { return this._startTime; } /** * Gets if a file filter should also use patterns for directories * like in .gitignore files or not. * * @param {deploy_contracts.FileFilter} filter The filter to check. * @param {boolean} [defaultValue] The default value. * * @return {boolean} Also use directory patterns or not. */ public useGitIgnoreStylePatternsInFilter(filter: deploy_contracts.FileFilter, defaultValue = true): boolean { let cfg = this.config; // global setting let useGitIgnoreStylePatterns = deploy_helpers.toBooleanSafe(cfg.useGitIgnoreStylePatterns, deploy_helpers.toBooleanSafe(defaultValue)); if (filter) { // now check filter useGitIgnoreStylePatterns = deploy_helpers.toBooleanSafe(filter.useGitIgnoreStylePatterns, useGitIgnoreStylePatterns); } return useGitIgnoreStylePatterns; } }
the_stack
import * as coreClient from "@azure/core-client"; /** Result of the request to list REST API operations. It contains a list of operations and a URL nextLink to get the next set of results. */ export interface OperationListResult { /** List of operations supported by the resource provider. */ value?: Operation[]; /** * URL to get the next set of operation list results if there are any. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** REST API operation */ export interface Operation { /** Operation name: {provider}/{resource}/{operation} */ name?: string; /** The object that describes the operation. */ display?: OperationDisplay; } /** The object that describes the operation. */ export interface OperationDisplay { /** Friendly name of the resource provider */ provider?: string; /** Operation type: read, write, delete, listKeys/action, etc. */ operation?: string; /** Resource type on which the operation is performed. */ resource?: string; /** Friendly name of the operation */ description?: string; } /** Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). */ export interface ErrorResponse { /** The error object. */ error?: ErrorDetail; } /** The error detail. */ export interface ErrorDetail { /** * The error code. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly code?: string; /** * The error message. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; /** * The error target. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly target?: string; /** * The error details. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly details?: ErrorDetail[]; /** * The error additional info. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly additionalInfo?: ErrorAdditionalInfo[]; } /** The resource management error additional info. */ export interface ErrorAdditionalInfo { /** * The additional info type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** * The additional info. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly info?: Record<string, unknown>; } /** Parameters body to pass for resource name availability check. */ export interface CheckNameAvailabilityParameters { /** Resource name. */ name: string; /** Resource type. The only legal value of this property for checking redis cache name availability is 'Microsoft.Cache/redis'. */ type: string; } /** The response of listUpgradeNotifications. */ export interface NotificationListResponse { /** List of all notifications. */ value?: UpgradeNotification[]; /** * Link for next set of notifications. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Properties of upgrade notification. */ export interface UpgradeNotification { /** * Name of upgrade notification. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * Timestamp when upgrade notification occurred. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly timestamp?: Date; /** * Details about this upgrade notification * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly upsellNotification?: { [propertyName: string]: string }; } /** Parameters supplied to the Create Redis operation. */ export interface RedisCreateParameters { /** A list of availability zones denoting where the resource needs to come from. */ zones?: string[]; /** The geo-location where the resource lives */ location: string; /** Resource tags. */ tags?: { [propertyName: string]: string }; /** All Redis Settings. Few possible keys: rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta,maxmemory-policy,notify-keyspace-events,maxmemory-samples,slowlog-log-slower-than,slowlog-max-len,list-max-ziplist-entries,list-max-ziplist-value,hash-max-ziplist-entries,hash-max-ziplist-value,set-max-intset-entries,zset-max-ziplist-entries,zset-max-ziplist-value etc. */ redisConfiguration?: RedisCommonPropertiesRedisConfiguration; /** Redis version. Only major version will be used in PUT/PATCH request with current valid values: (4, 6) */ redisVersion?: string; /** Specifies whether the non-ssl Redis server port (6379) is enabled. */ enableNonSslPort?: boolean; /** The number of replicas to be created per primary. */ replicasPerMaster?: number; /** The number of replicas to be created per primary. */ replicasPerPrimary?: number; /** A dictionary of tenant settings */ tenantSettings?: { [propertyName: string]: string }; /** The number of shards to be created on a Premium Cluster Cache. */ shardCount?: number; /** Optional: requires clients to use a specified TLS version (or higher) to connect (e,g, '1.0', '1.1', '1.2') */ minimumTlsVersion?: TlsVersion; /** Whether or not public endpoint access is allowed for this cache. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private endpoints are the exclusive access method. Default value is 'Enabled' */ publicNetworkAccess?: PublicNetworkAccess; /** The SKU of the Redis cache to deploy. */ sku: Sku; /** The full resource ID of a subnet in a virtual network to deploy the Redis cache in. Example format: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1 */ subnetId?: string; /** Static IP address. Optionally, may be specified when deploying a Redis cache inside an existing Azure Virtual Network; auto assigned by default. */ staticIP?: string; } /** SKU parameters supplied to the create Redis operation. */ export interface Sku { /** The type of Redis cache to deploy. Valid values: (Basic, Standard, Premium) */ name: SkuName; /** The SKU family to use. Valid values: (C, P). (C = Basic/Standard, P = Premium). */ family: SkuFamily; /** The size of the Redis cache to deploy. Valid values: for C (Basic/Standard) family (0, 1, 2, 3, 4, 5, 6), for P (Premium) family (1, 2, 3, 4). */ capacity: number; } /** Create/Update/Get common properties of the redis cache. */ export interface RedisCommonProperties { /** All Redis Settings. Few possible keys: rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta,maxmemory-policy,notify-keyspace-events,maxmemory-samples,slowlog-log-slower-than,slowlog-max-len,list-max-ziplist-entries,list-max-ziplist-value,hash-max-ziplist-entries,hash-max-ziplist-value,set-max-intset-entries,zset-max-ziplist-entries,zset-max-ziplist-value etc. */ redisConfiguration?: RedisCommonPropertiesRedisConfiguration; /** Redis version. Only major version will be used in PUT/PATCH request with current valid values: (4, 6) */ redisVersion?: string; /** Specifies whether the non-ssl Redis server port (6379) is enabled. */ enableNonSslPort?: boolean; /** The number of replicas to be created per primary. */ replicasPerMaster?: number; /** The number of replicas to be created per primary. */ replicasPerPrimary?: number; /** A dictionary of tenant settings */ tenantSettings?: { [propertyName: string]: string }; /** The number of shards to be created on a Premium Cluster Cache. */ shardCount?: number; /** Optional: requires clients to use a specified TLS version (or higher) to connect (e,g, '1.0', '1.1', '1.2') */ minimumTlsVersion?: TlsVersion; /** Whether or not public endpoint access is allowed for this cache. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private endpoints are the exclusive access method. Default value is 'Enabled' */ publicNetworkAccess?: PublicNetworkAccess; } /** All Redis Settings. Few possible keys: rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta,maxmemory-policy,notify-keyspace-events,maxmemory-samples,slowlog-log-slower-than,slowlog-max-len,list-max-ziplist-entries,list-max-ziplist-value,hash-max-ziplist-entries,hash-max-ziplist-value,set-max-intset-entries,zset-max-ziplist-entries,zset-max-ziplist-value etc. */ export interface RedisCommonPropertiesRedisConfiguration { /** Describes unknown properties. The value of an unknown property can be of "any" type. */ [property: string]: any; /** Specifies whether the rdb backup is enabled */ rdbBackupEnabled?: string; /** Specifies the frequency for creating rdb backup */ rdbBackupFrequency?: string; /** Specifies the maximum number of snapshots for rdb backup */ rdbBackupMaxSnapshotCount?: string; /** The storage account connection string for storing rdb file */ rdbStorageConnectionString?: string; /** First storage account connection string */ aofStorageConnectionString0?: string; /** Second storage account connection string */ aofStorageConnectionString1?: string; /** Value in megabytes reserved for fragmentation per shard */ maxfragmentationmemoryReserved?: string; /** The eviction strategy used when your data won't fit within its memory limit. */ maxmemoryPolicy?: string; /** Value in megabytes reserved for non-cache usage per shard e.g. failover. */ maxmemoryReserved?: string; /** Value in megabytes reserved for non-cache usage per shard e.g. failover. */ maxmemoryDelta?: string; /** * The max clients config * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly maxclients?: string; } /** Redis cache access keys. */ export interface RedisAccessKeys { /** * The current primary key that clients can use to authenticate with Redis cache. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly primaryKey?: string; /** * The current secondary key that clients can use to authenticate with Redis cache. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly secondaryKey?: string; } /** Linked server Id */ export interface RedisLinkedServer { /** * Linked server Id. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; } /** Details of single instance of redis. */ export interface RedisInstanceDetails { /** * Redis instance SSL port. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly sslPort?: number; /** * If enableNonSslPort is true, provides Redis instance Non-SSL port. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nonSslPort?: number; /** * If the Cache uses availability zones, specifies availability zone where this instance is located. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly zone?: string; /** * If clustering is enabled, the Shard ID of Redis Instance * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly shardId?: number; /** * Specifies whether the instance is a primary node. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly isMaster?: boolean; /** * Specifies whether the instance is a primary node. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly isPrimary?: boolean; } /** The Private Endpoint resource. */ export interface PrivateEndpoint { /** * The ARM identifier for Private Endpoint * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; } /** A collection of information about the state of the connection between service consumer and provider. */ export interface PrivateLinkServiceConnectionState { /** Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. */ status?: PrivateEndpointServiceConnectionStatus; /** The reason for approval/rejection of the connection. */ description?: string; /** A message indicating if changes on the service provider require any updates on the consumer. */ actionsRequired?: string; } /** Common fields that are returned in the response for all Azure Resource Manager resources */ export interface Resource { /** * Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The name of the resource * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; } /** Parameters supplied to the Update Redis operation. */ export interface RedisUpdateParameters { /** Resource tags. */ tags?: { [propertyName: string]: string }; /** All Redis Settings. Few possible keys: rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta,maxmemory-policy,notify-keyspace-events,maxmemory-samples,slowlog-log-slower-than,slowlog-max-len,list-max-ziplist-entries,list-max-ziplist-value,hash-max-ziplist-entries,hash-max-ziplist-value,set-max-intset-entries,zset-max-ziplist-entries,zset-max-ziplist-value etc. */ redisConfiguration?: RedisCommonPropertiesRedisConfiguration; /** Redis version. Only major version will be used in PUT/PATCH request with current valid values: (4, 6) */ redisVersion?: string; /** Specifies whether the non-ssl Redis server port (6379) is enabled. */ enableNonSslPort?: boolean; /** The number of replicas to be created per primary. */ replicasPerMaster?: number; /** The number of replicas to be created per primary. */ replicasPerPrimary?: number; /** A dictionary of tenant settings */ tenantSettings?: { [propertyName: string]: string }; /** The number of shards to be created on a Premium Cluster Cache. */ shardCount?: number; /** Optional: requires clients to use a specified TLS version (or higher) to connect (e,g, '1.0', '1.1', '1.2') */ minimumTlsVersion?: TlsVersion; /** Whether or not public endpoint access is allowed for this cache. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private endpoints are the exclusive access method. Default value is 'Enabled' */ publicNetworkAccess?: PublicNetworkAccess; /** The SKU of the Redis cache to deploy. */ sku?: Sku; } /** The response of list Redis operation. */ export interface RedisListResult { /** List of Redis cache instances. */ value?: RedisResource[]; /** * Link for next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Specifies which Redis access keys to reset. */ export interface RedisRegenerateKeyParameters { /** The Redis access key to regenerate. */ keyType: RedisKeyType; } /** Specifies which Redis node(s) to reboot. */ export interface RedisRebootParameters { /** Which Redis node(s) to reboot. Depending on this value data loss is possible. */ rebootType?: RebootType; /** If clustering is enabled, the ID of the shard to be rebooted. */ shardId?: number; /** A list of redis instances to reboot, specified by per-instance SSL ports or non-SSL ports. */ ports?: number[]; } /** Response to force reboot for Redis cache. */ export interface RedisForceRebootResponse { /** * Status message * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; } /** Parameters for Redis import operation. */ export interface ImportRDBParameters { /** File format. */ format?: string; /** files to import. */ files: string[]; } /** Parameters for Redis export operation. */ export interface ExportRDBParameters { /** File format. */ format?: string; /** Prefix to use for exported files. */ prefix: string; /** Container name to export to. */ container: string; } /** The response of list firewall rules Redis operation. */ export interface RedisFirewallRuleListResult { /** Results of the list firewall rules operation. */ value?: RedisFirewallRule[]; /** * Link for next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** The response of list patch schedules Redis operation. */ export interface RedisPatchScheduleListResult { /** Results of the list patch schedules operation. */ value?: RedisPatchSchedule[]; /** * Link for next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Patch schedule entry for a Premium Redis Cache. */ export interface ScheduleEntry { /** Day of the week when a cache can be patched. */ dayOfWeek: DayOfWeek; /** Start hour after which cache patching can start. */ startHourUtc: number; /** ISO8601 timespan specifying how much time cache patching can take. */ maintenanceWindow?: string; } /** Parameter required for creating a linked server to redis cache. */ export interface RedisLinkedServerCreateParameters { /** Fully qualified resourceId of the linked redis cache. */ linkedRedisCacheId: string; /** Location of the linked redis cache. */ linkedRedisCacheLocation: string; /** Role of the linked server. */ serverRole: ReplicationRole; } /** Create properties for a linked server */ export interface RedisLinkedServerCreateProperties { /** Fully qualified resourceId of the linked redis cache. */ linkedRedisCacheId: string; /** Location of the linked redis cache. */ linkedRedisCacheLocation: string; /** Role of the linked server. */ serverRole: ReplicationRole; } /** List of linked servers (with properties) of a Redis cache. */ export interface RedisLinkedServerWithPropertiesList { /** List of linked servers (with properties) of a Redis cache. */ value?: RedisLinkedServerWithProperties[]; /** * Link for next set. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** List of private endpoint connection associated with the specified storage account */ export interface PrivateEndpointConnectionListResult { /** Array of private endpoint connections */ value?: PrivateEndpointConnection[]; } /** A list of private link resources */ export interface PrivateLinkResourceListResult { /** Array of private link resources */ value?: PrivateLinkResource[]; } /** Properties supplied to Create Redis operation. */ export type RedisCreateProperties = RedisCommonProperties & { /** The SKU of the Redis cache to deploy. */ sku: Sku; /** The full resource ID of a subnet in a virtual network to deploy the Redis cache in. Example format: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1 */ subnetId?: string; /** Static IP address. Optionally, may be specified when deploying a Redis cache inside an existing Azure Virtual Network; auto assigned by default. */ staticIP?: string; }; /** Patchable properties of the redis cache. */ export type RedisUpdateProperties = RedisCommonProperties & { /** The SKU of the Redis cache to deploy. */ sku?: Sku; }; /** The Private Endpoint Connection resource. */ export type PrivateEndpointConnection = Resource & { /** The resource of private end point. */ privateEndpoint?: PrivateEndpoint; /** A collection of information about the state of the connection between service consumer and provider. */ privateLinkServiceConnectionState?: PrivateLinkServiceConnectionState; /** * The provisioning state of the private endpoint connection resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: PrivateEndpointConnectionProvisioningState; }; /** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */ export type TrackedResource = Resource & { /** Resource tags. */ tags?: { [propertyName: string]: string }; /** The geo-location where the resource lives */ location: string; }; /** The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location */ export type ProxyResource = Resource & {}; /** A private link resource */ export type PrivateLinkResource = Resource & { /** * The private link resource group id. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly groupId?: string; /** * The private link resource required member names. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly requiredMembers?: string[]; /** The private link resource Private link DNS zone name. */ requiredZoneNames?: string[]; }; /** Properties of a linked server to be returned in get/put response */ export type RedisLinkedServerProperties = RedisLinkedServerCreateProperties & { /** * Terminal state of the link between primary and secondary redis cache. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; }; /** Properties of the redis cache. */ export type RedisProperties = RedisCreateProperties & { /** * Redis instance provisioning status. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: ProvisioningState; /** * Redis host name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly hostName?: string; /** * Redis non-SSL port. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly port?: number; /** * Redis SSL port. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly sslPort?: number; /** * The keys of the Redis cache - not set if this object is not the response to Create or Update redis cache * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly accessKeys?: RedisAccessKeys; /** * List of the linked servers associated with the cache * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly linkedServers?: RedisLinkedServer[]; /** * List of the Redis instances associated with the cache * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly instances?: RedisInstanceDetails[]; /** * List of private endpoint connection associated with the specified redis cache * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly privateEndpointConnections?: PrivateEndpointConnection[]; }; /** A single Redis item in List or Get Operation. */ export type RedisResource = TrackedResource & { /** A list of availability zones denoting where the resource needs to come from. */ zones?: string[]; /** All Redis Settings. Few possible keys: rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta,maxmemory-policy,notify-keyspace-events,maxmemory-samples,slowlog-log-slower-than,slowlog-max-len,list-max-ziplist-entries,list-max-ziplist-value,hash-max-ziplist-entries,hash-max-ziplist-value,set-max-intset-entries,zset-max-ziplist-entries,zset-max-ziplist-value etc. */ redisConfiguration?: RedisCommonPropertiesRedisConfiguration; /** Redis version. Only major version will be used in PUT/PATCH request with current valid values: (4, 6) */ redisVersion?: string; /** Specifies whether the non-ssl Redis server port (6379) is enabled. */ enableNonSslPort?: boolean; /** The number of replicas to be created per primary. */ replicasPerMaster?: number; /** The number of replicas to be created per primary. */ replicasPerPrimary?: number; /** A dictionary of tenant settings */ tenantSettings?: { [propertyName: string]: string }; /** The number of shards to be created on a Premium Cluster Cache. */ shardCount?: number; /** Optional: requires clients to use a specified TLS version (or higher) to connect (e,g, '1.0', '1.1', '1.2') */ minimumTlsVersion?: TlsVersion; /** Whether or not public endpoint access is allowed for this cache. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private endpoints are the exclusive access method. Default value is 'Enabled' */ publicNetworkAccess?: PublicNetworkAccess; /** The SKU of the Redis cache to deploy. */ sku: Sku; /** The full resource ID of a subnet in a virtual network to deploy the Redis cache in. Example format: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1 */ subnetId?: string; /** Static IP address. Optionally, may be specified when deploying a Redis cache inside an existing Azure Virtual Network; auto assigned by default. */ staticIP?: string; /** * Redis instance provisioning status. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: ProvisioningState; /** * Redis host name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly hostName?: string; /** * Redis non-SSL port. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly port?: number; /** * Redis SSL port. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly sslPort?: number; /** * The keys of the Redis cache - not set if this object is not the response to Create or Update redis cache * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly accessKeys?: RedisAccessKeys; /** * List of the linked servers associated with the cache * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly linkedServers?: RedisLinkedServer[]; /** * List of the Redis instances associated with the cache * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly instances?: RedisInstanceDetails[]; /** * List of private endpoint connection associated with the specified redis cache * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly privateEndpointConnections?: PrivateEndpointConnection[]; }; /** A firewall rule on a redis cache has a name, and describes a contiguous range of IP addresses permitted to connect */ export type RedisFirewallRule = ProxyResource & { /** lowest IP address included in the range */ startIP: string; /** highest IP address included in the range */ endIP: string; }; /** Response to put/get patch schedules for Redis cache. */ export type RedisPatchSchedule = ProxyResource & { /** List of patch schedules for a Redis cache. */ scheduleEntries: ScheduleEntry[]; }; /** Response to put/get linked server (with properties) for Redis cache. */ export type RedisLinkedServerWithProperties = ProxyResource & { /** Fully qualified resourceId of the linked redis cache. */ linkedRedisCacheId?: string; /** Location of the linked redis cache. */ linkedRedisCacheLocation?: string; /** Role of the linked server. */ serverRole?: ReplicationRole; /** * Terminal state of the link between primary and secondary redis cache. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; }; /** Parameters required for creating a firewall rule on redis cache. (Note, you can just use the FirewallRule type instead now.) */ export type RedisFirewallRuleCreateParameters = RedisFirewallRule & {}; /** Known values of {@link SkuName} that the service accepts. */ export enum KnownSkuName { Basic = "Basic", Standard = "Standard", Premium = "Premium" } /** * Defines values for SkuName. \ * {@link KnownSkuName} can be used interchangeably with SkuName, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Basic** \ * **Standard** \ * **Premium** */ export type SkuName = string; /** Known values of {@link SkuFamily} that the service accepts. */ export enum KnownSkuFamily { C = "C", P = "P" } /** * Defines values for SkuFamily. \ * {@link KnownSkuFamily} can be used interchangeably with SkuFamily, * this enum contains the known values that the service supports. * ### Known values supported by the service * **C** \ * **P** */ export type SkuFamily = string; /** Known values of {@link TlsVersion} that the service accepts. */ export enum KnownTlsVersion { One0 = "1.0", One1 = "1.1", One2 = "1.2" } /** * Defines values for TlsVersion. \ * {@link KnownTlsVersion} can be used interchangeably with TlsVersion, * this enum contains the known values that the service supports. * ### Known values supported by the service * **1.0** \ * **1.1** \ * **1.2** */ export type TlsVersion = string; /** Known values of {@link PublicNetworkAccess} that the service accepts. */ export enum KnownPublicNetworkAccess { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for PublicNetworkAccess. \ * {@link KnownPublicNetworkAccess} can be used interchangeably with PublicNetworkAccess, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type PublicNetworkAccess = string; /** Known values of {@link ProvisioningState} that the service accepts. */ export enum KnownProvisioningState { Creating = "Creating", Deleting = "Deleting", Disabled = "Disabled", Failed = "Failed", Linking = "Linking", Provisioning = "Provisioning", RecoveringScaleFailure = "RecoveringScaleFailure", Scaling = "Scaling", Succeeded = "Succeeded", Unlinking = "Unlinking", Unprovisioning = "Unprovisioning", Updating = "Updating" } /** * Defines values for ProvisioningState. \ * {@link KnownProvisioningState} can be used interchangeably with ProvisioningState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Creating** \ * **Deleting** \ * **Disabled** \ * **Failed** \ * **Linking** \ * **Provisioning** \ * **RecoveringScaleFailure** \ * **Scaling** \ * **Succeeded** \ * **Unlinking** \ * **Unprovisioning** \ * **Updating** */ export type ProvisioningState = string; /** Known values of {@link PrivateEndpointServiceConnectionStatus} that the service accepts. */ export enum KnownPrivateEndpointServiceConnectionStatus { Pending = "Pending", Approved = "Approved", Rejected = "Rejected" } /** * Defines values for PrivateEndpointServiceConnectionStatus. \ * {@link KnownPrivateEndpointServiceConnectionStatus} can be used interchangeably with PrivateEndpointServiceConnectionStatus, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Pending** \ * **Approved** \ * **Rejected** */ export type PrivateEndpointServiceConnectionStatus = string; /** Known values of {@link PrivateEndpointConnectionProvisioningState} that the service accepts. */ export enum KnownPrivateEndpointConnectionProvisioningState { Succeeded = "Succeeded", Creating = "Creating", Deleting = "Deleting", Failed = "Failed" } /** * Defines values for PrivateEndpointConnectionProvisioningState. \ * {@link KnownPrivateEndpointConnectionProvisioningState} can be used interchangeably with PrivateEndpointConnectionProvisioningState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Succeeded** \ * **Creating** \ * **Deleting** \ * **Failed** */ export type PrivateEndpointConnectionProvisioningState = string; /** Known values of {@link RebootType} that the service accepts. */ export enum KnownRebootType { PrimaryNode = "PrimaryNode", SecondaryNode = "SecondaryNode", AllNodes = "AllNodes" } /** * Defines values for RebootType. \ * {@link KnownRebootType} can be used interchangeably with RebootType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **PrimaryNode** \ * **SecondaryNode** \ * **AllNodes** */ export type RebootType = string; /** Known values of {@link DefaultName} that the service accepts. */ export enum KnownDefaultName { Default = "default" } /** * Defines values for DefaultName. \ * {@link KnownDefaultName} can be used interchangeably with DefaultName, * this enum contains the known values that the service supports. * ### Known values supported by the service * **default** */ export type DefaultName = string; /** Defines values for RedisKeyType. */ export type RedisKeyType = "Primary" | "Secondary"; /** Defines values for DayOfWeek. */ export type DayOfWeek = | "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" | "Saturday" | "Sunday" | "Everyday" | "Weekend"; /** Defines values for ReplicationRole. */ export type ReplicationRole = "Primary" | "Secondary"; /** Optional parameters. */ export interface OperationsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult; /** Optional parameters. */ export interface OperationsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult; /** Optional parameters. */ export interface RedisCheckNameAvailabilityOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface RedisListUpgradeNotificationsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listUpgradeNotifications operation. */ export type RedisListUpgradeNotificationsResponse = NotificationListResponse; /** Optional parameters. */ export interface RedisCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type RedisCreateResponse = RedisResource; /** Optional parameters. */ export interface RedisUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the update operation. */ export type RedisUpdateResponse = RedisResource; /** Optional parameters. */ export interface RedisDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface RedisGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type RedisGetResponse = RedisResource; /** Optional parameters. */ export interface RedisListByResourceGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroup operation. */ export type RedisListByResourceGroupResponse = RedisListResult; /** Optional parameters. */ export interface RedisListBySubscriptionOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listBySubscription operation. */ export type RedisListBySubscriptionResponse = RedisListResult; /** Optional parameters. */ export interface RedisListKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listKeys operation. */ export type RedisListKeysResponse = RedisAccessKeys; /** Optional parameters. */ export interface RedisRegenerateKeyOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the regenerateKey operation. */ export type RedisRegenerateKeyResponse = RedisAccessKeys; /** Optional parameters. */ export interface RedisForceRebootOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the forceReboot operation. */ export type RedisForceRebootOperationResponse = RedisForceRebootResponse; /** Optional parameters. */ export interface RedisImportDataOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface RedisExportDataOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface RedisListUpgradeNotificationsNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listUpgradeNotificationsNext operation. */ export type RedisListUpgradeNotificationsNextResponse = NotificationListResponse; /** Optional parameters. */ export interface RedisListByResourceGroupNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroupNext operation. */ export type RedisListByResourceGroupNextResponse = RedisListResult; /** Optional parameters. */ export interface RedisListBySubscriptionNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listBySubscriptionNext operation. */ export type RedisListBySubscriptionNextResponse = RedisListResult; /** Optional parameters. */ export interface FirewallRulesListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type FirewallRulesListResponse = RedisFirewallRuleListResult; /** Optional parameters. */ export interface FirewallRulesCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type FirewallRulesCreateOrUpdateResponse = RedisFirewallRule; /** Optional parameters. */ export interface FirewallRulesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type FirewallRulesGetResponse = RedisFirewallRule; /** Optional parameters. */ export interface FirewallRulesDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface FirewallRulesListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type FirewallRulesListNextResponse = RedisFirewallRuleListResult; /** Optional parameters. */ export interface PatchSchedulesListByRedisResourceOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByRedisResource operation. */ export type PatchSchedulesListByRedisResourceResponse = RedisPatchScheduleListResult; /** Optional parameters. */ export interface PatchSchedulesCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type PatchSchedulesCreateOrUpdateResponse = RedisPatchSchedule; /** Optional parameters. */ export interface PatchSchedulesDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface PatchSchedulesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type PatchSchedulesGetResponse = RedisPatchSchedule; /** Optional parameters. */ export interface PatchSchedulesListByRedisResourceNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByRedisResourceNext operation. */ export type PatchSchedulesListByRedisResourceNextResponse = RedisPatchScheduleListResult; /** Optional parameters. */ export interface LinkedServerCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type LinkedServerCreateResponse = RedisLinkedServerWithProperties; /** Optional parameters. */ export interface LinkedServerDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface LinkedServerGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type LinkedServerGetResponse = RedisLinkedServerWithProperties; /** Optional parameters. */ export interface LinkedServerListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type LinkedServerListResponse = RedisLinkedServerWithPropertiesList; /** Optional parameters. */ export interface LinkedServerListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type LinkedServerListNextResponse = RedisLinkedServerWithPropertiesList; /** Optional parameters. */ export interface PrivateEndpointConnectionsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type PrivateEndpointConnectionsListResponse = PrivateEndpointConnectionListResult; /** Optional parameters. */ export interface PrivateEndpointConnectionsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type PrivateEndpointConnectionsGetResponse = PrivateEndpointConnection; /** Optional parameters. */ export interface PrivateEndpointConnectionsPutOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the put operation. */ export type PrivateEndpointConnectionsPutResponse = PrivateEndpointConnection; /** Optional parameters. */ export interface PrivateEndpointConnectionsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface PrivateLinkResourcesListByRedisCacheOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByRedisCache operation. */ export type PrivateLinkResourcesListByRedisCacheResponse = PrivateLinkResourceListResult; /** Optional parameters. */ export interface RedisManagementClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import * as ABIDecoder from "abi-decoder"; import * as _ from "lodash"; import * as Web3 from "web3"; // Utils import { BigNumber } from "../../../../utils/bignumber"; import * as Units from "../../../../utils/units"; import { Web3Utils } from "../../../../utils/web3_utils"; // Adapters import { SimpleInterestLoanAdapter } from "../../../../src/adapters"; // Apis import { AdaptersAPI, ContractsAPI, LogsAPI, OrderAPI, SignerAPI } from "../../../../src/apis/"; // Types import { DebtOrderData } from "../../../../src/types"; // Scenarios import { RepaymentRouterErrorScenario } from "../scenarios"; // Wrappers import { DebtKernelContract, DummyTokenContract, RepaymentRouterContract, SimpleInterestTermsContractContract, TokenRegistryContract, TokenTransferProxyContract, } from "../../../../src/wrappers"; import { ACCOUNTS } from "../../../accounts"; const CONTRACT_OWNER = ACCOUNTS[0].address; const CREDITOR = ACCOUNTS[1].address; const DEBTOR = ACCOUNTS[2].address; const REPAYMENT_AMOUNT = Units.ether(10); const PRINCIPAL_AMOUNT = REPAYMENT_AMOUNT.mul(3); const TX_DEFAULTS = { from: CONTRACT_OWNER, gas: 400000 }; export class GetScenarioRunner { private web3Utils: Web3Utils; private web3: Web3; // Contracts private debtKernel: DebtKernelContract; private repaymentRouter: RepaymentRouterContract; private principalToken: DummyTokenContract; private termsContract: SimpleInterestTermsContractContract; private tokenTransferProxy: TokenTransferProxyContract; private tokenRegistry: TokenRegistryContract; // APIs private contractsAPI: ContractsAPI; private logsAPI: LogsAPI; private signerAPI: SignerAPI; private adaptersApi: AdaptersAPI; private orderAPI: OrderAPI; // Adapters private simpleInterestLoan: SimpleInterestLoanAdapter; private isConfigured: boolean = false; private currentSnapshotId: number; constructor(web3: Web3) { this.web3 = web3; this.web3Utils = new Web3Utils(web3); this.testGetLogsAfterRepaymentScenario = this.testGetLogsAfterRepaymentScenario.bind(this); this.saveSnapshotAsync = this.saveSnapshotAsync.bind(this); this.revertToSavedSnapshot = this.revertToSavedSnapshot.bind(this); this.testEventCount = this.testEventCount.bind(this); this.testIncludesExpectedFields = this.testIncludesExpectedFields.bind(this); this.testIsArray = this.testIsArray.bind(this); } public async configure() { // Prevent unnecessary configuration. if (this.isConfigured) { return; } // Construct all necessary dependencies. this.contractsAPI = new ContractsAPI(this.web3); this.logsAPI = new LogsAPI(this.web3, this.contractsAPI); this.signerAPI = new SignerAPI(this.web3, this.contractsAPI); this.adaptersApi = new AdaptersAPI(this.web3, this.contractsAPI); this.orderAPI = new OrderAPI(this.web3, this.contractsAPI, this.adaptersApi); const { debtKernel, repaymentRouter, tokenTransferProxy, } = await this.contractsAPI.loadDharmaContractsAsync(); const tokenRegistry = await this.contractsAPI.loadTokenRegistry(); const dummyREPAddress = await tokenRegistry.getTokenAddressBySymbol.callAsync("REP"); const principalToken = await DummyTokenContract.at(dummyREPAddress, this.web3, TX_DEFAULTS); const termsContract = await this.contractsAPI.loadSimpleInterestTermsContract(); this.debtKernel = debtKernel; this.repaymentRouter = repaymentRouter; this.principalToken = principalToken; this.termsContract = termsContract; this.tokenTransferProxy = tokenTransferProxy; this.tokenRegistry = tokenRegistry; this.simpleInterestLoan = new SimpleInterestLoanAdapter(this.web3, this.contractsAPI); // Mark instance as configured. this.isConfigured = true; } public testGetLogsAfterRepaymentScenario(scenario: RepaymentRouterErrorScenario) { let txHash: string; describe(scenario.description, () => { beforeEach(async () => { // Set up a valid repayment scenario. const principalToken = await this.generateTransferOfToken("REP"); const debtOrderData = await this.generateSignedDebtOrderDataWithToken("REP"); const issuanceHash = await this.orderAPI.getIssuanceHash(debtOrderData); await this.orderAPI.fillAsync(debtOrderData, { from: CREDITOR }); txHash = await this.repaymentRouter.repay.sendTransactionAsync( issuanceHash, REPAYMENT_AMOUNT, principalToken.address, { from: DEBTOR }, ); }); describe('and the arguments include "LogRepayment" as a string', async () => { it("returns an array", async () => { await this.testIsArray("LogRepayment", txHash); }); it("includes a single log matching the repayment", async () => { await this.testEventCount("LogRepayment", txHash, 1); }); it("the log includes all of the expected log fields", async () => { await this.testIncludesExpectedFields("LogRepayment", txHash); }); describe("and the arguments include limit of 0", async () => { it("returns 0 events", async () => { await this.testEventCount("LogRepayment", txHash, 0, { limit: 0 }); }); }); describe("and the arguments specify events between blocks 0 and 2", async () => { it("returns 0 events", async () => { await this.testEventCount("LogRepayment", txHash, 0, { fromBlock: 0, toBlock: 2, }); }); }); describe("and the arguments specify events between blocks 2 and 'latest'", async () => { it("returns 1 event", async () => { await this.testEventCount("LogRepayment", txHash, 1, { fromBlock: 2, toBlock: "latest", }); }); }); }); describe('and the arguments include "LogRepayment" as an array', async () => { it("includes a single log matching the repayment", async () => { await this.testEventCount(["LogRepayment"], txHash, 1); }); it("the log includes all of the expected log fields", async () => { await this.testIncludesExpectedFields(["LogRepayment"], txHash); }); describe("and the arguments include limit of 0", async () => { it("returns 0 events", async () => { await this.testEventCount(["LogRepayment"], txHash, 0, { limit: 0 }); }); }); describe("and the arguments specify events between blocks 0 and 2", async () => { it("returns 0 events", async () => { await this.testEventCount(["LogRepayment"], txHash, 0, { fromBlock: 0, toBlock: 2, }); }); }); describe("and the arguments specify events between blocks 2 and 'latest'", async () => { it("returns 1 event", async () => { await this.testEventCount(["LogRepayment"], txHash, 1, { fromBlock: 2, toBlock: "latest", }); }); }); }); describe("and the arguments include an array of different event types", async () => { it("includes a single log matching the repayment", async () => { await this.testEventCount(["LogRepayment", "Transfer"], txHash, 1); }); it("the log includes all of the expected log fields", async () => { await this.testIncludesExpectedFields(["LogRepayment", "Transfer"], txHash); }); describe("and the arguments include limit of 0", async () => { it("returns 0 events", async () => { await this.testEventCount(["LogRepayment", "Transfer"], txHash, 0, { limit: 0, }); }); }); }); }); } public async saveSnapshotAsync() { this.currentSnapshotId = await this.web3Utils.saveTestSnapshot(); } public async revertToSavedSnapshot() { await this.web3Utils.revertToSnapshot(this.currentSnapshotId); } private async testIsArray(eventName: string, txHash: string) { const matchingLogs = await this.filterLogs(eventName, txHash); expect(Array.isArray(matchingLogs)).toBe(true); } private async testIncludesExpectedFields(eventName: string | string[], txHash: string) { const matchingLogs = await this.filterLogs(eventName, txHash); const logKeys = Object.keys(matchingLogs[0]); expect(logKeys).toEqual([ "logIndex", "transactionIndex", "transactionHash", "blockHash", "blockNumber", "address", "type", "event", "args", ]); } private async testEventCount( eventName: string | string[], txHash: string, count: number, args?: object, ) { const matchingLogs = await this.filterLogs(eventName, txHash, args); expect(matchingLogs.length).toEqual(count); } private async filterLogs( eventName, txHash, args?: object, ): Promise<ABIDecoder.DecodedLogEntry[]> { const logs: ABIDecoder.DecodedLogEntry[] = await this.logsAPI.get(eventName, args); return _.filter(logs, (log) => log.transactionHash === txHash); } private async generateTransferOfToken(symbol: string): Promise<DummyTokenContract> { const tokenAddress = await this.tokenRegistry.getTokenAddressBySymbol.callAsync(symbol); const token = await DummyTokenContract.at(tokenAddress, this.web3, TX_DEFAULTS); // Grant creditor a balance of tokens await token.setBalance.sendTransactionAsync(CREDITOR, PRINCIPAL_AMOUNT, { from: CONTRACT_OWNER, }); // Grant debtor a balance of tokens await token.setBalance.sendTransactionAsync(DEBTOR, REPAYMENT_AMOUNT, { from: CONTRACT_OWNER, }); // Approve the token transfer proxy for a sufficient // amount of tokens for an order fill. await token.approve.sendTransactionAsync( this.tokenTransferProxy.address, PRINCIPAL_AMOUNT, { from: CREDITOR, }, ); await token.approve.sendTransactionAsync( this.tokenTransferProxy.address, REPAYMENT_AMOUNT.plus(1), { from: DEBTOR, }, ); return token; } private async generateSignedDebtOrderDataWithToken( tokenSymbol: string, ): Promise<DebtOrderData> { const debtOrderData = await this.simpleInterestLoan.toDebtOrder({ debtor: DEBTOR, creditor: CREDITOR, principalAmount: PRINCIPAL_AMOUNT, principalTokenSymbol: tokenSymbol, interestRate: new BigNumber(0.1), amortizationUnit: "months", termLength: new BigNumber(2), salt: new BigNumber(0), }); debtOrderData.debtorSignature = await this.signerAPI.asDebtor(debtOrderData, false); return debtOrderData; } }
the_stack
import * as _ from 'lodash'; import {AbstractComponent} from '@common/component/abstract.component'; import {CommonUtil} from '@common/util/common.util'; import {Datasource} from '@domain/datasource/datasource'; import {Widget} from '@domain/dashboard/widget/widget'; import {WidgetShowType} from '@domain/dashboard/dashboard.globalOptions'; import {Filter} from '@domain/workbook/configurations/filter/filter'; import {Dashboard, DashboardWidgetRelation, LayoutWidgetInfo} from '@domain/dashboard/dashboard'; import {FilterWidget, FilterWidgetConfiguration} from '@domain/dashboard/widget/filter-widget'; import {DashboardUtil} from './util/dashboard.util'; export class AbstractDashboardComponent extends AbstractComponent { /** * Convert spec to UI * @param {Dashboard} boardInfo * @return {Dashboard} */ public convertSpecToUI(boardInfo: Dashboard): Dashboard { // Change spec server to ui ( userDefinedFields -> customFields ) if (boardInfo.configuration['userDefinedFields']) { boardInfo.configuration.customFields = _.cloneDeep(CommonUtil.objectToArray(boardInfo.configuration['userDefinedFields'])); } if (boardInfo.dataSources) { // Filter ( dataSource ( id -> engineName ) ) const filters: Filter[] = DashboardUtil.getBoardFilters(boardInfo); if (filters && 0 < filters.length) { const uniqFilterKeyList: string[] = []; boardInfo.configuration.filters = filters.filter((filter: Filter) => { const uniqFilterKey: string = filter.dataSource + '_' + filter.field; if (-1 === uniqFilterKeyList.indexOf(uniqFilterKey)) { const filterDs: Datasource = boardInfo.dataSources.find(ds => ds.id === filter.dataSource); (filterDs) && (filter.dataSource = filterDs.engineName); if (this.isNullOrUndefined(filter.dataSource)) { const fieldDs: Datasource = boardInfo.dataSources.find(ds => ds.fields.some(item => item.name === filter.field)); (fieldDs) && (filter.dataSource = fieldDs.engineName); } uniqFilterKeyList.push(uniqFilterKey); return true; } else { return false; } }); } // Widget const widgets: Widget[] = boardInfo.widgets; if (widgets && 0 < widgets.length) { widgets.forEach((widget: Widget) => { if ('filter' === widget.type) { // FilterWidget : Filter ( dataSource ( id -> engineName ) ) const conf: FilterWidgetConfiguration = widget.configuration as FilterWidgetConfiguration; const filterDs: Datasource = boardInfo.dataSources.find(ds => ds.id === conf.filter.dataSource); (filterDs) && (conf.filter.dataSource = filterDs.engineName); if (this.isNullOrUndefined(conf.filter.dataSource)) { const fieldDs: Datasource = boardInfo.dataSources.find(ds => ds.fields.some(item => item.name === conf.filter.field)); (fieldDs) && (conf.filter.dataSource = fieldDs.engineName); } } }); } } return boardInfo; } // function - convertSpecToUI /** * 부모차트 목록 조회 */ public getParentFilter(filter: Filter, board: Dashboard): Filter[] { let prevFilter: Filter[] = []; const filterWidget: FilterWidget = DashboardUtil.getFilterWidgetByFilter(board, filter); if (board.configuration.filterRelations && filterWidget) { this._findWidgetRelation(filterWidget.id, board.configuration.filterRelations, [], (_target: DashboardWidgetRelation, hierarchy: string[]) => { if (0 < hierarchy.length) { prevFilter = hierarchy.map(item => { const conf: FilterWidgetConfiguration = (DashboardUtil.getWidget(board, item) as FilterWidget).configuration; return DashboardUtil.getBoardFilter(board, conf.filter.dataSource, conf.filter.field); }); } return true; }, board); } return prevFilter.filter(item => !!item); // prevFilter = prevFilter.filter(item => !!item); // if (isOnlyExistValue) { // return prevFilter.filter(item => (<InclusionFilter>item).valueList && 0 < (<InclusionFilter>item).valueList.length); // } else { // return prevFilter; // } } // function - getParentFilter /** * 위젯을 추가 및 Layout 내 위젯이 배치될 수 있도록 목록 등록 * @param {Dashboard} board * @param {Widget} widget * @param {boolean} isInLayout * @returns {Dashboard} * @protected */ protected _addWidget(board: Dashboard, widget: Widget, isInLayout: boolean = false): Dashboard { board.widgets.push(widget); const newWidget: LayoutWidgetInfo = new LayoutWidgetInfo(widget.id, widget.type); (isInLayout) && (newWidget.isInLayout = true); if (WidgetShowType.BY_WIDGET !== board.configuration.options.widget.showTitle) { newWidget.title = (WidgetShowType.ON === board.configuration.options.widget.showTitle); } (board.configuration.widgets) || (board.configuration.widgets = []); board.configuration.widgets.push(newWidget); if ('page' === widget.type) { (board.configuration.relations) || (board.configuration.relations = []); this._addWidgetRelation(widget.id, board.configuration.relations); } else if ('filter' === widget.type) { (board.configuration.filterRelations) || (board.configuration.filterRelations = []); this._addWidgetRelation(widget.id, board.configuration.filterRelations, board); } return board; } // function - addWidget /** * 위젯 삭제 * @param {Dashboard} board * @param {string} widgetId * @returns {Dashboard} * @protected */ protected _removeWidget(board: Dashboard, widgetId: string): Dashboard { const targetIdx: number = board.widgets.findIndex(item => item.id === widgetId); // remove widget relation if ('page' === board.widgets[targetIdx].type) { this._removeWidgetRelation(widgetId, board.configuration.relations); } else if ('filter' === board.widgets[targetIdx].type) { this._removeWidgetRelation(widgetId, board.configuration.filterRelations, board); } // remove widget board.widgets.splice(targetIdx, 1); // remove layout config const layoutTargetIdx: number = board.configuration.widgets.findIndex(item => item.ref === widgetId); board.configuration.widgets.splice(layoutTargetIdx, 1); return board; } // function - removeWidget /** * 위젯 연관관계 추가 * @param {string} widgetId * @param {DashboardWidgetRelation[]} items * @param {Dashboard} board * @protected */ protected _addWidgetRelation(widgetId: string, items: DashboardWidgetRelation[], board?: Dashboard) { (items) || (items = []); items.push(new DashboardWidgetRelation(widgetId)); (board) && (this._generateFilterRelationMap(board)); } // function - _addWidgetRelation /** * 연관 관계 삭제 * @param {string} widgetId * @param {DashboardWidgetRelation[]} items * @param {Dashboard} board * @protected */ protected _removeWidgetRelation(widgetId: string, items: DashboardWidgetRelation[], board?: Dashboard) { if (items) { this._findWidgetRelation(widgetId, items, [], (target: DashboardWidgetRelation, _hierarchy: string[], list: DashboardWidgetRelation[]) => { const delIdx: number = list.findIndex(item => item.ref === target.ref); if (-1 < delIdx) { list.splice(delIdx, 1); } (board) && (this._generateFilterRelationMap(board)); return true; } ); } } // function - _removeWidgetRelation /** * 연관 관계 최하단 여부 판단 * @param {string} widgetId * @param {DashboardWidgetRelation[]} items * @param {Dashboard} board * @private */ protected _isLeafWidgetRelation(widgetId: string, items: DashboardWidgetRelation[], board?: Dashboard): boolean { return this._findWidgetRelation(widgetId, items, [], (target: DashboardWidgetRelation) => { return !(target.children && 0 < target.children.length); }, board ); } // function - _isLeafWidgetRelation /** * 부모 위젯 아이디 탐색 * @param {string} widgetId * @param {DashboardWidgetRelation[]} relations * @returns {string} * @protected */ protected _findParentWidgetId(widgetId: string, relations: DashboardWidgetRelation[]): string { let parentId: string = ''; relations.some(item => { if (item.children) { if (-1 < item.children.findIndex(child => child.ref === widgetId)) { parentId = item.ref; return true; } else { parentId = this._findParentWidgetId(widgetId, item.children); return ('' !== parentId); } } else { return false; } }); return parentId; } // function - _findParentWidgetId /** * 하위 위젯 목록 조회 * @param {string} targetId * @param {DashboardWidgetRelation[]} items * @param {Function} callback * @param {Dashboard} board * @private */ protected _getAllChildWidgetRelation(targetId: string, items: DashboardWidgetRelation[], callback: HierarchyCallback, board: Dashboard) { const getChildItems = (relItems: DashboardWidgetRelation[], children: string[]) => { if (relItems && 0 < relItems.length) { return relItems.reduce((acc, item) => { acc.push(item.ref); if (item.children && 0 < item.children.length) { acc = getChildItems(item.children, acc); } return acc; }, children); } else { return children; } }; this._findWidgetRelation(targetId, items, [], (target: DashboardWidgetRelation, _hierarchy: string[]) => { (callback) && (callback(target, getChildItems(target.children, []))); return true; }, board ); } /** * 필터의 관계 Map을 생성한다. * @param board * @protected */ protected _generateFilterRelationMap(board: Dashboard) { const circulateItems = (items: DashboardWidgetRelation[], callback: (target: DashboardWidgetRelation) => void) => { if (items) { items.forEach(relItem => { (callback) && (callback(relItem)); (relItem.children) && (circulateItems(relItem.children, callback)); }); } }; (board.configuration.filterRelMap) || (board.configuration.filterRelMap = {}); circulateItems(board.configuration.filterRelations, (relItem: DashboardWidgetRelation) => { this._findWidgetRelation(relItem.ref, board.configuration.filterRelations, [], (target: DashboardWidgetRelation, hierarchy: string[]) => { const filterWidget: FilterWidget = DashboardUtil.getWidget(board, target.ref) as FilterWidget; if (filterWidget) { board.configuration.filterRelMap[target.ref] = { widgetId: target.ref, relItem: target, parents: hierarchy, dataSource: filterWidget.configuration.filter.dataSource, field: filterWidget.configuration.filter.field, type: filterWidget.configuration.filter.type }; } return true; } ); }) } // function - _generateFilterRelationMap /** * 위젯 연관관계 탐색 * @param {string} targetId * @param {DashboardWidgetRelation[]} items * @param {string[]} hierarchy * @param {Function} callback * @param {Dashboard} board * @protected */ protected _findWidgetRelation(targetId: string, items: DashboardWidgetRelation[], hierarchy: string[] = [], callback: HierarchyCallback, board?: Dashboard): boolean { if (board) { const relMapItem = board.configuration.filterRelMap[targetId]; if (relMapItem) { return callback(relMapItem.relItem, relMapItem.parents, items); } } else { return items.some((relItem: DashboardWidgetRelation) => { const newHierarchy = [].concat(hierarchy); if (targetId === relItem.ref) { return callback(relItem, newHierarchy, items); } else { if (relItem.children) { newHierarchy.push(relItem.ref); return this._findWidgetRelation(targetId, relItem.children, newHierarchy, callback); } else { return false; } } }); } } // function - _findWidgetRelation } type HierarchyCallback = (target: DashboardWidgetRelation, hierarchy: string[], item?: DashboardWidgetRelation[]) => boolean;
the_stack
import * as gax from 'google-gax'; import { Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall, } from 'google-gax'; import * as path from 'path'; import {Transform} from 'stream'; import {RequestType} from 'google-gax/build/src/apitypes'; import * as protos from '../../protos/protos'; /** * Client JSON configuration object, loaded from * `src/v3/notification_channel_service_client_config.json`. * This file defines retry strategy and timeouts for all API methods in this library. */ import * as gapicConfig from './notification_channel_service_client_config.json'; const version = require('../../../package.json').version; /** * The Notification Channel API provides access to configuration that * controls how messages related to incidents are sent. * @class * @memberof v3 */ export class NotificationChannelServiceClient { private _terminated = false; private _opts: ClientOptions; private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; descriptors: Descriptors = { page: {}, stream: {}, longrunning: {}, batching: {}, }; innerApiCalls: {[name: string]: Function}; pathTemplates: {[name: string]: gax.PathTemplate}; notificationChannelServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of NotificationChannelServiceClient. * * @param {object} [options] - The configuration object. * The options accepted by the constructor are described in detail * in [this document](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#creating-the-client-instance). * The common options are: * @param {object} [options.credentials] - Credentials object. * @param {string} [options.credentials.client_email] * @param {string} [options.credentials.private_key] * @param {string} [options.email] - Account email address. Required when * using a .pem or .p12 keyFilename. * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or * .p12 key downloaded from the Google Developers Console. If you provide * a path to a JSON file, the projectId option below is not necessary. * NOTE: .pem and .p12 require you to specify options.email as well. * @param {number} [options.port] - The port on which to connect to * the remote host. * @param {string} [options.projectId] - The project ID from the Google * Developer's Console, e.g. 'grape-spaceship-123'. We will also check * the environment variable GCLOUD_PROJECT for your project ID. If your * app is running in an environment which supports * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, * your project ID will be detected automatically. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. * Follows the structure of {@link gapicConfig}. * @param {boolean} [options.fallback] - Use HTTP fallback mode. * In fallback mode, a special browser-compatible transport implementation is used * instead of gRPC transport. In browser context (if the `window` object is defined) * the fallback mode is enabled automatically; set `options.fallback` to `false` * if you need to override this behavior. */ constructor(opts?: ClientOptions) { // Ensure that options include all the required fields. const staticMembers = this .constructor as typeof NotificationChannelServiceClient; const servicePath = opts?.servicePath || opts?.apiEndpoint || staticMembers.servicePath; const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== staticMembers.servicePath && !('scopes' in opts)) { opts['scopes'] = staticMembers.scopes; } // Choose either gRPC or proto-over-HTTP implementation of google-gax. this._gaxModule = opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. this._gaxGrpc = new this._gaxModule.GrpcClient(opts); // Save options to use in initialize() method. this._opts = opts; // Save the auth object to the client, for use by other methods. this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set the default scopes in auth client if needed. if (servicePath === staticMembers.servicePath) { this.auth.defaultScopes = staticMembers.scopes; } // Determine the client header string. const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); } // Load the applicable protos. // For Node.js, pass the path to JSON proto file. // For browsers, pass the JSON content. const nodejsProtoPath = path.join( __dirname, '..', '..', 'protos', 'protos.json' ); this._protos = this._gaxGrpc.loadProto( opts.fallback ? // eslint-disable-next-line @typescript-eslint/no-var-requires require('../../protos/protos.json') : nodejsProtoPath ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/alertPolicies/{alert_policy}' ), folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' ), folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' ), folderGroupPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/groups/{group}' ), folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/notificationChannels/{notification_channel}' ), folderServicePathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/services/{service}' ), folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' ), organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/alertPolicies/{alert_policy}' ), organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' ), organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' ), organizationGroupPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/groups/{group}' ), organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/notificationChannels/{notification_channel}' ), organizationServicePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/services/{service}' ), organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' ), projectPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}' ), projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/alertPolicies/{alert_policy}' ), projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' ), projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' ), projectGroupPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/groups/{group}' ), projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/notificationChannels/{notification_channel}' ), projectServicePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/services/{service}' ), projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { listNotificationChannelDescriptors: new this._gaxModule.PageDescriptor( 'pageToken', 'nextPageToken', 'channelDescriptors' ), listNotificationChannels: new this._gaxModule.PageDescriptor( 'pageToken', 'nextPageToken', 'notificationChannels' ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( 'google.monitoring.v3.NotificationChannelService', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')} ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this.innerApiCalls = {}; } /** * Initialize the client. * Performs asynchronous operations (such as authentication) and prepares the client. * This function will be called automatically when any class method is called for the * first time, but if you need to initialize it before calling an actual method, * feel free to call initialize() directly. * * You can await on this method if you want to make sure the client is initialized. * * @returns {Promise} A promise that resolves to an authenticated service stub. */ initialize() { // If the client stub promise is already initialized, return immediately. if (this.notificationChannelServiceStub) { return this.notificationChannelServiceStub; } // Put together the "service stub" for // google.monitoring.v3.NotificationChannelService. this.notificationChannelServiceStub = this._gaxGrpc.createStub( this._opts.fallback ? (this._protos as protobuf.Root).lookupService( 'google.monitoring.v3.NotificationChannelService' ) : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.monitoring.v3.NotificationChannelService, this._opts ) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. const notificationChannelServiceStubMethods = [ 'listNotificationChannelDescriptors', 'getNotificationChannelDescriptor', 'listNotificationChannels', 'getNotificationChannel', 'createNotificationChannel', 'updateNotificationChannel', 'deleteNotificationChannel', 'sendNotificationChannelVerificationCode', 'getNotificationChannelVerificationCode', 'verifyNotificationChannel', ]; for (const methodName of notificationChannelServiceStubMethods) { const callPromise = this.notificationChannelServiceStub.then( stub => (...args: Array<{}>) => { if (this._terminated) { return Promise.reject('The client has already been closed.'); } const func = stub[methodName]; return func.apply(stub, args); }, (err: Error | null | undefined) => () => { throw err; } ); const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor ); this.innerApiCalls[methodName] = apiCall; } return this.notificationChannelServiceStub; } /** * The DNS address for this API service. * @returns {string} The DNS address for this service. */ static get servicePath() { return 'monitoring.googleapis.com'; } /** * The DNS address for this API service - same as servicePath(), * exists for compatibility reasons. * @returns {string} The DNS address for this service. */ static get apiEndpoint() { return 'monitoring.googleapis.com'; } /** * The port for this API service. * @returns {number} The default port for this service. */ static get port() { return 443; } /** * The scopes needed to make gRPC calls for every method defined * in this service. * @returns {string[]} List of default scopes. */ static get scopes() { return [ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', 'https://www.googleapis.com/auth/monitoring.read', ]; } getProjectId(): Promise<string>; getProjectId(callback: Callback<string, undefined, undefined>): void; /** * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ getProjectId( callback?: Callback<string, undefined, undefined> ): Promise<string> | void { if (callback) { this.auth.getProjectId(callback); return; } return this.auth.getProjectId(); } // ------------------- // -- Service calls -- // ------------------- getNotificationChannelDescriptor( request: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, options?: CallOptions ): Promise< [ protos.google.monitoring.v3.INotificationChannelDescriptor, ( | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest | undefined ), {} | undefined ] >; getNotificationChannelDescriptor( request: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, options: CallOptions, callback: Callback< protos.google.monitoring.v3.INotificationChannelDescriptor, | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest | null | undefined, {} | null | undefined > ): void; getNotificationChannelDescriptor( request: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, callback: Callback< protos.google.monitoring.v3.INotificationChannelDescriptor, | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest | null | undefined, {} | null | undefined > ): void; /** * Gets a single channel descriptor. The descriptor indicates which fields * are expected / permitted for a notification channel of the given type. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The channel type for which to execute the request. The format is: * * projects/[PROJECT_ID_OR_NUMBER]/notificationChannelDescriptors/[CHANNEL_TYPE] * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [NotificationChannelDescriptor]{@link google.monitoring.v3.NotificationChannelDescriptor}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example * const [response] = await client.getNotificationChannelDescriptor(request); */ getNotificationChannelDescriptor( request: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, optionsOrCallback?: | CallOptions | Callback< protos.google.monitoring.v3.INotificationChannelDescriptor, | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest | null | undefined, {} | null | undefined >, callback?: Callback< protos.google.monitoring.v3.INotificationChannelDescriptor, | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest | null | undefined, {} | null | undefined > ): Promise< [ protos.google.monitoring.v3.INotificationChannelDescriptor, ( | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest | undefined ), {} | undefined ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); this.initialize(); return this.innerApiCalls.getNotificationChannelDescriptor( request, options, callback ); } getNotificationChannel( request: protos.google.monitoring.v3.IGetNotificationChannelRequest, options?: CallOptions ): Promise< [ protos.google.monitoring.v3.INotificationChannel, protos.google.monitoring.v3.IGetNotificationChannelRequest | undefined, {} | undefined ] >; getNotificationChannel( request: protos.google.monitoring.v3.IGetNotificationChannelRequest, options: CallOptions, callback: Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.IGetNotificationChannelRequest | null | undefined, {} | null | undefined > ): void; getNotificationChannel( request: protos.google.monitoring.v3.IGetNotificationChannelRequest, callback: Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.IGetNotificationChannelRequest | null | undefined, {} | null | undefined > ): void; /** * Gets a single notification channel. The channel includes the relevant * configuration details with which the channel was created. However, the * response may truncate or omit passwords, API keys, or other private key * matter and thus the response may not be 100% identical to the information * that was supplied in the call to the create method. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The channel for which to execute the request. The format is: * * projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [NotificationChannel]{@link google.monitoring.v3.NotificationChannel}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example * const [response] = await client.getNotificationChannel(request); */ getNotificationChannel( request: protos.google.monitoring.v3.IGetNotificationChannelRequest, optionsOrCallback?: | CallOptions | Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.IGetNotificationChannelRequest | null | undefined, {} | null | undefined >, callback?: Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.IGetNotificationChannelRequest | null | undefined, {} | null | undefined > ): Promise< [ protos.google.monitoring.v3.INotificationChannel, protos.google.monitoring.v3.IGetNotificationChannelRequest | undefined, {} | undefined ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); this.initialize(); return this.innerApiCalls.getNotificationChannel( request, options, callback ); } createNotificationChannel( request: protos.google.monitoring.v3.ICreateNotificationChannelRequest, options?: CallOptions ): Promise< [ protos.google.monitoring.v3.INotificationChannel, protos.google.monitoring.v3.ICreateNotificationChannelRequest | undefined, {} | undefined ] >; createNotificationChannel( request: protos.google.monitoring.v3.ICreateNotificationChannelRequest, options: CallOptions, callback: Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.ICreateNotificationChannelRequest | null | undefined, {} | null | undefined > ): void; createNotificationChannel( request: protos.google.monitoring.v3.ICreateNotificationChannelRequest, callback: Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.ICreateNotificationChannelRequest | null | undefined, {} | null | undefined > ): void; /** * Creates a new notification channel, representing a single notification * endpoint such as an email address, SMS number, or PagerDuty service. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The project on which to execute the request. The format is: * * projects/[PROJECT_ID_OR_NUMBER] * * This names the container into which the channel will be * written, this does not name the newly created channel. The resulting * channel's name will have a normalized version of this field as a prefix, * but will add `/notificationChannels/[CHANNEL_ID]` to identify the channel. * @param {google.monitoring.v3.NotificationChannel} request.notificationChannel * Required. The definition of the `NotificationChannel` to create. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [NotificationChannel]{@link google.monitoring.v3.NotificationChannel}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example * const [response] = await client.createNotificationChannel(request); */ createNotificationChannel( request: protos.google.monitoring.v3.ICreateNotificationChannelRequest, optionsOrCallback?: | CallOptions | Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.ICreateNotificationChannelRequest | null | undefined, {} | null | undefined >, callback?: Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.ICreateNotificationChannelRequest | null | undefined, {} | null | undefined > ): Promise< [ protos.google.monitoring.v3.INotificationChannel, protos.google.monitoring.v3.ICreateNotificationChannelRequest | undefined, {} | undefined ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); this.initialize(); return this.innerApiCalls.createNotificationChannel( request, options, callback ); } updateNotificationChannel( request: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, options?: CallOptions ): Promise< [ protos.google.monitoring.v3.INotificationChannel, protos.google.monitoring.v3.IUpdateNotificationChannelRequest | undefined, {} | undefined ] >; updateNotificationChannel( request: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, options: CallOptions, callback: Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.IUpdateNotificationChannelRequest | null | undefined, {} | null | undefined > ): void; updateNotificationChannel( request: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, callback: Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.IUpdateNotificationChannelRequest | null | undefined, {} | null | undefined > ): void; /** * Updates a notification channel. Fields not specified in the field mask * remain unchanged. * * @param {Object} request * The request object that will be sent. * @param {google.protobuf.FieldMask} request.updateMask * The fields to update. * @param {google.monitoring.v3.NotificationChannel} request.notificationChannel * Required. A description of the changes to be applied to the specified * notification channel. The description must provide a definition for * fields to be updated; the names of these fields should also be * included in the `update_mask`. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [NotificationChannel]{@link google.monitoring.v3.NotificationChannel}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example * const [response] = await client.updateNotificationChannel(request); */ updateNotificationChannel( request: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, optionsOrCallback?: | CallOptions | Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.IUpdateNotificationChannelRequest | null | undefined, {} | null | undefined >, callback?: Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.IUpdateNotificationChannelRequest | null | undefined, {} | null | undefined > ): Promise< [ protos.google.monitoring.v3.INotificationChannel, protos.google.monitoring.v3.IUpdateNotificationChannelRequest | undefined, {} | undefined ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ 'notification_channel.name': request.notificationChannel!.name || '', }); this.initialize(); return this.innerApiCalls.updateNotificationChannel( request, options, callback ); } deleteNotificationChannel( request: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, options?: CallOptions ): Promise< [ protos.google.protobuf.IEmpty, protos.google.monitoring.v3.IDeleteNotificationChannelRequest | undefined, {} | undefined ] >; deleteNotificationChannel( request: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, options: CallOptions, callback: Callback< protos.google.protobuf.IEmpty, | protos.google.monitoring.v3.IDeleteNotificationChannelRequest | null | undefined, {} | null | undefined > ): void; deleteNotificationChannel( request: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, callback: Callback< protos.google.protobuf.IEmpty, | protos.google.monitoring.v3.IDeleteNotificationChannelRequest | null | undefined, {} | null | undefined > ): void; /** * Deletes a notification channel. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The channel for which to execute the request. The format is: * * projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] * @param {boolean} request.force * If true, the notification channel will be deleted regardless of its * use in alert policies (the policies will be updated to remove the * channel). If false, channels that are still referenced by an existing * alerting policy will fail to be deleted in a delete operation. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example * const [response] = await client.deleteNotificationChannel(request); */ deleteNotificationChannel( request: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, optionsOrCallback?: | CallOptions | Callback< protos.google.protobuf.IEmpty, | protos.google.monitoring.v3.IDeleteNotificationChannelRequest | null | undefined, {} | null | undefined >, callback?: Callback< protos.google.protobuf.IEmpty, | protos.google.monitoring.v3.IDeleteNotificationChannelRequest | null | undefined, {} | null | undefined > ): Promise< [ protos.google.protobuf.IEmpty, protos.google.monitoring.v3.IDeleteNotificationChannelRequest | undefined, {} | undefined ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); this.initialize(); return this.innerApiCalls.deleteNotificationChannel( request, options, callback ); } sendNotificationChannelVerificationCode( request: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, options?: CallOptions ): Promise< [ protos.google.protobuf.IEmpty, ( | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest | undefined ), {} | undefined ] >; sendNotificationChannelVerificationCode( request: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, options: CallOptions, callback: Callback< protos.google.protobuf.IEmpty, | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest | null | undefined, {} | null | undefined > ): void; sendNotificationChannelVerificationCode( request: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, callback: Callback< protos.google.protobuf.IEmpty, | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest | null | undefined, {} | null | undefined > ): void; /** * Causes a verification code to be delivered to the channel. The code * can then be supplied in `VerifyNotificationChannel` to verify the channel. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The notification channel to which to send a verification code. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example * const [response] = await client.sendNotificationChannelVerificationCode(request); */ sendNotificationChannelVerificationCode( request: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, optionsOrCallback?: | CallOptions | Callback< protos.google.protobuf.IEmpty, | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest | null | undefined, {} | null | undefined >, callback?: Callback< protos.google.protobuf.IEmpty, | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest | null | undefined, {} | null | undefined > ): Promise< [ protos.google.protobuf.IEmpty, ( | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest | undefined ), {} | undefined ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); this.initialize(); return this.innerApiCalls.sendNotificationChannelVerificationCode( request, options, callback ); } getNotificationChannelVerificationCode( request: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, options?: CallOptions ): Promise< [ protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, ( | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest | undefined ), {} | undefined ] >; getNotificationChannelVerificationCode( request: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, options: CallOptions, callback: Callback< protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest | null | undefined, {} | null | undefined > ): void; getNotificationChannelVerificationCode( request: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, callback: Callback< protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest | null | undefined, {} | null | undefined > ): void; /** * Requests a verification code for an already verified channel that can then * be used in a call to VerifyNotificationChannel() on a different channel * with an equivalent identity in the same or in a different project. This * makes it possible to copy a channel between projects without requiring * manual reverification of the channel. If the channel is not in the * verified state, this method will fail (in other words, this may only be * used if the SendNotificationChannelVerificationCode and * VerifyNotificationChannel paths have already been used to put the given * channel into the verified state). * * There is no guarantee that the verification codes returned by this method * will be of a similar structure or form as the ones that are delivered * to the channel via SendNotificationChannelVerificationCode; while * VerifyNotificationChannel() will recognize both the codes delivered via * SendNotificationChannelVerificationCode() and returned from * GetNotificationChannelVerificationCode(), it is typically the case that * the verification codes delivered via * SendNotificationChannelVerificationCode() will be shorter and also * have a shorter expiration (e.g. codes such as "G-123456") whereas * GetVerificationCode() will typically return a much longer, websafe base * 64 encoded string that has a longer expiration time. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The notification channel for which a verification code is to be generated * and retrieved. This must name a channel that is already verified; if * the specified channel is not verified, the request will fail. * @param {google.protobuf.Timestamp} request.expireTime * The desired expiration time. If specified, the API will guarantee that * the returned code will not be valid after the specified timestamp; * however, the API cannot guarantee that the returned code will be * valid for at least as long as the requested time (the API puts an upper * bound on the amount of time for which a code may be valid). If omitted, * a default expiration will be used, which may be less than the max * permissible expiration (so specifying an expiration may extend the * code's lifetime over omitting an expiration, even though the API does * impose an upper limit on the maximum expiration that is permitted). * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [GetNotificationChannelVerificationCodeResponse]{@link google.monitoring.v3.GetNotificationChannelVerificationCodeResponse}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example * const [response] = await client.getNotificationChannelVerificationCode(request); */ getNotificationChannelVerificationCode( request: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, optionsOrCallback?: | CallOptions | Callback< protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest | null | undefined, {} | null | undefined >, callback?: Callback< protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest | null | undefined, {} | null | undefined > ): Promise< [ protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, ( | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest | undefined ), {} | undefined ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); this.initialize(); return this.innerApiCalls.getNotificationChannelVerificationCode( request, options, callback ); } verifyNotificationChannel( request: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, options?: CallOptions ): Promise< [ protos.google.monitoring.v3.INotificationChannel, protos.google.monitoring.v3.IVerifyNotificationChannelRequest | undefined, {} | undefined ] >; verifyNotificationChannel( request: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, options: CallOptions, callback: Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.IVerifyNotificationChannelRequest | null | undefined, {} | null | undefined > ): void; verifyNotificationChannel( request: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, callback: Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.IVerifyNotificationChannelRequest | null | undefined, {} | null | undefined > ): void; /** * Verifies a `NotificationChannel` by proving receipt of the code * delivered to the channel as a result of calling * `SendNotificationChannelVerificationCode`. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The notification channel to verify. * @param {string} request.code * Required. The verification code that was delivered to the channel as * a result of invoking the `SendNotificationChannelVerificationCode` API * method or that was retrieved from a verified channel via * `GetNotificationChannelVerificationCode`. For example, one might have * "G-123456" or "TKNZGhhd2EyN3I1MnRnMjRv" (in general, one is only * guaranteed that the code is valid UTF-8; one should not * make any assumptions regarding the structure or format of the code). * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [NotificationChannel]{@link google.monitoring.v3.NotificationChannel}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example * const [response] = await client.verifyNotificationChannel(request); */ verifyNotificationChannel( request: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, optionsOrCallback?: | CallOptions | Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.IVerifyNotificationChannelRequest | null | undefined, {} | null | undefined >, callback?: Callback< protos.google.monitoring.v3.INotificationChannel, | protos.google.monitoring.v3.IVerifyNotificationChannelRequest | null | undefined, {} | null | undefined > ): Promise< [ protos.google.monitoring.v3.INotificationChannel, protos.google.monitoring.v3.IVerifyNotificationChannelRequest | undefined, {} | undefined ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); this.initialize(); return this.innerApiCalls.verifyNotificationChannel( request, options, callback ); } listNotificationChannelDescriptors( request: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, options?: CallOptions ): Promise< [ protos.google.monitoring.v3.INotificationChannelDescriptor[], protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest | null, protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse ] >; listNotificationChannelDescriptors( request: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, options: CallOptions, callback: PaginationCallback< protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, | protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse | null | undefined, protos.google.monitoring.v3.INotificationChannelDescriptor > ): void; listNotificationChannelDescriptors( request: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, callback: PaginationCallback< protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, | protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse | null | undefined, protos.google.monitoring.v3.INotificationChannelDescriptor > ): void; /** * Lists the descriptors for supported channel types. The use of descriptors * makes it possible for new channel types to be dynamically added. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The REST resource name of the parent from which to retrieve * the notification channel descriptors. The expected syntax is: * * projects/[PROJECT_ID_OR_NUMBER] * * Note that this names the parent container in which to look for the * descriptors; to retrieve a single descriptor by name, use the * {@link google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor|GetNotificationChannelDescriptor} * operation, instead. * @param {number} request.pageSize * The maximum number of results to return in a single response. If * not set to a positive number, a reasonable value will be chosen by the * service. * @param {string} request.pageToken * If non-empty, `page_token` must contain a value returned as the * `next_page_token` in a previous response to request the next set * of results. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is Array of [NotificationChannelDescriptor]{@link google.monitoring.v3.NotificationChannelDescriptor}. * The client library will perform auto-pagination by default: it will call the API as many * times as needed and will merge results from all the pages into this array. * Note that it can affect your quota. * We recommend using `listNotificationChannelDescriptorsAsync()` * method described below for async iteration which you can stop as needed. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) * for more details and examples. */ listNotificationChannelDescriptors( request: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, optionsOrCallback?: | CallOptions | PaginationCallback< protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, | protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse | null | undefined, protos.google.monitoring.v3.INotificationChannelDescriptor >, callback?: PaginationCallback< protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, | protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse | null | undefined, protos.google.monitoring.v3.INotificationChannelDescriptor > ): Promise< [ protos.google.monitoring.v3.INotificationChannelDescriptor[], protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest | null, protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); this.initialize(); return this.innerApiCalls.listNotificationChannelDescriptors( request, options, callback ); } /** * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The REST resource name of the parent from which to retrieve * the notification channel descriptors. The expected syntax is: * * projects/[PROJECT_ID_OR_NUMBER] * * Note that this names the parent container in which to look for the * descriptors; to retrieve a single descriptor by name, use the * {@link google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor|GetNotificationChannelDescriptor} * operation, instead. * @param {number} request.pageSize * The maximum number of results to return in a single response. If * not set to a positive number, a reasonable value will be chosen by the * service. * @param {string} request.pageToken * If non-empty, `page_token` must contain a value returned as the * `next_page_token` in a previous response to request the next set * of results. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} * An object stream which emits an object representing [NotificationChannelDescriptor]{@link google.monitoring.v3.NotificationChannelDescriptor} on 'data' event. * The client library will perform auto-pagination by default: it will call the API as many * times as needed. Note that it can affect your quota. * We recommend using `listNotificationChannelDescriptorsAsync()` * method described below for async iteration which you can stop as needed. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) * for more details and examples. */ listNotificationChannelDescriptorsStream( request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, options?: CallOptions ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); const callSettings = new gax.CallSettings(options); this.initialize(); return this.descriptors.page.listNotificationChannelDescriptors.createStream( this.innerApiCalls.listNotificationChannelDescriptors as gax.GaxCall, request, callSettings ); } /** * Equivalent to `listNotificationChannelDescriptors`, but returns an iterable object. * * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The REST resource name of the parent from which to retrieve * the notification channel descriptors. The expected syntax is: * * projects/[PROJECT_ID_OR_NUMBER] * * Note that this names the parent container in which to look for the * descriptors; to retrieve a single descriptor by name, use the * {@link google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor|GetNotificationChannelDescriptor} * operation, instead. * @param {number} request.pageSize * The maximum number of results to return in a single response. If * not set to a positive number, a reasonable value will be chosen by the * service. * @param {string} request.pageToken * If non-empty, `page_token` must contain a value returned as the * `next_page_token` in a previous response to request the next set * of results. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Object} * An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). * When you iterate the returned iterable, each element will be an object representing * [NotificationChannelDescriptor]{@link google.monitoring.v3.NotificationChannelDescriptor}. The API will be called under the hood as needed, once per the page, * so you can stop the iteration when you don't need more results. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) * for more details and examples. * @example * const iterable = client.listNotificationChannelDescriptorsAsync(request); * for await (const response of iterable) { * // process response * } */ listNotificationChannelDescriptorsAsync( request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, options?: CallOptions ): AsyncIterable<protos.google.monitoring.v3.INotificationChannelDescriptor> { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); options = options || {}; const callSettings = new gax.CallSettings(options); this.initialize(); return this.descriptors.page.listNotificationChannelDescriptors.asyncIterate( this.innerApiCalls['listNotificationChannelDescriptors'] as GaxCall, request as unknown as RequestType, callSettings ) as AsyncIterable<protos.google.monitoring.v3.INotificationChannelDescriptor>; } listNotificationChannels( request: protos.google.monitoring.v3.IListNotificationChannelsRequest, options?: CallOptions ): Promise< [ protos.google.monitoring.v3.INotificationChannel[], protos.google.monitoring.v3.IListNotificationChannelsRequest | null, protos.google.monitoring.v3.IListNotificationChannelsResponse ] >; listNotificationChannels( request: protos.google.monitoring.v3.IListNotificationChannelsRequest, options: CallOptions, callback: PaginationCallback< protos.google.monitoring.v3.IListNotificationChannelsRequest, | protos.google.monitoring.v3.IListNotificationChannelsResponse | null | undefined, protos.google.monitoring.v3.INotificationChannel > ): void; listNotificationChannels( request: protos.google.monitoring.v3.IListNotificationChannelsRequest, callback: PaginationCallback< protos.google.monitoring.v3.IListNotificationChannelsRequest, | protos.google.monitoring.v3.IListNotificationChannelsResponse | null | undefined, protos.google.monitoring.v3.INotificationChannel > ): void; /** * Lists the notification channels that have been created for the project. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The project on which to execute the request. The format is: * * projects/[PROJECT_ID_OR_NUMBER] * * This names the container * in which to look for the notification channels; it does not name a * specific channel. To query a specific channel by REST resource name, use * the * {@link google.monitoring.v3.NotificationChannelService.GetNotificationChannel|`GetNotificationChannel`} * operation. * @param {string} request.filter * If provided, this field specifies the criteria that must be met by * notification channels to be included in the response. * * For more details, see [sorting and * filtering](https://cloud.google.com/monitoring/api/v3/sorting-and-filtering). * @param {string} request.orderBy * A comma-separated list of fields by which to sort the result. Supports * the same set of fields as in `filter`. Entries can be prefixed with * a minus sign to sort in descending rather than ascending order. * * For more details, see [sorting and * filtering](https://cloud.google.com/monitoring/api/v3/sorting-and-filtering). * @param {number} request.pageSize * The maximum number of results to return in a single response. If * not set to a positive number, a reasonable value will be chosen by the * service. * @param {string} request.pageToken * If non-empty, `page_token` must contain a value returned as the * `next_page_token` in a previous response to request the next set * of results. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is Array of [NotificationChannel]{@link google.monitoring.v3.NotificationChannel}. * The client library will perform auto-pagination by default: it will call the API as many * times as needed and will merge results from all the pages into this array. * Note that it can affect your quota. * We recommend using `listNotificationChannelsAsync()` * method described below for async iteration which you can stop as needed. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) * for more details and examples. */ listNotificationChannels( request: protos.google.monitoring.v3.IListNotificationChannelsRequest, optionsOrCallback?: | CallOptions | PaginationCallback< protos.google.monitoring.v3.IListNotificationChannelsRequest, | protos.google.monitoring.v3.IListNotificationChannelsResponse | null | undefined, protos.google.monitoring.v3.INotificationChannel >, callback?: PaginationCallback< protos.google.monitoring.v3.IListNotificationChannelsRequest, | protos.google.monitoring.v3.IListNotificationChannelsResponse | null | undefined, protos.google.monitoring.v3.INotificationChannel > ): Promise< [ protos.google.monitoring.v3.INotificationChannel[], protos.google.monitoring.v3.IListNotificationChannelsRequest | null, protos.google.monitoring.v3.IListNotificationChannelsResponse ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); this.initialize(); return this.innerApiCalls.listNotificationChannels( request, options, callback ); } /** * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The project on which to execute the request. The format is: * * projects/[PROJECT_ID_OR_NUMBER] * * This names the container * in which to look for the notification channels; it does not name a * specific channel. To query a specific channel by REST resource name, use * the * {@link google.monitoring.v3.NotificationChannelService.GetNotificationChannel|`GetNotificationChannel`} * operation. * @param {string} request.filter * If provided, this field specifies the criteria that must be met by * notification channels to be included in the response. * * For more details, see [sorting and * filtering](https://cloud.google.com/monitoring/api/v3/sorting-and-filtering). * @param {string} request.orderBy * A comma-separated list of fields by which to sort the result. Supports * the same set of fields as in `filter`. Entries can be prefixed with * a minus sign to sort in descending rather than ascending order. * * For more details, see [sorting and * filtering](https://cloud.google.com/monitoring/api/v3/sorting-and-filtering). * @param {number} request.pageSize * The maximum number of results to return in a single response. If * not set to a positive number, a reasonable value will be chosen by the * service. * @param {string} request.pageToken * If non-empty, `page_token` must contain a value returned as the * `next_page_token` in a previous response to request the next set * of results. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} * An object stream which emits an object representing [NotificationChannel]{@link google.monitoring.v3.NotificationChannel} on 'data' event. * The client library will perform auto-pagination by default: it will call the API as many * times as needed. Note that it can affect your quota. * We recommend using `listNotificationChannelsAsync()` * method described below for async iteration which you can stop as needed. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) * for more details and examples. */ listNotificationChannelsStream( request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, options?: CallOptions ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); const callSettings = new gax.CallSettings(options); this.initialize(); return this.descriptors.page.listNotificationChannels.createStream( this.innerApiCalls.listNotificationChannels as gax.GaxCall, request, callSettings ); } /** * Equivalent to `listNotificationChannels`, but returns an iterable object. * * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The project on which to execute the request. The format is: * * projects/[PROJECT_ID_OR_NUMBER] * * This names the container * in which to look for the notification channels; it does not name a * specific channel. To query a specific channel by REST resource name, use * the * {@link google.monitoring.v3.NotificationChannelService.GetNotificationChannel|`GetNotificationChannel`} * operation. * @param {string} request.filter * If provided, this field specifies the criteria that must be met by * notification channels to be included in the response. * * For more details, see [sorting and * filtering](https://cloud.google.com/monitoring/api/v3/sorting-and-filtering). * @param {string} request.orderBy * A comma-separated list of fields by which to sort the result. Supports * the same set of fields as in `filter`. Entries can be prefixed with * a minus sign to sort in descending rather than ascending order. * * For more details, see [sorting and * filtering](https://cloud.google.com/monitoring/api/v3/sorting-and-filtering). * @param {number} request.pageSize * The maximum number of results to return in a single response. If * not set to a positive number, a reasonable value will be chosen by the * service. * @param {string} request.pageToken * If non-empty, `page_token` must contain a value returned as the * `next_page_token` in a previous response to request the next set * of results. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Object} * An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). * When you iterate the returned iterable, each element will be an object representing * [NotificationChannel]{@link google.monitoring.v3.NotificationChannel}. The API will be called under the hood as needed, once per the page, * so you can stop the iteration when you don't need more results. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) * for more details and examples. * @example * const iterable = client.listNotificationChannelsAsync(request); * for await (const response of iterable) { * // process response * } */ listNotificationChannelsAsync( request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, options?: CallOptions ): AsyncIterable<protos.google.monitoring.v3.INotificationChannel> { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); options = options || {}; const callSettings = new gax.CallSettings(options); this.initialize(); return this.descriptors.page.listNotificationChannels.asyncIterate( this.innerApiCalls['listNotificationChannels'] as GaxCall, request as unknown as RequestType, callSettings ) as AsyncIterable<protos.google.monitoring.v3.INotificationChannel>; } // -------------------- // -- Path templates -- // -------------------- /** * Return a fully-qualified folderAlertPolicy resource name string. * * @param {string} folder * @param {string} alert_policy * @returns {string} Resource name string. */ folderAlertPolicyPath(folder: string, alertPolicy: string) { return this.pathTemplates.folderAlertPolicyPathTemplate.render({ folder: folder, alert_policy: alertPolicy, }); } /** * Parse the folder from FolderAlertPolicy resource. * * @param {string} folderAlertPolicyName * A fully-qualified path representing folder_alert_policy resource. * @returns {string} A string representing the folder. */ matchFolderFromFolderAlertPolicyName(folderAlertPolicyName: string) { return this.pathTemplates.folderAlertPolicyPathTemplate.match( folderAlertPolicyName ).folder; } /** * Parse the alert_policy from FolderAlertPolicy resource. * * @param {string} folderAlertPolicyName * A fully-qualified path representing folder_alert_policy resource. * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromFolderAlertPolicyName(folderAlertPolicyName: string) { return this.pathTemplates.folderAlertPolicyPathTemplate.match( folderAlertPolicyName ).alert_policy; } /** * Return a fully-qualified folderAlertPolicyCondition resource name string. * * @param {string} folder * @param {string} alert_policy * @param {string} condition * @returns {string} Resource name string. */ folderAlertPolicyConditionPath( folder: string, alertPolicy: string, condition: string ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.render({ folder: folder, alert_policy: alertPolicy, condition: condition, }); } /** * Parse the folder from FolderAlertPolicyCondition resource. * * @param {string} folderAlertPolicyConditionName * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the folder. */ matchFolderFromFolderAlertPolicyConditionName( folderAlertPolicyConditionName: string ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( folderAlertPolicyConditionName ).folder; } /** * Parse the alert_policy from FolderAlertPolicyCondition resource. * * @param {string} folderAlertPolicyConditionName * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromFolderAlertPolicyConditionName( folderAlertPolicyConditionName: string ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( folderAlertPolicyConditionName ).alert_policy; } /** * Parse the condition from FolderAlertPolicyCondition resource. * * @param {string} folderAlertPolicyConditionName * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the condition. */ matchConditionFromFolderAlertPolicyConditionName( folderAlertPolicyConditionName: string ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( folderAlertPolicyConditionName ).condition; } /** * Return a fully-qualified folderChannelDescriptor resource name string. * * @param {string} folder * @param {string} channel_descriptor * @returns {string} Resource name string. */ folderChannelDescriptorPath(folder: string, channelDescriptor: string) { return this.pathTemplates.folderChannelDescriptorPathTemplate.render({ folder: folder, channel_descriptor: channelDescriptor, }); } /** * Parse the folder from FolderChannelDescriptor resource. * * @param {string} folderChannelDescriptorName * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the folder. */ matchFolderFromFolderChannelDescriptorName( folderChannelDescriptorName: string ) { return this.pathTemplates.folderChannelDescriptorPathTemplate.match( folderChannelDescriptorName ).folder; } /** * Parse the channel_descriptor from FolderChannelDescriptor resource. * * @param {string} folderChannelDescriptorName * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ matchChannelDescriptorFromFolderChannelDescriptorName( folderChannelDescriptorName: string ) { return this.pathTemplates.folderChannelDescriptorPathTemplate.match( folderChannelDescriptorName ).channel_descriptor; } /** * Return a fully-qualified folderGroup resource name string. * * @param {string} folder * @param {string} group * @returns {string} Resource name string. */ folderGroupPath(folder: string, group: string) { return this.pathTemplates.folderGroupPathTemplate.render({ folder: folder, group: group, }); } /** * Parse the folder from FolderGroup resource. * * @param {string} folderGroupName * A fully-qualified path representing folder_group resource. * @returns {string} A string representing the folder. */ matchFolderFromFolderGroupName(folderGroupName: string) { return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) .folder; } /** * Parse the group from FolderGroup resource. * * @param {string} folderGroupName * A fully-qualified path representing folder_group resource. * @returns {string} A string representing the group. */ matchGroupFromFolderGroupName(folderGroupName: string) { return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) .group; } /** * Return a fully-qualified folderNotificationChannel resource name string. * * @param {string} folder * @param {string} notification_channel * @returns {string} Resource name string. */ folderNotificationChannelPath(folder: string, notificationChannel: string) { return this.pathTemplates.folderNotificationChannelPathTemplate.render({ folder: folder, notification_channel: notificationChannel, }); } /** * Parse the folder from FolderNotificationChannel resource. * * @param {string} folderNotificationChannelName * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the folder. */ matchFolderFromFolderNotificationChannelName( folderNotificationChannelName: string ) { return this.pathTemplates.folderNotificationChannelPathTemplate.match( folderNotificationChannelName ).folder; } /** * Parse the notification_channel from FolderNotificationChannel resource. * * @param {string} folderNotificationChannelName * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the notification_channel. */ matchNotificationChannelFromFolderNotificationChannelName( folderNotificationChannelName: string ) { return this.pathTemplates.folderNotificationChannelPathTemplate.match( folderNotificationChannelName ).notification_channel; } /** * Return a fully-qualified folderService resource name string. * * @param {string} folder * @param {string} service * @returns {string} Resource name string. */ folderServicePath(folder: string, service: string) { return this.pathTemplates.folderServicePathTemplate.render({ folder: folder, service: service, }); } /** * Parse the folder from FolderService resource. * * @param {string} folderServiceName * A fully-qualified path representing folder_service resource. * @returns {string} A string representing the folder. */ matchFolderFromFolderServiceName(folderServiceName: string) { return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) .folder; } /** * Parse the service from FolderService resource. * * @param {string} folderServiceName * A fully-qualified path representing folder_service resource. * @returns {string} A string representing the service. */ matchServiceFromFolderServiceName(folderServiceName: string) { return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) .service; } /** * Return a fully-qualified folderServiceServiceLevelObjective resource name string. * * @param {string} folder * @param {string} service * @param {string} service_level_objective * @returns {string} Resource name string. */ folderServiceServiceLevelObjectivePath( folder: string, service: string, serviceLevelObjective: string ) { return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render( { folder: folder, service: service, service_level_objective: serviceLevelObjective, } ); } /** * Parse the folder from FolderServiceServiceLevelObjective resource. * * @param {string} folderServiceServiceLevelObjectiveName * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the folder. */ matchFolderFromFolderServiceServiceLevelObjectiveName( folderServiceServiceLevelObjectiveName: string ) { return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( folderServiceServiceLevelObjectiveName ).folder; } /** * Parse the service from FolderServiceServiceLevelObjective resource. * * @param {string} folderServiceServiceLevelObjectiveName * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service. */ matchServiceFromFolderServiceServiceLevelObjectiveName( folderServiceServiceLevelObjectiveName: string ) { return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( folderServiceServiceLevelObjectiveName ).service; } /** * Parse the service_level_objective from FolderServiceServiceLevelObjective resource. * * @param {string} folderServiceServiceLevelObjectiveName * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( folderServiceServiceLevelObjectiveName: string ) { return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( folderServiceServiceLevelObjectiveName ).service_level_objective; } /** * Return a fully-qualified folderUptimeCheckConfig resource name string. * * @param {string} folder * @param {string} uptime_check_config * @returns {string} Resource name string. */ folderUptimeCheckConfigPath(folder: string, uptimeCheckConfig: string) { return this.pathTemplates.folderUptimeCheckConfigPathTemplate.render({ folder: folder, uptime_check_config: uptimeCheckConfig, }); } /** * Parse the folder from FolderUptimeCheckConfig resource. * * @param {string} folderUptimeCheckConfigName * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the folder. */ matchFolderFromFolderUptimeCheckConfigName( folderUptimeCheckConfigName: string ) { return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( folderUptimeCheckConfigName ).folder; } /** * Parse the uptime_check_config from FolderUptimeCheckConfig resource. * * @param {string} folderUptimeCheckConfigName * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ matchUptimeCheckConfigFromFolderUptimeCheckConfigName( folderUptimeCheckConfigName: string ) { return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( folderUptimeCheckConfigName ).uptime_check_config; } /** * Return a fully-qualified organizationAlertPolicy resource name string. * * @param {string} organization * @param {string} alert_policy * @returns {string} Resource name string. */ organizationAlertPolicyPath(organization: string, alertPolicy: string) { return this.pathTemplates.organizationAlertPolicyPathTemplate.render({ organization: organization, alert_policy: alertPolicy, }); } /** * Parse the organization from OrganizationAlertPolicy resource. * * @param {string} organizationAlertPolicyName * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationAlertPolicyName( organizationAlertPolicyName: string ) { return this.pathTemplates.organizationAlertPolicyPathTemplate.match( organizationAlertPolicyName ).organization; } /** * Parse the alert_policy from OrganizationAlertPolicy resource. * * @param {string} organizationAlertPolicyName * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromOrganizationAlertPolicyName( organizationAlertPolicyName: string ) { return this.pathTemplates.organizationAlertPolicyPathTemplate.match( organizationAlertPolicyName ).alert_policy; } /** * Return a fully-qualified organizationAlertPolicyCondition resource name string. * * @param {string} organization * @param {string} alert_policy * @param {string} condition * @returns {string} Resource name string. */ organizationAlertPolicyConditionPath( organization: string, alertPolicy: string, condition: string ) { return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render( { organization: organization, alert_policy: alertPolicy, condition: condition, } ); } /** * Parse the organization from OrganizationAlertPolicyCondition resource. * * @param {string} organizationAlertPolicyConditionName * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationAlertPolicyConditionName( organizationAlertPolicyConditionName: string ) { return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( organizationAlertPolicyConditionName ).organization; } /** * Parse the alert_policy from OrganizationAlertPolicyCondition resource. * * @param {string} organizationAlertPolicyConditionName * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromOrganizationAlertPolicyConditionName( organizationAlertPolicyConditionName: string ) { return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( organizationAlertPolicyConditionName ).alert_policy; } /** * Parse the condition from OrganizationAlertPolicyCondition resource. * * @param {string} organizationAlertPolicyConditionName * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the condition. */ matchConditionFromOrganizationAlertPolicyConditionName( organizationAlertPolicyConditionName: string ) { return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( organizationAlertPolicyConditionName ).condition; } /** * Return a fully-qualified organizationChannelDescriptor resource name string. * * @param {string} organization * @param {string} channel_descriptor * @returns {string} Resource name string. */ organizationChannelDescriptorPath( organization: string, channelDescriptor: string ) { return this.pathTemplates.organizationChannelDescriptorPathTemplate.render({ organization: organization, channel_descriptor: channelDescriptor, }); } /** * Parse the organization from OrganizationChannelDescriptor resource. * * @param {string} organizationChannelDescriptorName * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationChannelDescriptorName( organizationChannelDescriptorName: string ) { return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( organizationChannelDescriptorName ).organization; } /** * Parse the channel_descriptor from OrganizationChannelDescriptor resource. * * @param {string} organizationChannelDescriptorName * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ matchChannelDescriptorFromOrganizationChannelDescriptorName( organizationChannelDescriptorName: string ) { return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( organizationChannelDescriptorName ).channel_descriptor; } /** * Return a fully-qualified organizationGroup resource name string. * * @param {string} organization * @param {string} group * @returns {string} Resource name string. */ organizationGroupPath(organization: string, group: string) { return this.pathTemplates.organizationGroupPathTemplate.render({ organization: organization, group: group, }); } /** * Parse the organization from OrganizationGroup resource. * * @param {string} organizationGroupName * A fully-qualified path representing organization_group resource. * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationGroupName(organizationGroupName: string) { return this.pathTemplates.organizationGroupPathTemplate.match( organizationGroupName ).organization; } /** * Parse the group from OrganizationGroup resource. * * @param {string} organizationGroupName * A fully-qualified path representing organization_group resource. * @returns {string} A string representing the group. */ matchGroupFromOrganizationGroupName(organizationGroupName: string) { return this.pathTemplates.organizationGroupPathTemplate.match( organizationGroupName ).group; } /** * Return a fully-qualified organizationNotificationChannel resource name string. * * @param {string} organization * @param {string} notification_channel * @returns {string} Resource name string. */ organizationNotificationChannelPath( organization: string, notificationChannel: string ) { return this.pathTemplates.organizationNotificationChannelPathTemplate.render( { organization: organization, notification_channel: notificationChannel, } ); } /** * Parse the organization from OrganizationNotificationChannel resource. * * @param {string} organizationNotificationChannelName * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationNotificationChannelName( organizationNotificationChannelName: string ) { return this.pathTemplates.organizationNotificationChannelPathTemplate.match( organizationNotificationChannelName ).organization; } /** * Parse the notification_channel from OrganizationNotificationChannel resource. * * @param {string} organizationNotificationChannelName * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the notification_channel. */ matchNotificationChannelFromOrganizationNotificationChannelName( organizationNotificationChannelName: string ) { return this.pathTemplates.organizationNotificationChannelPathTemplate.match( organizationNotificationChannelName ).notification_channel; } /** * Return a fully-qualified organizationService resource name string. * * @param {string} organization * @param {string} service * @returns {string} Resource name string. */ organizationServicePath(organization: string, service: string) { return this.pathTemplates.organizationServicePathTemplate.render({ organization: organization, service: service, }); } /** * Parse the organization from OrganizationService resource. * * @param {string} organizationServiceName * A fully-qualified path representing organization_service resource. * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationServiceName( organizationServiceName: string ) { return this.pathTemplates.organizationServicePathTemplate.match( organizationServiceName ).organization; } /** * Parse the service from OrganizationService resource. * * @param {string} organizationServiceName * A fully-qualified path representing organization_service resource. * @returns {string} A string representing the service. */ matchServiceFromOrganizationServiceName(organizationServiceName: string) { return this.pathTemplates.organizationServicePathTemplate.match( organizationServiceName ).service; } /** * Return a fully-qualified organizationServiceServiceLevelObjective resource name string. * * @param {string} organization * @param {string} service * @param {string} service_level_objective * @returns {string} Resource name string. */ organizationServiceServiceLevelObjectivePath( organization: string, service: string, serviceLevelObjective: string ) { return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render( { organization: organization, service: service, service_level_objective: serviceLevelObjective, } ); } /** * Parse the organization from OrganizationServiceServiceLevelObjective resource. * * @param {string} organizationServiceServiceLevelObjectiveName * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( organizationServiceServiceLevelObjectiveName: string ) { return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( organizationServiceServiceLevelObjectiveName ).organization; } /** * Parse the service from OrganizationServiceServiceLevelObjective resource. * * @param {string} organizationServiceServiceLevelObjectiveName * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service. */ matchServiceFromOrganizationServiceServiceLevelObjectiveName( organizationServiceServiceLevelObjectiveName: string ) { return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( organizationServiceServiceLevelObjectiveName ).service; } /** * Parse the service_level_objective from OrganizationServiceServiceLevelObjective resource. * * @param {string} organizationServiceServiceLevelObjectiveName * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( organizationServiceServiceLevelObjectiveName: string ) { return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( organizationServiceServiceLevelObjectiveName ).service_level_objective; } /** * Return a fully-qualified organizationUptimeCheckConfig resource name string. * * @param {string} organization * @param {string} uptime_check_config * @returns {string} Resource name string. */ organizationUptimeCheckConfigPath( organization: string, uptimeCheckConfig: string ) { return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.render({ organization: organization, uptime_check_config: uptimeCheckConfig, }); } /** * Parse the organization from OrganizationUptimeCheckConfig resource. * * @param {string} organizationUptimeCheckConfigName * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationUptimeCheckConfigName( organizationUptimeCheckConfigName: string ) { return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( organizationUptimeCheckConfigName ).organization; } /** * Parse the uptime_check_config from OrganizationUptimeCheckConfig resource. * * @param {string} organizationUptimeCheckConfigName * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( organizationUptimeCheckConfigName: string ) { return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( organizationUptimeCheckConfigName ).uptime_check_config; } /** * Return a fully-qualified project resource name string. * * @param {string} project * @returns {string} Resource name string. */ projectPath(project: string) { return this.pathTemplates.projectPathTemplate.render({ project: project, }); } /** * Parse the project from Project resource. * * @param {string} projectName * A fully-qualified path representing Project resource. * @returns {string} A string representing the project. */ matchProjectFromProjectName(projectName: string) { return this.pathTemplates.projectPathTemplate.match(projectName).project; } /** * Return a fully-qualified projectAlertPolicy resource name string. * * @param {string} project * @param {string} alert_policy * @returns {string} Resource name string. */ projectAlertPolicyPath(project: string, alertPolicy: string) { return this.pathTemplates.projectAlertPolicyPathTemplate.render({ project: project, alert_policy: alertPolicy, }); } /** * Parse the project from ProjectAlertPolicy resource. * * @param {string} projectAlertPolicyName * A fully-qualified path representing project_alert_policy resource. * @returns {string} A string representing the project. */ matchProjectFromProjectAlertPolicyName(projectAlertPolicyName: string) { return this.pathTemplates.projectAlertPolicyPathTemplate.match( projectAlertPolicyName ).project; } /** * Parse the alert_policy from ProjectAlertPolicy resource. * * @param {string} projectAlertPolicyName * A fully-qualified path representing project_alert_policy resource. * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromProjectAlertPolicyName(projectAlertPolicyName: string) { return this.pathTemplates.projectAlertPolicyPathTemplate.match( projectAlertPolicyName ).alert_policy; } /** * Return a fully-qualified projectAlertPolicyCondition resource name string. * * @param {string} project * @param {string} alert_policy * @param {string} condition * @returns {string} Resource name string. */ projectAlertPolicyConditionPath( project: string, alertPolicy: string, condition: string ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.render({ project: project, alert_policy: alertPolicy, condition: condition, }); } /** * Parse the project from ProjectAlertPolicyCondition resource. * * @param {string} projectAlertPolicyConditionName * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the project. */ matchProjectFromProjectAlertPolicyConditionName( projectAlertPolicyConditionName: string ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( projectAlertPolicyConditionName ).project; } /** * Parse the alert_policy from ProjectAlertPolicyCondition resource. * * @param {string} projectAlertPolicyConditionName * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromProjectAlertPolicyConditionName( projectAlertPolicyConditionName: string ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( projectAlertPolicyConditionName ).alert_policy; } /** * Parse the condition from ProjectAlertPolicyCondition resource. * * @param {string} projectAlertPolicyConditionName * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the condition. */ matchConditionFromProjectAlertPolicyConditionName( projectAlertPolicyConditionName: string ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( projectAlertPolicyConditionName ).condition; } /** * Return a fully-qualified projectChannelDescriptor resource name string. * * @param {string} project * @param {string} channel_descriptor * @returns {string} Resource name string. */ projectChannelDescriptorPath(project: string, channelDescriptor: string) { return this.pathTemplates.projectChannelDescriptorPathTemplate.render({ project: project, channel_descriptor: channelDescriptor, }); } /** * Parse the project from ProjectChannelDescriptor resource. * * @param {string} projectChannelDescriptorName * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the project. */ matchProjectFromProjectChannelDescriptorName( projectChannelDescriptorName: string ) { return this.pathTemplates.projectChannelDescriptorPathTemplate.match( projectChannelDescriptorName ).project; } /** * Parse the channel_descriptor from ProjectChannelDescriptor resource. * * @param {string} projectChannelDescriptorName * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ matchChannelDescriptorFromProjectChannelDescriptorName( projectChannelDescriptorName: string ) { return this.pathTemplates.projectChannelDescriptorPathTemplate.match( projectChannelDescriptorName ).channel_descriptor; } /** * Return a fully-qualified projectGroup resource name string. * * @param {string} project * @param {string} group * @returns {string} Resource name string. */ projectGroupPath(project: string, group: string) { return this.pathTemplates.projectGroupPathTemplate.render({ project: project, group: group, }); } /** * Parse the project from ProjectGroup resource. * * @param {string} projectGroupName * A fully-qualified path representing project_group resource. * @returns {string} A string representing the project. */ matchProjectFromProjectGroupName(projectGroupName: string) { return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) .project; } /** * Parse the group from ProjectGroup resource. * * @param {string} projectGroupName * A fully-qualified path representing project_group resource. * @returns {string} A string representing the group. */ matchGroupFromProjectGroupName(projectGroupName: string) { return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) .group; } /** * Return a fully-qualified projectNotificationChannel resource name string. * * @param {string} project * @param {string} notification_channel * @returns {string} Resource name string. */ projectNotificationChannelPath(project: string, notificationChannel: string) { return this.pathTemplates.projectNotificationChannelPathTemplate.render({ project: project, notification_channel: notificationChannel, }); } /** * Parse the project from ProjectNotificationChannel resource. * * @param {string} projectNotificationChannelName * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the project. */ matchProjectFromProjectNotificationChannelName( projectNotificationChannelName: string ) { return this.pathTemplates.projectNotificationChannelPathTemplate.match( projectNotificationChannelName ).project; } /** * Parse the notification_channel from ProjectNotificationChannel resource. * * @param {string} projectNotificationChannelName * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the notification_channel. */ matchNotificationChannelFromProjectNotificationChannelName( projectNotificationChannelName: string ) { return this.pathTemplates.projectNotificationChannelPathTemplate.match( projectNotificationChannelName ).notification_channel; } /** * Return a fully-qualified projectService resource name string. * * @param {string} project * @param {string} service * @returns {string} Resource name string. */ projectServicePath(project: string, service: string) { return this.pathTemplates.projectServicePathTemplate.render({ project: project, service: service, }); } /** * Parse the project from ProjectService resource. * * @param {string} projectServiceName * A fully-qualified path representing project_service resource. * @returns {string} A string representing the project. */ matchProjectFromProjectServiceName(projectServiceName: string) { return this.pathTemplates.projectServicePathTemplate.match( projectServiceName ).project; } /** * Parse the service from ProjectService resource. * * @param {string} projectServiceName * A fully-qualified path representing project_service resource. * @returns {string} A string representing the service. */ matchServiceFromProjectServiceName(projectServiceName: string) { return this.pathTemplates.projectServicePathTemplate.match( projectServiceName ).service; } /** * Return a fully-qualified projectServiceServiceLevelObjective resource name string. * * @param {string} project * @param {string} service * @param {string} service_level_objective * @returns {string} Resource name string. */ projectServiceServiceLevelObjectivePath( project: string, service: string, serviceLevelObjective: string ) { return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render( { project: project, service: service, service_level_objective: serviceLevelObjective, } ); } /** * Parse the project from ProjectServiceServiceLevelObjective resource. * * @param {string} projectServiceServiceLevelObjectiveName * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the project. */ matchProjectFromProjectServiceServiceLevelObjectiveName( projectServiceServiceLevelObjectiveName: string ) { return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( projectServiceServiceLevelObjectiveName ).project; } /** * Parse the service from ProjectServiceServiceLevelObjective resource. * * @param {string} projectServiceServiceLevelObjectiveName * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service. */ matchServiceFromProjectServiceServiceLevelObjectiveName( projectServiceServiceLevelObjectiveName: string ) { return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( projectServiceServiceLevelObjectiveName ).service; } /** * Parse the service_level_objective from ProjectServiceServiceLevelObjective resource. * * @param {string} projectServiceServiceLevelObjectiveName * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( projectServiceServiceLevelObjectiveName: string ) { return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( projectServiceServiceLevelObjectiveName ).service_level_objective; } /** * Return a fully-qualified projectUptimeCheckConfig resource name string. * * @param {string} project * @param {string} uptime_check_config * @returns {string} Resource name string. */ projectUptimeCheckConfigPath(project: string, uptimeCheckConfig: string) { return this.pathTemplates.projectUptimeCheckConfigPathTemplate.render({ project: project, uptime_check_config: uptimeCheckConfig, }); } /** * Parse the project from ProjectUptimeCheckConfig resource. * * @param {string} projectUptimeCheckConfigName * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the project. */ matchProjectFromProjectUptimeCheckConfigName( projectUptimeCheckConfigName: string ) { return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( projectUptimeCheckConfigName ).project; } /** * Parse the uptime_check_config from ProjectUptimeCheckConfig resource. * * @param {string} projectUptimeCheckConfigName * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ matchUptimeCheckConfigFromProjectUptimeCheckConfigName( projectUptimeCheckConfigName: string ) { return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( projectUptimeCheckConfigName ).uptime_check_config; } /** * Terminate the gRPC channel and close the client. * * The client will no longer be usable and all future behavior is undefined. * @returns {Promise} A promise that resolves when the client is closed. */ close(): Promise<void> { this.initialize(); if (!this._terminated) { return this.notificationChannelServiceStub!.then(stub => { this._terminated = true; stub.close(); }); } return Promise.resolve(); } }
the_stack
import { isIterable, isFunction, isMissing } from "@esfx/internal-guards"; import { defineTag, Tag } from "@esfx/internal-tag"; import { CancelableSource, Cancelable, CancelSignal, CancelSubscription, CancelError } from "@esfx/cancelable"; import { LinkedList, LinkedListNode } from "@esfx/collections-linkedlist"; import { Disposable } from "@esfx/disposable"; export { CancelSubscription, CancelError } from "@esfx/cancelable"; interface CancelState { getState(): "unsignaled" | "signaled" | "closed"; subscribe(onSignaled: () => void): CancelSubscription; } interface CancelLinks { getLinkedState(): "unsignaled" | "signaled" | "closed"; unlink(): void; } function executeCallback(callback: () => void) { try { callback(); } catch (e) { // HostReportError(e); setImmediate(() => { throw e; }); } } function isSignaled(signal: CancelSignal) { return signal.signaled; } function canBeSignaled(signal: CancelSignal) { return signal !== Cancelable.none && (!(signal instanceof CancelToken) || signal.canBeSignaled); } const disposablePrototype: object = Object.getPrototypeOf(Disposable.create(() => { })); const cancelSourcePrototype: object = { [Cancelable.cancelSignal](this: CancelSource) { return this.token; }, [CancelableSource.cancel](this: CancelSource) { this.cancel(); }, }; Object.setPrototypeOf(cancelSourcePrototype, disposablePrototype); defineTag(cancelSourcePrototype, "CancelSource"); function createCancelSource(links: CancelLinks | undefined): CancelSource { let state: "unsignaled" | "signaled" | "closed" = "unsignaled"; let token: CancelToken | undefined; let subscriptions: LinkedList<() => void> | undefined; const source: CancelSource = Object.setPrototypeOf({ get token() { return token || (token = createCancelToken({ getState() { return state === "unsignaled" && links ? links.getLinkedState() : state; }, subscribe(onSignaled) { if (state === "closed") { return Cancelable.none.subscribe(onSignaled); } if (state === "signaled") { return Cancelable.canceled.subscribe(onSignaled); } const list = subscriptions || (subscriptions = new LinkedList()); return createCancelSubscription(list.push(onSignaled)); } })); }, cancel() { if (state !== "unsignaled") { return; } const currentLinks = links; const currentSubscriptions = subscriptions; state = "signaled"; links = undefined; subscriptions = undefined; if (currentLinks) { currentLinks.unlink(); } if (currentSubscriptions) { for (const node of [...currentSubscriptions.nodes()]) { // The registration for each callback holds onto the node, the node holds onto the // list, and the list holds all other nodes and callbacks. By removing the node from // the list, the GC can collect any otherwise unreachable nodes. if (node.detachSelf()) { executeCallback(node.value); node.value = undefined!; } } } }, close() { if (state !== "unsignaled") { return; } const currentLinks = links; const currentSubscriptions = subscriptions; state = "closed"; links = undefined; subscriptions = undefined; if (currentLinks) { currentLinks.unlink(); } if (currentSubscriptions) { for (const node of [...currentSubscriptions.nodes()]) { if (node.detachSelf()) { node.value = undefined!; } } } }, }, cancelSourcePrototype); Object.freeze(source); return source; } function createCancelSubscription(node: LinkedListNode<() => void>): CancelSubscription { return CancelSubscription.create(() => { if (node.detachSelf()) { node.value = undefined!; } }); } function createCancelToken(source: CancelState): CancelToken { const token = Object.create(CancelToken.prototype, { _state: { value: source } }); Object.freeze(token); return token; } // A source that cannot be canceled. const closedSource = createCancelSource(/*links*/ undefined); closedSource.close(); // A source that is already canceled. const canceledSource = createCancelSource(/*links*/ undefined); canceledSource.cancel(); /** * Signals a CancelToken when cancellation has been requested. */ export interface CancelSource extends CancelableSource, Disposable { /** * Gets the CancelToken linked to this source. */ readonly token: CancelToken; /** * Cancels the source, evaluating any subscribed callbacks. If any callback raises an exception, * the exception is propagated to a host specific unhanedle exception mechanism. */ cancel(): void; /** * Closes the source, preventing the possibility of future cancellation. */ close(): void; } /** * Propagates notifications that operations should be canceled. */ @Tag() export class CancelToken implements Cancelable, CancelSignal { static readonly none = closedSource.token; static readonly canceled = canceledSource.token; private _state!: CancelState; private constructor() { throw new TypeError("Object not creatable."); } /** * Gets a value indicating whether the token is signaled. */ get signaled() { return this._state.getState() === "signaled"; } /** * Gets a value indicating whether the token can be signaled. */ get canBeSignaled() { return this._state.getState() !== "closed"; } /** * Creates a new CancelSource. */ static source(): CancelSource { return createCancelSource(/*links*/ undefined); } /** * Gets a CancelToken from a cancelable. */ static from(cancelable: Cancelable | null | undefined) { if (!isMissing(cancelable) && !Cancelable.hasInstance(cancelable)) { throw new TypeError("Cancelable exepected: cancelable"); } if (cancelable === Cancelable.none || isMissing(cancelable)) { return CancelToken.none; } if (cancelable === Cancelable.canceled) { return CancelToken.canceled; } if (cancelable instanceof CancelToken) { return cancelable; } if (cancelSourcePrototype.isPrototypeOf(cancelable)) { return (cancelable as CancelSource).token; } const signal = cancelable[Cancelable.cancelSignal](); if (!canBeSignaled(signal)) { return CancelToken.none; } if (isSignaled(signal)) { return CancelToken.canceled; } let subscription: CancelSubscription | undefined; const source = createCancelSource({ getLinkedState() { return isSignaled(signal) ? "signaled" : canBeSignaled(signal) ? "unsignaled" : "closed"; }, unlink() { if (subscription) { subscription.unsubscribe(); subscription = undefined; } } }) subscription = signal.subscribe(source.cancel); return source.token; } /** * Returns a CancelToken that becomes signaled when **any** of the provided cancelables are signaled. * @param cancelables An iterable of Cancelable objects. */ static race(cancelables: Iterable<Cancelable>) { if (!isIterable(cancelables)) { throw new TypeError("Object not iterable: cancelables"); } const signals: CancelSignal[] = []; for (const cancelable of cancelables) { if (!Cancelable.hasInstance(cancelable)) throw new TypeError("Cancelable element expected: cancelables"); signals.push(cancelable[Cancelable.cancelSignal]()); } if (!signals.some(canBeSignaled)) { return CancelToken.none; } if (signals.some(isSignaled)) { return CancelToken.canceled; } const subscriptions: CancelSubscription[] = []; const source = createCancelSource({ getLinkedState() { if (signals.some(isSignaled)) return "signaled"; if (signals.every(canBeSignaled)) return "unsignaled"; return "closed"; }, unlink() { if (subscriptions.length > 0) { for (const subscription of subscriptions.splice(0, subscriptions.length)) { subscription.unsubscribe(); } } } }); for (const signal of signals) { subscriptions.push(signal.subscribe(source.cancel)); } return source.token; } /** * Returns a CancelToken that becomes signaled when **all** of the provided cancelables are signaled. * @param cancelables An iterable of Cancelable objects. */ static all(cancelables: Iterable<Cancelable>) { if (!isIterable(cancelables)) { throw new TypeError("Object not iterable: cancelables"); } const signals: CancelSignal[] = []; for (const cancelable of cancelables) { if (!Cancelable.hasInstance(cancelable)) throw new TypeError("Cancelable element expected: cancelables"); signals.push(cancelable[Cancelable.cancelSignal]()); } if (!signals.some(canBeSignaled)) { return CancelToken.none; } if (signals.every(isSignaled)) { return CancelToken.canceled; } let signalsRemaining = signals.length; const subscriptions: CancelSubscription[] = []; const source = createCancelSource({ getLinkedState() { if (signals.every(isSignaled)) return "signaled"; if (signals.every(canBeSignaled)) return "unsignaled"; return "closed"; }, unlink() { if (subscriptions.length > 0) { for (const subscription of subscriptions.splice(0, subscriptions.length)) { subscription.unsubscribe(); } } } }); for (const signal of signals) { let signaled = false; subscriptions.push(signal.subscribe(() => { if (!signaled) { signaled = true; signalsRemaining--; if (signalsRemaining === 0) { source.cancel(); } } })); } return source.token; } /** * Throws a CancelError if the token was signaled. */ throwIfSignaled() { if (this.signaled) { const error = new CancelError(); if (Error.captureStackTrace) { Error.captureStackTrace(error, throwIfSignaledMethod); } throw error; } } /** * Subscribes to notifications for when the object becomes signaled. */ subscribe(onSignaled: () => void): CancelSubscription { if (!isFunction(onSignaled)) throw new TypeError("Function expected: onSignaled"); return this._state.subscribe(onSignaled); } // #region Cancelable [Cancelable.cancelSignal](): CancelToken { return this; } // #endregion Cancelable } const throwIfSignaledMethod = CancelToken.prototype.throwIfSignaled;
the_stack
import { CancellationToken, Progress, ProgressLocation, Uri, window, workspace, WorkspaceConfiguration } from 'vscode'; import * as path from 'path'; import * as http from 'http'; import * as https from 'https'; import * as fse from 'fs-extra'; import * as _ from 'lodash'; import * as os from 'os'; import { getJavaProjects, getProjectType } from '../controller/utils'; import { IJavaTestItem, ProjectType, TestKind } from '../types'; import { createWriteStream, WriteStream } from 'fs'; import { URL } from 'url'; import { ClientRequest, IncomingMessage } from 'http'; import { sendError } from 'vscode-extension-telemetry-wrapper'; export async function enableTests(testKind?: TestKind): Promise<void> { const project: IJavaTestItem | undefined = await getTargetProject(); if (!project) { return; } const projectType: ProjectType = await getProjectType(project); switch (projectType) { case ProjectType.UnmanagedFolder: await setupUnmanagedFolder(Uri.parse(project.uri!), testKind); return; default: // currently other typed projects are not supported. break; } return; } async function getTargetProject(): Promise<IJavaTestItem | undefined> { let testProjects: IJavaTestItem[] = []; for (const workspaceFolder of workspace.workspaceFolders || [] ) { testProjects.push(...await getJavaProjects(workspaceFolder)); } testProjects = testProjects.filter((project: IJavaTestItem) => { return project.testKind === TestKind.None; }); if (testProjects.length === 0) { sendError(new Error('Failed to find a project to enable tests.')); return undefined; } // currently this feature will only be enabled when workspace contains one unmanaged folder without test dependencies. return testProjects[0]; } async function setupUnmanagedFolder(projectUri: Uri, testKind?: TestKind): Promise<void> { testKind ??= await getTestKind(); if (testKind === undefined) { return; } const libFolder: string = await getLibFolder(projectUri); const libFolderExists: boolean = await fse.pathExists(libFolder); if (!libFolderExists) { await fse.ensureDir(libFolder); } try { await window.withProgress({ location: ProgressLocation.Notification, cancellable: true }, async (progress: Progress<{message?: string; increment?: number}>, token: CancellationToken) => { const metadata: IArtifactMetadata[] = getJarIds(testKind!); for (const jar of metadata) { if (token.isCancellationRequested) { throw new Error('User cancelled'); } progress.report({ message: `Downloading ${jar.artifactId}.jar...`, }); if (!jar.version) { jar.version = await getLatestVersion(jar.groupId, jar.artifactId) || jar.defaultVersion; } await downloadJar(libFolder, jar.groupId, jar.artifactId, jar.version, metadata.length, progress, token); } }); } catch (e) { if (e?.message !== 'User cancelled') { sendError(e); } if (!libFolderExists) { fse.remove(libFolder); } return; } updateProjectSettings(projectUri, libFolder); } async function getTestKind(): Promise<TestKind | undefined> { const framework: any = await window.showQuickPick([{ label: 'JUnit Jupiter', value: TestKind.JUnit5, }, { label: 'JUnit', value: TestKind.JUnit, }, { label: 'TestNG', value: TestKind.TestNG, }], { placeHolder: 'Select the test framework to be enabled.' }); return framework?.value; } async function getLibFolder(projectUri: Uri): Promise<string> { const referencedLibraries: any = workspace.getConfiguration('java', projectUri).get('project.referencedLibraries'); if (_.isArray(referencedLibraries)) { // do a simple check if the project uses default lib location. if (referencedLibraries.includes('lib/**/*.jar')) { return path.join(projectUri.fsPath, 'lib'); } } for (let i: number = 0; i < 100; i++) { const folderPath: string = path.join(projectUri.fsPath, `test-lib${i > 0 ? i : ''}`); if (await fse.pathExists(folderPath)) { continue; } return folderPath; } return path.join(projectUri.fsPath, 'test-lib'); } function getJarIds(testKind: TestKind): IArtifactMetadata[] { switch (testKind) { case TestKind.JUnit5: return [{ groupId: 'org.junit.platform', artifactId: 'junit-platform-console-standalone', defaultVersion: '1.8.2', }]; case TestKind.JUnit: return [{ groupId: 'junit', artifactId: 'junit', defaultVersion: '4.13.2', }, { groupId: 'org.hamcrest', artifactId: 'hamcrest-core', version: '1.3', defaultVersion: '1.3', }]; case TestKind.TestNG: return [{ groupId: 'org.testng', artifactId: 'testng', defaultVersion: '7.5', }, { groupId: 'com.beust', artifactId: 'jcommander', defaultVersion: '1.82', }, { groupId: 'org.slf4j', artifactId: 'slf4j-api', defaultVersion: '1.7.35', }]; default: return []; } } async function getLatestVersion(groupId: string, artifactId: string): Promise<string | undefined> { try { const response: any = await getHttpsAsJSON(getQueryLink(groupId, artifactId)); if (!response.response?.docs?.[0]?.latestVersion) { sendError(new Error(`Invalid format for the latest version response`)); return undefined; } return response.response.docs[0].latestVersion; } catch (e) { sendError(new Error(`Failed to fetch the latest version for ${groupId}:${artifactId}`)); } return undefined; } async function downloadJar( libFolder: string, groupId: string, artifactId: string, version: string, totalJars: number, progress: Progress<{message?: string; increment?: number}>, token: CancellationToken ): Promise<void> { // tslint:disable-next-line: typedef await new Promise<void>(async (resolve, reject) => { progress.report({ message: `Downloading ${artifactId}-${version}.jar...`, }); const tempFilePath: string = path.join(os.tmpdir(), `${artifactId}-${version}.jar`); const writer: WriteStream = createWriteStream(tempFilePath); const url: string = getDownloadLink(groupId, artifactId, version); const totalSize: number = await getTotalBytes(url); if (token.isCancellationRequested) { writer.close(); return reject(new Error('User cancelled')); } const req: ClientRequest = https.get(url, (res: IncomingMessage) => { res.pipe(writer); res.on('data', (chunk: any) => { progress.report({ message: `Downloading ${artifactId}-${version}.jar...`, increment: chunk.length / totalSize / totalJars * 100, }); }); }); token.onCancellationRequested(() => { req.destroy(); writer.close(); fse.unlink(tempFilePath); reject(new Error('User cancelled')); }); req.on('error', (err: any) => { writer.close(); fse.unlink(tempFilePath); reject(err); }); writer.on('finish', () => { writer.close(); const filePath: string = path.join(libFolder, `${artifactId}-${version}.jar`); fse.move(tempFilePath, filePath, { overwrite: false }); return resolve(); }); writer.on('error', () => { writer.close(); fse.unlink(tempFilePath); reject(new Error('Failed to write jar file.')); }); }); } async function updateProjectSettings(projectUri: Uri, libFolder: string): Promise<void> { // if 'referenced libraries' is already set to 'lib/**/*.jar' if (path.basename(libFolder) === 'lib') { window.showInformationMessage("Test libraries have been downloaded into 'lib/'."); return; } const relativePath: string = path.relative(projectUri.fsPath, libFolder); const testDependencies: string = path.join(relativePath, '**', '*.jar'); const configuration: WorkspaceConfiguration = workspace.getConfiguration('java', projectUri); let referencedLibraries: any = configuration.get('project.referencedLibraries'); if (_.isArray(referencedLibraries)) { referencedLibraries.push(testDependencies); referencedLibraries = Array.from(new Set(referencedLibraries)); } else if (_.isObject(referencedLibraries)) { referencedLibraries = referencedLibraries as {include: string[]}; referencedLibraries.include.push(testDependencies); referencedLibraries.include = Array.from(new Set(referencedLibraries.include)); if (!referencedLibraries.exclude && !referencedLibraries.sources) { referencedLibraries = referencedLibraries.include; } } configuration.update('project.referencedLibraries', referencedLibraries); window.showInformationMessage(`Test libraries have been downloaded into '${relativePath}/'.`); } async function getHttpsAsJSON(link: string): Promise<any> { // tslint:disable-next-line: typedef const response: string = await new Promise<string>((resolve, reject) => { let result: string = ''; https.get(link, { headers: { 'User-Agent': 'vscode-JavaTestRunner/0.1', }, }, (res: http.IncomingMessage) => { if (res.statusCode !== 200) { return reject(new Error(`Request failed with status code: ${res.statusCode}`)); } res.on('data', (chunk: any) => { result = result.concat(chunk.toString()); }); res.on('end', () => { resolve(result); }); res.on('error', reject); }); }); return JSON.parse(response); } async function getTotalBytes(url: string): Promise<number> { // tslint:disable-next-line: typedef return new Promise<number>((resolve, reject) => { const link: URL = new URL(url); const req: ClientRequest = https.request({ host: link.host, path: link.pathname, method: 'HEAD' }, (res: http.IncomingMessage) => { const num: number = parseInt(res.headers['content-length'] as string, 10); resolve(num); }); req.on('error', reject); req.end(); }); } function getQueryLink(groupId: string, artifactId: string): string { return `https://search.maven.org/solrsearch/select?q=id:%22${groupId}:${artifactId}%22&rows=1&wt=json`; } function getDownloadLink(groupId: string, artifactId: string, version: string): string { return `https://repo1.maven.org/maven2/${groupId.split('.').join('/')}/${artifactId}/${version}/${artifactId}-${version}.jar` } interface IArtifactMetadata { groupId: string; artifactId: string; version?: string; defaultVersion: string; }
the_stack
import {array, extend, isArray, isObject, isString, Mark, Spec} from 'vega'; import MARK_EXTENTS from '../constants/markExtents'; import {State, store} from '../store'; import {GuideType} from '../store/factory/Guide'; import {applicationIsEnabled, InteractionRecord, MarkApplicationRecord} from '../store/factory/Interaction'; import {GroupRecord} from '../store/factory/marks/Group'; import {PipelineRecord} from '../store/factory/Pipeline'; import {WidgetRecord} from '../store/factory/Widget'; import {input} from '../util/dataset-utils'; import duplicate from '../util/duplicate'; import name from '../util/exportName'; import exportName from '../util/exportName'; import {propSg} from '../util/prop-signal'; import {signalLookup} from '../util/signal-lookup'; import {addApplicationToScene, addDatasetsToScene, addInputsToScene, addSelectionToScene, addVoronoiMark, addWidgetApplicationToScene, addWidgetSelectionToScene, getScaleInfoForGroup, pushSignalsInScene, getFieldsOfGroup} from './demonstrations'; import manipulators from './manipulators'; const json2csv = require('json2csv'), imutils = require('../util/immutable-utils'), getIn = imutils.getIn, getInVis = imutils.getInVis, ORDER = require('../constants/sortOrder'); const SPEC_COUNT = {data: {}, scales: {}, _totaled: false}, DATA_COUNT = {marks: {}, scales: {}}, SCALE_COUNT = {marks: {}, guides: {}}; // How many times data sources and scales have been used. let counts = duplicate(SPEC_COUNT); /** * Exports primitives in the redux store as a complete Vega specification. * * @param {boolean} [internal=false] Should Lyra-specific properties be * removed (e.g., converting property signal references to actual values). When * true, additional mark specifications are also added corresponding to the * direct-manipulation interactors (handles, connectors, etc.). * @returns {Object} A Vega specification. */ export function exporter(internal: boolean = false): Spec { const state = store.getState(); const int = internal === true; counts = duplicate(SPEC_COUNT); let spec: Spec = exporter.scene(state, int); spec.data = exporter.pipelines(state, int); // Add interactions and widgets from store spec = exporter.interactions(state, spec); spec = exporter.widgets(state, spec); return spec; } exporter.interactions = function(state: State, spec) { state.getIn(['vis', 'present', 'interactions']).forEach((interaction: InteractionRecord) => { const group: GroupRecord = state.getIn(['vis', 'present', 'marks', String(interaction.groupId)]); const groupName = exportName(group.name); const scaleInfo = getScaleInfoForGroup(state, group._id); const fieldsOfGroup = getFieldsOfGroup(state, group._id); const mouseTypes = group._interactions.map(interactionId => { const interaction: InteractionRecord = state.getIn(['vis', 'present', 'interactions', String(interactionId)]); if (!interaction.input) { return null; } return interaction.input.mouse; }).filter(x => x); const exclusive = (new Set(mouseTypes)).size !== mouseTypes.length; // if there's more than one drag, for example, drag should not activate when shift+drag activates spec = addDatasetsToScene(spec, groupName, interaction.id); spec = addInputsToScene(spec, groupName, interaction.id, interaction.input, scaleInfo, fieldsOfGroup, exclusive); if (interaction.selection) { spec = addSelectionToScene(spec, groupName, interaction.id, interaction.input, interaction.selection); } if (interaction.applications.length) { for (const application of interaction.applications) { if (!applicationIsEnabled(application, interaction)) continue; spec = addApplicationToScene(spec, groupName, interaction.id, interaction.input, application); if (interaction.input && interaction.input.mouse && interaction.input.mouse === 'mouseover' && interaction.input.nearest) { const targetMarkName = (application as any).targetMarkName; if (targetMarkName) { const encoding = interaction.selection && interaction.selection.type === 'point' ? interaction.selection.encoding : null; spec = addVoronoiMark(spec, groupName, encoding, targetMarkName, interaction.id, application.id); } } } } spec = pushSignalsInScene(spec, groupName, interaction.signals); }); return spec; } exporter.widgets = function(state: State, spec) { state.getIn(['vis', 'present', 'widgets']).forEach((widget: WidgetRecord) => { const group: GroupRecord = state.getIn(['vis', 'present', 'marks', String(widget.groupId)]); const groupName = exportName(group.name); if (widget.selection) { spec = addWidgetSelectionToScene(spec, widget, widget.selection); } if (widget.applications.length) { for (const application of widget.applications) { spec = addWidgetApplicationToScene(spec, groupName, widget, application); } } }); return spec; } exporter.pipelines = function(state: State, internal: boolean) { const pipelines: PipelineRecord[] = getInVis(state, 'pipelines').valueSeq(); return pipelines.reduce(function(spec, pipeline) { spec.push(exporter.dataset(state, internal, pipeline._source)); const aggrs = pipeline._aggregates.toJS(); for (const key in aggrs) { spec.push(exporter.dataset(state, internal, aggrs[key])); } return spec; }, []); }; exporter.dataset = function(state: State, internal: boolean, id: number) { const dataset = getInVis(state, 'datasets.' + id).toJS(), spec = clean(duplicate(dataset), internal), values = input(id), format = spec.format && spec.format.type, sort = exporter.sort(dataset); counts.data[id] = counts.data[id] || duplicate(DATA_COUNT); // Resolve dataset ID to name. // Only include the raw values in the exported spec if: // 1. We're re-rendering the Lyra view // 2. Raw values were provided by the user directly (i.e., no url/source). if (spec.source) { spec.source = name(getInVis(state, 'datasets.' + spec.source + '.name')); } else if (internal) { spec.values = values; delete spec.url; delete spec.format; // values are JSON, so do not need to be reparsed. } else if (!spec.url) { spec.values = format && format !== 'json' ? json2csv({data: values, del: format === 'tsv' ? '\t' : ','}) : values; } const interactions: InteractionRecord[] = state.getIn(['vis', 'present', 'interactions']).valueSeq().toArray(); const interactionSignals = [].concat.apply([], interactions.filter(interaction => interaction.signals.length).map(interaction => interaction.signals.map(signal => signal.signal))); const widgets: WidgetRecord[] = state.getIn(['vis', 'present', 'widgets']).valueSeq().toArray(); const widgetSignals = [].concat.apply([], widgets.filter(widget => widget.signals.length).map(widget => widget.signals.map(signal => signal.signal))); const signals = interactionSignals.concat(widgetSignals); spec.transform = spec.transform || []; if (sort !== undefined) { spec.transform.push(sort); } spec.transform.forEach(s => { if (s.type === 'lookup') { s.from = state.getIn(['vis', 'present', 'datasets', s.from, 'name']) } if (s.type === 'filter') { // if any of the interaction signals in the filter are undefined, just let everything pass signals.forEach(signal => { if (s.expr.indexOf(signal) >= 0) { s.expr = `(${signal} ? ${s.expr} : true)`; } }); } }) return spec; }; /** * Method that builds the vega sort data transform code from * the current dataset. * * @param {object} dataset The current dataset * @returns {object} undefined if _sort not in dataset and the * vega data transform code to be appended to the vega spec to * the dataset */ exporter.sort = function(dataset) { const sort = dataset._sort; if (!sort) { return; } return { type: 'sort', by: (sort.order === ORDER.DESC ? '-' : '') + sort.field }; }; exporter.scene = function(state: State, internal: boolean): Mark { const sceneId = state.getIn(['vis', 'present', 'scene', '_id']); let spec = exporter.group(state, internal, sceneId); if (internal) { spec = spec[0]; } // Remove mark-specific properties that do not apply to scenes. // delete spec.type; delete spec.from; delete spec.encode; return spec; }; exporter.mark = function(state: State, internal: boolean, id: number) { const mark = getInVis(state, 'marks.' + id).toJS(); const spec = clean(duplicate(mark), internal); const up = mark.encode.update; const upspec = spec.encode.update; const facet = mark._facet; if (facet) { spec.from = {data: facet.name}; } else if (spec.from) { let fromId; if ((fromId = spec.from.data)) { spec.from.data = name(getInVis(state, 'datasets.' + fromId + '.name')); const count = counts.data[fromId] || (counts.data[fromId] = duplicate(DATA_COUNT)); count.marks[id] = true; } else if ((fromId = spec.from.mark)) { spec.from.mark = name(getInVis(state, 'marks.' + fromId + '.name')); } } Object.keys(upspec).forEach(function(key) { let specVal = upspec[key]; const origVal = up[key]; const origScale = origVal.scale; if (!isObject(specVal)) { // signalRef resolved to literal specVal = upspec[key] = {value: specVal}; } // Use the origVal to determine if scale/fields have been set in case // specVal was replaced above (e.g., scale + signal). if (origScale) { specVal.scale = name(getInVis(state, 'scales.' + origScale + '.name')); const count = counts.scales[origScale] || (counts.scales[origScale] = duplicate(SCALE_COUNT)); count.marks[id] = true; } if (origVal.group) { specVal.field = {group: origVal.group}; delete specVal.group; } }); if (internal) { spec.role = `lyra_${mark._id}`; const s = manipulators(mark, spec); return facet ? pathgroup(state, s, facet) : s; } return facet ? pathgroup(state, spec, facet) : spec; }; function pathgroup(state, marks, facet) { return { name: 'pathgroup', type: 'group', from: { facet: { ...facet, data: name(getInVis(state, 'datasets.' + facet.data + '.name')) } }, encode: { update: { width: {field: {group: 'width'}}, height: {field: {group: 'height'}} } }, marks: array(marks) } } exporter.group = function(state: State, internal: boolean, id: number) { const mark: GroupRecord = getInVis(state, `marks.${id}`); const spec = exporter.mark(state, internal, id); const group = internal ? spec[0] : spec; ['scale', 'mark', 'axe', 'legend'].forEach(function(childType) { const childTypes = childType + 's', // Pluralized for spec key. storePath = childTypes === 'axes' || childTypes === 'legends' ? 'guides' : childTypes; // Route export to the most appropriate function. group[childTypes] = mark[childTypes] .map(cid => { const child = getInVis(state, `${storePath}.${cid}`); return !child ? null : exporter[child.type] ? exporter[child.type](state, internal, cid) : exporter[childType] ? exporter[childType](state, internal, cid) : clean(duplicate(child.toJS()), internal); }) .reduce((children, child) => { // If internal === true, children are an array of arrays which must be flattened. if (isArray(child)) { children.push.apply(children, child); } else if (child) { children.push(child); } return children; }, []); }); if (mark.name !== 'Scene') { // Add width/height signals so that nested scales span correctly. group.signals = group.signals || []; group.signals.push( {name: 'width', value: groupSize(mark, 'x')}, {name: 'height', value: groupSize(mark, 'y')}, ); } return spec; }; exporter.area = function(state: State, internal: boolean, id: number) { const spec = exporter.mark(state, internal, id); const area = array(spec.name === 'pathgroup' ? spec.marks : spec)[0]; const update = area.encode.update; // Export with dummy data to have an initial area appear on the canvas. if (!area.from) { area.from = {data: 'dummy_data'}; update.x = {signal: `datum.x + ${propSg(id, 'area', 'x')}`}; update.y = {signal: `datum.y + ${propSg(id, 'area', 'y')}`}; } if (update.orient.value === 'horizontal') { delete update.y2; } else { delete update.x2; } return spec; }; exporter.line = function(state: State, internal: boolean, id: number) { const spec = exporter.mark(state, internal, id); const line = array(spec.name === 'pathgroup' ? spec.marks : spec)[0]; const update = line.encode.update; // Export with dummy data to have an initial area appear on the canvas. if (!line.from) { line.from = {data: 'dummy_data'}; update.x = {signal: `datum.x + ${propSg(id, 'line', 'x')}`}; update.y = {signal: `datum.y + ${propSg(id, 'line', 'y')}`}; } return spec; }; exporter.scale = function(state: State, internal: boolean, id: number) { const scale = getInVis(state, 'scales.' + id).toJS(), spec = clean(duplicate(scale), internal); counts.scales[id] = counts.scales[id] || duplicate(SCALE_COUNT); if (!scale.domain && scale._domain && scale._domain.length ) { spec.domain = scale._manual && scale._manualDomain.length ? scale._manualDomain : dataRef(state, scale, scale._domain); } if (!scale.range && scale._range && scale._range.length) { spec.range = dataRef(state, scale, scale._range); } // TODO: Sorting multiple datasets? const sortOrder = isObject(spec.domain) && spec.domain._sortOrder; if (sortOrder) { spec.reverse = sortOrder === ORDER.DESC ? !spec.reverse : !!spec.reserve; } return spec; }; exporter.axe = exporter.legend = function(state: State, internal: boolean, id: number) { const guide = getInVis(state, 'guides.' + id).toJS(), spec = clean(duplicate(guide), internal), gtype = guide._gtype, type = guide._type; if (gtype === GuideType.Axis) { counts.scales[spec.scale].guides[id] = true; spec.scale = name(getInVis(state, 'scales.' + spec.scale + '.name')); } else if (gtype === GuideType.Legend) { counts.scales[spec[type]].guides[id] = true; spec[type] = name(getInVis(state, 'scales.' + spec[type] + '.name')); } Object.keys(spec.encode).forEach(function(prop) { const def = spec.encode[prop]; Object.keys(def).forEach(function(key) { if (!isObject(def[key])) { // signalRef resolved to literal def[key] = {value: def[key]}; } }); }); return spec; }; function groupSize(group, dimension: 'x' | 'y') { const update = group.encode.update, extents = MARK_EXTENTS[dimension]; // TODO: If these properties are scale bound. if (!update[extents.SPAN.name]._disabled) { return signalLookup(update[extents.SPAN.name].signal); } } /** * Utility method to clean a spec object by removing Lyra-specific keys * (i.e., those prefixed by an underscore). * * @param {Object} spec - A Lyra representation from the store. * @param {Boolean} internal - Whether to resolve signal references to values. * @returns {Object} A cleaned spec object */ function clean(spec, internal: boolean) { let cleanKey; for (const [key, prop] of Object.entries(spec)) { cleanKey = key.startsWith('_'); cleanKey = cleanKey || prop === null || prop === undefined || (prop as any)._disabled; if (cleanKey) { delete spec[key]; } else if (key === 'name' && isString(prop)) { spec[key] = name(prop); } else if (isObject(prop)) { if ((prop as any).signal && !internal) { // Render signals to their value if ((prop as any).signal.startsWith('lyra')) { spec[key] = signalLookup((prop as any).signal); } } else { // Recurse spec[key] = clean(spec[key], internal); } } } return spec; } export function getCounts(recount: boolean) { let key, entry; if (recount) { exporter(); } else if (counts._totaled) { return counts; } for (key in counts.data) { entry = counts.data[key]; entry.total = Object.keys(entry.marks).length + Object.keys(entry.scales).length; } for (key in counts.scales) { entry = counts.scales[key]; entry.markTotal = Object.keys(entry.marks).length; entry.guideTotal = Object.keys(entry.guides).length; entry.total = entry.markTotal + entry.guideTotal; } return (counts._totaled = true), counts; } /** * Utility method to export a list of fields to DataRefs. We don't default to * the last option, as the structure has performance implications in Vega. * Most to least performant: * {"data": ..., "field": ...} for a single field * {"data": ..., "fields": [...]} for multiple fields from the same dataset. * {"fields": [...]} for multiple fields from distinct datasets * * @param {object} state Redux state * @param {Object} scale The definition of the scale. * @param {Array} ref Array of fields * @returns {Object} A Vega DataRef */ function dataRef(state: State, scale, ref) { let sets = {}, data, did, field, i, len, keys; // One ref if (ref.length === 1) { ref = ref[0]; data = getInVis(state, 'datasets.' + ref.data); return sortDataRef(data, scale, ref.field); } // More than one ref for (i = 0, len = ref.length; i < len; ++i) { data = getInVis(state, 'datasets.' + ref[i].data); field = ref[i].field; sets[(did = data.get('_id'))] = sets[did] || (sets[did] = []); sets[did].push(field); } keys = Object.keys(sets); if (keys.length === 1) { return sortDataRef(data, scale, sets[did]); } ref = {fields: []}; for (i = 0, len = keys.length; i < len; ++i) { data = getInVis(state, 'datasets.' + keys[i]); ref.fields.push(sortDataRef(data, scale, sets[keys[i]])); } return ref; } function sortDataRef(data, scale, field) { let ref; if (Array.isArray(field)) { ref = { data: name(data.get('name')), fields: field }; } else { ref = { data: name(data.get('name')), field: field }; } if (scale.type === 'ordinal' && data.get('_sort')) { const sortField = getIn(data, '_sort.field'); return extend({}, ref, { sort: sortField === ref.field ? true : {field: sortField, op: 'min'}, _sortOrder: getIn(data, '_sort.order') }); } const dsId = data.get('_id'), count = counts.data[dsId] || (counts.data[dsId] = duplicate(DATA_COUNT)); count.scales[scale._id] = true; return ref; } module.exports.exportName = name; module.exports.counts = getCounts;
the_stack
import { Component, OnInit, OnDestroy, AfterViewInit, AfterViewChecked, OnChanges, SimpleChanges, ChangeDetectorRef, Input, Output, EventEmitter, ViewChild } from '@angular/core'; import { BsModalService } from 'ngx-bootstrap/modal'; import { NotificationService } from '../../../../../shared'; import { JhiEventManager } from 'ng-jhipster'; import { DataSourceService } from '../../../../data-source/data-source.service'; import { WidgetService } from 'app/entities/widget/widget.service'; import { HttpErrorResponse } from '@angular/common/http'; import { SelectComponent } from 'ng2-select'; import { Z_FIXED } from 'zlib'; /** * This component is used to render and configure a query paramter * inside a query template. */ @Component({ selector: 'query-parameter', templateUrl: './query-parameter.component.html', styleUrls: ['./query-parameter.component.scss'] }) export class QueryParameterComponent implements OnInit, OnDestroy, AfterViewInit, AfterViewChecked, OnChanges { @Input() queryWidgetId; @Input() dataSource; @Input() name; @Input() parameterDef: Object; @Input() readMode: boolean; @Output() parameterCompliantChange: EventEmitter<Object> = new EventEmitter(); isParamterDefinitionCompliant: boolean = false; parameterPanelCollapsed: boolean = false; tmpLabel: string = ''; labelEditingPopIsOpen: boolean = false; dataSourceMetadata: Object; @ViewChild(SelectComponent) valueSelectComponent: SelectComponent; // ngselect aux vars staticDomainDefinition: string; activeValues: Object[] = []; // faceting, used to define the values' domain through elastic faceting: Object; classes: string[]; fields: string[]; minDocCount: number = 1; maxValuesPerField: number = 1000; selectedClassProperties: string[] = []; panelHeadingHeight: string = '35px'; constructor(protected notificationService: NotificationService, protected dataSourceService: DataSourceService, protected eventManager: JhiEventManager, protected cdr: ChangeDetectorRef, protected modalService: BsModalService, protected widgetService: WidgetService) { } ngOnInit() { this.dataSourceService.loadMetadata(this.dataSource['id']).subscribe((dataSourceMetadata: Object) => { this.dataSourceMetadata = dataSourceMetadata; if (this.parameterDef['domain']['definitionType'] === 'dynamic-faceting') { // then we init the selectedClassProperties var this.selectedClassProperties = this.getClassProperties(this.parameterDef['domain']['class']); this.updateParamDomainFromFaceting(); } }, (error: HttpErrorResponse) => { this.handleError(error.error, 'Metadata loading'); }); } ngOnChanges(changes: SimpleChanges): void { if (changes['name'] && changes['parameterDef']) { if (!this.parameterDef['label']) { // first param loading, then we init the label with the name of the parameter this.parameterDef['label'] = changes['name']['currentValue']; } if (this.parameterDef['domain']['definitionType'] === 'static') { // then we init the string we use for the form used to edit the domain this.staticDomainDefinition = ''; this.parameterDef['domain']['set'].forEach((domainValue) => { this.staticDomainDefinition += domainValue + '\n'; }); } // loading active values for ngselect component this.fromStringValueToArray(this.parameterDef['value']).forEach((activeValue) => { activeValue = activeValue.replace('"', '').replace('"', ''); this.activeValues.push({ id: activeValue, text: activeValue }); }); } } ngOnDestroy() { this.detachListenersToValuesSelectDropdownMenu(); } ngAfterViewInit() { this.attachListenersToValuesSelectDropdownMenu(); } /** * Attaches listeners in order to display values select dropdown menu outside the container with overflow: hidden * The dropdown menu position is computed on: * - select input click * - scroll event inside the window */ attachListenersToValuesSelectDropdownMenu() { const selectElementId = '#selected_values_' + this.name; const selectInput = (<any>$(selectElementId + ' .ui-select-container')); // select input click selectInput.click(() => { this.selectInputScrollHandler(selectInput, selectElementId); }); // scroll events (<any>$('*')).on('scroll', () => { this.selectInputScrollHandler(selectInput, selectElementId); }); (<any>$(window)).on('scroll', () => { this.selectInputScrollHandler(selectInput, selectElementId); }); } /** * Detaches listeners in order to display values select dropdown menu outside the container with overflow: hidden * The dropdown menu position is computed on: * - select input click * - scroll event inside the window */ detachListenersToValuesSelectDropdownMenu() { const selectElementId = '#selected_values_' + this.name; const selectInput = (<any>$(selectElementId + ' .ui-select-container')); // select input click selectInput.unbind(); // scroll events (<any>$('*')).off('scroll', this.selectInputScrollHandler(selectInput, selectElementId)); (<any>$(window)).off('scroll', this.selectInputScrollHandler(selectInput, selectElementId)); } selectInputScrollHandler(selectInput, selectElementId) { const selectDropdownMenuId = selectElementId + ' .dropdown-menu'; if (selectInput.get(0)) { const coordinates = selectInput.offset(); const pageYOffset = window.pageYOffset; const top = selectInput.outerHeight() + coordinates.top - pageYOffset + 'px'; const left = coordinates.left; (<any>$(selectDropdownMenuId)).css({ 'position': 'fixed', 'top': top, 'left': left, 'width': selectInput.outerWidth(), 'max-height': '150px' }); } } ngAfterViewChecked() {} updateParamLabel() { this.parameterDef['label'] = this.tmpLabel; this.tmpLabel = ''; this.labelEditingPopIsOpen = false; } updateParamDomain() { switch (this.parameterDef['domain']['definitionType']) { case 'static': this.updateParamDomainFromStaticDef(); break; case 'dynamic-faceting': this.updateParamDomainFromFaceting(); break; case 'dynamic-query': this.updateParamDomainFromQuery(); break; } } updateParamDomainFromStaticDef() { this.parameterDef['domain']['set'] = this.fromStaticStringDomainToArray(this.staticDomainDefinition); if (this.parameterDef['domain']['set'].length > 0) { setTimeout(() => { this.attachListenersToValuesSelectDropdownMenu(); }, 100); } } fromStaticStringDomainToArray(values: string): string[] { return values .replace('[', '') .replace(']', '') .split('\n'); } fromStringValueToArray(values: string): string[] { if (values && values.length > 0) { return values .replace('[', '') .replace(']', '') .split(','); } return []; } updateParamDomainFromFaceting() { if (this.dataSource && this.dataSource['indexing'] && this.dataSource['indexing'].toString() === 'INDEXED') { if (this.dataSource['id']) { const classes: string[] = [this.parameterDef['domain']['class']]; const fields: string[] = [this.parameterDef['domain']['property']]; this.widgetService.fetchWholeFacetingForDatasource(this.dataSource['id'], classes, fields, this.minDocCount, this.maxValuesPerField) .subscribe((res: Object) => { this.faceting = res; const facetingClass = this.parameterDef['domain']['class']; const facetingProperty = this.parameterDef['domain']['property']; this.parameterDef['domain']['set'] = Object.keys(this.faceting[facetingClass]['propertyValues'][facetingProperty]); if (this.parameterDef['domain']['set'].length > 0) { setTimeout(() => { this.attachListenersToValuesSelectDropdownMenu(); }, 100); } }, (err: HttpErrorResponse) => { this.handleError(err.error, 'Faceting updating'); }); } else { // recursive call waiting that datasource id is loaded setTimeout(() => { this.updateParamDomainFromFaceting(); }, 20); } } } updateParamDomainFromQuery() { const json = { query: this.parameterDef['domain']['query'], datasetCardinality: 0, params: [] }; const jsonContent = JSON.stringify(json); this.widgetService.loadTabledata(this.queryWidgetId, jsonContent).subscribe((data) => { // update domain from data const columns = Object.keys(data['nodesClasses']['Table']['properties']); if (columns.length > 1) { const message = 'Too many columns returned in the resulset, cannot choose which column must to be considered for the domain definition.'; this.notificationService.push('error', 'Query Domain', message); } else { this.parameterDef['domain']['set'] = data['nodes'].map((node) => { return node['data']['record'][columns[0]] + ''; }); } if (this.parameterDef['domain']['set'].length > 0) { setTimeout(() => { this.attachListenersToValuesSelectDropdownMenu(); }, 100); } }, (error: HttpErrorResponse) => { this.handleError(error.error, 'Data loading'); }); } updateSelectedClassProperties() { this.parameterDef['domain']['property'] = undefined; this.selectedClassProperties = []; if (this.parameterDef['domain']['class']) { this.selectedClassProperties = this.getClassProperties(this.parameterDef['domain']['class']); } else { console.log('Cannot update properties as the selected class seems to be udefined.'); } if (this.selectedClassProperties.length === 0) { this.notificationService.push('warning', 'No Property found', 'No property found for the selected class.'); } } onParamTypeupdate() { this.parameterDef['value'] = ''; this.activeValues = []; if (this.parameterDef['type'] === 'free-text') { this.parameterDef['domain'] = {}; } else { if (!this.parameterDef['domain']['set']) { this.parameterDef['domain']['set'] = []; } if (this.parameterDef['domain']['set'] && this.parameterDef['domain']['set'].length > 0) { setTimeout(() => { this.attachListenersToValuesSelectDropdownMenu(); }, 100); } } } clearDomainAndValues() { this.parameterDef['value'] = ''; // cleaning select component active values and static domain values this.activeValues = []; this.staticDomainDefinition = ''; switch (this.parameterDef['domain']['definitionType']) { case 'static': this.parameterDef['domain']['set'] = []; delete this.parameterDef['domain']['query']; delete this.parameterDef['domain']['class']; delete this.parameterDef['domain']['property']; break; case 'dynamic-faceting': this.parameterDef['domain']['set'] = []; delete this.parameterDef['domain']['query']; this.parameterDef['domain']['class'] = undefined; this.parameterDef['domain']['property'] = undefined; break; case 'dynamic-query': this.parameterDef['domain']['set'] = []; delete this.parameterDef['domain']['class']; delete this.parameterDef['domain']['property']; this.parameterDef['domain']['query'] = undefined; break; } } getClassProperties(className: string): string[] { const classProperties: string[] = []; const classesMetadata = this.dataSourceMetadata['nodesClasses']; if (!classesMetadata) { console.error('[getClassProperties] class not found.'); return; } for (const propName of Object.keys(classesMetadata[className]['properties'])) { classProperties.push(propName); } return classProperties; } updateSelectParamValue() { const currSelectedValues = this.valueSelectComponent.active.map((selectItem) => { return selectItem['text']; }); this.parameterDef['value'] = JSON.stringify(currSelectedValues); if (this.readMode) { this.parameterCompliantChange.emit(); } } handleFixedParamValueChanging() { if (this.readMode) { this.parameterCompliantChange.emit(); } } /** * Check the settings and return true if the configuration is valid, otherwise false. */ isValid() { if (this.parameterDef['type'] && this.parameterDef['value']) { return true; } return false; } handleError(error: any, title: string) { let message: string = ''; if (error['detail']) { message = error['detail']; message = message.substring(0, 300) + ' ...'; } else if (error['_body']['detail']) { message = error['_body']['detail']; message = message.substring(0, 300) + ' ...'; } this.notificationService.push('error', title, message); } }
the_stack
import { Component, OnInit, OnDestroy, AfterViewInit, AfterViewChecked, OnChanges, SimpleChanges, ChangeDetectorRef, ViewChild, ViewChildren, QueryList } from '@angular/core'; import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal'; import { PrimaryWidget } from '../../primary-widget'; import { WidgetService } from '../../../widget.service'; import { NotificationService, Base64Service, Principal, WidgetEventBusService } from '../../../../../shared'; import * as $ from 'jquery'; import { Subscription } from 'rxjs'; import { JhiEventManager } from 'ng-jhipster'; import { DataWidgetComponent, FetchingMode } from '../datawidget.component'; import { DataSourceService } from '../../../../data-source/data-source.service'; import { DatasetUpdatedMessage, DatasetUpdatedMessageContent, SnapshotMenuComponent, TableComponent, SortingStatus } from '../../..'; import { SubsetSelectionChangeMessageContent, MessageType } from '../../../event-message'; import { DataSource } from 'app/entities/data-source'; import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Router } from '@angular/router'; import { QueryParameterComponent } from './query-parameter.component'; const elementResizeEvent = require('element-resize-event'); /** * This component allows users to build and save query templates, to run stated query and inspect * the actual resulset through a table perspective. */ @Component({ selector: 'query-widget', templateUrl: './querywidget.component.html', styleUrls: ['./querywidget.component.scss'] }) export class QueryWidgetComponent extends DataWidgetComponent implements PrimaryWidget, OnInit, OnDestroy, AfterViewInit, AfterViewChecked, OnChanges { subsetSelectionSubscription: Subscription; datasetPropagationRequestSubscription: Subscription; maxSidebarHeight: string; loadingGraphElements = []; // used to store new graph elements retrieved with the last query/snapshot loadingGraphElementsPositions = {}; // used to store new graph elements retrieved with the last snapshot // fetching mode appendLastResult: boolean = false; // querying queryLanguageSelection: string = 'OrientDB SQL'; supportedQueryLanguages: string[] = ['OrientDB SQL', 'SQL (RDBMS)']; lastLoadedData: Object; modalRef: BsModalRef; currentQuery: string = ''; skipIsolatedNodes: boolean = false; skipEdgesNotInDataset: boolean = false; includesNodesOfEdge: boolean = false; parametersName2Info: Object = {}; // Parameters components @ViewChildren(QueryParameterComponent) parameterComponents: QueryList<QueryParameterComponent>; // auto update autoUpdate: boolean = false; minimumTimeoutWindow: number; autoUpdateIntervalWindow: number; autoUpdateInterval; // timer used to trigger the new data fetching once the time window has completed autoUpdatePopover: string = `Use this flag to refresh data according to the last query.<br/> You can state the time interval by specifying the desired number of seconds in the form below.<br/> Append-last-result and auto-update flags cannot be both enabled.`; autoSwitchTabPopover: string = `Use this flag to automatically switch to the table perspective after query execution in order to inspect the result.<br/>`; // flag stating if the current dataset must be propagated to potential secondary widgets newDatasetToPropagate: boolean = false; // table data @ViewChild('tableComponent') tableComponent: TableComponent; lastLoadedColumns: Object[] = []; deletionEnabled: boolean = false; selectionEnabled: boolean = false; classNameColumnIncluded: boolean = false; // snapshot menu @ViewChild('snapshotMenu') snapshotMenu: SnapshotMenuComponent; // perspective queryTabActive: boolean = true; tableTabActive: boolean = false; datasourceTabActive: boolean = false; autoSwitchTabAfterQuery: boolean = false; public outerAccordion: string = 'outer-accordion'; public innerAccordion: string = 'inner-accordion'; // rows height queryLanguageRowHeight: string; queryRowHeight: string; paramsTitleHeight: string; parametersRowHeight: string; constructor(protected principal: Principal, protected widgetService: WidgetService, protected notificationService: NotificationService, protected dataSourceService: DataSourceService, protected eventManager: JhiEventManager, protected cdr: ChangeDetectorRef, protected modalService: BsModalService, protected base64Service: Base64Service, protected widgetEventBusService: WidgetEventBusService, protected router: Router) { super(principal, widgetService, notificationService, dataSourceService, eventManager, cdr, modalService, base64Service, widgetEventBusService, router); this.dataSourceMetadata = { nodesClasses: { Table: {} } }; this.subscribeToEventBus(); } subscribeToEventBus() { this.subsetSelectionSubscription = this.widgetEventBusService.getMessage(MessageType.SUBSET_SELECTION_CHANGE).subscribe((message) => { if (message.data['primaryWidgetId'] === this.widget.id) { this.onSubsetSelection(message.data); } }); this.datasetPropagationRequestSubscription = this.widgetEventBusService.getMessage(MessageType.DATASET_PROPAGATION_REQUEST).subscribe((message) => { if (message.data['primaryWidgetId'] === this.widget.id) { if (this.oldSnapshotToLoad && !this.snapshotLoaded) { // IGNORE THE MESSAGE: dataset will be propagated after the snapshot is loaded } else { this.propagateDatasetTo(message.data['secondaryWidgetId']); } } }); } unsubscribeToEventBus() { this.subsetSelectionSubscription.unsubscribe(); this.datasetPropagationRequestSubscription.unsubscribe(); } ngOnInit() { this.lastLoadedData = { elements: [] }; // widget id init this.widgetId = this.widget['id']; this.fileName = this.widget['name']; const datasourceId = this.widget['dataSourceId']; if (!this.embedded) { this.dataSourceService.find(datasourceId).subscribe((res: DataSource) => { this.dataSource = res; this.checkDatasourceIndexingAlert(); }); } if (this.oldSnapshotToLoad) { // load snapshot this.loadSnapshot(); } // initializing the search term observer this.searchTermObserver = this.searchTerm.subscribe((event) => { this.lastEmittedSearchTerm = event; }); this.registerChangeInDashboards(); // authorities and depending params init if (!this.embedded) { this.initParamsDependingOnUserIdentities(); } // autoupdate params init if (!this.embedded) { this.minimumTimeoutWindow = this.principal['userIdentity']['contract']['pollingInterval']; this.autoUpdateIntervalWindow = this.minimumTimeoutWindow; } } registerChangeInDashboards() { this.dashboardPanelResizedSubscriber = this.eventManager.subscribe( 'dashboardPanelResized', (response) => { if (response.content === this.widgetId) { console.log('Query widget #' + this.widgetId + ' detected resize in minimized view.'); } } ); } ngOnChanges(changes: SimpleChanges): void { } ngOnDestroy() { this.eventManager.destroy(this.dashboardPanelResizedSubscriber); this.unsubscribeToEventBus(); this.stopAutoUpdateInterval(); } ngAfterViewInit() { this.sidebarResetMenu(); // initialising rows heights according to the view mode this.updateViewportHeightsAccordingToWidgetHeight(); // sidebar height if (!this.embedded) { this.maxSidebarHeight = this.widgetHeight; } else { this.adjustWidgetHeightToEmbeddingIframeHeight(); } // possible overflow handling this.tooltipOnOverflow(); // attach listener to resize event const elementId = '#widget-viewport_' + this.widgetId; const element = $(elementId).get(0); elementResizeEvent(element, () => { this.updateViewportHeightsAccordingToWidgetHeight(); }); if (this.minimizedView) { // hide tabs (<any>$('.widget-viewport .tab-container ul')).css('display', 'none'); } } ngAfterViewChecked() { } updateViewportHeightsAccordingToWidgetHeight() { this.queryRowHeight = '25%'; if (this.minimizedView) { this.queryLanguageRowHeight = '0px'; this.paramsTitleHeight = '0px'; this.parametersRowHeight = parseInt(this.widgetHeight.replace('px', ''), 10) - parseInt(this.queryLanguageRowHeight.replace('px', ''), 10) - parseInt(this.paramsTitleHeight.replace('px', ''), 10) + 'px'; } else { this.queryLanguageRowHeight = '18%'; this.paramsTitleHeight = '8%'; this.parametersRowHeight = '49%'; } } /** * It updated parameters list according to the current query */ handleQueryChange(event?) { if (this.currentQuery.indexOf(':') < 0 && Object.keys(this.parametersName2Info).length > 0) { this.parametersName2Info = {}; } if (this.currentQuery.indexOf(':') >= 0) { const queryWords = this.currentQuery.split(/\s+/) .filter((word) => { if (word.indexOf(':') >= 0) { return true; } return false; }).map((word) => { return word.replace(':', ''); }); // removing no more present parameters for (const paramName of Object.keys(this.parametersName2Info)) { if (queryWords.indexOf(paramName) < 0) { delete this.parametersName2Info[paramName]; } } // adding new params if not already present queryWords.forEach((queryWord) => { if (!this.parametersName2Info[queryWord]) { this.parametersName2Info[queryWord] = { value: undefined, type: undefined, domain: { set: [] } }; } }); } } /** * It catches changings of the contained parameters and saves the current widget status if in minimized view. */ handleParameterCompliantChange() { if (this.minimizedView) { this.saveAll(true); } } /** * Perspective */ switchTab(justChosenTab: string) { if (justChosenTab === 'query') { this.queryTabActive = true; this.tableTabActive = false; this.datasourceTabActive = false; } else if (justChosenTab === 'table') { this.queryTabActive = false; this.tableTabActive = true; this.datasourceTabActive = false; } else if (justChosenTab === 'datasource') { this.queryTabActive = false; this.tableTabActive = false; this.datasourceTabActive = true; } } /** * Theme limitless */ sidebarResetMenu() { // Add 'active' class to parent list item in all levels $('.navigation').find('li.active').parents('li').addClass('active'); // Hide all nested lists $('.navigation').find('li').not('.active, .category-title').has('ul').children('ul').addClass('hidden-ul'); // Highlight children links $('.navigation').find('li').has('ul').children('a').addClass('has-ul'); $('.navigation-main').find('li').has('ul').children('a').unbind('click'); $('.navigation-main').find('li').has('ul').children('a').on('click', function(e) { e.preventDefault(); // Collapsible $(this).parent('li') .not('.disabled') .not($('.sidebar-xs') .not('.sidebar-xs-indicator') .find('.navigation-main') .children('li')) .toggleClass('active') .children('ul') .slideToggle(250); // Accordion if ($('.navigation-main').hasClass('navigation-accordion')) { $(this).parent('li') .not('.disabled') .not($('.sidebar-xs') .not('.sidebar-xs-indicator') .find('.navigation-main') .children('li')) .siblings(':has(.has-ul)') .removeClass('active') .children('ul') .slideUp(250); } }); this.toggleOverflowMenu(); } tooltipOnOverflow() { (<any>$('.mightOverflow')).bind('mouseover', function() { const $this = $(this); const width = (<any>$('span')).width(); if (this.offsetWidth > width && !$this.attr('title')) { $this.attr('title', $this.text()); } }); } toggleSideBar() { if (this.sidebarCollapsed) { this.expandSidebar(); } else { this.collapseSidebar(); } } checkSidebarStatusOnExit() { if (this.sidebarCollapsed) { (<any>$('body')).removeClass('sidebar-xs'); } } collapseSidebar() { const initialSidebarSize = (<any>$('.sidebar')).width(); (<any>$('body')).addClass('sidebar-xs'); const finalSidebarSize = (<any>$('.sidebar')).width(); this.sidebarCollapsed = !this.sidebarCollapsed; this.toggleOverflowMenu(); } expandSidebar() { const initialSidebarSize = (<any>$('.sidebar')).width(); (<any>$('body')).removeClass('sidebar-xs'); const finalSidebarSize = (<any>$('.sidebar')).width(); this.sidebarCollapsed = !this.sidebarCollapsed; this.toggleOverflowMenu(); } toggleOverflowMenu() { if (this.sidebarCollapsed) { // remove 'vertical-overflow-scroll' from element with 'cell-content-wrapper' class $('#sidebar-dynamic').removeClass('vertical-overflow-scroll'); // add 'submenu-vertical-overflow' to element with 'hidden-ul' class $('.hidden-ul').addClass('submenu-vertical-overflow'); } else { // add 'vertical-overflow-scroll' to element with 'cell-content-wrapper' class $('#sidebar-dynamic').addClass('vertical-overflow-scroll'); // remove 'submenu-vertical-overflow' from element with 'hidden-ul' class $('.hidden-ul').removeClass('submenu-vertical-overflow'); } } /** * Data loading */ clearQuery() { this.currentQuery = ''; } loadElementsFromClasses(propagateNewDataset?: boolean) { // DO NOTHING FOR NOW } loadNodesFromIds(nodeIds: string[], propagateNewDataset?: boolean) { // DO NOTHING FOR NOW } loadDataFromQuery(query: string, propagateNewDataset?: boolean) { // DO NOTHING FOR NOW } loadDataFromCurrentQuery(propagateNewDataset?: boolean) { if (this.currentQuery) { let canExecuteQuery: boolean = true; let parametricQuery: boolean = true; // if there are parameters we have to check their validity if (this.parameterComponents.length > 0) { for (const currParameter of this.parameterComponents.toArray()) { if (!currParameter.isValid()) { canExecuteQuery = false; parametricQuery = false; const message = '\'' + currParameter['name'] + '\' parameter is not well defined. Cannot perform the query, please check the parameter definition and try again.'; this.notificationService.push('warning', 'Wrong Parameter definition', message); break; } } } else { parametricQuery = false; } if (canExecuteQuery) { this.loadTableData(this.currentQuery, propagateNewDataset, parametricQuery); } } else { this.notificationService.push('error', 'Query', 'Query not correctly specified. Please check the query again.'); } } loadTableData(query: string, propagateNewDataset: boolean, parametricQuery: boolean) { const queryParams: Object[] = []; if (parametricQuery) { for (const parameterName of Object.keys(this.parametersName2Info)) { queryParams.push({ name: parameterName, type: this.parametersName2Info[parameterName]['type'], value: this.parametersName2Info[parameterName]['value'], }); } } const json = { query: query, datasetCardinality: 0, params: queryParams }; const jsonContent = JSON.stringify(json); this.startSpinner(); this.widgetService.loadTabledata(this.widget['id'], jsonContent).subscribe((data) => { this.stopSpinner(); // update dataset and metadata this.updateQueryWidgetData(data); this.updateQueryMetadataFromData(data); if (!this.minimizedView && this.autoSwitchTabAfterQuery) { this.switchTab('table'); } // propagating the new current dataset if requested if (propagateNewDataset && this.minimizedView) { this.propagateDatasetMulticastChange(); } // saving the widget if in minimized view in order to keep the last retrieved dataset // propagated to the potential secondary widgets and avoid inconsistency if (this.minimizedView) { this.saveAll(true); } }, (error: HttpErrorResponse) => { this.stopSpinner(); this.handleError(error.error, 'Data loading'); }); } loadSnapshot() { if (this.embedded) { // use the open service to load the snapshot this.widgetService.loadSnapshotForEmbeddedWidget(this.widget['uuid']).subscribe((snapshot: Object) => { this.performSnapshotLoading(snapshot); }, (error: HttpErrorResponse) => { this.stopSpinner(); this.notificationService.push('error', 'Widget not available', this.notSharedWidgetMessage); }); } else { // use the closed service to load the snpashot this.widgetService.loadSnapshot(this.widgetId).subscribe((snapshot: Object) => { this.startSpinner(); this.performSnapshotLoading(snapshot); }, (error: HttpErrorResponse) => { this.stopSpinner(); this.handleError(error.error, 'Snapshot loading'); }); } } performSnapshotLoading(snapshot) { setTimeout(() => { // small timeout just to allow spinner to start, otherwise cy loading interferes with angular variable // update process and the spinner does not start this.updateQueryWidgetFromSnapshot(snapshot); this.snapshotLoaded = true; }, 10); } updateQueryWidgetFromSnapshot(snapshot) { this.newDatasetToPropagate = snapshot['newDatasetToPropagate']; if (this.newDatasetToPropagate && this.minimizedView) { this.propagateDatasetMulticastChangeFromSnapshot(snapshot); this.newDatasetToPropagate = false; } if (snapshot['queryLanguageSelection']) { this.queryLanguageSelection = snapshot['queryLanguageSelection']; } // Loading metadata this.dataSourceMetadata = snapshot['dataSourceMetadata']; this.appendLastResult = snapshot['appendLastResult']; // Loading data if (snapshot['lastLoadedData']) { this.lastLoadedData = snapshot['lastLoadedData']; } if (snapshot['lastLoadedColumns']) { this.lastLoadedColumns = snapshot['lastLoadedColumns']; } if (!this.minimizedView && snapshot['perspective']) { this.queryTabActive = snapshot['perspective']['queryTabActive']; this.tableTabActive = snapshot['perspective']['tableTabActive']; this.datasourceTabActive = snapshot['perspective']['datasourceTabActive']; } if (snapshot['currentQuery']) { this.currentQuery = snapshot['currentQuery']; } if (snapshot['parametersName2Info']) { this.parametersName2Info = snapshot['parametersName2Info']; } // Auto Update if (snapshot['autoUpdate'] !== undefined) { this.autoUpdate = snapshot['autoUpdate']; } if (snapshot['autoUpdateIntervalWindow']) { this.autoUpdateIntervalWindow = snapshot['autoUpdateIntervalWindow']; } if (this.autoUpdate) { this.startAutoUpdateInterval(); } // auto switch to table tab after query if (snapshot['autoSwitchTabAfterQuery']) { this.autoSwitchTabAfterQuery = snapshot['autoSwitchTabAfterQuery']; } this.stopSpinner(); } handleAppendLastResultChange() { // append-last-result flag cannot work with auto update, as they are mutual exclusive if (this.autoUpdate) { this.switchAutoUpdate(); } } switchAutoUpdate() { this.autoUpdate = !this.autoUpdate; this.handleAutoUpdateFlagChange(); } handleAutoUpdateFlagChange() { if (this.autoUpdate) { // trigger the timeout this.startAutoUpdateInterval(); // auto-update cannot work with append-last-result flag, as they are mutual exclusive if (this.appendLastResult) { this.appendLastResult = false; } } else { // stop the timeout this.stopAutoUpdateInterval(); } } startAutoUpdateInterval() { this.autoUpdateInterval = setInterval(() => { this.performLastDataFetching(); }, this.autoUpdateIntervalWindow * 1000); } stopAutoUpdateInterval() { clearInterval(this.autoUpdateInterval); } handleAutoUpdateIntervalChange() { setTimeout(() => { if (!this.autoUpdateIntervalWindow || this.autoUpdateIntervalWindow < this.minimumTimeoutWindow) { this.autoUpdateIntervalWindow = this.minimumTimeoutWindow; $('#autoUpdateIntervalWindow').val(this.autoUpdateIntervalWindow); } if (this.autoUpdate) { // stop the old interval this.stopAutoUpdateInterval(); // start a new interval according to the new current time window this.startAutoUpdateInterval(); } }, 500); } performLastDataFetching() { const propagateNewDataset: boolean = true; this.loadDataFromCurrentQuery(propagateNewDataset); } /** * Used to propagate a dataset change in multicast to all the secondary widgets. It's performed after the snapshot loading in the minimized view. * @param snapshot */ propagateDatasetMulticastChangeFromSnapshot(snapshot: Object): void { const elements = snapshot['lastLoadedData']['elements']; const cleanedDatasourceMetadata = this.cleanDatasourceMetadataForSecondaryWidget(snapshot['dataSourceMetadata'], elements); const content: DatasetUpdatedMessageContent = this.buildDatasetMessageContent(elements, cleanedDatasourceMetadata); this.widgetEventBusService.publish(MessageType.DATASET_UPDATED_MESSAGE, new DatasetUpdatedMessage(content)); } /** * Used to propagate a dataset change in multicast to all the secondary widgets starting from the current widget dataset and metadata. */ propagateDatasetMulticastChange() { if (this.lastLoadedData && this.lastLoadedData['elements'].length > 0 && this.dataSourceMetadata) { const elements = this.lastLoadedData['elements']; const cleanedDatasourceMetadata = this.cleanDatasourceMetadataForSecondaryWidget(this.dataSourceMetadata, elements); const content: DatasetUpdatedMessageContent = this.buildDatasetMessageContent(elements, cleanedDatasourceMetadata); this.widgetEventBusService.publish(MessageType.DATASET_UPDATED_MESSAGE, new DatasetUpdatedMessage(content)); } } /** * Used to propagate dataset after a request from a specific secondary widget. */ propagateDatasetTo(secondaryWidgetId: number) { const elements: Object[] = this.lastLoadedData['elements']; const cleanedDatasourceMetadata = this.cleanDatasourceMetadataForSecondaryWidget(this.dataSourceMetadata, elements); const content: DatasetUpdatedMessageContent = this.buildDatasetMessageContent(elements, cleanedDatasourceMetadata, secondaryWidgetId); this.widgetEventBusService.publish(MessageType.DATASET_UPDATED_MESSAGE, new DatasetUpdatedMessage(content)); } buildDatasetMessageContent(elements: Object[], dataSourceMetadata: Object, secondaryWidgetId?: number): DatasetUpdatedMessageContent { const content: DatasetUpdatedMessageContent = { primaryWidgetId: this.widget.id, secondaryWidgetId: secondaryWidgetId, data: elements, metadata: dataSourceMetadata }; return content; } cleanDatasourceMetadataForSecondaryWidget(dataSourceMetadata: Object, elements: Object[]): Object { return super.cleanDatasourceMetadataForSecondaryWidget(dataSourceMetadata, elements); } getEmptyWidgetMessageHeight() { const widgetHeight: number = parseInt(this.widgetHeight.replace('px', ''), 10); const top: string = widgetHeight / 3 + 'px'; return top; } /** * It adds data elements (single vertices and edges) * to the instance variables if not present yet. * @param data */ updateQueryWidgetData(data) { /* * Elements */ // saving class name inside data object and setting 'selectable' with the default value (true) data['nodes'].forEach((elem) => { elem['data']['class'] = elem['classes']; elem['selectable'] = true; // whether the selection state is mutable (default true) }); if (this.appendLastResult) { this.lastLoadedData['elements'] = this.lastLoadedData['elements'].concat(data['nodes']).concat(data['edges']); } else { this.lastLoadedData['elements'] = data['nodes'].concat(data['edges']); } // updating to-save and new-dataset-to-propagate flags this.toSave = true; this.newDatasetToPropagate = true; } /** * It updates datasource metadata starting from the data retrieved through: * - nodes loading by ids * - nodes fetching per class */ updateQueryMetadataFromData(data) { // updating node class properties with the new entering nodes just loaded const tableClassMetadata = data['nodesClasses']['Table']['properties']; if (!this.appendLastResult) { // clearing the last prop info this.dataSourceMetadata['nodesClasses']['Table']['properties'] = {}; this.dataSourceMetadata['nodesClasses']['Table']['cardinality'] = 0; } for (const currProperty of Object.keys(tableClassMetadata)) { const newEnteringPropertyMetadata = { name: currProperty, type: tableClassMetadata[currProperty] }; this.dataSourceMetadata['nodesClasses']['Table']['properties'][currProperty] = newEnteringPropertyMetadata; } // cardinality updating this.dataSourceMetadata['nodesClasses']['Table']['cardinality'] += data['nodesClasses']['Table']['cardinality']; // last classes and columns updating if (!this.appendLastResult) { this.lastLoadedColumns = []; } if (data['nodesClasses'] && data['nodesClasses']['Table']['properties']) { const newTableColumns: Object[] = []; const properties = Object.keys(data['nodesClasses']['Table']['properties']); for (const propertyName of properties) { const currProperty = data['nodesClasses']['Table']['properties'][propertyName]; const currPropertyInfo = { className: 'Table', name: propertyName, type: currProperty['type'], included: true, sortingStatus: SortingStatus.NOT_SORTED }; newTableColumns.push(currPropertyInfo); } const finalColumns = new Set(this.lastLoadedColumns.concat(newTableColumns)); this.lastLoadedColumns = Array.from(finalColumns); } } /** * Event bus methods */ onSubsetSelection(message: SubsetSelectionChangeMessageContent) { // DO NOTHING FOR NOW } /** * It performs all the operations that must be performed after the indexing process completion. */ performOperationsAfterIndexingComplete() { // faceting update this.updateParametersFacetings(); } updateParametersFacetings() { // TODO } /** * It's called to update the input elements for the table component when occurs: * - elements selection/unselection * - elements showing/hiding * - elements adding in the current dataset * - elements removing from the current dataset * All the elements will be included, then the set is ordere according to selection order. */ updateLoadedElements() { this.lastLoadedData['elements'] = [...this.lastLoadedData['elements']]; // just to make the update visible to the table child component } /* * Save/export functions, snapshot loading */ // saves both data and metadata saveAll(hideNotification?: boolean) { let infoNotification; if (!hideNotification) { infoNotification = this.notificationService.push('info', 'Save', 'Saving the widget...', 3000, 'fa fa-spinner fa-spin'); } const delay: number = 10; setTimeout(() => { // just to avoid the saving ops block the first notification message const json = { queryLanguageSelection: this.queryLanguageSelection, lastLoadedData: this.lastLoadedData, lastLoadedColumns: this.lastLoadedColumns, dataSourceMetadata: this.dataSourceMetadata, newDatasetToPropagate: this.newDatasetToPropagate, appendLastResult: this.appendLastResult, currentQuery: this.currentQuery, parametersName2Info: this.parametersName2Info, autoUpdate: this.autoUpdate, autoUpdateIntervalWindow: this.autoUpdateIntervalWindow, autoSwitchTabAfterQuery: this.autoSwitchTabAfterQuery }; const perspective: Object = { queryTabActive: this.queryTabActive, tableTabActive: this.tableTabActive, datasourceTabActive: this.datasourceTabActive, }; json['perspective'] = perspective; const jsonContent = JSON.stringify(json); this.widgetService.updateWidget(this.widgetId, jsonContent).subscribe((res: HttpResponse<any>) => { if (res.status === 200 || res.status === 204) { if (infoNotification) { const message: string = 'Data correctly saved.'; this.notificationService.updateNotification(infoNotification, 'success', 'Save', message, undefined, true); } // updating to-save flag this.toSave = false; // updating snapshot-menu if (this.snapshotMenu) { this.snapshotMenu.loadSnapshotsNames(); } } else { if (infoNotification) { const message = 'Saving attempt failed.\n' + 'Response status: ' + res.status; this.notificationService.updateNotification(infoNotification, 'error', 'Save', message, undefined, true); } } }, (error: HttpErrorResponse) => { if (infoNotification) { this.notificationService.updateNotification(infoNotification, 'error', 'Save', 'Saving attempt failed.', undefined, true); } console.log(error.error); }); }, delay); } }
the_stack
import './strings.m.js'; import './tab.js'; import './tab_group.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {addWebUIListener, removeWebUIListener, WebUIListener} from 'chrome://resources/js/cr.m.js'; import {FocusOutlineManager} from 'chrome://resources/js/cr/ui/focus_outline_manager.m.js'; import {CustomElement} from 'chrome://resources/js/custom_element.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.m.js'; import {isRTL} from 'chrome://resources/js/util.m.js'; import {DragManager, DragManagerDelegate} from './drag_manager.js'; import {isTabElement, TabElement} from './tab.js'; import {isDragHandle, isTabGroupElement, TabGroupElement} from './tab_group.js'; import {Tab, TabGroupVisualData} from './tab_strip.mojom-webui.js'; import {TabsApiProxy, TabsApiProxyImpl} from './tabs_api_proxy.js'; /** * The amount of padding to leave between the edge of the screen and the active * tab when auto-scrolling. This should leave some room to show the previous or * next tab to afford to users that there more tabs if the user scrolls. */ const SCROLL_PADDING: number = 32; let scrollAnimationEnabled: boolean = true; const TOUCH_CONTEXT_MENU_OFFSET_X: number = 8; const TOUCH_CONTEXT_MENU_OFFSET_Y: number = -40; /** * Context menu should position below the element for touch. */ function getContextMenuPosition(element: Element): {x: number, y: number} { const rect = element.getBoundingClientRect(); return { x: rect.left + TOUCH_CONTEXT_MENU_OFFSET_X, y: rect.bottom + TOUCH_CONTEXT_MENU_OFFSET_Y }; } export function setScrollAnimationEnabledForTesting(enabled: boolean) { scrollAnimationEnabled = enabled; } enum LayoutVariable { VIEWPORT_WIDTH = '--tabstrip-viewport-width', TAB_WIDTH = '--tabstrip-tab-thumbnail-width', } /** * Animates a series of elements to indicate that tabs have moved position. */ function animateElementMoved( movedElement: Element, prevIndex: number, newIndex: number) { // Direction is -1 for moving towards a lower index, +1 for moving // towards a higher index. If moving towards a lower index, the TabList needs // to animate everything from the movedElement's current index to its prev // index by traversing the nextElementSibling of each element because the // movedElement is now at a preceding position from all the elements it has // slid across. If moving towards a higher index, the TabList needs to // traverse the previousElementSiblings. const direction = Math.sign(newIndex - prevIndex); function getSiblingToAnimate(element: Element): Element|null { return direction === -1 ? element.nextElementSibling : element.previousElementSibling; } let elementToAnimate = getSiblingToAnimate(movedElement); for (let i = newIndex; i !== prevIndex && elementToAnimate; i -= direction) { const elementToAnimatePrevIndex = i; const elementToAnimateNewIndex = i - direction; slideElement( elementToAnimate, elementToAnimatePrevIndex, elementToAnimateNewIndex); elementToAnimate = getSiblingToAnimate(elementToAnimate); } slideElement(movedElement, prevIndex, newIndex); } /** * Animates the slide of an element across the tab strip (both vertically and * horizontally for pinned tabs, and horizontally for other tabs and groups). */ function slideElement(element: Element, prevIndex: number, newIndex: number) { let horizontalMovement = newIndex - prevIndex; let verticalMovement = 0; if (isTabElement(element) && (element as TabElement).tab.pinned) { const pinnedTabsPerColumn = 3; const columnChange = Math.floor(newIndex / pinnedTabsPerColumn) - Math.floor(prevIndex / pinnedTabsPerColumn); horizontalMovement = columnChange; verticalMovement = (newIndex - prevIndex) - (columnChange * pinnedTabsPerColumn); } horizontalMovement *= isRTL() ? -1 : 1; const translateX = `calc(${horizontalMovement * -1} * ` + '(var(--tabstrip-tab-width) + var(--tabstrip-tab-spacing)))'; const translateY = `calc(${verticalMovement * -1} * ` + '(var(--tabstrip-tab-height) + var(--tabstrip-tab-spacing)))'; (element as TabElement | TabGroupElement).isValidDragOverTarget = false; const animation = element.animate( [ {transform: `translate(${translateX}, ${translateY})`}, {transform: 'translate(0, 0)'}, ], { duration: 120, easing: 'ease-out', }); function onComplete() { (element as TabElement | TabGroupElement).isValidDragOverTarget = true; } animation.oncancel = onComplete; animation.onfinish = onComplete; } export class TabListElement extends CustomElement implements DragManagerDelegate { animationPromises: Promise<void>; private currentScrollUpdateFrame_: number|null; private documentVisibilityChangeListener_: () => void; private draggedItem_?: TabElement|TabGroupElement; private dropPlaceholder_: HTMLElement; private focusOutlineManager_: FocusOutlineManager; private thumbnailTracker_: Map<number, boolean>; private intersectionObserver_: IntersectionObserver; private activatingTabId_?: number; private activatingTabIdTimestamp_?: number; // In ms. private eventTracker_: EventTracker; private lastTargetedItem_: TabElement|TabGroupElement|null = null; private lastTouchPoint_?: {clientX: number, clientY: number}; private pinnedTabsElement_: Element; private tabsApi_: TabsApiProxy; private unpinnedTabsElement_: Element; private webUIListeners_: WebUIListener[]; private windowBlurListener_: () => void; private scrollingTimeoutId_: number; private scrollListener_: (e: Event) => void; static get template() { return `{__html_template__}`; } constructor() { super(); /** * A chain of promises that the tab list needs to keep track of. The chain * is useful in cases when the list needs to wait for all animations to * finish in order to get accurate pixels (such as getting the position of a * tab) or accurate element counts. */ this.animationPromises = Promise.resolve(); /** * The ID of the current animation frame that is in queue to update the * scroll position. */ this.currentScrollUpdateFrame_ = null; this.documentVisibilityChangeListener_ = () => this.onDocumentVisibilityChange_(); /** * The element that is currently being dragged. */ this.draggedItem_; this.dropPlaceholder_ = document.createElement('div'); this.dropPlaceholder_.id = 'dropPlaceholder'; this.focusOutlineManager_ = FocusOutlineManager.forDocument(document); /** * Map of tab IDs to whether or not the tab's thumbnail should be tracked. */ this.thumbnailTracker_ = new Map(); /** * An intersection observer is needed to observe which TabElements are * currently in view or close to being in view, which will help determine * which thumbnails need to be tracked to stay fresh and which can be * untracked until they become visible. */ this.intersectionObserver_ = new IntersectionObserver(entries => { for (const entry of entries) { this.thumbnailTracker_.set( (entry.target as TabElement).tab.id, entry.isIntersecting); } if (this.scrollingTimeoutId_ === -1) { // If there is no need to wait for scroll to end, immediately process // and request thumbnails. this.flushThumbnailTracker_(); } }, { root: this, // The horizontal root margin is set to 100% to also track thumbnails that // are one standard finger swipe away. rootMargin: '0% 100%', }); this.eventTracker_ = new EventTracker(); this.pinnedTabsElement_ = this.$('#pinnedTabs')!; this.tabsApi_ = TabsApiProxyImpl.getInstance(); this.unpinnedTabsElement_ = this.$('#unpinnedTabs')!; this.webUIListeners_ = []; this.windowBlurListener_ = () => this.onWindowBlur_(); /** * Timeout that is created at every scroll event and is either canceled at * each subsequent scroll event or resolves after a few milliseconds after * the last scroll event. */ this.scrollingTimeoutId_ = -1; this.scrollListener_ = (e) => this.onScroll_(e); this.addWebUIListener_('theme-changed', () => { // Refetch theme colors, group color and tab favicons on theme change. this.fetchAndUpdateColors_(); this.fetchAndUpdateGroupData_(); this.fetchAndUpdateTabs_(); }); this.tabsApi_.observeThemeChanges(); const callbackRouter = this.tabsApi_.getCallbackRouter(); callbackRouter.layoutChanged.addListener( this.applyCSSDictionary_.bind(this)); callbackRouter.tabThumbnailUpdated.addListener( this.tabThumbnailUpdated_.bind(this)); callbackRouter.longPress.addListener(() => this.handleLongPress_()); callbackRouter.contextMenuClosed.addListener( () => this.clearLastTargetedItem_()); callbackRouter.receivedKeyboardFocus.addListener( () => this.onReceivedKeyboardFocus_()); this.eventTracker_.add( document, 'contextmenu', e => this.onContextMenu_(e)); this.eventTracker_.add( document, 'pointerup', e => this.onPointerUp_(e as PointerEvent)); this.eventTracker_.add( document, 'visibilitychange', () => this.onDocumentVisibilityChange_()); this.eventTracker_.add(window, 'blur', () => this.onWindowBlur_()); this.eventTracker_.add(this, 'scroll', e => this.onScroll_(e)); this.eventTracker_.add( document, 'touchstart', e => this.onTouchStart_(e as TouchEvent)); // Touchmove events happen when a user has started a touch gesture sequence // and proceeded to move their touch pointer across the screen. Ensure that // we clear the `last_targeted_item_` in these cases to ensure the pressed // visual is cleared away. this.eventTracker_.add( document, 'touchmove', () => this.clearLastTargetedItem_()); const dragManager = new DragManager(this); dragManager.startObserving(); } private addAnimationPromise_(promise: Promise<void>) { this.animationPromises = this.animationPromises.then(() => promise); } private addWebUIListener_(eventName: string, callback: Function) { this.webUIListeners_.push(addWebUIListener(eventName, callback)); } private animateScrollPosition_(scrollBy: number) { if (this.currentScrollUpdateFrame_) { cancelAnimationFrame(this.currentScrollUpdateFrame_); this.currentScrollUpdateFrame_ = null; } const prevScrollLeft = this.scrollLeft; if (!scrollAnimationEnabled || !this.tabsApi_.isVisible()) { // Do not animate if tab strip is not visible. this.scrollLeft = prevScrollLeft + scrollBy; return; } const duration = 350; let startTime: number; const onAnimationFrame = (currentTime: number) => { const startScroll = this.scrollLeft; if (!startTime) { startTime = currentTime; } const elapsedRatio = Math.min(1, (currentTime - startTime) / duration); // The elapsed ratio should be decelerated such that the elapsed time // of the animation gets less and less further apart as time goes on, // giving the effect of an animation that slows down towards the end. When // 0ms has passed, the decelerated ratio should be 0. When the full // duration has passed, the ratio should be 1. const deceleratedRatio = 1 - (1 - elapsedRatio) / Math.pow(2, 6 * elapsedRatio); this.scrollLeft = prevScrollLeft + (scrollBy * deceleratedRatio); this.currentScrollUpdateFrame_ = deceleratedRatio < 1 ? requestAnimationFrame(onAnimationFrame) : null; }; this.currentScrollUpdateFrame_ = requestAnimationFrame(onAnimationFrame); } private applyCSSDictionary_(dictionary: {[key: string]: string}) { for (const [cssVariable, value] of Object.entries(dictionary)) { this.style.setProperty(cssVariable, value); } } private clearScrollTimeout_() { clearTimeout(this.scrollingTimeoutId_); this.scrollingTimeoutId_ = -1; } connectedCallback() { this.tabsApi_.getLayout().then( ({layout}) => this.applyCSSDictionary_(layout)); this.fetchAndUpdateColors_(); const getTabsStartTimestamp = Date.now(); this.tabsApi_.getTabs().then(({tabs}) => { this.tabsApi_.reportTabDataReceivedDuration( tabs.length, Date.now() - getTabsStartTimestamp); const createTabsStartTimestamp = Date.now(); tabs.forEach(tab => this.onTabCreated_(tab)); this.fetchAndUpdateGroupData_(); this.tabsApi_.reportTabCreationDuration( tabs.length, Date.now() - createTabsStartTimestamp); const callbackRouter = this.tabsApi_.getCallbackRouter(); callbackRouter.showContextMenu.addListener( () => this.onShowContextMenu_()); callbackRouter.tabCreated.addListener(this.onTabCreated_.bind(this)); callbackRouter.tabMoved.addListener(this.onTabMoved_.bind(this)); callbackRouter.tabRemoved.addListener(this.onTabRemoved_.bind(this)); callbackRouter.tabReplaced.addListener(this.onTabReplaced_.bind(this)); callbackRouter.tabUpdated.addListener(this.onTabUpdated_.bind(this)); callbackRouter.tabActiveChanged.addListener( this.onTabActivated_.bind(this)); callbackRouter.tabCloseCancelled.addListener( this.onTabCloseCancelled_.bind(this)); callbackRouter.tabGroupStateChanged.addListener( this.onTabGroupStateChanged_.bind(this)); callbackRouter.tabGroupClosed.addListener( this.onTabGroupClosed_.bind(this)); callbackRouter.tabGroupMoved.addListener( this.onTabGroupMoved_.bind(this)); callbackRouter.tabGroupVisualsChanged.addListener( this.onTabGroupVisualsChanged_.bind(this)); }); } disconnectedCallback() { this.webUIListeners_.forEach(removeWebUIListener); this.eventTracker_.removeAll(); } private createTabElement_(tab: Tab): TabElement { const tabElement = new TabElement(); tabElement.tab = tab; tabElement.onTabActivating = (id) => { this.onTabActivating_(id); }; return tabElement; } private findTabElement_(tabId: number): TabElement|null { return this.$<TabElement>(`tabstrip-tab[data-tab-id="${tabId}"]`); } private findTabGroupElement_(groupId: string): TabGroupElement|null { return this.$<TabGroupElement>( `tabstrip-tab-group[data-group-id="${groupId}"]`); } private fetchAndUpdateColors_() { this.tabsApi_.getColors().then( ({colors}) => this.applyCSSDictionary_(colors)); } private fetchAndUpdateGroupData_() { const tabGroupElements = this.$all<TabGroupElement>('tabstrip-tab-group'); this.tabsApi_.getGroupVisualData().then(({data}) => { tabGroupElements.forEach(tabGroupElement => { tabGroupElement.updateVisuals( assert(data[tabGroupElement.dataset.groupId!])!); }); }); } private fetchAndUpdateTabs_() { this.tabsApi_.getTabs().then(({tabs}) => { tabs.forEach(tab => this.onTabUpdated_(tab)); }); } private getActiveTab_(): TabElement|null { return this.$<TabElement>('tabstrip-tab[active]'); } getIndexOfTab(tabElement: TabElement): number { return Array.prototype.indexOf.call(this.$all('tabstrip-tab'), tabElement); } /** @return in pixels */ private getLayoutVariable_(variable: LayoutVariable): number { return parseInt(this.style.getPropertyValue(variable), 10); } private handleLongPress_() { if (this.lastTargetedItem_) { this.lastTargetedItem_.setTouchPressed(true); } } private onContextMenu_(event: Event) { // Prevent the default context menu from triggering. event.preventDefault(); } private onPointerUp_(event: PointerEvent) { event.stopPropagation(); if (event.pointerType !== 'touch' && event.button === 2) { // If processing an uncaught right click event show the background context // menu. this.tabsApi_.showBackgroundContextMenu(event.clientX, event.clientY); } } private onDocumentVisibilityChange_() { if (!this.tabsApi_.isVisible()) { this.scrollToActiveTab_(); } this.unpinnedTabsElement_.childNodes.forEach(element => { if (isTabGroupElement(element as Element)) { element.childNodes.forEach( tabElement => this.updateThumbnailTrackStatus_(tabElement as TabElement)); } else { this.updateThumbnailTrackStatus_(element as TabElement); } }); } private onReceivedKeyboardFocus_() { // FocusOutlineManager relies on the most recent event fired on the // document. When the tab strip first gains keyboard focus, no such event // exists yet, so the outline needs to be explicitly set to visible. this.focusOutlineManager_.visible = true; this.$<TabElement>('tabstrip-tab')!.focus(); } private onTabActivated_(tabId: number) { if (this.activatingTabId_ === tabId) { this.tabsApi_.reportTabActivationDuration( Date.now() - this.activatingTabIdTimestamp_!); } this.activatingTabId_ = undefined; this.activatingTabIdTimestamp_ = undefined; // There may be more than 1 TabElement marked as active if other events // have updated a Tab to have an active state. For example, if a // tab is created with an already active state, there may be 2 active // TabElements: the newly created tab and the previously active tab. this.$all<TabElement>('tabstrip-tab[active]') .forEach((previouslyActiveTab) => { if (previouslyActiveTab.tab.id !== tabId) { previouslyActiveTab.tab = /** @type {!Tab} */ ( Object.assign({}, previouslyActiveTab.tab, {active: false})); } }); const newlyActiveTab = this.findTabElement_(tabId); if (newlyActiveTab) { newlyActiveTab.tab = Object.assign({}, newlyActiveTab.tab, {active: true}); if (!this.tabsApi_.isVisible()) { this.scrollToTab_(newlyActiveTab); } } } private onTabActivating_(id: number) { assert(this.activatingTabId_ === undefined); const activeTab = this.getActiveTab_(); if (activeTab && activeTab.tab.id === id) { return; } this.activatingTabId_ = id; this.activatingTabIdTimestamp_ = Date.now(); } private onTabCloseCancelled_(id: number) { const tabElement = this.findTabElement_(id); if (!tabElement) { return; } tabElement.resetSwipe(); } private onShowContextMenu_() { // If we do not have a touch point don't show the context menu. if (!this.lastTouchPoint_) { return; } if (this.lastTargetedItem_ && isTabElement(this.lastTargetedItem_)) { const position = getContextMenuPosition(this.lastTargetedItem_); this.tabsApi_.showTabContextMenu( (this.lastTargetedItem_ as TabElement).tab.id, position.x, position.y); } else { this.tabsApi_.showBackgroundContextMenu( this.lastTouchPoint_.clientX, this.lastTouchPoint_.clientY); } } private onTabCreated_(tab: Tab) { const droppedTabElement = this.findTabElement_(tab.id); if (droppedTabElement) { droppedTabElement.tab = tab; droppedTabElement.setDragging(false); this.tabsApi_.setThumbnailTracked(tab.id, true); return; } const tabElement = this.createTabElement_(tab); this.placeTabElement(tabElement, tab.index, tab.pinned, tab.groupId); this.addAnimationPromise_(tabElement.slideIn()); if (tab.active) { this.scrollToTab_(tabElement); } } private onTabGroupClosed_(groupId: string) { const tabGroupElement = this.findTabGroupElement_(groupId); if (!tabGroupElement) { return; } tabGroupElement.remove(); } private onTabGroupMoved_(groupId: string, index: number) { const tabGroupElement = this.findTabGroupElement_(groupId); if (!tabGroupElement) { return; } this.placeTabGroupElement(tabGroupElement, index); } private onTabGroupStateChanged_( tabId: number, index: number, groupId: string) { const tabElement = this.findTabElement_(tabId)!; tabElement.tab = Object.assign({}, tabElement.tab, {groupId: groupId}); this.placeTabElement(tabElement, index, false, groupId); } private onTabGroupVisualsChanged_( groupId: string, visualData: TabGroupVisualData) { const tabGroupElement = this.findTabGroupElement_(groupId)!; tabGroupElement.updateVisuals(visualData); } private onTabMoved_(tabId: number, newIndex: number, pinned: boolean) { const movedTab = this.findTabElement_(tabId); if (movedTab) { this.placeTabElement(movedTab, newIndex, pinned, movedTab.tab.groupId); if (movedTab.tab.active) { this.scrollToTab_(movedTab); } } } private onTabRemoved_(tabId: number) { const tabElement = this.findTabElement_(tabId); if (tabElement) { this.addAnimationPromise_(tabElement.slideOut()); } } private onTabReplaced_(oldId: number, newId: number) { const tabElement = this.findTabElement_(oldId); if (!tabElement) { return; } tabElement.tab = Object.assign({}, tabElement.tab, {id: newId}); } private onTabUpdated_(tab: Tab) { const tabElement = this.findTabElement_(tab.id); if (!tabElement) { return; } const previousTab = tabElement.tab; tabElement.tab = tab; if (previousTab.pinned !== tab.pinned) { // If the tab is being pinned or unpinned, we need to move it to its new // location this.placeTabElement(tabElement, tab.index, tab.pinned, tab.groupId); if (tab.active) { this.scrollToTab_(tabElement); } this.updateThumbnailTrackStatus_(tabElement); } } private onWindowBlur_() { if (this.shadowRoot!.activeElement) { // Blur the currently focused element when the window is blurred. This // prevents the screen reader from momentarily reading out the // previously focused element when the focus returns to this window. (this.shadowRoot!.activeElement as HTMLElement).blur(); } } private onScroll_(e: Event) { this.clearScrollTimeout_(); this.scrollingTimeoutId_ = setTimeout(() => { this.flushThumbnailTracker_(); this.clearScrollTimeout_(); }, 100); } private onTouchStart_(event: TouchEvent) { const composedPath = event.composedPath() as Element[]; const dragOverTabElement = (composedPath.find(isTabElement) || composedPath.find(isTabGroupElement) || null) as TabElement | TabGroupElement | null; // Make sure drag handle is under touch point when dragging a tab group. if (dragOverTabElement && isTabGroupElement(dragOverTabElement) && !composedPath.find(isDragHandle)) { return; } this.lastTargetedItem_ = dragOverTabElement; const touch = event.changedTouches[0]!; this.lastTouchPoint_ = {clientX: touch.clientX, clientY: touch.clientY}; } private clearLastTargetedItem_() { if (this.lastTargetedItem_) { this.lastTargetedItem_.setTouchPressed(false); } this.lastTargetedItem_ = null; this.lastTouchPoint_ = undefined; } placeTabElement( element: TabElement, index: number, pinned: boolean, groupId?: string) { const isInserting = !element.isConnected; const previousIndex = isInserting ? -1 : this.getIndexOfTab(element); const previousParent = element.parentElement; this.updateTabElementDomPosition_(element, index, pinned, groupId); if (!isInserting && previousParent === element.parentElement) { // Only animate if the tab is being moved within the same parent. Tab // moves that change pinned state or grouped states do not animate. animateElementMoved(element, previousIndex, index); } if (isInserting) { this.updateThumbnailTrackStatus_(element); } } placeTabGroupElement(element: TabGroupElement, index: number) { const previousDomIndex = Array.from(this.unpinnedTabsElement_.children).indexOf(element); if (element.isConnected && element.childElementCount && this.getIndexOfTab(element.firstElementChild as TabElement) < index) { // If moving after its original position, the index value needs to be // offset by 1 to consider itself already attached to the DOM. index++; } let elementAtIndex = this.$all('tabstrip-tab')[index]!; if (elementAtIndex && elementAtIndex.parentElement && isTabGroupElement(elementAtIndex.parentElement)) { elementAtIndex = elementAtIndex.parentElement; } this.unpinnedTabsElement_.insertBefore(element, elementAtIndex); // Animating the TabGroupElement move should be treated the same as // animating a TabElement. Therefore, treat indices as if they were mere // tabs and do not use the group's model index as they are not as accurate // in representing DOM movements. animateElementMoved( element, previousDomIndex, Array.from(this.unpinnedTabsElement_.children).indexOf(element)); } private flushThumbnailTracker_() { this.thumbnailTracker_.forEach((shouldTrack, tabId) => { this.tabsApi_.setThumbnailTracked(tabId, shouldTrack); }); this.thumbnailTracker_.clear(); } private scrollToActiveTab_() { const activeTab = this.getActiveTab_(); if (!activeTab) { return; } this.scrollToTab_(activeTab); } private scrollToTab_(tabElement: TabElement) { const tabElementWidth = this.getLayoutVariable_(LayoutVariable.TAB_WIDTH); const tabElementRect = tabElement.getBoundingClientRect(); // In RTL languages, the TabElement's scale animation scales from right to // left. Therefore, the value of its getBoundingClientRect().left may not be // accurate of its final rendered size because the element may not have // fully scaled to the left yet. const tabElementLeft = isRTL() ? tabElementRect.right - tabElementWidth : tabElementRect.left; const leftBoundary = SCROLL_PADDING; let scrollBy = 0; if (tabElementLeft === leftBoundary) { // Perfectly aligned to the left. return; } else if (tabElementLeft < leftBoundary) { // If the element's left is to the left of the left boundary, scroll // such that the element's left edge is aligned with the left boundary. scrollBy = tabElementLeft - leftBoundary; } else { const tabElementRight = tabElementLeft + tabElementWidth; const rightBoundary = this.getLayoutVariable_(LayoutVariable.VIEWPORT_WIDTH) - SCROLL_PADDING; if (tabElementRight > rightBoundary) { scrollBy = (tabElementRight) - rightBoundary; } else { // Perfectly aligned to the right. return; } } this.animateScrollPosition_(scrollBy); } shouldPreventDrag(): boolean { return this.$all('tabstrip-tab').length === 1; } private tabThumbnailUpdated_(tabId: number, imgData: string) { const tab = this.findTabElement_(tabId); if (tab) { tab.updateThumbnail(imgData); } } private updateTabElementDomPosition_( element: TabElement, index: number, pinned: boolean, groupId?: string) { // Remove the element if it already exists in the DOM. This simplifies // the way indices work as it does not have to count its old index in // the initial layout of the DOM. element.remove(); if (pinned) { this.pinnedTabsElement_.insertBefore( element, this.pinnedTabsElement_.childNodes[index]!); } else { let elementToInsert: TabElement|TabGroupElement = element; let elementAtIndex: TabElement|TabGroupElement = this.$all<TabElement>('tabstrip-tab').item(index); let parentElement = this.unpinnedTabsElement_; if (groupId) { let tabGroupElement = this.findTabGroupElement_(groupId); if (tabGroupElement) { // If a TabGroupElement already exists, add the TabElement to it. parentElement = tabGroupElement; } else { // If a TabGroupElement does not exist, create one and add the // TabGroupElement into the DOM. tabGroupElement = document.createElement('tabstrip-tab-group'); tabGroupElement.setAttribute('data-group-id', groupId); tabGroupElement.appendChild(element); elementToInsert = tabGroupElement; } } if (elementAtIndex && elementAtIndex.parentElement && isTabGroupElement(elementAtIndex.parentElement) && (elementAtIndex.previousElementSibling === null && elementAtIndex.tab.groupId !== groupId)) { // If the element at the model index is in a group, and the group is // different from the new tab's group, and is the first element in its // group, insert the new element before its TabGroupElement. If a // TabElement is being sandwiched between two TabElements in a group, it // can be assumed that the tab will eventually be inserted into the // group as well. elementAtIndex = elementAtIndex.parentElement as TabGroupElement; } if (elementAtIndex && elementAtIndex.parentElement === parentElement) { parentElement.insertBefore(elementToInsert, elementAtIndex); } else { parentElement.appendChild(elementToInsert); } } } private updateThumbnailTrackStatus_(tabElement: TabElement) { if (!tabElement.tab) { return; } if (this.tabsApi_.isVisible() && !tabElement.tab.pinned) { // If the tab strip is visible and the tab is not pinned, let the // IntersectionObserver start observing the TabElement to automatically // determine if the tab's thumbnail should be tracked. this.intersectionObserver_.observe(tabElement); } else { // If the tab strip is not visible or the tab is pinned, the tab does not // need to show or update any thumbnails. this.intersectionObserver_.unobserve(tabElement); this.tabsApi_.setThumbnailTracked(tabElement.tab.id, false); } } } declare global { interface HTMLElementTagNameMap { 'tabstrip-tab-list': TabListElement; } } customElements.define('tabstrip-tab-list', TabListElement);
the_stack
import Authorize from './authorize'; import BaseClient from './baseclient'; import Caching from './caching'; import IndexedDB from './indexeddb'; import InMemoryStorage from './inmemorystorage'; import LocalStorage from './localstorage'; import EventHandling from './eventhandling'; import GoogleDrive from './googledrive'; import Dropbox from './dropbox'; import SyncError from './sync-error'; import UnauthorizedError from './unauthorized-error'; import * as util from './util'; interface RSModule { name: string; builder: Function; } /** * Constructor for the remoteStorage object/instance * * This class primarily contains feature detection code and convenience API. * * Depending on which features are built in, it contains different attributes * and functions. See the individual features for more information. * * @param {object} config - an optional configuration object * @class */ declare class RemoteStorage { /** * Pending get/put/delete calls * @private */ _pending: { [key: string]: any; }[]; /** * TODO: document */ _cleanups: []; /** * TODO: document */ _pathHandlers: { [key: string]: any; }; /** * Holds OAuth app keys for Dropbox, Google Drive */ apiKeys: object; /** * Holds the feature class instance, added by feature initialization * TODO use type Access */ access: any; /** * Holds the feature class instance, added by feature initialization * TODO use type Sync */ sync: any; /** * Holds the feature class instance, added by feature initialization */ caching: Caching; _syncTimer: any; syncStopped: any; get: any; put: any; delete: any; backend: 'remotestorage' | 'dropbox' | 'googledrive'; /** * Holds a WireClient instance, added by feature initialization * TODO use correct type */ remote: any; local: IndexedDB | LocalStorage | InMemoryStorage; dropbox: Dropbox; googledrive: GoogleDrive; fireInitial: Function; on: any; constructor(cfg?: object); /** * Indicating if remoteStorage is currently connected. */ get connected(): boolean; static Authorize: typeof Authorize; static SyncError: typeof SyncError; static Unauthorized: typeof UnauthorizedError; static DiscoveryError: (message: any) => void; static util: typeof util; /** * Load all modules passed as arguments * @private */ loadModules(): void; /** * Initiate the OAuth authorization flow. * * This function is called by custom storage backend implementations * (e.g. Dropbox or Google Drive). * * @param {object} options * @param {string} options.authURL - URL of the authorization endpoint * @param {string} [options.scope] - access scope * @param {string} [options.clientId] - client identifier (defaults to the * origin of the redirectUri) * @private */ authorize(options: { authURL: string; scope?: string; clientId?: string; redirectUri?: string; }): void; /** * TODO: document * @private */ impliedauth(storageApi?: string, redirectUri?: string): void; /** * @property {object} remote * * Depending on the chosen backend, this is either an instance of ``WireClient``, * ``Dropbox`` or ``GoogleDrive``. * * @property {boolean} remote.connected - Whether or not a remote store is connected * @property {boolean} remote.online - Whether last sync action was successful or not * @property {string} remote.userAddress - The user address of the connected user * @property {string} remote.properties - The properties of the WebFinger link */ /** * Connect to a remoteStorage server. * * Discovers the WebFinger profile of the given user address and initiates * the OAuth dance. * * This method must be called *after* all required access has been claimed. * When using the connect widget, it will call this method itself. * * Special cases: * * 1. If a bearer token is supplied as second argument, the OAuth dance * will be skipped and the supplied token be used instead. This is * useful outside of browser environments, where the token has been * acquired in a different way. * * 2. If the Webfinger profile for the given user address doesn't contain * an auth URL, the library will assume that client and server have * established authorization among themselves, which will omit bearer * tokens in all requests later on. This is useful for example when using * Kerberos and similar protocols. * * @param {string} userAddress - The user address (user@host) to connect to. * @param {string} token - (optional) A bearer token acquired beforehand */ connect(userAddress: string, token?: string): void; /** * Reconnect the remote server to get a new authorization. */ reconnect(): void; /** * "Disconnect" from remote server to terminate current session. * * This method clears all stored settings and deletes the entire local * cache. */ disconnect(): void; /** * TODO: document * @private */ setBackend(what: any): void; /** * Add a "change" event handler to the given path. Whenever a "change" * happens (as determined by the backend, such as e.g. * <RemoteStorage.IndexedDB>) and the affected path is equal to or below the * given 'path', the given handler is called. * * You should usually not use this method directly, but instead use the * "change" events provided by :doc:`BaseClient </js-api/base-client>` * * @param {string} path - Absolute path to attach handler to * @param {function} handler - Handler function */ onChange(path: string, handler: Function): void; /** * TODO: do we still need this, now that we always instantiate the prototype? * * Enable remoteStorage logging. */ enableLog(): void; /** * TODO: do we still need this, now that we always instantiate the prototype? * * Disable remoteStorage logging */ disableLog(): void; /** * log * * The same as <RemoteStorage.log>. */ log(...args: any[]): void; /** * Set the OAuth key/ID for either GoogleDrive or Dropbox backend support. * * @param {Object} apiKeys - A config object with these properties: * @param {string} [apiKeys.type] - Backend type: 'googledrive' or 'dropbox' * @param {string} [apiKeys.key] - Client ID for GoogleDrive, or app key for Dropbox */ setApiKeys(apiKeys: { [key in ApiKeyType]?: string; }): void | boolean; /** * Set redirect URI to be used for the OAuth redirect within the * in-app-browser window in Cordova apps. * * @param uri - A valid HTTP(S) URI */ setCordovaRedirectUri(uri: string): void; _init: () => void; features: any[]; loadFeature: (featureName: any) => void; featureSupported: (featureName: any, success: any) => void; featureDone: () => void; featuresDone: number; featuresLoaded: () => void; featureInitialized: (featureName: any) => void; featureFailed: (featureName: any, err: any) => void; hasFeature: (feature: any) => any; _setCachingModule: () => void; _collectCleanupFunctions: () => void; _fireReady: () => void; initFeature: (featureName: any) => void; /** * TODO: document * @private */ _setGPD(impl: any, context?: any): void; /** * TODO: document * @private */ _pendingGPD(methodName: any): Function; /** * TODO: document * @private */ _processPending(): void; /** * TODO: document * @private */ _bindChange(object: { on: Function; }): void; /** * TODO: document * @private */ _dispatchEvent(eventName: string, event: any): void; /** * This method enables you to quickly instantiate a BaseClient, which you can * use to directly read and manipulate data in the connected storage account. * * Please use this method only for debugging and development, and choose or * create a :doc:`data module </data-modules>` for your app to use. * * @param path - The base directory of the BaseClient that will be returned * (with a leading and a trailing slash) * * @returns A client with the specified scope (category/base directory) */ scope(path: string): BaseClient; /** * Get the value of the sync interval when application is in the foreground * * @returns {number} A number of milliseconds */ getSyncInterval(): number; /** * Set the value of the sync interval when application is in the foreground * * @param interval - Sync interval in milliseconds (between 1000 and 3600000) */ setSyncInterval(interval: number): void; /** * Get the value of the sync interval when application is in the background * * @returns A number of milliseconds */ getBackgroundSyncInterval(): number; /** * Set the value of the sync interval when the application is in the * background * * @param interval - Sync interval in milliseconds (between 1000 and 3600000) */ setBackgroundSyncInterval(interval: number): void; /** * Get the value of the current sync interval. Can be background or * foreground, custom or default. * * @returns {number} A number of milliseconds */ getCurrentSyncInterval(): number; /** * Get the value of the current network request timeout * * @returns {number} A number of milliseconds */ getRequestTimeout(): number; /** * Set the timeout for network requests. * * @param timeout - Timeout in milliseconds */ setRequestTimeout(timeout: number): void; /** * TODO: document * @private */ syncCycle(): void; /** * Start synchronization with remote storage, downloading and uploading any * changes within the cached paths. * * Please consider: local changes will attempt sync immediately, and remote * changes should also be synced timely when using library defaults. So * this is mostly useful for letting users sync manually, when pressing a * sync button for example. This might feel safer to them sometimes, esp. * when shifting between offline and online a lot. * * @returns {Promise} A Promise which resolves when the sync has finished */ startSync(): Promise<void>; /** * Stop the periodic synchronization. */ stopSync(): void; addModule(module: RSModule): void; /** * Load module * @private */ _loadModule(moduleName: string, moduleBuilder: Function): { [key: string]: unknown; }; } interface RemoteStorage extends EventHandling { } declare enum ApiKeyType { GOOGLE = "googledrive", DROPBOX = "dropbox" } export = RemoteStorage; //# sourceMappingURL=remotestorage.d.ts.map
the_stack
/// <reference types="node" /> import stream = require("stream"); import events = require("events"); import fs = require("fs"); declare namespace FS { export interface Opts { windows?: boolean | undefined; drives?: string[] | undefined; root?: string | undefined; } } declare class FS { constructor(content: any, opts?: FS.Opts) rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; renameSync(oldPath: string, newPath: string): void; truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; truncateSync(path: string, len?: number): void; ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; ftruncateSync(fd: number, len?: number): void; chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; chownSync(path: string, uid: number, gid: number): void; fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; fchownSync(fd: number, uid: number, gid: number): void; lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; lchownSync(path: string, uid: number, gid: number): void; chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; chmodSync(path: string, mode: number): void; chmodSync(path: string, mode: string): void; fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; fchmodSync(fd: number, mode: number): void; fchmodSync(fd: number, mode: string): void; lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; lchmodSync(path: string, mode: number): void; lchmodSync(path: string, mode: string): void; stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: fs.Stats) => any): void; lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: fs.Stats) => any): void; fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: fs.Stats) => any): void; statSync(path: string): fs.Stats; lstatSync(path: string): fs.Stats; fstatSync(fd: number): fs.Stats; link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; linkSync(srcpath: string, dstpath: string): void; symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; symlinkSync(srcpath: string, dstpath: string, type?: string): void; readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; readlinkSync(path: string): string; realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; realpath(path: string, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; realpathSync(path: string, cache?: { [path: string]: string }): string; unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; unlinkSync(path: string): void; rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; rmdirSync(path: string): void; mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; mkdirSync(path: string, mode?: number): void; mkdirSync(path: string, mode?: string): void; readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; readdirSync(path: string): string[]; close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; closeSync(fd: number): void; open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; openSync(path: string, flags: string, mode?: number): number; openSync(path: string, flags: string, mode?: string): number; utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; utimesSync(path: string, atime: number, mtime: number): void; utimesSync(path: string, atime: Date, mtime: Date): void; futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; futimesSync(fd: number, atime: number, mtime: number): void; futimesSync(fd: number, atime: Date, mtime: Date): void; fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; fsyncSync(fd: number): void; write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; readFile(filename: string, options: { encoding: string; flag?: string | undefined; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; readFile(filename: string, options: { flag?: string | undefined; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; readFileSync(filename: string, encoding: string): string; readFileSync(filename: string, options: { encoding: string; flag?: string | undefined; }): string; readFileSync(filename: string, options?: { flag?: string | undefined; }): Buffer; writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; writeFile(filename: string, data: any, options: { encoding?: string | undefined; mode?: number | undefined; flag?: string | undefined; }, callback?: (err: NodeJS.ErrnoException) => void): void; writeFile(filename: string, data: any, options: { encoding?: string | undefined; mode?: string | undefined; flag?: string | undefined; }, callback?: (err: NodeJS.ErrnoException) => void): void; writeFileSync(filename: string, data: any, options?: { encoding?: string | undefined; mode?: number | undefined; flag?: string | undefined; }): void; writeFileSync(filename: string, data: any, options?: { encoding?: string | undefined; mode?: string | undefined; flag?: string | undefined; }): void; appendFile(filename: string, data: any, options: { encoding?: string | undefined; mode?: number | undefined; flag?: string | undefined; }, callback?: (err: NodeJS.ErrnoException) => void): void; appendFile(filename: string, data: any, options: { encoding?: string | undefined; mode?: string | undefined; flag?: string | undefined; }, callback?: (err: NodeJS.ErrnoException) => void): void; appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; appendFileSync(filename: string, data: any, options?: { encoding?: string | undefined; mode?: number | undefined; flag?: string | undefined; }): void; appendFileSync(filename: string, data: any, options?: { encoding?: string | undefined; mode?: string | undefined; flag?: string | undefined; }): void; watchFile(filename: string, listener: (curr: fs.Stats, prev: fs.Stats) => void): void; watchFile(filename: string, options: { persistent?: boolean | undefined; interval?: number | undefined; }, listener: (curr: fs.Stats, prev: fs.Stats) => void): void; unwatchFile(filename: string, listener?: (curr: fs.Stats, prev: fs.Stats) => void): void; watch(filename: string, listener?: (event: string, filename: string) => any): fs.FSWatcher; watch(filename: string, options: { persistent?: boolean | undefined; }, listener?: (event: string, filename: string) => any): fs.FSWatcher; exists(path: string, callback?: (exists: boolean) => void): void; existsSync(path: string): boolean; createReadStream(path: string, options?: { flags?: string | undefined; encoding?: string | undefined; fd?: string | undefined; mode?: number | undefined; bufferSize?: number | undefined; }): fs.ReadStream; createReadStream(path: string, options?: { flags?: string | undefined; encoding?: string | undefined; fd?: string | undefined; mode?: string | undefined; bufferSize?: number | undefined; }): fs.ReadStream; createWriteStream(path: string, options?: { flags?: string | undefined; encoding?: string | undefined; string?: string | undefined; }): fs.WriteStream; } export = FS;
the_stack
declare namespace GoldenLayout { export type ItemConfigType = ItemConfig | ComponentConfig | ReactComponentConfig; export interface Settings { /** * Turns headers on or off. If false, the layout will be displayed with splitters only. * Default: true */ hasHeaders?: boolean; /** * Constrains the area in which items can be dragged to the layout's container. Will be set to false * automatically when layout.createDragSource() is called. * Default: true */ constrainDragToContainer?: boolean; /** * If true, the user can re-arrange the layout by dragging items by their tabs to the desired location. * Default: true */ reorderEnabled?: boolean; /** * If true, the user can select items by clicking on their header. This sets the value of layout.selectedItem to * the clicked item, highlights its header and the layout emits a 'selectionChanged' event. * Default: false */ selectionEnabled?: boolean; /** * Decides what will be opened in a new window if the user clicks the popout icon. If true the entire stack will * be transferred to the new window, if false only the active component will be opened. * Default: false */ popoutWholeStack?: boolean; /** * Specifies if an error is thrown when a popout is blocked by the browser (e.g. by opening it programmatically). * If false, the popout call will fail silently. * Default: true */ blockedPopoutsThrowError?: boolean; /** * Specifies if all popouts should be closed when the page that created them is closed. Popouts don't have a * strong dependency on their parent and can exist on their own, but can be quite annoying to close by hand. In * addition, any changes made to popouts won't be stored after the parent is closed. * Default: true */ closePopoutsOnUnload?: boolean; /** * Specifies if the popout icon should be displayed in the header-bar. * Default: true */ showPopoutIcon?: boolean; /** * Specifies if the maximise icon should be displayed in the header-bar. * Default: true */ showMaximiseIcon: boolean; /** * Specifies if the close icon should be displayed in the header-bar. * Default: true */ showCloseIcon: boolean; } export interface Dimensions { /** * The width of the borders between the layout items in pixel. Please note: The actual draggable area is wider * than the visible one, making it safe to set this to small values without affecting usability. * Default: 5 */ borderWidth?: number; /** * The minimum height an item can be resized to (in pixel). * Default: 10 */ minItemHeight?: number; /** * The minimum width an item can be resized to (in pixel). * Default: 10 */ minItemWidth?: number; /** * The height of the header elements in pixel. This can be changed, but your theme's header css needs to be * adjusted accordingly. * Default: 20 */ headerHeight?: number; /** * The width of the element that appears when an item is dragged (in pixel). * Default: 300 */ dragProxyWidth?: number; /** * The height of the element that appears when an item is dragged (in pixel). * Default: 200 */ dragProxyHeight?: number; } export interface Labels { /** * The tooltip text that appears when hovering over the close icon. * Default: 'close' */ close?: string; /** * The tooltip text that appears when hovering over the maximise icon. * Default: 'maximise' */ maximise?: string; /** * The tooltip text that appears when hovering over the minimise icon. * Default: 'minimise' */ minimise?: string; /** * The tooltip text that appears when hovering over the popout icon. * Default: 'open in new window' */ popout?: string; } export interface ItemConfig { /** * The type of the item. Possible values are 'row', 'column', 'stack', 'component' and 'react-component'. */ type: string; /** * An array of configurations for items that will be created as children of this item. */ content?: ItemConfigType[]; /** * The width of this item, relative to the other children of its parent in percent */ width?: number; /** * The height of this item, relative to the other children of its parent in percent */ height?: number; /** * A String or an Array of Strings. Used to retrieve the item using item.getItemsById() */ id?: string | string[]; /** * Determines if the item is closable. If false, the x on the items tab will be hidden and container.close() * will return false * Default: true */ isClosable?: boolean; /** * The title of the item as displayed on its tab and on popout windows * Default: componentName or '' */ title?: string; } export interface ComponentConfig extends ItemConfig { /** * The name of the component as specified in layout.registerComponent. Mandatory if type is 'component'. */ componentName: string; /** * A serialisable object. Will be passed to the component constructor function and will be the value returned by * container.getState(). */ componentState?: any; } export interface ReactComponentConfig extends ItemConfig { /** * The name of the component as specified in layout.registerComponent. Mandatory if type is 'react-component' */ component: string; /** * Properties that will be passed to the component and accessible using this.props. */ props?: any; } export interface Config { settings?: Settings; dimensions?: Dimensions; labels?: Labels; content: ItemConfigType[]; } export interface ContentItem { /** * This items configuration in its current state */ config: ItemConfigType /** * The type of the item. Can be row, column, stack, component or root */ type: string; /** * An array of items that are children of this item */ contentItems: ContentItem[]; /** * The item that is this item's parent (or null if the item is root) */ parent: ContentItem; /** * A String or array of identifiers if provided in the configuration */ id: string; /** * True if the item had been initialised */ isInitialised: boolean; /** * True if the item is maximised */ isMaximised: boolean; /** * True if the item is the layout's root item */ isRoot: boolean; /** * True if the item is a row */ isRow: boolean; /** * True if the item is a column */ isColumn: boolean; /** * True if the item is a stack */ isStack: boolean; /** * True if the item is a component */ isComponent: boolean; /** * A reference to the layoutManager that controls this item */ layoutManager: any; /** * The item's outer element */ element: any; /** * The item's inner element. Can be the same as the outer element. */ childElementContainer: Container; /** * Only Stacks have this method! It's the programmatical equivalent of clicking a tab. * @param contentItem The new active content item */ setActiveContentItem(contentItem: ContentItem): void; /** * Returns all items with the specified id. * @param id An id specified in the itemConfig */ getItemsById(id: string | string[]): ContentItem[]; } export interface Container extends EventEmitter { /** * The current width of the container in pixel */ width: number; /** * The current height of the container in pixel */ height: number; } export interface BrowserWindow { } export interface EventEmitter { /** * Subscribe to an event * @param eventName The name of the event to describe to * @param callback The function that should be invoked when the event occurs * @param context The value of the this pointer in the callback function */ on(eventName: string, callback: Function, context?: any): void; /** * Notify listeners of an event and pass arguments along * @param eventName The name of the event to emit */ emit(eventName: string, arg1?: any, arg2?: any, ...argN: any[]): void; /** * Alias for emit */ trigger(eventName: string, arg1?: any, arg2?: any, ...argN: any[]): void; /** * Unsubscribes either all listeners if just an eventName is provided, just a specific callback if invoked with * eventName and callback or just a specific callback with a specific context if invoked with all three * arguments. * @param eventName The name of the event to unsubscribe from * @param callback The function that should be invoked when the event occurs * @param context The value of the this pointer in the callback function */ unbind(eventName: string, callback?: Function, context?: any): void; /** * Alias for unbind */ off(eventName: string, callback?: Function, context?: any): void; } }
the_stack
/// <reference path="../../elements.d.ts" /> import { Polymer } from '../../../../tools/definitions/polymer'; import { I18NKeys } from '../../../_locales/i18n-keys'; declare const browserAPI: browserAPI; declare const BrowserAPI: BrowserAPI; declare global { interface ErrorReportingToolSquare extends HTMLElement { xPos: string; yPos: string; } } namespace ErrorReportingToolElement { export const errorReportingTool: { reportType: string; image: string; hide: boolean; } = { /** * The type of the report */ reportType: { type: String, value: 'bug', notify: true }, /** * The screencap's dataURI */ image: { type: String, value: '', notify: true }, /** * Whether this overlay needs to be hidden */ hide: { type: Boolean, value: true, notify: true } } as any; interface ErrorHandler { (event: Event | string, source?: string, fileno?: number, columnNumber?: number, error?: Error): boolean|undefined; } export class ERT { static is: any = 'error-reporting-tool'; /** * The startposition of the selected area */ private static _dragStart: { X: number; Y: number; }; /** * The last size of the selected area */ private static _lastSize: { X: number; Y: number; }; /** * The last positions of the cursor */ private static _lastPos: { X: number; Y: number; }; /** * The last error that occurred in the console */ static lastErrors: { message: string; source: any; lineno: number; colno: number; error: Error; handled: boolean; }[] = []; static properties = errorReportingTool; static toggleVisibility(this: ErrorReportingTool) { this.hide = !this.hide; }; static isBugType(this: ErrorReportingTool, reportType: string): boolean { return reportType === 'bug'; }; static isEmptyImage(this: ErrorReportingTool, img: string): boolean { return img === ''; }; private static _scaleScreenshot(this: ErrorReportingTool, canvas: HTMLCanvasElement, newImg: HTMLImageElement) { this.image = canvas.toDataURL(); let maxViewportHeight = window.innerHeight - 450; if (maxViewportHeight > 750) { maxViewportHeight = 750; } if ((750 / newImg.width) * newImg.height > maxViewportHeight) { const captureConts = Array.prototype.slice.apply(this.shadowRoot.querySelectorAll('.captureCont')); captureConts.forEach((captureCont: HTMLElement) => { captureCont.style.width = ((maxViewportHeight / newImg.height) * newImg.width) + 'px'; }); } }; private static _cropScreenshot(this: ErrorReportingTool, dataURI: string, cropData: { width: number; height: number; left: number; top: number; }) { return new Promise<void>((resolve) => { const img = new Image(); const canvas = this.$.cropCanvas; const context = canvas.getContext('2d'); img.onload = () => { //Crop the image context.clearRect(0, 0, canvas.width, canvas.height); canvas.setAttribute('height', cropData.height + ''); canvas.setAttribute('width', cropData.width + ''); canvas.style.display = 'none'; this.appendChild(canvas); context.drawImage(img, cropData.left, cropData.top, cropData.width, cropData.height, 0, 0, cropData.width, cropData.height); //Scale the image to fit the canvas const base64 = canvas.toDataURL(); const newImg = new Image(); newImg.onload = () => { this._scaleScreenshot(canvas, newImg); resolve(null); }; newImg.src = base64; const imgTag = document.createElement('img'); imgTag.src = base64; document.body.appendChild(imgTag); }; img.src = dataURI; const imgTag2 = document.createElement('img'); imgTag2.src = dataURI; document.body.appendChild(imgTag2); }); }; private static async _screenshot(this: ErrorReportingTool, cropData: { width: number; height: number; left: number; top: number; }) { //Make sure the overlay is gone for a while this.$.overlay.style.display = 'none'; const { windowId } = await browserAPI.tabs.getCurrent(); const dataURI = await browserAPI.tabs.captureVisibleTab(windowId, { format: 'png', quality: 100 }); //Turn it on again this.$.overlay.style.display = 'block'; await this._cropScreenshot(dataURI, cropData); }; private static _px(this: ErrorReportingTool, num: number): string { return num + 'px'; }; private static _translateX(this: ErrorReportingTool, el: ErrorReportingToolSquare, x: string) { el.xPos = x; window.setTransform(el, `translate(${x},${el.yPos || '0px'})`); }; private static _translateY(this: ErrorReportingTool, el: ErrorReportingToolSquare, y: string) { el.yPos = y; window.setTransform(el, `translate(${el.xPos || '0px'}, ${y})`); }; private static _unLink<T extends { [key: string]: any; }>(this: ErrorReportingTool, obj: T): T { return JSON.parse(JSON.stringify(obj)); } private static _getDivs(this: ErrorReportingTool, direction: 'x'|'y'): [ErrorReportingToolSquare, ErrorReportingToolSquare]; private static _getDivs(this: ErrorReportingTool, direction: 'xy'): [ErrorReportingToolSquare, ErrorReportingToolSquare, ErrorReportingToolSquare, ErrorReportingToolSquare]; private static _getDivs(this: ErrorReportingTool, direction: 'x'|'y'|'xy'): [ErrorReportingToolSquare, ErrorReportingToolSquare]| [ErrorReportingToolSquare, ErrorReportingToolSquare, ErrorReportingToolSquare, ErrorReportingToolSquare] { const x: [ErrorReportingToolSquare, ErrorReportingToolSquare] = [this.$.highlightingLeftSquare, this.$.highlightingRightSquare]; const y: [ErrorReportingToolSquare, ErrorReportingToolSquare] = [this.$.highlightingTopSquare, this.$.highlightingBotSquare]; switch (direction) { case 'x': return x; case 'y': return y; case 'xy': return x.concat(y) as [ErrorReportingToolSquare, ErrorReportingToolSquare, ErrorReportingToolSquare, ErrorReportingToolSquare]; } } private static _setDivsXValues(this: ErrorReportingTool, left: string, marginLeftPx: string, rightDivTranslate: string, [topHeight, botHeight]: [number, number]) { const [ leftDiv, rightDiv ] = this._getDivs('x'); leftDiv.style.width = left; window.addCalcFn(rightDiv, 'width', `100vw - ${marginLeftPx}`); leftDiv.style.height = rightDiv.style.height = this._px(window.innerHeight - topHeight - (window.innerHeight - botHeight)); this._translateX(rightDiv, rightDivTranslate); } private static _setSelectionX(this: ErrorReportingTool, startX: number, width: number, xHeights: [number, number]) { const left = startX + width; if (width < 0) { this._setDivsXValues(this._px(left), this._px(startX), this._px(left - width), xHeights); } else { this._setDivsXValues(this._px(startX), this._px(left), this._px(left), xHeights); } } private static _setDivsYValues(this: ErrorReportingTool, { topHeight, heights, botHeight }: { topHeight: string; heights: string; botHeight: number; }) { const [ leftDiv, rightDiv, topDiv, botDiv ] = this._getDivs('xy'); topDiv.style.height = topHeight; leftDiv.style.height = rightDiv.style.height = heights + 'px'; botDiv.style.height = this._px(window.innerHeight - botHeight); this._translateY(botDiv, this._px(botHeight)); this._translateY(leftDiv, topHeight); this._translateY(rightDiv, topHeight); } private static _setSelectionY(this: ErrorReportingTool, startY: number, height: number, startPlusHeightPx: number) { if (height < 0) { this._setDivsYValues({ topHeight: this._px(startPlusHeightPx), heights: this._px(-height), botHeight: startY }); } else { this._setDivsYValues({ topHeight: this._px(startY), heights: this._px(height), botHeight: startPlusHeightPx }); } } private static _changed(this: ErrorReportingTool, width: number, height: number) { return this._lastSize.X !== width || this._lastSize.Y !== height; } private static _setSelection(this: ErrorReportingTool, { startX, width }: { startX: number; width: number; }, { startY, height }: { startY: number; height: number; }) { if (!this._changed(width, height)) { return; } const topHeight = height < 0 ? startY + height : startY; const botHeight = height < 0 ? startY : startY + height; this._setSelectionX(startX, width, [topHeight, botHeight]); this._setSelectionY(startY, height, startY + height); } static handleSelection(this: ErrorReportingTool, e: Polymer.PolymerDragEvent) { switch (e.detail.state) { case 'start': this.$.highlightButtons.classList.add('hidden'); const startYPx = e.detail.y + 'px'; this._lastSize.X = this._lastSize.Y = 0; this._dragStart = this._unLink(this._lastPos = { X: e.detail.x, Y: e.detail.y }); this.$.highlightingTopSquare.style.width = '100vw'; this.$.highlightingTopSquare.style.height = startYPx; this.$.highlightingLeftSquare.style.width = startYPx; this._translateY(this.$.highlightingBotSquare, startYPx); this._translateY(this.$.highlightingLeftSquare, startYPx); this._translateY(this.$.highlightingRightSquare, startYPx); break; case 'end': this.$.highlightButtons.classList.remove('hidden'); break; case 'track': if (e.detail.x !== this._lastPos.X || e.detail.y !== this._lastPos.Y) { const width = e.detail.dx; const height = e.detail.dy; const startX = e.detail.x - width; const startY = e.detail.y - height; this._setSelection({ startX, width }, { startY, height }); this._lastSize = { X: width, Y: height }; this._lastPos = { X: e.detail.x, Y: e.detail.y } } break; } }; private static _resetSelection(this: ErrorReportingTool) { this._setSelectionX(0, 0, [0, 0]); this._setSelectionY(0, 0, 0); } private static _toggleScreenCapArea(this: ErrorReportingTool, visible: boolean) { this.$.highlightingTopSquare.style.height = '100vh'; this.$.highlightingTopSquare.style.width = '100vw'; this._resetSelection(); this.$.overlay.classList[visible ? 'add' : 'remove']('toggled'); this.$.overlay.style.pointerEvents = visible ? 'initial' : 'none'; } static cancelScreencap(this: ErrorReportingTool) { this._toggleScreenCapArea(false); this.$.errorReportingDialog.open(); }; static async finishScreencap(this: ErrorReportingTool) { this._toggleScreenCapArea(false); await this._screenshot({ top: this._dragStart.Y, left: this._dragStart.X, height: this._lastSize.Y, width: this._lastSize.X }); this.$.errorReportingDialog.open(); }; private static _resetVars(this: ErrorReportingTool) { this._dragStart = this._unLink(this._lastSize = this._unLink(this._lastPos = { X: 0, Y: 0 })); } static addCapture(this: ErrorReportingTool) { this.$.errorReportingDialog.close(); this._resetVars(); this._toggleScreenCapArea(true); }; static reportBug(this: ErrorReportingTool) { this.reportType = 'bug'; this.image = ''; this.$.errorReportingDialog.open(); }; private static async _getStorages() { return { local: await browserAPI.storage.local.get<CRM.StorageLocal>(), sync: await browserAPI.storage.local.get<CRM.SettingsStorage>(), } } private static async _downloadFiles(this: ErrorReportingTool) { if (!(browserAPI.downloads)) { return false; } await browserAPI.downloads.download({ url: this.image, filename: 'screencap.png' }); if (this.reportType === 'bug') { const { local, sync } = await this._getStorages(); const dataCont = { local, sync, lastErrors: this.lastErrors }; await browserAPI.downloads.download({ url: 'data:text/plain;base64,' + window.btoa(JSON.stringify(dataCont)), filename: 'settings.txt' //Downloads as text because github doesn't allow JSON uploads }); } return true; }; private static _hideCheckmark(this: ErrorReportingTool) { this.$.bugCheckmarkCont.classList.remove('checkmark'); this.async(() => { this.$.reportingButtonElevation.classList.remove('checkmark'); this.$.bugButton.classList.remove('checkmark'); this.$.bugCheckmark.classList.remove('checked'); }, 350); } private static _checkCheckmark(this: ErrorReportingTool) { this.$.bugButton.classList.add('checkmark'); this.async(() => { this.$.reportingButtonElevation.classList.add('checkmark'); this.$.bugCheckmarkCont.classList.add('checkmark'); this.async(() => { this.$.bugCheckmark.classList.add('checked'); this.async(this._hideCheckmark, 5000); }, 350); }, 350); }; private static async _getDownloadPermission(this: ErrorReportingTool): Promise<boolean> { if (BrowserAPI.getSrc().downloads && BrowserAPI.getSrc().downloads.download) { return true; } if (!(BrowserAPI.getSrc().permissions)) { window.app.util.showToast(await this.__async(I18NKeys.crmApp.code.downloadNotSupported)); return false; } const granted = await browserAPI.permissions.contains({ permissions: ['downloads'] }); if (granted) { window.errorReportingTool.$.errorReportingDialog.close(); const listener = () => { this._checkCheckmark(); window.removeEventListener('focus', listener); }; window.addEventListener('focus', listener); return true; } else { const nowGranted = await browserAPI.permissions.request({ permissions: ['downloads'] }); //Refresh browserAPI object browserAPI.downloads = browserAPI.downloads || BrowserAPI.getDownloadAPI(); if (!nowGranted) { window.doc.acceptDownloadToast.show(); } return nowGranted; } }; static async submitErrorReport(this: ErrorReportingTool) { const granted = await this._getDownloadPermission(); if (!granted) { return; } if (!await this._downloadFiles()) { window.app.util.showToast(await this.__async(I18NKeys.crmApp.code.downloadNotSupported)); return; } //Take the user to the github page const messageBody = `${await this.__async(I18NKeys.util.errorReportingTool.messagePlaceholder)}\n`; const title = (this.reportType === 'bug' ? 'Bug: ' : 'Feature: ') + await this.__async(I18NKeys.util.errorReportingTool.titlePlaceholder); window.open('https://github.com/SanderRonde/CustomRightClickMenu/issues/new?title=' + title + '&body=' + messageBody, '_blank'); }; private static _onError(this: ErrorReportingTool, message: string, source: any, lineno: number, colno: number, error: Error, handled: boolean) { this.lastErrors.push({ message, source, lineno, colno, error, handled }); }; private static _registerOnError(this: ErrorReportingTool) { const handlers: ErrorHandler[] = []; if (window.onerror) { handlers.push(window.onerror as ErrorHandler); } window.onerror = (message: string, source: any, lineno: number, colno: number, error: Error) => { let handled: boolean = false; handlers.forEach((handler) => { if (handler(message, source, lineno, colno, error)) { handled = true; } }); this._onError(message, source, lineno, colno, error, handled); if (handled) { return true; } return undefined; } Object.defineProperty(window, 'onerror', { set(handler: ErrorHandler) { handlers.push(handler); } }); } static ready(this: ErrorReportingTool) { window.errorReportingTool = this; this._registerOnError(); } } if (window.objectify) { window.register(ERT); } else { window.addEventListener('RegisterReady', () => { window.register(ERT); }); } } export type ErrorReportingTool = Polymer.El<'error-reporting-tool', typeof ErrorReportingToolElement.ERT & typeof ErrorReportingToolElement.errorReportingTool>;
the_stack
import underscore = require('underscore'); import urijs = require('urijs'); import collection_util = require('../base/collectionutil'); import event_stream = require('../base/event_stream'); import err_util = require('../base/err_util'); import ico = require('./ico'); import image = require('./image'); import site_info = require('./site_info'); import stringutil = require('../base/stringutil'); import url_util = require('../base/url_util'); // Icon Sources: // - Static URls at $HOST/$ICON_NAME (Favicon, Apple Touch Icon etc.) // - Image URLs referenced from page in <meta> or <link> tags (eg. Favicon, Apple touch icons, // Facebook, Twitter and Schema.org URLs) // - HTML URLs referenced from page in <meta> or <link> tags which // require icons (eg. Apple iTunes pages, Social media pages, Twitter accounts) // - DuckDuckGo instant answer API query for '<domain name minus tld>' // App and Social Media Links: // // Google+ link: // <link href="https://plus.google.com/<ID>" rel="publisher" /> // G+ pages have schema.org <meta ...imageprop> tags on them // // App links: // <meta name="apple-itunes-app" content="app-id=$APP_ID" /> // -- iTunes store pages have Facebook OpenGraph <meta> tags on them // <meta property="fb:app_id" content="$APP_ID" /> // // Image tags: // <img> tags on page containing keywords such as 'icon' or 'logo' // // RSS links: // <link rel="alternate" type="application/rss+xml" title="Latest News" href="/rss/rss.xml" /> // RSS XML format has image/url tag. // list of known <link> and <meta> tags that point // to an icon for the site. // // See also: // - http://microformats.org/wiki/existing-rel-values (list of known // values for 'rel' attribute of <link> tags) // - http://www.iacquire.com/blog/18-meta-tags-every-webpage-should-have-in-2013 // - Google structured data testing tool: http://www.google.com/webmasters/tools/richsnippets // export enum MetaTagType { Meta, Link, } var ICON_LINK_TYPES: PageLink[] = [ // Favicons { type: MetaTagType.Link, rel: 'icon' }, { type: MetaTagType.Link, rel: 'shortcut icon' }, { type: MetaTagType.Link, rel: 'image_src' }, // iOS hi-DPI site icons { type: MetaTagType.Link, rel: 'apple-touch-icon' }, { type: MetaTagType.Link, rel: 'apple-touch-icon-precomposed' }, // Facebook OpenGraph (http://developers.facebook.com/docs/opengraphprotocol/) { type: MetaTagType.Meta, rel: 'og:image' }, // Twitter Cards (https://dev.twitter.com/docs/cards) { type: MetaTagType.Meta, rel: 'twitter:image' }, { type: MetaTagType.Meta, rel: 'twitter:image:src' }, // Schema.org { type: MetaTagType.Meta, rel: 'image' }, // Other { type: MetaTagType.Meta, rel: 'msapplication-TileImage' }, ]; export interface UrlResponse { status: number; body: string; } /** Interface used by SiteInfoService service for fetching arbitrary URLs. */ export interface UrlFetcher { fetch(url: string): Promise<UrlResponse>; } /** Determines the type and width/height of an icon fetched from * a URL and returns an Icon object. * * If @p data is in .ico format, the largest icon in the file * is returned and the data in the returned Icon.data field * will be in .bmp format. */ export function iconFromData(url: string, buffer: Uint8Array): site_info.Icon { var data = new Uint8Array(<any>buffer); if (ico.isIco(data)) { var maxIcon = underscore.max( ico.read(new DataView(data.buffer)), (icon: ico.Icon) => { return icon.width; } ); return { url: url, width: maxIcon.width, height: maxIcon.height, data: maxIcon.data, }; } else { var imageInfo = image.getInfo(buffer); if (!imageInfo) { var start = collection_util.hexlify(buffer.subarray(0, 50)); console.log( 'Unable to determine image type of %s', url, 'from data of length', buffer.length, start, collection_util.stringFromBuffer(buffer.subarray(0, 50)) ); return null; } return { url: url, width: imageInfo.width, height: imageInfo.height, data: data, }; } } interface IconFetchState { url: string; reply: Promise<UrlResponse>; icon: site_info.Icon; status: number; } /** IconFetcher fetches and decodes icons from specified URLs. * * URLs are enqueued for fetching using addUrl(). When a URL is fetched, * the 'done' event is emitted. * * IconFetcher remembers the URLs that have been enqueued for fetching * and ignores requests to fetch URLs that have already been fetched * or for which requests are in-flight. */ class IconFetcher { private fetcher: UrlFetcher; private queue: IconFetchState[]; // map of URL -> (null|status) for URLs that have // already been fetched or are enqueued for fetching private fetchedUrls: Map<string, number>; /** Stream of URL fetch completion events. */ done: event_stream.EventStream<IconFetchState>; constructor(fetcher: UrlFetcher) { this.fetcher = fetcher; this.done = new event_stream.EventStream<IconFetchState>(); this.queue = []; this.fetchedUrls = new Map<string, number>(); } /** Returns the number of outstanding URL fetch requests which * have not yet completed. */ remaining(): number { return this.queue.length; } /** Fetch and decode an icon URL. A 'done' event is emitted * when the fetch completes. */ addUrl(url: string) { if (this.fetchedUrls.has(url)) { // URL has already been fetched or request // is in-flight return; } this.fetchedUrls.set(url, null); var queueItem: IconFetchState = { url: url, icon: null, reply: this.fetcher.fetch(url), status: null, }; this.queue.push(queueItem); queueItem.reply .then(reply => { queueItem.status = reply.status; this.fetchedUrls.set(url, reply.status); if (reply.status == 200) { var buffer = collection_util.bufferFromString(reply.body); try { queueItem.icon = iconFromData(url, buffer); } catch (ex) { var start = collection_util.hexlify( buffer.subarray(0, 50) ); console.log( 'Failed to decode icon', url, 'from data of length', buffer.length, start, ex.message ); } } else { let error = ''; try { let response = JSON.parse(reply.body); if (typeof response === 'object' && response.error) { error = response.error; } } catch (ex) { error = reply.body; } console.warn( `Icon lookup for ${url} failed with status ${ reply.status }: ${error}` ); } }) .catch(e => { queueItem.status = 0; this.fetchedUrls.set(url, 0); }) .then(() => { this.queue.splice(this.queue.indexOf(queueItem), 1); this.done.publish(queueItem); }); } } /** Returns true if a <meta> or <link> element on a page * links to an icon or image for the page or parent domain. */ export function isIconLink(link: PageLink): boolean { var isIcon = false; ICON_LINK_TYPES.forEach(linkType => { if ( linkType.type === link.type && stringutil.equalIgnoreCase(linkType.rel, link.rel) ) { isIcon = true; } }); return isIcon; } export class SiteInfoService implements site_info.SiteInfoProvider { private cache: collection_util.OMap<site_info.QueryResult>; updated: event_stream.EventStream<string>; constructor(public fetcher: UrlFetcher) { this.cache = {}; this.updated = new event_stream.EventStream<string>(); } forget(url: string) { url = url_util.normalize(url); delete this.cache[url]; } lookup(url: string): site_info.QueryResult { url = url_util.normalize(url); if (this.cache[url]) { return this.cache[url]; } var result: site_info.QueryResult = { info: { url: url, icons: [], }, state: site_info.QueryState.Updating, }; this.cache[url] = result; this.update(url); return this.status(url); } status(url: string): site_info.QueryResult { url = url_util.normalize(url); return this.cache[url]; } private update(url: string) { url = url_util.normalize(url); var SOURCE_COUNT = 2; var sourcesQueried = 0; var iconFetcher = new IconFetcher(this.fetcher); var updateQueryState = () => { if ( iconFetcher.remaining() == 0 && sourcesQueried == SOURCE_COUNT ) { this.cache[url].state = site_info.QueryState.Ready; this.updated.publish(url); } }; iconFetcher.done.listen(result => { if (result.status == 200) { if (result.icon) { this.cache[url].info.icons.push(result.icon); } this.updated.publish(url); } updateQueryState(); }); // check standard icon paths for host var STANDARD_PATHS: string[] = [ '/favicon.ico', '/apple-touch-icon.png', '/apple-touch-icon-precomposed.png', ]; STANDARD_PATHS.forEach(path => { var urlParts = urijs.parse(url); urlParts.path = path; iconFetcher.addUrl(urijs.build(urlParts)); }); ++sourcesQueried; // fetch URL and look for links to icons in the HTML content var pageLinkFetcher = new PageLinkFetcher(this.fetcher); pageLinkFetcher .fetch(url) .then(links => { var rootUrl = url; links.forEach(link => { if (isIconLink(link)) { var absoluteLinkUrl = urijs(link.url).absoluteTo( rootUrl ); iconFetcher.addUrl(absoluteLinkUrl.toString()); } }); }) .catch(() => {}) .then(() => { ++sourcesQueried; updateQueryState(); }); } } /** Represents a link to a related resource listed in * an HTML page, eg. via a <meta> or <link> tag. */ export interface PageLink { type: MetaTagType; /** The relation of this resource to the page, specified * via the 'rel' attribute of <link> tags or 'property', * 'name', 'itemprop' etc. attributes of <meta> tags. */ rel: string; /** The URL of the linked resource, specified via the * 'href' attribute of <link> tags or the 'content' * attribute of <meta> tags. */ url?: string; } interface Token { start: number; length: number; } // holds the tag name and text of // a parsed HTML tag interface ParsedTag { type: string; attrs: collection_util.OMap<string>; text: string; } function isSpace(ch: string) { // taken from http://stackoverflow.com/questions/1496826 return ch.length === 1 && /\s/.test(ch); } /** PageLinkFetcher retrieves an HTML page and * extracts links to related resources from <meta> and <link> tags */ export class PageLinkFetcher { constructor(public fetcher: UrlFetcher) {} extractLinks(content: string): PageLink[] { var linkStart = /\<(link|meta)/i; var links: PageLink[] = []; while (true) { var match = content.match(linkStart); if (!match) { break; } var linkType: MetaTagType; var linkRel = ''; var linkUrl = ''; var tagStart = (<any>match).index; var tag = this.parseTag(content.substr(tagStart)); content = content.substr(tagStart + tag.text.length); var propAttrs = ['rel', 'property', 'name', 'itemprop']; var urlAttrs = ['href', 'content']; if (tag.type == 'link') { linkType = MetaTagType.Link; } else { linkType = MetaTagType.Meta; } for (var i = 0; i < propAttrs.length && !linkRel; i++) { var propName = propAttrs[i]; if (tag.attrs[propName]) { for (var k = 0; k < urlAttrs.length && !linkUrl; k++) { if (tag.attrs[urlAttrs[k]]) { linkRel = tag.attrs[propName]; linkUrl = tag.attrs[urlAttrs[k]]; } } } } if (linkType !== null && linkRel && linkUrl) { links.push({ type: linkType, rel: linkRel.toLowerCase(), url: linkUrl, }); } } return links; } fetch(url: string): Promise<PageLink[]> { return this.fetcher.fetch(url).then(response => { return this.extractLinks(response.body); }); } private parseTag(content: string): ParsedTag { var attrs: collection_util.OMap<string> = {}; var tokens = this.tokenizeTag(content); var inVal = false; var attrName = ''; var tagType = ''; tokens.forEach(token => { var text = this.unquote(content.substr(token.start, token.length)); if (text == '<' || text == '>') { return; } if (!tagType) { tagType = text.toLowerCase(); return; } if (text == '=') { inVal = true; } else if (inVal) { attrs[attrName] = text; inVal = false; } else { attrName = text.toLowerCase(); } }); var last = tokens[tokens.length - 1]; var parsed = { type: tagType, attrs: attrs, text: content.substr(tokens[0].start, last.start + last.length), }; return parsed; } // removes surrounding quotes and unescapes any quotes // within a string. // // unquote('foo') => 'foo' // unquote('"foo\"bar"') => 'foo"bar' private unquote(text: string): string { var quoteCh = text[0]; if (quoteCh != '"' && quoteCh != "'") { return text; } var unquoted = ''; for (var i = 1; i < text.length; i++) { if (text[i] == '\\') { unquoted += text[i + 1]; i += 2; } else if (text[i] == quoteCh) { break; } else { unquoted += text[i]; } } return unquoted; } // split an HTML tag into tokens, eg. // tokenizeTag('<link rel="foo" href="bar">') => // ['<','link','rel','=','foo','href','bar','>'] private tokenizeTag(content: string): Token[] { var tagDepth = 0; var quoteChar: string = null; var prevCh: string = null; var tokens: Token[] = []; var tokenStart = 0; var next = (i: number) => { var length = i - tokenStart; var text = content.substr(tokenStart, length); if (!text.match(/^\s*$/)) { tokens.push({ start: tokenStart, length: length, }); } tokenStart = i; }; var i = 0; for (; i < content.length; i++) { var ch = content[i]; if (quoteChar === null) { if (ch === '<') { ++tagDepth; next(i); } else if (ch === '>') { --tagDepth; next(i); if (tagDepth == 0) { next(i + 1); break; } } else if (ch === '"' || ch === "'") { quoteChar = ch; next(i); } else if (ch === '=') { next(i); } else if (isSpace(ch)) { if (!isSpace(prevCh)) { next(i); } } else if ( isSpace(prevCh) || prevCh === '<' || prevCh === '=' ) { next(i); } } else if (ch === quoteChar) { if (prevCh !== '\\') { quoteChar = null; next(i + 1); } } prevCh = ch; } return tokens; } } /** DuckDuckGo fetches an icon associated with a URL using * the DDG instant answer API */ export class DuckDuckGoClient { constructor(private fetcher: UrlFetcher) {} /** Fetch the URL for the icon associated with a given URL's * domain. */ fetchIconUrl(url: string): Promise<string> { var itemDomain = urijs(url).domain(); if (itemDomain.length > 0) { var ddgQuery = this.fetcher.fetch( 'https://api.duckduckgo.com/?q=' + itemDomain + '&format=json' ); return ddgQuery.then(result => { if (result.status == 200) { var queryResult = JSON.parse(result.body); if (queryResult.Image && queryResult.ImageIsLogo) { return Promise.resolve<string>(queryResult.Image); } else { return Promise.reject<string>( new err_util.ApiError( url, result.status, 'DDG query did not return an icon' ) ); } } else { return Promise.reject<string>( new err_util.ApiError( url, result.status, 'DDG query failed' ) ); } }); } else { return Promise.reject<string>( new err_util.BaseError( 'Could not extract domain for URL: ' + url ) ); } } }
the_stack
export default function makeDashboard(integrationId: string) { return { __inputs: [], __requires: [], annotations: { list: [] }, editable: false, gnetId: null, graphTooltip: 1, hideControls: false, id: null, links: [], refresh: "", rows: [ { collapse: false, collapsed: false, panels: [ { cacheTimeout: null, colorBackground: false, colorValue: false, colors: ["#299c46", "rgba(237, 129, 40, 0.89)", "#d44a3a"], datasource: "$datasource", format: "none", gauge: { maxValue: 100, minValue: 0, show: false, thresholdLabels: false, thresholdMarkers: true }, gridPos: {}, id: 2, interval: null, links: [], mappingType: 1, mappingTypes: [ { name: "value to text", value: 1 }, { name: "range to text", value: 2 } ], maxDataPoints: 100, nullPointMode: "connected", nullText: null, postfix: "", postfixFontSize: "50%", prefix: "", prefixFontSize: "50%", rangeMaps: [ { from: "null", text: "N/A", to: "null" } ], span: 2, sparkline: { fillColor: "rgba(31, 118, 189, 0.18)", full: false, lineColor: "rgb(31, 120, 193)", show: false }, tableColumn: "", targets: [ { expr: `sum(up{integration_id="${integrationId}",job="apiserver"})`, format: "time_series", intervalFactor: 2, legendFormat: "", refId: "A" } ], thresholds: "", title: "Up", tooltip: { shared: false }, type: "singlestat", valueFontSize: "80%", valueMaps: [ { op: "=", text: "N/A", value: "null" } ], valueName: "min" }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "$datasource", fill: 1, gridPos: {}, id: 3, legend: { alignAsTable: false, avg: false, current: false, max: false, min: false, rightSide: false, show: true, total: false, values: false }, lines: true, linewidth: 1, links: [], nullPointMode: "null", percentage: false, pointradius: 5, points: false, renderer: "flot", repeat: null, seriesOverrides: [], spaceLength: 10, span: 5, stack: false, steppedLine: false, targets: [ { expr: `sum(rate(apiserver_request_total{integration_id="${integrationId}",job="apiserver", instance=~"$instance",code=~"2.."}[5m]))`, format: "time_series", intervalFactor: 2, legendFormat: "2xx", refId: "A" }, { expr: `sum(rate(apiserver_request_total{integration_id="${integrationId}",job="apiserver", instance=~"$instance",code=~"3.."}[5m]))`, format: "time_series", intervalFactor: 2, legendFormat: "3xx", refId: "B" }, { expr: `sum(rate(apiserver_request_total{integration_id="${integrationId}",job="apiserver", instance=~"$instance",code=~"4.."}[5m]))`, format: "time_series", intervalFactor: 2, legendFormat: "4xx", refId: "C" }, { expr: `sum(rate(apiserver_request_total{integration_id="${integrationId}",job="apiserver", instance=~"$instance",code=~"5.."}[5m]))`, format: "time_series", intervalFactor: 2, legendFormat: "5xx", refId: "D" } ], thresholds: [], timeFrom: null, timeShift: null, title: "RPC Rate", tooltip: { shared: false, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { format: "ops", label: null, logBase: 1, max: null, min: null, show: true }, { format: "ops", label: null, logBase: 1, max: null, min: null, show: true } ] }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "$datasource", fill: 1, gridPos: {}, id: 4, legend: { alignAsTable: "true", avg: false, current: "true", max: false, min: false, rightSide: "true", show: "true", total: false, values: "true" }, lines: true, linewidth: 1, links: [], nullPointMode: "null", percentage: false, pointradius: 5, points: false, renderer: "flot", repeat: null, seriesOverrides: [], spaceLength: 10, span: 5, stack: false, steppedLine: false, targets: [ { expr: `histogram_quantile(0.99, sum(rate(apiserver_request_duration_seconds_bucket{integration_id="${integrationId}",job="apiserver", instance=~"$instance"}[5m])) by (verb, le))`, format: "time_series", intervalFactor: 2, legendFormat: "{{verb}}", refId: "A" } ], thresholds: [], timeFrom: null, timeShift: null, title: "Request duration 99th quantile", tooltip: { shared: false, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { format: "s", label: null, logBase: 1, max: null, min: null, show: true }, { format: "s", label: null, logBase: 1, max: null, min: null, show: true } ] } ], repeat: null, repeatIteration: null, repeatRowId: null, showTitle: false, title: "Dashboard Row", titleSize: "h6", type: "row" }, { collapse: false, collapsed: false, panels: [ { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "$datasource", fill: 1, gridPos: {}, id: 5, legend: { alignAsTable: false, avg: false, current: false, max: false, min: false, rightSide: false, show: false, total: false, values: false }, lines: true, linewidth: 1, links: [], nullPointMode: "null", percentage: false, pointradius: 5, points: false, renderer: "flot", repeat: null, seriesOverrides: [], spaceLength: 10, span: 6, stack: false, steppedLine: false, targets: [ { expr: `sum(rate(workqueue_adds_total{integration_id="${integrationId}",job="apiserver", instance=~"$instance"}[5m])) by (instance, name)`, format: "time_series", intervalFactor: 2, legendFormat: "{{instance}} {{name}}", refId: "A" } ], thresholds: [], timeFrom: null, timeShift: null, title: "Work Queue Add Rate", tooltip: { shared: false, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { format: "ops", label: null, logBase: 1, max: null, min: 0, show: true }, { format: "ops", label: null, logBase: 1, max: null, min: 0, show: true } ] }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "$datasource", fill: 1, gridPos: {}, id: 6, legend: { alignAsTable: false, avg: false, current: false, max: false, min: false, rightSide: false, show: false, total: false, values: false }, lines: true, linewidth: 1, links: [], nullPointMode: "null", percentage: false, pointradius: 5, points: false, renderer: "flot", repeat: null, seriesOverrides: [], spaceLength: 10, span: 6, stack: false, steppedLine: false, targets: [ { expr: `sum(rate(workqueue_depth{integration_id="${integrationId}",job="apiserver", instance=~"$instance"}[5m])) by (instance, name)`, format: "time_series", intervalFactor: 2, legendFormat: "{{instance}} {{name}}", refId: "A" } ], thresholds: [], timeFrom: null, timeShift: null, title: "Work Queue Depth", tooltip: { shared: false, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { format: "short", label: null, logBase: 1, max: null, min: 0, show: true }, { format: "short", label: null, logBase: 1, max: null, min: 0, show: true } ] }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "$datasource", fill: 1, gridPos: {}, id: 7, legend: { alignAsTable: "true", avg: false, current: "true", max: false, min: false, rightSide: "true", show: "true", total: false, values: "true" }, lines: true, linewidth: 1, links: [], nullPointMode: "null", percentage: false, pointradius: 5, points: false, renderer: "flot", repeat: null, seriesOverrides: [], spaceLength: 10, span: 12, stack: false, steppedLine: false, targets: [ { expr: `histogram_quantile(0.99, sum(rate(workqueue_queue_duration_seconds_bucket{integration_id="${integrationId}",job="apiserver", instance=~"$instance"}[5m])) by (instance, name, le))`, format: "time_series", intervalFactor: 2, legendFormat: "{{instance}} {{name}}", refId: "A" } ], thresholds: [], timeFrom: null, timeShift: null, title: "Work Queue Latency", tooltip: { shared: false, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { format: "s", label: null, logBase: 1, max: null, min: null, show: true }, { format: "s", label: null, logBase: 1, max: null, min: null, show: true } ] } ], repeat: null, repeatIteration: null, repeatRowId: null, showTitle: false, title: "Dashboard Row", titleSize: "h6", type: "row" }, { collapse: false, collapsed: false, panels: [ { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "$datasource", fill: 1, gridPos: {}, id: 8, legend: { alignAsTable: false, avg: false, current: false, max: false, min: false, rightSide: false, show: true, total: false, values: false }, lines: true, linewidth: 1, links: [], nullPointMode: "null", percentage: false, pointradius: 5, points: false, renderer: "flot", repeat: null, seriesOverrides: [], spaceLength: 10, span: 4, stack: false, steppedLine: false, targets: [ { expr: `etcd_helper_cache_entry_total{integration_id="${integrationId}",job="apiserver", instance=~"$instance"}`, format: "time_series", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeShift: null, title: "ETCD Cache Entry Total", tooltip: { shared: false, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { format: "short", label: null, logBase: 1, max: null, min: 0, show: true }, { format: "short", label: null, logBase: 1, max: null, min: 0, show: true } ] }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "$datasource", fill: 1, gridPos: {}, id: 9, legend: { alignAsTable: false, avg: false, current: false, max: false, min: false, rightSide: false, show: true, total: false, values: false }, lines: true, linewidth: 1, links: [], nullPointMode: "null", percentage: false, pointradius: 5, points: false, renderer: "flot", repeat: null, seriesOverrides: [], spaceLength: 10, span: 4, stack: false, steppedLine: false, targets: [ { expr: `sum(rate(etcd_helper_cache_hit_total{integration_id="${integrationId}",job="apiserver",instance=~"$instance"}[5m])) by (intance)`, format: "time_series", intervalFactor: 2, legendFormat: "{{instance}} hit", refId: "A" }, { expr: `sum(rate(etcd_helper_cache_miss_total{integration_id="${integrationId}",job="apiserver",instance=~"$instance"}[5m])) by (instance)`, format: "time_series", intervalFactor: 2, legendFormat: "{{instance}} miss", refId: "B" } ], thresholds: [], timeFrom: null, timeShift: null, title: "ETCD Cache Hit/Miss Rate", tooltip: { shared: false, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { format: "ops", label: null, logBase: 1, max: null, min: 0, show: true }, { format: "ops", label: null, logBase: 1, max: null, min: 0, show: true } ] }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "$datasource", fill: 1, gridPos: {}, id: 10, legend: { alignAsTable: false, avg: false, current: false, max: false, min: false, rightSide: false, show: true, total: false, values: false }, lines: true, linewidth: 1, links: [], nullPointMode: "null", percentage: false, pointradius: 5, points: false, renderer: "flot", repeat: null, seriesOverrides: [], spaceLength: 10, span: 4, stack: false, steppedLine: false, targets: [ { expr: `histogram_quantile(0.99,sum(rate(etcd_request_cache_get_duration_seconds_bucket{integration_id="${integrationId}",job="apiserver",instance=~"$instance"}[5m])) by (instance, le))`, format: "time_series", intervalFactor: 2, legendFormat: "{{instance}} get", refId: "A" }, { expr: `histogram_quantile(0.99,sum(rate(etcd_request_cache_add_duration_seconds_bucket{integration_id="${integrationId}",job="apiserver",instance=~"$instance"}[5m])) by (instance, le))`, format: "time_series", intervalFactor: 2, legendFormat: "{{instance}} miss", refId: "B" } ], thresholds: [], timeFrom: null, timeShift: null, title: "ETCD Cache Duration 99th Quantile", tooltip: { shared: false, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { format: "s", label: null, logBase: 1, max: null, min: 0, show: true }, { format: "s", label: null, logBase: 1, max: null, min: 0, show: true } ] } ], repeat: null, repeatIteration: null, repeatRowId: null, showTitle: false, title: "Dashboard Row", titleSize: "h6", type: "row" }, { collapse: false, collapsed: false, panels: [ { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "$datasource", fill: 1, gridPos: {}, id: 11, legend: { alignAsTable: false, avg: false, current: false, max: false, min: false, rightSide: false, show: true, total: false, values: false }, lines: true, linewidth: 1, links: [], nullPointMode: "null", percentage: false, pointradius: 5, points: false, renderer: "flot", repeat: null, seriesOverrides: [], spaceLength: 10, span: 4, stack: false, steppedLine: false, targets: [ { expr: `process_resident_memory_bytes{integration_id="${integrationId}",job="apiserver",instance=~"$instance"}`, format: "time_series", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeShift: null, title: "Memory", tooltip: { shared: false, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { format: "bytes", label: null, logBase: 1, max: null, min: null, show: true }, { format: "bytes", label: null, logBase: 1, max: null, min: null, show: true } ] }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "$datasource", fill: 1, gridPos: {}, id: 12, legend: { alignAsTable: false, avg: false, current: false, max: false, min: false, rightSide: false, show: true, total: false, values: false }, lines: true, linewidth: 1, links: [], nullPointMode: "null", percentage: false, pointradius: 5, points: false, renderer: "flot", repeat: null, seriesOverrides: [], spaceLength: 10, span: 4, stack: false, steppedLine: false, targets: [ { expr: `rate(process_cpu_seconds_total{integration_id="${integrationId}",job="apiserver",instance=~"$instance"}[5m])`, format: "time_series", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeShift: null, title: "CPU usage", tooltip: { shared: false, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { format: "short", label: null, logBase: 1, max: null, min: 0, show: true }, { format: "short", label: null, logBase: 1, max: null, min: 0, show: true } ] }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "$datasource", fill: 1, gridPos: {}, id: 13, legend: { alignAsTable: false, avg: false, current: false, max: false, min: false, rightSide: false, show: true, total: false, values: false }, lines: true, linewidth: 1, links: [], nullPointMode: "null", percentage: false, pointradius: 5, points: false, renderer: "flot", repeat: null, seriesOverrides: [], spaceLength: 10, span: 4, stack: false, steppedLine: false, targets: [ { expr: `go_goroutines{integration_id="${integrationId}",job="apiserver",instance=~"$instance"}`, format: "time_series", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeShift: null, title: "Goroutines", tooltip: { shared: false, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { format: "short", label: null, logBase: 1, max: null, min: null, show: true }, { format: "short", label: null, logBase: 1, max: null, min: null, show: true } ] } ], repeat: null, repeatIteration: null, repeatRowId: null, showTitle: false, title: "Dashboard Row", titleSize: "h6", type: "row" } ], schemaVersion: 14, style: "dark", tags: ["kubernetes-integration"], templating: { list: [ { current: { text: "Prometheus", value: "Prometheus" }, hide: 0, label: null, name: "datasource", options: [], query: "prometheus", refresh: 1, regex: "", type: "datasource" }, { allValue: null, current: {}, datasource: "$datasource", hide: 0, includeAll: true, label: null, multi: false, name: "instance", options: [], query: `label_values(apiserver_request_total{job="apiserver"}, instance)`, refresh: 2, regex: "", sort: 0, tagValuesQuery: "", tags: [], tagsQuery: "", type: "query", useTags: false } ] }, time: { from: "now-1h", to: "now" }, timepicker: { refresh_intervals: [ "5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d" ], time_options: ["5m", "15m", "1h", "6h", "12h", "24h", "2d", "7d", "30d"] }, timezone: "", title: "Kubernetes / API server metrics", uid: `api-${integrationId}`, version: 0 }; } export type Dashboard = ReturnType<typeof makeDashboard>;
the_stack
import { ConfigEntry } from '@smartthings/core-sdk' export namespace DeviceHealthEvent { export enum StatusEnum { OFFLINE = 'OFFLINE', ONLINE = 'ONLINE', UNHEALTHY = 'UNHEALTHY' // TODO is this correct or is it the core API definition? } export enum ReasonEnum { NONE = 'NONE', SERVICE_UNAVAILABLE = 'SERVICE_UNAVAILABLE', HUB_OFFLINE = 'HUB_OFFLINE', ZWAVE_OFFLINE = 'ZWAVE_OFFLINE', ZIGBEE_OFFLINE = 'ZIGBEE_OFFLINE', BLUETOOTH_OFFLINE = 'BLUETOOTH_OFFLINE', HUB_DISCONNECTED = 'HUB_DISCONNECTED' } } export namespace HubHealthEvent { export enum StatusEnum { OFFLINE = 'OFFLINE', ONLINE = 'ONLINE', ZWAVE_OFFLINE = 'ZWAVE_OFFLINE', ZWAVE_ONLINE = 'ZWAVE_ONLINE', ZIGBEE_OFFLINE = 'ZIGBEE_OFFLINE', ZIGBEE_ONLINE = 'ZIGBEE_ONLINE', BLUETOOTH_OFFLINE = 'BLUETOOTH_OFFLINE', BLUETOOTH_ONLINE = 'BLUETOOTH_ONLINE' } export enum ReasonEnum { NONE = 'NONE', DISCONNECTED = 'DISCONNECTED', INACTIVE = 'INACTIVE' } } export namespace SecurityArmStateEvent { export enum ArmStateEnum { UNKNOWN = 'UNKNOWN', ARMED_STAY = 'ARMED_STAY', ARMED_AWAY = 'ARMED_AWAY', DISARMED = 'DISARMED' } } export namespace AppEvent { export enum ValueTypeEnum { NULL_VALUE = 'NULL_VALUE', INT_VALUE = 'INT_VALUE', DOUBLE_VALUE = 'DOUBLE_VALUE', STRING_VALUE = 'STRING_VALUE', BOOLEAN_VALUE = 'BOOLEAN_VALUE' } export interface DeviceEvent { /** * The ID of the event. */ eventId: string /** * The ID of the location in which the event was triggered. */ locationId: string /** * The ID of the device associated with the DEVICE_EVENT. */ deviceId: string /** * The name of the component on the device that the event is associated with. */ componentId: string /** * The name of the capability associated with the DEVICE_EVENT. */ capability: string /** * The name of the DEVICE_EVENT. This typically corresponds to an attribute name of the device-handler’s capabilities. */ attribute: string /** * The value of the event. The type of the value is dependent on the capability's attribute type. */ value: any /** * The root level data type of the value field. The data types are representative of standard JSON data types. */ valueType: string /** * Whether or not the state of the device has changed as a result of the DEVICE_EVENT. */ stateChange: boolean /** * json map as defined by capability data schema */ data: any /** * The name of subscription that caused delivery. */ subscriptionName: string } export enum DeviceLifecycle { CREATE = 'CREATE', DELETE = 'DELETE', UPDATE = 'UPDATE', MOVE_FROM = 'MOVE_FROM', MOVE_TO = 'MOVE_TO', } export interface DeviceLifecycleEvent { lifecycle: DeviceLifecycle; /** * The id of the event. */ eventId: string /** * The id of the location in which the event was triggered. */ locationId: string /** * The id of the device. */ deviceId: string /** * The name of the device */ deviceName: string /** * The principal that made the change */ principal: string // TODO -- figure this out // create: DeviceLifecycleCreate; // _delete: DeviceLifecycleDelete; // update: DeviceLifecycleUpdate; // moveFrom: DeviceLifecycleMove; // moveTo: DeviceLifecycleMove; } export interface DeviceHealthEvent { /** * The id of the event. */ eventId: string /** * The id of the location in which the event was triggered. */ locationId: string /** * The id of the device. */ deviceId: string /** * The id of the hub. */ hubId: string /** * The status of the device. */ status: DeviceHealthEvent.StatusEnum /** * The reason the device is offline. */ reason: DeviceHealthEvent.ReasonEnum } export interface HubHealthEvent { /** * The id of the event. */ eventId: string; /** * The id of the location in which the event was triggered. */ locationId: string; /** * The id of the hub. */ hubId: string; /** * The status of the hub. */ status: HubHealthEvent.StatusEnum; /** * The reason the hub is offline. */ reason: HubHealthEvent.ReasonEnum; } export class DeviceCommandsEventCommand { componentId: string capability: string command: string arguments: any[] } export interface DeviceCommandsEvent { /** * The id of the event. */ eventId: string /** * The guid of the device that the commands are for. */ deviceId: string /** * The device profile ID of the device instance. */ profileId: string /** * The external ID that was set during install of a device. */ externalId: string commands: DeviceCommandsEventCommand[] } export interface ModeEvent { /** * The id of the event. */ eventId: string /** * The id of the location in which the event was triggered. */ locationId: string /** * The ID of the mode associated with a MODE_EVENT. */ modeId: string } export interface TimerEvent { /** * The ID of the event. */ eventId: string /** * The name of the schedule that caused this event. */ name: string type: string // TimerType; TODO - what types? /** * The IS0-8601 date time strings in UTC that this event was scheduled for. */ time: Date /** * The CRON expression if the schedule was of type CRON. */ expression: string } export enum SceneLifecycle { CREATE = 'CREATE', DELETE = 'DELETE', UPDATE = 'UPDATE', } export interface SceneLifecycleEvent { lifecycle: SceneLifecycle /** * The id of the event. */ eventId: string /** * The id of the location in which the event was triggered. */ locationId: string /** * The id of the scene. */ sceneId: string // TODO - what are these? // 'create': SceneLifecycleCreate; // 'update': SceneLifecycleUpdate; // '_delete': SceneLifecycleDelete; } export interface SimpleValue { /** * The type of the value. */ valueType: ValueTypeEnum intValue: number doubleValue: number stringValue: string boolValue: boolean } export interface SecurityArmStateEvent { /** * The id of the event. */ eventId: string /** * The id of the location in which the event was triggered. */ locationId: string /** * The arm state of a security system. */ armState: SecurityArmStateEvent.ArmStateEnum /** * A set of key / value pairs useful for passing any optional arguments. */ optionalArguments: { [key: string]: SimpleValue } } export interface Event { /** * The IS0-8601 date time string in UTC that this event was created. */ eventTime: Date eventType: EventType deviceEvent: DeviceEvent deviceLifecycleEvent: DeviceLifecycleEvent deviceHealthEvent: DeviceHealthEvent deviceCommandsEvent: DeviceCommandsEvent modeEvent: ModeEvent timerEvent: TimerEvent sceneLifecycleEvent: SceneLifecycleEvent securityArmStateEvent: SecurityArmStateEvent } export interface EventData { authToken: string installedApp: InstalledApp events: Event[] } export type ConfigMap = {[name: string]: ConfigEntry[]} export type Permissions = string | string[] export interface InstalledApp { installedAppId: string locationId: string config: ConfigMap permissions: Permissions } export interface UpdateData { authToken: string refreshToken: string installedApp: InstalledApp previousConfig: ConfigMap previousPermissions: Permissions } export enum AppLifecycle { PING = 'PING', CONFIGURATION = 'CONFIGURATION', OAUTH_CALLBACK = 'OAUTH_CALLBACK', INSTALL = 'INSTALL', UPDATE = 'UPDATE', UNINSTALL = 'UNINSTALL', EVENT = 'EVENT', EXECUTE = 'EXECUTE', CONFIRMATION = 'CONFIRMATION', } export enum ConfigurationType { INITIALIZE = 'INITIALIZE', PAGE = 'PAGE' } export enum EventType { DEVICE_EVENT = 'DEVICE_EVENT', TIMER_EVENT = 'TIMER_EVENT', DEVICE_COMMANDS_EVENT = 'DEVICE_COMMANDS_EVENT', DEVICE_LIFECYCLE_EVENT = 'DEVICE_LIFECYCLE_EVENT', DEVICE_HEALTH_EVENT = 'DEVICE_HEALTH_EVENT', HUB_HEALTH_EVENT = 'HUB_HEALTH_EVENT', MODE_EVENT = 'MODE_EVENT', SECURITY_ARM_STATE_EVENT = 'SECURITY_ARM_STATE_EVENT', INSTALLED_APP_LIFECYCLE_EVENT = 'INSTALLED_APP_LIFECYCLE_EVENT', } export namespace ClientDetails { export enum DisplayModeEnum { DARK = 'DARK', LIGHT = 'LIGHT' } export enum SupportedTemplatesEnum { V1 = 'BASIC_V1', V2 = 'BASIC_V2' } } export interface ClientDetails { /** * The operating system of the client application initiating the request. */ os: string /** * The version of the client application initiating the request. */ version: string /** * Language header representing the clients preferred language. The format of the `Accept-Language` header follows what is defined in [RFC 7231, section 5.3.5](https://tools.ietf.org/html/rfc7231#section-5.3.5) */ language: string /** * The display mode of the operating system of the client. */ displayMode: ClientDetails.DisplayModeEnum /** * Templates that could be renderable in the client */ supportedTemplates: ClientDetails.SupportedTemplatesEnum[] } export interface InstallData { /** * An OAuth token to use when calling into SmartThings APIs. */ authToken: string /** * A refresh token which maybe used to obtain authorization to SmartThings API after expiration of the authToken. An integration will need to use this refreshToken to support calling the SmartThings API outside the context of an event. */ refreshToken: string installedApp: InstalledApp } export interface UninstallData { installedApp: InstalledApp } export interface ConfigurationData { /** * The id of the installed app. */ installedAppId: string phase: string // ConfigurationPhase TODO - what are these /** * A developer defined page ID. Must be URL safe characters. */ pageId: string /** * The previous page the user completed. Must be URL safe characters. */ previousPageId: string config: ConfigMap } export interface PingData { /** * A challenge phrase that the SmartApp must echo back to validate itself. */ challenge: string } export interface OAuthCallbackData { /** * The id of the installed app. */ installedAppId: string /** * A relative URL containing all of the query string parameters as returned by the third party oauth system. A SmartApp can parse the `urlPath` property to extract any sensitive auth codes/tokens which can then be used to access the third party system. */ urlPath: string } export interface ExecuteData { /** * An OAuth token to use when calling into SmartThings APIs. */ authToken: string installedApp: InstalledApp /** * An arbitrary map of input parameters which the SmartApp can use to build a custom response. */ parameters: { [key: string]: string } } export interface DashboardData { /** * An OAuth token to use when calling into SmartThings APIs. */ authToken: string installedApp: InstalledApp } export interface ConfirmationData { /** * A globally unique identifier for an app. */ appId: string /** * An HTTPS url that may be visited to confirm / activate an App registration. */ confirmationUrl: string } export interface ExecutionRequest { lifecycle: AppLifecycle executionId: string appId: string /** * An IETF BCP 47 language tag representing the chosen locale for this account. */ locale: string version: string client: ClientDetails eventData: EventData installData: InstallData updateData: UpdateData uninstallData: UninstallData configurationData: ConfigurationData pingData: PingData oauthCallbackData: OAuthCallbackData executeData: ExecuteData dashboardData: DashboardData confirmationData: ConfirmationData } }
the_stack
import { assert } from "chai"; import * as sinon from "sinon"; import { TimeoutError } from "../await/timeout-error"; import { assertErrorChain, fakeConnection } from "../helpers.spec"; import { JoinError } from "./join"; import { joinAll } from "./join-all"; function successResponsesForChannelChunk(channels: string[]): string[] { return channels.map( (ch) => `:justinfan12345!justinfan12345@justinfan12345.tmi.twitch.tv JOIN #${ch}` ); } describe("./operations/join-all", function () { describe("#joinAll()", function () { it("should send the correct wire command for a single chunk", function () { sinon.useFakeTimers(); const { client, data } = fakeConnection(); joinAll(client, ["pajlada", "randers", "nymn_hs", "forsen"]); assert.deepStrictEqual(data, [ "JOIN #pajlada,#randers,#nymn_hs,#forsen\r\n", ]); }); it("should send the correct wire command for a multiple chunks", async function () { const { client, clientError, emitAndEnd, emit, data } = fakeConnection(); const firstChunkChannels = [ "007_zeppelin", "00joel0", "00xxxzeroxxx00", "0414811480", "0hhhschnapp", "0liver92", "0malleycat", "0mrwaffles0", "0neeyedwolf", "0oopatrickoo0", "0strand47", "0wegtail0", "0x4c554b49", "101bryce", "1023alec", "112_ty", "123drnijal321", "123kosta", "123rollwithme", "12ballergarza", "12camster", "12kt3_", "12stealth", "13458788393762899", "13misterj", "142squad", "15santmyern", "1802_callum", "1_achillus_1", "1a2ip105josip", "1blessedmom", "1carrot_tv", "1charlie3_", "1darkss", "1jarelle", "1mattyp7", "1nekolai", "1o0qnov7", "1regular_guy", "1shoot1heat1", "1ststring", "1stworldgg", "1thefighter2", "1thegreenarrow1", "1trutank", "1wilshire", "1wolverine59", "1yourmom4", "20thcenturyrasta", "21cheeseheadtv", "23al3o7", "23chrism", "2447indiana", "24_hollywood_", "24atabe", "24k_jsmooth", "25an8th", "26shorty11", "27aaaaaaaaaaz", "2icyalpha", "2kcheezy", "2muchp0wer", "2ndtrip", "2ofemyesterday", "2philosophy4", "2rushthefrog", "2twotango", "2what2nani2", "2xxhitmanxx6", "30clipkey", "30indabasement", "317536", "31conspiracy", "31valerio", "33dommarino", "3ddielurkk", "3ddy3d", "3diii", "3lch0b1", "3puttbirdie", "3rnrkassanyt", "412_sye", "420_playzz", "420darthreefer", "4511_911", "46legend", "47ripz", "4chainreaver", "4nanassalad", "4nugg", "4secs", "4tn1ght", "50cal_muaythai", "50nocent", "5330b8", "54bryce54", "559slumpgod", "55sllew", "5alixz", "5h4h", "5iivebodies", "5roachdylan", "5starbr686", "5tylepointz", "610harry", "64c248", "661patrick", "676755678696", "69purepenguin69", "6_leprbeast_12", "6lack_shinobi", "6lue6illsonat", "70grade", "7hebrady", "7mdanz", "7wells_", "801_mk4r32", "850k0p3ning", "88littlefoot88", "8bombtv", "8thoctopuz", "98dark98", "98sparkz", "9calighost4", "a1d3ns4stdad", "a1phadog1", "a1thicksauce", "a4k_scope", "a55eater51", "a63caddyboy", "a6g0d", "a__d__a__m_", "a_deadly_love", "a_hal0_pr0d1gy", "a_skylit_drive", "aaghaad", "aahtherapy", "aandy_11", "aaronbull22010123", "aaronfhd", "aaronhenry4", "aaronrosse55", "aaronscharf", "aarun_", "aasc19", "aashuraaa", "aasomee", "aayyoo_brian", "ab_pete21", "abaked_potato_27", "abakedfish", "abbyzgamingchannel", "abchxnn", "abcomb", "abdul_jahar_", "abenedict7", "abennett11", "abergsoften", "aberrant_ninja", "abhishekc22", "abitdelusional", "abn_vp_polo", "abode_juve", "abominableally", "aboriyan7", "about_75_puppies", "abovexcloudz", "aboyero97", "abraham_h12", "abraxaslobo", "abrightshadow", "abskater02", "absolutemachine1", "abstracreality", "absurdityttv", "absxrdityx", "abusemiicro", "abusyseagull", "acanizal521", "accretian", "accurateee", "aceboogie_215", "acedrewfiggy", "acehuntinyt", "acerfoxz", "acescorpion35555", "acethemace4", "acethough", "achieverexe", "achillesj", "acho1117", "achtlireinhardt", "achubyredneck", "acidzloco", "ackes", "ackey917", "acm6600", "acornzzzz", "acorrn", "acr202", "acrdominate", "acridwindow5397", "acrobaticfork", "acrowe412", "activetwirl", "acupzz", "acweezy", "ad__23", "adam97416", "adamantassassin", "adamdotson1994", "adamdumb", "adameric85", "adamjbrown10", "adamjonezi", "adamkopo", "adamnat95", "adamroark1996", "adamshortt123", "adamwarlock_", "adan0520", "adan_4tears", "adansanch94", "adavi_", "addroon", "adeddy", "adel0406", "ademonstration", "adhd_alex99", "adiaxe_x", "adnane_benany", "ado_da_don", "adok25", "adonisvango", "adonzo14", "adooooo", "adrialeti1810", "adrian0368", "adrianarmitage1134", "adriaxpaola", "adrielomo", "adrocess", "adrugaddictstream", "adstban", "adub12w", "adude03", "aduval_", "advancednewb", "advancedprimate", "advilow", "adz89_", "aei1119", "aergl0w", "aero2448", "aerusam", "aesselidrah", "aether_shiv", "aetherinthek", "afgbludz", "afolabi180", "afonsocruz9817", "afro_budd_98", "afroblack", "afroditto", "afterearth323", "aftm12", "aftnine", "ag3k20205", "ag_shmopboy", "agbonzzorn", "agecristina", "agerasan", "agirlcalledjim", "aglore94", "agonzales003", "agoracy", "aguilarj13", "aguynamede", "agxd3m0n", "ahacienda", "ahhh_griff", "ahmad_kurd_", "ahmed200438", "ahnegrotwt", "ahole232", "ahopkins2018", "ahrnesson1919", "aicudi", "aidankitts", "aidant1992", "aiden1328", "aiden_like_what", "aidenhamilton", "aidxstown", "aiglon19", "aiirplays", "ailoator", "aimbrat_", "aimoroyale", "aiphameez", "air_agu", "airbusadam", "airk00laid09", "airweeily", "aizenxhollow", "aj2nd", "aj_25", "aj_the1st", "aj_wint", "aj_zzzzz", "ajayx_x", "ajboolin", "ajbrown30", "ajcase21", "ajhollowayvrm", "ajkauri", "ajm7aus", "ajmack21", "ajr_95", "ajxrunnerx", "ak__er1nho__47", "aka_bloodtooth", "aka_mrx", "aka_shots", "akabani", "akamalikk", "akarobles", "akasuspect", "akathektos", "akeekerz", "akg_alpha", "akibbarvatiya", "akiileez", "akillerintux", "akira_hdk", "akiraarcade", "akirazlol", "akjomab", "akkvme", "akonel89", "akretsch10", "akse1234", "akselmaron", ]; const secondChunkChannels = ["pajlada", "nymn_hs", "forsen"]; const channels = [...firstChunkChannels, ...secondChunkChannels]; const promise = joinAll(client, channels); // method sends first chunk... assert.deepStrictEqual(data, [ "JOIN #" + firstChunkChannels.join(",#") + "\r\n", ]); // then awaits all responses/failures for that chunk... // let's simulate 100% success emit(...successResponsesForChannelChunk(firstChunkChannels)); // wait for promised to be settled in the response handling await new Promise((resolve) => setImmediate(resolve)); assert.deepStrictEqual(data, [ "JOIN #" + firstChunkChannels.join(",#") + "\r\n", "JOIN #pajlada,#nymn_hs,#forsen\r\n", ]); // leave out nymn_hs so nymn_hs should have an error (outpaced) emitAndEnd( ":justinfan12345!justinfan12345@justinfan12345.tmi.twitch.tv JOIN #pajlada", ":justinfan12345!justinfan12345@justinfan12345.tmi.twitch.tv JOIN #forsen" ); const results = await promise; // no error for successful channel // tslint:disable-next-line:no-string-literal assert.isUndefined(results["pajlada"]); // error for nymn_hs (no response received) assertErrorChain( // tslint:disable-next-line:no-string-literal results["nymn_hs"], JoinError, "Failed to join channel nymn_hs: A response to a command issued later than this command was received", TimeoutError, "A response to a command issued later than this command was received" ); assert.isTrue(client.wantedChannels.has("nymn_hs")); assert.isFalse(client.joinedChannels.has("nymn_hs")); assert.isTrue(client.wantedChannels.has("pajlada")); assert.isTrue(client.joinedChannels.has("pajlada")); await assertErrorChain( clientError, JoinError, "Failed to join channel nymn_hs: A response to a command issued later than this command was received", TimeoutError, "A response to a command issued later than this command was received" ); }); }); });
the_stack
import { V1PodTemplateSpec, V1Container, V1Probe, V1Volume, V1PodSpec, V1KeyToPath, V1ContainerPort, V1VolumeMount } from "@kubernetes/client-node"; import { isPodSpecTemplateEqual } from "./Pod"; // mock logger jest.mock("@opstrace/utils", () => ({ log: { debug: jest.fn } })); function generateProbe(template: Partial<V1Probe> = {}): Required<V1Probe> { return { exec: { command: ["cat", "/tmp/healthy"] }, failureThreshold: 1, initialDelaySeconds: 5, periodSeconds: 5, httpGet: { // @ts-ignore should be number, not object as TS insists port: 3000 }, successThreshold: 1, timeoutSeconds: 1, tcpSocket: { // @ts-ignore should be number, not object as TS insists port: 8080 }, ...template }; } function generateContainerPort( template: Partial<V1ContainerPort> = {} ): V1ContainerPort { return { name: "my-port", containerPort: 1001, hostPort: 2001, ...template }; } function generateVolumeMount( template: Partial<V1VolumeMount> = {} ): V1VolumeMount { return { name: "my-volume", mountPath: "/mountPath", subPath: "/subpath", ...template }; } function generateContainer(template: Partial<V1Container> = {}): V1Container { return { name: "busybox", image: "busybox:1.25", ports: [ generateContainerPort({ name: "port-one" }), generateContainerPort({ name: "port-two" }), generateContainerPort({ name: "port-three" }) ], volumeMounts: [ generateVolumeMount({ name: "volume-mount-one" }), generateVolumeMount({ name: "volume-mount-two" }), generateVolumeMount({ name: "volume-mount-three" }) ], env: [ { name: "my-env", value: "my-env-value" } ], args: ["HOSTNAME", "KUBERNETES_PORT"], livenessProbe: generateProbe(), readinessProbe: generateProbe(), ...template }; } function generateVolumeItem(template: Partial<V1KeyToPath> = {}): V1KeyToPath { return { key: "SPECIAL_LEVEL", mode: 511, path: "keys", ...template }; } function generateVolumes(template: Partial<V1Volume> = {}): V1Volume { return { name: "my-volume", configMap: { defaultMode: 511, name: "special-config", optional: false, items: [ generateVolumeItem({ key: "ONE" }), generateVolumeItem({ key: "TWO" }), generateVolumeItem({ key: "THREE" }) ] }, secret: { defaultMode: 511, secretName: "special-secret", optional: false, items: [ generateVolumeItem({ key: "FOUR" }), generateVolumeItem({ key: "FIVE" }), generateVolumeItem({ key: "SEVEN" }) ] }, ...template }; } function generatePodSpec(): V1PodSpec { return { serviceAccountName: "my-service-account", containers: [generateContainer()], initContainers: [generateContainer()], volumes: [generateVolumes()] }; } // return pod for testing function generatePodTemplateSpec( template: Partial<V1PodTemplateSpec> = {} ): Required<V1PodTemplateSpec> { return { metadata: { /* start default metadata */ generation: 1, resourceVersion: "1234", selfLink: "/random/string", uid: "randomstring", /* end default metadata */ annotations: { some: "annotation" }, labels: { some: "label" } }, spec: generatePodSpec(), ...template }; } test("should return true when spec matches", () => { const desired = generatePodTemplateSpec(); const existing = generatePodTemplateSpec(); expect(isPodSpecTemplateEqual(desired, existing)).toBe(true); }); test("should return true when spec matches and default metatada is set", () => { const desired = generatePodTemplateSpec({ metadata: { generation: 1, resourceVersion: "1234", selfLink: "/random/string", uid: "randomstring" } }); const existing = generatePodTemplateSpec({ metadata: { generation: 2, resourceVersion: "5678", selfLink: "/even/more/random/string", uid: "evenmorerandomstring" } }); expect(isPodSpecTemplateEqual(desired, existing)).toBe(true); }); describe("volumes", () => { it("should return true when volumes have not changed", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.volumes = [generateVolumes(), generateVolumes()]; desired.spec.volumes = [generateVolumes(), generateVolumes()]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(true); }); it("should return false when volume names changed", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.volumes = [ generateVolumes({ name: "old name one" }), generateVolumes({ name: "new name two" }) ]; desired.spec.volumes = [ generateVolumes({ name: "new name one" }), generateVolumes({ name: "new name two" }) ]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); describe("configMap", () => { describe("items", () => { it("should return false when items have changed", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.volumes![0].configMap!.items = [ generateVolumeItem({ key: "ONE OLD" }), generateVolumeItem({ key: "TWO OLD" }), generateVolumeItem({ key: "THREE OLD" }) ]; desired.spec.volumes![0].configMap!.items = [ generateVolumeItem({ key: "ONE NEW" }), generateVolumeItem({ key: "TWO NEW" }) ]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); }); }); describe("secrets", () => { describe("items", () => { it("should return false when items have changed", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.volumes![0].secret!.items = [ generateVolumeItem({ key: "ONE OLD" }), generateVolumeItem({ key: "TWO OLD" }), generateVolumeItem({ key: "THREE OLD" }) ]; desired.spec.volumes![0].secret!.items = [ generateVolumeItem({ key: "ONE NEW" }), generateVolumeItem({ key: "TWO NEW" }) ]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); }); }); }); describe("initContainers", () => { it("should return true when initContainers have not changed", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.initContainers = [generateContainer(), generateContainer()]; desired.spec.initContainers = [generateContainer(), generateContainer()]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(true); }); it("should return false when initContainers amount has changed", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.initContainers = [generateContainer(), generateContainer()]; desired.spec.initContainers = [generateContainer()]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); }); describe("containers", () => { it("should return true when containers have not changed", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.containers = [generateContainer(), generateContainer()]; desired.spec.containers = [generateContainer(), generateContainer()]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(true); }); it("should return false when container amount has changed", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.containers = [generateContainer(), generateContainer()]; desired.spec.containers = [generateContainer()]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); describe("ports", () => { it("should return false when quantity changes", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.containers[0].ports = [ generateContainerPort(), generateContainerPort() ]; desired.spec.containers[0].ports = [generateContainerPort()]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); it("should return false when name doesnt match", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.containers[0].ports = [ generateContainerPort({ name: "old" }) ]; desired.spec.containers[0].ports = [ generateContainerPort({ name: "new" }) ]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); it("should return false when containerPort doesnt match", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.containers[0].ports = [ generateContainerPort({ containerPort: 1 }) ]; desired.spec.containers[0].ports = [ generateContainerPort({ containerPort: 2 }) ]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); it("should return false when hostPort doesnt match", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.containers[0].ports = [ generateContainerPort({ hostPort: 1 }) ]; desired.spec.containers[0].ports = [ generateContainerPort({ hostPort: 2 }) ]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); }); describe("volume mounts", () => { it("should return false when quantity changes", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.containers[0].volumeMounts = [ generateVolumeMount(), generateVolumeMount() ]; desired.spec.containers[0].volumeMounts = [generateVolumeMount()]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); it("should return false when name doesnt match", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.containers[0].volumeMounts = [ generateVolumeMount({ name: "old" }) ]; desired.spec.containers[0].volumeMounts = [ generateVolumeMount({ name: "new" }) ]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); it("should return false when mountPath doesnt match", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.containers[0].volumeMounts = [ generateVolumeMount({ mountPath: "mount-path-old" }) ]; desired.spec.containers[0].volumeMounts = [ generateVolumeMount({ mountPath: "mount-path-new" }) ]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); it("should return false when subPath doesnt match", () => { const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.containers[0].volumeMounts = [ generateVolumeMount({ subPath: "sub-path-old" }) ]; desired.spec.containers[0].volumeMounts = [ generateVolumeMount({ subPath: "sub-path-new" }) ]; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); }); describe("liveness probe", () => { it("should return false when exec doesnt match", () => { const existingProbe = generateProbe(); const desiredProbe = generateProbe({ exec: { command: ["different", "command"] } }); const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.containers[0].livenessProbe = existingProbe; desired.spec.containers[0].livenessProbe = desiredProbe; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); it("should return false when httpGet doesnt match", () => { const existingProbe = generateProbe(); const desiredProbe = generateProbe({ httpGet: { // @ts-ignore should be number, not object as TS insists port: 3001 } }); const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.containers[0].livenessProbe = existingProbe; desired.spec.containers[0].livenessProbe = desiredProbe; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); it("should return false when tcpSocket doesnt match", () => { const existingProbe = generateProbe(); const desiredProbe = generateProbe({ tcpSocket: { // @ts-ignore should be number, not object as TS insists port: 3001 } }); const existing = generatePodTemplateSpec(); const desired = generatePodTemplateSpec(); existing.spec.containers[0].livenessProbe = existingProbe; desired.spec.containers[0].livenessProbe = desiredProbe; expect(isPodSpecTemplateEqual(desired, existing)).toBe(false); }); }); });
the_stack
module android.app { const MATCH_PARENT = android.view.ViewGroup.LayoutParams.MATCH_PARENT; import R = android.R; import AlertDialog = android.app.AlertDialog; import DialogInterface = android.content.DialogInterface; import Drawable = android.graphics.drawable.Drawable; import ColorDrawable = android.graphics.drawable.ColorDrawable; import Color = android.graphics.Color; import Handler = android.os.Handler; import Message = android.os.Message; import TextUtils = android.text.TextUtils; import TypedValue = android.util.TypedValue; import Gravity = android.view.Gravity; import KeyEvent = android.view.KeyEvent; import LayoutInflater = android.view.LayoutInflater; import View = android.view.View; import ViewGroup = android.view.ViewGroup; import LayoutParams = android.view.ViewGroup.LayoutParams; import Window = android.view.Window; import WindowManager = android.view.WindowManager; import AdapterView = android.widget.AdapterView; import OnItemClickListener = android.widget.AdapterView.OnItemClickListener; import ArrayAdapter = android.widget.ArrayAdapter; import Button = android.widget.Button; import FrameLayout = android.widget.FrameLayout; import ImageView = android.widget.ImageView; import LinearLayout = android.widget.LinearLayout; import ListAdapter = android.widget.ListAdapter; import ListView = android.widget.ListView; import ScrollView = android.widget.ScrollView; import TextView = android.widget.TextView; import WeakReference = java.lang.ref.WeakReference; import Dialog = android.app.Dialog; import Context = android.content.Context; export class AlertController { private mContext:Context; private mDialogInterface:DialogInterface; private mWindow:Window; private mTitle:string; private mMessage:string; private mListView:ListView; private mView:View; private mViewSpacingLeft:number = 0; private mViewSpacingTop:number = 0; private mViewSpacingRight:number = 0; private mViewSpacingBottom:number = 0; private mViewSpacingSpecified:boolean = false; private mButtonPositive:Button; private mButtonPositiveText:string; private mButtonPositiveMessage:Message; private mButtonNegative:Button; private mButtonNegativeText:string; private mButtonNegativeMessage:Message; private mButtonNeutral:Button; private mButtonNeutralText:string; private mButtonNeutralMessage:Message; private mScrollView:ScrollView; //private mIconId:number = -1; private mIcon:Drawable; private mIconView:ImageView; private mTitleView:TextView; private mMessageView:TextView; private mCustomTitleView:View; private mForceInverseBackground:boolean; private mAdapter:ListAdapter; private mCheckedItem:number = -1; private mAlertDialogLayout:string; private mListLayout:string; private mMultiChoiceItemLayout:string; private mSingleChoiceItemLayout:string; private mListItemLayout:string; private mHandler:Handler; mButtonHandler:View.OnClickListener = (()=> { const inner_this = this; class _Inner implements View.OnClickListener { onClick(v:View):void { let m:Message = null; if (v == inner_this.mButtonPositive && inner_this.mButtonPositiveMessage != null) { m = Message.obtain(inner_this.mButtonPositiveMessage); } else if (v == inner_this.mButtonNegative && inner_this.mButtonNegativeMessage != null) { m = Message.obtain(inner_this.mButtonNegativeMessage); } else if (v == inner_this.mButtonNeutral && inner_this.mButtonNeutralMessage != null) { m = Message.obtain(inner_this.mButtonNeutralMessage); } if (m != null) { m.sendToTarget(); } // Post a message so we dismiss after the above handlers are executed inner_this.mHandler.obtainMessage(AlertController.ButtonHandler.MSG_DISMISS_DIALOG, inner_this.mDialogInterface).sendToTarget(); } } return new _Inner(); })(); private static shouldCenterSingleButton(context:Context):boolean { return true; //let outValue:TypedValue = new TypedValue(); //context.getTheme().resolveAttribute(android.R.attr.alertDialogCenterButtons, outValue, true); //return outValue.data != 0; } constructor(context:Context, di:DialogInterface, window:Window) { this.mContext = context; this.mDialogInterface = di; this.mWindow = window; this.mHandler = new AlertController.ButtonHandler(di); //let a:TypedArray = context.obtainStyledAttributes(null, com.android.internal.R.styleable.AlertDialog, com.android.internal.R.attr.alertDialogStyle, 0); this.mAlertDialogLayout = R.layout.alert_dialog; this.mListLayout = R.layout.select_dialog; this.mMultiChoiceItemLayout = R.layout.select_dialog_multichoice; this.mSingleChoiceItemLayout = R.layout.select_dialog_singlechoice; this.mListItemLayout = R.layout.select_dialog_item; //a.recycle(); } //static canTextInput(v:View):boolean { // if (v.onCheckIsTextEditor()) { // return true; // } // if (!(v instanceof ViewGroup)) { // return false; // } // let vg:ViewGroup = <ViewGroup> v; // let i:number = vg.getChildCount(); // while (i > 0) { // i--; // v = vg.getChildAt(i); // if (AlertController.canTextInput(v)) { // return true; // } // } // return false; //} installContent():void { /* We use a custom title so never request a window title */ //this.mWindow.requestFeature(Window.FEATURE_NO_TITLE); //if (this.mView == null || !AlertController.canTextInput(this.mView)) { // this.mWindow.setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); //} let layout = this.mContext.getLayoutInflater().inflate(this.mAlertDialogLayout, this.mWindow.getContentParent(), false); this.mWindow.setContentView(layout); this.setupView(); } setTitle(title:string):void { this.mTitle = title; if (this.mTitleView != null) { this.mTitleView.setText(title); } } /** * @see AlertDialog.Builder#setCustomTitle(View) */ setCustomTitle(customTitleView:View):void { this.mCustomTitleView = customTitleView; } setMessage(message:string):void { this.mMessage = message; if (this.mMessageView != null) { this.mMessageView.setText(message); } } ///** // * Set the view to display in the dialog. // */ //setView(view:View):void { // this.mView = view; // this.mViewSpacingSpecified = false; //} /** * Set the view to display in the dialog along with the spacing around that view */ setView(view:View, viewSpacingLeft = 0, viewSpacingTop = 0, viewSpacingRight = 0, viewSpacingBottom = 0):void { this.mView = view; if (!viewSpacingLeft && !viewSpacingTop && !viewSpacingRight && !viewSpacingBottom) { this.mViewSpacingSpecified = false; } else { this.mViewSpacingSpecified = true; this.mViewSpacingLeft = viewSpacingLeft; this.mViewSpacingTop = viewSpacingTop; this.mViewSpacingRight = viewSpacingRight; this.mViewSpacingBottom = viewSpacingBottom; } } /** * Sets a click listener or a message to be sent when the button is clicked. * You only need to pass one of {@code listener} or {@code msg}. * * @param whichButton Which button, can be one of * {@link DialogInterface#BUTTON_POSITIVE}, * {@link DialogInterface#BUTTON_NEGATIVE}, or * {@link DialogInterface#BUTTON_NEUTRAL} * @param text The text to display in positive button. * @param listener The {@link DialogInterface.OnClickListener} to use. * @param msg The {@link Message} to be sent when clicked. */ setButton(whichButton:number, text:string, listener:DialogInterface.OnClickListener, msg:Message):void { if (msg == null && listener != null) { msg = this.mHandler.obtainMessage(whichButton, listener); } switch (whichButton) { case DialogInterface.BUTTON_POSITIVE: this.mButtonPositiveText = text; this.mButtonPositiveMessage = msg; break; case DialogInterface.BUTTON_NEGATIVE: this.mButtonNegativeText = text; this.mButtonNegativeMessage = msg; break; case DialogInterface.BUTTON_NEUTRAL: this.mButtonNeutralText = text; this.mButtonNeutralMessage = msg; break; default: throw Error(`new IllegalArgumentException("Button does not exist")`); } } /** * Set resId to 0 if you don't want an icon. * @param resId the resourceId of the drawable to use as the icon or 0 * if you don't want an icon. */ //setIcon(resId:number):void { // this.mIconId = resId; // if (this.mIconView != null) { // if (resId > 0) { // this.mIconView.setImageResource(this.mIconId); // } else if (resId == 0) { // this.mIconView.setVisibility(View.GONE); // } // } //} setIcon(icon:Drawable):void { this.mIcon = icon; if ((this.mIconView != null) && (this.mIcon != null)) { this.mIconView.setImageDrawable(icon); } } ///** // * @param attrId the attributeId of the theme-specific drawable // * to resolve the resourceId for. // * // * @return resId the resourceId of the theme-specific drawable // */ //getIconAttributeResId(attrId:number):number { // let out:TypedValue = new TypedValue(); // this.mContext.getTheme().resolveAttribute(attrId, out, true); // return out.resourceId; //} setInverseBackgroundForced(forceInverseBackground:boolean):void { this.mForceInverseBackground = forceInverseBackground; } getListView():ListView { return this.mListView; } getButton(whichButton:number):Button { switch (whichButton) { case DialogInterface.BUTTON_POSITIVE: return this.mButtonPositive; case DialogInterface.BUTTON_NEGATIVE: return this.mButtonNegative; case DialogInterface.BUTTON_NEUTRAL: return this.mButtonNeutral; default: return null; } } onKeyDown(keyCode:number, event:KeyEvent):boolean { return this.mScrollView != null && this.mScrollView.executeKeyEvent(event); } onKeyUp(keyCode:number, event:KeyEvent):boolean { return this.mScrollView != null && this.mScrollView.executeKeyEvent(event); } private setupView():void { let contentPanel:LinearLayout = <LinearLayout> this.mWindow.findViewById(R.id.contentPanel); this.setupContent(contentPanel); let hasButtons:boolean = this.setupButtons(); let topPanel:LinearLayout = <LinearLayout> this.mWindow.findViewById(R.id.topPanel); //let a:TypedArray = this.mContext.obtainStyledAttributes(null, com.android.internal.R.styleable.AlertDialog, com.android.internal.R.attr.alertDialogStyle, 0); let hasTitle:boolean = this.setupTitle(topPanel); let buttonPanel:View = this.mWindow.findViewById(R.id.buttonPanel); if (!hasButtons) { buttonPanel.setVisibility(View.GONE); this.mWindow.setCloseOnTouchOutsideIfNotSet(true); } let customPanel:FrameLayout = null; if (this.mView != null) { customPanel = <FrameLayout> this.mWindow.findViewById(R.id.customPanel); let custom:FrameLayout = <FrameLayout> this.mWindow.findViewById(R.id.custom); custom.addView(this.mView, new LayoutParams(MATCH_PARENT, MATCH_PARENT)); if (this.mViewSpacingSpecified) { custom.setPadding(this.mViewSpacingLeft, this.mViewSpacingTop, this.mViewSpacingRight, this.mViewSpacingBottom); } if (this.mListView != null) { (<LinearLayout.LayoutParams> customPanel.getLayoutParams()).weight = 0; } } else { this.mWindow.findViewById(R.id.customPanel).setVisibility(View.GONE); } /* Only display the divider if we have a title and a * custom view or a message. */ if (hasTitle) { let divider:View = null; if (this.mMessage != null || this.mView != null || this.mListView != null) { divider = this.mWindow.findViewById(R.id.titleDivider); } else { divider = this.mWindow.findViewById(R.id.titleDividerTop); } if (divider != null) { divider.setVisibility(View.VISIBLE); } } this.setBackground(topPanel, contentPanel, customPanel, hasButtons, hasTitle, buttonPanel); //a.recycle(); } private setupTitle(topPanel:LinearLayout):boolean { let hasTitle:boolean = true; if (this.mCustomTitleView != null) { // Add the custom title view directly to the topPanel layout let lp:LinearLayout.LayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); topPanel.addView(this.mCustomTitleView, 0, lp); // Hide the title template let titleTemplate:View = this.mWindow.findViewById(R.id.title_template); titleTemplate.setVisibility(View.GONE); } else { const hasTextTitle:boolean = !TextUtils.isEmpty(this.mTitle); this.mIconView = <ImageView> this.mWindow.findViewById(R.id.icon); if (hasTextTitle) { /* Display the title if a title is supplied, else hide it */ this.mTitleView = <TextView> this.mWindow.findViewById(R.id.alertTitle); this.mTitleView.setText(this.mTitle); /* Do this last so that if the user has supplied any * icons we use them instead of the default ones. If the * user has specified 0 then make it disappear. */ //if (this.mIconId > 0) { // this.mIconView.setImageResource(this.mIconId); //} else if (this.mIcon != null) { this.mIconView.setImageDrawable(this.mIcon); } else //if (this.mIconId == 0) { /* Apply the padding from the icon to ensure the * title is aligned correctly. */ this.mTitleView.setPadding(this.mIconView.getPaddingLeft(), this.mIconView.getPaddingTop(), this.mIconView.getPaddingRight(), this.mIconView.getPaddingBottom()); this.mIconView.setVisibility(View.GONE); } } else { // Hide the title template let titleTemplate:View = this.mWindow.findViewById(R.id.title_template); titleTemplate.setVisibility(View.GONE); this.mIconView.setVisibility(View.GONE); topPanel.setVisibility(View.GONE); hasTitle = false; } } return hasTitle; } private setupContent(contentPanel:LinearLayout):void { this.mScrollView = <ScrollView> this.mWindow.findViewById(R.id.scrollView); this.mScrollView.setFocusable(false); // Special case for users that only want to display a String this.mMessageView = <TextView> this.mWindow.findViewById(R.id.message); if (this.mMessageView == null) { return; } if (this.mMessage != null) { this.mMessageView.setText(this.mMessage); } else { this.mMessageView.setVisibility(View.GONE); this.mScrollView.removeView(this.mMessageView); if (this.mListView != null) { contentPanel.removeView(this.mWindow.findViewById(R.id.scrollView)); contentPanel.addView(this.mListView, new LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)); contentPanel.setLayoutParams(new LinearLayout.LayoutParams(MATCH_PARENT, 0, 1.0)); } else { contentPanel.setVisibility(View.GONE); } } } private setupButtons():boolean { let BIT_BUTTON_POSITIVE:number = 1; let BIT_BUTTON_NEGATIVE:number = 2; let BIT_BUTTON_NEUTRAL:number = 4; let whichButtons:number = 0; this.mButtonPositive = <Button> this.mWindow.findViewById(R.id.button1); this.mButtonPositive.setOnClickListener(this.mButtonHandler); if (TextUtils.isEmpty(this.mButtonPositiveText)) { this.mButtonPositive.setVisibility(View.GONE); } else { this.mButtonPositive.setText(this.mButtonPositiveText); this.mButtonPositive.setVisibility(View.VISIBLE); whichButtons = whichButtons | BIT_BUTTON_POSITIVE; } this.mButtonNegative = <Button> this.mWindow.findViewById(R.id.button2); this.mButtonNegative.setOnClickListener(this.mButtonHandler); if (TextUtils.isEmpty(this.mButtonNegativeText)) { this.mButtonNegative.setVisibility(View.GONE); } else { this.mButtonNegative.setText(this.mButtonNegativeText); this.mButtonNegative.setVisibility(View.VISIBLE); whichButtons = whichButtons | BIT_BUTTON_NEGATIVE; } this.mButtonNeutral = <Button> this.mWindow.findViewById(R.id.button3); this.mButtonNeutral.setOnClickListener(this.mButtonHandler); if (TextUtils.isEmpty(this.mButtonNeutralText)) { this.mButtonNeutral.setVisibility(View.GONE); } else { this.mButtonNeutral.setText(this.mButtonNeutralText); this.mButtonNeutral.setVisibility(View.VISIBLE); whichButtons = whichButtons | BIT_BUTTON_NEUTRAL; } if (AlertController.shouldCenterSingleButton(this.mContext)) { /* * If we only have 1 button it should be centered on the layout and * expand to fill 50% of the available space. */ if (whichButtons == BIT_BUTTON_POSITIVE) { this.centerButton(this.mButtonPositive); } else if (whichButtons == BIT_BUTTON_NEGATIVE) { this.centerButton(this.mButtonNegative); } else if (whichButtons == BIT_BUTTON_NEUTRAL) { this.centerButton(this.mButtonNeutral); } } return whichButtons != 0; } private centerButton(button:Button):void { let params:LinearLayout.LayoutParams = <LinearLayout.LayoutParams> button.getLayoutParams(); params.gravity = Gravity.CENTER_HORIZONTAL; params.weight = 0.5; button.setLayoutParams(params); let leftSpacer:View = this.mWindow.findViewById(R.id.leftSpacer); if (leftSpacer != null) { leftSpacer.setVisibility(View.VISIBLE); } let rightSpacer:View = this.mWindow.findViewById(R.id.rightSpacer); if (rightSpacer != null) { rightSpacer.setVisibility(View.VISIBLE); } } private setBackground(topPanel:LinearLayout, contentPanel:LinearLayout, customPanel:View, hasButtons:boolean, hasTitle:boolean, buttonPanel:View):void { /* Get all the different background required */ let fullDark:Drawable = R.image.popup_full_bright;//R.drawable.popup_full_dark; let topDark:Drawable = R.image.popup_top_bright;//R.drawable.popup_top_dark; let centerDark:Drawable = R.image.popup_center_bright;//R.drawable.popup_center_dark; let bottomDark:Drawable = R.image.popup_bottom_bright;//R.drawable.popup_bottom_dark; let fullBright:Drawable = R.image.popup_full_bright; let topBright:Drawable = R.image.popup_top_bright; let centerBright:Drawable = R.image.popup_center_bright; let bottomBright:Drawable = R.image.popup_bottom_bright; let bottomMedium:Drawable = R.image.popup_bottom_bright;//R.drawable.popup_bottom_medium; /* * We now set the background of all of the sections of the alert. * First collect together each section that is being displayed along * with whether it is on a light or dark background, then run through * them setting their backgrounds. This is complicated because we need * to correctly use the full, top, middle, and bottom graphics depending * on how many views they are and where they appear. */ let views:View[] = new Array<View>(4); let light:boolean[] = new Array<boolean>(4); let lastView:View = null; let lastLight:boolean = false; let pos:number = 0; if (hasTitle) { views[pos] = topPanel; light[pos] = false; pos++; } /* The contentPanel displays either a custom text message or * a ListView. If it's text we should use the dark background * for ListView we should use the light background. If neither * are there the contentPanel will be hidden so set it as null. */ views[pos] = (contentPanel.getVisibility() == View.GONE) ? null : contentPanel; light[pos] = this.mListView != null; pos++; if (customPanel != null) { views[pos] = customPanel; light[pos] = this.mForceInverseBackground; pos++; } if (hasButtons) { views[pos] = buttonPanel; light[pos] = true; } let setView:boolean = false; for (pos = 0; pos < views.length; pos++) { let v:View = views[pos]; if (v == null) { continue; } if (lastView != null) { if (!setView) { lastView.setBackground(lastLight ? topBright : topDark); } else { lastView.setBackground(lastLight ? centerBright : centerDark); } setView = true; } lastView = v; lastLight = light[pos]; } if (lastView != null) { if (setView) { /* ListViews will use the Bright background but buttons use * the Medium background. */ lastView.setBackground(lastLight ? (hasButtons ? bottomMedium : bottomBright) : bottomDark); } else { lastView.setBackground(lastLight ? fullBright : fullDark); } } if ((this.mListView != null) && (this.mAdapter != null)) { this.mListView.setAdapter(this.mAdapter); if (this.mCheckedItem > -1) { this.mListView.setItemChecked(this.mCheckedItem, true); this.mListView.setSelection(this.mCheckedItem); } } } } export module AlertController { export class ButtonHandler extends Handler { // Button clicks have Message.what as the BUTTON{1,2,3} constant private static MSG_DISMISS_DIALOG:number = 1; private mDialog:WeakReference<DialogInterface>; constructor(dialog:DialogInterface) { super(); this.mDialog = new WeakReference<DialogInterface>(dialog); } handleMessage(msg:Message):void { switch (msg.what) { case DialogInterface.BUTTON_POSITIVE: case DialogInterface.BUTTON_NEGATIVE: case DialogInterface.BUTTON_NEUTRAL: (<DialogInterface.OnClickListener> msg.obj).onClick(this.mDialog.get(), msg.what); break; case ButtonHandler.MSG_DISMISS_DIALOG: (<DialogInterface> msg.obj).dismiss(); } } } export class RecycleListView extends ListView { mRecycleOnMeasure:boolean = true; constructor(context:Context, bindElement?:HTMLElement, defStyle?:Map<string, string>) { super(context, bindElement, defStyle); } protected recycleOnMeasure():boolean { return this.mRecycleOnMeasure; } } export class AlertParams { mContext:Context; mInflater:LayoutInflater; mIconId:number = 0; mIcon:Drawable; //mIconAttrId:number = 0; mTitle:string; mCustomTitleView:View; mMessage:string; mPositiveButtonText:string; mPositiveButtonListener:DialogInterface.OnClickListener; mNegativeButtonText:string; mNegativeButtonListener:DialogInterface.OnClickListener; mNeutralButtonText:string; mNeutralButtonListener:DialogInterface.OnClickListener; mCancelable:boolean; mOnCancelListener:DialogInterface.OnCancelListener; mOnDismissListener:DialogInterface.OnDismissListener; mOnKeyListener:DialogInterface.OnKeyListener; mItems:string[]; mAdapter:ListAdapter; mOnClickListener:DialogInterface.OnClickListener; mView:View; mViewSpacingLeft:number = 0; mViewSpacingTop:number = 0; mViewSpacingRight:number = 0; mViewSpacingBottom:number = 0; mViewSpacingSpecified:boolean = false; mCheckedItems:boolean[]; mIsMultiChoice:boolean; mIsSingleChoice:boolean; mCheckedItem:number = -1; mOnCheckboxClickListener:DialogInterface.OnMultiChoiceClickListener; //mCursor:Cursor; mLabelColumn:string; mIsCheckedColumn:string; mForceInverseBackground:boolean; mOnItemSelectedListener:AdapterView.OnItemSelectedListener; mOnPrepareListViewListener:AlertParams.OnPrepareListViewListener; mRecycleOnMeasure:boolean = true; constructor(context:Context) { this.mContext = context; this.mCancelable = true; this.mInflater = context.getLayoutInflater();//<LayoutInflater> context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } apply(dialog:AlertController):void { if (this.mCustomTitleView != null) { dialog.setCustomTitle(this.mCustomTitleView); } else { if (this.mTitle != null) { dialog.setTitle(this.mTitle); } if (this.mIcon != null) { dialog.setIcon(this.mIcon); } //if (this.mIconId >= 0) { // dialog.setIcon(this.mIconId); //} //if (this.mIconAttrId > 0) { // dialog.setIcon(dialog.getIconAttributeResId(this.mIconAttrId)); //} } if (this.mMessage != null) { dialog.setMessage(this.mMessage); } if (this.mPositiveButtonText != null) { dialog.setButton(DialogInterface.BUTTON_POSITIVE, this.mPositiveButtonText, this.mPositiveButtonListener, null); } if (this.mNegativeButtonText != null) { dialog.setButton(DialogInterface.BUTTON_NEGATIVE, this.mNegativeButtonText, this.mNegativeButtonListener, null); } if (this.mNeutralButtonText != null) { dialog.setButton(DialogInterface.BUTTON_NEUTRAL, this.mNeutralButtonText, this.mNeutralButtonListener, null); } if (this.mForceInverseBackground) { dialog.setInverseBackgroundForced(true); } // adapter or a cursor if ((this.mItems != null) /*|| (this.mCursor != null)*/ || (this.mAdapter != null)) { this.createListView(dialog); } if (this.mView != null) { if (this.mViewSpacingSpecified) { dialog.setView(this.mView, this.mViewSpacingLeft, this.mViewSpacingTop, this.mViewSpacingRight, this.mViewSpacingBottom); } else { dialog.setView(this.mView); } } /* dialog.setCancelable(mCancelable); dialog.setOnCancelListener(mOnCancelListener); if (mOnKeyListener != null) { dialog.setOnKeyListener(mOnKeyListener); } */ } private createListView(dialog:AlertController):void { const listView:AlertController.RecycleListView = <AlertController.RecycleListView> this.mInflater.inflate(dialog.mListLayout, null); let adapter:ListAdapter; if (this.mIsMultiChoice) { //if (this.mCursor == null) { adapter = (()=> { const inner_this = this; class _Inner extends ArrayAdapter<string> { getView(position:number, convertView:View, parent:ViewGroup):View { let view:View = super.getView(position, convertView, parent); if (inner_this.mCheckedItems != null) { let isItemChecked:boolean = inner_this.mCheckedItems[position]; if (isItemChecked) { listView.setItemChecked(position, true); } } return view; } } return new _Inner(this.mContext, dialog.mMultiChoiceItemLayout, R.id.text1, this.mItems); })(); //} else { // adapter = (()=>{ // const inner_this=this; // class _Inner extends CursorAdapter { // // private mLabelIndex:number = 0; // // private mIsCheckedIndex:number = 0; // // { // const cursor:Cursor = this.getCursor(); // mLabelIndex = cursor.getColumnIndexOrThrow(inner_this.mLabelColumn); // mIsCheckedIndex = cursor.getColumnIndexOrThrow(inner_this.mIsCheckedColumn); // } // // bindView(view:View, context:Context, cursor:Cursor):void { // let text:CheckedTextView = <CheckedTextView> view.findViewById(R.id.text1); // text.setText(cursor.getString(mLabelIndex)); // listView.setItemChecked(cursor.getPosition(), cursor.getInt(mIsCheckedIndex) == 1); // } // // newView(context:Context, cursor:Cursor, parent:ViewGroup):View { // return inner_this.mInflater.inflate(dialog.mMultiChoiceItemLayout, parent, false); // } // } // return new _Inner(this.mContext, this.mCursor, false); // })(); //} } else { let layout:string = this.mIsSingleChoice ? dialog.mSingleChoiceItemLayout : dialog.mListItemLayout; //if (this.mCursor == null) { adapter = (this.mAdapter != null) ? this.mAdapter : new ArrayAdapter<string>(this.mContext, layout, R.id.text1, this.mItems); //} else { // adapter = new SimpleCursorAdapter(this.mContext, layout, this.mCursor, [ this.mLabelColumn ], [ R.id.text1 ]); //} } if (this.mOnPrepareListViewListener != null) { this.mOnPrepareListViewListener.onPrepareListView(listView); } /* Don't directly set the adapter on the ListView as we might * want to add a footer to the ListView later. */ dialog.mAdapter = adapter; dialog.mCheckedItem = this.mCheckedItem; const inner_this = this; if (this.mOnClickListener != null) { listView.setOnItemClickListener({ onItemClick(parent:AdapterView<any>, v:View, position:number, id:number):void { inner_this.mOnClickListener.onClick(dialog.mDialogInterface, position); if (!inner_this.mIsSingleChoice) { dialog.mDialogInterface.dismiss(); } } }); } else if (this.mOnCheckboxClickListener != null) { listView.setOnItemClickListener({ onItemClick(parent:AdapterView<any>, v:View, position:number, id:number):void { if (inner_this.mCheckedItems != null) { inner_this.mCheckedItems[position] = listView.isItemChecked(position); } inner_this.mOnCheckboxClickListener.onClick(dialog.mDialogInterface, position, listView.isItemChecked(position)); } }); } // Attach a given OnItemSelectedListener to the ListView if (this.mOnItemSelectedListener != null) { listView.setOnItemSelectedListener(this.mOnItemSelectedListener); } if (this.mIsSingleChoice) { listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); } else if (this.mIsMultiChoice) { listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); } listView.mRecycleOnMeasure = this.mRecycleOnMeasure; dialog.mListView = listView; } } export module AlertParams { /** * Interface definition for a callback to be invoked before the ListView * will be bound to an adapter. */ export interface OnPrepareListViewListener { /** * Called before the ListView is bound to an adapter. * @param listView The ListView that will be shown in the dialog. */ onPrepareListView(listView:ListView):void ; } } } }
the_stack
import { options } from '@tko/utils'; import { removeNode, triggerEvent, extend } from '@tko/utils'; import { unwrap, observable as observableConstructor } from '@tko/observable'; import { computed as computedConstructor } from '@tko/computed'; import { MultiProvider } from '@tko/provider.multi'; import { DataBindProvider } from '@tko/provider.databind'; import { VirtualProvider } from '@tko/provider.virtual'; import { applyBindings, contextFor, applyBindingsToDescendants } from '../dist'; import {bindings as coreBindings} from '@tko/binding.core'; import '@tko/utils/helpers/jasmine-13-helper'; describe('Binding dependencies', function () { var bindingHandlers beforeEach(jasmine.prepareTestNode); beforeEach(function () { var provider = new MultiProvider({providers: [ new DataBindProvider(), new VirtualProvider() ]}) options.bindingProviderInstance = provider bindingHandlers = provider.bindingHandlers bindingHandlers.set(coreBindings); }) it('If the binding handler depends on an observable, invokes the init handler once and the update handler whenever a new value is available', function () { var observable = new observableConstructor(); var initPassedValues = [], updatePassedValues = []; bindingHandlers.test = { init: function (element, valueAccessor) { initPassedValues.push(valueAccessor()()); }, update: function (element, valueAccessor) { updatePassedValues.push(valueAccessor()()); } }; testNode.innerHTML = "<div data-bind='test: myObservable'></div>"; applyBindings({ myObservable: observable }, testNode); expect(initPassedValues.length).toEqual(1); expect(updatePassedValues.length).toEqual(1); expect(initPassedValues[0]).toBeUndefined(); expect(updatePassedValues[0]).toBeUndefined(); observable('A'); expect(initPassedValues.length).toEqual(1); expect(updatePassedValues.length).toEqual(2); expect(updatePassedValues[1]).toEqual('A'); }); it('If the associated DOM element was removed by KO, handler subscriptions are disposed immediately', function () { var observable = new observableConstructor('A'); bindingHandlers.anyHandler = { update: function (element, valueAccessor) { valueAccessor(); } }; testNode.innerHTML = "<div data-bind='anyHandler: myObservable()'></div>"; applyBindings({ myObservable: observable }, testNode); expect(observable.getSubscriptionsCount()).toEqual(1); removeNode(testNode); expect(observable.getSubscriptionsCount()).toEqual(0); }); it('If the associated DOM element was removed independently of KO, handler subscriptions are disposed on the next evaluation', function () { var observable = new observableConstructor('A'); bindingHandlers.anyHandler = { update: function (element, valueAccessor) { valueAccessor(); } }; testNode.innerHTML = "<div data-bind='anyHandler: myObservable()'></div>"; applyBindings({ myObservable: observable }, testNode); expect(observable.getSubscriptionsCount()).toEqual(1); testNode.parentNode.removeChild(testNode); observable('B'); // Force re-evaluation expect(observable.getSubscriptionsCount()).toEqual(0); }); it('If the binding attribute involves an observable, re-invokes the bindings if the observable notifies a change', function () { var observable = new observableConstructor({ message: 'hello' }); var passedValues = []; bindingHandlers.test = { update: function (element, valueAccessor) { passedValues.push(valueAccessor()); } }; testNode.innerHTML = "<div data-bind='test: myObservable().message'></div>"; applyBindings({ myObservable: observable }, testNode); expect(passedValues.length).toEqual(1); expect(passedValues[0]).toEqual('hello'); observable({ message: 'goodbye' }); expect(passedValues.length).toEqual(2); expect(passedValues[1]).toEqual('goodbye'); }); it('Should not reinvoke init for notifications triggered during first evaluation', function () { var observable = observableConstructor('A'); var initCalls = 0; bindingHandlers.test = { init: function (element, valueAccessor) { initCalls++; var value = valueAccessor(); // Read the observable (to set up a dependency on it), and then also write to it (to trigger re-eval of bindings) // This logic probably wouldn't be in init but might be indirectly invoked by init value(); value('B'); } }; testNode.innerHTML = "<div data-bind='test: myObservable'></div>"; applyBindings({ myObservable: observable }, testNode); expect(initCalls).toEqual(1); }); it('Should not run update before init, even if an associated observable is updated by a different binding before init', function () { // Represents the "theoretical issue" posed by Ryan in comments on https://github.com/SteveSanderson/knockout/pull/193 var observable = observableConstructor('A'), hasInittedSecondBinding = false, hasUpdatedSecondBinding = false; bindingHandlers.test1 = { init: function (element, valueAccessor) { // Read the observable (to set up a dependency on it), and then also write to it (to trigger re-eval of bindings) // This logic probably wouldn't be in init but might be indirectly invoked by init var value = valueAccessor(); value(); value('B'); } } bindingHandlers.test2 = { init: function () { hasInittedSecondBinding = true; }, update: function () { if (!hasInittedSecondBinding) { throw new Error("Called 'update' before 'init'"); } hasUpdatedSecondBinding = true; } } testNode.innerHTML = "<div data-bind='test1: myObservable, test2: true'></div>"; applyBindings({ myObservable: observable }, testNode); expect(hasUpdatedSecondBinding).toEqual(true); }); it('Should be able to get all updates to observables in both init and update', function () { var lastBoundValueInit, lastBoundValueUpdate; bindingHandlers.testInit = { init: function (element, valueAccessor) { computedConstructor(function () { lastBoundValueInit = unwrap(valueAccessor()); }); } }; bindingHandlers.testUpdate = { update: function (element, valueAccessor) { lastBoundValueUpdate = unwrap(valueAccessor()); } }; testNode.innerHTML = "<div data-bind='testInit: myProp()'></div><div data-bind='testUpdate: myProp()'></div>"; var vm = observableConstructor({ myProp: observableConstructor('initial value') }); applyBindings(vm, testNode); expect(lastBoundValueInit).toEqual('initial value'); expect(lastBoundValueUpdate).toEqual('initial value'); // update value of observable vm().myProp('second value'); expect(lastBoundValueInit).toEqual('second value'); expect(lastBoundValueUpdate).toEqual('second value'); // update value of observable to another observable vm().myProp(observableConstructor('third value')); expect(lastBoundValueInit).toEqual('third value'); expect(lastBoundValueUpdate).toEqual('third value'); // update view model with brand-new property vm({ myProp: function () { return 'fourth value'; }}); expect(lastBoundValueInit).toEqual('fourth value'); expect(lastBoundValueUpdate).toEqual('fourth value'); }); it('Should not update sibling bindings if a binding is updated', function () { var countUpdates = 0, observable = observableConstructor(1); bindingHandlers.countingHandler = { update: function () { countUpdates++; } } bindingHandlers.unwrappingHandler = { update: function (element, valueAccessor) { valueAccessor(); } } testNode.innerHTML = "<div data-bind='countingHandler: true, unwrappingHandler: myObservable()'></div>"; applyBindings({ myObservable: observable }, testNode); expect(countUpdates).toEqual(1); observable(3); expect(countUpdates).toEqual(1); }); it('Should not subscribe to observables accessed in init function', function () { var observable = observableConstructor('A'); bindingHandlers.test = { init: function (element, valueAccessor) { var value = valueAccessor(); value(); } } testNode.innerHTML = "<div data-bind='if: true'><div data-bind='test: myObservable'></div></div>"; applyBindings({ myObservable: observable }, testNode); expect(observable.getSubscriptionsCount()).toEqual(0); }); it('Should access latest value from extra binding when normal binding is updated', function () { delete bindingHandlers.nonexistentHandler; var observable = observableConstructor(), updateValue; var vm = {myObservable: observable, myNonObservable: 'first value'}; bindingHandlers.existentHandler = { update: function (element, valueAccessor, allBindings) { valueAccessor()(); // create dependency updateValue = allBindings.get('nonexistentHandler'); } } testNode.innerHTML = "<div data-bind='existentHandler: myObservable, nonexistentHandler: myNonObservable'></div>"; applyBindings(vm, testNode); expect(updateValue).toEqual('first value'); vm.myNonObservable = 'second value'; observable.notifySubscribers(); expect(updateValue).toEqual('second value'); }); it('Should update a binding when its observable is modified in a sibling binding', function () { // Represents an issue brought up in the forum: https://groups.google.com/d/topic/knockoutjs/ROyhN7T2WJw/discussion var latestValue, observable1 = observableConstructor(1), observable2 = observableConstructor(); bindingHandlers.updatedHandler = { update: function () { latestValue = observable2(); } } bindingHandlers.modifyingHandler = { update: function () { observable2(observable1()); } } // The order of the bindings matters: this tests that a later binding will update an earlier binding testNode.innerHTML = "<div data-bind='updatedHandler: true, modifyingHandler: true'></div>"; applyBindings({}, testNode); expect(latestValue).toEqual(1); observable1(2); expect(latestValue).toEqual(2); }); it('Should track observables accessed within the binding provider\'s "getBindingAccessor" function', function () { var observable = observableConstructor('substitute') class TestProvider extends DataBindProvider { getBindingAccessors (node, bindingContext) { var bindings = super.getBindingAccessors(node, bindingContext) if (bindings && bindings.text) { var newValue = observable(); bindings.text = () => newValue } return bindings } } const provider = new TestProvider() options.bindingProviderInstance = provider provider.bindingHandlers.set(coreBindings) testNode.innerHTML = "<div data-bind='text: \"hello\"'></div>"; applyBindings({}, testNode); expect(testNode).toContainText('substitute'); expect(observable.getSubscriptionsCount()).toEqual(1); // update observable to update binding observable('new value'); expect(testNode).toContainText('new value'); }); it('Should not cause updates if an observable accessed in a childrenComplete callback is changed', function () { bindingHandlers.test = { init: function () { return { controlsDescendantBindings: true }; }, update: function (element, valueAccessor, allBindings, viewModel, bindingContext) { unwrap(valueAccessor()); element.innerHTML = "<span data-bind='text: childprop'></span>"; applyBindingsToDescendants(bindingContext, element); } }; var callbackObservable = observableConstructor(1), bindingObservable = observableConstructor(1), callbacks = 0, vm = { childprop: 'child', bindingObservable: bindingObservable, callback: function () { callbackObservable(); callbacks++; } }; testNode.innerHTML = "<div data-bind='test: bindingObservable, childrenComplete: callback'></div>"; applyBindings(vm, testNode); expect(callbacks).toEqual(1); // Change the childprop which is not an observable so should not change the bound element vm.childprop = 'new child'; expect(testNode.childNodes[0]).toContainText('child'); // Update callback observable and check that the binding wasn't updated callbackObservable(2); expect(testNode.childNodes[0]).toContainText('child'); // Update the bound observable and verify that the binding is now updated bindingObservable(2); expect(testNode.childNodes[0]).toContainText('new child'); expect(callbacks).toEqual(2); }); it('Should always use the latest value of a childrenComplete callback', function () { bindingHandlers.test = { init: function () { return { controlsDescendantBindings: true }; }, update: function (element, valueAccessor, allBindings, viewModel, bindingContext) { var innerContext = bindingContext.createChildContext({childprop: unwrap(valueAccessor())}); element.innerHTML = "<span data-bind='text: childprop'></span>"; applyBindingsToDescendants(innerContext, element); } } var callbackSpy1 = jasmine.createSpy('callbackSpy1'), callbackSpy2 = jasmine.createSpy('callbackSpy2'), vm = { observable: observableConstructor('value'), callback: callbackSpy1 }; testNode.innerHTML = "<div data-bind='test: observable, childrenComplete: callback'></div>"; applyBindings(vm, testNode); expect(callbackSpy1).toHaveBeenCalled(); callbackSpy1.reset(); vm.callback = callbackSpy2; vm.observable('new value'); expect(testNode.childNodes[0]).toContainText('new value'); expect(callbackSpy1).not.toHaveBeenCalled(); expect(callbackSpy2).toHaveBeenCalled(); }); describe('Observable view models', function () { it('Should update bindings (including callbacks)', function () { var vm = observableConstructor(), clickedVM; function checkVM (data) { clickedVM = data; } testNode.innerHTML = "<div><input data-bind='value:someProp' /><input type='button' data-bind='click: checkVM' /></div>"; vm({ someProp: 'My prop value', checkVM: checkVM }); applyBindings(vm, testNode); expect(vm.getSubscriptionsCount()).toEqual(1); expect(testNode.childNodes[0].childNodes[0].value).toEqual('My prop value'); // a change to the input value should be written to the model testNode.childNodes[0].childNodes[0].value = 'some user-entered value'; triggerEvent(testNode.childNodes[0].childNodes[0], 'change'); expect(vm().someProp).toEqual('some user-entered value'); // a click should use correct view model triggerEvent(testNode.childNodes[0].childNodes[1], 'click'); expect(clickedVM).toEqual(vm()); // set the view-model to a new object vm({ someProp: observableConstructor('My new prop value'), checkVM: checkVM }); expect(testNode.childNodes[0].childNodes[0].value).toEqual('My new prop value'); // a change to the input value should be written to the new model testNode.childNodes[0].childNodes[0].value = 'some new user-entered value'; triggerEvent(testNode.childNodes[0].childNodes[0], 'change'); expect(vm().someProp()).toEqual('some new user-entered value'); // a click should use correct view model triggerEvent(testNode.childNodes[0].childNodes[1], 'click'); expect(clickedVM).toEqual(vm()); // clear the element and the view-model (shouldn't be any errors) and the subscription should be cleared removeNode(testNode); vm(null); expect(vm.getSubscriptionsCount()).toEqual(0); }); it('Should provide access to the view model\'s observable through $rawData', function () { var vm = observableConstructor('text'); testNode.innerHTML = "<div data-bind='text:$data'></div>"; applyBindings(vm, testNode); expect(testNode).toContainText('text'); var context = contextFor(testNode); expect(context.$data).toEqual('text'); expect(context.$rawData).toBe(vm); }); it('Should set $rawData to the observable returned from a function', function () { var vm = observableConstructor('text'); testNode.innerHTML = "<div data-bind='text:$data'></div>"; applyBindings(function () { return vm; }, testNode); expect(testNode).toContainText('text'); var context = contextFor(testNode); expect(context.$data).toEqual('text'); expect(context.$rawData).toBe(vm); }); it('Should set $rawData to the view model if a function unwraps the observable view model', function () { var vm = observableConstructor('text'); testNode.innerHTML = "<div data-bind='text:$data'></div>"; applyBindings(function () { return vm(); }, testNode); expect(testNode).toContainText('text'); var context = contextFor(testNode); expect(context.$data).toEqual('text'); expect(context.$rawData).toBe('text'); // Updating view model updates bindings and context vm('new text'); expect(testNode).toContainText('new text'); expect(context.$data).toEqual('new text'); expect(context.$rawData).toBe('new text'); }); it('Should dispose view model subscription on next update when bound node is removed outside of KO', function () { var vm = observableConstructor('text'); testNode.innerHTML = "<div data-bind='text:$data'></div>"; applyBindings(vm, testNode); expect(vm.getSubscriptionsCount()).toEqual(1); // remove the element and re-set the view-model; the subscription should be cleared testNode.parentNode.removeChild(testNode); vm(null); expect(vm.getSubscriptionsCount()).toEqual(0); }); it('Should update all child contexts (including values copied from the parent)', function () { bindingHandlers.setChildContext = { init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { applyBindingsToDescendants( bindingContext.createChildContext(function () { return unwrap(valueAccessor()) }), element); return { controlsDescendantBindings: true }; } }; testNode.innerHTML = "<div data-bind='setChildContext:obj1'><span data-bind='text:prop1'></span><span data-bind='text:$root.prop2'></span></div>"; var vm = observableConstructor({obj1: {prop1: 'First '}, prop2: 'view model'}); applyBindings(vm, testNode); expect(testNode).toContainText('First view model'); // change view model to new object vm({obj1: {prop1: 'Second view '}, prop2: 'model'}); expect(testNode).toContainText('Second view model'); // change it again vm({obj1: {prop1: 'Third view model'}, prop2: ''}); expect(testNode).toContainText('Third view model'); // clear the element and the view-model (shouldn't be any errors) and the subscription should be cleared removeNode(testNode); vm(null); expect(vm.getSubscriptionsCount()).toEqual(0); }); it('Should update all extended contexts (including values copied from the parent)', function () { bindingHandlers.withProperties = { init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { var innerBindingContext = bindingContext.extend(valueAccessor); applyBindingsToDescendants(innerBindingContext, element); return { controlsDescendantBindings: true }; } }; testNode.innerHTML = "<div data-bind='withProperties: obj1'><span data-bind='text:prop1'></span><span data-bind='text:prop2'></span><span data-bind='text:$rawData().prop3'></span></div>"; var vm = observableConstructor({obj1: {prop1: 'First '}, prop2: 'view ', prop3: 'model'}); applyBindings(vm, testNode); expect(testNode).toContainText('First view model'); // change view model to new object vm({obj1: {prop1: 'Second view '}, prop2: 'model', prop3: ''}); expect(testNode).toContainText('Second view model'); // change it again vm({obj1: {prop1: ''}, prop2: '', prop3: 'Third view model'}); expect(testNode).toContainText('Third view model'); // clear the element and the view-model (shouldn't be any errors) and the subscription should be cleared removeNode(testNode); vm(null); expect(vm.getSubscriptionsCount()).toEqual(0); }); it('Should maintain correct $rawData in extended context when parent is bound to a function that returns an observable view model', function () { bindingHandlers.extended = { init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { applyBindingsToDescendants(bindingContext.extend(valueAccessor), element); return { controlsDescendantBindings: true }; } }; var vm1 = observableConstructor('vm1'), vm2 = observableConstructor('vm2'), whichVm = observableConstructor(vm1); testNode.innerHTML = "<div data-bind='extended: {}'><div data-bind='text: $data'></div></div>"; applyBindings(function () { return whichVm(); }, testNode); expect(testNode).toContainText('vm1'); var parentContext = contextFor(testNode), childContext = contextFor(testNode.childNodes[0].childNodes[0]); expect(parentContext.$data).toEqual('vm1'); expect(parentContext.$rawData).toBe(vm1); expect(childContext).not.toBe(parentContext); expect(childContext.$data).toEqual('vm1'); expect(childContext.$rawData).toBe(vm1); // Updating view model updates bindings and context whichVm(vm2); expect(testNode).toContainText('vm2'); expect(childContext.$data).toEqual('vm2'); expect(childContext.$rawData).toBe(vm2); }); it('Should update an extended child context', function () { bindingHandlers.withProperties = { init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { var childBindingContext = bindingContext.createChildContext(null, null, function (context) { extend(context, valueAccessor()); }); applyBindingsToDescendants(childBindingContext, element); return { controlsDescendantBindings: true }; } }; testNode.innerHTML = "<div data-bind='withProperties: obj1'><span data-bind='text:prop1'></span><span data-bind='text:$parent.prop2'></span></div>"; var vm = observableConstructor({obj1: {prop1: 'First '}, prop2: 'view model'}); applyBindings(vm, testNode); expect(testNode).toContainText('First view model'); // ch ange view model to new object vm({obj1: {prop1: 'Second view '}, prop2: 'model'}); expect(testNode).toContainText('Second view model'); // change it again vm({obj1: {prop1: 'Third view model'}, prop2: ''}); expect(testNode).toContainText('Third view model'); // clear the element and the view-model (shouldn't be any errors) and the subscription should be cleared removeNode(testNode); vm(null); expect(vm.getSubscriptionsCount()).toEqual(0); }); }); describe('Order', function () { var bindingOrder; beforeEach(function () { bindingOrder = []; function makeBinding (name) { return { init: function () { bindingOrder.push(name); } }; } bindingHandlers.test1 = makeBinding(1); bindingHandlers.test2 = makeBinding(2); bindingHandlers.test3 = makeBinding(3); bindingHandlers.test4 = makeBinding(4); }); it('Should default to the order in the binding', function () { testNode.innerHTML = "<div data-bind='test1, test2, test3'></div>"; applyBindings(null, testNode); expect(bindingOrder).toEqual([1, 2, 3]); }); it('Should be based on binding\'s "after" values, which override the default binding order', function () { bindingHandlers.test2.after = ['test1']; bindingHandlers.test3.after = ['test2']; testNode.innerHTML = "<div data-bind='test3, test2, test1'></div>"; applyBindings(null, testNode); expect(bindingOrder).toEqual([1, 2, 3]); }); it('Should leave bindings without an "after" value where they are', function () { // This test is set up to be unambiguous, because only test1 and test2 are reordered // (they have the dependency between them) and test3 is left alone. bindingHandlers.test2.after = ['test1']; testNode.innerHTML = "<div data-bind='test2, test1, test3'></div>"; applyBindings(null, testNode); expect(bindingOrder).toEqual([1, 2, 3]); }); it('Should leave bindings without an "after" value where they are (extended)', function () { // This test is ambiguous, because test3 could either be before test1 or after test2. // So we accept either result. bindingHandlers.test2.after = ['test1']; testNode.innerHTML = "<div data-bind='test2, test3, test1'></div>"; applyBindings(null, testNode); expect(bindingOrder).toEqualOneOf([[1, 2, 3], [3, 1, 2]]); }); it('Should throw an error if bindings have a cyclic dependency', function () { // We also verify that test4 and unknownBinding don't appear in the error message, because they aren't part of the cycle bindingHandlers.test1.after = ['test3']; bindingHandlers.test2.after = ['test1']; bindingHandlers.test3.after = ['test4', 'test2']; bindingHandlers.test4.after = []; testNode.innerHTML = "<div data-bind='test1, unknownBinding, test2, test4, test3'></div>"; expect(function () { applyBindings(null, testNode); }).toThrow('Cannot combine the following bindings, because they have a cyclic dependency: test1, test3, test2'); }) }); });
the_stack
import { ByteStr, asciiByteStr } from '../bytestr' import { Pos, SrcFile } from '../pos' import { token } from '../token' import { DiagKind, DiagHandler } from '../diag' import * as ast from '../ast' import { Type, PrimType, FunType, UIntType, types as T, intTypes, t_nil } from "../ast" import { optcf_op1, optcf_op2 } from './opt_cf' import { ops, opinfo } from "./ops" import { Value, Block, BlockKind, Fun, Pkg, BranchPrediction, nilValue } from './ssa' import { opselect1, opselect2, opselectConv } from './opselect' import { Config } from './config' import { LocalSlot } from './localslot' // debug logging // import { printir } from './repr' import { debuglog as dlog } from '../util' // const dlog = function(..._ :any[]){} // silence dlog // const dlogPhi = dlog const dlogPhi = function(..._ :any[]){} // silence // const dlogVar = dlog const dlogVar = function(..._ :any[]){} const bitypes = ast.types export enum IRBuilderFlags { Default = 0, Comments = 1 << 1, // include comments in some values, for formatting } class TmpName extends ByteStr {} // IRBuilder produces SSA IR for functions, taking AST as the input. // // The "inline"/"single-pass" Phi placement heuristic is based on the paper // "Simple and Efficient Construction of Static Single Assignment Form" // https://pp.info.uni-karlsruhe.de/uploads/publikationen/braun13cc.pdf // export class IRBuilder { config :Config pkg :Pkg sfile :SrcFile|null = null diagh :DiagHandler|null = null b :Block // current block f :Fun // current function flags :IRBuilderFlags = IRBuilderFlags.Default addrtype :UIntType vars :Map<ByteStr,Value> // variable assignments in the current block (map from variable symbol // to ssa value) defvars :(Map<ByteStr,Value>|null)[] // all defined variables at the end of each block. Indexed by block id. // null indicates there are no variables in that block. incompletePhis :Map<Block,Map<ByteStr,Value>>|null // tracks pending, incomplete phis that are completed by sealBlock for // blocks that are sealed after they have started. This happens when preds // are not known at the time a block starts, but is known and registered // before the block ends. breakTo :Block|null = null // Nearest block. For unlabeled "break". startmem :Value // initial function memory (InitMem) sp :Value // current function's SP (stack pointer) sb :Value // current function's SB (static base pointer) stacktop :Value // current top of stack init(config :Config, diagh :DiagHandler|null = null, flags :IRBuilderFlags = IRBuilderFlags.Default ) { const r = this r.config = config r.pkg = new Pkg() r.sfile = null r.diagh = diagh r.vars = new Map<ByteStr,Value>() r.defvars = [] r.incompletePhis = null r.flags = flags r.sp = nilValue // // select integer types const [intt_s, intt_u] = intTypes(config.intSize) r.addrtype = intTypes(config.addrSize)[1] this.concreteType = (t :Type) :PrimType => { switch (t) { case T.int: return intt_s case T.uint: return intt_u case T.uintptr: return r.addrtype default: assert(t.isPrimType(), `${t} is not a PrimType`) return t as PrimType } } } // addTopLevel is the primary interface to builder // addTopLevel(sfile :SrcFile, d :ast.Decl|ast.FunExpr) :Fun|null { // Note: d must not contain unresolved references (including types). // If there are unresolved references, behavior is undefined. // const r = this r.sfile = sfile if (d instanceof ast.MultiDecl) { for (let d2 of d.decls) { r.addTopLevel(sfile, d2) } } else if (d instanceof ast.VarDecl) { r.global(d) } else if (d instanceof ast.FunExpr) { if (d.isInit) { // Sanity checks (parser has already checked these things) assert(d.sig.params.length == 0, 'init fun with parameters') assert(d.sig.result === t_nil, 'init fun with result') assert(d.body, 'missing body') r.initCode(d.body as ast.Expr) } else if (d.body) { // regular function with an implementation (d.body) return r.fun(d) } else { dlog(`skipping pure function declaration ${d}`) } } else if (d instanceof ast.ImportDecl) { dlog(`TODO ImportDecl`) } else if (d instanceof ast.TypeDecl) { dlog(`TODO TypeDecl`) } return null // TODO: return other top-level things } // startBlock sets the current block we're generating code in // startBlock(b :Block) { const r = this assert(r.b == null, "starting block without ending block") r.b = b } // startSealedBlock is a convenience for sealBlock followed by startBlock // startSealedBlock(b :Block) { this.sealBlock(b) this.startBlock(b) } // sealBlock sets b.sealed=true, indicating that no further predecessors // will be added (no changes to b.preds) // sealBlock(b :Block) { const s = this assert(!b.sealed, `block ${b} already sealed`) dlog(`${b}`) if (s.incompletePhis) { let entries = s.incompletePhis.get(b) if (entries) { for (let [name, phi] of entries) { dlogPhi(`complete pending phi ${phi} (${name})`) s.addPhiOperands(name, phi) } s.incompletePhis.delete(b) } } b.sealed = true } // endBlock marks the end of generating code for the current block. // Returns the (former) current block. Returns null if there is no current // block, i.e. if no code flows to the current execution point. // The block sealed if not already sealed. // endBlock() :Block { const r = this let b = r.b assert(b != null, "no current block") // move block-local vars to long-term definition data // first we fill any holes in defvars // while (r.defvars.length <= b.id) { // r.defvars.push(null) // } r.defvars[b.id] = r.vars // reset block-local vars r.vars = new Map<ByteStr,Value>() if (DEBUG) { // make sure we crash if we try to use b before a new block is started ;(r as any).b = null } // [optimization] change last value to TailCall when block returns // and last value is Call if ( b.kind == BlockKind.Ret && b.values.length && b.values[b.values.length-1].op == ops.Call ) { b.values[b.values.length-1].op = ops.TailCall } return b } startFun(f :Fun) { const s = this assert(s.f == null, "starting function with existing function") s.f = f } endFun() { const s = this assert(s.f, "ending function without a current function") if (DEBUG) { let dloglines :string[] = [] for (let name of s.f.namedValues.keys()) { let e = s.f.namedValues.get(name) let line = ` ${name}\t=> ` if (e && e.values.length) { line += Array.from(new Set(e.values)).join(', ') } else { line += '-' } dloglines.push(line) } dlog(`s.f.namedValues:\n` + dloglines.join("\n") + "\n") } // TODO: run passes on s.f here // if (s.config.optimize) { // // perform early dead-code elimination // optdce(s.f) // } // if (s.regalloc) { // // perform register allocation // s.regalloc.regallocFun(s.f) // } if (DEBUG) { ;(s as any).f = null } } // concreteType normalizes abstract types to concrete types. // E.g. concreteType(int) -> i32 (if int->i32 exists in typemap) // concreteType(t :Type) :PrimType { // Note: This function is replaced by the constructor assert(t.isPrimType()) return t as PrimType } // nilValue returns a placeholder value. // This is meant to be used only during development and should be removed // when the IR builder is complete. // nilValue() :Value { assert(this.b, "no current block") return this.b.newValue0(ops.Unknown, t_nil) } global(_ :ast.VarDecl) { dlog(`TODO`) } initCode(_body :ast.Expr) { // const r = this // const f = r.pkg.init || (r.pkg.init = new Fun([], t_nil, 'init')) // r.block(f, null, body, 'init') // console.log(`\n-----------------------\n${f}`) } _funIds = new Map<ast.FunExpr,int>() getFunId(x :ast.FunExpr) :int { // function id mapping const s = this let id = s._funIds.get(x) if (id === undefined) { // allocate new funid id = s._funIds.size s._funIds.set(x, id) } return id } fun(x :ast.FunExpr) :Fun { const r = this assert(x.body, `unresolved function ${x}`) assert(x.type, "unresolved function type") let funid = r.getFunId(x) let funtype = x.type as FunType let f = new Fun( funid, r.config, funtype, x.name ? x.name.value : null, x.sig.params.length ) // Add initial memory state, SP and SB to top of entry block r.startmem = f.entry.newValue0(ops.InitMem, T.mem) r.sp = f.entry.newValue0(ops.SP, r.addrtype) r.sb = f.entry.newValue0(ops.SB, r.addrtype) // stack starts at startmem r.stacktop = r.startmem // initialize arguments for (let i = 0; i < x.sig.params.length; i++) { let p = x.sig.params[i] if (p.name && !p.name.value.isUnderscore()) { let t = r.concreteType(funtype.args[i]) let name = p.name.value let v = f.entry.newValue0(ops.Arg, t, i, name) r.vars.set(name, v) } } r.startFun(f) r.startSealedBlock(f.entry) let bodyval = r.block(x.body as ast.Expr) // printir(f); dlog(`r.b = ${r.b}`); process.exit(0) // XXX if (r.b as any) { // end last block if not already ended r.b.kind = BlockKind.Ret if (!(x.body instanceof ast.Block)) { // body is a single expression -- control value is that expression // assert(!(x.body instanceof ast.ReturnStmt), // "'return' as function expression body should have called "+ // "ret() to close block") r.b.setControl(bodyval) } // when body is a block and it didn't end, it was empty and thus // the return type is nil (no control value.) r.endBlock() } assert((r as any).b == null, "function exit block not ended") assert( f.blocks[f.blocks.length-1].kind == BlockKind.Ret, `last block ${f.blocks[f.blocks.length-1]} in function ` + `is not BlockKind.Ret ` + `(instead it is ${BlockKind[f.blocks[f.blocks.length-1].kind]})` ) // assert(f.tailb.kind == BlockKind.Ret, // "last block in function is not BlockKind.Ret") r.endFun() r.pkg.addFun(f) // zero out function state in debug mode, to cause errors on access if (DEBUG) { ;(r as any).startmem = null ;(r as any).sp = null ;(r as any).sb = null } return f } // block generates values from an AST block. // It's the caller's responsibility to create and manage IR blocks. // block(x :ast.Expr) :Value|null { const r = this if (x instanceof ast.Block) { return r.stmtList(x.list) // returns last expr, or null } return r.expr(x) } // stmt adds one or more TAC to block b in function f from statement s // stmt(s :ast.Stmt) :Value|null { const r = this if (s instanceof ast.IfExpr) { r.if_(s) } else if (s instanceof ast.ReturnStmt) { r.ret(r.expr(s.result)) } else if (s instanceof ast.ForStmt) { // includes WhileStmt r.for_(s) } else if (s instanceof ast.Expr) { return r.expr(s) } else if (s instanceof ast.VarDecl) { if (s.values) { // explicit value; e.g. "x = 3" for (let i = 0; i < s.idents.length; i++) { let id = s.idents[i] let v = r.expr(s.values[i]) r.varDef(id.value, v) } } else { // default value; e.g. "x i32" => "x = 0" assert(s.type, 'var decl without type or values') let t = (s.type as ast.Expr).type as PrimType assert(t, 'unresolved type') assert(t.isPrimType(), 'non-basic type not yet supported') let v = r.f.constVal(t, 0) // nil for (let id of s.idents) { r.varDef(id.value, v) } } // } else if (s instanceof ast.InlineMark) { // s.newValue1I(ssa.OpInlMark, t.TypeVoid, n.Xoffset, s.mem()) } else { dlog(`TODO: handle ${s.constructor.name}`) } return null } varDef(name :ByteStr, init :Value) :Value { const s = this let v = s.b.newValue1(ops.VarDef, init.type, init, 0, name) assert(!s.vars.has(name), `redeclaration of var ${name}`) s.vars.set(name, v) return v } stmtList(v :ast.Stmt[]) :Value|null { const s = this let i = 0 if (v.length > 0) while (true) { assert(s.b) let x = s.stmt(v[i++]) if (i == v.length) { return x } } return null } ret(val :Value|null) { const s = this let b = s.endBlock() b.kind = BlockKind.Ret b.setControl(val) } // for_ builds a conditional loop. // // The current block is first ended as a simple "cont" and a new block // is created for the loop condition, which when true branches to // the loop body, and after the loop when false. // // Example: // x = 5 // while x > 0 { // x-- // } // Becomes: // b0: // v0 = ConstI32 [5] // x // v1 = ConstI32 [0] // v2 = ConstI32 [1] // cont -> b1 // b1: <- b0 // while // v3 = Phi v1 v5 // v4 = GreaterS32 v1 v2 // if v4 -> b2, b3 // b2: <- b1 // then // v5 = SubI32 v3 v2 // x = x - 1 // cont -> b1 // b3: // end while // ret // // for_(n: ast.ForStmt) { // Note: WhileStmt is a ForStmt without init or incr const s = this // initializing code (may be none) if (n.init) { s.stmt(n.init) } let bCond = s.f.newBlock(BlockKind.Plain) let bBody = s.f.newBlock(BlockKind.Plain) let bIncr = s.f.newBlockNoAdd(BlockKind.Plain) let bEnd = s.f.newBlockNoAdd(BlockKind.Plain) bBody.pos = n.pos // end "entry" block (whatever block comes before "while") let bEntry = s.endBlock() dlog(`for ${n} endBlock() => ${bEntry}`) assert(bEntry.sealed) // if (!bEntry.sealed) { // s.sealBlock(bEntry) // all preds of bEntry are known // } // connect entry -> condition bEntry.addEdgeTo(bCond) // condition s.startBlock(bCond) let unconditional = true if (n.cond) { unconditional = false let cond = s.expr(n.cond) // condition for looping if (s.config.optimize && opinfo[cond.op].constant) { // constant condition if (cond.auxIsZero()) { // while loop never taken // convert condition block to continuation block and seal it bCond.kind = BlockKind.Plain s.sealBlock(bCond) // no more preds s.f.removeBlock(bBody) s.f.freeBlock(bIncr) s.f.freeBlock(bEnd) return } else { // loop unconditionally unconditional = true // TODO: produce error if there is no break or labeled continue // inside the body. } } if (!unconditional) { let b = s.endBlock() b.kind = BlockKind.If b.setControl(cond) b.likely = BranchPrediction.Likely b.addEdgeTo(bBody) // yes b.addEdgeTo(bEnd) // no } } if (unconditional) { let b = s.endBlock() b.kind = BlockKind.Plain b.addEdgeTo(bBody) // yes (unconditional) } // break/continue let prevBreak = s.breakTo s.breakTo = bEnd // TODO: continue // TODO: labels // body s.startSealedBlock(bBody) // all preds of bBody are known s.block(n.body) // note: intentionally ignore return value // break/continue s.breakTo = prevBreak // end body let bodyEnd = s.endBlock() if (bodyEnd.values.length == 0 && bodyEnd.sealed) { // short-circuit empty body // // Example where b2->b3->b2 is short-circuited to b2->b2: // b2: <— b1, b3 // ... // if v1 —> b4, b3 // b3: <— b2 // cont —> b2 // b4: <— b2 // ... // // After short-circuit: // b2: <— b1, b2 // ... // if v1 —> b4, b2 // b4: <— b2 // ... // assert(bodyEnd.preds.length == 1) let pred0 = bodyEnd.preds[0]! assert(pred0.succs.length > 0) let idx = pred0.succs.indexOf(bodyEnd) assert( idx != -1, `${bodyEnd}.preds contains ${pred0}, ` + `but ${pred0}.succs doesn't contain ${bodyEnd}` ) pred0.succs.splice(idx) s.f.removeBlock(bodyEnd) bodyEnd = pred0 } // incr? if (n.incr) { bodyEnd.addEdgeTo(bIncr) s.f.blocks.push(bIncr) s.startSealedBlock(bIncr) s.stmt(n.incr) let b = s.endBlock() b.addEdgeTo(bCond) } else { bodyEnd.addEdgeTo(bCond) s.f.freeBlock(bIncr) } // seal cond block s.sealBlock(bCond) // all preds of bCond are known // start continuation block s.f.blocks.push(bEnd) s.startSealedBlock(bEnd) dlog(`bEnd ${bEnd}`) // add comments if (s.flags & IRBuilderFlags.Comments) { let prefix = n instanceof ast.WhileStmt ? "while" : "for" bCond.comment = `${prefix}.b${bCond.id}.cond` bIncr.comment = `${prefix}.b${bCond.id}.incr` bBody.comment = `${prefix}.b${bCond.id}.body` bEnd.comment = `${prefix}.b${bCond.id}.end` } } // if_ reads an if expression. // Returns a new empty block that's the block after the if. // if_(s :ast.IfExpr) { // // if..end has the following semantics: // // if cond b1 b2 // b1: // <then-block> // goto b2 // b2: // <continuation-block> // // if..else..end has the following semantics: // // if cond b1 b2 // b1: // <then-block> // goto b3 // b2: // <else-block> // goto b3 // b3: // <continuation-block> // const r = this // generate control condition let control = r.expr(s.cond) // potentially inline or eliminate branches when control is constant if (r.config.optimize && opinfo[control.op].constant) { if (control.auxIsZero()) { // "else" branch always taken if (s.els_) { r.block(s.els_) } // else: no else branch -- entire if-expression is eliminated } else { // "then" branch always taken r.block(s.then) } return } // end predecessor block (leading up to and including "if") let ifb = r.endBlock() ifb.kind = BlockKind.If ifb.setControl(control) // create blocks for then and else branches let thenb = r.f.newBlock(BlockKind.Plain) let elsebidx = r.f.blocks.length let elseb = r.f.newBlock(BlockKind.Plain) ifb.succs = [thenb, elseb] // if -> then, else // create "then" block thenb.preds = [ifb] // then <- if r.startSealedBlock(thenb) r.block(s.then) thenb = r.endBlock() if (s.els_) { // if cond then A else B end // allocate "cont" block let contbidx = r.f.blocks.length let contb = r.f.newBlock(BlockKind.Plain) // create "else" block elseb.preds = [ifb] // else <- if r.startSealedBlock(elseb) r.block(s.els_) elseb = r.endBlock() elseb.succs = [contb] thenb.succs = [contb] // then -> cont contb.preds = [thenb, elseb] // cont <- then, else r.startSealedBlock(contb) // move ending block to end r.f.moveBlockToEnd(contbidx) // r.f.blocks.copyWithin(contbidx, contbidx+1) // r.f.blocks[r.f.blocks.length-1] = contb if (r.flags & IRBuilderFlags.Comments) { thenb.comment = 'then' elseb.comment = 'else' contb.comment = 'endif' } } else { // if cond then A end thenb.succs = [elseb] // then -> else elseb.preds = [ifb, thenb] // else <- if, then elseb.succs = [] r.startSealedBlock(elseb) // move ending block to end r.f.blocks.copyWithin(elsebidx, elsebidx+1) r.f.blocks[r.f.blocks.length-1] = elseb if (r.flags & IRBuilderFlags.Comments) { thenb.comment = 'then' elseb.comment = 'endif' } } } // assign does left = right. // Right has already been evaluated to ssa, left has not. assign(left :ast.Expr, right :Value) :Value { const s = this assert(left instanceof ast.Ident, `${left.constructor.name} not supported`) let name = (left as ast.Ident).value if (name.isEmpty) { // "_" return right } // // copy right -> left // let v = s.b.newValue1(ops.Copy, right.type, right) // if (s.flags & IRBuilderFlags.Comments) { // v.addComment(name.toString()) // } // s.writeVariable(name, v) // return v // instead of issuing an intermediate "copy", simply associate variable // name with the value on the right-hand side. s.writeVariable(name, right) if (s.flags & IRBuilderFlags.Comments) { right.addComment(name.toString()) } return right } // process an assignment node assignment(s :ast.Assignment) :Value { const r = this if (s.op == token.INC || s.op == token.DEC) { // e.g. "x++" => "x = x + 1" assert(s.lhs.length == 1) assert(s.rhs.length == 0) let lhs = s.lhs[0] // let t = r.concreteType(lhs.type) let x = r.expr(lhs) let y = r.f.constVal(x.type, 1) // generate "x = x op 1" let tok = s.op == token.INC ? token.ADD : token.SUB let op = opselect2(tok, x.type, y.type) let v = r.b.newValue2(op, x.type, x, y) return r.assign(lhs, v) } if (s.op != token.ASSIGN) { assert( // i.e. not "op=" s.op < token.assignop_beg || s.op > token.assignop_end, `invalid assignment operation ${token[s.op]}` ) // "x += 4", "x *= 2", etc => "x = x + 4", "x = x * 2", etc. assert(s.lhs.length == 1) assert(s.rhs.length == 1) let lhs = s.lhs[0] // let t = r.concreteType(lhs.type) let x = r.expr(lhs) let y = r.expr(s.rhs[0]) let op = opselect2(s.op, x.type, y.type) let v = r.b.newValue2(op, x.type, x, y) return r.assign(lhs, v) } // if we get here, we're dealing with a regular assignment, e.g. "x = y" // break up "x, y = a, b" assignments into simple "x = a", "y = b" // let z = s.lhs.length let preloadRhs :(Value|undefined)[]|null = null // "holey" array if (z > 1) { // potentially rewrite RHS with preloads and temps when an identifier // appears on both the left and right side. // // e.g. "x, y, z = y, x, 2" causes x and y to be preloaded into // temporaries: // t0 = load x // t1 = load y // store t1 x // store t0 y // z = 2 // let leftnames = new Map<ByteStr,int>() // name => position for (let i = 0; i < z; i++) { let x = s.lhs[i] if (x.isIdent()) { leftnames.set(x.value, i) } } for (let i = 0; i < z; i++) { let x = s.rhs[i] if (x.isIdent()) { let Li = leftnames.get(x.value) if (Li == i) { // e.g. "x, y = x, 2" r.diag('warn', `${x} assigned to itself`, x.pos) } else if (Li !== undefined) { // appears on the left -- preload if (!preloadRhs) { preloadRhs = new Array<Value|undefined>(s.rhs.length) } preloadRhs[i] = r.expr(x) } } } } let v :Value|null = null for (let i = 0; i < z; i++) { let left = s.lhs[i] let k :Value|undefined if (preloadRhs && (k = preloadRhs[i])) { v = k } else { v = r.expr(s.rhs[i]) } if (s.decls[i]) { // declares a new variable assert(left.isIdent()) assert(!(left as ast.Ident).value.isEmpty, `AST contains vardef "_"`) v = r.varDef((left as ast.Ident).value, v) } else { // write to existing variable v = r.assign(left, v) } } // last value represents the assignment expression return v as Value } expr(s :ast.Expr) :Value { const r = this assert(s.type, `type not resolved for ${s}`) if (s instanceof ast.NumLit) { const t = r.concreteType(s.type) return r.f.constVal(t, s.value) } if (s instanceof ast.Ident) { const t = r.concreteType(s.type as Type) return r.readVariable(s.value, t, null) } if (s instanceof ast.Assignment) { return r.assignment(s) } if (s instanceof ast.Operation) { // "x op y" => "tmp = x op y" -> tmp if (s.op == token.OROR || s.op == token.ANDAND) { return r.opAndAnd(s) } const t = r.concreteType(s.type as Type) let left = r.expr(s.x) if (s.y) { // Basic binary operation let right = r.expr(s.y) let op = opselect2(s.op, left.type, right.type) if (r.config.optimize) { // attempt to evaluate constant expression let v = optcf_op2(r.b, op, left, right) if (v) { // if (r.b !== v.b) { // // place a Copy when the definition is in a different block // // to maintain CFG integrity. // v = r.copy(v) // } return v } } return r.b.newValue2(op, t, left, right) } // Basic unary operation let op = opselect1(s.op, left.type) if (r.config.optimize) { // attempt to evaluate constant expression let v = optcf_op1(r.b, op, left) if (v) { // if (r.b !== v.b) { // // place a Copy when the definition is in a different block // // to maintain CFG integrity. // v = r.copy(v) // } return v } } return r.b.newValue1(op, t, left) } if (s instanceof ast.CallExpr) { return r.funcall(s) } if (s instanceof ast.TypeConvExpr) { return r.conv(s) } dlog(`TODO: handle ${s.constructor.name}`) return r.nilValue() } conv(s :ast.TypeConvExpr) :Value { const r = this let t = s.type as PrimType assert(t.isPrimType()) let x = r.expr(s.expr) let op = opselectConv(x.type, t) return r.b.newValue1(op, t, x) } copy(v :Value) :Value { return this.b.newValue1(ops.Copy, v.type, v) } tmpNames :TmpName[] = [] tmpNameBytes :Uint8Array|null = null tmpNameHash :int = 0 allocTmpName() :TmpName { let n = this.tmpNames.pop() if (!n) { if (this.tmpNameBytes) { n = new TmpName(this.tmpNameHash, this.tmpNameBytes) } else { n = asciiByteStr('tmp') this.tmpNameBytes = n.bytes this.tmpNameHash = n.hash } } return n } freeTmpName(n :TmpName) { this.tmpNames.push(n) } opAndAnd(n :ast.Operation) :Value { // high-level "&&" or "||" operation, lowered to branching. // // We implement "||" and "&&" via a temporary var and "if" branch. // E.g. source code // x && y // is converted to // t = x // if t { // t = y // } // and t is unsed in place. // OROR is converted in a similar manner: // x || y // is converted to // t = x // if !t { // t = y // } // // Reference of Go AST -> IR for OROR and ANDAND: // https://github.com/golang/go/blob/ // 10d096fec2fe8f3e88f847fd0ac17c0601bf6442/src/cmd/compile/internal/ // gc/ssa.go#L1957 // // ------------------------------------------------------------------- // Note on WASM: // WebAssembly provides a "select" operator with these semantics: // t1 = A<T> // t2 = B<T> // select C<i32> t1 t2 => D<T> // Where if C is not zero, value of A is used, otherwise value of B is // used, resulting in D. A and B must be of the same type and both A // and B are evaluated prior to the operator (not short-circuiting.) // This would make sense to use only for special cases where both A // and B are constants. // In order to target this operator in WASM, we need a higher-level // construct to represent ANDAND and OROR. After this (current) // if-construction, it won't be easy to later "revert" to ANDAND and // OROR. // Idea 1: Include target information when generating IR and only // unroll into "if" branches if the target doesn't support // something like WASM's "select". // Idea 2: Perform this step later // // However, for now, since it's a possibly-small RoI optimization // opportunity, we're ignoring this. // ------------------------------------------------------------------- // const s = this assert(n.y != null) let tmpname = s.allocTmpName() let left = s.expr(n.x) s.writeVariable(tmpname, left) let t = left.type let rightb = s.f.newBlock(BlockKind.Plain) // y let contb = s.f.newBlock(BlockKind.Plain) // t // end entry "if" block let ifb = s.endBlock() ifb.kind = BlockKind.If ifb.setControl(left) if (n.op == token.OROR) { // flip branches; equivalent to "ifFalse"/"ifz" // contb.likely = BranchPrediction.Likely // rightb.likely = BranchPrediction.Unlikely ifb.succs = [contb, rightb] // if -> contb, rightb } else { assert(n.op == token.ANDAND) // rightb.likely = BranchPrediction.Likely // contb.likely = BranchPrediction.Unlikely ifb.succs = [rightb, contb] // if -> rightb, contb } // gen "right" block rightb.preds = [ifb] // rightb <- if s.startSealedBlock(rightb) let right = s.expr(n.y as ast.Expr) // TODO: do we really need a "copy" here? Can't we just do this instead // s.writeVariable(tmpname, right) // and then navigate the resulting Phi when lowering to target code? // // let tmpv = s.b.newValue1(ops.Copy, right.type, right) // s.writeVariable(tmpname, tmpv) s.writeVariable(tmpname, right) rightb = s.endBlock() rightb.succs = [contb] // rightb -> contb assert(t.equals(right.type), `operands have different types: ${t} <> ${right.type}`) // start continuation block contb.preds = [ifb, rightb] // contb <- ifb, rightb s.startSealedBlock(contb) let v = s.readVariable(tmpname, T.bool, null) // remove tmpname s.removeVariable(ifb, tmpname) s.freeTmpName(tmpname) return v } spoffs = 0 // stack pointer offset stackPush(v :Value) { const s = this assert(v.type.isPrimType()) // compute address (SP + stack offset) let addr = s.b.newValue1(ops.OffPtr, T.mem, s.sp, s.spoffs) // Store v to addr. arg2=mem, aux=type s.stacktop = s.b.newValue3(ops.Store, T.mem, addr, v, s.stacktop, 0, v.type) // increment offset to stack pointer s.spoffs += v.type.storageSize() } stackPop(t :PrimType) :Value { const s = this assert(t.storageSize() <= s.addrtype.storageSize()) // compute address (SP + stack offset) let addr = s.b.newValue1(ops.OffPtr, T.mem, s.sp, s.spoffs) // load return value at spoffs of type rt s.stacktop = s.b.newValue2(ops.Load, t, addr, s.stacktop) // decrement offset to stack pointer s.spoffs -= t.storageSize() return s.stacktop } funcall(x :ast.CallExpr) :Value { // See https://rsms.me/co/doc/stack/ const s = this if (x.hasRest) { dlog(`TODO: handle call with hasRest`) } // TODO: handle any function by // let fv = s.expr(x.receiver) // and implementing function resolution somehow in readGlobal et al. assert(x.receiver instanceof ast.Ident, "non-id callee not yet supported") let funident = x.receiver as ast.Ident let ft = funident.type as FunType assert(ft, "unresolved function type") assert(funident.ent, "unresolved callee") assert(funident.ent!.value.isFunExpr(), "call on non-function") let funid = this.getFunId(funident.ent!.value as ast.FunExpr) // TODO: support other types like strings etc assert(ft.result.isPrimType(), `non-basic type ${ft.result.constructor.name} not yet supported`) // first unroll argument values in order (LTR) let argvals :Value[] = [] for (let arg of x.args) { argvals.push(s.expr(arg)) } // let stacksize = ft.argWidth() // includes receiver, args, and results // push params on stack for (let i = argvals.length; i > 0;) { let arg = argvals[--i] s.stackPush(arg) } // generate call op s.stacktop = s.b.newValue1(ops.Call, T.mem, s.stacktop, funid) // x.args.length // register call s.f.ncalls++ // TODO: We may want to use IntGraph to build a call graph // load return value off of the stack return s.stackPop(s.concreteType(ft.result as PrimType)) // == s.stacktop } readVariable(name :ByteStr, t :PrimType, b :Block|null) :Value { const s = this if (!b || b === s.b) { let v = s.vars.get(name) if (v) { return v } b = s.b } else { let m = s.defvars[b.id] if (m) { let v = m.get(name) if (v) { return v } } } // global value numbering return s.readVariableRecursive(name, t, b) } removeVariable(b :Block, name :ByteStr) :bool { if (b === this.b) { return this.vars.delete(name) } let m = this.defvars[b.id] return m ? m.delete(name) : false } readGlobal(name :ByteStr) :Value { const s = this dlog(`TODO readGlobal ${name}`) return s.nilValue() // FIXME } writeVariable(name :ByteStr, v :Value, b? :Block) { const s = this dlogVar(`${b || s.b} ${name} = ${v.op} ${v}`) if (!b || b === s.b) { s.vars.set(name, v) } else { let m = s.defvars[b.id] if (m) { m.set(name, v) } else { s.defvars[b.id] = new Map<ByteStr,Value>([[name, v]]) } } if (!(name instanceof TmpName)) { // TODO: find a better and more efficient way to map a LocalSlot // in a map structure. For now, we use a string representation of its // internal state. let local = new LocalSlot(name, v.type, 0) let e = s.f.namedValues.get(local.key()) if (e) { e.values.push(v) } else { s.f.namedValues.set(local.key(), { local, values: [v] }) } } } addIncompletePhi(phi :Value, name :ByteStr, b :Block) { const s = this dlogPhi(`${b} ${phi} var=${name}`) let names = s.incompletePhis ? s.incompletePhis.get(b) : null if (!names) { names = new Map<ByteStr,Value>() if (!s.incompletePhis) { s.incompletePhis = new Map<Block,Map<ByteStr,Value>>() } s.incompletePhis.set(b, names) } names.set(name, phi) } readVariableRecursive(name :ByteStr, t :PrimType, b :Block) :Value { const s = this let val :Value if (!b.sealed) { // incomplete CFG dlogPhi(`${b} ${name} not yet sealed`) val = b.newPhi(t) s.addIncompletePhi(val, name, b) } else if (b.preds.length == 1) { dlogPhi(`${b} ${name} common case: single predecessor ${b.preds[0]}`) // Optimize the common case of one predecessor: No phi needed val = s.readVariable(name, t, b.preds[0]) dlogPhi(`found ${name} : ${val}`) } else if (b.preds.length == 0) { dlogPhi(`${b} ${name} uncommon case: outside of function`) // entry block val = s.readGlobal(name) // TODO: consider just returning the value here instead of falling // through and causing writeVariable. } else { dlogPhi(`${b} ${name} uncommon case: multiple predecessors`) // Break potential cycles with operandless phi val = b.newPhi(t) s.writeVariable(name, val, b) val = s.addPhiOperands(name, val) } s.writeVariable(name, val, b) return val } addPhiOperands(name :ByteStr, phi :Value) :Value { const s = this assert(phi.op === ops.Phi) assert(phi.b.preds.length > 0, 'phi in block without predecessors') // Determine operands from predecessors dlogPhi(`${name} phi=${phi}`) for (let pred of phi.b.preds) { dlogPhi(` ${pred}`) let v = s.readVariable(name, phi.type, pred) if (v !== phi) { dlogPhi(` ${pred} ${v}<${v.op}>`) phi.addArg(v) } } return phi } // diag reports a diagnostic message, or an error if k is ERROR // diag(k :DiagKind, msg :string, pos :Pos) { const r = this assert(k != "error", "unexpected DiagKind 'error'") if (r.diagh) { assert(r.sfile) r.diagh((r.sfile as SrcFile).position(pos), msg, k) } } }
the_stack
import { MessageAttachmentResolvable } from '@src/api/entities/attachment/interfaces/MessageAttachmentResolvable' import { RawAttachment } from '@discordoo/providers' import { MessageAttachment } from '@src/api/entities/attachment/MessageAttachment' import { ColorResolvable } from '@src/api/entities/interfaces/ColorResolvable' import { EmptyBigBit, EmptyBit, PermissionFlags, RawColors } from '@src/constants' import { DiscordooError } from '@src/utils/DiscordooError' import { is } from 'typescript-is' import { ValidationError } from '@src/utils/ValidationError' import { MessageResolvable } from '@src/api/entities/message/interfaces/MessageResolvable' import { ChannelResolvable } from '@src/api/entities/channel/interfaces/ChannelResolvable' import { MessageEmbed, MessageEmbedResolvable, RawMessageEmbedData } from '@src/api/entities/embed' import { GuildResolvable } from '@src/api/entities/guild/interfaces/GuildResolvable' import { StickerResolvable } from '@src/api/entities/sticker' import { BigBitFieldResolvable, BitFieldResolvable } from '@src/api/entities/bitfield/interfaces' import { ReadonlyBigBitField } from '@src/api/entities/bitfield/ReadonlyBigBitField' import { ReadonlyBitField } from '@src/api/entities/bitfield/ReadonlyBitField' import { UserResolvable } from '@src/api/entities/user/interfaces/UserResolvable' import { Client } from '@src/core' import { RoleResolvable } from '@src/api/entities/role' import { RoleTagsResolvable } from '@src/api/entities/role/interfaces/RoleTagsResolvable' import { RoleTagsData } from '@src/api/entities/role/interfaces/RoleTagsData' import { ShardListResolvable } from '@src/utils/interfaces' import { range } from '@src/utils/range' import { EmojiResolvable, Message } from '@src/api' import { MessageReactionResolvable } from '@src/api/entities/reaction/interfaces/MessageReactionResolvable' import { PermissionOverwriteResolvable } from '@src/api/entities/overwrites/interfaces/PermissionOverwriteResolvable' import { RawPermissionOverwriteData } from '@src/api/entities/overwrites/interfaces/RawPermissionOverwriteData' import { ReplaceType } from '@src/utils/types' import { PermissionOverwrite } from '@src/api/entities/overwrites/PermissionOverwrite' import { GuildMemberResolvable } from '@src/api/entities/member/interfaces/GuildMemberResolvable' import { MessageReaction } from '@src/api/entities/reaction/MessageReaction' import { EntitiesUtil } from '@src/api/entities/EntitiesUtil' import { MessageReferenceResolvable } from '@src/api/entities/message/interfaces/MessageReferenceResolvable' import { RawMessageReferenceData } from '@src/api/entities/message/interfaces/RawMessageReferenceData' import { ThreadMemberResolvable } from '@src/api/entities/member/interfaces/ThreadMemberResolvable' export function resolveFiles(resolvable: MessageAttachmentResolvable[]): Promise<RawAttachment[]> { return Promise.all(resolvable.map(resolveFile)) } export function resolveFile(resolvable: MessageAttachmentResolvable): Promise<RawAttachment> { if (resolvable instanceof MessageAttachment) return resolvable.toRaw() return new MessageAttachment(resolvable).toRaw() // FIXME: low performance } export function resolveColor(resolvable: ColorResolvable): number { if (!is<ColorResolvable>(resolvable)) throw new ValidationError(undefined, 'Bad color:', resolvable) let result: any = RawColors.BLACK if (typeof resolvable === 'string') { switch (resolvable) { case 'DEFAULT': return RawColors.BLACK case 'RANDOM': return Math.floor(Math.random() * 16777215) default: result = RawColors[resolvable] ?? parseInt(resolvable.replace('#', ''), 16) } } else if (Array.isArray(resolvable)) { result = (resolvable[0] << 16) + (resolvable[1] << 8) + resolvable[2] } if (typeof result !== 'number' || isNaN(result) || result < 0 || result > 16777215) { throw new DiscordooError(undefined, 'Bad color:', resolvable) } return result } const InvalidBitFieldError = (invalid: any) => new DiscordooError(undefined, 'Invalid BitField:', invalid) export function resolveBigBitField(resolvable: BigBitFieldResolvable, emptyBit: bigint = EmptyBigBit): bigint { if (Array.isArray(resolvable)) { return resolvable.reduce<bigint>((prev, curr) => { return prev | resolveBigBitField(curr, emptyBit) }, emptyBit) } switch (typeof resolvable) { case 'number': { if (isNaN(resolvable) || resolvable === Infinity) throw InvalidBitFieldError(resolvable) return BigInt(resolvable) } case 'bigint': return resolvable case 'string': { try { if (resolvable.endsWith('n')) return BigInt(resolvable.slice(0, resolvable.length - 1)) return BigInt(resolvable) } catch (e) { throw new DiscordooError('BigBitFieldResolvable', 'Cannot convert', resolvable, 'to big bitfield.') } } case 'object': { if (resolvable instanceof ReadonlyBigBitField) return resolvable.bitfield if (typeof resolvable?.bits === 'string' && resolvable.bits?.endsWith('n')) return BigInt(resolvable.bits.slice(0, resolvable.bits.length)) } break } throw InvalidBitFieldError(resolvable) } export function resolveBitField(resolvable: BitFieldResolvable, emptyBit: number = EmptyBit): number { if (Array.isArray(resolvable)) { return resolvable.reduce<number>((prev, curr) => { return prev | resolveBitField(curr, emptyBit) }, emptyBit) } switch (typeof resolvable) { case 'number': { if (isNaN(resolvable) || resolvable === Infinity) throw InvalidBitFieldError(resolvable) return resolvable } case 'object': { if (resolvable instanceof ReadonlyBitField) return resolvable.bitfield if (typeof resolvable.bits === 'number'!) return resolvable.bits } } throw InvalidBitFieldError(resolvable) } export function resolveEmbedToRaw(resolvable: MessageEmbedResolvable): RawMessageEmbedData { if (resolvable instanceof MessageEmbed) return resolvable.toJson() return new MessageEmbed(resolvable).toJson() // FIXME: low performance } export function resolvePermissionOverwriteToRaw( resolvable: PermissionOverwriteResolvable, existing?: PermissionOverwrite ): RawPermissionOverwriteData { const result: ReplaceType<RawPermissionOverwriteData, 'allow' | 'deny', bigint> = { id: resolvable.id, type: resolvable.type, allow: existing?.allow?.bitfield ?? EmptyBigBit, deny: existing?.deny?.bitfield ?? EmptyBigBit, } if ('allow' in resolvable) { result.allow |= resolveBigBitField(resolvable.allow) result.deny |= resolveBigBitField(resolvable.deny) } else { let { allow, deny } = result for (const [ key, action ] of Object.entries(resolvable)) { if (PermissionFlags[key] === undefined) continue switch (action as boolean | null) { case true: allow |= PermissionFlags[key] // add to allow deny &= (~(PermissionFlags[key] | EmptyBigBit)) // remove from deny break case false: deny |= PermissionFlags[key] // add to deny allow &= (~(PermissionFlags[key] | EmptyBigBit)) // remove from allow break case null: allow &= (~(PermissionFlags[key] | EmptyBigBit)) // remove from allow deny &= (~(PermissionFlags[key] | EmptyBigBit)) // remove from deny break } } result.allow = allow result.deny = deny } return { ...result, deny: result.deny.toString(), allow: result.allow.toString() } } export async function resolveMessageReaction(client: Client, resolvable: MessageReactionResolvable): Promise<MessageReaction | undefined> { if (!resolvable) return undefined const MessageReaction = EntitiesUtil.get('MessageReaction') if (resolvable instanceof MessageReaction) return resolvable return resolvable.message && resolvable.emoji && resolvable.channel ? new MessageReaction(client).init(resolvable) : undefined } export function resolveRoleTags(resolvable: RoleTagsResolvable): RoleTagsData { return { botId: 'bot_id' in resolvable ? resolvable.bot_id : 'botId' in resolvable ? resolvable.botId : undefined, integrationId: 'integration_id' in resolvable ? resolvable.integration_id : 'integrationId' in resolvable ? resolvable.integrationId : undefined, premiumSubscriber: 'premium_subscriber' in resolvable ? true : 'premiumSubscriber' in resolvable ? resolvable.premiumSubscriber : false } } function resolveAnythingToId(resolvable: any): string | undefined { if (resolvable && typeof resolvable === 'string') return resolvable return resolvable?.id } export function resolveMessageId(resolvable: MessageResolvable): string | undefined { return resolveAnythingToId(resolvable) } export function resolveChannelId(resolvable: ChannelResolvable): string | undefined { return resolveAnythingToId(resolvable) } export function resolveGuildId(resolvable: GuildResolvable): string | undefined { return resolveAnythingToId(resolvable) } export function resolveStickerId(resolvable: StickerResolvable): string | undefined { return resolveAnythingToId(resolvable) } export function resolveUserId(resolvable: UserResolvable): string | undefined { return resolveAnythingToId(resolvable) } export function resolveUserOrMemberId(resolvable: UserResolvable | GuildMemberResolvable | ThreadMemberResolvable): string | undefined { return resolveMemberId(resolvable as any) ?? resolveUserId(resolvable as any) } export function resolveRoleId(resolvable: RoleResolvable): string | undefined { return resolveAnythingToId(resolvable) } export function resolveEmojiId(resolvable: EmojiResolvable | MessageReactionResolvable): string | undefined { if (typeof resolvable === 'string') return encodeURIComponent(resolvable) if ('emoji' in resolvable) { if ('emojiId' in resolvable) { return resolvable.emojiId } return resolveEmojiId(resolvable.emoji) } // sometimes I hate typings if ('id' in resolvable && resolvable.id) { return `${resolvable.animated ? 'a:' : ''}${resolvable.name}:${resolvable.id}` } else if ('name' in resolvable && resolvable.name) { return encodeURIComponent(resolvable.name) } return undefined } export function resolveMemberId(member: GuildMemberResolvable | ThreadMemberResolvable): string | undefined { if (typeof member === 'string') return member if (typeof member === 'object') { if ('userId' in member) return member.userId if ('user' in member && member.user) return resolveUserId(member.user) if ('user_id' in member) return member.user_id } return undefined } export function resolveDiscordShards(shards: ShardListResolvable): number[] { const source = 'DiscordShardListResolver' let result: number[] = [] switch (typeof shards) { case 'number': result = range(shards) break case 'string': if (!isNaN(parseInt(shards))) { result = range(parseInt(shards)) } else { throw new DiscordooError(source, 'received disallowed shard list type: string, value:', shards) } break case 'object': if (Array.isArray(shards)) { const arr = shards.filter(v => typeof v !== 'number'! || isNaN(v)) if (arr.length) { throw new DiscordooError(source, 'array of shards contains non-number value. array:', shards) } result = shards } else { if (typeof shards.from !== 'number'! || typeof shards.to !== 'number'!) { throw new DiscordooError(source, 'received object as shard list, but shards.from or shards.to is not a number.') } shards = range(shards.from, shards.to) } break default: throw new DiscordooError(source, 'received disallowed shard list type:', typeof shards) } return result } export function resolveDiscordooShards(client: Client, shards: ShardListResolvable | 'all' | 'current'): number[] { const source = 'DiscordooShardListResolver' let result: number[] = [] switch (typeof shards) { case 'string': { switch (true) { case shards === 'all': result = range(client.internals.sharding.totalShards) break case shards === 'current': result = [ ...client.internals.sharding.shards ] break case !isNaN(parseInt(shards)): result = [ parseInt(shards) ] break default: throw new DiscordooError(source, 'do not know how to resolve shards from this string:', shards) } } break case 'object': if (Array.isArray(shards)) { if (shards.filter(v => typeof v !== 'number'! || isNaN(v)).length) { throw new DiscordooError(source, 'array of shards contains non-number value. array:', shards) } result = shards } else { const shardsIsNaN = new DiscordooError(source, 'received object as shard list, but shards.from or shards.to is not a number.') if (typeof shards.from !== 'number'! || typeof shards.to !== 'number'!) { throw shardsIsNaN } if (isNaN(shards.from) || isNaN(shards.to)) { throw shardsIsNaN } result = range(shards.from, shards.to) } break case 'number': result = [ shards ] break default: throw new DiscordooError(source, 'do not know how to resolve shards from', typeof shards + '.', 'Provided shards:', shards) } return result } export function resolveMessageReferenceToRaw(resolvable: MessageReferenceResolvable): RawMessageReferenceData { const data: any = resolvable return { guild_id: data.guildId ?? data.guild_id ?? resolveGuildId(data.guild), channel_id: data.channelId ?? data.channel_id ?? resolveChannelId(data.channel), message_id: data.id ?? data.messageId ?? data.message_id ?? resolveMessageId(data.message) } } // TODO: resolveComponents
the_stack
import nj from '../core'; import * as tools from '../utils/tools'; import '../helpers/filter'; //Get compiled property const REGEX_JS_PROP = /('[^']*')|("[^"]*")|(-?[0-9][0-9]*(\.\d+)?)|true|false|null|undefined|Object|Array|Math|Date|JSON|(([a-zA-Z_$#@])([a-zA-Z_$\d]*))/; const REGEX_REPLACE_CHAR = /_njQs(\d+)_/g; const REGEX_REPLACE_SET = /_njSet_/; function _replaceStr(prop, innerQuotes) { return prop.replace(REGEX_REPLACE_CHAR, (all, g1) => innerQuotes[g1]); } function _compiledProp(prop, innerBrackets, innerQuotes, source) { const ret = tools.obj(); const propO = prop; //If there are vertical lines in the property,then use filter if (prop.indexOf('|') >= 0) { const filters = []; let filtersTmp; filtersTmp = prop.split('|'); prop = filtersTmp[0].trim(); //Extract property filtersTmp = filtersTmp.slice(1); tools.each( filtersTmp, filter => { filter = filter.trim(); if (filter === '') { return; } const retF = _getFilterParam(filter), filterObj = tools.obj(), filterName = retF[0].trim(); //Get filter name if (filterName) { const paramsF = retF[1]; //Get filter param //Multiple params are separated by commas. if (paramsF != null) { const params = []; tools.each( innerBrackets[paramsF].split(','), p => { if (p !== '') { params[params.length] = _compiledProp(p.trim(), innerBrackets, innerQuotes, source); } }, true ); filterObj.params = params; } filterObj.name = filterName; filters.push(filterObj); } }, true ); ret.filters = filters; } //替换字符串值 prop = _replaceStr(prop, innerQuotes); //Extract the parent data path if (prop.indexOf('../') === 0) { let n = 0; prop = prop.replace(/\.\.\//g, function() { n++; return ''; }); ret.parentNum = n; } //Extract the js property if (prop !== '') { const matchProp = REGEX_JS_PROP.exec(prop); const hasAccessor = matchProp[6] === '#'; ret.name = hasAccessor ? matchProp[7] : matchProp[0]; if (!matchProp[5]) { //Sign the parameter is a basic type value. ret.isBasicType = true; } if (hasAccessor) { ret.isAccessor = true; } ret.name = ret.name.replace(REGEX_REPLACE_SET, () => { ret.hasSet = true; return ''; }); } else { ret.isEmpty = true; } return ret; } //Get filter param function _getFilterParam(obj) { return obj.split(`'bracket_`); } //Extract replace parameters const REGEX_LT_GT = /_nj(L|G)t_/g; const LT_GT_LOOKUP = { _njLt_: '<', _njGt_: '>' }; const REGEX_QUOTE = /"[^"]*"|'[^']*'/g; const REGEX_OPERATORS_ESCAPE = /\*|\||\/|\.|\?|\+/g; const SP_FILTER_LOOKUP = { '||': 'or', '..': 'rOpe', '..<': 'rLt' }; let REGEX_SP_FILTER; function createFilterAlias(name?, alias?) { if (name && alias) { SP_FILTER_LOOKUP[name] = alias; } REGEX_SP_FILTER = new RegExp( '[\\s]+((' + Object.keys(SP_FILTER_LOOKUP) .map(o => { return o.replace(REGEX_OPERATORS_ESCAPE, match => '\\' + match); }) .join('|') + ')[\\s]+)', 'g' ); } createFilterAlias(); const FN_FILTER_LOOKUP = { ')': ')_(', ']': ']_(' }; const REGEX_FN_FILTER = /(\)|\]|\.([^\s'"._#()|]+))[\s]*\(/g; const REGEX_SPACE_S_FILTER = /([(,|])[\s]+/g; const REGEX_PROP_FILTER = /\.([a-zA-Z_$#@][a-zA-Z_$\d]*)/g; const REGEX_ARRPROP_FILTER = /([^\s([,])(\[)/g; const ARR_OBJ_FILTER_LOOKUP = { '[': 'list(', ']': ')', '{': 'obj(', '}': ')' }; const REGEX_ARR_OBJ_FILTER = /\[|\]|\{|\}/g; //const REGEX_OBJKEY_FILTER = /([(,][\s]*)([^\s:,'"()|]+):/g; const REGEX_SET_FILTER = /^[\s]*set[\s]+|([(,])[\s]*set[\s]+/g; const REGEX_BRACKET_FILTER = /^[\s]*([(]+)|([(,])[\s]*([(]+)/g; const NOT_OPERATORS = ['../']; const REGEX_NEGATIVE = /-[0-9]/; const BEGIN_CHARS = ['', '(', '[', ',']; const OPERATORS = [ '+=', '+', '-[0-9]', '-', '**', '*', '%%', '%', '===', '!==', '==', '!=', '<=>', '<=', '>=', '=', '..<', '<', '>', '&&', '||', '?:', '?', ':', '../', '..', '/' ]; let REGEX_OPERATORS; function createRegexOperators(operator?) { if (operator) { let insertIndex = 0; OPERATORS.forEach((o, i) => { if (o.indexOf(operator) >= 0) { insertIndex = i + 1; } }); OPERATORS.splice(insertIndex, 0, operator); } REGEX_OPERATORS = new RegExp( OPERATORS.map(o => { return o.replace(REGEX_OPERATORS_ESCAPE, match => '\\' + match); }).join('|'), 'g' ); } createRegexOperators(); function _getProp(matchArr, innerQuotes, i, addSet) { let prop = matchArr[2].trim(); const item = [matchArr[0], matchArr[1], null, true]; if (i > 0) { item[3] = false; //Sign not contain all of placehorder } if (addSet) { prop = 'set ' + prop; } //替换特殊过滤器名称并且为简化过滤器补全"|"符 prop = prop .replace(REGEX_LT_GT, match => LT_GT_LOOKUP[match]) .replace(REGEX_QUOTE, match => { innerQuotes.push(match); return '_njQs' + (innerQuotes.length - 1) + '_'; }) .replace(REGEX_OPERATORS, (match, index) => { if (REGEX_NEGATIVE.test(match)) { if (index > 0 && BEGIN_CHARS.indexOf(prop[index - 1].trim()) < 0) { //Example: 123-456 return match.split('-').join(' - '); } else { //Example: -123+456 return match; } } else { return NOT_OPERATORS.indexOf(match) < 0 ? ` ${match} ` : match; } }) .replace(REGEX_SP_FILTER, (all, g1, match) => ' ' + SP_FILTER_LOOKUP[match] + ' ') .replace(REGEX_PROP_FILTER, (all, g1) => { const startWithHash = g1[0] === '#'; if (startWithHash) { g1 = g1.substr(1); } const lastCharIndex = g1.length - 1, endWithUnderline = lastCharIndex > 0 && g1[lastCharIndex] === '_'; return ( (startWithHash ? '#' : '.') + `('` + (endWithUnderline ? g1.substr(0, lastCharIndex) : g1) + `')` + (endWithUnderline ? '_' : '') ); }) .replace(REGEX_ARRPROP_FILTER, (all, g1, g2) => g1 + '.(') .replace(REGEX_ARR_OBJ_FILTER, match => ARR_OBJ_FILTER_LOOKUP[match]) .replace(REGEX_SET_FILTER, (all, g1) => (g1 ? g1 : '') + '_njSet_') .replace(REGEX_BRACKET_FILTER, (all, g1, g2, g3) => (g2 ? g2 : '') + (g2 ? g3 : g1).replace(/[(]/g, 'bracket(')) //.replace(REGEX_OBJKEY_FILTER, (all, g1, g2) => g1 + ' \'' + g2 + '\' : ') .replace(REGEX_SPACE_S_FILTER, (all, match) => match) .replace(REGEX_FN_FILTER, (all, match, g1) => (!g1 ? FN_FILTER_LOOKUP[match] : `.('` + g1 + `')_(`)); item[2] = prop.trim(); return item; } function _getReplaceParam(obj, tmplRule, innerQuotes, hasColon, addSet) { const pattern = tmplRule.replaceParam; let matchArr, ret, i = 0; if (!hasColon) { while ((matchArr = pattern.exec(obj))) { if (!ret) { ret = []; } const startRuleR = matchArr[2]; ret.push( _getProp( [matchArr[0], startRuleR ? startRuleR : matchArr[5], startRuleR ? matchArr[3] : matchArr[6]], innerQuotes, i, addSet ) ); i++; } } else { matchArr = [obj, tmplRule.startRule, obj]; ret = [_getProp(matchArr, innerQuotes, i, addSet)]; } return ret; } const REGEX_INNER_BRACKET = /\(([^()]*)\)/g; const REGEX_FIX_OPERATOR_1 = /([!]+)((-?[0-9][0-9]*(\.\d+)?|[^\s,|'=]+)('bracket_\d+)?([._#]'bracket_\d+)*)/g; const REGEX_FIX_OPERATOR = /[\s]+([^\s(),|"']+)[\s]+((-?[0-9][0-9]*(\.\d+)?|[^\s,|']+)('bracket_\d+)?([._#]'bracket_\d+)*)/g; const REGEX_SPACE_FILTER = /[(,]/g; const REGEX_FIX_FILTER = /(\|)?(((\.+|_|#+)'bracket_)|[\s]+([^\s._#|]+[\s]*'bracket_))/g; function _fixOperator(prop, innerBrackets) { prop = prop.replace(REGEX_FIX_OPERATOR_1, function() { const args = arguments; innerBrackets.push(_fixFilter(args[2])); return args[1] + `'bracket_` + (innerBrackets.length - 1); }); return _fixFilter( prop.replace(REGEX_FIX_OPERATOR, function() { const args = arguments; innerBrackets.push(_fixFilter(args[2])); return ' ' + args[1] + `'bracket_` + (innerBrackets.length - 1); }) ); } function _fixFilter(prop) { return (' ' + prop) .replace(REGEX_SPACE_FILTER, all => all + ' ') .replace(REGEX_FIX_FILTER, (all, g1, g2, g3, g4, g5) => (g1 ? all : ' | ' + (g3 ? g3 : g5))) .trim(); } function _replaceInnerBrackets(prop, innerBrackets) { const propR = prop.replace(REGEX_INNER_BRACKET, (all, s1) => { innerBrackets.push(_fixOperator(s1, innerBrackets)); return `'bracket_` + (innerBrackets.length - 1); }); if (propR !== prop) { return _replaceInnerBrackets(propR, innerBrackets); } else { return _fixOperator(propR, innerBrackets); } } //Get compiled parameter export function compiledParam(value, tmplRule, hasColon?, onlyKey?, addSet?) { const ret = tools.obj(), isStr = tools.isString(value); let strs = isStr ? (!hasColon ? value.split(tmplRule.replaceSplit) : ['', '']) : [value], props = null, isAll = false; //此处指替换符是否占满整个属性值;若无替换符时为false if (isStr) { //替换插值变量以外的文本中的换行符 strs = strs.map(str => str.replace(/\n/g, '_njNl_').replace(/\r/g, '')); } //If have placehorder if (strs.length > 1) { const innerQuotes = []; const params = _getReplaceParam(value, tmplRule, innerQuotes, hasColon, addSet); props = []; tools.each( params, param => { const retP = tools.obj(), innerBrackets = []; isAll = param[3] ? param[0] === value : false; //If there are several curly braces in one property value, "isAll" must be false. const prop = _replaceInnerBrackets(param[2], innerBrackets); retP.prop = _compiledProp(prop, innerBrackets, innerQuotes, value); //To determine whether it is necessary to escape retP.escape = param[1] !== tmplRule.firstChar + tmplRule.startRule; props.push(retP); }, true ); } ret.props = props; ret.strs = strs; ret.isAll = isAll; ret.onlyKey = onlyKey; return ret; } tools.assign(nj, { createFilterAlias, createRegexOperators });
the_stack
import { assert, expect } from "chai"; import * as sinon from "sinon"; import * as path from "path"; import { BisCodeSpec, Code, DefinitionElementProps, ElementAspectProps, EntityMetaData, RelatedElement, RelatedElementProps } from "@itwin/core-common"; import { DefinitionElement, IModelDb, RepositoryLink, Schema, SnapshotDb, SpatialViewDefinition, UrlLink, ViewDefinition3d, } from "../../core-backend"; import { IModelTestUtils } from "../IModelTestUtils"; import { KnownTestLocations } from "../KnownTestLocations"; import { Element } from "../../Element"; import { Schemas } from "../../Schema"; import { ClassRegistry } from "../../ClassRegistry"; import { Id64Set } from "@itwin/core-bentley"; describe("Class Registry", () => { let imodel: SnapshotDb; before(() => { const seedFileName = IModelTestUtils.resolveAssetFile("test.bim"); const testFileName = IModelTestUtils.prepareOutputFile("ClassRegistry", "ClassRegistryTest.bim"); imodel = IModelTestUtils.createSnapshotFromSeed(testFileName, seedFileName); assert.exists(imodel); }); after(() => { imodel?.close(); }); it("should verify the Entity metadata of known element subclasses", () => { const code1 = new Code({ spec: "0x10", scope: "0x11", value: "RF1.dgn" }); const el = imodel.elements.getElement(code1); assert.exists(el); if (el) { const metaData: EntityMetaData | undefined = el.getClassMetaData(); assert.exists(metaData); if (undefined === metaData) return; assert.equal(metaData.ecclass, el.classFullName); // I happen to know that this is a BisCore:RepositoryLink assert.equal(metaData.ecclass, RepositoryLink.classFullName); // Check the metadata on the class itself assert.isTrue(metaData.baseClasses.length > 0); assert.equal(metaData.baseClasses[0], UrlLink.classFullName); assert.equal(metaData.customAttributes![0].ecclass, "BisCore:ClassHasHandler"); // Check the metadata on the one property that RepositoryLink defines, RepositoryGuid assert.exists(metaData.properties); assert.isDefined(metaData.properties.repositoryGuid); const p = metaData.properties.repositoryGuid; assert.equal(p.extendedType, "BeGuid"); assert.equal(p.customAttributes![1].ecclass, "CoreCustomAttributes:HiddenProperty"); } const el2 = imodel.elements.getElement("0x34"); assert.exists(el2); if (el2) { const metaData = el2.getClassMetaData(); assert.exists(metaData); if (undefined === metaData) return; assert.equal(metaData.ecclass, el2.classFullName); // I happen to know that this is a BisCore.SpatialViewDefinition assert.equal(metaData.ecclass, SpatialViewDefinition.classFullName); assert.isTrue(metaData.baseClasses.length > 0); assert.equal(metaData.baseClasses[0], ViewDefinition3d.classFullName); assert.exists(metaData.properties); assert.isDefined(metaData.properties.modelSelector); const n = metaData.properties.modelSelector; assert.equal(n.relationshipClass, "BisCore:SpatialViewDefinitionUsesModelSelector"); } }); it("should verify Entity metadata with both base class and mixin properties", async () => { const schemaPathname = path.join(KnownTestLocations.assetsDir, "TestDomain.ecschema.xml"); await imodel.importSchemas([schemaPathname]); // will throw an exception if import fails const testDomainClass = imodel.getMetaData("TestDomain:TestDomainClass"); // will throw on failure assert.equal(testDomainClass.baseClasses.length, 2); assert.equal(testDomainClass.baseClasses[0], DefinitionElement.classFullName); assert.equal(testDomainClass.baseClasses[1], "TestDomain:IMixin"); // Ensures the IMixin has been loaded as part of getMetadata call above. assert.isDefined(imodel.classMetaDataRegistry.find("TestDomain:IMixin")); // Verify that the forEach method which is called when constructing an entity // is picking up all expected properties. const testData: string[] = []; IModelDb.forEachMetaData(imodel, "TestDomain:TestDomainClass", true, (propName) => { testData.push(propName); }, false); const expectedString = testData.find((testString: string) => { return testString === "testMixinProperty"; }); assert.isDefined(expectedString); }); }); describe("Class Registry - generated classes", () => { let imodel: SnapshotDb; const testSchemaPath = path.join(KnownTestLocations.assetsDir, "TestGeneratedClasses.ecschema.xml"); before(async () => { const seedFileName = IModelTestUtils.resolveAssetFile("test.bim"); const testFileName = IModelTestUtils.prepareOutputFile("ClassRegistry", "ClassRegistryTest.bim"); imodel = IModelTestUtils.createSnapshotFromSeed(testFileName, seedFileName); assert.exists(imodel); await imodel.importSchemas([testSchemaPath]); // will throw an exception if import fails }); after(() => { imodel?.close(); }); interface TestEntityProps extends DefinitionElementProps { prop: string; } interface TestElementWithNavPropProps extends DefinitionElementProps { navProp: RelatedElementProps; } interface DerivedWithNavPropProps extends TestElementWithNavPropProps { derivedNavProp: RelatedElementProps; } // eslint-disable-next-line @typescript-eslint/no-unused-vars interface TestNonElementWithNavPropProps extends ElementAspectProps { navProp: RelatedElement; } class TestGeneratedClasses extends Schema { public static override get schemaName(): string { return "TestGeneratedClasses"; } public static get classes() { return [ TestElementWithNavProp, DerivedWithNavProp, Derived2, Derived3, Derived4, Derived5, Derived6 ]; } public static registerSchema() { if (this !== Schemas.getRegisteredSchema(this.schemaName)) { Schemas.unregisterSchema(this.schemaName); Schemas.registerSchema(this); // eslint-disable-next-line @typescript-eslint/naming-convention for (const class_ of this.classes) { ClassRegistry.register(class_, this); } } } public static unregisterSchema() { Schemas.unregisterSchema(this.schemaName); } } class TestElementWithNavProp extends DefinitionElement { public static override get className() { return "TestElementWithNavProp"; } public static override schema = TestGeneratedClasses; public navProp: RelatedElement; public constructor(props: TestElementWithNavPropProps, inIModel: IModelDb) { super(props, inIModel); this.navProp = new RelatedElement(props.navProp); } } class DerivedWithNavProp extends TestElementWithNavProp { public static override get className() { return "DerivedWithNavProp"; } public static override schema = TestGeneratedClasses; public derivedNavProp: RelatedElement; public constructor(props: DerivedWithNavPropProps, inIModel: IModelDb) { super(props, inIModel); this.derivedNavProp = new RelatedElement(props.derivedNavProp); } } class Derived2 extends DerivedWithNavProp { public static override get className() { return "Derived2"; } } class Derived3 extends Derived2 { public static override get className() { return "Derived3"; } } class Derived4 extends Derived3 { public static override get className() { return "Derived4"; } } class Derived5 extends Derived4 { public static override get className() { return "Derived5"; } } class Derived6 extends Derived5 { public static override get className() { return "Derived6"; } } // if a single inherited class is not generated, the entire hierarchy is considered not-generated it("should only generate automatic collectPredecessorIds implementations for generated classes", async () => { await imodel.importSchemas([testSchemaPath]); // will throw an exception if import fails // eslint-disable-next-line @typescript-eslint/naming-convention const GeneratedTestElementWithNavProp = imodel.getJsClass<typeof Element>("TestGeneratedClasses:TestElementWithNavProp"); const testEntityId = imodel.elements.insertElement({ classFullName: "TestGeneratedClasses:TestEntity", prop: "sample-value", model: IModelDb.dictionaryId, code: Code.createEmpty(), } as TestEntityProps); const elemWithNavProp = new GeneratedTestElementWithNavProp({ classFullName: "TestGeneratedClasses:TestElementWithNavProp", navProp: { id: testEntityId, relClassName: "TestGeneratedClasses:ElemRel", }, } as TestElementWithNavPropProps, imodel); // eslint-disable-next-line @typescript-eslint/unbound-method assert.isDefined(GeneratedTestElementWithNavProp.prototype.getPredecessorIds); expect( [...elemWithNavProp.getPredecessorIds()], ).to.have.members( [elemWithNavProp.model, elemWithNavProp.code.scope, testEntityId] ); // eslint-disable-next-line @typescript-eslint/naming-convention const GeneratedTestNonElementWithNavProp = imodel.getJsClass("TestGeneratedClasses:TestNonElementWithNavProp"); assert.isFalse(GeneratedTestNonElementWithNavProp.prototype.hasOwnProperty("collectPredecessorIds")); }); it("should not override collectPredecessorIds for BisCore schema classes", async () => { // AnnotationFrameStyle is an example of an unregistered bis class without an implementation of collectPredecessorIds // eslint-disable-next-line @typescript-eslint/dot-notation assert.isTrue(imodel.getJsClass("BisCore:AnnotationFrameStyle").prototype.hasOwnProperty("collectPredecessorIds")); }); it("should get predecessors from its bis superclass", async () => { await imodel.importSchemas([testSchemaPath]); // will throw an exception if import fails // eslint-disable-next-line @typescript-eslint/naming-convention const GeneratedTestElementWithNavProp = imodel.getJsClass<typeof Element>("TestGeneratedClasses:TestElementWithNavProp"); const testEntityId = imodel.elements.insertElement({ classFullName: "TestGeneratedClasses:TestEntity", prop: "sample-value", model: IModelDb.dictionaryId, code: Code.createEmpty(), } as TestEntityProps); const elemWithNavProp = new GeneratedTestElementWithNavProp({ classFullName: "TestGeneratedClasses:TestElementWithNavProp", navProp: new RelatedElement({ id: testEntityId, relClassName: "TestGeneratedClasses:ElemRel", }), model: IModelDb.dictionaryId, code: new Code({ scope: IModelDb.rootSubjectId, spec: imodel.codeSpecs.getByName(BisCodeSpec.spatialCategory).id, value: "", }), parent: new RelatedElement({ // since we don't actually insert this element in this test, using an arbitrary id string id: "0x0000ffff", relClassName: "BisCore:ElementOwnsChildElements", }), } as TestElementWithNavPropProps, imodel); // super class here is Element so we should get the code.scope, model and parent as predecessors expect( [...elemWithNavProp.getPredecessorIds()], ).to.have.members( [elemWithNavProp.model, elemWithNavProp.code.scope, elemWithNavProp.parent?.id, testEntityId].filter((x) => x !== undefined) ); }); it("should not override custom registered schema class implementations of collectPredecessorIds", async () => { const testImplPredecessorId = "TEST-INVALID-ID"; class MyTestElementWithNavProp extends TestElementWithNavProp { public override collectPredecessorIds(predecessorIds: Id64Set) { super.collectPredecessorIds(predecessorIds); predecessorIds.add(testImplPredecessorId); } } class MyTestGeneratedClasses extends TestGeneratedClasses { public static override get classes() { return [ MyTestElementWithNavProp, Derived2, Derived3, Derived4, Derived5, Derived6 ]; } } MyTestGeneratedClasses.registerSchema(); // eslint-disable-next-line @typescript-eslint/naming-convention const ActualTestElementWithNavProp = imodel.getJsClass<typeof MyTestElementWithNavProp>(TestElementWithNavProp.classFullName); const testElementWithNavPropCollectPredecessorsSpy = sinon.spy(ActualTestElementWithNavProp.prototype, "collectPredecessorIds"); // eslint-disable-next-line @typescript-eslint/naming-convention const ActualDerivedWithNavProp = imodel.getJsClass<typeof Element>(DerivedWithNavProp.classFullName); const testEntity1Id = imodel.elements.insertElement({ classFullName: "TestGeneratedClasses:TestEntity", prop: "sample-value-1", model: IModelDb.dictionaryId, code: Code.createEmpty(), } as TestEntityProps); const testEntity2Id = imodel.elements.insertElement({ classFullName: "TestGeneratedClasses:TestEntity", prop: "sample-value-2", model: IModelDb.dictionaryId, code: Code.createEmpty(), } as TestEntityProps); const elemWithNavProp = new ActualTestElementWithNavProp({ classFullName: TestElementWithNavProp.classFullName, navProp: { id: testEntity1Id, relClassName: "TestGeneratedClasses:ElemRel", }, } as TestElementWithNavPropProps, imodel); // eslint-disable-next-line @typescript-eslint/unbound-method assert.isDefined(ActualTestElementWithNavProp.prototype.getPredecessorIds); expect( [...elemWithNavProp.getPredecessorIds()], ).to.have.members( [elemWithNavProp.model, elemWithNavProp.code.scope, elemWithNavProp.parent?.id, testImplPredecessorId].filter((x) => x !== undefined) ); expect(testElementWithNavPropCollectPredecessorsSpy.called).to.be.true; testElementWithNavPropCollectPredecessorsSpy.resetHistory(); const derivedElemWithNavProp = new ActualDerivedWithNavProp({ classFullName: DerivedWithNavProp.classFullName, navProp: { id: testEntity1Id, relClassName: "TestGeneratedClasses:ElemRel", }, derivedNavProp: { id: testEntity2Id, relClassName: "TestGeneratedClasses:DerivedElemRel", }, } as DerivedWithNavPropProps, imodel); // eslint-disable-next-line @typescript-eslint/unbound-method assert.isDefined(ActualDerivedWithNavProp.prototype.getPredecessorIds); // This demonstrates that if a non-generated class has a registered non-biscore base, it will not get a generated impl, expect( [...derivedElemWithNavProp.getPredecessorIds()] ).to.have.members( [elemWithNavProp.model, elemWithNavProp.code.scope, elemWithNavProp.parent?.id, testImplPredecessorId].filter((x) => x !== undefined) ); // explicitly check we called the super function // (we already know its implementation was called, because testImplPredecessorId is in the derived call's result) expect(testElementWithNavPropCollectPredecessorsSpy.called).to.be.true; sinon.restore(); MyTestGeneratedClasses.unregisterSchema(); }); it("should work along a complex chain of overrides", async () => { class MyDerived2 extends Derived2 { public override collectPredecessorIds(predecessorIds: Id64Set) { super.collectPredecessorIds(predecessorIds); predecessorIds.add("derived-2"); } } class MyDerived4 extends Derived4 { public override collectPredecessorIds(predecessorIds: Id64Set) { super.collectPredecessorIds(predecessorIds); predecessorIds.add("derived-4"); } } class MyTestGeneratedClasses extends TestGeneratedClasses { public static override get classes() { // leaving Derived3,5,6 generated return [MyDerived2, MyDerived4]; } } MyTestGeneratedClasses.registerSchema(); /* eslint-disable @typescript-eslint/naming-convention */ const ActualTestElementWithNavProp = imodel.getJsClass<typeof Element>("TestGeneratedClasses:TestElementWithNavProp"); const ActualDerivedWithNavProp = imodel.getJsClass<typeof Element>("TestGeneratedClasses:DerivedWithNavProp"); const ActualDerived2 = imodel.getJsClass<typeof Element>("TestGeneratedClasses:Derived2"); const ActualDerived3 = imodel.getJsClass<typeof Element>("TestGeneratedClasses:Derived3"); const ActualDerived4 = imodel.getJsClass<typeof Element>("TestGeneratedClasses:Derived4"); const ActualDerived5 = imodel.getJsClass<typeof Element>("TestGeneratedClasses:Derived5"); const ActualDerived6 = imodel.getJsClass<typeof Element>("TestGeneratedClasses:Derived6"); /* eslint-enable @typescript-eslint/no-redeclare */ expect(ActualTestElementWithNavProp.isGeneratedClass).to.be.true; expect(ActualDerivedWithNavProp.isGeneratedClass).to.be.true; expect(ActualDerived2.isGeneratedClass).to.be.false; expect(ActualDerived3.isGeneratedClass).to.be.true; expect(ActualDerived4.isGeneratedClass).to.be.false; expect(ActualDerived5.isGeneratedClass).to.be.true; expect(ActualDerived6.isGeneratedClass).to.be.true; assert.isTrue(ActualTestElementWithNavProp.prototype.hasOwnProperty("collectPredecessorIds" )); // should have automatic impl assert.isTrue(ActualDerivedWithNavProp.prototype.hasOwnProperty("collectPredecessorIds")); assert.isTrue(ActualDerived2.prototype.hasOwnProperty("collectPredecessorIds")); // non-generated; manually implements so has method assert.isFalse(ActualDerived3.prototype.hasOwnProperty("collectPredecessorIds")); // base is non-generated so it shouldn't get the automatic impl assert.isTrue(ActualDerived4.prototype.hasOwnProperty("collectPredecessorIds")); // manually implements so it should have the method assert.isFalse(ActualDerived5.prototype.hasOwnProperty("collectPredecessorIds")); // ancestor is non-generated so it shouldn't get the automatic impl assert.isFalse(ActualDerived6.prototype.hasOwnProperty("collectPredecessorIds")); // ancestor is non-generated so it shouldn't get the automatic impl const testEntity1Id = imodel.elements.insertElement({ classFullName: "TestGeneratedClasses:Derived6", prop: "sample-value-1", model: IModelDb.dictionaryId, code: Code.createEmpty(), } as TestEntityProps); const testEntity2Id = imodel.elements.insertElement({ classFullName: "TestGeneratedClasses:TestEntity", prop: "sample-value-2", model: IModelDb.dictionaryId, code: Code.createEmpty(), } as TestEntityProps); const derived6Id = imodel.elements.insertElement({ classFullName: Derived6.classFullName, model: IModelDb.dictionaryId, navProp: { id: testEntity1Id, relClassName: "TestGeneratedClasses:ElemRel", }, derivedNavProp: { id: testEntity2Id, relClassName: "TestGeneratedClasses:DerivedElemRel", }, } as DerivedWithNavPropProps); const derived6 = imodel.elements.getElement(derived6Id); /** it is not possible to make a spy of an already existing spy, so lazy try making one * this is necessary since due to prototypes, some "methods" we listen to are actually the same */ function spyCollectPredecessorIds(cls: typeof Element): sinon.SinonSpy { if ((cls.prototype as any).collectPredecessorIds.isSinonProxy) { return (cls.prototype as any).collectPredecessorIds; } return sinon.spy(cls.prototype, "collectPredecessorIds" as any); } const elementMethodSpy = spyCollectPredecessorIds(Element); const testElementWithNavPropSpy = spyCollectPredecessorIds(ActualTestElementWithNavProp); const derivedWithNavPropSpy = spyCollectPredecessorIds(ActualDerivedWithNavProp); const derived2Spy = spyCollectPredecessorIds(ActualDerived2); const derived3Spy = spyCollectPredecessorIds(ActualDerived3); const derived4Spy = spyCollectPredecessorIds(ActualDerived4); const derived5Spy = spyCollectPredecessorIds(ActualDerived5); const derived6Spy = spyCollectPredecessorIds(ActualDerived6); // This demonstrates that if a generated class (Derived6) has a non-generated ancestor, it will not get a generated impl // instead it will just call the closest non-generated ancestor (Derived4) expect([...derived6.getPredecessorIds()]).to.have.members( [ derived6.model, derived6.code.scope, derived6.parent?.id, // "TestGeneratedClasses:Derived4" is MyDerived4 above, which extends the Derived4 class, which extends up // without any custom ancestor implementing collectPredecessorIds, so Element.collectPredecessorIds is called as the // super, and no navigation properties or other custom implementations are called so we only get "derived-4" "derived-4", ].filter((x) => x !== undefined) ); expect(elementMethodSpy.called).to.be.true; // this is the `super.collectPredecessorIds` call in MyDerived4 expect(testElementWithNavPropSpy.called).to.be.false; expect(derivedWithNavPropSpy.called).to.be.false; // these are the same (tested below) expect(derived2Spy.called).to.be.false; expect(derived3Spy.called).to.be.false; // these are all the same (tested below) expect(derived4Spy.called).to.be.true; expect(derived5Spy.called).to.be.true; expect(derived6Spy.called).to.be.true; expect( new Set( [ Element, ActualTestElementWithNavProp, ActualDerivedWithNavProp, Derived2, Derived3, // same as above (so will be removed from set) Derived4, Derived5, // save as above (so will be removed from set) Derived6, // save as above (so will be removed from set) ].map((e) => e.prototype["collectPredecessorIds"]) // eslint-disable-line @typescript-eslint/dot-notation ) ).to.deep.equal( new Set( [ Element, ActualTestElementWithNavProp, ActualDerivedWithNavProp, Derived2, Derived4, // eslint-disable-next-line @typescript-eslint/dot-notation ].map((e) => e.prototype["collectPredecessorIds"]) // eslint-disable-line @typescript-eslint/dot-notation ) ); MyTestGeneratedClasses.unregisterSchema(); sinon.restore(); }); }); class Base { public static staticProperty: string = "base"; public static get sqlName(): string { return `s.${this.staticProperty}`; } } class Derived extends Base { } describe("Static Properties", () => { it("should be inherited, and the subclass should get its own copy", async () => { assert.equal(Base.staticProperty, "base"); assert.equal(Derived.staticProperty, "base"); // Derived inherits Base's staticProperty (via its prototype) Derived.staticProperty = "derived"; // Derived now gets its own copy of staticProperty assert.equal(Base.staticProperty, "base"); // Base's staticProperty remains as it was assert.equal(Derived.staticProperty, "derived"); // Derived's staticProperty is now different assert.equal(Base.sqlName, "s.base"); const d = new Derived(); assert.equal((d.constructor as any).staticProperty, "derived"); // Instances of Derived see Derived.staticProperty const b = new Base(); assert.equal((b.constructor as any).staticProperty, "base"); // Instances of Base see Base.staticProperty }); });
the_stack
import { Result, asyncResult } from '@expo/results'; import { EntityCompanionDefinition } from './EntityCompanionProvider'; import { CreateMutator, UpdateMutator } from './EntityMutator'; import EntityPrivacyPolicy from './EntityPrivacyPolicy'; import { EntityQueryContext } from './EntityQueryContext'; import ReadonlyEntity from './ReadonlyEntity'; import ViewerContext from './ViewerContext'; /** * Entity is a privacy-first data model. * * A instance of an entity represents a single "row" of persisted data in a database that a * viewer, represented by the corresponding {@link ViewerContext}, has permission to read. * * Create, read, update, and delete permissions for an entity are declaratively defined using an * {@link EntityPrivacyPolicy}. * * Entites are loaded through an {@link EntityLoader}, which is responsible for * orchestrating fetching, caching, and authorization of reading "rows". * * Entities are mutated and deleted through an {@link EntityMutator}, which is responsible for * orchestrating database writes, cache invalidation, and authorization of writing "rows". * * All concrete entity implementations should extend this class and provide their * own {@link EntityCompanionDefinition}. */ export default abstract class Entity< TFields, TID extends NonNullable<TFields[TSelectedFields]>, TViewerContext extends ViewerContext, TSelectedFields extends keyof TFields = keyof TFields > extends ReadonlyEntity<TFields, TID, TViewerContext, TSelectedFields> { /** * Vend mutator for creating a new entity in given query context. * @param viewerContext - viewer context of creating user * @param queryContext - query context in which to perform the create * @returns mutator for creating an entity */ static creator< TMFields, TMID extends NonNullable<TMFields[TMSelectedFields]>, TMViewerContext extends ViewerContext, TMViewerContext2 extends TMViewerContext, TMEntity extends Entity<TMFields, TMID, TMViewerContext, TMSelectedFields>, TMPrivacyPolicy extends EntityPrivacyPolicy< TMFields, TMID, TMViewerContext, TMEntity, TMSelectedFields >, TMSelectedFields extends keyof TMFields = keyof TMFields >( this: IEntityClass< TMFields, TMID, TMViewerContext, TMEntity, TMPrivacyPolicy, TMSelectedFields >, viewerContext: TMViewerContext2, queryContext: EntityQueryContext = viewerContext .getViewerScopedEntityCompanionForClass(this) .getQueryContextProvider() .getQueryContext() ): CreateMutator<TMFields, TMID, TMViewerContext, TMEntity, TMPrivacyPolicy, TMSelectedFields> { return viewerContext .getViewerScopedEntityCompanionForClass(this) .getMutatorFactory() .forCreate(queryContext); } /** * Vend mutator for updating an existing entity in given query context. * @param existingEntity - entity to update * @param queryContext - query context in which to perform the update * @returns mutator for updating existingEntity */ static updater< TMFields, TMID extends NonNullable<TMFields[TMSelectedFields]>, TMViewerContext extends ViewerContext, TMEntity extends Entity<TMFields, TMID, TMViewerContext, TMSelectedFields>, TMPrivacyPolicy extends EntityPrivacyPolicy< TMFields, TMID, TMViewerContext, TMEntity, TMSelectedFields >, TMSelectedFields extends keyof TMFields = keyof TMFields >( this: IEntityClass< TMFields, TMID, TMViewerContext, TMEntity, TMPrivacyPolicy, TMSelectedFields >, existingEntity: TMEntity, queryContext: EntityQueryContext = existingEntity .getViewerContext() .getViewerScopedEntityCompanionForClass(this) .getQueryContextProvider() .getQueryContext() ): UpdateMutator<TMFields, TMID, TMViewerContext, TMEntity, TMPrivacyPolicy, TMSelectedFields> { return existingEntity .getViewerContext() .getViewerScopedEntityCompanionForClass(this) .getMutatorFactory() .forUpdate(existingEntity, queryContext); } /** * Delete an existing entity in given query context. * @param existingEntity - entity to delete * @param queryContext - query context in which to perform the delete */ static deleteAsync< TMFields, TMID extends NonNullable<TMFields[TMSelectedFields]>, TMViewerContext extends ViewerContext, TMEntity extends Entity<TMFields, TMID, TMViewerContext, TMSelectedFields>, TMPrivacyPolicy extends EntityPrivacyPolicy< TMFields, TMID, TMViewerContext, TMEntity, TMSelectedFields >, TMSelectedFields extends keyof TMFields = keyof TMFields >( this: IEntityClass< TMFields, TMID, TMViewerContext, TMEntity, TMPrivacyPolicy, TMSelectedFields >, existingEntity: TMEntity, queryContext: EntityQueryContext = existingEntity .getViewerContext() .getViewerScopedEntityCompanionForClass(this) .getQueryContextProvider() .getQueryContext() ): Promise<Result<void>> { return existingEntity .getViewerContext() .getViewerScopedEntityCompanionForClass(this) .getMutatorFactory() .forDelete(existingEntity, queryContext) .deleteAsync(); } /** * Delete an existing entity in given query context, throwing if deletion is unsuccessful. * @param existingEntity - entity to delete * @param queryContext - query context in which to perform the delete */ static enforceDeleteAsync< TMFields, TMID extends NonNullable<TMFields[TMSelectedFields]>, TMViewerContext extends ViewerContext, TMEntity extends Entity<TMFields, TMID, TMViewerContext, TMSelectedFields>, TMPrivacyPolicy extends EntityPrivacyPolicy< TMFields, TMID, TMViewerContext, TMEntity, TMSelectedFields >, TMSelectedFields extends keyof TMFields = keyof TMFields >( this: IEntityClass< TMFields, TMID, TMViewerContext, TMEntity, TMPrivacyPolicy, TMSelectedFields >, existingEntity: TMEntity, queryContext: EntityQueryContext = existingEntity .getViewerContext() .getViewerScopedEntityCompanionForClass(this) .getQueryContextProvider() .getQueryContext() ): Promise<void> { return existingEntity .getViewerContext() .getViewerScopedEntityCompanionForClass(this) .getMutatorFactory() .forDelete(existingEntity, queryContext) .enforceDeleteAsync(); } /** * Check whether an entity loaded by a viewer can be updated by that same viewer. * * @remarks * * This may be useful in situations relying upon the thrown privacy policy thrown authorization error * is insufficient for the task at hand. When dealing with purely a sequence of mutations it is easy * to roll back all mutations given a single authorization error by wrapping them in a single transaction. * When certain portions of a mutation cannot be rolled back transactionally (third pary calls, * legacy code, etc), using this method can help decide whether the sequence of mutations will fail before * attempting them. Note that if any privacy policy rules use a piece of data being updated in the mutations * the result of this method and the update mutation itself may differ. * * @param existingEntity - entity loaded by viewer * @param queryContext - query context in which to perform the check */ static async canViewerUpdateAsync< TMFields, TMID extends NonNullable<TMFields[TMSelectedFields]>, TMViewerContext extends ViewerContext, TMEntity extends Entity<TMFields, TMID, TMViewerContext, TMSelectedFields>, TMPrivacyPolicy extends EntityPrivacyPolicy< TMFields, TMID, TMViewerContext, TMEntity, TMSelectedFields >, TMSelectedFields extends keyof TMFields = keyof TMFields >( this: IEntityClass< TMFields, TMID, TMViewerContext, TMEntity, TMPrivacyPolicy, TMSelectedFields >, existingEntity: TMEntity, queryContext: EntityQueryContext = existingEntity .getViewerContext() .getViewerScopedEntityCompanionForClass(this) .getQueryContextProvider() .getQueryContext() ): Promise<boolean> { const companion = existingEntity .getViewerContext() .getViewerScopedEntityCompanionForClass(this); const privacyPolicy = new (this.getCompanionDefinition().privacyPolicyClass)(); const evaluationResult = await asyncResult( privacyPolicy.authorizeUpdateAsync( existingEntity.getViewerContext(), queryContext, existingEntity, companion.getMetricsAdapter() ) ); return evaluationResult.ok; } /** * Check whether an entity loaded by a viewer can be deleted by that same viewer. * * @remarks * See remarks for canViewerUpdate. * * @param existingEntity - entity loaded by viewer * @param queryContext - query context in which to perform the check */ static async canViewerDeleteAsync< TMFields, TMID extends NonNullable<TMFields[TMSelectedFields]>, TMViewerContext extends ViewerContext, TMEntity extends Entity<TMFields, TMID, TMViewerContext, TMSelectedFields>, TMPrivacyPolicy extends EntityPrivacyPolicy< TMFields, TMID, TMViewerContext, TMEntity, TMSelectedFields >, TMSelectedFields extends keyof TMFields = keyof TMFields >( this: IEntityClass< TMFields, TMID, TMViewerContext, TMEntity, TMPrivacyPolicy, TMSelectedFields >, existingEntity: TMEntity, queryContext: EntityQueryContext = existingEntity .getViewerContext() .getViewerScopedEntityCompanionForClass(this) .getQueryContextProvider() .getQueryContext() ): Promise<boolean> { const companion = existingEntity .getViewerContext() .getViewerScopedEntityCompanionForClass(this); const privacyPolicy = new (this.getCompanionDefinition().privacyPolicyClass)(); const evaluationResult = await asyncResult( privacyPolicy.authorizeDeleteAsync( existingEntity.getViewerContext(), queryContext, existingEntity, companion.getMetricsAdapter() ) ); return evaluationResult.ok; } } /** * An interface to pass in constructor (class) of an Entity as a function argument. */ export interface IEntityClass< TFields, TID extends NonNullable<TFields[TSelectedFields]>, TViewerContext extends ViewerContext, TEntity extends ReadonlyEntity<TFields, TID, TViewerContext, TSelectedFields>, TPrivacyPolicy extends EntityPrivacyPolicy< TFields, TID, TViewerContext, TEntity, TSelectedFields >, TSelectedFields extends keyof TFields = keyof TFields > { new (viewerContext: TViewerContext, obj: Readonly<TFields>): TEntity; getCompanionDefinition(): EntityCompanionDefinition< TFields, TID, TViewerContext, TEntity, TPrivacyPolicy, TSelectedFields >; }
the_stack
import React, { useEffect } from 'react'; import { ipcRenderer } from 'electron'; import { Row, Col, Form, Input, InputNumber, Button, Select, Radio, Switch, message, Space, Divider } from 'antd'; import { useAppContext } from '@renderer/context/app'; import { usePlatform } from '@renderer/hook/usePlatform'; import { domainPathValidationRule } from '@renderer/utils/validationRule'; const inputItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 15 } }; const switchtemLayout = { labelCol: { span: 13 }, wrapperCol: { span: 11 } }; export const Setting = () => { const { state: { configuration, uploaderProfiles } } = useAppContext(); const platform = usePlatform(); const [form] = Form.useForm(); useEffect(() => { form.setFieldsValue(configuration); }, [configuration]); useEffect(() => { function handleWorkflowCopyReply(_, res) { if (res) { message.success('右键菜单添加成功'); } else { message.error('右键菜单添加失败'); } } function handleInstallCliReply(_, res) { if (res) { message.success('CLI 安装成功'); } else { message.error('CLI 安装失败'); } } function handleToggleWebServerReply(_, res: { toggle: boolean; success: boolean; message?: string }) { if (res.success) { message.success(res.toggle ? 'WebServer 开启成功' : 'WebServer 关闭成功'); } else { message.error(res.toggle ? `WebServer 开启失败${message || ''}` : 'WebServer 关闭失败'); } } function handleToggleUploadShortcutKeyReply(_, res: { toggle: boolean; success: boolean }) { if (res.success) { message.success(res.toggle ? '上传快捷键设置成功' : '上传快捷键关闭成功'); } else { message.error(res.toggle ? '上传快捷键设置失败' : '上传快捷键关闭失败'); } } ipcRenderer.on('copy-darwin-workflow-reply', handleWorkflowCopyReply); ipcRenderer.on('install-cli-reply', handleInstallCliReply); ipcRenderer.on('toggle-webserver-reply', handleToggleWebServerReply); ipcRenderer.on('toggle-upload-shortcut-key-reply', handleToggleUploadShortcutKeyReply); return () => { ipcRenderer.removeListener('copy-darwin-workflow-reply', handleWorkflowCopyReply); ipcRenderer.removeListener('install-cli-reply', handleInstallCliReply); ipcRenderer.removeListener('toggle-webserver-reply', handleToggleWebServerReply); ipcRenderer.removeListener('toggle-upload-shortcut-key-reply', handleToggleUploadShortcutKeyReply); }; }, []); const handleSubmit = () => { form.submit(); }; const handleReset = () => { form.resetFields(); }; const handleFinish = values => { console.log(values); ipcRenderer.send('setting-configuration-update', values); }; /** * Shortcut key recording only contains modifier key numbers and letters */ const handleShortcutKeyRecord = (event: React.KeyboardEvent<HTMLInputElement>) => { event.persist(); event.preventDefault(); const { shiftKey, ctrlKey, altKey, metaKey, keyCode } = event; const res = [] as string[]; if (metaKey) { res.push(process.platform === 'darwin' ? 'Command' : 'Super'); } if (shiftKey) { res.push('Shift'); } if (ctrlKey) { res.push('Control'); } if (altKey) { res.push('Alt'); } const modifierKeyCodeArr = [91, 93, 18, 17, 16]; if (!modifierKeyCodeArr.includes(keyCode)) { const keyName = String.fromCharCode(keyCode).toUpperCase(); if (/^[0-9A-Z]$/.test(keyName)) { res.push(keyName); } } if (res.length > 0) { form.setFieldsValue({ uploadShortcutKey: res.join('+') }); } }; const handleToggleWebServer = () => { const webServerPort = form.getFieldValue('webServerPort'); if (webServerPort) { ipcRenderer.send('toggle-webserver', webServerPort); } else { console.error('webServerPort is not exists'); } }; const handleToggleUploadShortcutKey = () => { const uploadShortcutKey = form.getFieldValue('uploadShortcutKey'); if (uploadShortcutKey) { ipcRenderer.send('toggle-upload-shortcut-key', uploadShortcutKey); } else { console.error('upload shortcut key is not exists'); } }; const handleAddWorkflow = () => { ipcRenderer.send('copy-darwin-workflow'); }; const handleInstallCli = () => { ipcRenderer.send('install-cli'); }; const handleOpenLog = () => { ipcRenderer.send('open-log'); }; return ( <div className="setting-wrapper"> <header> <span>设置</span> <Divider /> </header> <main> <Form {...switchtemLayout} layout="horizontal" labelAlign="left" form={form} initialValues={configuration} onFinish={handleFinish} > <Row> <Col xs={24}> <Form.Item name="urlType" label="链接格式" {...inputItemLayout}> <Radio.Group> <Radio.Button value="URL">URL</Radio.Button> <Radio.Button value="HTML">HTML</Radio.Button> <Radio.Button value="Markdown">Markdown</Radio.Button> </Radio.Group> </Form.Item> </Col> </Row> <Row> <Col xs={24}> <Form.Item name="defaultUploaderProfileId" label="默认上传器配置" {...inputItemLayout}> <Select> {uploaderProfiles.map(item => ( <Select.Option key={item.id} value={item.id}> {item.name} </Select.Option> ))} </Select> </Form.Item> </Col> </Row> <Row> <Col xs={24}> <Form.Item name="proxy" label="设置代理" {...inputItemLayout}> <Input /> </Form.Item> </Col> </Row> <Row> <Col xs={12}> <Form.Item name="autoCopy" label="自动复制" valuePropName="checked"> <Switch /> </Form.Item> </Col> <Col xs={12}> <Form.Item name="autoRecover" label="自动恢复粘贴板内容" valuePropName="checked"> <Switch /> </Form.Item> </Col> </Row> <Row> <Col xs={12}> <Form.Item name="rename" label="重命名文件" valuePropName="checked"> <Switch /> </Form.Item> </Col> <Col xs={12}> <Form.Item name="renameFormat" wrapperCol={{ span: 18 }} rules={[domainPathValidationRule]} extra="魔法变量: {fileName} {fileExtName} {uuid:n} {year} {month} {day} {hour} {minute} {second}" > <Input placeholder="请输入文件命名格式" /> </Form.Item> </Col> </Row> <Row> <Col xs={12}> <Form.Item name="showNotifaction" label="系统通知提示" valuePropName="checked"> <Switch /> </Form.Item> </Col> <Col xs={12}> <Form.Item name="sound" label="提示音" valuePropName="checked"> <Switch /> </Form.Item> </Col> </Row> <Row> <Col xs={12}> <Form.Item name="autoStart" label="开机自启" valuePropName="checked"> <Switch /> </Form.Item> </Col> </Row> <Row> <Col xs={12}> <Form.Item name="autoUpdate" label="自动检查更新" valuePropName="checked"> <Switch /> </Form.Item> </Col> <Col xs={12}> <Form.Item name="useBetaVersion" label="接收beta版本更新" valuePropName="checked"> <Switch /> </Form.Item> </Col> </Row> <Row> <Col xs={24}> <Form.Item label="WebServer" {...inputItemLayout} wrapperCol={{ span: 8 }}> <Row gutter={8}> <Col xs={18}> <Form.Item name="webServerPort"> <InputNumber style={{ width: '100%' }} min={3001} max={65535} disabled={configuration.openWebServer} /> </Form.Item> </Col> <Col xs={6}> <Form.Item name="openWebServer" valuePropName="checked" hidden> <Switch /> </Form.Item> <Button onClick={handleToggleWebServer}>{configuration.openWebServer ? '关闭' : '开启'}</Button> </Col> </Row> </Form.Item> </Col> </Row> <Row> <Col xs={24}> <Form.Item label="上传快捷键" {...inputItemLayout} wrapperCol={{ span: 8 }}> <Row gutter={8}> <Col xs={18}> <Form.Item name="uploadShortcutKey"> <Input onKeyDown={handleShortcutKeyRecord} disabled={configuration.openUploadShortcutKey} /> </Form.Item> </Col> <Col xs={6}> <Form.Item name="openUploadShortcutKey" valuePropName="checked" hidden> <Switch /> </Form.Item> <Button onClick={handleToggleUploadShortcutKey}> {configuration.openUploadShortcutKey ? '关闭' : '开启'} </Button> </Col> </Row> </Form.Item> </Col> </Row> </Form> </main> <footer> <Divider /> <Space> <Button type="primary" onClick={handleSubmit}> 保存并应用 </Button> <Button onClick={handleReset}>放弃</Button> {platform === 'darwin' && ( <> <Button onClick={handleInstallCli}>安装 CLI</Button> <Button onClick={handleAddWorkflow}>添加右键菜单</Button> </> )} <Button onClick={handleOpenLog}>打开日志</Button> </Space> </footer> </div> ); };
the_stack
import { toQueryString } from "../../utils"; import { SdkClient } from "../common/sdk-client"; import { KPICalculationModels } from "./kpi-models"; /** * The KPI Calculation Service computes Key Performance Indicators (KPIs) for an asset. It uses data sources such as sensors, control units and calendars. * Typical use cases for the KPI Calculation Service are: * Evaluation of characteristics, such as reliability, availability, and maintainability * Condition-based maintenance * Diagnostics applications and root-cause analysis * Risk assessment * * @see https://developer.mindsphere.io/apis/analytics-kpicalculation/api-kpicalculation-samples.html * * @export * @class KPICalculationClient * @extends {SdkClient} */ export class KPICalculationClient extends SdkClient { private _baseUrl: string = "/api/kpicalculation/v3"; /** * Launches kpi computation task with specific parameters. * * @param {KPICalculationModels.Timeseries} timeseries * @param {{ * from: Date; * to: Date; * variableName: string; * initialState: string; * }} params * @param params.from Start time of the interval * @param params.to End time of the interval * @param params.variableName: Target variable name. Only this variable will be taken from the given timeseries data. * @param params.initialState: initial KP state (Available values : "RSH", "SH", "POH", FOH") - * @see https://developer.mindsphere.io/apis/analytics-kpicalculation/api-kpicalculation-basics-kpi.html * * * No Data Hours (NoData) - Time, in hours, where required data from the unit is unavailable. This KPI is introduced to deal with possible data gaps. * * * Period Hours (PH) – Time, in hours, inside the period under consideration. * * * Available Hours (AH) – Time, in hours, during which the unit was capable of providing service, regardless of the capacity level that it provides.\ * * * Service Hours (SH) – Time, in hours, during which the unit was in-service. * * * Reserve Shutdown Hours (RSH) – Time, in hours, during which the unit was available, but not in service. * * * Unavailable Hours (UH) – Time, in hours, during which the unit was not capable of operation because of operational or equipment failures, external restrictions, testing, work being performed, or an adverse condition. The unavailable state persists until the unit is made available for operation. * * * Planned Outage Hours (POH) – Time, in hours, during which the unit (or a major item of equipment) was originally scheduled for a planned outage including the estimated duration plus the extension of planned work beyond this. The extension due to either a condition discovered during the planned outage or a startup failure would result as forced (unplanned) outage. * * * Forced Outage Hours (FOH) – Time, in hours, during which the unit was unavailable due to a component failure or another condition that requires the unit to be removed from service immediately or before the next planned outage. * * @returns {Promise<KPICalculationModels.KpiSet>} * * @memberOf KPICalculationClient */ async ComputeKPI( timeseries: KPICalculationModels.Timeseries, params: { from: Date; to: Date; variableName: string; initialState: string; } ): Promise<KPICalculationModels.KpiSet> { return (await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/computekpi?${toQueryString(params)}`, body: timeseries, })) as KPICalculationModels.KpiSet; } /** * * Launches kpi state computation task with specific parameters. * * @see https://developer.mindsphere.io/apis/analytics-kpicalculation/api-kpicalculation-basics-kpi-states.html * * @param {KPICalculationModels.RequestParametersBundle} requestParametersBundle * @param {{ * from: Date; * to: Date; * variableName: string; * initialState: string; * defaultState: string; * threshold: number; * shutdownCorrelationThreshold: number; * }} params * @param params.from Start time of the interval * @param params.to End time of the interval * @param params.variableName: Target variable name. Only this variable will be taken from the given timeseries data. * @param params.initialState: initial KPI state (Available values : "RSH", "SH", "POH", FOH") - * @param params.defaultState: default KPI state (Avaialble values: "RSH", "FOH") * @param params.threshold: Threshould to check values. Positive value * @param params.shutdownCorrelationThreshold: Shutdown correlation threshold in mills. The first event from the interval [timestamp - shutdownCorrelationThreshold, timestamp + shutdownCorrelationThreshold] will be analyzed for each timeseries item. * * * No Data Hours (NoData) - Time, in hours, where required data from the unit is unavailable. This KPI is introduced to deal with possible data gaps. * * * Period Hours (PH) – Time, in hours, inside the period under consideration. * * * Available Hours (AH) – Time, in hours, during which the unit was capable of providing service, regardless of the capacity level that it provides.\ * * * Service Hours (SH) – Time, in hours, during which the unit was in-service. * * * Reserve Shutdown Hours (RSH) – Time, in hours, during which the unit was available, but not in service. * * * Unavailable Hours (UH) – Time, in hours, during which the unit was not capable of operation because of operational or equipment failures, external restrictions, testing, work being performed, or an adverse condition. The unavailable state persists until the unit is made available for operation. * * * Planned Outage Hours (POH) – Time, in hours, during which the unit (or a major item of equipment) was originally scheduled for a planned outage including the estimated duration plus the extension of planned work beyond this. The extension due to either a condition discovered during the planned outage or a startup failure would result as forced (unplanned) outage. * * * Forced Outage Hours (FOH) – Time, in hours, during which the unit was unavailable due to a component failure or another condition that requires the unit to be removed from service immediately or before the next planned outage. * * @returns {Promise<KPICalculationModels.KpiStateIndicationSet>} * @memberOf KPICalculationClient */ async CaclulateKpiStates( requestParametersBundle: KPICalculationModels.RequestParametersBundle, params: { from: Date; to: Date; variableName: string; initialState: string; defaultState: string; threshold: number; shutdownCorrelationThreshold: number; } ) { return (await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/calculatekpistates?${toQueryString(params)}`, body: requestParametersBundle, })) as KPICalculationModels.KpiStateIndicationSet; } /** * * Launches kpi state computation task with specific parameters. * * @see https://developer.mindsphere.io/apis/analytics-kpicalculation/api-kpicalculation-basics-kpi-states.html * * @param {KPICalculationModels.RequestParametersBundle} requestParametersBundle * @param {{ * from: Date; * to: Date; * assetId: string; * aspectName: string; * variableName: string; * initialState: string; * defaultState: string; * threshold: number; * shutdownCorrelationThreshold: number; * }} params * @param params.from Start time of the interval * @param params.to End time of the interval * @param params.assetId Unique identifier of the asset (entity) * @param params.aspectName Name of the aspect (property set) * @param params.variableName: Target variable name. Only this variable will be taken from the given timeseries data. * @param params.initialState: initial KPI state (Available values : "RSH", "SH", "POH", FOH") - * @param params.defaultState: default KPI state (Avaialble values: "RSH", "FOH") * @param params.threshold: Threshould to check values. Positive value * @param params.shutdownCorrelationThreshold: Shutdown correlation threshold in mills. The first event from the interval [timestamp - shutdownCorrelationThreshold, timestamp + shutdownCorrelationThreshold] will be analyzed for each timeseries item. * * * No Data Hours (NoData) - Time, in hours, where required data from the unit is unavailable. This KPI is introduced to deal with possible data gaps. * * * Period Hours (PH) – Time, in hours, inside the period under consideration. * * * Available Hours (AH) – Time, in hours, during which the unit was capable of providing service, regardless of the capacity level that it provides.\ * * * Service Hours (SH) – Time, in hours, during which the unit was in-service. * * * Reserve Shutdown Hours (RSH) – Time, in hours, during which the unit was available, but not in service. * * * Unavailable Hours (UH) – Time, in hours, during which the unit was not capable of operation because of operational or equipment failures, external restrictions, testing, work being performed, or an adverse condition. The unavailable state persists until the unit is made available for operation. * * * Planned Outage Hours (POH) – Time, in hours, during which the unit (or a major item of equipment) was originally scheduled for a planned outage including the estimated duration plus the extension of planned work beyond this. The extension due to either a condition discovered during the planned outage or a startup failure would result as forced (unplanned) outage. * * * Forced Outage Hours (FOH) – Time, in hours, during which the unit was unavailable due to a component failure or another condition that requires the unit to be removed from service immediately or before the next planned outage. * * @returns {Promise<KPICalculationModels.KpiStateIndicationSet>} * @memberOf KPICalculationClient */ async CalculateKpiStatesDirect( requestParametersBundle: KPICalculationModels.RequestParametersBundleDirect, params: { from: Date; to: Date; assetId: string; aspectName: string; variableName: string; initialState: string; defaultState: string; threshold: number; shutdownCorrelationThreshold: number; } ) { return (await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/calculatekpistatesDirect?${toQueryString(params)}`, body: requestParametersBundle, })) as KPICalculationModels.KpiStateIndicationSet; } }
the_stack
import algoliasearch from 'algoliasearch'; import htmlToText from 'html-to-text'; import chunk from 'lodash/chunk'; import keyBy from 'lodash/keyBy'; import { isAnyTest } from '../../lib/executionEnvironment'; import * as _ from 'underscore'; import { getAlgoliaIndexName, collectionIsAlgoliaIndexed, AlgoliaIndexCollectionName } from '../../lib/algoliaUtil'; import { Comments } from '../../lib/collections/comments'; import { Posts } from '../../lib/collections/posts'; import { postStatuses } from '../../lib/collections/posts/constants'; import RSSFeeds from '../../lib/collections/rssfeeds/collection'; import Sequences from '../../lib/collections/sequences/collection'; import { Tags } from '../../lib/collections/tags/collection'; import Users from '../../lib/collections/users/collection'; import { algoliaAppIdSetting } from '../../lib/publicSettings'; import { DatabaseServerSetting } from '../databaseSettings'; import { dataToMarkdown } from '../editor/make_editable_callbacks'; import filter from 'lodash/filter'; import { asyncFilter } from '../../lib/utils/asyncUtils'; import { truncatise } from '../../lib/truncatise'; export type AlgoliaIndexedDbObject = DbComment|DbPost|DbUser|DbSequence|DbTag; export interface AlgoliaIndexedCollection<T extends AlgoliaIndexedDbObject> extends CollectionBase<T, AlgoliaIndexCollectionName> { toAlgolia: (document: T) => Promise<Array<AlgoliaDocument>|null> } const COMMENT_MAX_SEARCH_CHARACTERS = 18000 const USER_BIO_MAX_SEARCH_CHARACTERS = COMMENT_MAX_SEARCH_CHARACTERS const TAG_MAX_SEARCH_CHARACTERS = COMMENT_MAX_SEARCH_CHARACTERS; Comments.toAlgolia = async (comment: DbComment): Promise<Array<AlgoliaComment>|null> => { if (comment.deleted) return null; const algoliaComment: AlgoliaComment = { objectID: comment._id, _id: comment._id, userId: comment.userId, baseScore: comment.baseScore, isDeleted: comment.deleted, retracted: comment.retracted, deleted: comment.deleted, spam: comment.spam, legacy: comment.legacy, userIP: comment.userIP, createdAt: comment.createdAt, postedAt: comment.postedAt, af: comment.af, body: "", }; const commentAuthor = await Users.findOne({_id: comment.userId}); if (commentAuthor && !commentAuthor.deleted) { algoliaComment.authorDisplayName = commentAuthor.displayName; algoliaComment.authorUserName = commentAuthor.username; algoliaComment.authorSlug = commentAuthor.slug; } const parentPost = await Posts.findOne({_id: comment.postId}); if (parentPost) { algoliaComment.postId = comment.postId; algoliaComment.postTitle = parentPost.title; algoliaComment.postSlug = parentPost.slug; } let body = "" if (comment.contents?.originalContents?.type) { const { data, type } = comment.contents.originalContents body = dataToMarkdown(data, type) } // Limit comment size to ensure we stay below Algolia search Limit // TODO: Actually limit by encoding size as opposed to characters algoliaComment.body = body.slice(0, COMMENT_MAX_SEARCH_CHARACTERS) return [algoliaComment] } Sequences.toAlgolia = async (sequence: DbSequence): Promise<Array<AlgoliaSequence>|null> => { if (sequence.isDeleted || sequence.draft || sequence.hidden) return null; const algoliaSequence: AlgoliaSequence = { objectID: sequence._id, _id: sequence._id, title: sequence.title, userId: sequence.userId, createdAt: sequence.createdAt, af: sequence.af, plaintextDescription: "", }; const sequenceAuthor = await Users.findOne({_id: sequence.userId}); if (sequenceAuthor) { algoliaSequence.authorDisplayName = sequenceAuthor.displayName; algoliaSequence.authorUserName = sequenceAuthor.username; algoliaSequence.authorSlug = sequenceAuthor.slug; } // Limit comment size to ensure we stay below Algolia search Limit // TODO: Actually limit by encoding size as opposed to characters const { html = "" } = sequence.contents || {}; const plaintextBody = htmlToText.fromString(html); algoliaSequence.plaintextDescription = plaintextBody.slice(0, 2000); return [algoliaSequence] } Users.toAlgolia = async (user: DbUser): Promise<Array<AlgoliaUser>|null> => { if (user.deleted) return null; if (user.deleteContent) return null; let howOthersCanHelpMe = "" if (user.howOthersCanHelpMe?.originalContents?.type) { const { data, type } = user.howOthersCanHelpMe.originalContents howOthersCanHelpMe = dataToMarkdown(data, type) } let howICanHelpOthers = "" if (user.howICanHelpOthers?.originalContents?.type) { const { data, type } = user.howICanHelpOthers.originalContents howICanHelpOthers = dataToMarkdown(data, type) } const bioOriginalContents = user.biography?.originalContents; const bio = bioOriginalContents ? dataToMarkdown(bioOriginalContents.data, bioOriginalContents.type) : ""; const htmlBio = user.biography?.html || ""; const algoliaUser: AlgoliaUser = { _id: user._id, objectID: user._id, username: user.username, displayName: user.displayName, createdAt: user.createdAt, isAdmin: user.isAdmin, bio: bio.slice(0, USER_BIO_MAX_SEARCH_CHARACTERS), htmlBio: truncatise(htmlBio, { TruncateBy: 'characters', TruncateLength: USER_BIO_MAX_SEARCH_CHARACTERS - 500 // some buffer for HTML tags }), howOthersCanHelpMe: howOthersCanHelpMe.slice(0, USER_BIO_MAX_SEARCH_CHARACTERS), howICanHelpOthers: howICanHelpOthers.slice(0, USER_BIO_MAX_SEARCH_CHARACTERS), karma: user.karma, slug: user.slug, jobTitle: user.jobTitle, organization: user.organization, careerStage: user.careerStage, website: user.website, groups: user.groups, af: user.groups && user.groups.includes('alignmentForum'), ...(user.mapLocation?.geometry?.location?.lat && {_geoloc: { lat: user.mapLocation.geometry.location.lat, lng: user.mapLocation.geometry.location.lng, }}), ...(user.mapLocation?.formatted_address && {mapLocationAddress: user.mapLocation.formatted_address}) } return [algoliaUser]; } // TODO: Refactor this to no longer by this insane parallel code path, and instead just make a graphQL query and use all the relevant data Posts.toAlgolia = async (post: DbPost): Promise<Array<AlgoliaPost>|null> => { if (post.status !== postStatuses.STATUS_APPROVED) return null; if (post.authorIsUnreviewed) return null; const tags = post.tagRelevance ? Object.entries(post.tagRelevance).filter(([tagId, relevance]:[string, number]) => relevance > 0).map(([tagId]) => tagId) : [] const algoliaMetaInfo: AlgoliaPost = { _id: post._id, userId: post.userId, url: post.url, title: post.title, slug: post.slug, baseScore: post.baseScore, status: post.status, legacy: post.legacy, commentCount: post.commentCount, userIP: post.userIP, createdAt: post.createdAt, postedAt: post.postedAt, isFuture: post.isFuture, viewCount: post.viewCount, lastCommentedAt: post.lastCommentedAt, draft: post.draft, af: post.af, tags, body: "", }; const postAuthor = await Users.findOne({_id: post.userId}); if (postAuthor && !postAuthor.deleted) { algoliaMetaInfo.authorSlug = postAuthor.slug; algoliaMetaInfo.authorDisplayName = postAuthor.displayName; algoliaMetaInfo.authorFullName = postAuthor.fullName; } const postFeed = await RSSFeeds.findOne({_id: post.feedId}); if (postFeed) { algoliaMetaInfo.feedName = postFeed.nickname; algoliaMetaInfo.feedLink = post.feedLink; } let postBatch: Array<AlgoliaPost> = []; let body = "" if (post.contents?.originalContents?.type) { const { data, type } = post.contents.originalContents body = dataToMarkdown(data, type) } if (body) { body.split("\n\n").forEach((paragraph, paragraphCounter) => { postBatch.push(_.clone({ ...algoliaMetaInfo, objectID: post._id + "_" + paragraphCounter, // Algolia limits text to 20 KB. They don't say what encoding they use though. // Some random tests seem to imply that they use UTF-8, which means between 1 and 4 bytes per character. // So limit to 18,000 characters under the assumption that we have ~1.1 bytes/character. body: paragraph.slice(0, 18000), })); }) } else { postBatch.push(_.clone({ ...algoliaMetaInfo, objectID: post._id + "_0", body: "" })); } return postBatch; } Tags.toAlgolia = async (tag: DbTag): Promise<Array<AlgoliaTag>|null> => { if (tag.deleted) return null; if (tag.adminOnly) return null; let description = "" if (tag.description?.originalContents?.type) { const { data, type } = tag.description.originalContents description = dataToMarkdown(data, type) } // Limit tag description size to ensure we stay below Algolia search Limit // TODO: Actually limit by encoding size as opposed to characters description = description.slice(0, TAG_MAX_SEARCH_CHARACTERS) return [{ _id: tag._id, objectID: tag._id, name: tag.name, slug: tag.slug, core: tag.core, defaultOrder: tag.defaultOrder, suggestedAsFilter: tag.suggestedAsFilter, postCount: tag.postCount, wikiOnly: tag.wikiOnly, description, }]; } // Do algoliaIndex.waitTask as an async function rather than a // callback-accepting function. async function algoliaWaitForTask(algoliaIndex: algoliasearch.Index, taskID: number) { return new Promise<void>((resolve,reject) => { algoliaIndex.waitTask(taskID, (err) => { if (err) reject(err); else resolve(); }); }); } // Do algoliaIndex.addObjects as an async function rather than a // callback-accepting function. Returns a content object with a taskID // and a list objectIDs. // // https://www.algolia.com/doc/api-reference/api-methods/add-objects/ async function algoliaAddObjects(algoliaIndex: algoliasearch.Index, objects: Array<AlgoliaDocument>) { return new Promise((resolve,reject) => { algoliaIndex.addObjects(objects, (err, content) => { if (err) reject(err); else resolve(content); }); }); } // Do algoliaIndex.deleteObjects as an async function rather than a // callback-accepting function. Returns a content object with a taskID // and a list objectIDs. // https://www.algolia.com/doc/api-reference/api-methods/delete-objects/ export async function algoliaDeleteIds(algoliaIndex: algoliasearch.Index, ids: Array<string>) { return new Promise((resolve,reject) => { algoliaIndex.deleteObjects(ids, (err, content) => { if (err) reject(err); else resolve(content); }); }); } // Do algoliaIndex.getObjects as an async function rather than a // callback-accepting function. Returns a content object with a results field. // https://www.algolia.com/doc/api-reference/api-methods/get-objects/ async function algoliaGetObjects(algoliaIndex: algoliasearch.Index, ids: Array<string>): Promise<{results: Array<AlgoliaDocument>}> { return new Promise((resolve: (result: {results: Array<AlgoliaDocument>})=>void, reject) => { algoliaIndex.getObjects(ids, (err,content) => { if (err) { reject(err); } else { // Downcast because Algolia doesn't guarantee an _id field, but our schema does resolve(content as {results: Array<AlgoliaDocument>}); } }); }); } export async function algoliaDoSearch(algoliaIndex: algoliasearch.Index, query: algoliasearch.QueryParameters) { return new Promise((resolve,reject) => { algoliaIndex.search(query, (err,content) => { if (err) reject(err); else resolve(content); }); }); } // Do a query, but get all of the results, instead of just the first page of // results. Since Algolia searches have a maximum page size of 1000, this // requires doing multiple queries with pagination. // // Because it does multiple queries for different pages, this may return // duplicate results or omit results, if the index is modified while it is // running. // // IMPORTANT CAVEAT: If this index uses 'distinct', only one entry from each // group will be returned. async function algoliaDoCompleteSearch(algoliaIndex: algoliasearch.Index, query: algoliasearch.QueryParameters) { let allResults: Array<any> = []; let pageSize = 1000; // Max permitted by API let firstPageResults: any = await algoliaDoSearch(algoliaIndex, { ...query, hitsPerPage: pageSize, }); for (let hit of firstPageResults.hits) { allResults.push(hit); } for (let i=1; i<firstPageResults.nbPages; i++) { let pageResults: any = await algoliaDoSearch(algoliaIndex, { ...query, hitsPerPage: pageSize, offset: pageSize*i, }); for (let hit of pageResults.hits) allResults.push(hit); } return allResults; } export async function algoliaSetIndexSettings(algoliaIndex: algoliasearch.Index, settings: algoliasearch.IndexSettings) { return new Promise((resolve,reject) => { algoliaIndex.setSettings(settings, { forwardToReplicas: true }, (err, content) => { if (err) reject(err); else resolve(content); } ); }); } export async function algoliaSetIndexSettingsAndWait(algoliaIndex: algoliasearch.Index, settings: algoliasearch.IndexSettings) { let result: any = await algoliaSetIndexSettings(algoliaIndex, settings); await algoliaWaitForTask(algoliaIndex, result.taskID); } export async function algoliaGetAllDocuments(algoliaIndex: algoliasearch.Index): Promise<Array<AlgoliaDocument>> { return new Promise((resolve,reject) => { let results: Array<AlgoliaDocument> = []; let browser = algoliaIndex.browseAll(); browser.on('result', (content) => { for (let result of content.hits) { // Downcast because Algolia doesn't guarantee an _id field, but our schema does results.push(result as AlgoliaDocument); } }); browser.on('end', () => { resolve(results); }); browser.on('error', (err) => { reject(err); }); }); } // Given a list of objects that should be in the Algolia index, check whether // they are, and whether all fields on them match. If there are any differences, // correct them. // // (We do this rather than add blindly, because addObjects called are expensive // -- both in the traditional performance sense, and also in the sense that // Algolia's usage-based billing is built around it.) // TODO: This used to return any errors encountered, but now throws them async function addOrUpdateIfNeeded(algoliaIndex: algoliasearch.Index, objects: Array<AlgoliaDocument>) { if (objects.length == 0) return; const ids = _.map(objects, o=>o._id); const algoliaObjects: Array<AlgoliaDocument|null> = (await algoliaGetObjects(algoliaIndex, ids)).results; // Workaround for getting filter to properly typecheck: https://github.com/microsoft/TypeScript/issues/16069#issuecomment-392022894 const isNotNull = <T extends {}>(x:undefined | null | T) : x is T => !!x const algoliaObjectsNonnull: Array<AlgoliaDocument> = filter(algoliaObjects, isNotNull); const algoliaObjectsById = keyBy(algoliaObjectsNonnull, o=>o._id); const objectsToSync = _.filter(objects, obj => !_.isEqual(obj, algoliaObjectsById[obj._id])); if (objectsToSync.length > 0) { const response: any = await algoliaAddObjects(algoliaIndex, objectsToSync); await algoliaWaitForTask(algoliaIndex, response.taskID); } } // Given an objectID from an Algolia record, figure out whether this record is // part of a group of records merged by `distinct`, and if so, return the set // of objectIDs of records in that group. Otherwise return the given ID. async function algoliaObjectIDtoIDgroup(algoliaIndex: algoliasearch.Index, id: string): Promise<Array<string>> { // Does the ID have an underscore in it? If so, it's (_id)_(group index) if (id.indexOf('_') >= 0) { const [mongoId, groupIndexStr] = id.split('_'); const groupIndex = parseInt(groupIndexStr); const largestIndex = await getHighestGroupIndexInGroup(algoliaIndex, mongoId, groupIndex); return _.map(_.range(largestIndex+1), index=>`${mongoId}_${index}`); } else { return [id]; } } // Find the largest ID in this group. Unfortunately the only way to do this is // to try retrieving different IDs, and see what does and doesn't come back. async function getHighestGroupIndexInGroup(algoliaIndex: algoliasearch.Index, mongoId: string, lowerBound: number): Promise<number> { let largestIndex = lowerBound; while (await algoliaIdExists(algoliaIndex, `${mongoId}_${largestIndex+1}`)) { largestIndex++; } return largestIndex; } // Given a set of objectIDs, some of which are of the form (mongoId)_(groupIndex) // and some of which aren't, some of which share mongoIds but not groupIndexes, // return all objectIDs in the algolia index which share a mongoId with one of // the provided objectIDs, but have a higher groupIndex than any in the input. async function algoliaObjectIDsToHigherIDSet(algoliaIndex: algoliasearch.Index, ids: Array<string>): Promise<Array<string>> { const highestGroupIndexes: Record<string,number> = {}; for (let id of ids) { if (id.indexOf('_') >= 0) { const [mongoId, groupIndexStr] = id.split('_'); const groupIndex = parseInt(groupIndexStr); if (!(mongoId in highestGroupIndexes) || (groupIndex > highestGroupIndexes[mongoId])) highestGroupIndexes[mongoId] = groupIndex; } } let result: Array<string> = []; for (let mongoId of Object.keys(highestGroupIndexes)) { const largestIndexInInput = highestGroupIndexes[mongoId]; const largestIndexInAlgolia = await getHighestGroupIndexInGroup(algoliaIndex, mongoId, largestIndexInInput); for (let i=largestIndexInInput+1; i<=largestIndexInAlgolia; i++) result.push(`${mongoId}_${i}`); } return result; } async function algoliaIdExists(algoliaIndex: algoliasearch.Index, id: string): Promise<boolean> { const response = await algoliaGetObjects(algoliaIndex, [id]); const nonnullResults = _.filter(response.results, r=>!!r); return nonnullResults.length>0; } // Given a list of mongo IDs that should *not* be in the Algolia index, check // whether any are, and (if any are), delete them. // // We first do a series of queries, one per mongo ID, to collect the indexed // pieces of the deleted documents (since they're split into multiple index // entries by paragraph). async function deleteIfPresent(algoliaIndex: algoliasearch.Index, ids: Array<string>) { let algoliaIdsToDelete: Array<any> = []; for (const mongoId of ids) { const results = await algoliaDoCompleteSearch(algoliaIndex, { query: mongoId, restrictSearchableAttributes: ["_id"], attributesToRetrieve: ['objectID','_id'], }); for (const hit of results) { const idGroup = await algoliaObjectIDtoIDgroup(algoliaIndex, hit.objectID) for (const id of idGroup) algoliaIdsToDelete.push(id); } } if (algoliaIdsToDelete.length > 0) { const response: any = await algoliaDeleteIds(algoliaIndex, algoliaIdsToDelete); await algoliaWaitForTask(algoliaIndex, response.taskID); } } const algoliaAdminKeySetting = new DatabaseServerSetting<string | null>('algolia.adminKey', null) export function getAlgoliaAdminClient() { const algoliaAppId = algoliaAppIdSetting.get(); const algoliaAdminKey = algoliaAdminKeySetting.get() if (!algoliaAppId || !algoliaAdminKey) { if (!isAnyTest) { //eslint-disable-next-line no-console console.info("No Algolia credentials found. To activate search please provide 'algolia.appId' and 'algolia.adminKey' in the settings") } return null; } let client = algoliasearch(algoliaAppId, algoliaAdminKey); return client; } export async function algoliaDocumentExport<T extends AlgoliaIndexedDbObject>({ documents, collection, updateFunction}: { documents: Array<AlgoliaIndexedDbObject>, collection: AlgoliaIndexedCollection<T>, updateFunction?: any, }) { if (!collectionIsAlgoliaIndexed(collection.collectionName)) { // If this is a collection that isn't Algolia-indexed, don't index it. (This // gets called from voting code, which tried to update Algolia indexes to // change baseScore. tagRels have voting, but aren't Algolia-indexed.) return; } // if (isDevelopment) { // Only run document export in production environment // return null // } let client = getAlgoliaAdminClient(); if (!client) { return; } let algoliaIndex = client.initIndex(getAlgoliaIndexName(collection.collectionName as AlgoliaIndexCollectionName)); let totalErrors: any[] = []; await algoliaIndexDocumentBatch({ documents, collection: collection as AlgoliaIndexedCollection<AlgoliaIndexedDbObject>, algoliaIndex, errors: totalErrors, updateFunction }); if (totalErrors.length > 0) { //eslint-disable-next-line no-console console.error("Encountered the following errors while exporting to Algolia: ", totalErrors) } } export async function algoliaExportById<T extends AlgoliaIndexedDbObject>(collection: AlgoliaIndexedCollection<T>, documentId: string) { const document = await collection.findOne({_id: documentId}); if (document) { await algoliaDocumentExport({ documents: [document], collection }); } } // Sometimes 100 posts generate more index requests than algolia will willingly // handle - split them up in that case // Export for testing export function subBatchArray<T>(arr: Array<T>, maxSize: number): Array<Array<T>> { const result: Array<Array<T>> = [] while (arr.length > 0) { result.push(arr.slice(0, maxSize)) arr = arr.slice(maxSize, arr.length) } return result } export async function algoliaIndexDocumentBatch<T extends AlgoliaIndexedDbObject>({ documents, collection, algoliaIndex, errors, updateFunction }: { documents: Array<T>, collection: AlgoliaIndexedCollection<T>, algoliaIndex: algoliasearch.Index, errors: Array<any>, updateFunction: any, }) { let importBatch: Array<AlgoliaDocument> = []; let itemsToDelete: Array<string> = []; for (let item of documents) { if (updateFunction) updateFunction(item) const canAccess = collection.checkAccess ? await collection.checkAccess(null, item, null) : true; let algoliaEntries: Array<AlgoliaDocument>|null = canAccess ? await collection.toAlgolia(item) : null; if (algoliaEntries && algoliaEntries.length>0) { importBatch.push.apply(importBatch, algoliaEntries); // Append all of algoliaEntries to importBatch } else { itemsToDelete.push(item._id); } } if (importBatch.length > 0) { const subBatches = subBatchArray(importBatch, 1000) for (const subBatch of subBatches) { const objectIdsAdded = _.map(subBatch, doc=>doc.objectID); const excessIdsToDelete = await algoliaObjectIDsToHigherIDSet(algoliaIndex, objectIdsAdded); let err try { if (excessIdsToDelete.length > 0) { const deleteResponse: any = await algoliaDeleteIds(algoliaIndex, excessIdsToDelete); await algoliaWaitForTask(algoliaIndex, deleteResponse.taskID); } err = await addOrUpdateIfNeeded(algoliaIndex, _.map(subBatch, _.clone)); } catch (uncaughtErr) { err = uncaughtErr } if (err) errors.push(err) } } if (itemsToDelete.length > 0) { const err: any = await deleteIfPresent(algoliaIndex, itemsToDelete); if (err) errors.push(err) } } export async function subsetOfIdsAlgoliaShouldntIndex<T extends AlgoliaIndexedDbObject>(collection: AlgoliaIndexedCollection<T>, ids: Array<string>) { // Filter out duplicates const sortedIds = _.clone(ids).sort(); const uniqueIds = _.uniq(sortedIds, true); const pages = chunk(uniqueIds, 1000); let itemsToIndexById: Record<string,boolean> = {}; for (let page of pages) { let items: Array<T> = await collection.find({ _id: {$in: page} }).fetch(); let itemsToIndex = await asyncFilter(items, async (item: T) => !!(await collection.toAlgolia(item))); for (let item of itemsToIndex) { itemsToIndexById[item._id] = true; } } return _.filter(ids, id => !(id in itemsToIndexById)); }
the_stack
import {Spec} from "vega"; import {ScaleRecord} from "../store/factory/Scale"; import {State} from "../store"; import duplicate from "../util/duplicate"; import {MarkRecord} from "../store/factory/Mark"; import {GroupRecord} from "../store/factory/marks/Group"; import {ScaleInfo, ApplicationRecord, SelectionRecord, PointSelectionRecord, MarkApplicationRecord, ScaleApplicationRecord, TransformApplicationRecord, IntervalSelectionRecord, InteractionInput, InteractionSignal} from "../store/factory/Interaction"; import {ColumnRecord, DatasetRecord} from "../store/factory/Dataset"; import {NOMINAL, ORDINAL, QUANTITATIVE, TEMPORAL} from "vega-lite/src/type"; import * as dsUtil from '../util/dataset-utils'; import {WidgetRecord, WidgetSelectionRecord} from "../store/factory/Widget"; import {Map} from 'immutable'; export function addDatasetsToScene(sceneSpec: Spec, groupName: string, interactionId: number): Spec { const sceneUpdated = duplicate(sceneSpec); const data = sceneUpdated.data || (sceneUpdated.data = []); sceneUpdated.data = [...data, {"name": `brush_store_${groupName}_${interactionId}`}, {"name": `grid_store_${groupName}_${interactionId}`}, {"name": `points_store_${groupName}_${interactionId}`}, ]; return sceneUpdated; } export function addInputsToScene(sceneSpec: Spec, groupName: string, interactionId: number, input: InteractionInput, scaleInfo: ScaleInfo, fieldsOfGroup: string[], exclusive?: boolean): Spec { const {xScaleName, yScaleName, xFieldName, yFieldName} = scaleInfo; const {ifXElse, ifYElse, ifXY} = conditionalHelpersForScales(scaleInfo); sceneSpec = applySignals(sceneSpec, groupName, [ { "name": "unit", "value": {}, "on": [ { "events": "mousemove", "update": "isTuple(group()) ? group() : unit" } ] }, { "name": `key_modifier_${interactionId}`, "value": input && input.keycode ? false : true, "on": [ { "events": [{"source": "window", "type": "keydown"}], "update": input && input.keycode ? `event.keyCode === ${input.keycode}` : (exclusive ? "false" : "true") }, { "events": [{"source": "window", "type": "keyup"}], "update": input && input.keycode ? "false" : "true" } ] }, { "name": `mouse_x_${interactionId}`, "on": [ { "events": "mousemove", "update": `key_modifier_${interactionId} ? x(unit) : mouse_x_${interactionId}` } ] }, { "name": `mouse_y_${interactionId}`, "on": [ { "events": "mousemove", "update": `key_modifier_${interactionId} ? y(unit) : mouse_y_${interactionId}` } ] }, ]); if (xScaleName && xFieldName) { sceneSpec = applySignals(sceneSpec, groupName, [ { "name": `mouse_${xFieldName}_${interactionId}`, "on": [ { "events": "mousemove", "update": `key_modifier_${interactionId} ? invert("${xScaleName}", mouse_x_${interactionId}) : mouse_${xFieldName}_${interactionId}` } ] } ]) } if (yScaleName && yFieldName) { sceneSpec = applySignals(sceneSpec, groupName, [ { "name": `mouse_${yFieldName}_${interactionId}`, "on": [ { "events": "mousemove", "update": `key_modifier_${interactionId} ? invert("${yScaleName}", mouse_x_${interactionId}) : mouse_${yFieldName}_${interactionId}` } ] } ]) } // Point sceneSpec = applySignals(sceneSpec, groupName, [ {"name": `points_${interactionId}`, "update": `vlSelectionResolve(\"points_store_${groupName}_${interactionId}\")`}, { "name": `lyra_is_point_projecting_${interactionId}`, "init": "false" }, { "name": `lyra_points_tuple_${interactionId}`, "update": `lyra_is_point_projecting_${interactionId} ? points_tuple_projected_${interactionId} : points_tuple_${interactionId}` }, { "name": `points_tuple_${interactionId}`, "on": [ { "events": [Object.assign( {"source": "scope", "type": input && input.mouse !== 'drag' ? input.mouse : "click"}, input && input.mouse && input.mouse === 'mouseover' && input.nearest ? {"markname": `voronoi_${interactionId}`} : {} )], "update": `datum && !datum.manipulator && item().mark.marktype !== 'group' ? (key_modifier_${interactionId} ? {unit: \"layer_0\", fields: points_tuple_fields_${interactionId}, values: [(item().isVoronoi ? datum.datum : datum)['_vgsid_']], datum: (item().isVoronoi ? datum.datum : datum)} : points_tuple_${interactionId} ) : null`, "force": true }, {"events": [{"source": "scope", "type": "dblclick"}], "update": "null"} ] }, { "name": `points_tuple_projected_${interactionId}`, "on": [ { "events": [Object.assign( {"source": "scope", "type": input && input.mouse !== 'drag' ? input.mouse : "click"}, input && input.mouse && input.mouse === 'mouseover' && input.nearest ? {"markname": `voronoi_${interactionId}`} : {} )], "update": `datum && !datum.manipulator && item().mark.marktype !== 'group' ? (key_modifier_${interactionId} ? {unit: \"layer_0\", fields: points_tuple_fields_${interactionId}, values: [(item().isVoronoi ? datum.datum : datum)['_vgsid_']], datum: (item().isVoronoi ? datum.datum : datum)} : points_tuple_projected_${interactionId} ) : null`, "force": true }, {"events": [{"source": "scope", "type": "dblclick"}], "update": "null"} ] }, { "name": `points_tuple_fields_${interactionId}`, "value": [{"type": "E", "field": '_vgsid_'}] }, { "name": `points_modify_${interactionId}`, "update": `modify(\"points_store_${groupName}_${interactionId}\", lyra_points_tuple_${interactionId}, true, null)` } ]); sceneSpec = applySignals(sceneSpec, groupName, fieldsOfGroup.map(field => { return { "name": `point_${field}_${interactionId}`, "on": [ { "events": {"signal": `lyra_points_tuple_${interactionId}`}, "update": `lyra_points_tuple_${interactionId} && lyra_points_tuple_${interactionId}.datum ? lyra_points_tuple_${interactionId}.datum["${field}"] : null`, } ] } })); // Interval sceneSpec = addBrushMark(sceneSpec, groupName, interactionId, scaleInfo); sceneSpec = applySignals(sceneSpec, groupName, [ { "name": `brush_x_start_${interactionId}`, "on": [ { "events": {"signal": `lyra_brush_x_${interactionId}`}, "update": `lyra_brush_x_${interactionId}[0]` } ] }, { "name": `brush_x_end_${interactionId}`, "on": [ { "events": {"signal": `lyra_brush_x_${interactionId}`}, "update": `lyra_brush_x_${interactionId}[1]` } ] }, { "name": `brush_y_start_${interactionId}`, "on": [ { "events": {"signal": `lyra_brush_y_${interactionId}`}, "update": `lyra_brush_y_${interactionId}[0]` } ] }, { "name": `brush_y_end_${interactionId}`, "on": [ { "events": {"signal": `lyra_brush_y_${interactionId}`}, "update": `lyra_brush_y_${interactionId}[1]` } ] }, { "name": ifXElse(`brush_${xFieldName}_${xScaleName}_start_${interactionId}`, `brush_x_field_undefined_start_${interactionId}`), "on": [ { "events": {"signal": ifXElse(`brush_${xFieldName}_${xScaleName}_${interactionId}`, `brush_x_field_undefined_${interactionId}`)}, "update": ifXElse(`brush_${xFieldName}_${xScaleName}_${interactionId} && brush_${xFieldName}_${xScaleName}_${interactionId}.length ? brush_${xFieldName}_${xScaleName}_${interactionId}[0] : null`, 'null') } ] }, { "name": ifXElse(`brush_${xFieldName}_${xScaleName}_end_${interactionId}`, `brush_x_field_undefined_end_${interactionId}`), "on": [ { "events": {"signal": ifXElse(`brush_${xFieldName}_${xScaleName}_${interactionId}`, `brush_x_field_undefined_${interactionId}`)}, "update": ifXElse(`brush_${xFieldName}_${xScaleName}_${interactionId} && brush_${xFieldName}_${xScaleName}_${interactionId}.length ? brush_${xFieldName}_${xScaleName}_${interactionId}[1] : null`, 'null') } ] }, { "name": ifYElse(`brush_${yFieldName}_${yScaleName}_start_${interactionId}`, `brush_y_field_undefined_start_${interactionId}`), "on": [ { "events": {"signal": ifYElse(`brush_${yFieldName}_${yScaleName}_${interactionId}`, `brush_y_field_undefined_${interactionId}`)}, "update": ifYElse(`brush_${yFieldName}_${yScaleName}_${interactionId} && brush_${yFieldName}_${yScaleName}_${interactionId}.length ? brush_${yFieldName}_${yScaleName}_${interactionId}[0] : null`, 'null') } ] }, { "name": ifYElse(`brush_${yFieldName}_${yScaleName}_end_${interactionId}`, `brush_y_field_undefined_end_${interactionId}`), "on": [ { "events": {"signal": ifYElse(`brush_${yFieldName}_${yScaleName}_${interactionId}`, `brush_y_field_undefined_${interactionId}`)}, "update": ifYElse(`brush_${yFieldName}_${yScaleName}_${interactionId} && brush_${yFieldName}_${yScaleName}_${interactionId}.length ? brush_${yFieldName}_${yScaleName}_${interactionId}[1] : null`, 'null') } ] }, { "name": `lyra_brush_is_x_encoding_${interactionId}`, "init": "false" }, { "name": `lyra_brush_is_y_encoding_${interactionId}`, "init": "false" }, { "name": `lyra_brush_x_${interactionId}`, "update": `lyra_brush_is_y_encoding_${interactionId} ? [width, 0] : brush_x_${interactionId}` }, { "name": `lyra_brush_y_${interactionId}`, "update": `lyra_brush_is_x_encoding_${interactionId} ? [0, height] : brush_y_${interactionId}` }, {"name": `brush_${interactionId}`, "update": `vlSelectionResolve(\"brush_store_${groupName}_${interactionId}\")`}, {"name": `grid_${interactionId}`, "update": `vlSelectionResolve(\"grid_store_${groupName}_${interactionId}\")`}, { "name": `brush_x_${interactionId}`, "value": [], "on": [ { "events": { "source": "scope", "type": "mousedown", "filter": [ `!event.item || event.item.mark.name !== \"lyra_brush_brush_${interactionId}\"` ] }, "update": `key_modifier_${interactionId} ? [x(unit), x(unit)] : brush_x_${interactionId}` }, { "events": { "source": "window", "type": "mousemove", "consume": true, "between": [ { "source": "scope", "type": "mousedown", "filter": [ `!event.item || event.item.mark.name !== \"lyra_brush_brush_${interactionId}\"` ] }, { "source": "window", "type": "mouseup" } ] }, "update": `key_modifier_${interactionId} ? [brush_x_${interactionId}[0], clamp(x(unit), 0, width)] : brush_x_${interactionId}` }, { "events": { "signal": `brush_scale_trigger_${interactionId}` }, "update": ifXElse(`isArray(brush_${xFieldName}_${xScaleName}_${interactionId}) && length(brush_${xFieldName}_${xScaleName}_${interactionId}) == 2 ? [scale(\"${xScaleName}\", brush_${xFieldName}_${xScaleName}_${interactionId}[0]), scale(\"${xScaleName}\", brush_${xFieldName}_${xScaleName}_${interactionId}[1])] : [0, 0]`, "[width, 0]") }, { "events": { "signal": `brush_translate_delta_${interactionId}` }, "update": `clampRange(panLinear(brush_translate_anchor_${interactionId}.extent_x, brush_translate_delta_${interactionId}.x / span(brush_translate_anchor_${interactionId}.extent_x)), 0, width)` }, { "events": { "signal": `brush_zoom_delta_${interactionId}` }, "update": `clampRange(zoomLinear(brush_x_${interactionId}, brush_zoom_anchor_${interactionId}.x, brush_zoom_delta_${interactionId}), 0, width)` }, { "events": [ { "source": "scope", "type": "dblclick" } ], "update": "[0, 0]" } ] }, { "name": ifXElse(`brush_${xFieldName}_${xScaleName}_${interactionId}`, `brush_x_field_undefined_${interactionId}`), "on": ifXElse([ { "events": { "signal": `lyra_brush_x_${interactionId}` }, "update": ifXElse(`lyra_brush_x_${interactionId}[0] === lyra_brush_x_${interactionId}[1] ? null : invert(\"${xScaleName}\", lyra_brush_x_${interactionId})`, '') } ], []) }, { "name": `brush_y_${interactionId}`, "value": [], "on": [ { "events": { "source": "scope", "type": "mousedown", "filter": [ `!event.item || event.item.mark.name !== \"lyra_brush_brush_${interactionId}\"` ] }, "update": `key_modifier_${interactionId} ? [y(unit), y(unit)] : brush_y_${interactionId}` }, { "events": { "source": "window", "type": "mousemove", "consume": true, "between": [ { "source": "scope", "type": "mousedown", "filter": [ `!event.item || event.item.mark.name !== \"lyra_brush_brush_${interactionId}\"` ] }, { "source": "window", "type": "mouseup" } ] }, "update": `key_modifier_${interactionId} ? [brush_y_${interactionId}[0], clamp(y(unit), 0, height)] : brush_y_${interactionId}` }, { "events": { "signal": `brush_scale_trigger_${interactionId}` }, "update": ifYElse(`isArray(brush_${yFieldName}_${yScaleName}_${interactionId}) && length(brush_${yFieldName}_${yScaleName}_${interactionId}) == 2 ? [scale(\"${yScaleName}\", brush_${yFieldName}_${yScaleName}_${interactionId}[0]), scale(\"${yScaleName}\", brush_${yFieldName}_${yScaleName}_${interactionId}[1])] : [0, 0]`, "[0, height]") }, { "events": { "signal": `brush_translate_delta_${interactionId}` }, "update": `clampRange(panLinear(brush_translate_anchor_${interactionId}.extent_y, brush_translate_delta_${interactionId}.y / span(brush_translate_anchor_${interactionId}.extent_y)), 0, height)` }, { "events": { "signal": `brush_zoom_delta_${interactionId}` }, "update": `clampRange(zoomLinear(brush_y_${interactionId}, brush_zoom_anchor_${interactionId}.y, brush_zoom_delta_${interactionId}), 0, height)` }, { "events": [ { "source": "scope", "type": "dblclick" } ], "update": "[0, 0]" } ] }, { "name": ifYElse(`brush_${yFieldName}_${yScaleName}_${interactionId}`, `brush_y_field_undefined_${interactionId}`), "on": ifYElse([ { "events": { "signal": `lyra_brush_y_${interactionId}` }, "update": ifYElse(`lyra_brush_y_${interactionId}[0] === lyra_brush_y_${interactionId}[1] ? null : invert(\"${yScaleName}\", lyra_brush_y_${interactionId})`, '') } ], []) }, { "name": `brush_scale_trigger_${interactionId}`, "value": {}, "on": [ { "events": [].concat(ifXElse([ { "scale": "x" } ], [])).concat(ifYElse([ { "scale": "y" } ], [])), "update": ifXElse(`(!isArray(brush_${xFieldName}_${xScaleName}_${interactionId}) || (+invert(\"${xScaleName}\", lyra_brush_x_${interactionId})[0] === +brush_${xFieldName}_${xScaleName}_${interactionId}[0] && +invert(\"${xScaleName}\", lyra_brush_x_${interactionId})[1] === +brush_${xFieldName}_${xScaleName}_${interactionId}[1]))`, '') + ifXY(" && ") + ifYElse(`(!isArray(brush_${yFieldName}_${yScaleName}_${interactionId}) || (+invert(\"${yScaleName}\", lyra_brush_y_${interactionId})[0] === +brush_${yFieldName}_${yScaleName}_${interactionId}[0] && +invert(\"${yScaleName}\", lyra_brush_y_${interactionId})[1] === +brush_${yFieldName}_${yScaleName}_${interactionId}[1]))`, '') + ` ? brush_scale_trigger_${interactionId} : {}` } ] }, { "name": `brush_tuple_${interactionId}`, "on": [ { "events": [ { "signal": ifXElse(`brush_${xFieldName}_${xScaleName}_${interactionId}`, "") + ifXY(" || ") + ifYElse(`brush_${yFieldName}_${yScaleName}_${interactionId}`, "") } ], "update": ifXElse(`brush_${xFieldName}_${xScaleName}_${interactionId}`, "") + ifXY(" && ") + ifYElse(`brush_${yFieldName}_${yScaleName}_${interactionId}`, "") + ` ? {unit: \"\", fields: brush_tuple_fields_${interactionId}, values: [` + ifXElse(`brush_${xFieldName}_${xScaleName}_${interactionId}`, "") + ifXY(",") + ifYElse(`brush_${yFieldName}_${yScaleName}_${interactionId}`, "") + "]} : null" } ] }, { "name": `brush_tuple_fields_${interactionId}`, "value": [].concat(ifXElse([ { "field": xFieldName, "channel": "x", "type": "R" } ], [])).concat(ifYElse([ { "field": yFieldName, "channel": "y", "type": "R" } ], [])) }, { "name": `brush_translate_anchor_${interactionId}`, "value": {}, "on": [ { "events": [ { "source": "scope", "type": "mousedown", "markname": `lyra_brush_brush_${interactionId}` } ], "update": `key_modifier_${interactionId} ? {x: x(unit), y: y(unit), extent_x: slice(lyra_brush_x_${interactionId}), extent_y: slice(lyra_brush_y_${interactionId})} : brush_translate_anchor_${interactionId}` } ] }, { "name": `brush_translate_delta_${interactionId}`, "value": {}, "on": [ { "events": [ { "source": "window", "type": "mousemove", "consume": true, "between": [ { "source": "scope", "type": "mousedown", "markname": `lyra_brush_brush_${interactionId}` }, { "source": "window", "type": "mouseup" } ] } ], "update": `key_modifier_${interactionId} ? {x: brush_translate_anchor_${interactionId}.x - x(unit), y: brush_translate_anchor_${interactionId}.y - y(unit)} : brush_translate_delta_${interactionId}` } ] }, { "name": `brush_zoom_anchor_${interactionId}`, "on": [ { "events": [ { "source": "scope", "type": "wheel", "consume": true, "markname": `lyra_brush_brush_${interactionId}` } ], "update": `key_modifier_${interactionId} ? {x: x(unit), y: y(unit)} : brush_zoom_anchor_${interactionId}` } ] }, { "name": `brush_zoom_delta_${interactionId}`, "on": [ { "events": [ { "source": "scope", "type": "wheel", "consume": true, "markname": `lyra_brush_brush_${interactionId}` } ], "force": true, "update": `key_modifier_${interactionId} ? pow(1.001, event.deltaY * pow(16, event.deltaMode)) : brush_zoom_delta_${interactionId}` } ] }, { "name": `brush_modify_${interactionId}`, "update": `modify(\"brush_store_${groupName}_${interactionId}\", brush_tuple_${interactionId}, true)` }, { "name": ifXElse(`lyra_grid_${xFieldName}_${xScaleName}_${interactionId}`, `lyra_grid_x_field_undefined_${interactionId}`), "update": ifXElse(`lyra_brush_is_y_encoding_${interactionId} ? grid_translate_anchor_${interactionId}.extent_x : grid_${xFieldName}_${xScaleName}_${interactionId}`, `grid_x_field_undefined_${interactionId}`), }, { "name": ifYElse(`lyra_grid_${yFieldName}_${yScaleName}_${interactionId}`, `lyra_grid_y_field_undefined_${interactionId}`), "update": ifYElse(`lyra_brush_is_x_encoding_${interactionId} ? grid_translate_anchor_${interactionId}.extent_y : grid_${yFieldName}_${yScaleName}_${interactionId}`, `grid_y_field_undefined_${interactionId}`), }, { "name": ifXElse(`grid_${xFieldName}_${xScaleName}_${interactionId}`, `grid_x_field_undefined_${interactionId}`), "on": ifXElse([ { "events": {"signal": `grid_translate_delta_${interactionId}`}, "update": `panLinear(grid_translate_anchor_${interactionId}.extent_x, -grid_translate_delta_${interactionId}.x / width)` }, { "events": {"signal": `grid_zoom_delta_${interactionId}`}, "update": `zoomLinear(domain(\"${xScaleName}\"), grid_zoom_anchor_${interactionId}.x, grid_zoom_delta_${interactionId})` }, {"events": [{"source": "scope", "type": "dblclick"}], "update": "null"} ], []) }, { "name": ifYElse(`grid_${yFieldName}_${yScaleName}_${interactionId}`, `grid_y_field_undefined_${interactionId}`), "on": ifYElse([ { "events": {"signal": `grid_translate_delta_${interactionId}`}, "update": `panLinear(grid_translate_anchor_${interactionId}.extent_y, grid_translate_delta_${interactionId}.y / height)` }, { "events": {"signal": `grid_zoom_delta_${interactionId}`}, "update": `zoomLinear(domain(\"${yScaleName}\"), grid_zoom_anchor_${interactionId}.y, grid_zoom_delta_${interactionId})` }, {"events": [{"source": "scope", "type": "dblclick"}], "update": "null"} ], []) }, { "name": `grid_tuple_${interactionId}`, "on": [ { "events": [{"signal": ifXElse(`lyra_grid_${xFieldName}_${xScaleName}_${interactionId}`, "") + ifXY(" || ") + ifYElse(`lyra_grid_${yFieldName}_${yScaleName}_${interactionId}`, "")}], "update": ifXElse(`lyra_grid_${xFieldName}_${xScaleName}_${interactionId}`, "") + ifXY(" && ") + ifYElse(`lyra_grid_${yFieldName}_${yScaleName}_${interactionId}`, "") + `? {unit: \"\", fields: brush_tuple_fields_${interactionId}, values: [` + ifXElse(`lyra_grid_${xFieldName}_${xScaleName}_${interactionId}`, "") + ifXY(",") + ifYElse(`lyra_grid_${yFieldName}_${yScaleName}_${interactionId}`, "") + "]} : null" } ] }, { "name": `grid_translate_anchor_${interactionId}`, "value": {}, "on": [ { "events": [{"source": "scope", "type": "mousedown"}], "update": `key_modifier_${interactionId} ? {x: x(unit), y: y(unit)` + ifXElse(`, extent_x: domain(\"${xScaleName}\")`, "") + ifYElse(`, extent_y: domain(\"${yScaleName}\")`, "") + `} : grid_translate_anchor_${interactionId}` }, ] }, { "name": `grid_translate_delta_${interactionId}`, "value": {}, "on": [ { "events": [ { "source": "window", "type": "mousemove", "consume": true, "between": [ {"source": "scope", "type": "mousedown"}, {"source": "window", "type": "mouseup"} ] } ], "update": `key_modifier_${interactionId} ? {x: grid_translate_anchor_${interactionId}.x - x(unit), y: grid_translate_anchor_${interactionId}.y - y(unit)} : grid_translate_delta_${interactionId}` }, ] }, { "name": `grid_zoom_anchor_${interactionId}`, "on": [ { "events": [{"source": "scope", "type": "wheel", "consume": true}], "update": `key_modifier_${interactionId} ? {` + ifXElse(`x: invert(\"${xScaleName}\", x(unit))`, "") + ifXY(", ") + ifYElse(`y: invert(\"${yScaleName}\", y(unit))`, "") + `} : grid_zoom_anchor_${interactionId}` } ] }, { "name": `grid_zoom_delta_${interactionId}`, "on": [ { "events": [{"source": "scope", "type": "wheel", "consume": true}], "force": true, "update": `key_modifier_${interactionId} ? pow(1.001, event.deltaY * pow(16, event.deltaMode)) : grid_zoom_delta_${interactionId}` } ] }, { "name": `grid_modify_${interactionId}`, "update": `modify(\"grid_store_${groupName}_${interactionId}\", grid_tuple_${interactionId}, true)` }, ]); return sceneSpec; } export function addSelectionToScene(sceneSpec: Spec, groupName: string, interactionId: number, input: InteractionInput, selection: SelectionRecord): Spec { switch (selection.type) { case 'point': selection = selection as PointSelectionRecord; const field = selection.field; sceneSpec = removeBrushMark(sceneSpec, groupName); sceneSpec = applySignals(sceneSpec, groupName, [ { "name": `lyra_is_point_projecting_${interactionId}`, "init": field && field !== "_vgsid_" ? "true" : "false" }, { "name": `points_tuple_projected_${interactionId}`, "on": [ { "events": [Object.assign( {"source": "scope", "type": input && input.mouse !== 'drag' ? input.mouse : "click"}, input && input.mouse && input.mouse === 'mouseover' && input.nearest ? {"markname": `voronoi_${interactionId}`} : {} )], "update": `datum && !datum.manipulator && item().mark.marktype !== 'group' ? (key_modifier_${interactionId} ? {unit: \"layer_0\", fields: points_tuple_fields_${interactionId}, values: [(item().isVoronoi ? datum.datum : datum)['${field ? field : '_vgsid_'}']], datum: (item().isVoronoi ? datum.datum : datum)} : points_tuple_projected_${interactionId} ) : null`, "force": true }, {"events": [{"source": "scope", "type": "dblclick"}], "update": "null"} ] }, { "name": `points_tuple_fields_${interactionId}`, "value": [ Object.assign( {"type": "E", "field": field ? field : '_vgsid_'}, selection.encoding ? {"channel": selection.encoding} : {} ) ] }, ]); switch (selection.ptype) { case 'single': break; case 'multi': sceneSpec = applySignals(sceneSpec, groupName, [ { "name": `points_toggle_${interactionId}`, "value": false, // TODO(jzong) i disagree with this default behavior in vega "on": [ { "events": [Object.assign( {"source": "scope", "type": input && input.mouse !== 'drag' ? input.mouse : "click"}, input && input.mouse && input.mouse === 'mouseover' && input.nearest ? {"markname": `voronoi_${interactionId}`} : {} )], "update": "event.shiftKey" // TODO(jzong) incorporate this into the event key customization logic }, {"events": [{"source": "scope", "type": "dblclick"}], "update": "false"} ] } ]); } return sceneSpec; case 'interval': selection = selection as IntervalSelectionRecord; switch (selection.encoding) { case 'x': return applySignals(sceneSpec, groupName, [ { "name": `lyra_brush_is_x_encoding_${interactionId}`, "init": "true" }, { "name": `lyra_brush_is_y_encoding_${interactionId}`, "init": "false" } ]); case 'y': return applySignals(sceneSpec, groupName, [ { "name": `lyra_brush_is_y_encoding_${interactionId}`, "init": "true" }, { "name": `lyra_brush_is_x_encoding_${interactionId}`, "init": "false" } ]); default: return sceneSpec; } } } export function addApplicationToScene(sceneSpec: Spec, groupName: string, interactionId: number, input: InteractionInput, application: ApplicationRecord): Spec { const isDemonstratingInterval = input.mouse === 'drag'; let targetGroupName, targetMarkName; switch (application.type) { case 'mark': application = application as MarkApplicationRecord; targetGroupName = application.targetGroupName; targetMarkName = application.targetMarkName; const unselectedValue = application.unselectedValue; sceneSpec = applyMarkProperties(sceneSpec, targetGroupName, targetMarkName, { "encode": { "update": { [application.propertyName]: [ { "test": isDemonstratingInterval ? `!(length(data(\"brush_store_${groupName}_${interactionId}\"))) || (vlSelectionTest(\"brush_store_${groupName}_${interactionId}\", datum))` : `!(length(data(\"points_store_${groupName}_${interactionId}\"))) || (vlSelectionTest(\"points_store_${groupName}_${interactionId}\", datum))`, }, {"value": unselectedValue} ], } } }); return sceneSpec; case 'scale': application = application as ScaleApplicationRecord; // targetGroupName = application.targetGroupName; // TODO: support target group for scale applications targetGroupName = groupName; const scaleInfo = application.scaleInfo; sceneSpec = removeBrushMark(sceneSpec, groupName); sceneSpec = clipGroup(sceneSpec, groupName); return applyScaleProperties(sceneSpec, targetGroupName, [ { "_axis": "x", "name": scaleInfo.xScaleName, "domainRaw": {"signal": `grid_${interactionId}["${scaleInfo.xFieldName}"]`}, "zero": false }, { "_axis": "y", "name": scaleInfo.yScaleName, "domainRaw": {"signal": `grid_${interactionId}["${scaleInfo.yFieldName}"]`}, "zero": false } ]); case 'transform': application = application as TransformApplicationRecord; const datasetName = application.datasetName; targetGroupName = application.targetGroupName; targetMarkName = application.targetMarkName; const newDatasetName = datasetName + "_filter_" + targetGroupName; sceneSpec = applyMarkProperties(sceneSpec, targetGroupName, targetMarkName, { "from": { "data": newDatasetName } }); const {source, transform} = collectTransforms(sceneSpec, datasetName, []); sceneSpec = applyDatasetProperties(sceneSpec, { "name": newDatasetName, "source": source, "transform": [{ "type": "filter", "expr": isDemonstratingInterval ? `!(length(data(\"brush_store_${groupName}_${interactionId}\"))) || (vlSelectionTest(\"brush_store_${groupName}_${interactionId}\", datum))` : `!(length(data(\"points_store_${groupName}_${interactionId}\"))) || (vlSelectionTest(\"points_store_${groupName}_${interactionId}\", datum))`, }, ...transform] }); return sceneSpec; } } export function pushSignalsInScene(sceneSpec: Spec, groupName: string, interactionSignals: InteractionSignal[]) { sceneSpec = duplicate(sceneSpec); interactionSignals.forEach(s => { if (s.push) { sceneSpec.signals = sceneSpec.signals || []; sceneSpec.signals = editSignals(sceneSpec.signals, [{"name": s.signal}]); sceneSpec.marks = sceneSpec.marks.map(markSpec => { if (markSpec.name && markSpec.name === groupName && markSpec.type === 'group') { markSpec.signals = markSpec.signals.map(gs => { if (gs.name === s.signal) { return {...gs, "push": "outer"}; } return gs; }); } return markSpec; }); } }) return sceneSpec; } export function addWidgetSelectionToScene(sceneSpec: Spec, widget: WidgetRecord, selection: WidgetSelectionRecord): Spec { sceneSpec = duplicate(sceneSpec); sceneSpec.signals = sceneSpec.signals || []; switch (selection.type) { case 'select': sceneSpec.signals = editSignals(sceneSpec.signals, [ { "name": `widget_${widget.id}`, "bind": { name: widget.field.name, input: 'select', ...widgetParams(widget.field, widget.dsId) } } ]); return sceneSpec; case 'radio': sceneSpec.signals = editSignals(sceneSpec.signals, [ { "name": `widget_${widget.id}`, "bind": { name: widget.field.name, input: 'radio', ...widgetParams(widget.field, widget.dsId) } } ]); return sceneSpec; case 'range': const params = widgetParams(widget.field, widget.dsId) sceneSpec.signals = editSignals(sceneSpec.signals, [ { "name": `widget_${widget.id}`, "bind": { name: widget.field.name, input: 'range', min: params.min, max: params.max, step: selection.step || params.step } } ]); return sceneSpec; default: return sceneSpec; } } export function addWidgetApplicationToScene(sceneSpec: Spec, groupName: string, widget: WidgetRecord, application: MarkApplicationRecord): Spec { if (!widget.selection) return sceneSpec; const targetMarkName = application.targetMarkName; const unselectedValue = application.unselectedValue; return applyMarkProperties(sceneSpec, groupName, targetMarkName, { "encode": { "update": { [application.propertyName]: [ { "test": `datum.${widget.field.name} ${widget.selection.comparator} widget_${widget.id}`, }, {"value": unselectedValue} ], } } }); } function applySignals(sceneSpec, groupName: string, signals: any[]): Spec { const sceneUpdated = duplicate(sceneSpec); sceneUpdated.marks = sceneUpdated.marks.map(markSpec => { if (markSpec.name && markSpec.name === groupName && markSpec.type === 'group') { markSpec.signals = editSignals(markSpec.signals, signals); } return markSpec; }); return sceneUpdated; } function applyMarkProperties(sceneSpec, groupName: string, markName: string, markProperties: any): Spec { sceneSpec = duplicate(sceneSpec); sceneSpec.marks = sceneSpec.marks.map(markSpec => { if (markSpec.name && markSpec.name === groupName && markSpec.type === 'group') { return mapNestedMarksOfGroup(markSpec, (mark) => { if (mark.name === markName) { for (let [key, value] of Object.entries(markProperties)) { if (key !== 'encode') { mark[key] = value; } } if (markProperties.encode && markProperties.encode.update) { for (let [key, value] of Object.entries(markProperties.encode.update)) { const oldValue = mark.encode.update[key]; if (oldValue) { if (Array.isArray(oldValue) && oldValue.length) { if (oldValue[0].test && !value[0].test.includes(oldValue[0].test)) { value[0].test = value[0].test + ' && ' + oldValue[0].test; } value[0] = {...oldValue[0], ...value[0]}; } else { value[0] = {...value[0], ...oldValue}; } } mark.encode.update[key] = value; } } } return mark; }); } return markSpec; }); return sceneSpec; } function removeBrushMark(sceneSpec, groupName: string): Spec { sceneSpec = duplicate(sceneSpec); sceneSpec.marks = sceneSpec.marks.map(markSpec => { if (markSpec.name && markSpec.name === groupName && markSpec.type === 'group') { markSpec.marks = markSpec.marks.filter(mark => !(mark.name && mark.name.startsWith('lyra_brush'))); } return markSpec; }); return sceneSpec; } function clipGroup(sceneSpec, groupName: string): Spec { sceneSpec = duplicate(sceneSpec); sceneSpec.marks = sceneSpec.marks.map(markSpec => { if (markSpec.name && markSpec.name === groupName && markSpec.type === 'group') { return mapNestedMarksOfGroup(markSpec, (mark) => { mark.clip = true; return mark; }); } return markSpec; }); return sceneSpec; } function applyScaleProperties(sceneSpec, groupName: string, scaleProperties: any): Spec { sceneSpec = duplicate(sceneSpec); sceneSpec.marks = sceneSpec.marks.map(markSpec => { if (markSpec.name && markSpec.name === groupName && markSpec.type === 'group') { markSpec.scales.forEach(scale => { scaleProperties.forEach(scaleProps => { if (scale.name === scaleProps.name) { for (let [key, value] of Object.entries(scaleProps)) { if (key === '_axis') continue; scale[key] = value; } } }); }); } return markSpec; }); return sceneSpec; } function collectTransforms(sceneSpec, datasetName: string, transforms: any[]): {source: string, transform: any[]} { const dataset = sceneSpec.data.filter(data => data.name === datasetName)[0]; const currentTransforms = transforms.concat(dataset.transform); const currentTransformsToString = currentTransforms.map(x => JSON.stringify(x)); const uniqueTransforms = currentTransforms.filter((transform, idx) => { return currentTransformsToString.indexOf(JSON.stringify(transform)) === idx; }); if (dataset.source) { return collectTransforms(sceneSpec, dataset.source, uniqueTransforms); } return {source: datasetName, transform: uniqueTransforms}; } function applyDatasetProperties(sceneSpec, datasetProperties): Spec { sceneSpec = duplicate(sceneSpec); const data = sceneSpec.data || (sceneSpec.data = []); const deduplicated = data.filter(d => d.name !== datasetProperties.name); sceneSpec.data = [...deduplicated, datasetProperties]; return sceneSpec; } function conditionalHelpersForScales(scaleInfo: ScaleInfo) { const {xScaleName, yScaleName, xFieldName, yFieldName} = scaleInfo; return { ifXElse: (e1, e2) => xScaleName && xFieldName ? e1 : e2, ifYElse: (e1, e2) => yScaleName && yFieldName ? e1 : e2, ifXY: (e1) => xScaleName && xFieldName && yScaleName && yFieldName ? e1 : '' } } function addBrushMark(sceneSpec, groupName: string, interactionId: number, scaleInfo: ScaleInfo): Spec { const {ifXElse, ifYElse, ifXY} = conditionalHelpersForScales(scaleInfo); sceneSpec = duplicate(sceneSpec); sceneSpec.marks = sceneSpec.marks.map(markSpec => { if (markSpec.name && markSpec.name === groupName && markSpec.type === 'group') { markSpec.marks = [ ...markSpec.marks, { "name": `lyra_brush_brush_bg_${interactionId}`, "type": "rect", "clip": true, "encode": { "enter": { "fill": { "value": "#333" }, "fillOpacity": { "value": 0.125 } }, "update": { "x": [ Object.assign({ "test": `data(\"brush_store_${groupName}_${interactionId}\").length && data(\"brush_store_${groupName}_${interactionId}\")[0].unit === \"\"`, }, ifXElse({"signal": `lyra_brush_x_${interactionId}[0]`}, {"value": "0"})), { "value": 0 } ], "y": [ Object.assign({ "test": `data(\"brush_store_${groupName}_${interactionId}\").length && data(\"brush_store_${groupName}_${interactionId}\")[0].unit === \"\"`, }, ifYElse({"signal": `lyra_brush_y_${interactionId}[0]`}, {"value": "0"})), { "value": 0 } ], "x2": [ Object.assign({ "test": `data(\"brush_store_${groupName}_${interactionId}\").length && data(\"brush_store_${groupName}_${interactionId}\")[0].unit === \"\"`, }, ifXElse({"signal": `lyra_brush_x_${interactionId}[1]`}, {"signal": "width"})), { "value": 0 } ], "y2": [ Object.assign({ "test": `data(\"brush_store_${groupName}_${interactionId}\").length && data(\"brush_store_${groupName}_${interactionId}\")[0].unit === \"\"`, }, ifYElse({"signal": `lyra_brush_y_${interactionId}[1]`}, {"signal": "height"})), { "value": 0 } ] } } }, { "name": `lyra_brush_brush_${interactionId}`, "type": "rect", "clip": true, "encode": { "enter": { "fill": { "value": "transparent" } }, "update": { "x": [ Object.assign({ "test": `data(\"brush_store_${groupName}_${interactionId}\").length && data(\"brush_store_${groupName}_${interactionId}\")[0].unit === \"\"`, }, ifXElse({"signal": `lyra_brush_x_${interactionId}[0]`}, {"value": "0"})), { "value": 0 } ], "y": [ Object.assign({ "test": `data(\"brush_store_${groupName}_${interactionId}\").length && data(\"brush_store_${groupName}_${interactionId}\")[0].unit === \"\"`, }, ifYElse({"signal": `lyra_brush_y_${interactionId}[0]`}, {"value": "0"})), { "value": 0 } ], "x2": [ Object.assign({ "test": `data(\"brush_store_${groupName}_${interactionId}\").length && data(\"brush_store_${groupName}_${interactionId}\")[0].unit === \"\"`, }, ifXElse({"signal": `lyra_brush_x_${interactionId}[1]`}, {"signal": "width"})), { "value": 0 } ], "y2": [ Object.assign({ "test": `data(\"brush_store_${groupName}_${interactionId}\").length && data(\"brush_store_${groupName}_${interactionId}\")[0].unit === \"\"`, }, ifYElse({"signal": `lyra_brush_y_${interactionId}[1]`}, {"signal": "height"})), { "value": 0 } ], "stroke": [ { "test": ifXElse(`lyra_brush_x_${interactionId}[0] !== lyra_brush_x_${interactionId}[1]`, "") + ifXY(" && ") + ifYElse(`lyra_brush_y_${interactionId}[0] !== lyra_brush_y_${interactionId}[1]`, ""), "value": "white" }, { "value": null } ] } } } ] } return markSpec; }); return sceneSpec; } export function addVoronoiMark(sceneSpec, groupName: string, encoding: 'x' | 'y', targetMarkName: string, interactionId: number, applicationId: string): Spec { sceneSpec = duplicate(sceneSpec); sceneSpec.marks = sceneSpec.marks.map(markSpec => { if (markSpec.name && markSpec.name === groupName && markSpec.type === 'group') { const targetMarkPresent = markSpec.marks.find(mark => mark.name === targetMarkName); if (targetMarkPresent) { markSpec.marks = markSpec.marks.filter(mark => mark.name !== `voronoi_${interactionId}`); markSpec.marks = [ ...markSpec.marks, { "name": `voronoi_${interactionId}`, "type": "path", "interactive": true, "from": {"data": targetMarkName}, "encode": { "update": { "fill": {"value": "transparent"}, "strokeWidth": {"value": 0.35}, "stroke": {"value": "transparent"}, // "stroke": {"value": "#333"}, // for debugging "isVoronoi": {"value": true} } }, "transform": [ { "type": "voronoi", "x": {"expr": encoding === 'y' ? "0" : "datum.datum.x || 0"}, "y": {"expr": encoding === 'x' ? "0" : "datum.datum.y || 0"}, "size": [{"signal": "width"}, {"signal": "height"}] } ] } ]; } } return markSpec; }); return sceneSpec; } function getScaleRecords(state: State, groupId: number): {scaleRecordX: ScaleRecord, scaleRecordY: ScaleRecord} { const ret = { scaleRecordX: null, scaleRecordY: null }; const group: GroupRecord = state.getIn(['vis', 'present', 'marks', String(groupId)]); const childMarkIds: number[] = group.get('marks') as any as number[];// (vega-typings thinks these are vega objects but they're ids) const childMarks: MarkRecord[] = childMarkIds.map((id) => state.getIn(['vis', 'present', 'marks', String(id)])); if (!childMarks.length) { return ret; } const mark = childMarks[0]; if (mark.encode && mark.encode.update) { if (mark.encode.update.x) { const {scale} = mark.encode.update.x as any; ret.scaleRecordX = state.getIn(['vis', 'present', 'scales', String(scale)]); } if (mark.encode.update.y) { const {scale} = mark.encode.update.y as any; ret.scaleRecordY = state.getIn(['vis', 'present', 'scales', String(scale)]); } } return ret; } export function getFieldsOfGroup(state: State, groupId: number): string[] { const group: GroupRecord = state.getIn(['vis', 'present', 'marks', String(groupId)]) const marksOfGroup = getNestedMarksOfGroup(state, group); let fieldsOfGroup = []; const markWithData = marksOfGroup.find(mark => mark.from && mark.from.data); // TODO(jzong): multiple datasets same group? if (markWithData) { const dsId = String(markWithData.from.data); const dataset: DatasetRecord = state.getIn(['vis', 'present', 'datasets', String(dsId)]); const schema = dataset.get('_schema'); const fields = schema.keySeq().toArray(); fieldsOfGroup = fields; } return fieldsOfGroup; } export function getScaleInfoForGroup(state: State, groupId: number): ScaleInfo { const {scaleRecordX, scaleRecordY} = getScaleRecords(state, groupId); return { xScaleName: scaleRecordX ? scaleRecordX.get('name') : null, xFieldName: scaleRecordX && scaleRecordX.get('_domain').length > 0 ? scaleRecordX.get('_domain')[0].field : null, yScaleName: scaleRecordY ? scaleRecordY.get('name') : null, yFieldName: scaleRecordY && scaleRecordY.get('_domain').length > 0 ? scaleRecordY.get('_domain')[0].field : null, }; } export function cleanSpecForPreview(sceneSpec, width: number, height: number, groupName: string, interactionId: number): Spec { const sceneUpdated = duplicate(sceneSpec); sceneUpdated.autosize = "none"; sceneUpdated.marks = sceneUpdated.marks.map(markSpec => { if (markSpec.name && markSpec.type === 'group') { // don't touch manipulators, which don't have names const oldWidth = markSpec.encode?.update?.width?.value || 640; const oldHeight = markSpec.encode?.update?.height?.value || 360; const wScale = width / oldWidth; // preview width / main view width const hScale = height / oldHeight; // preview height / main view height markSpec.axes = markSpec.axes.map((axis) => { return {...axis, title: '', labels: false, ticks: false, domain: false}; }); markSpec.legends = []; markSpec.encode.update.x = {"value": 0}; markSpec.encode.update.y = {"value": 0}; markSpec.encode.update.width = {"signal": "width"}; markSpec.encode.update.height = {"signal": "height"}; markSpec = mapNestedMarksOfGroup(markSpec, mark => { if (mark.type === 'symbol' && mark.encode?.update?.size) { if (Array.isArray(mark.encode.update.size) && mark.encode?.update?.size.length == 2) { mark.encode.update.size = mark.encode.update.size.map(def => { if (def.value) { return { ...def, value: def.value * (wScale + hScale) / 2 } } return def; }) } else if (mark.encode.update.size.value) { mark.encode.update.size.value *= (wScale + hScale) / 2; } } if (mark.type === 'text') { if (mark.encode?.update?.fontSize?.value) { mark.encode.update.fontSize.value /= 2; } if (mark.encode?.update?.dx?.value) { mark.encode.update.dx.value *= wScale; } if (mark.encode?.update?.dy?.value) { mark.encode.update.dy.value *= hScale; } if (mark.encode?.update?.x?.value) { mark.encode.update.x.value *= wScale; } if (mark.encode?.update?.y?.value) { mark.encode.update.y.value *= hScale; } } if (mark.type === 'line' && mark.encode?.update?.strokeWidth?.value) { mark.encode.update.strokeWidth.value /= 2; } return mark; }); if (markSpec.name !== groupName) { // hide groups non-relevant to preview (but can't delete them in the case of multiview filtering) markSpec.encode.update.x = {"value": -999}; markSpec.encode.update.y = {"value": -999}; } markSpec.scales = markSpec.scales.map(scale => { if (scale.range) { const range = scale.range; if (Array.isArray(range) && range.length == 2 && !range.some(isNaN)) { scale.range = range.map(n => n / 10); } if (range.step && range.step.signal) { markSpec.signals = markSpec.signals.map(signal => { if (signal.name === range.step.signal) { signal.value /= 2; } return signal; }); } } return scale; }) } return markSpec; }); return addBaseSignalsForPreview(sceneUpdated, groupName, interactionId); } function addBaseSignalsForPreview(sceneSpec, groupName, interactionId) { const sceneUpdated = duplicate(sceneSpec); const baseSignalsScoped = baseSignals.map(s => { if (s.name === 'width' || s.name === 'height') return s; return { ...s, name: `${s.name}_${interactionId}` } }); sceneUpdated.marks = sceneUpdated.marks.map(markSpec => { if (markSpec.name && markSpec.name === groupName && markSpec.type === 'group') { markSpec.signals = editSignals(markSpec.signals, baseSignalsScoped); } return markSpec; }); return sceneUpdated; } export function editSignals(specSignals, interactionSignals) { const removeOldValues = specSignals.filter(signal => { return interactionSignals.every(newSignal => newSignal.name !== signal.name); }); return removeOldValues.concat(interactionSignals); // return specSignals.map(signal => { // const match = interactionSignals.find(s => s.name === signal.name); // return match ? match : signal; // }).concat(interactionSignals.filter(signal => { // return !specSignals.find(s => s.name === signal.name); // })); } const baseSignals = [ { name: "width", init: "75" }, { name: "height", init: "75" }, { name: "mouse_x", init: "null" }, { name: "mouse_y", init: "null" }, { name: "brush_x", init: "[0, 0]" }, { name: "brush_y", init: "[0, 0]" }, { name: "brush_zoom_anchor", init: "null" }, { name: "brush_zoom_delta", init: "null" }, { name: "grid_zoom_anchor", init: "null" }, { name: "grid_zoom_delta", init: "null" }, { name: "points_tuple", init: "null" }, { "name": "grid_translate_anchor", "init": {}, }, { "name": "grid_translate_delta", "init": {} }, ]; export function widgetParams(fieldDef: ColumnRecord, id: number) { const type = fieldDef.mtype; const data = dsUtil.output(id); let fieldValues = data.map(e => e[fieldDef.name]); if (type === NOMINAL || type === ORDINAL) { fieldValues = [...new Set(fieldValues)]; if (fieldValues.length > 50) { // TODO What to do for very large number of options? fieldValues = fieldValues.slice(0, 50); } return {options: fieldValues}; } else if (type === QUANTITATIVE || type === TEMPORAL) { fieldValues = fieldValues.sort((a,b)=> a-b); const length = fieldValues.length; const isInteger = fieldValues.every(v => Number.isInteger(v)); return { max: fieldValues[length-1], min: fieldValues[0], step: isInteger ? 1 : 0.1 } } else { // TODO: other types? } } /** * Returns all non-group, non-lyra marks that are children of a group or its subgroups. * @param group */ export function getNestedMarksOfGroup(state: State, group: GroupRecord): MarkRecord[] { if (!group) return []; return group.marks.map(markId => { const mark = state.getIn(['vis', 'present', 'marks', String(markId)]); if (mark.type === 'group') { return getNestedMarksOfGroup(state, group); } return mark; }).filter((mark) => { return !mark.name.startsWith('lyra'); }); } /** * Applies fn to all non-group, non-lyra marks that are children of groupSpec or its subgroups. Returns copy of groupSpec with changes applied */ export function mapNestedMarksOfGroup(groupSpec, fn: (mark: any) => any) { groupSpec = duplicate(groupSpec); groupSpec.marks = groupSpec.marks.map(mark => { if (mark.name && mark.name.startsWith('lyra')) return mark; if (mark.type === 'group') { return mapNestedMarksOfGroup(mark, fn); } return fn(mark); }); return groupSpec; }
the_stack
import { assert } from 'chai' import { Utils, WalletFactory, XrplNetwork } from 'xpring-common-js' import IssuedCurrencyClient from '../../src/XRP/issued-currency-client' import { FakeXRPNetworkClient, FakeXRPNetworkClientResponses, } from './fakes/fake-xrp-network-client' import 'mocha' import TrustLine from '../../src/XRP/shared/trustline' import { XrpError, XrpErrorType } from '../../src/XRP' import { FakeWebSocketNetworkClient, FakeWebSocketNetworkClientResponses, } from './fakes/fake-web-socket-network-client' import { AccountLinesResponse, WebSocketResponse, GatewayBalancesResponse, RippledMethod, AccountLinesSuccessfulResponse, GatewayBalancesSuccessfulResponse, ResponseStatus, } from '../../src/XRP/shared/rippled-web-socket-schema' import GatewayBalances, { gatewayBalancesFromResponse, } from '../../src/XRP/shared/gateway-balances' import IssuedCurrency from '../../src/XRP/shared/issued-currency' const fakeSucceedingGrpcClient = new FakeXRPNetworkClient() const fakeSucceedingWebSocketClient = new FakeWebSocketNetworkClient() const testAddress = 'X76YZJgkFzdSLZQTa7UzVSs34tFgyV2P16S3bvC8AWpmwdH' const testClassicAddress = 'rNvEhC9xXxvwn8wt5sZ9ByXL22dHs4pAr1' const walletFactory = new WalletFactory(XrplNetwork.Test) describe('Issued Currency Client', function (): void { before(async function () { this.wallet = (await walletFactory.generateRandomWallet())!.wallet }) it('getTrustLines - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient. const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN getTrustLines is called const trustLines = await issuedCurrencyClient.getTrustLines(testAddress) const expectedTrustLines: Array<TrustLine> = [] const trustlinesResponse: AccountLinesResponse = await fakeSucceedingWebSocketClient.getAccountLines( testAddress, ) const trustlinesSuccessfulResponse = trustlinesResponse as AccountLinesSuccessfulResponse if (trustlinesSuccessfulResponse.result.lines === undefined) { throw XrpError.malformedResponse } for (const trustLineResponse of trustlinesSuccessfulResponse.result.lines) { const trustLine = new TrustLine(trustLineResponse) expectedTrustLines.push(trustLine) } // THEN the result is as expected assert.deepEqual(trustLines, expectedTrustLines) }) it('getTrustLines - invalid account', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN getTrustLines is called with an invalid address THEN an error is propagated. const address = 'malformedAddress' try { await issuedCurrencyClient.getTrustLines(address) } catch (error) { assert.typeOf(error, 'Error') assert.equal(error, XrpError.xAddressRequired) } }) it('getTrustLines - invalid peerAccount', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN getTrustLines is called with an invalid peerAccount address THEN an error is thrown. const peerAddress = 'malformedAddress' try { await issuedCurrencyClient.getTrustLines(testAddress, peerAddress) } catch (error) { assert.typeOf(error, 'Error') assert.equal(error, XrpError.xAddressRequired) } }) it('getTrustLines - account not found error response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with faked networking that will return an error response for getAccountLines const accountNotFoundResponse: AccountLinesResponse = { error: 'actNotFound', error_code: 19, error_message: 'Account not found.', id: 'account_lines_r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', request: { account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', command: RippledMethod.accountLines, id: 'account_lines_r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', ledger_index: 'validated', }, status: ResponseStatus.error, type: 'response', } const fakeErroringWebSocketClientResponses = new FakeWebSocketNetworkClientResponses( FakeWebSocketNetworkClientResponses.defaultSubscribeResponse(), accountNotFoundResponse, ) const fakeErroringWebSocketClient = new FakeWebSocketNetworkClient( fakeErroringWebSocketClientResponses, ) const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeErroringWebSocketClient, XrplNetwork.Test, ) // WHEN getTrustLines is called THEN an error is thrown. try { await issuedCurrencyClient.getTrustLines(testAddress) } catch (error) { assert.typeOf(error, 'Error') } }) it('getTrustLines - invalid params error response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with faked networking that will return an error response for getAccountLines const invalidParamsResponse: AccountLinesResponse = { error: 'invalidParams', error_code: 31, error_message: "Missing field 'account'.", id: 'account_lines_r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', request: { account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', command: RippledMethod.accountLines, id: 'account_lines_r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', ledger_index: 'validated', }, status: ResponseStatus.error, type: 'response', } const fakeErroringWebSocketClientResponses = new FakeWebSocketNetworkClientResponses( FakeWebSocketNetworkClientResponses.defaultSubscribeResponse(), invalidParamsResponse, ) const fakeErroringWebSocketClient = new FakeWebSocketNetworkClient( fakeErroringWebSocketClientResponses, ) const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeErroringWebSocketClient, XrplNetwork.Test, ) // WHEN getTrustLines is called THEN an error is thrown. try { await issuedCurrencyClient.getTrustLines(testAddress) } catch (error) { assert.typeOf(error, 'Error') } }) it('requireAuthorizedTrustlines - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN requireAuthorizedTrustlines is called const result = await issuedCurrencyClient.requireAuthorizedTrustlines( this.wallet, ) const transactionHash = result.hash // THEN a transaction hash exists and is the expected hash const expectedTransactionHash = Utils.toHex( FakeXRPNetworkClientResponses.defaultSubmitTransactionResponse().getHash_asU8(), ) assert.exists(transactionHash) assert.strictEqual(transactionHash, expectedTransactionHash) }) it('requireAuthorizedTrustlines - submission failure', function (): void { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeXRPNetworkClientResponses( FakeXRPNetworkClientResponses.defaultAccountInfoResponse(), FakeXRPNetworkClientResponses.defaultFeeResponse(), FakeXRPNetworkClientResponses.defaultError, ) const failingNetworkClient = new FakeXRPNetworkClient(failureResponses) const issuedCurrencyClient = new IssuedCurrencyClient( failingNetworkClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN requireAuthorizedTrustlines is attempted THEN an error is propagated. issuedCurrencyClient .requireAuthorizedTrustlines(this.wallet) .catch((error) => { assert.deepEqual(error, FakeXRPNetworkClientResponses.defaultError) }) }) it('allowUnauthorizedTrustlines - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN allowUnauthorizedTrustlines is called const result = await issuedCurrencyClient.allowUnauthorizedTrustlines( this.wallet, ) const transactionHash = result.hash // THEN a transaction hash exists and is the expected hash const expectedTransactionHash = Utils.toHex( FakeXRPNetworkClientResponses.defaultSubmitTransactionResponse().getHash_asU8(), ) assert.exists(transactionHash) assert.strictEqual(transactionHash, expectedTransactionHash) }) it('allowUnauthorizedTrustlines - submission failure', function (): void { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeXRPNetworkClientResponses( FakeXRPNetworkClientResponses.defaultAccountInfoResponse(), FakeXRPNetworkClientResponses.defaultFeeResponse(), FakeXRPNetworkClientResponses.defaultError, ) const failingNetworkClient = new FakeXRPNetworkClient(failureResponses) const issuedCurrencyClient = new IssuedCurrencyClient( failingNetworkClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN allowUnauthorizedTrustlines is attempted THEN an error is propagated. issuedCurrencyClient .requireAuthorizedTrustlines(this.wallet) .catch((error) => { assert.deepEqual(error, FakeXRPNetworkClientResponses.defaultError) }) }) it('enableRippling - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN enableRippling is called const result = await issuedCurrencyClient.enableRippling(this.wallet) const transactionHash = result.hash // THEN a transaction hash exists and is the expected hash const expectedTransactionHash = Utils.toHex( FakeXRPNetworkClientResponses.defaultSubmitTransactionResponse().getHash_asU8(), ) assert.exists(transactionHash) assert.strictEqual(transactionHash, expectedTransactionHash) }) it('enableRippling - submission failure', function (): void { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeXRPNetworkClientResponses( FakeXRPNetworkClientResponses.defaultAccountInfoResponse(), FakeXRPNetworkClientResponses.defaultFeeResponse(), FakeXRPNetworkClientResponses.defaultError, ) const failingNetworkClient = new FakeXRPNetworkClient(failureResponses) const issuedCurrencyClient = new IssuedCurrencyClient( failingNetworkClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN enableRippling is attempted THEN an error is propagated. issuedCurrencyClient.enableRippling(this.wallet).catch((error) => { assert.deepEqual(error, FakeXRPNetworkClientResponses.defaultError) }) }) it('disallowIncomingXrp - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN disallowIncomingXrp is called const result = await issuedCurrencyClient.disallowIncomingXrp(this.wallet) const transactionHash = result.hash // THEN a transaction hash exists and is the expected hash const expectedTransactionHash = Utils.toHex( FakeXRPNetworkClientResponses.defaultSubmitTransactionResponse().getHash_asU8(), ) assert.exists(transactionHash) assert.strictEqual(transactionHash, expectedTransactionHash) }) it('disallowIncomingXrp - submission failure', function (): void { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeXRPNetworkClientResponses( FakeXRPNetworkClientResponses.defaultAccountInfoResponse(), FakeXRPNetworkClientResponses.defaultFeeResponse(), FakeXRPNetworkClientResponses.defaultError, ) const failingNetworkClient = new FakeXRPNetworkClient(failureResponses) const issuedCurrencyClient = new IssuedCurrencyClient( failingNetworkClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN disallowIncomingXrp is attempted THEN an error is propagated. issuedCurrencyClient.disallowIncomingXrp(this.wallet).catch((error) => { assert.deepEqual(error, FakeXRPNetworkClientResponses.defaultError) }) }) it('allowIncomingXrp - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN allowIncomingXrp is called const result = await issuedCurrencyClient.allowIncomingXrp(this.wallet) const transactionHash = result.hash // THEN a transaction hash exists and is the expected hash const expectedTransactionHash = Utils.toHex( FakeXRPNetworkClientResponses.defaultSubmitTransactionResponse().getHash_asU8(), ) assert.exists(transactionHash) assert.strictEqual(transactionHash, expectedTransactionHash) }) it('allowIncomingXrp - submission failure', function (): void { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeXRPNetworkClientResponses( FakeXRPNetworkClientResponses.defaultAccountInfoResponse(), FakeXRPNetworkClientResponses.defaultFeeResponse(), FakeXRPNetworkClientResponses.defaultError, ) const failingNetworkClient = new FakeXRPNetworkClient(failureResponses) const issuedCurrencyClient = new IssuedCurrencyClient( failingNetworkClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN allowIncomingXrp is attempted THEN an error is propagated. issuedCurrencyClient.allowIncomingXrp(this.wallet).catch((error) => { assert.deepEqual(error, FakeXRPNetworkClientResponses.defaultError) }) }) it('getGatewayBalances - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with faked networking that will return successful responses. const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN getBalances is called const gatewayBalances = await issuedCurrencyClient.getGatewayBalances( testAddress, ) const expectedGatewayBalances: GatewayBalances = gatewayBalancesFromResponse( (await fakeSucceedingWebSocketClient.getGatewayBalances( testAddress, )) as GatewayBalancesSuccessfulResponse, ) // THEN the result is as expected assert.deepEqual(gatewayBalances, expectedGatewayBalances) }) it('getGatewayBalances - invalid account', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN getGatewayBalances is called with a classic address (no X-address) THEN an error is propagated. const classicAddress = 'rhhh49pFH96roGyuC4E5P4CHaNjS1k8gzM' try { await issuedCurrencyClient.getGatewayBalances(classicAddress) } catch (error) { assert.typeOf(error, 'Error') assert.equal(error, XrpError.xAddressRequired) } }) it('getGatewayBalances - invalid addressToExclude, single address', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN getGatewayBalances is called with a classic addressToExclude (no X-address) THEN an error is propagated. const classicAddress = 'rhhh49pFH96roGyuC4E5P4CHaNjS1k8gzM' try { await issuedCurrencyClient.getGatewayBalances(testAddress, [ classicAddress, ]) } catch (error) { assert.typeOf(error, 'Error') assert.equal(error, XrpError.xAddressRequired) } }) it('getGatewayBalances - invalid addressToExclude, multiple addresses', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN getGatewayBalances is called with classic addresses to exclude (no X-address) THEN an error is propagated. const classicAddress1 = 'rhhh49pFH96roGyuC4E5P4CHaNjS1k8gzM' const classicAddress2 = 'r4DymtkgUAh2wqRxVfdd3Xtswzim6eC6c5' try { await issuedCurrencyClient.getGatewayBalances(testAddress, [ classicAddress1, classicAddress2, ]) } catch (error) { assert.typeOf(error, 'Error') assert.equal(error, XrpError.xAddressRequired) } }) it('getGatewayBalances - account not found error response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with faked networking that will return an error response for getGatewayBalances const accountNotFoundResponse: GatewayBalancesResponse = { error: 'actNotFound', error_code: 19, error_message: 'Account not found.', id: 'gateway_balances_X76YZJgkFzdSLZQTa7UzVSs34tFgyV2P16S3bvC8AWpmwdH', request: { account: 'X76YZJgkFzdSLZQTa7UzVSs34tFgyV2P16S3bvC8AWpmwdH', command: RippledMethod.gatewayBalances, hotwallet: [ 'rKm4uWpg9tfwbVSeATv4KxDe6mpE9yPkgJ', 'ra7JkEzrgeKHdzKgo4EUUVBnxggY4z37kt', ], id: 'gateway_balances_X76YZJgkFzdSLZQTa7UzVSs34tFgyV2P16S3bvC8AWpmwdH', ledger_index: 'validated', strict: true, }, status: ResponseStatus.error, type: 'response', } const fakeErroringWebSocketClientResponses = new FakeWebSocketNetworkClientResponses( FakeWebSocketNetworkClientResponses.defaultSubscribeResponse(), FakeWebSocketNetworkClientResponses.defaultGetAccountLinesResponse(), accountNotFoundResponse, ) const fakeErroringWebSocketClient = new FakeWebSocketNetworkClient( fakeErroringWebSocketClientResponses, ) const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeErroringWebSocketClient, XrplNetwork.Test, ) // WHEN getGatewayBalances is called THEN an error is propagated. try { await issuedCurrencyClient.getGatewayBalances(testAddress) } catch (error) { assert.typeOf(error, 'Error') assert.equal(error, XrpError.accountNotFound) } }) it('requireDestinationTags - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN requireDestinationTags is called const result = await issuedCurrencyClient.requireDestinationTags( this.wallet, ) const transactionHash = result.hash // THEN a transaction hash exists and is the expected hash const expectedTransactionHash = Utils.toHex( FakeXRPNetworkClientResponses.defaultSubmitTransactionResponse().getHash_asU8(), ) assert.exists(transactionHash) assert.strictEqual(transactionHash, expectedTransactionHash) }) it('requireDestinationTags - submission failure', function (): void { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeXRPNetworkClientResponses( FakeXRPNetworkClientResponses.defaultAccountInfoResponse(), FakeXRPNetworkClientResponses.defaultFeeResponse(), FakeXRPNetworkClientResponses.defaultError, ) const failingNetworkClient = new FakeXRPNetworkClient(failureResponses) const issuedCurrencyClient = new IssuedCurrencyClient( failingNetworkClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN requireDestinationTags is attempted THEN an error is propagated. issuedCurrencyClient.requireDestinationTags(this.wallet).catch((error) => { assert.deepEqual(error, FakeXRPNetworkClientResponses.defaultError) }) }) it('allowNoDestinationTag - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN allowNoDestinationTag is called const result = await issuedCurrencyClient.allowNoDestinationTag(this.wallet) const transactionHash = result.hash // THEN a transaction hash exists and is the expected hash const expectedTransactionHash = Utils.toHex( FakeXRPNetworkClientResponses.defaultSubmitTransactionResponse().getHash_asU8(), ) assert.exists(transactionHash) assert.strictEqual(transactionHash, expectedTransactionHash) }) it('allowNoDestinationTag - submission failure', function (): void { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeXRPNetworkClientResponses( FakeXRPNetworkClientResponses.defaultAccountInfoResponse(), FakeXRPNetworkClientResponses.defaultFeeResponse(), FakeXRPNetworkClientResponses.defaultError, ) const failingNetworkClient = new FakeXRPNetworkClient(failureResponses) const issuedCurrencyClient = new IssuedCurrencyClient( failingNetworkClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN allowNoDestinationTag is attempted THEN an error is propagated. issuedCurrencyClient.allowNoDestinationTag(this.wallet).catch((error) => { assert.deepEqual(error, FakeXRPNetworkClientResponses.defaultError) }) }) it('getTransferFee - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will successfully return information from a `getAccountInfo` call const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const expectedTransferFee = 1000000012 // WHEN getTransferFee is called const transferFee = await issuedCurrencyClient.getTransferFee( this.wallet.getAddress(), ) // THEN the expected transfer rate value is returned. assert.exists(transferFee) assert.equal(transferFee, expectedTransferFee) }) it('getTransferFee - bad address', function (): void { // GIVEN an IssuedCurrencyClient with mocked networking that will succeed const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const badAddress = 'badAddress' // WHEN getTransferFee is attempted THEN an error is propagated. issuedCurrencyClient.getTransferFee(badAddress).catch((error) => { assert.deepEqual(error, XrpError.xAddressRequired) }) }) it('getTransferFee - submission failure', function (): void { // GIVEN an IssuedCurrencyClient with mocked networking that will fail to make a `getAccountInfo` request const failureResponses = new FakeXRPNetworkClientResponses( FakeXRPNetworkClientResponses.defaultAccountInfoResponse(), FakeXRPNetworkClientResponses.defaultFeeResponse(), FakeXRPNetworkClientResponses.defaultError, ) const failingNetworkClient = new FakeXRPNetworkClient(failureResponses) const issuedCurrencyClient = new IssuedCurrencyClient( failingNetworkClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN getTransferFee is attempted THEN an error is propagated. issuedCurrencyClient .getTransferFee(this.wallet.getAddress()) .catch((error) => { assert.deepEqual(error, FakeXRPNetworkClientResponses.defaultError) }) }) it('setTransferFee - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const transferFee = 1000000012 // WHEN setTransferFee is called const result = await issuedCurrencyClient.setTransferFee( transferFee, this.wallet, ) const transactionHash = result.hash // THEN a transaction hash exists and is the expected hash const expectedTransactionHash = Utils.toHex( FakeXRPNetworkClientResponses.defaultSubmitTransactionResponse().getHash_asU8(), ) assert.exists(transactionHash) assert.strictEqual(transactionHash, expectedTransactionHash) }) it('setTransferFee - submission failure', function (): void { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeXRPNetworkClientResponses( FakeXRPNetworkClientResponses.defaultAccountInfoResponse(), FakeXRPNetworkClientResponses.defaultFeeResponse(), FakeXRPNetworkClientResponses.defaultError, ) const failingNetworkClient = new FakeXRPNetworkClient(failureResponses) const issuedCurrencyClient = new IssuedCurrencyClient( failingNetworkClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const transferFee = 1000000012 // WHEN setTransferFee is attempted THEN an error is propagated. issuedCurrencyClient .setTransferFee(transferFee, this.wallet) .catch((error) => { assert.deepEqual(error, FakeXRPNetworkClientResponses.defaultError) }) }) it('enableGlobalFreeze - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN enableGlobalFreeze is called const result = await issuedCurrencyClient.enableGlobalFreeze(this.wallet) const transactionHash = result.hash // THEN a transaction hash exists and is the expected hash const expectedTransactionHash = Utils.toHex( FakeXRPNetworkClientResponses.defaultSubmitTransactionResponse().getHash_asU8(), ) assert.exists(transactionHash) assert.strictEqual(transactionHash, expectedTransactionHash) }) it('enableGlobalFreeze - submission failure', function (): void { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeXRPNetworkClientResponses( FakeXRPNetworkClientResponses.defaultAccountInfoResponse(), FakeXRPNetworkClientResponses.defaultFeeResponse(), FakeXRPNetworkClientResponses.defaultError, ) const failingNetworkClient = new FakeXRPNetworkClient(failureResponses) const issuedCurrencyClient = new IssuedCurrencyClient( failingNetworkClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN enableGlobalFreeze is attempted THEN an error is propagated. issuedCurrencyClient.enableGlobalFreeze(this.wallet).catch((error) => { assert.deepEqual(error, FakeXRPNetworkClientResponses.defaultError) }) }) it('disableGlobalFreeze - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN disableGlobalFreeze is called const result = await issuedCurrencyClient.disableGlobalFreeze(this.wallet) const transactionHash = result.hash // THEN a transaction hash exists and is the expected hash const expectedTransactionHash = Utils.toHex( FakeXRPNetworkClientResponses.defaultSubmitTransactionResponse().getHash_asU8(), ) assert.exists(transactionHash) assert.strictEqual(transactionHash, expectedTransactionHash) }) it('disableGlobalFreeze - submission failure', function (): void { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeXRPNetworkClientResponses( FakeXRPNetworkClientResponses.defaultAccountInfoResponse(), FakeXRPNetworkClientResponses.defaultFeeResponse(), FakeXRPNetworkClientResponses.defaultError, ) const failingNetworkClient = new FakeXRPNetworkClient(failureResponses) const issuedCurrencyClient = new IssuedCurrencyClient( failingNetworkClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN disableGlobalFreeze is attempted THEN an error is propagated. issuedCurrencyClient.disableGlobalFreeze(this.wallet).catch((error) => { assert.deepEqual(error, FakeXRPNetworkClientResponses.defaultError) }) }) it('enableNoFreeze - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN enableNoFreeze is called const result = await issuedCurrencyClient.enableNoFreeze(this.wallet) const transactionHash = result.hash // THEN a transaction hash exists and is the expected hash const expectedTransactionHash = Utils.toHex( FakeXRPNetworkClientResponses.defaultSubmitTransactionResponse().getHash_asU8(), ) assert.exists(transactionHash) assert.strictEqual(transactionHash, expectedTransactionHash) }) it('enableNoFreeze - submission failure', function (): void { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeXRPNetworkClientResponses( FakeXRPNetworkClientResponses.defaultAccountInfoResponse(), FakeXRPNetworkClientResponses.defaultFeeResponse(), FakeXRPNetworkClientResponses.defaultError, ) const failingNetworkClient = new FakeXRPNetworkClient(failureResponses) const issuedCurrencyClient = new IssuedCurrencyClient( failingNetworkClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN enableNoFreeze is attempted THEN an error is propagated. issuedCurrencyClient.enableNoFreeze(this.wallet).catch((error) => { assert.deepEqual(error, FakeXRPNetworkClientResponses.defaultError) }) }) it('issuedCurrencyPayment - success', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const issuedCurrency: IssuedCurrency = { currency: 'FOO', issuer: testAddress, value: '100', } // WHEN issuedCurrencyPayment is called const transactionResult = await issuedCurrencyClient.issuedCurrencyPayment( this.wallet, testAddress, issuedCurrency, 0.5, ) // THEN the result is a transaction result with the expected hash const expectedTransactionHash = Utils.toHex( FakeXRPNetworkClientResponses.defaultSubmitTransactionResponse().getHash_asU8(), ) assert.exists(transactionResult) assert.equal(transactionResult.hash, expectedTransactionHash) }) it('issuedCurrencyPayment - submission failure', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeXRPNetworkClientResponses( FakeXRPNetworkClientResponses.defaultAccountInfoResponse(), FakeXRPNetworkClientResponses.defaultFeeResponse(), FakeXRPNetworkClientResponses.defaultError, ) const failingNetworkClient = new FakeXRPNetworkClient(failureResponses) const issuedCurrencyClient = new IssuedCurrencyClient( failingNetworkClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const issuedCurrency: IssuedCurrency = { currency: 'FOO', issuer: testAddress, value: '100', } // WHEN issuedCurrencyPayment is called THEN an error is propagated. try { await issuedCurrencyClient.issuedCurrencyPayment( this.wallet, testAddress, issuedCurrency, 0.5, ) } catch (error) { assert.equal(error, FakeXRPNetworkClientResponses.defaultError) } }) it('issuedCurrencyPayment - classic destination address', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const issuedCurrency: IssuedCurrency = { currency: 'FOO', issuer: testAddress, value: '100', } // WHEN issuedCurrencyPayment is called with a classic address argument for destination THEN an error is thrown. try { await issuedCurrencyClient.issuedCurrencyPayment( this.wallet, testClassicAddress, issuedCurrency, 0.5, ) } catch (error) { assert.equal(error.errorType, XrpErrorType.XAddressRequired) } }) it('issuedCurrencyPayment - classic issuer address', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const issuedCurrency: IssuedCurrency = { currency: 'FOO', issuer: testClassicAddress, value: '100', } // WHEN issuedCurrencyPayment is called with a classic address argument for issuer THEN an error is thrown. try { await issuedCurrencyClient.issuedCurrencyPayment( this.wallet, testAddress, issuedCurrency, 0.5, ) } catch (error) { assert.equal(error.errorType, XrpErrorType.XAddressRequired) } }) it('sendIssuedCurrencyPayment - errors with matching sender and issuer', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const issuedCurrency: IssuedCurrency = { currency: 'FOO', issuer: this.wallet.getAddress(), value: '100', } // WHEN sendIssuedCurrencyPayment is called with matching sender and issuer addresses, THEN an error is thrown. try { await issuedCurrencyClient.sendIssuedCurrencyPayment( this.wallet, testAddress, issuedCurrency, 0.5, ) } catch (error) { assert.equal(error.errorType, XrpErrorType.InvalidInput) } }) it('sendIssuedCurrencyPayment - errors with matching destination and issuer', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const issuedCurrency: IssuedCurrency = { currency: 'FOO', issuer: testAddress, value: '100', } // WHEN sendIssuedCurrencyPayment is called with matching sender and issuer addresses, THEN an error is thrown. try { await issuedCurrencyClient.sendIssuedCurrencyPayment( this.wallet, testAddress, issuedCurrency, 0.5, ) } catch (error) { assert.equal(error.errorType, XrpErrorType.InvalidInput) } }) it('monitorAccountTransactions - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient. const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const callback = (_data: WebSocketResponse) => { return } // WHEN monitorAccountTransactions is called const monitorResponse = await issuedCurrencyClient.monitorAccountTransactions( testAddress, callback, ) // THEN the result is as expected assert.isTrue(monitorResponse) }) it('monitorAccountTransactions - submission failure', function (): void { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeWebSocketNetworkClientResponses( FakeWebSocketNetworkClientResponses.defaultError, ) const callback = (_data: WebSocketResponse) => { return } const failingWebSocketClient = new FakeWebSocketNetworkClient( failureResponses, ) const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, failingWebSocketClient, XrplNetwork.Test, ) // WHEN monitorAccountTransactions is attempted THEN an error is propagated. issuedCurrencyClient .monitorAccountTransactions(testAddress, callback) .catch((error) => { assert.deepEqual( error, FakeWebSocketNetworkClientResponses.defaultError, ) }) }) it('stopMonitoringAccountTransactions - successful response', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient. const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN stopMonitoringAccountTransactions is called const monitorResponse = await issuedCurrencyClient.stopMonitoringAccountTransactions( testAddress, ) // THEN the result is as expected assert.isTrue(monitorResponse) }) it('stopMonitoringAccountTransactions - submission failure', function (): void { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeWebSocketNetworkClientResponses( FakeWebSocketNetworkClientResponses.defaultError, ) const failingWebSocketClient = new FakeWebSocketNetworkClient( failureResponses, ) const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, failingWebSocketClient, XrplNetwork.Test, ) // WHEN stopMonitoringAccountTransactions is attempted THEN an error is propagated. issuedCurrencyClient .stopMonitoringAccountTransactions(testAddress) .catch((error) => { assert.deepEqual( error, FakeWebSocketNetworkClientResponses.defaultError, ) }) }) it('calculateSendMaxValue - negative transferFee throws', function (): void { const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const amount = '1000' const transferFee = -0.05 try { issuedCurrencyClient.calculateSendMaxValue(amount, transferFee) } catch (error) { assert.typeOf(error, 'Error') assert.equal(error.errorType, XrpErrorType.InvalidInput) } }) it('calculateSendMaxValue - zero transferFee equals amount', function (): void { const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const amount = '1000' const transferFee = 0 const calculatedSendMaxValue = issuedCurrencyClient.calculateSendMaxValue( amount, transferFee, ) const expectedSendMaxValue = amount assert.equal(calculatedSendMaxValue, expectedSendMaxValue) }) it('calculateSendMaxValue - simple value, no scientific notation', function (): void { const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const amount = '1000' const transferFee = 5 const calculatedSendMaxValue = issuedCurrencyClient.calculateSendMaxValue( amount, transferFee, ) const expectedSendMaxValue = '1050' assert.equal(calculatedSendMaxValue, expectedSendMaxValue) }) it('calculateSendMaxValue - large value, precision overflow', function (): void { const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const amount = '1234567890123456' const transferFee = 5.43 const calculatedSendMaxValue = issuedCurrencyClient.calculateSendMaxValue( amount, transferFee, ) // Without rounding, expected value is: 1.3016049265571596608e15, 20 digits of precision (calculated on Wolfram Alpha) const expectedSendMaxValue = '1.30160492655716e15' assert.equal(calculatedSendMaxValue, expectedSendMaxValue) }) it('calculateSendMaxValue - small value, precision overflow', function (): void { const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) const amount = '0.00001234567890123456' const transferFee = 3.1 const calculatedSendMaxValue = issuedCurrencyClient.calculateSendMaxValue( amount, transferFee, ) // Without rounding, expected value is: 1.272839494717283e-5, 16 digits of precision (calculated on Wolfram Alpha) const expectedSendMaxValue = '1.27283949471729e-5' assert.equal(calculatedSendMaxValue, expectedSendMaxValue) }) it('createOffer - success', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN createOffer is called const takerGetsIssuedCurrency: IssuedCurrency = { issuer: testClassicAddress, currency: 'FAK', value: '100', } const takerPaysXrp = '50' const offerSequenceNumber = 1 const expiration = 1946684800 const transactionResult = await issuedCurrencyClient.createOffer( this.wallet, takerGetsIssuedCurrency, takerPaysXrp, offerSequenceNumber, expiration, ) // THEN a transaction hash exists and is the expected hash const expectedTransactionHash = Utils.toHex( FakeXRPNetworkClientResponses.defaultSubmitTransactionResponse().getHash_asU8(), ) assert.exists(transactionResult.hash) assert.strictEqual(transactionResult.hash, expectedTransactionHash) }) it('createOffer - submission failure', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeXRPNetworkClientResponses( FakeXRPNetworkClientResponses.defaultAccountInfoResponse(), FakeXRPNetworkClientResponses.defaultFeeResponse(), FakeXRPNetworkClientResponses.defaultError, ) const failingNetworkClient = new FakeXRPNetworkClient(failureResponses) const issuedCurrencyClient = new IssuedCurrencyClient( failingNetworkClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN createOffer is called THEN an error is propagated. const takerGetsIssuedCurrency: IssuedCurrency = { issuer: testClassicAddress, currency: 'FAK', value: '100', } const takerPaysXrp = '50' const offerSequenceNumber = 1 const expiration = 1946684800 try { await issuedCurrencyClient.createOffer( this.wallet, takerGetsIssuedCurrency, takerPaysXrp, offerSequenceNumber, expiration, ) } catch (error) { assert.equal(error, FakeXRPNetworkClientResponses.defaultError) } }) it('cancelOffer - success', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient with mocked networking that will return a successful hash for submitTransaction const issuedCurrencyClient = new IssuedCurrencyClient( fakeSucceedingGrpcClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN cancelOffer is called const offerSequenceNumber = 1 const transactionResult = await issuedCurrencyClient.cancelOffer( this.wallet, offerSequenceNumber, ) // THEN a transaction hash exists and is the expected hash const expectedTransactionHash = Utils.toHex( FakeXRPNetworkClientResponses.defaultSubmitTransactionResponse().getHash_asU8(), ) assert.exists(transactionResult.hash) assert.strictEqual(transactionResult.hash, expectedTransactionHash) }) it('cancelOffer - submission failure', async function (): Promise<void> { // GIVEN an IssuedCurrencyClient which will fail to submit a transaction. const failureResponses = new FakeXRPNetworkClientResponses( FakeXRPNetworkClientResponses.defaultAccountInfoResponse(), FakeXRPNetworkClientResponses.defaultFeeResponse(), FakeXRPNetworkClientResponses.defaultError, ) const failingNetworkClient = new FakeXRPNetworkClient(failureResponses) const issuedCurrencyClient = new IssuedCurrencyClient( failingNetworkClient, fakeSucceedingWebSocketClient, XrplNetwork.Test, ) // WHEN cancelOffer is called THEN an error is propagated. const offerSequenceNumber = 1 try { await issuedCurrencyClient.cancelOffer(this.wallet, offerSequenceNumber) } catch (error) { assert.equal(error, FakeXRPNetworkClientResponses.defaultError) } }) })
the_stack
import {Request, Response, NextFunction} from 'express'; import express = require('express'); import getPort = require('get-port'); import BicycleClient, {NetworkLayer} from '../client'; import BicycleServer from '../server'; import MemoryStore from '../sessions/MemorySessionStore'; import {createErrorResult} from '../types/ErrorResult'; import {createNodeID} from '../types/NodeID'; let allowErrors = false; const serverErrors: Error[] = []; // sessions expire after just 1 second for testing const sessionStore = new MemoryStore(1000); const bicycle = new BicycleServer(__dirname + '/../test-schema', { sessionStore, disableDefaultLogging: true, onError({error}) { if (allowErrors) { serverErrors.push(error); } else { console.error(error.stack); throw error; } }, }); test('a successful query', () => { const app = express(); const todo = { id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', title: 'Hello World', completed: false, }; app.use( '/bicycle', bicycle.createMiddleware((req, res) => { return { db: { getTodos() { // ^[a-f0-9]{8}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{12}$ return [todo]; }, }, }; }), ); app.use((err: any, req: Request, res: Response, next: NextFunction) => { res.statusCode = 500; res.end(err.stack); }); return getPort() .then(port => ({server: app.listen(port), port})) .then(({server, port}) => { return new Promise((resolve, reject) => { const client = new BicycleClient({ networkLayer: new NetworkLayer( 'http://localhost:' + port + '/bicycle', ), }); client.subscribe( {todos: {id: true, title: true, completed: true}}, (result, loaded, errors, errorDetails) => { try { expect(typeof result).toBe('object'); expect(typeof loaded).toBe('boolean'); expect(Array.isArray(errors)).toBe(true); expect(Array.isArray(errorDetails)).toBe(true); if (errors.length) { throw new Error(errors[0]); } if (loaded) { expect(result).toEqual({todos: [todo]}); server.close(); resolve(); } } catch (ex) { server.close(); reject(ex); } }, ); }); }); }); test('a successful server query', () => { const todo = { id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', title: 'Hello World', completed: false, }; const context = { db: { getTodos() { // ^[a-f0-9]{8}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{12}$ return [todo]; }, }, }; return bicycle .runQuery({todos: {id: true, title: true, completed: true}}, context) .then(result => { expect(result).toEqual({todos: [todo]}); }); }); test('a successful server render', () => { const todoID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'; const todo = {id: todoID, title: 'Hello World', completed: false}; const context = { db: { getTodos() { // ^[a-f0-9]{8}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{12}$ return [todo]; }, getTodo() { return todo; }, }, }; const req: Request = {request: true} as any; const res: Response = {response: true} as any; const A1 = {a: 1}; const A2 = {a: 2}; const renderServerSide = bicycle.createServerRenderer<any, Object, Object>( () => context, (client, reqArg, resArg, a1, a2) => { expect(reqArg).toBe(req); expect(resArg).toBe(res); expect(a1).toBe(A1); expect(a2).toBe(A2); const resultA = client.queryCache({todos: {id: true}}); if (resultA.loaded) { return client.queryCache({ [`todoById(id:${JSON.stringify( (resultA.result as any).todos[0].id, )})`]: { id: true, title: true, completed: true, }, }); } return 'not loaded yet'; }, ); return renderServerSide(req, res, A1, A2).then( ({serverPreparation, result}) => { expect(typeof serverPreparation).toBe('object'); expect(typeof serverPreparation.s).toBe('string'); expect(serverPreparation.q).toEqual({ 'todoById(id:"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")': { completed: true, id: true, title: true, }, todos: {id: true}, }); expect(serverPreparation.c).toEqual({ Root: { root: { ['todoById(id:"' + todoID + '")']: createNodeID('Todo', todoID), todos: [createNodeID('Todo', todoID)], }, }, Todo: { [todoID]: todo, }, }); expect(result).toEqual({ result: { todoById: todo, }, loaded: true, errors: [], errorDetails: [], }); }, ); }); test('a successful mutation with a result', () => { // 1. run a query // 2. check the inital value // 3. run a mutations // 4. check that the query result updates // 5. check the mutation updated successfully const app = express(); const todo = { id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', title: 'Hello World', completed: false, }; const todos: any[] = []; app.use( '/bicycle', bicycle.createMiddleware((req, res) => { return { db: { getTodos() { // ^[a-f0-9]{8}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{12}$ return todos; }, addTodo({title, completed}: any) { expect(title).toBe(todo.title); expect(completed).toBe(todo.completed); todos.push(todo); return Promise.resolve(todo.id); }, }, }; }), ); app.use((err: any, req: Request, res: Response, next: NextFunction) => { res.statusCode = 500; res.end(err.stack); }); return getPort() .then(port => ({server: app.listen(port), port})) .then(({server, port}) => { let resolveMutation: any, rejectMutation: any; const muationPromise = new Promise((resolve, reject) => { resolveMutation = resolve; rejectMutation = reject; }); return new Promise((resolve, reject) => { const client = new BicycleClient({ networkLayer: new NetworkLayer( 'http://localhost:' + port + '/bicycle', ), }); client.subscribeToNetworkErrors(reject); client.subscribeToMutationErrors(reject); let firstRun = true; client.subscribe( {todos: {id: true, title: true, completed: true}}, (result, loaded, errors, errorDetails) => { try { expect(typeof result).toBe('object'); expect(typeof loaded).toBe('boolean'); expect(Array.isArray(errors)).toBe(true); expect(Array.isArray(errorDetails)).toBe(true); if (errors.length) { throw new Error(errors[0]); } if (loaded) { if (firstRun) { expect(result).toEqual({todos: []}); firstRun = false; client .update('Todo.addTodo', { title: todo.title, completed: todo.completed, }) .then(result => { expect(result).toEqual({id: todo.id}); }) .then( () => { resolveMutation(); }, err => { reject(err); rejectMutation(err); }, ); } else { expect(result).toEqual({todos: [todo]}); server.close(); resolve(); } } } catch (ex) { server.close(); reject(ex); } }, ); }).then(() => muationPromise); }); }); test('a failing query', () => { allowErrors = true; const app = express(); app.use( '/bicycle', bicycle.createMiddleware((req, res) => { return { db: { getTodos() { return Promise.reject(new Error('Whatever')); }, }, }; }), ); app.use((err: any, req: Request, res: Response, next: NextFunction) => { res.statusCode = 500; res.end(err.stack); }); return getPort() .then(port => ({server: app.listen(port), port})) .then(({server, port}) => { return new Promise((resolve, reject) => { const client = new BicycleClient({ networkLayer: new NetworkLayer( 'http://localhost:' + port + '/bicycle', ), }); client.subscribe( {todos: {id: true, title: true, completed: true}}, (result, loaded, errors, errorDetails) => { try { expect(typeof result).toBe('object'); expect(typeof loaded).toBe('boolean'); expect(Array.isArray(errors)).toBe(true); expect(Array.isArray(errorDetails)).toBe(true); if (loaded) { allowErrors = false; expect(serverErrors.length).toBe(1); expect(serverErrors[0].message).toBe( 'Whatever while getting Root(root).todos', ); expect(result).toEqual({ todos: createErrorResult( 'Whatever while getting Root(root).todos', {}, ), }); expect(errors).toEqual([ 'Whatever while getting Root(root).todos', ]); expect(errorDetails).toEqual([ createErrorResult( 'Whatever while getting Root(root).todos', {}, ), ]); server.close(); resolve(); } } catch (ex) { server.close(); reject(ex); } }, ); }); }); });
the_stack
export const formConfigurationsIncludes = { fieldsAccordionInclude: [ { key: "fields", type: "accordion", title: "fields", itemTitleKey: "key", fields: [{ key: "anyFieldInclude", type: "include", include: "anyFieldInclude" }] } ], anyFieldInclude: [ { key: "baseFieldInclude", type: "include", include: "baseFieldInclude" }, { key: "type", title: "type", type: "select", options: [ { value: "accordion" }, { value: "boolean" }, { value: "bundle-manager" }, { value: "bundle-image-thumbnail" }, { value: "chips" }, { value: "code-editor" }, { value: "data-nest" }, { value: "date" }, { value: "empty-line" }, { value: "extend" }, { value: "hidden" }, { value: "info" }, { value: "markdown" }, { value: "nest" }, { value: "number" }, { value: "readonly" }, { value: "section" }, { value: "select" }, { value: "string" } ], default: "string", required: true }, { key: "typeExtend", type: "extend", nest: false, groupdata: false, selectorKey: "type", fields: [], clearExcept: ["key"], types: [ { key: "accordion", fields: [{ key: "accordionInclude", type: "include", include: "accordionInclude" }] }, { key: "boolean", fields: [{ key: "booleanInclude", type: "include", include: "booleanInclude" }] }, { key: "bundle-manager", fields: [{ key: "bundleManagerInclude", type: "include", include: "bundleManagerInclude" }] }, { key: "bundle-image-thumbnail", fields: [{ key: "bundleImageThumbnailInclude", type: "include", include: "bundleImageThumbnailInclude" }] }, { key: "chips", fields: [{ key: "chipsInclude", type: "include", include: "chipsInclude" }] }, { key: "code-editor", fields: [{ key: "codeEditorInclude", type: "include", include: "codeEditorInclude" }] }, { key: "data-nest", fields: [{ key: "dataNestInclude", type: "include", include: "dataNestInclude" }] }, { key: "date", fields: [{ key: "dateInclude", type: "include", include: "dateInclude" }] }, { key: "empty-line", fields: [{ key: "emptyLineInclude", type: "include", include: "emptyLineInclude" }] }, { key: "extend", fields: [{ key: "extendInclude", type: "include", include: "extendInclude" }] }, { key: "hidden", fields: [{ key: "hiddenInclude", type: "include", include: "hiddenInclude" }] }, { key: "info", fields: [{ key: "infoInclude", type: "include", include: "infoInclude" }] }, { key: "markdown", fields: [{ key: "markdownInclude", type: "include", include: "markdownInclude" }] }, { key: "number", fields: [{ key: "numberInclude", type: "include", include: "numberInclude" }] }, { key: "nest", fields: [{ key: "nestInclude", type: "include", include: "nestInclude" }] }, { key: "readonly", fields: [{ key: "readonlyInclude", type: "include", include: "readonlyInclude" }] }, { key: "section", fields: [{ key: "sectionInclude", type: "include", include: "sectionInclude" }] }, { key: "select", fields: [{ key: "selectInclude", type: "include", include: "selectInclude" }] }, { key: "string", fields: [{ key: "textFieldInclude", type: "include", include: "textFieldInclude" }] } ] } ], baseFieldInclude: [{ key: "key", type: "string", title: "key", required: true }], accordionInclude: [ { key: "title", title: "title", type: "string", required: true }, { key: "itemTitleKey", title: "itemTitleKey", type: "chips" }, { key: "fieldsAccordionInclude", type: "include", include: "fieldsAccordionInclude" } ], booleanInclude: [ { key: "title", title: "title", type: "string", required: true }, { key: "default", title: "default", type: "boolean", default: false }, { key: "tip", title: "tip", type: "string" } ], bundleManagerInclude: [ { key: "title", title: "title", type: "string", required: true }, { key: "path", title: "path", type: "string" }, { key: "extensions", title: "extensions", type: "chips" }, { key: "fieldsAccordionInclude", type: "include", include: "fieldsAccordionInclude" } ], bundleImageThumbnailInclude: [{ key: "src", title: "src", type: "string", required: false }], chipsInclude: [ { key: "title", title: "title", type: "string", required: true }, { key: "default", title: "default", type: "chips" } ], codeEditorInclude: [ { key: "title", title: "title", type: "string", required: true }, { key: "language", title: "language", type: "string", required: false }, { key: "default", title: "default", type: "string", multiLine: true, default: false }, { key: "tip", title: "tip", type: "string" }, { key: "lightTheme", title: "lightTheme", type: "boolean", default: true } ], dataNestInclude: [{ key: "fieldsAccordionInclude", type: "include", include: "fieldsAccordionInclude" }], dateInclude: [ { key: "title", title: "title", type: "string", required: true }, { key: "required", title: "required", type: "boolean", default: true }, { key: "default", title: "default", type: "date" }, { key: "tip", title: "tip", type: "string" } ], emptyLineInclude: [{ key: "amount", title: "amount", type: "number" }], extendInclude: [ { key: "fieldsAccordionInclude", type: "include", include: "fieldsAccordionInclude" }, // initialState?: { [key: string]: any }; { key: "selectorKey", title: "selectorKey", type: "string", required: true }, { key: "types", type: "accordion", title: "types", itemTitleKey: ["key"], fields: [ { key: "key", title: "key", type: "string", required: true }, { key: "fieldsAccordionInclude", type: "include", include: "fieldsAccordionInclude" } ] }, { key: "clearOnChange", title: "clearOnChange", type: "chips" }, { key: "clearExcept", title: "clearExcept", type: "chips" } ], infoInclude: [ { key: "content", title: "content", type: "markdown", multiLine: true }, { key: "size", title: "size", type: "select", default: "default", options: [{ value: "small" }, { value: "default" }, { value: "large" }] }, { key: "lineHeight", title: "lineHeight", type: "number", default: 1.2 }, { key: "theme", title: "theme", type: "select", default: "default", options: [ { value: "default" }, { value: "bare" }, { value: "warn" }, { value: "warn-bare" }, { value: "black" }, { value: "black-bare" }, { value: "gray" }, { value: "gray-bare" } ] } ], hiddenInclude: [ { key: "value", title: "value", type: "string", required: false }, { key: "default", title: "default", type: "string", required: false } ], markdownInclude: [ { key: "title", title: "title", type: "string", required: true }, { key: "multiLine", title: "multiLine", type: "boolean", default: true }, { key: "default", title: "default", type: "markdown", multiLine: true, default: false }, { key: "tip", title: "tip", type: "string" } ], nestInclude: [ { key: "title", title: "title", type: "string", required: true }, { key: "groupdata", title: "groupdata", type: "boolean", default: false }, { key: "fieldsAccordionInclude", type: "include", include: "fieldsAccordionInclude" } ], numberInclude: [ { key: "title", title: "title", type: "string", required: true }, // { key: "required", title: "required", type: "boolean", default: false }, { key: "default", title: "default", type: "number" }, { key: "tip", title: "tip", type: "string" } ], readonlyInclude: [ { key: "title", title: "title", type: "string", required: true }, { key: "required", title: "required", type: "boolean", default: false }, { key: "value", title: "default", type: "string" }, { key: "default", title: "default", type: "string" }, { key: "multiLine", title: "multiLine", type: "boolean", default: false }, { key: "defaultExtend", type: "extend", selectorKey: "multiLine", clearOnChange: [], types: [ { key: "true", fields: [{ key: "default", title: "default", type: "string", multiLine: true }] }, { key: "false", fields: [{ key: "default", title: "default", type: "string" }] } ] }, { key: "tip", title: "tip", type: "string" } ], textFieldInclude: [ { key: "title", title: "title", type: "string", required: true }, { key: "required", title: "required", type: "boolean", default: false }, { key: "pattern", title: "pattern", type: "string", required: false }, { key: "multiLine", title: "multiLine", type: "boolean", default: false }, { key: "defaultExtend", type: "extend", selectorKey: "multiLine", clearOnChange: [], types: [ { key: "true", fields: [{ key: "default", title: "default", type: "string", multiLine: true }] }, { key: "false", fields: [{ key: "default", title: "default", type: "string" }] } ] }, { key: "tip", title: "tip", type: "string" } ], sectionInclude: [ { key: "title", title: "title", type: "string", required: true }, { key: "groupdata", title: "groupdata", type: "boolean", default: false }, { key: "fieldsAccordionInclude", type: "include", include: "fieldsAccordionInclude" } ], selectInclude: [ { key: "title", title: "title", type: "string", required: true }, { key: "options", title: "options", type: "accordion", itemTitleKey: "value", fields: [ { key: "value", title: "value", type: "string" }, { key: "text", title: "text", type: "string" } ] }, { key: "multiple", title: "multiple", type: "boolean", default: false }, { key: "required", title: "required", type: "boolean", default: false }, { key: "multipleExtend", selectorKey: "multiple", type: "extend", clearOnChange: ["default"], types: [ { key: "false", fields: [{ key: "default", title: "default", type: "string", default: "" }] }, { key: "true", fields: [ { key: "default", title: "default", type: "chips", default: [] } ] } ] }, { key: "tip", title: "tip", type: "string" } ] };
the_stack
import * as React from "react"; import { Button } from "react-common/controls/Button"; import { SvgCoord } from '../lib/skillGraphUtils'; import { ActivityStatus } from '../lib/skillMapUtils'; /* eslint-disable import/no-unassigned-import, import/no-internal-modules */ import '../styles/graphnode.css' /* eslint-enable import/no-unassigned-import, import/no-internal-modules */ interface GraphNodeProps { node: MapNode; kind: MapNodeKind; width: number; position: SvgCoord; status: ActivityStatus; theme: SkillGraphTheme; selected?: boolean; onItemSelect?: (id: string, kind: MapNodeKind) => void; onItemDoubleClick?: (id: string, kind: MapNodeKind) => void; } interface GraphNodeState { hover: boolean; } export class GraphNode extends React.Component<GraphNodeProps, GraphNodeState> { constructor(props: GraphNodeProps) { super(props); this.state = { hover: false } } protected handleClick = () => { if (this.props.onItemSelect) this.props.onItemSelect(this.props.node.activityId, this.props.kind); } protected handleDoubleClick = () => { if (this.props.onItemDoubleClick) this.props.onItemDoubleClick(this.props.node.activityId, this.props.kind); } protected handleKeyDown = (e: React.KeyboardEvent) => { const charCode = (typeof e.which == "number") ? e.which : e.keyCode; if (charCode === 13 /* enter */ || charCode === 32 /* space */) { e.preventDefault(); e.stopPropagation(); if (this.props.onItemSelect) this.props.onItemSelect(this.props.node.activityId, this.props.kind); } } protected getIcon(status: ActivityStatus, kind: MapNodeKind): string { switch (kind) { case "reward": return "\uf059" case "completion": return "\uf091"; default: switch (status) { case "locked": return "\uf023"; case "completed": return "\uf058"; default: return "\uf101"; } } } protected getIconClass(status: ActivityStatus, kind: MapNodeKind): string { switch (kind) { case "reward": case "completion": return "fas graph-icon" default: switch (status) { case "locked": case "completed": return "fas graph-icon"; default: return "graph-icon-x"; } } } protected getAccessibilityStatusText() { const { status } = this.props; switch (status) { case "completed": return lf("Completed activity."); case "inprogress": return lf("Activity in progress."); case "locked": return lf("This activity is locked. Complete the previous activity to unlock it."); case "notstarted": case "restarted": return lf("Unstarted activity."); } } protected getNodeMarker(status: string, width: number, foreground: string, background: string): JSX.Element { // Used for positioning the corner circle on completed activities so that it isn't // perfectly aligned with the node const nudgeUnit = width / 50; const starUnit = width / 576; switch (status) { case "notstarted": return <g transform={`translate(${(width / 2) - (12 * nudgeUnit)} ${(-width / 2) - (9 * nudgeUnit)})`}> <title>{lf("Not Started")}</title> <g transform={`scale(${starUnit / 2})`}> {fontAwesomeStar(foreground, background)} </g> </g> default: return <g /> } } render() { const { hover } = this.state; const { width, position, selected, status, kind, theme, node } = this.props; let foreground = hover ? theme.unlockedNodeColor : theme.unlockedNodeForeground; let background = hover ? theme.unlockedNodeForeground : theme.unlockedNodeColor; if (status === "locked") { background = hover ? theme.lockedNodeForeground : theme.lockedNodeColor; foreground = hover ? theme.lockedNodeColor : theme.lockedNodeForeground; } else if (kind !== "activity") { background = hover ? theme.rewardNodeForeground : theme.rewardNodeColor; foreground = hover ? theme.rewardNodeColor : theme.rewardNodeForeground; } else if (status === "completed") { background = hover ? theme.completedNodeForeground : theme.completedNodeColor; foreground = hover ? theme.completedNodeColor : theme.completedNodeForeground; } const selectedUnit = width / 8; const yOffset = width / 12.5; const descriptionId = "graph-node-" + node.activityId; let description: string | undefined; switch (node.kind) { case "activity": description = node.description || node.displayName break; case "completion": description = lf("A reward for completing this skillmap."); break; } return ( <g ref={this.handleRef} className={`graph-activity ${selected ? "selected" : ""} ${hover ? "hover" : ""}`} transform={`translate(${position.x} ${position.y})`} onKeyDown={this.handleKeyDown} onClick={this.handleClick} onDoubleClick={this.handleDoubleClick} data-activity={node.activityId}> <foreignObject width={width} height={width} x={-width / 2} y={-width / 2}> <Button className="graph-node-button" title={node.displayName} onClick={this.handleClick} onKeydown={this.handleKeyDown} role="menuitem" ariaHasPopup={status !== "locked" ? "true" : "false"} ariaExpanded={selected} ariaControls={selected ? "info-panel-actions" : undefined} ariaDescribedBy={descriptionId} /> {/** * Hidden accessibility text; ideally this would be visible in the DOM, * but we only show the description when a node has been clicked; not when it * is focused * */} <div id={descriptionId} style={{ display: "none" }}> <p> {this.getAccessibilityStatusText()} </p> {description && <p> {description} </p> } </div> </foreignObject> { selected && (kind !== "activity" ? <circle className="highlight" cx={0} cy={0} r={width / 2 + selectedUnit} stroke={theme.selectedStrokeColor} /> : <rect className="highlight" x={-width / 2 - selectedUnit} y={-width / 2 - selectedUnit} width={width + 2 * selectedUnit} height={width + 2 * selectedUnit} rx={width / 6} stroke={theme.selectedStrokeColor} />) } { kind !== "activity" ? <circle className="focus-outline" cx={0} cy={0} r={width / 2 + selectedUnit * 2} stroke="none" fill="none" /> : <rect className="focus-outline" x={-width / 2 - selectedUnit * 2} y={-width / 2 - selectedUnit * 2} width={width + 4 * selectedUnit} height={width + 4 * selectedUnit} rx={width / 6} stroke="none" fill="none" /> } { kind !== "activity" ? <circle cx={0} cy={0} r={width / 2} fill={background} stroke={foreground} strokeWidth="2" /> : <rect x={-width / 2} y={-width / 2} width={width} height={width} rx={width / 10} fill={background} stroke={foreground} strokeWidth="2" /> } { kind === "activity" && this.getNodeMarker(status, width, theme.selectedStrokeColor, theme.strokeColor) } <text dy={yOffset} textAnchor="middle" alignmentBaseline="middle" dominantBaseline="middle" fill={foreground} className={this.getIconClass(status, kind)}> {this.getIcon(status, kind)} </text> </g> ); } protected handleRef = (g: SVGGElement) => { if (g) { g.addEventListener("mouseenter", () => { this.setState({ hover: true }); }); g.addEventListener("mouseleave", () => { this.setState({ hover: false }); }); } } } function fontAwesomeStar(fill: string, stroke: string) { // Font Awesome Free 5.15.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) return <path fill={fill} stroke={stroke} strokeWidth="50" d="M259.3 17.8L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0z" /> }
the_stack
export interface DisassemblyItem { /** * The memory address of the disassembled instruction */ address: number; /** * Operation codes used for the disassembly */ opCodes?: string; /** * Indicates that the disassembly instruction has an associated label */ hasLabel?: boolean; /** * The Z80 assembly instruction */ instruction?: string; /** * Disassembler-generated comment */ hardComment?: string; /** * The start position of token to replace */ tokenPosition?: number; /** * The length of token to replace */ tokenLength?: number; /** * Signs that this item has a symbol that can be associated with a literal */ hasSymbol?: boolean; /** * The symbol value */ symbolValue?: number; /** * Indicates if this item has a label symbol */ hasLabelSymbol?: boolean; /** * Formatted label */ formattedLabel?: string; /** * Formatted comment */ formattedComment?: string; /** * Signs that this item is just a prefix item */ isPrefixItem?: boolean; /** * The optional prefix comment */ prefixComment?: string; } /** * This class represents the output of the disassembly project */ export class DisassemblyOutput { private _outputItems = new Array<DisassemblyItem>(); private _outputByAddress = new Map<number, DisassemblyItem>(); private readonly _labels = new Map<number, DisassemblyLabel>(); /** * Gets the list of output items */ get outputItems(): Array<DisassemblyItem> { return this._outputItems; } /** * Gets the labels created during disassembly */ get labels(): Map<number, DisassemblyLabel> { return this._labels; } /** * Clears the entire output */ clear(): void { this._outputItems = new Array<DisassemblyItem>(); this._outputByAddress = new Map<number, DisassemblyItem>(); } /** * Adds a new item to the output * @param item Disassembly item to add */ addItem(item: DisassemblyItem): void { this._outputItems.push(item); this._outputByAddress.set(item.address, item); } /** * Gets a disassembly item by its address * @param addr Item address * @returns The speicifid item, if found; otherwise, undefined */ get(addr: number): DisassemblyItem | undefined { return this._outputByAddress.get(addr); } /** * Creates a new label according to its address and optional name * @param addr Label address * @param referringOpAddr The address of operation referring to the label * @returns The newly created label */ createLabel(addr: number, referringOpAddr?: number): void { let label = this._labels.get(addr); if (!label) { label = new DisassemblyLabel(addr); this._labels.set(label.address, label); } if (referringOpAddr) { label.references.push(referringOpAddr); } } /** * Replaces the original output items * @param items Items to replace the original output with */ replaceOutputItems(items: DisassemblyItem[]): void { this._outputItems = items; this._outputByAddress.clear(); for (const item of items) { if (!item.isPrefixItem) { this._outputByAddress.set(item.address, item); } } } } /** * This class describes a label with its references */ export class DisassemblyLabel { /** * Label address */ address: number; /** * Addresses of instructions that reference this label */ readonly references: Array<number>; /** * Initializes disassembly label information * @param address Label address */ constructor(address: number) { this.address = address; this.references = new Array<number>(); } } /** * This enumeration represents the memory section types that can be used * when disassemblying a project. */ export enum MemorySectionType { /** * Simply skip the section without any output code generation */ Skip, /** * Create Z80 disassembly for the memory section */ Disassemble, /** * Create a byte array for the memory section */ ByteArray, /** * Create a word array for the memory section */ WordArray, /** * Create an RST 28 bytecode memory section */ Rst28Calculator, } /** * This class describes a memory section with a start address and a length */ export class MemorySection { private _start = 0; private _end = 0; private _type = MemorySectionType.Disassemble; /** * The start address of the section */ get startAddress() { return this._start; } set startAddress(value: number) { this._start = value & 0xffff; } /** * The end address of the section (inclusive) */ get endAddress() { return this._end; } set endAddress(value: number) { this._end = value & 0xffff; } /** * The type of the memory section */ get sectionType() { return this._type; } set sectionType(value: MemorySectionType) { this._type = value; } /** * The lenght of the memory section */ get lenght(): number { return (this.endAddress - this.startAddress + 1) & 0xffff; } /** * Creates a MemorySection with the specified properties * @param startAddress Starting address * @param endAddress Ending address (inclusive) * @param sectionType Section type */ constructor( startAddress: number, endAddress: number, sectionType = MemorySectionType.Disassemble ) { if (endAddress >= startAddress) { this.startAddress = startAddress; this.endAddress = endAddress; } else { this.startAddress = endAddress; this.endAddress = startAddress; } this.sectionType = sectionType; } /** * Checks if this memory section overlaps with the othe one * @param other Other memory section * @return True, if the sections overlap */ overlaps(other: MemorySection): boolean { return ( (other._start >= this._start && other._start <= this._end) || (other._end >= this._start && other._end <= this._end) || (this._start >= other._start && this._start <= other._end) || (this._end >= other._start && this._end <= other._end) ); } /** * Checks if this section has the same start and length than the other * @param other Other memory section * @return True, if the sections have the same start and length */ sameSection(other: MemorySection): boolean { return this._start === other._start && this._end === other._end; } /** * Gets the intersection of the two memory sections * @param other Other memory section * @return Intersection, if exists; otherwise, undefined */ intersect(other: MemorySection): MemorySection | undefined { let intStart = -1; let intEnd = -1; if (other._start >= this._start && other._start <= this._end) { intStart = other._start; } if (other._end >= this._start && other._end <= this._end) { intEnd = other._end; } if (this._start >= other._start && this._start <= other._end) { intStart = this._start; } if (this._end >= other._start && this._end <= other._end) { intEnd = this._end; } return intStart < 0 || intEnd < 0 ? undefined : new MemorySection(intStart, intEnd); } /** * * @param other Checks if this memory section equals with the other */ equals(other: MemorySection): boolean { return ( this._start === other._start && this._end === other._end && this._type === other._type ); } } /** * This class specifies the spectrum disassembly flags that can be passed * to the Z80 disassembler to provide Spectrum ROM-specific disassembly */ export enum SpectrumSpecificDisassemblyFlags { None = 0, Spectrum48Rst08 = 0x0001, Spectrum48Rst28 = 0x0002, Spectrum48 = Spectrum48Rst08 | Spectrum48Rst28, Spectrum128Rst28 = 0x0004, Spectrum128 = Spectrum128Rst28, SpectrumP3 = Spectrum128Rst28, SpectrumNext = Spectrum128Rst28, } /** * This class contains helpers that manage ZX Spectrum float numbers */ export class FloatNumber { /** * Convert bytes into a ZX Spectrum floating point number * @param bytes Bytes of the float number */ static FromBytes(bytes: number[]): number { if (bytes.length !== 5) { throw new Error("A float number must be exactly 5 bytes"); } if (bytes[0] === 0) { // --- Simple integer form const neg = bytes[1] === 0xff; return (bytes[2] + bytes[3] * 0x100) * (neg ? -1 : 1); } const sign = (bytes[1] & 0x80) === 0 ? 1 : -1; const mantUpper = (((bytes[1] & 0x7f) | 0x80) << 23) * 2; const mant = mantUpper + (bytes[2] << 16) + (bytes[3] << 8) + bytes[4]; const exp = bytes[0] - 128 - 32; return sign * mant * Math.pow(2.0, exp); } /** * Convert compact bytes into a ZX Spectrum floating point number * @param bytes Bytes of the float number */ static FromCompactBytes(bytes: number[]): number { let copyFrom = 1; let exp = bytes[0] & 0x3f; if (exp === 0) { exp = bytes[1]; copyFrom = 2; } exp += 0x50; const newBytes = [0x00, 0x00, 0x00, 0x00, 0x00]; newBytes[0] = exp; let idx = 1; for (let i = copyFrom; i < bytes.length; i++) { newBytes[idx++] = bytes[i]; } return FloatNumber.FromBytes(newBytes); } } /** * This class implements a memory map of the ZX Spectrum virtual machine. * Internally, the sections of the memory map are kept ordered by the section's * start addresses. */ export class MemoryMap { sections: MemorySection[] = []; /** * Gets the count of items in the memory map */ get count() { return this.sections.length; } /** * Adds the specified item to the map * @param item Memory section item to add to the map */ add(item: MemorySection): void { // --- We store the items of the list in ascending order by StartAddress let overlapFound: boolean; do { overlapFound = false; // --- Adjust all old sections that overlap with the new one for (let i = 0; i < this.sections.length; i++) { var oldSection = this.sections[i]; if (item.overlaps(oldSection)) { // --- The new item overlaps with one of the exisitning ones overlapFound = true; const oldStart = oldSection.startAddress; const oldEndEx = oldSection.endAddress; const newStart = item.startAddress; const newEndEx = item.endAddress; if (oldStart < newStart) { // --- Adjust the length of the old section: // --- it gets shorter oldSection.endAddress = newStart - 1; if (oldEndEx > newEndEx) { // --- The rightmost part of the old section becomes a new section const newSection = new MemorySection(newEndEx + 1, oldEndEx); this.sections.splice(i + 1, 0, newSection); } break; } if (oldStart >= newStart) { if (oldEndEx <= newEndEx) { // --- The old section entirely intersects wiht the new section: // --- Remove the old section this.sections.splice(i, 1); } else { // --- Change the old sections's start address oldSection.startAddress = newEndEx + 1; } break; } } } } while (overlapFound); // --- At this point we do not have no old overlapping section anymore. // --- Insert the nex section to its place according to its StartAddress let insertPos = this.sections.length; for (var i = 0; i < this.sections.length; i++) { if (this.sections[i].startAddress > item.startAddress) { // --- This is the right place to insert the new section insertPos = i; break; } } this.sections.splice(insertPos, 0, item); } /** * Merges the sections of another map into this one * @param map Map to merge into this one * @param offset Optional offset of start and end addresses */ merge(map: MemoryMap, offset: number = 0): void { if (!map) { return; } for (const section of map.sections) { this.add( new MemorySection( section.startAddress + offset, section.endAddress + offset, section.sectionType ) ); } } /** * Joins adjacent Disassembly memory sections */ normalize(): void { var changed = true; while (changed) { changed = false; for (var i = 1; i < this.count; i++) { const prevSection = this.sections[i - 1]; const currentSection = this.sections[i]; if ( prevSection.endAddress !== currentSection.startAddress - 1 || prevSection.sectionType !== MemorySectionType.Disassemble || currentSection.sectionType !== MemorySectionType.Disassemble ) { continue; } prevSection.endAddress = currentSection.endAddress; this.sections.splice(i, 1); changed = true; } } } } /** * Allows the JavaScript event loop to process waiting messages */ export function processMessages(): Promise<void> { return new Promise<void>((resolve) => { setTimeout(() => { resolve(); }, 0); }); } /** * Converts an unsigned byte to a signed byte */ export function toSbyte(x: number) { x &= 0xff; return x >= 128 ? x - 256 : x; } /** * Converts value to a signed short */ export function toSshort(x: number) { x &= 0xffff; return x >= 32768 ? x - 65536 : x; } /** * Converts the input value to a 2-digit hexadecimal string * @param value Value to convert */ export function intToX2(value: number): string { const hnum = value.toString(16).toUpperCase(); if (hnum.length >= 2) { return hnum; } return "0" + hnum; } /** * Converts the input value to a 4-digit hexadecimal string * @param value Value to convert */ export function intToX4(value: number): string { const hnum = value.toString(16).toUpperCase(); if (hnum.length >= 4) { return hnum; } return "0000".substring(0, 4 - hnum.length) + hnum; }
the_stack
import { Collection } from './collection' import { CouchbaseError, PathExistsError, PathInvalidError } from './errors' import { StoreSemantics } from './generaltypes' import { LookupInSpec, MutateInSpec } from './sdspecs' import { NodeCallback, PromiseHelper } from './utilities' /** * CouchbaseList provides a simplified interface for storing lists * within a Couchbase document. * * @see {@link Collection.list} * @category Datastructures */ export class CouchbaseList { private _coll: Collection private _key: string /** * @internal */ constructor(collection: Collection, key: string) { this._coll = collection this._key = key } private async _get(): Promise<any[]> { const doc = await this._coll.get(this._key) if (!(doc.content instanceof Array)) { throw new CouchbaseError('expected document of array type') } return doc.content } /** * Returns the entire list of items in this list. * * @param callback A node-style callback to be invoked after execution. */ async getAll(callback?: NodeCallback<any[]>): Promise<any[]> { return PromiseHelper.wrapAsync(async () => { return await this._get() }, callback) } /** * Iterates each item in the list. * * @param rowCallback A callback invoked for each item in the list. * @param callback A node-style callback to be invoked after execution. */ async forEach( rowCallback: (value: any, index: number, array: CouchbaseList) => void, callback?: NodeCallback<void> ): Promise<void> { return PromiseHelper.wrapAsync(async () => { const values = await this._get() for (let i = 0; i < values.length; ++i) { rowCallback(values[i], i, this) } }, callback) } /** * Provides the ability to async-for loop this object. */ [Symbol.asyncIterator](): AsyncIterator<any> { const getNext = async () => this._get() return { data: null as null | any[], index: -1, async next() { if (this.index < 0) { this.data = await getNext() this.index = 0 } const data = this.data as any[] if (this.index < data.length) { return { done: false, value: data[this.index++] } } return { done: true } }, } as any } /** * Retrieves the item at a specific index in the list. * * @param index The index to retrieve. * @param callback A node-style callback to be invoked after execution. */ async getAt(index: number, callback?: NodeCallback<any>): Promise<any> { return PromiseHelper.wrapAsync(async () => { const res = await this._coll.lookupIn(this._key, [ LookupInSpec.get('[' + index + ']'), ]) const itemRes = res.content[0] if (itemRes.error) { throw itemRes.error } return itemRes.value }, callback) } /** * Removes an item at a specific index from the list. * * @param index The index to remove. * @param callback A node-style callback to be invoked after execution. */ async removeAt(index: number, callback?: NodeCallback<void>): Promise<void> { return PromiseHelper.wrapAsync(async () => { await this._coll.mutateIn(this._key, [ MutateInSpec.remove('[' + index + ']'), ]) }, callback) } /** * Returns the index of a specific value from the list. * * @param value The value to search for. * @param callback A node-style callback to be invoked after execution. */ async indexOf(value: any, callback?: NodeCallback<number>): Promise<number> { return PromiseHelper.wrapAsync(async () => { const items = await this._get() for (let i = 0; i < items.length; ++i) { if (items[i] === value) { return i } } return -1 }, callback) } /** * Returns the number of items in the list. * * @param callback A node-style callback to be invoked after execution. */ async size(callback?: NodeCallback<number>): Promise<number> { return PromiseHelper.wrapAsync(async () => { const res = await this._coll.lookupIn(this._key, [LookupInSpec.count('')]) return res.content[0].value }, callback) } /** * Adds a new item to the end of the list. * * @param value The value to add. * @param callback A node-style callback to be invoked after execution. */ async push(value: any, callback?: NodeCallback<void>): Promise<void> { return PromiseHelper.wrapAsync(async () => { await this._coll.mutateIn( this._key, [MutateInSpec.arrayAppend('', value)], { storeSemantics: StoreSemantics.Upsert, } ) }, callback) } /** * Adds a new item to the beginning of the list. * * @param value The value to add. * @param callback A node-style callback to be invoked after execution. */ async unshift(value: any, callback?: NodeCallback<void>): Promise<void> { return PromiseHelper.wrapAsync(async () => { await this._coll.mutateIn( this._key, [MutateInSpec.arrayPrepend('', value)], { storeSemantics: StoreSemantics.Upsert, } ) }, callback) } } /** * CouchbaseMap provides a simplified interface for storing a map * within a Couchbase document. * * @see {@link Collection.map} * @category Datastructures */ export class CouchbaseMap { private _coll: Collection private _key: string /** * @internal */ constructor(collection: Collection, key: string) { this._coll = collection this._key = key } private async _get(): Promise<{ [key: string]: any }> { const doc = await this._coll.get(this._key) if (!(doc.content instanceof Object)) { throw new CouchbaseError('expected document of object type') } return doc.content } /** * Returns an object representing all items in the map. * * @param callback A node-style callback to be invoked after execution. */ async getAll( callback?: NodeCallback<{ [key: string]: any }> ): Promise<{ [key: string]: any }> { return PromiseHelper.wrapAsync(async () => { return await this._get() }, callback) } /** * Iterates through every item in the map. * * @param rowCallback A callback invoked for each item in the list. * @param callback A node-style callback to be invoked after execution. */ async forEach( rowCallback: (value: any, key: string, map: CouchbaseMap) => void, callback?: NodeCallback<void> ): Promise<void> { return PromiseHelper.wrapAsync(async () => { const values = await this._get() for (const i in values) { rowCallback(values[i], i, this) } }, callback) } /** * Provides the ability to async-for loop this object. */ [Symbol.asyncIterator](): AsyncIterator<[any, string]> { const getNext = async () => this._get() return { data: null as { [key: string]: any } | null, keys: null as string[] | null, index: -1, async next() { if (this.index < 0) { this.data = await getNext() this.keys = Object.keys(this.data) this.index = 0 } const keys = this.keys as string[] const data = this.data as { [key: string]: any } if (this.index < keys.length) { const key = keys[this.index++] return { done: false, value: [data[key], key] } } return { done: true, value: undefined } }, } as any } /** * Sets a specific to the specified value in the map. * * @param item The key in the map to set. * @param value The new value to set. * @param callback A node-style callback to be invoked after execution. */ async set( item: string, value: any, callback?: NodeCallback<void> ): Promise<void> { return PromiseHelper.wrapAsync(async () => { await this._coll.mutateIn(this._key, [MutateInSpec.upsert(item, value)], { storeSemantics: StoreSemantics.Upsert, }) }, callback) } /** * Fetches a specific key from the map. * * @param item The key in the map to retrieve. * @param callback A node-style callback to be invoked after execution. */ async get(item: string, callback?: NodeCallback<any>): Promise<any> { return PromiseHelper.wrapAsync(async () => { const res = await this._coll.lookupIn(this._key, [LookupInSpec.get(item)]) const itemRes = res.content[0] if (itemRes.error) { throw itemRes.error } return itemRes.value }, callback) } /** * Removes a specific key from the map. * * @param item The key in the map to remove. * @param callback A node-style callback to be invoked after execution. */ async remove(item: string, callback?: NodeCallback<void>): Promise<void> { return PromiseHelper.wrapAsync(async () => { await this._coll.mutateIn(this._key, [MutateInSpec.remove(item)]) }, callback) } /** * Checks whether a specific key exists in the map. * * @param item The key in the map to search for. * @param callback A node-style callback to be invoked after execution. */ async exists( item: string, callback?: NodeCallback<boolean> ): Promise<boolean> { return PromiseHelper.wrapAsync(async () => { const res = await this._coll.lookupIn(this._key, [ LookupInSpec.exists(item), ]) const itemRes = res.content[0] return itemRes.value }, callback) } /** * Returns a list of all the keys which exist in the map. * * @param callback A node-style callback to be invoked after execution. */ async keys(callback?: NodeCallback<string[]>): Promise<string[]> { return PromiseHelper.wrapAsync(async () => { const values = await this._get() return Object.keys(values) }, callback) } /** * Returns a list of all the values which exist in the map. * * @param callback A node-style callback to be invoked after execution. */ async values(callback?: NodeCallback<any[]>): Promise<any[]> { return PromiseHelper.wrapAsync(async () => { const values = await this._get() return Object.values(values) }, callback) } /** * Returns the number of items that exist in the map. * * @param callback A node-style callback to be invoked after execution. */ async size(callback?: NodeCallback<number>): Promise<number> { return PromiseHelper.wrapAsync(async () => { const res = await this._coll.lookupIn(this._key, [LookupInSpec.count('')]) return res.content[0].value }, callback) } } /** * CouchbaseQueue provides a simplified interface for storing a queue * within a Couchbase document. * * @see {@link Collection.queue} * @category Datastructures */ export class CouchbaseQueue { private _coll: Collection private _key: string /** * @internal */ constructor(collection: Collection, key: string) { this._coll = collection this._key = key } private async _get(): Promise<any[]> { const doc = await this._coll.get(this._key) if (!(doc.content instanceof Array)) { throw new CouchbaseError('expected document of array type') } return doc.content } /** * Returns the number of items in the queue. * * @param callback A node-style callback to be invoked after execution. */ async size(callback?: NodeCallback<number>): Promise<number> { return PromiseHelper.wrapAsync(async () => { const res = await this._coll.lookupIn(this._key, [LookupInSpec.count('')]) return res.content[0].value }, callback) } /** * Adds a new item to the back of the queue. * * @param value The value to add. * @param callback A node-style callback to be invoked after execution. */ async push(value: any, callback?: NodeCallback<void>): Promise<void> { return PromiseHelper.wrapAsync(async () => { await this._coll.mutateIn( this._key, [MutateInSpec.arrayPrepend('', value)], { storeSemantics: StoreSemantics.Upsert, } ) }, callback) } /** * Removes an item from the front of the queue. * * @param callback A node-style callback to be invoked after execution. */ async pop(callback?: NodeCallback<any>): Promise<any> { return PromiseHelper.wrapAsync(async () => { for (let i = 0; i < 16; ++i) { try { const res = await this._coll.lookupIn(this._key, [ LookupInSpec.get('[-1]'), ]) const value = res.content[0].value await this._coll.mutateIn(this._key, [MutateInSpec.remove('[-1]')], { cas: res.cas, }) return value } catch (e) { if (e instanceof PathInvalidError) { throw new CouchbaseError('no items available in list') } // continue and retry } } throw new CouchbaseError('no items available to pop') }, callback) } } /** * CouchbaseSet provides a simplified interface for storing a set * within a Couchbase document. * * @see {@link Collection.set} * @category Datastructures */ export class CouchbaseSet { private _coll: Collection private _key: string /** * @internal */ constructor(collection: Collection, key: string) { this._coll = collection this._key = key } private async _get(): Promise<any[]> { const doc = await this._coll.get(this._key) if (!(doc.content instanceof Array)) { throw new CouchbaseError('expected document of array type') } return doc.content } /** * Adds a new item to the set. Returning whether the item already existed * in the set or not. * * @param item The item to add. * @param callback A node-style callback to be invoked after execution. */ async add(item: any, callback?: NodeCallback<boolean>): Promise<boolean> { return PromiseHelper.wrapAsync(async () => { try { await this._coll.mutateIn( this._key, [MutateInSpec.arrayAddUnique('', item)], { storeSemantics: StoreSemantics.Upsert, } ) } catch (e) { if (e instanceof PathExistsError) { return false } throw e } return true }, callback) } /** * Returns whether a specific value already exists in the set. * * @param item The value to search for. * @param callback A node-style callback to be invoked after execution. */ async contains( item: any, callback?: NodeCallback<boolean> ): Promise<boolean> { return PromiseHelper.wrapAsync(async () => { const values = await this._get() for (let i = 0; i < values.length; ++i) { if (values[i] === item) { return true } } return false }, callback) } /** * Removes a specific value from the set. * * @param item The value to remove. * @param callback A node-style callback to be invoked after execution. */ async remove(item: any, callback?: NodeCallback<void>): Promise<void> { return PromiseHelper.wrapAsync(async () => { for (let i = 0; i < 16; ++i) { try { const res = await this._coll.get(this._key) if (!(res.content instanceof Array)) { throw new CouchbaseError('expected document of array type') } const itemIdx = res.content.indexOf(item) if (itemIdx === -1) { throw new Error('item was not found in set') } await this._coll.mutateIn( this._key, [MutateInSpec.remove('[' + itemIdx + ']')], { cas: res.cas, } ) return } catch (e) { // continue and retry } } throw new CouchbaseError('no items available to pop') }, callback) } /** * Returns a list of all values in the set. * * @param callback A node-style callback to be invoked after execution. */ async values(callback?: NodeCallback<any[]>): Promise<any[]> { return PromiseHelper.wrapAsync(async () => { return await this._get() }, callback) } /** * Returns the number of elements in this set. * * @param callback A node-style callback to be invoked after execution. */ async size(callback?: NodeCallback<number>): Promise<number> { return PromiseHelper.wrapAsync(async () => { const res = await this._coll.lookupIn(this._key, [LookupInSpec.count('')]) return res.content[0].value }, callback) } }
the_stack
import { Box, Collapse, Grid } from "@material-ui/core"; import Typography from "@material-ui/core/Typography"; import { Alert, AlertTitle } from "@material-ui/lab"; import arrayMutators from "final-form-arrays"; import { AutoCompleteMultipleValue, AutoCompleteMultiValuesFreeSolo } from "forms/Final/autoComplete"; import { FinalBoolCheckboxRender, FinalCheckboxGroupRender } from "forms/Final/checkbox"; import { FinalRadioGroupRender } from "forms/Final/radio"; import { FinalTextField } from "forms/Final/textfield"; import { FormDataPreview } from "forms/Final/util"; import { ROUTE_FORM_ID } from "forms/formIDs"; import { NormalizePositiveNumber, stringArrayTrimAndToLowerCaseParse, stringArrayTrimParse } from "forms/normalizer"; import { TargetsPanel } from "forms/Route/targetsPanel"; import { RouteDomains } from "forms/Route/Domains"; import { ValidatorArrayNotEmpty, ValidatorArrayOfPath } from "forms/validator"; import routesGif from "images/routes.gif"; import React from "react"; import { Field, FieldRenderProps, Form, FormRenderProps } from "react-final-form"; import { FieldArray, FieldArrayRenderProps } from "react-final-form-arrays"; import { useSelector } from "react-redux"; import { Link as RouteLink } from "react-router-dom"; import { RootState } from "reducers"; import { FormTutorialHelper } from "tutorials/formValueToReduxStoreListener"; import { finalValidateOrNotBlockByTutorial } from "tutorials/utils"; import { httpMethods, HttpRoute, methodsModeAll, methodsModeSpecific } from "types/route"; import { arraysMatch } from "utils"; import { includesForceHttpsDomain } from "utils/domain"; import { default as sc, default as stringConstants } from "utils/stringConstants"; import { SubmitButton } from "widgets/Button"; import { CollapseWrapper } from "widgets/CollapseWrapper"; import { Expansion } from "widgets/expansion"; import { KPanel } from "widgets/KPanel"; import { Caption } from "widgets/Label"; import { Prompt } from "widgets/Prompt"; import { RenderHttpRouteConditions } from "./conditions"; interface RouteFormProps { isEditing?: boolean; onSubmit: any; initial: HttpRoute; } const schemaOptions = [ { value: "http", label: "http", }, { value: "https", label: "https", htmlColor: "#9CCC65", }, ]; const RouteFormRaw: React.FC<RouteFormProps> = (props) => { const { isEditing, initial, onSubmit } = props; const { tutorialState, certificates } = useSelector((state: RootState) => { const certificates = state.certificates.certificates; return { tutorialState: state.tutorial, domains: state.domains.domains, certificates, }; }); const canCertDomainsSuiteForHost = (domains: string[], host: string) => { for (let i = 0; i < domains.length; i++) { const domain = domains[i]!; if (domain === "*") { return false; } if (domain.toLowerCase() === host.toLowerCase()) { return true; } const domainParts = domain.toLowerCase().split("."); const hostParts = host.toLowerCase().split("."); if (hostParts.length === 0 || domainParts.length === 0 || domainParts[0] !== "*") { continue; } if (arraysMatch(hostParts.slice(1), domainParts.slice(1))) { return true; } } return false; }; const renderCertificationStatus = (values: HttpRoute) => { const { hosts } = values; if (hosts.length === 0) { return null; } let missingCertsHosts: string[] = []; for (let host of hosts) { if (host === "") { continue; } const cert = certificates.find((c) => canCertDomainsSuiteForHost(c.domains, host)); if (!cert) { missingCertsHosts.push(host); } } const missingCertsCount = missingCertsHosts.length; return ( <Alert severity={missingCertsCount === 0 ? "success" : "warning"}> {missingCertsHosts.length > 0 ? ( <AlertTitle> {missingCertsHosts.length} host{missingCertsHosts.length > 1 ? "s are" : " is"} missing valid SSL certificate signed by a certificate authority. </AlertTitle> ) : ( <AlertTitle>All hosts have valid SSL certificates signed by a certificate authority.</AlertTitle> )} {missingCertsHosts.length > 0 ? ( <> <Box marginBottom={1}> {missingCertsHosts.map((host) => { return ( <Box key={host} ml={2} fontWeight="bold"> {host} </Box> ); })} </Box> <Box marginBottom={1}> <Typography> Invalid SSL certificate / Intermediate certificates error could occur when you try to access this route. Go to <RouteLink to="/domains">domains & certificates</RouteLink> page, add your domain, then follow the instruction to apply an certificate. </Typography> </Box> </> ) : null} </Alert> ); }; const renderTargets = () => { return ( <Box p={2}> <Grid container spacing={2}> <Grid item xs={12} sm={12} md={12}> <TargetsPanel /> </Grid> <Grid item xs={8} sm={8} md={8}> <CollapseWrapper title={stringConstants.ROUTE_MULTIPLE_TARGETS_HELPER}> <Box m={2} style={{ display: "flex", flexDirection: "column", justifyContent: "center", height: "100%" }}> <img src={routesGif} alt="routes with multi-target" width={233} height={133} /> <Box pt={2}> <Caption>{stringConstants.ROUTE_MULTIPLE_TARGETS_DESC}</Caption> </Box> </Box> </CollapseWrapper> </Grid> </Grid> </Box> ); }; const validate = (values: HttpRoute) => { let errors: any = {}; const { methods, methodsMode, schemes } = values; if (methodsMode === methodsModeSpecific) { errors.methods = ValidatorArrayNotEmpty(methods); } errors.schemes = ValidatorArrayNotEmpty(schemes); return Object.keys(errors).length > 0 ? errors : finalValidateOrNotBlockByTutorial(values, tutorialState, ROUTE_FORM_ID); }; //UX improvement: provide an intial target if there isn't one (this can probably be refactored) if (initial.destinations.length === 0) { initial.destinations.push({ weight: 1, host: "" }); } return ( <Form onSubmit={onSubmit} initialValues={initial} keepDirtyOnReinitialize validate={validate} mutators={{ ...arrayMutators, }} render={({ values, handleSubmit, form: { change } }: FormRenderProps<HttpRoute>) => { const { hosts, methodsMode, schemes, httpRedirectToHttps } = values; const hstsDomains = includesForceHttpsDomain(hosts); const methodOptions = httpMethods.map((m) => ({ value: m, label: m })); if (!schemes.includes("https")) { if (hstsDomains.length > 0) { if (schemes.includes("http")) { change("schemes", ["http", "https"]); } else { change("schemes", ["https"]); } } } // set httpRedirectToHttps to false if http or https is not in schemes if (!(schemes.includes("http") && schemes.includes("https")) && httpRedirectToHttps) { change("httpRedirectToHttps", false); } return ( <form onSubmit={handleSubmit} id="route-form"> <FormTutorialHelper form={ROUTE_FORM_ID} /> <Prompt /> <Box> <Grid container spacing={2}> <Grid item sm={6}> <KPanel title="Domains" style={{ height: "100%" }} content={ <Box p={2}> <RouteDomains /> </Box> } /> </Grid> <Grid item sm={6}> <KPanel title="Targets" content={renderTargets()} /> </Grid> </Grid> </Box> <Box mt={1}> <Grid container spacing={2}> <Grid item sm={6}> <KPanel title="Schemes and Methods" style={{ height: "100%" }}> <Box p={2}> <Field title="Http Methods" name="methodsMode" component={FinalRadioGroupRender} options={[ { value: methodsModeAll, label: sc.ROUTE_HTTP_METHOD_ALL, }, { value: methodsModeSpecific, label: sc.ROUTE_HTTP_METHOD_CUSTOM, }, ]} /> <Collapse in={methodsMode === methodsModeSpecific}> <FieldArray render={(props: FieldArrayRenderProps<string, any>) => { return <FinalCheckboxGroupRender {...props} options={methodOptions} />; }} name="methods" /> </Collapse> <FieldArray render={(props: FieldArrayRenderProps<string, any>) => { return ( <FinalCheckboxGroupRender {...props} title="Allow traffic through" options={schemaOptions} /> ); }} name="schemes" /> <Collapse in={ values.schemes && values.schemes.indexOf("http") > -1 && values.schemes.indexOf("https") > -1 } > <Field component={FinalBoolCheckboxRender} name="httpRedirectToHttps" type="checkbox" label={ <span> Redirect all <strong>http</strong> request to <strong>https</strong> with 301 status code. </span> } /> </Collapse> <Collapse in={values.schemes.includes("https")}> <Alert className="alert" severity="info"> {sc.ROUTE_HTTPS_ALERT} </Alert> {hstsDomains.length > 0 ? ( <Alert className="alert" severity="warning"> <Box display="flex"> The <Box ml="4px" mr="4px"> <strong>{hstsDomains.join(", ")}</strong> </Box> {stringConstants.HSTS_DOMAINS_REQUIRED_HTTPS} </Box> </Alert> ) : null} {renderCertificationStatus(values)} </Collapse> </Box> </KPanel> </Grid> <Grid item sm={6}> <KPanel style={{ height: "100%" }} title="Paths" content={ <Box p={2}> <Field render={(props: FieldRenderProps<string[]>) => ( <AutoCompleteMultiValuesFreeSolo<string> {...props} options={[]} /> )} label="Path Prefixes" name="paths" validate={ValidatorArrayOfPath} parse={stringArrayTrimParse} placeholder="e.g. /api/v1; /blogs; /assets" helperText={sc.ROUTE_PATHS_INPUT_HELPER} /> <Field type="checkbox" component={FinalBoolCheckboxRender} name="stripPath" label={sc.ROUTE_STRIP_PATH_LABEL} helperText={sc.ROUTE_STRIP_PATH_HELPER} /> </Box> } /> </Grid> </Grid> </Box> <Box mt={2}> <KPanel title="Rules"> <Box p={2}> <Caption> Set specific rules for this ingress. Only requests that match these conditions will be accepted. </Caption> <RenderHttpRouteConditions /> </Box> </KPanel> </Box> <Box mt={2}> <Expansion title="Cors" defaultUnfold={false}> <Box p={2}> <Box mb={2}> <Field render={(props: FieldRenderProps<string[]>) => ( <AutoCompleteMultiValuesFreeSolo<string> {...props} options={[]} /> )} parse={stringArrayTrimAndToLowerCaseParse} placeholder="e.g. *; http://example.com" name="cors.allowOrigins" label="Allow Origins" /> </Box> <Box mb={2}> <Field render={(props: FieldRenderProps<string[]>) => ( <AutoCompleteMultipleValue {...props} options={httpMethods} /> )} placeholder={`e.g. ${httpMethods.join("; ")}`} name="cors.allowMethods" label="Allow Methods" /> </Box> <Box mb={2}> <Field render={(props: FieldRenderProps<string[]>) => ( <AutoCompleteMultiValuesFreeSolo<string> {...props} options={[]} /> )} parse={stringArrayTrimAndToLowerCaseParse} placeholder="e.g. Custom-Header-Name" name="cors.allowHeaders" label="Allow Headers" /> </Box> <Box mb={2}> <Field name="cors.allowCredentials" type="checkbox" component={FinalBoolCheckboxRender} label="Allow Credentials" /> </Box> <Box mb={2}> <Field<number | undefined> component={FinalTextField} parse={NormalizePositiveNumber} name={`cors.maxAgeSeconds`} label="Max Age Seconds" placeholder="e.g. 86400" /> </Box> </Box> </Expansion> </Box> <Box mt={2}> <SubmitButton id="add-route-submit-button">{isEditing ? "Update" : "Create"} Route</SubmitButton> </Box> <FormDataPreview /> </form> ); }} /> ); }; export const RouteForm = RouteFormRaw;
the_stack
import React, { useState, useRef } from 'react'; import moment, { Moment } from 'moment'; import { PrimaryButton, SecondaryButton, ExportButton, ViewTransactionDetailsButton, SortButton, } from 'modules/common/buttons'; import { ASCENDING, DESCENDING, NEUTRAL, ETH, REP, DAI, } from 'modules/common/constants'; import { Pagination } from 'modules/common/pagination'; import { ValueLabel, TextLabel } from 'modules/common/labels'; import { DatePicker, FormDropdown } from 'modules/common/form'; import { Title } from 'modules/modal/common'; import { formatShares, formatDaiPrice, formatDai } from 'utils/format-number'; import Styles from 'modules/modal/modal.styles.less'; import { createBigNumber } from 'utils/create-big-number'; import { DismissableNotice, DISMISSABLE_NOTICE_BUTTON_TYPES, } from 'modules/reporting/common'; interface TransactionsProps { closeAction: Function; title: string; currentTimestamp: any; getTransactionsHistory: Function; } interface TransactionInfo { transactionHash: string; timestamp: number; marketDescription: string; outcome: number | null; outcomeDescription: string | null; action: string; price: string; quantity: string; coin: string; fee: string; total: string; details: string; } interface TransactionsState { coin: string; action: string; itemsPerPage: number; page: number; startDate: Date | any; endDate: Date | any; startFocused: boolean; endFocused: boolean; AllTransactions: Array<TransactionInfo>; filteredTransactions: Array<TransactionInfo>; priceSort: typeof ASCENDING | typeof DESCENDING | typeof NEUTRAL; quantitySort: typeof ASCENDING | typeof DESCENDING | typeof NEUTRAL; } const coinOptions = [ { label: 'All', value: 'ALL', }, { label: DAI, value: DAI, }, { label: 'REPv2', value: REP, }, { label: ETH, value: ETH, }, ]; const actionOptions = [ { label: 'All', value: 'ALL', }, { label: 'Open', value: 'OPEN', }, { label: 'Filled', value: 'FILLED', }, { label: 'Cancelled', value: 'CANCEL', }, { label: 'Claim Participation Tokens', value: 'CLAIM_PARTICIPATION_TOKENS', }, { label: 'Claim Staked REPv2 & Reporting Fees', value: 'CLAIM_WINNING_CROWDSOURCERS', }, { label: 'Claim Trading Proceeds', value: 'CLAIM_TRADING_PROCEEDS', }, { label: 'Dispute', value: 'DISPUTE', }, { label: 'Initial Report', value: 'INITIAL_REPORT', }, { label: 'Market Creation', value: 'MARKET_CREATION', }, ]; const paginationOptions = [ { label: '10 per page', value: 10, }, { label: '20 per page', value: 20, }, { label: '30 per page', value: 30, }, { label: '40 per page', value: 40, }, { label: '50 per page', value: 50, }, ]; export const Transactions: React.FC<TransactionsProps> = props => { //Default states const [coin, setCoin] = useState<string>('ALL'); const [action, setAction] = useState<string>('ALL'); const [itemsPerPage, setItemsPerPage] = useState<number>(20); const [page, setPage] = useState<number>(1); const [priceSort, setPriceSort] = useState<string>(NEUTRAL); const [quantitySort, setQuantitySort] = useState<string>(NEUTRAL); //Component states const [startDate, setStartDate] = useState<Moment>( moment(props.currentTimestamp * 1000).subtract(6, 'M') ); const [endDate, setEndDate] = useState<Moment>( moment(props.currentTimestamp * 1000) ); const [startFocused, setStartFocused] = useState<boolean>(false); const [endFocused, setEndFocused] = useState<boolean>(false); const [AllTransactions, setAllTransactions] = useState<TransactionInfo[]>([]); const [filteredTransactions, setFilteredTransactions] = useState< TransactionInfo[] >([]); //Refs const tableHeaderRef = useRef<HTMLDivElement>(null); const tableBodyRef = useRef<HTMLDivElement>(null); React.useEffect(() => { triggerSearch(); tableBodyRef.current.addEventListener('scroll', handleScroll); tableHeaderRef.current.addEventListener('scroll', handleScroll); return () => { tableBodyRef.current.removeEventListener('scroll', handleScroll); tableHeaderRef.current.removeEventListener('scroll', handleScroll); }; }, []); const handleScroll = () => { const body = tableBodyRef.current.scrollLeft; const head = tableHeaderRef.current.scrollLeft; if (body !== head) { tableHeaderRef.current.scrollTo(body, 0); } }; const cyclePriceSort = (e: Event) => { let updatedPriceSort = NEUTRAL; switch (priceSort) { case ASCENDING: // if ascending cycle to descending updatedPriceSort = DESCENDING; filteredTransactions.sort( (a, b) => parseFloat(b.price) - parseFloat(a.price) ); break; case NEUTRAL: // if neutral cycle to ascending updatedPriceSort = ASCENDING; filteredTransactions.sort( (a, b) => parseFloat(a.price) - parseFloat(b.price) ); break; default: // if descending cycle to neutral; filteredTransactions.sort((a, b) => b.timestamp - a.timestamp); break; } // @ts-ignore setPriceSort(updatedPriceSort); setFilteredTransactions(filteredTransactions); }; const cycleQuantitySort = (e: Event) => { let updatedQuantitySort = NEUTRAL; switch (quantitySort) { case ASCENDING: // if ascending cycle to descending updatedQuantitySort = DESCENDING; filteredTransactions.sort( (a, b) => parseFloat(b.quantity) - parseFloat(a.quantity) ); break; case NEUTRAL: // if neutral cycle to ascending updatedQuantitySort = ASCENDING; filteredTransactions.sort( (a, b) => parseFloat(a.quantity) - parseFloat(b.quantity) ); break; default: // if descending cycle to neutral; filteredTransactions.sort((a, b) => b.timestamp - a.timestamp); break; } // @ts-ignore setQuantitySort(updatedQuantitySort); setFilteredTransactions(filteredTransactions); }; const triggerSearch = () => { const { getTransactionsHistory } = props; getTransactionsHistory( startDate.unix().valueOf(), endDate.unix().valueOf(), coin, action, (AllTransactions: TransactionInfo[]) => { const filteredTransactions = filterTransactions( AllTransactions, coin, action ); if (tableHeaderRef) setAllTransactions(AllTransactions); setFilteredTransactions(filteredTransactions); } ); setPage(1); }; const resetSearch = () => { setStartDate(moment(currentTimestamp * 1000).subtract(6, 'M')); setEndDate(moment(currentTimestamp * 1000)); setFilteredTransactions(AllTransactions); triggerSearch(); }; const filterTransactions = ( transactions: Array<TransactionInfo>, coin: string, action: string ) => { const filteredTransactions = transactions.filter( (Transaction: TransactionInfo) => Transaction.coin === coin || coin === 'ALL' ); return filteredTransactions; }; const triggerTransactionsExport = () => { if (AllTransactions.length === 0) return; const items = AllTransactions; const replacer = (key: string, value: any) => (value === null ? '' : value); const header = Object.keys(items[0]); const csv = items.map((row: any) => header .map((fieldName: any) => JSON.stringify(row[fieldName], replacer)) .join(',') ); csv.unshift(header.join(',')); const exportCSV = csv.join('\r\n'); const transactionsDataString = 'data:text/plain;charset=utf-8,' + encodeURIComponent(exportCSV); const a = document.createElement('a'); a.setAttribute('href', transactionsDataString); a.setAttribute('download', 'AugurTransactions.csv'); a.click(); }; const addTransactionRow = (tx: TransactionInfo) => { const timestamp = tx.timestamp ? moment(tx.timestamp * 1000).format('D MMM YYYY HH:mm:ss') : null; const key = `${tx.transactionHash}-${tx.timestamp}-${tx.action}-${tx.outcomeDescription}`; // we never show the coin type outside of tx.coin so we can just format by shares always here. const quantity = formatShares(createBigNumber(tx.quantity)); const actionLabel = actionOptions.find((option: any) => { if (option.value === tx.action) return true; return false; }); return [ <span>{timestamp}</span>, <TextLabel keyId={tx.transactionHash} text={tx.marketDescription} />, <TextLabel text={tx.outcomeDescription || ''} />, <TextLabel text={ (actionLabel && actionLabel.label) || tx.action.replace(/_/g, ' ').toLowerCase() } />, <ValueLabel value={formatDaiPrice(Number(tx.price))} showDenomination={false} showEmptyDash={false} />, <ValueLabel value={quantity} showDenomination={false} showEmptyDash={false} />, <span>{tx.coin}</span>, <ValueLabel value={formatDai(Number(tx.fee))} showDenomination={false} showEmptyDash={false} />, <ValueLabel value={formatDai(createBigNumber(tx.total))} showDenomination={false} showEmptyDash={false} />, <ViewTransactionDetailsButton transactionHash={tx.transactionHash} />, ]; }; const { title, closeAction, currentTimestamp } = props; const pageInfo = { page, itemsPerPage, itemCount: filteredTransactions.length, action: (page: number) => setPage(page), }; const pageTransactions = filteredTransactions.slice( page * itemsPerPage - itemsPerPage, page * itemsPerPage ); const startDatePicker = { id: 'startDatePicker', date: startDate, placeholder: 'Start Date', onDateChange: (startDate: string) => { setStartDate(moment(startDate)); triggerSearch(); }, onFocusChange: ({ focused }: { focused: boolean }) => { if (startDate == null) { const startDate = moment(currentTimestamp * 1000); setStartDate(startDate); } setStartFocused(focused); }, focused: startFocused, displayFormat: 'D MMM YYYY', numberOfMonths: 1, }; const endDatePicker = { id: 'endDatePicker', date: endDate, placeholder: 'End Date', onDateChange: (endDate: string) => { setEndDate(moment(endDate)); triggerSearch(); }, onFocusChange: ({ focused }: { focused: boolean }) => { if (endDate == null) { const endDate = moment(currentTimestamp * 1000); setEndDate(endDate); } setEndFocused(focused); }, isOutsideRange: (day: Moment) => day.isAfter(moment(currentTimestamp * 1000).add(1, 'hour')) || day.isBefore(startDate), focused: endFocused, displayFormat: 'D MMM YYYY', numberOfMonths: 1, }; const transactionsRows = pageTransactions.map( (transaction: TransactionInfo) => addTransactionRow(transaction) ); return ( <div className={Styles.Transactions}> <Title title={title} closeAction={closeAction} /> <section> <span>Date From</span> <span>Date To</span> <span>Action</span> <span>Coin</span> <FormDropdown options={paginationOptions} defaultValue={itemsPerPage} onChange={(itemsPerPage: number) => setItemsPerPage(itemsPerPage)} /> <DatePicker {...startDatePicker} /> <DatePicker {...endDatePicker} /> <FormDropdown options={actionOptions} defaultValue={action} onChange={(action: string) => { const filteredTransactions = filterTransactions( AllTransactions, coin, action ); setFilteredTransactions(filteredTransactions); setAction(action); }} /> <FormDropdown options={coinOptions} defaultValue={coin} onChange={(coin: string) => { const filteredTransactions = filterTransactions( AllTransactions, coin, action ); setFilteredTransactions(filteredTransactions); setCoin(coin); }} /> <div> <SecondaryButton action={resetSearch} text="Reset" /> <PrimaryButton action={triggerSearch} text="Search" /> </div> <ExportButton action={triggerTransactionsExport} /> </section> <section> <DismissableNotice show buttonType={DISMISSABLE_NOTICE_BUTTON_TYPES.CLOSE} title="The export tool only shows transactions for 60 days after the markets finalization." /> </section> <div> <div ref={tableHeaderRef}> <span>Date</span> <span>Market</span> <span>Outcome</span> <span>Action</span> <span> <SortButton text="Price" sortOption={priceSort} action={(e: Event) => cyclePriceSort(e)} /> </span> <span> <SortButton text="Quantity" sortOption={quantitySort} action={(e: Event) => cycleQuantitySort(e)} /> </span> <span>Coin</span> <span>Trading Fee</span> <span>Total</span> <span>Etherscan</span> </div> <section ref={tableBodyRef}> <> {pageTransactions.length === 0 && ( <span className={Styles.NullTransactionsRow}> No Transactions </span> )} {transactionsRows} </> </section> </div> <div> <Pagination {...pageInfo} updateLimit={() => {}} /> <FormDropdown options={paginationOptions} defaultValue={itemsPerPage} onChange={(itemsPerPage: number) => setItemsPerPage(itemsPerPage)} openTop /> </div> </div> ); };
the_stack
"use strict"; // uuid: ce496037-5728-4543-b2b1-f8a9aaa3d0f0 // ------------------------------------------------------------------------ // Copyright (c) 2018 Alexandre Bento Freire. All rights reserved. // Licensed under the MIT License+uuid License. See License.txt for details // ------------------------------------------------------------------------ // Implements a list of built-in chart Tasks /** @module end-user | The lines bellow convey information for the end-user */ /** * ## Description * * A **chart** task creates an animated chart. * * **WARN** This plugin is still in development stage, parts of API can change in the future. * However is already in a stage that can be used. * * This plugin has the following built-in charts: * * - [pie](#PieChartTaskParams) * - [bar](#AxisChartTaskParams) * - [area](#AxisChartTaskParams) * - [line](#AxisChartTaskParams) * - [marker](#AxisChartTaskParams) * - [mixed](#AxisChartTaskParams) Draws different types of chars in the same chart, uses * [](#chartTypes) parameter to determine the type of each chart per series. * * read the details on [](#AxisChartTaskParams). * * ## Get started * How to create a simple bar chart: * * The bare-bones of a `abeamer.ini` file: * ```scss * $abeamer-width: 300; * $abeamer-height: 150; * ``` * * The bare-bones of a `html` file: * ```html * <div class="abeamer-story" id=story> * <div class=abeamer-scene id=scene1> * <canvas id=chart width=300 height=150></canvas> * </div> * </div> * ``` * * On the `hello-world` example, replace the `scene.addAnimations` with: * ```typescript * scene.addAnimations([{ * selector: '#chart', // JQuery selector pointing to the HtmlElement * tasks: [{ * handler: 'chart', // is always 'chart' for charts. * params: { * chartType: ABeamer.ChartTypes.bar, // or 'bar' if you are using javascript * labelsX: { captions: ['A', 'B', 'C', 'D', 'E'] }, * title: 'My first Chart', * data: [[100, 200, 50, 140, 300]], * } as ABeamer.AxisChartTaskParams, // comment as ... if you are using javascript * }], * }]); * ``` * The previous example, will create a static chart. * To animate it, change it the to following: * ```typescript * scene.addAnimations([{ * selector: 'canvas', * tasks: [{ * handler: 'chart', * params: { * chartType: ABeamer.ChartTypes.bar, * labelsX: { captions: ['A', 'B', 'C', 'D', 'E'] }, * title: 'My first Chart', * data: [[100, 200, 50, 140, 300]], * // animation parameters * pointHeightStart: 0.1, // defined the initial value for the animation point-height property * animeSelector: 'chart-anime-01', // unique animation selector to be used by the animator * } as ABeamer.AxisChartTaskParams, * }], * }]) * .addAnimations([{ * selector: `%chart-anime-01`, // animation selector defined previously, prefixed with '%' * duration: `1s`, * props: [{ * prop: 'point-height', // property which initial value is 0.1 * value: 1, // value at the end of animation * }], * }]); * ``` */ namespace ABeamer { // #generate-group-section // ------------------------------------------------------------------------ // Chart Tasks // ------------------------------------------------------------------------ // The following section contains data for the end-user // generated by `gulp build-definition-files` // ------------------------------- // #export-section-start: release export enum ChartTypes { pie, bar, area, line, marker, mixed, } export type ChartTaskName = 'chart'; export interface ExprSeries { /** * Expression that defines the series. * `v` is the variable that starts in `startValue`, increments `step`. * `n` is the number of points. */ expr: ExprString; /** * Number of points generated by the expr. * If it's undefined, but there is already a previous series it will use * the previous series nrPoints. * @default ChartDefaults.nrPoints */ nrPoints: uint; startValue?: number; step?: number; } export type SeriesData = number[] | ExprSeries; export enum ChartCaptionOrientation { horizontal, vertical, } export enum ChartCaptionPosition { top, bottom, left, right, } export enum ChartCaptionAlignment { left, center, right, } export interface ChartCaptions { fontColor?: string | ExprString; fontFamily?: string | ExprString; fontSize?: uint | ExprString; alignment?: ChartCaptionAlignment | string; position?: ChartCaptionPosition | string; orientation?: ChartCaptionOrientation | string; marginBefore?: uint | ExprString; marginAfter?: uint | ExprString; } export interface ChartLabels extends ChartCaptions { captions?: string[] | ExprString; } export type ChartLabelsX = ChartLabels; export interface ChartLegendMark { width?: uint | ExprString; height?: uint | ExprString; spacing?: uint | ExprString; } export interface ChartLegend extends ChartLabels { mark?: ChartLegendMark; } export interface ChartLabelsY extends ChartLabels { tickCount?: uint; } export enum ChartPointShape { circle, square, diamond, } export interface ChartMarkers { visible?: boolean | boolean[] | boolean[][]; shape?: (ChartPointShape | string) | (ChartPointShape | string)[] | (ChartPointShape | string)[][]; size?: uint | uint[] | uint[][]; color?: string | string[] | string[][]; } export interface ChartLine { visible?: boolean; color?: string | ExprString; width?: number | ExprString; } export interface ChartTitle extends ChartCaptions { caption: string | ExprString; } export interface ChartDefaults { labelsX: ChartLabelsX; labelsY: ChartLabelsY; legend: ChartLegend; title: ChartTitle; fillColors: string; strokeColors: string; strokeWidth: uint; markers: ChartMarkers; barWidth: uint; pointMaxHeight: uint; pointDistance: uint; seriesSpacing: uint; /** Number of Points for ExprSeries */ nrPoints: uint; } /** * Parameters for both [Axis Charts](#AxisChartTaskParams) and [Pie Charts](#PieChartTaskParams). */ export interface BaseChartTaskParams extends AnyParams { /** * Defines the type of chart. * If it's `mixed` it uses [](#chartTypes) */ chartType?: ChartTypes | string; /** * List of series of data points. * Each series much have the same number of data points. */ data: SeriesData[]; /** * Set with a unique virtual selector, to be used another `addAnimations` to animate the chart. * ### Example * ```typescript * scene.addAnimations([{ * selector: 'canvas', * tasks: [{ * handler: 'chart', * params: { * data: [[100, 200, 50, 140, 300]], * pointHeightStart: 0.1, // defined the initial value for the animation point-height property * animeSelector: 'chart-anime-02', // unique animation selector to be used by the animator * } as ABeamer.AxisChartTaskParams, * }], * }]) * .addAnimations([{ * selector: `%chart-anime-02`, // animation selector defined previously, prefixed with '%' * duration: `1s`, * props: [{ * prop: 'point-height', // property which initial value is 0.1 * value: 1, // value at the end of animation * }], * }]); * ``` */ animeSelector?: string; /** * Defines the chart title. * At the moment is only supported horizontal top or bottom titles. */ title?: string | ExprString | ChartTitle; /** * Defines the chart legend. * At the moment is only supported stacked left or right top legend. */ legend?: ChartLegend; // colors /** Interior Color used by `area`, `bar` and `pie` charts. */ fillColors?: string | string[] | string[][]; /** Outline Color used by `area`, `bar` and `pie` charts, and line color for `line` chart. */ strokeColors?: string | string[] | string[][]; strokeWidth?: uint | uint[] | uint[][]; } /** * Parameters used by Pie Charts. * Pie Charts provide the following animators: * - [angle](#PieChartTaskParams.angleStart) with initial value in angleStart. * - [dispersion](#PieChartTaskParams.dispersionStart) with initial value in dispersionStart. */ export interface PieChartTaskParams extends BaseChartTaskParams { /** * Initial angle in radians defining the zero radial line of the chart. * This parameter is animated with property `angle`. */ angleStart?: number | ExprString; /** * Initial dispersion factor defined between 0 and 1. * A dispersion defines the percentage of how much the pie circle will be used. * A value of 1 represents a full circle, and a value of 0.5, represents half circle. * This parameter is animated with property `dispersion`. */ dispersionStart?: number | ExprString; isClockwise?: boolean; } /** * Parameters used by Axis Charts, which are all except [Pie Charts](#PieChartTaskParams). * Axis Charts provide the following animators: * - [point-height](#AxisChartTaskParams.pointHeightStart) with initial value in pointHeightStart. * - [deviation](#AxisChartTaskParams.deviationStart) with initial value in deviationStart. * - [sweep](#AxisChartTaskParams.sweepStart) with initial value in sweepStart. */ export interface AxisChartTaskParams extends BaseChartTaskParams { /** * Chart Type per series. Use only if [](#chartType) is `mixed`. * @example: [ABeamer.ChartTypes.bar, ABeamer.ChartTypes.bar, ABeamer.ChartTypes.line] */ chartTypes?: (ChartTypes | string)[]; /** * Defines the X labels with complete information or just as an [](#ExprString). * If it's a ExprString, it will create one label for each point. * The iterator variable is `v`. * If it's an array, it must match the number of points in a series. * @example =2012 + v * @example { captions: ['A', 'B', 'C', 'D'] } */ labelsX?: ChartLabelsX | ExprString | string[]; /** * Defines the Y labels with complete information or just as an [](#ExprString). * If it's a ExprString, it will create one label for each point. * The iterator variable is `v`. * If it's an array, it must match the tickCount. * @example =v/1000 + 'k' * @example { captions: ['10', '20', '30', '40'] } */ labelsY?: ChartLabelsY | ExprString | string[]; // markers markers?: ChartMarkers; /** * x bar length for `bar` charts. * If it's zero, it's calculated automatically in order to fill the complete x-space. */ barWidth?: uint | ExprString; // points pointMaxHeight?: uint | ExprString; /** * x distance between two data points. * If it's zero, it's calculated automatically in order to fill the complete x-space. * If the chart includes bars charts it must be big enough to include all the bars. */ pointDistance?: uint | ExprString; /** * x space between two bars. Used only in `bar` charts. */ seriesSpacing?: uint | ExprString; // colors /** * Colors to be used in case of the data point is negative. * At the moment, it only supports `bar` charts. */ negativeFillColors?: string | string[] | string[][]; xAxis?: ChartLine; yAxis?: ChartLine; y0Line?: ChartLine; // limits maxValue?: number | ExprString; minValue?: number | ExprString; // animation pointHeightStart?: number | ExprString; deviationStart?: number | ExprString; sweepStart?: number | ExprString; } // #export-section-end: release // ------------------------------- // ------------------------------------------------------------------------ // Implementation // ------------------------------------------------------------------------ pluginManager.addPlugin({ id: 'abeamer.chart-tasks', uuid: '73631f28-df71-4b4d-88e1-c99a858e0fd3', author: 'Alexandre Bento Freire', email: 'abeamer@a-bentofreire.com', jsUrls: ['plugins/chart-tasks/chart-tasks.js'], teleportable: true, }); const _defValues = getVars()['chart'] = { labelsX: { fontFamily: 'sans-serif', fontColor: 'black', fontSize: 12, alignment: ChartCaptionAlignment.center, position: ChartCaptionPosition.bottom, orientation: ChartCaptionOrientation.horizontal, marginBefore: 0, marginAfter: 0, }, labelsY: { fontFamily: 'sans-serif', fontColor: 'black', fontSize: 12, alignment: ChartCaptionAlignment.right, position: ChartCaptionPosition.left, orientation: ChartCaptionOrientation.horizontal, marginBefore: 0, marginAfter: 5, tickCount: 6, }, legend: { fontFamily: 'sans-serif', fontColor: 'black', fontSize: 12, alignment: ChartCaptionAlignment.left, position: ChartCaptionPosition.right, orientation: ChartCaptionOrientation.horizontal, marginBefore: 0, marginAfter: 5, mark: { width: 10, height: 3, spacing: 4, }, }, title: { fontFamily: 'sans-serif', fontColor: 'black', fontSize: 14, alignment: ChartCaptionAlignment.center, position: ChartCaptionPosition.top, orientation: ChartCaptionOrientation.horizontal, marginBefore: 0, marginAfter: 0, }, fillColors: '#ffecad', strokeColors: '#101010', strokeWidth: 1, markers: { shape: ChartPointShape.square, size: 5, color: 'black', }, barWidth: 0, pointMaxHeight: 100, pointDistance: 0, seriesSpacing: 3, nrPoints: 10, } as ChartDefaults; /** * Returns the maximum value of array of array of numbers. */ function _maxOfArrayArray(data: number[][], startValue: number): number { data.forEach(series => { series.forEach(point => { startValue = Math.max(startValue, point); }); }); return startValue; } // ------------------------------------------------------------------------ // _ChartVirtualAnimator // ------------------------------------------------------------------------ class _ChartVirtualAnimator extends SimpleVirtualAnimator implements VirtualAnimator { charts: _WkChart[] = []; params: BaseChartTaskParams; animateProps(): void { this.charts.forEach(chart => { chart._drawChart(this.params); }); } } // ------------------------------------------------------------------------ // Captions // ------------------------------------------------------------------------ interface _WkChartCaptions { fontColor?: string; fontFamily?: string; fontSize?: uint; marginBefore?: uint; marginAfter?: uint; alignment?: ChartCaptionAlignment; orientation?: uint; position?: uint; width?: uint; height?: uint; x?: uint; y?: uint; } function _setUpCaptionsFont(l: _WkChartCaptions, ctx: CanvasRenderingContext2D): void { ctx.font = `${l.fontSize}px ${l.fontFamily}`; ctx.fillStyle = l.fontColor; ctx.textBaseline = 'bottom'; } // ------------------------------------------------------------------------ // Labels // ------------------------------------------------------------------------ interface _WkChartLabels extends _WkChartCaptions { captions?: string[]; } function _ExprStrToLabels<T extends ChartLabels>(l: T | ExprString | string[]): T { switch (typeof l) { case 'undefined': return {} as T; case 'string': return { captions: l as string } as T; default: return l as T; } } export let testDiv: HTMLDivElement; function _alignCaptions(l: _WkChartCaptions, ctx: CanvasRenderingContext2D, text: string, width: uint): uint { if (l.alignment === ChartCaptionAlignment.left) { return 0; } // let style: CSSStyleDeclaration; // if (!testDiv) { // testDiv = document.createElement('div'); // style = testDiv.style; // style.position = 'absolute'; // style.top = '0px'; // style.left = '0px'; // style.width = '1px'; // style.height = '0px'; // document.body.appendChild(testDiv); // } // style = testDiv.style; // style.display = 'inline-block'; // style.fontFamily = l.fontFamily; // style.fontSize = l.fontSize + 'px'; // testDiv.textContent = text; // style.display = 'none'; // @TODO: Implement a better way to compute the text height const sz = ctx.measureText(text); switch (l.alignment) { case ChartCaptionAlignment.center: return (width - sz.width) / 2; case ChartCaptionAlignment.right: return (width - sz.width); } return 0; } // ------------------------------------------------------------------------ // Line // ------------------------------------------------------------------------ interface _WkChartLine { visible: boolean; color: string; width: number; } // ------------------------------------------------------------------------ // Points // ------------------------------------------------------------------------ interface _WkChartTitle extends _WkChartCaptions { caption?: string; } // ------------------------------------------------------------------------ // Markers // ------------------------------------------------------------------------ interface _WkChartMarkers { visible?: boolean[][]; shape?: ChartPointShape[][]; size?: uint[][]; color?: string[][]; } // ------------------------------------------------------------------------ // Legend // ------------------------------------------------------------------------ interface _WkChartLegendMark { width: uint; height: uint; spacing: uint; } interface _WkChartLegend extends _WkChartCaptions { captions?: string[]; mark?: _WkChartLegendMark; } // ------------------------------------------------------------------------ // _WkChart // ------------------------------------------------------------------------ type _WkSeriesData = number[]; abstract class _WkChart { protected props: AnyParams; protected canvas: HTMLCanvasElement; protected context: CanvasRenderingContext2D; protected chartWidth: uint; protected chartHeight: uint; protected chartType: ChartTypes; protected min: number; protected max: number; protected sum: number; protected avg: number; protected nrPoints: uint; protected data: _WkSeriesData[]; protected animator: _ChartVirtualAnimator; // title protected title: _WkChartTitle = {}; // legends protected legend: _WkChartLegend = {}; // colors fillColors: string[][]; strokeColors: string[][]; strokeWidth: uint[][]; // overflow overflow: uint = 0; // graph (x0, y0) = (left, bottom) graphX0: uint = 0; graphY0: uint; graphX1: uint; graphY1: uint = 0; constructor(protected args: ABeamerArgs) { } _drawChart(_params: BaseChartTaskParams): void { this._drawLegend(); } protected _fillArrayArrayParam<TI, TO>(param: TI | TI[] | TI[][], defValue: TI, strMapper?: any): TO[][] { const res: TO[][] = []; if (param === undefined) { param = defValue; } const isParamArray = Array.isArray(param); if (!isParamArray && strMapper && typeof param === 'string') { param = strMapper[param]; } this.data.forEach((series, seriesI) => { let resItem = []; if (!isParamArray) { resItem = series.map(_v => param); } else { let subParam = param[seriesI]; const isSubParamArray = Array.isArray(subParam); if (!isSubParamArray && strMapper && typeof subParam === 'string') { subParam = strMapper[subParam]; } if (!isSubParamArray) { resItem = series.map(_v => subParam); } else { resItem = series.map((_v, i) => { let itemParam = subParam[i]; if (strMapper && typeof itemParam === 'string') { itemParam = strMapper[itemParam]; } return itemParam; }); } } res.push(resItem); }); return res; } _initChart(params: BaseChartTaskParams): void { // colors this.fillColors = this._fillArrayArrayParam(params.fillColors, _defValues.fillColors); this.strokeColors = this._fillArrayArrayParam(params.strokeColors, _defValues.strokeColors); this.strokeWidth = this._fillArrayArrayParam(params.strokeWidth, _defValues.strokeWidth); this.overflow = _maxOfArrayArray(this.strokeWidth, this.overflow); this.graphX1 = this.chartWidth; this.graphY0 = this.chartHeight; this._initTitle(params); this._initLegend(params); } _init(elAdapter: ElementAdapter, chartType: ChartTypes, animator: _ChartVirtualAnimator | undefined): void { this.canvas = elAdapter.getProp('element', this.args) as any; if (!this.canvas) { throwErr(`Didn't find the ${elAdapter.getId()}`); } this.context = this.canvas.getContext('2d'); this.chartWidth = this.canvas.width; this.chartHeight = this.canvas.height; this.chartType = chartType; this.animator = animator; this.props = animator ? animator.props : {}; } _initData(data: SeriesData[]): void { let max = -Number.MIN_VALUE; let min = Number.MAX_VALUE; let sum = 0; let nrPoints; this.data = data.map((series, seriesI) => { let res: _WkSeriesData; if (Array.isArray(series)) { res = series as _WkSeriesData; } else { res = []; const exprSeries = series as ExprSeries; const v0 = exprSeries.startValue || 0; const step = exprSeries.step || 1; const nrPts = exprSeries.nrPoints || nrPoints || _defValues.nrPoints; this.args.vars.n = nrPts; for (let i = 0; i < nrPts; i++) { this.args.vars.v = i * step + v0; const v1 = calcExpr(exprSeries.expr, this.args); res.push(typeof v1 === 'number' ? v1 : parseFloat(v1 as string)); } } if (!seriesI) { nrPoints = res.length; } else { if (res.length !== nrPoints) { throwErr(`Every Series must have the same number of points`); } } return res; }); this.data.forEach(series => { series.forEach(point => { max = Math.max(max, point); min = Math.min(min, point); sum += point; }); }); this.min = min; this.max = max; this.sum = sum; this.avg = (max - min) / 2; this.nrPoints = nrPoints; } protected _initCaptions(defaults: ChartCaptions, captions: string[], labThis: ChartLabels, labOther: ChartLabels): _WkChartCaptions { const res: _WkChartCaptions = { fontColor: ExprOrStrToStr(labThis.fontColor || labOther.fontColor, defaults.fontColor, this.args), fontFamily: ExprOrStrToStr(labThis.fontFamily || labOther.fontFamily, defaults.fontFamily, this.args), fontSize: ExprOrNumToNum(labThis.fontSize || labOther.fontSize, defaults.fontSize as number, this.args), alignment: parseEnum(labThis.alignment, ChartCaptionAlignment, defaults.alignment), position: parseEnum(labThis.position, ChartCaptionPosition, defaults.position), orientation: parseEnum(labThis.orientation, ChartCaptionOrientation, defaults.orientation), marginBefore: ExprOrNumToNum(labThis.marginBefore, defaults.marginBefore as number, this.args), marginAfter: ExprOrNumToNum(labThis.marginAfter, defaults.marginAfter as number, this.args), }; _setUpCaptionsFont(res, this.context); const isHorizontal = res.position === ChartCaptionPosition.top || res.position === ChartCaptionPosition.bottom; if (isHorizontal) { const joinedText = captions.join(' '); const sz = this.context.measureText(joinedText); res.width = sz.width; } else { res.width = 0; captions.forEach(caption => { res.width = Math.max(res.width, this.context.measureText(caption).width); }); } res.height = res.fontSize * 1.2; let d: uint; switch (res.position) { case ChartCaptionPosition.top: res.y = this.graphY1 + res.height + res.marginBefore; d = res.height + res.marginBefore + res.marginAfter; this.graphY1 += d; break; case ChartCaptionPosition.left: res.x = this.graphX0 + res.marginBefore; d = res.width + res.marginBefore + res.marginAfter; this.graphY0 = Math.min(this.graphY0, this.chartHeight - res.height / 2); this.graphX0 += d; break; case ChartCaptionPosition.bottom: res.y = this.graphY0 - res.marginAfter; d = res.height + res.marginBefore + res.marginAfter; this.graphY0 -= d; break; case ChartCaptionPosition.right: d = res.width + res.marginBefore + res.marginAfter; res.x = this.graphX1 + res.marginBefore - d; this.graphY0 = Math.min(this.graphY0, this.chartHeight - res.height / 2); this.graphX1 -= d; break; } return res; } protected _initTitle(params: AxisChartTaskParams): void { let title = params.title || {} as ChartTitle; if (typeof title === 'string') { title = { caption: title as string, }; } if (title.caption) { this.title = this._initCaptions(_defValues.title, [title.caption], title, title); this.title.caption = ExprOrStrToStr(title.caption, '', this.args); } } protected _initLegend(params: AxisChartTaskParams): void { const pLegend = _ExprStrToLabels(params.legend); const captions: any = pLegend.captions; if (captions) { this.legend = this._initCaptions(_defValues.legend, captions, pLegend, pLegend); this.legend.captions = captions; const defMark = _defValues.legend.mark; const pMark = pLegend.mark || {} as ChartLegendMark; this.legend.mark = { width: ExprOrNumToNum(pMark.width, defMark.width as number, this.args), height: ExprOrNumToNum(pMark.height, defMark.height as number, this.args), spacing: ExprOrNumToNum(pMark.spacing, defMark.spacing as number, this.args), }; const markWidAndSpace = this.legend.mark.width + this.legend.mark.spacing; switch (this.legend.position) { case ChartCaptionPosition.left: this.legend.x += markWidAndSpace; this.graphX0 += markWidAndSpace; break; case ChartCaptionPosition.right: this.graphX1 -= markWidAndSpace; break; } } } protected _getLegendColor(seriesI: uint, i: uint): string { return this.fillColors[seriesI][i]; } protected _drawLegend(): void { const legend = this.legend; if (legend.captions) { const ctx = this.context; const mark = legend.mark; const x = legend.x; const y0 = legend.height; const h = legend.height; const isPointLegend = this.data.length === 1; legend.captions.forEach((caption, i) => { const y = y0 + i * h; _setUpCaptionsFont(legend, ctx); const deltaX = _alignCaptions(legend, ctx, caption, legend.width); ctx.fillText(caption, x + deltaX, y); ctx.fillStyle = isPointLegend ? this._getLegendColor(0, i) : this._getLegendColor(i, 0); ctx.fillRect(x + deltaX - mark.width - mark.spacing, y - (h + mark.height) / 2, mark.width, mark.height); }); } } } // ------------------------------------------------------------------------ // calcBestMax // ------------------------------------------------------------------------ function _calcBestMax(v): number { const vAbs = Math.abs(v); const isNegative = v < 0; const l10v = Math.log10(vAbs); const l10vf = Math.floor(l10v); const vBase = 10 ** l10vf; const vSubDigits = vAbs % vBase; if (Math.abs(vSubDigits) > 0.00001) { const vLow = vAbs - vSubDigits; const vHigh = (isNegative ? -vLow + vBase : vLow + vBase); return vHigh; // console.log(v, l10v, l10vf, vSubDigits, vLow, vHigh); } else { return v; // console.log(v); } } // ------------------------------------------------------------------------ // Axis Chart // ------------------------------------------------------------------------ interface XDrawPoint { x: uint; xLabel: uint; xLabelWidth: uint; series: { x: uint, w: uint }[]; } class _WkAxisChart extends _WkChart { /** Chart Type per series. Use only if chartType is `mixed`. */ chartTypes: ChartTypes[]; // axis xAxis: _WkChartLine; yAxis: _WkChartLine; y0Line: _WkChartLine; // draw points xDrawPoints: XDrawPoint[] = []; x1: uint; // labels X labelsX: _WkChartLabels; // labels Y labelsY: _WkChartLabels; // markers markers: _WkChartMarkers; hasMarkers: boolean; // points pointMaxHeight: uint; // colors negativeFillColors: string[][]; // limits maxValue: number; bestMaxValue: number; minValue: number; avgValue: number; protected _calcCaptions(captions: string | string[], count: uint, min: number, max: number): string[] { const strCaption = captions as string; if (!strCaption || !Array.isArray(strCaption)) { const isCaptionsExpr = isExpr(strCaption as string); const newCaptions = []; const delta = (max - min) / (count - 1); for (let i = 0; i < count; i++) { const v = min + i * delta; if (isCaptionsExpr) { this.args.vars['v'] = v; const v1 = calcExpr(strCaption as string, this.args); newCaptions.push(v1.toString()); } else { newCaptions.push(v.toString()); } } captions = newCaptions; } return captions as string[]; } protected _initLabels(params: AxisChartTaskParams): void { const labelsX: ChartLabelsX = _ExprStrToLabels(params.labelsX); const labelsY: ChartLabelsY = _ExprStrToLabels(params.labelsY); let captions; // labels X captions = labelsX.captions; if (captions) { captions = this._calcCaptions(captions, this.nrPoints, 0, this.nrPoints - 1); this.labelsX = this._initCaptions(_defValues.labelsX, captions, labelsX, labelsY); this.labelsX.captions = captions; } // labels Y captions = labelsY.captions; if (labelsY.tickCount !== 0 || captions) { captions = this._calcCaptions(captions, labelsY.tickCount || _defValues.labelsY.tickCount, this.minValue, this.maxValue); this.labelsY = this._initCaptions(_defValues.labelsY, captions, labelsY, labelsX); this.labelsY.captions = captions; // in case there is no title make sure there is enough space for the labelsY const heightDiv2 = this.labelsY.height / 2; this.graphY1 = Math.max(this.graphY1, heightDiv2); } } protected _getLegendColor(seriesI: uint, i: uint): string { return this.chartTypes[seriesI] !== ChartTypes.line ? this.fillColors[seriesI][i] : this.strokeColors[seriesI][i]; } protected _initLine(line: ChartLine): _WkChartLine { return { visible: line.visible !== undefined ? line.visible : true, color: ExprOrStrToStr(line.color, '#7c7c7c', this.args), width: ExprOrNumToNum(line.width, 1, this.args), }; } protected _initMarkers(params: AxisChartTaskParams): void { const markers: _WkChartMarkers = {}; this.hasMarkers = params.markers !== undefined || this.chartTypes .findIndex(cType => cType === ChartTypes.marker) !== -1; const pMarkers = params.markers || {}; if (this.hasMarkers) { markers.visible = this._fillArrayArrayParam<boolean, boolean>( pMarkers.visible, this.chartType === ChartTypes.marker); markers.shape = this._fillArrayArrayParam<ChartPointShape | string, ChartPointShape>( pMarkers.shape, _defValues.markers.shape as ChartPointShape, ChartPointShape); markers.size = this._fillArrayArrayParam<uint, uint>( pMarkers.size, _defValues.markers.size as uint); markers.color = this._fillArrayArrayParam<string, string>( pMarkers.color, _defValues.markers.color as string); this.overflow = _maxOfArrayArray(markers.size, this.overflow); } this.markers = markers; } protected _drawMarkers(dataPixels: int[][][]): void { const points = this.markers; const ctx = this.context; this.data.forEach((series, seriesI) => { for (let i = 0; i < series.length; i++) { if (points.visible[seriesI][i]) { ctx.fillStyle = points.color[seriesI][i]; const size = points.size[seriesI][i]; const sizeDiv2 = size / 2; const [x, y] = dataPixels[seriesI][i]; switch (points.shape[seriesI][i]) { case ChartPointShape.circle: ctx.beginPath(); ctx.arc(x, y, sizeDiv2, 0, Math.PI * 2); ctx.fill(); break; case ChartPointShape.diamond: ctx.beginPath(); ctx.moveTo(x - sizeDiv2, y); ctx.lineTo(x, y - sizeDiv2); ctx.lineTo(x + sizeDiv2, y); ctx.lineTo(x, y + sizeDiv2); ctx.fill(); break; case ChartPointShape.square: ctx.fillRect(x - sizeDiv2, y - sizeDiv2, sizeDiv2, sizeDiv2); break; } } } }); } protected _drawLine(line: _WkChartLine, x0: uint, y0: uint, x1: uint, y1: uint): void { const ctx = this.context; ctx.beginPath(); ctx.strokeStyle = line.color; ctx.lineWidth = line.width; ctx.moveTo(x0, y0); ctx.lineTo(x1, y1); ctx.stroke(); } protected _computeBestValues(): void { this.bestMaxValue = _calcBestMax(this.max); } protected _computeDrawPoints(params: AxisChartTaskParams): void { this.pointMaxHeight = ExprOrNumToNum(params.pointMaxHeight, _defValues.pointMaxHeight, this.args); const x0 = this.graphX0 + this.overflow; const x1 = this.graphX1 - this.overflow; const xWidth = x1 - x0; const nrPoints = this.nrPoints; const pointArea = xWidth / nrPoints; let pointDistance = ExprOrNumToNum(params.pointDistance, _defValues.pointDistance, this.args); pointDistance = pointDistance || pointArea; let x = x0; const barChartCount = this.chartTypes.reduce((acc, v) => acc + (v === ChartTypes.bar ? 1 : 0)); if (barChartCount === 0) { for (let i = 0; i < nrPoints; i++) { const xMidPoint = x + pointDistance / 2; this.xDrawPoints.push({ x, xLabel: x, xLabelWidth: pointDistance, series: this.data.map(() => { return { x: xMidPoint, w: pointDistance }; }), }); x += pointDistance; } } else { // charts with bars required a special calculation let barWidth = ExprOrNumToNum(params.barWidth, _defValues.barWidth, this.args); const seriesSpacing = ExprOrNumToNum(params.seriesSpacing, _defValues.seriesSpacing, this.args); if (!barWidth) { barWidth = (pointDistance / barChartCount) - seriesSpacing; } const usedPointWidth = barWidth * barChartCount + seriesSpacing * (barChartCount - 1); for (let i = 0; i < nrPoints; i++) { let xBar = x; const xMidPoint = x + pointDistance / 2; this.xDrawPoints.push({ x, xLabel: x, xLabelWidth: usedPointWidth, series: this.data.map((_series, seriesI) => { if (this.chartTypes[seriesI] === ChartTypes.bar) { const xBarThis = xBar; xBar += barWidth + seriesSpacing; return { x: xBarThis, w: barWidth }; } return { x: xMidPoint, w: pointDistance }; }), }); x += pointDistance; } } this.x1 = x; } /** Initializes all the Axis Chart parameters. */ _initChart(params: AxisChartTaskParams): void { this.chartTypes = this.data.map((_series, seriesIndex) => { if (this.chartType !== ChartTypes.mixed) { return this.chartType; } if (!params.chartTypes || params.chartTypes.length <= seriesIndex) { return ChartTypes.bar; } return parseEnum(params.chartTypes[seriesIndex], ChartTypes, ChartTypes.bar); }); // axis this.xAxis = this._initLine(params.xAxis || {}); this.yAxis = this._initLine(params.yAxis || {}); this.y0Line = this._initLine(params.y0Line || {}); // limits this._computeBestValues(); this.maxValue = ExprOrNumToNum(params.maxValue, this.bestMaxValue, this.args); this.minValue = ExprOrNumToNum(params.minValue, Math.min(this.min, 0), this.args); this.avgValue = this.avg; super._initChart(params); // colors this.negativeFillColors = !params.negativeFillColors ? this.fillColors : this._fillArrayArrayParam<string, string>(params.negativeFillColors, 'white'); this._initMarkers(params); this._initLabels(params); this._computeDrawPoints(params); // animation this.props['point-height'] = ExprOrNumToNum(params.pointHeightStart, 1, this.args); this.props['deviation'] = ExprOrNumToNum(params.deviationStart, 1, this.args); this.props['sweep'] = ExprOrNumToNum(params.sweepStart, 1, this.args); } /** Implements Axis Chart animation. */ _drawChart(params: AxisChartTaskParams): void { const pointHeight = this.props['point-height']; const deviationV = this.props['deviation']; const sweepV = this.props['sweep']; const chartWidth = this.chartWidth; const chartHeight = this.chartHeight; const ctx = this.context; const x0 = this.graphX0; const y0 = this.graphY0; const y1 = this.graphY1; const topMargin = 1; const yLength = y0 - y1 - topMargin; // values const maxValue = this.maxValue; const minValue = this.minValue; const valueRange = maxValue - minValue; // y0 line const hasY0Line = maxValue * minValue < 0; const vy0Line = hasY0Line ? 0 : minValue >= 0 ? minValue : maxValue; const vy0LineClip = (vy0Line - minValue) / valueRange; const axis0Y = y0 - yLength * vy0LineClip; // data const data = this.data; const nrPoints = this.nrPoints; const drawNrPoints = sweepV >= 1 ? nrPoints : Math.max(Math.min(Math.floor(nrPoints * sweepV) + 1, nrPoints), 0); ctx.clearRect(0, 0, chartWidth, chartHeight); super._drawChart(params); const y = axis0Y; const dataMidPixels: int[][][] = []; // data points data.forEach((series, seriesI) => { let xPrev: int; let yPrev: int; const seriesPixels: int[][] = []; const seriesMidPixels: int[][] = []; const chartType = this.chartTypes[seriesI]; for (let i = 0; i < drawNrPoints; i++) { ctx.lineWidth = this.strokeWidth[seriesI][i]; ctx.strokeStyle = this.strokeColors[seriesI][i]; let v = series[i]; if (Math.abs(deviationV - 1) > 1e-6) { v = this.avgValue - ((this.avgValue - v) * deviationV); } ctx.fillStyle = v >= 0 ? this.fillColors[seriesI][i] : this.negativeFillColors[seriesI][i]; const xDrawPoint = this.xDrawPoints[i].series[seriesI]; // values const vClip = (v - vy0Line) / valueRange; const vT = vClip * pointHeight; // y const yLen = -yLength * vT; let yNew = yLen + y; // x const x = xDrawPoint.x; let xNew = x; const isSweeping = (i === drawNrPoints - 1) && (sweepV < 1); if (isSweeping) { const leftSweep = (sweepV - i / nrPoints); const reSweep = leftSweep / (1 / nrPoints); xNew = ((xNew - xPrev) * reSweep) + xPrev; yNew = ((yNew - yPrev) * reSweep) + yPrev; } let xMidNew = xNew; const yMidNew = yNew; switch (chartType) { case ChartTypes.bar: let barWidth = xDrawPoint.w; if (isSweeping) { const xSeriesDrawPt = this.xDrawPoints[i]; const xMaxSweepPos = xSeriesDrawPt.xLabel + xSeriesDrawPt.xLabelWidth * sweepV; if (xMaxSweepPos < x) { barWidth = 0; } else { barWidth = Math.min(x + barWidth, xMaxSweepPos) - x; } } if (barWidth > 0) { ctx.fillRect(x, y, barWidth, yLen); ctx.strokeRect(x, y, barWidth, yLen); } xMidNew = x + barWidth / 2; break; case ChartTypes.line: if (i) { ctx.beginPath(); ctx.moveTo(xPrev, yPrev); ctx.lineTo(xNew, yNew); ctx.stroke(); } break; } xPrev = xNew; yPrev = yNew; seriesPixels.push([xNew, yNew]); seriesMidPixels.push([xMidNew, yMidNew]); } if (chartType === ChartTypes.area) { ctx.beginPath(); ctx.moveTo(seriesPixels[0][0], y); seriesPixels.forEach(point => { ctx.lineTo(point[0], point[1]); }); ctx.lineTo(seriesPixels[seriesPixels.length - 1][0], y); ctx.lineTo(seriesPixels[0][0], y); ctx.fill(); ctx.stroke(); } dataMidPixels.push(seriesMidPixels); }); ctx.lineWidth = 1; // markers if (this.hasMarkers) { this._drawMarkers(dataMidPixels); } // titles const titleCaption = this.title.caption; if (this.title.caption) { _setUpCaptionsFont(this.title, ctx); const titleXPos = _alignCaptions(this.title, ctx, titleCaption, this.x1 - this.graphX0); ctx.fillText(titleCaption, this.graphX0 + titleXPos, this.title.y); } let captions: string[]; // labelsX if (this.labelsX) { _setUpCaptionsFont(this.labelsX, ctx); captions = this.labelsX.captions; for (let i = 0; i < captions.length; i++) { const x = this.xDrawPoints[i].xLabel; const text = captions[i]; const deltaX = _alignCaptions(this.labelsX, ctx, text, this.xDrawPoints[i].xLabelWidth); ctx.fillText(text, x + deltaX, this.labelsX.y); } } // labelsY if (this.labelsY) { _setUpCaptionsFont(this.labelsY, ctx); captions = this.labelsY.captions; const fs2 = this.labelsY.height / 2; const scale = yLength / (captions.length - 1); for (let i = 0; i < captions.length; i++) { const yi = y0 - scale * i; const text = this.labelsY.captions[i]; const deltaX = _alignCaptions(this.labelsY, ctx, text, this.labelsY.width); ctx.fillText(text, this.labelsY.x + deltaX, yi + fs2); } } // y0Line if (hasY0Line && this.y0Line.visible) { this._drawLine(this.y0Line, x0, axis0Y, this.x1, axis0Y); } // x-axis if (this.xAxis.visible) { this._drawLine(this.xAxis, x0, y0, this.x1, y0); } // y-axis if (this.yAxis.visible) { this._drawLine(this.yAxis, x0, y0, x0, y0 - yLength); } } } // ------------------------------------------------------------------------ // Pie Chart // ------------------------------------------------------------------------ class _WkPieChart extends _WkChart { _initChart(params: PieChartTaskParams): void { super._initChart(params); // animation this.props['angle'] = ExprOrNumToNum(params.angleStart, 0, this.args); this.props['dispersion'] = ExprOrNumToNum(params.dispersionStart, 1, this.args); } _drawChart(params: PieChartTaskParams): void { const angle = this.props['angle']; const dispersion = this.props['dispersion']; const isClockwise = params.isClockwise !== false; const overflow = this.overflow; const x0 = this.graphX0 + overflow; const y1 = this.graphY1 + overflow; const diameter = Math.min(this.graphX1 - x0 - overflow, this.graphY0 - y1 - overflow); const radius = diameter / 2; const ctx = this.context; ctx.clearRect(0, 0, this.chartWidth, this.chartHeight); super._drawChart(params); this.data.forEach((series, seriesI) => { for (let stage = 0; stage < 2; stage++) { let startAngle = angle; for (let i = 0; i < series.length; i++) { ctx.lineWidth = this.strokeWidth[seriesI][i]; ctx.strokeStyle = this.strokeColors[seriesI][i]; ctx.fillStyle = this.fillColors[seriesI][i]; const point = series[i]; const percentage = point / this.sum; let endAngle = (percentage * Math.PI * 2 * dispersion); if (!isClockwise) { endAngle = -endAngle; } endAngle += startAngle; ctx.beginPath(); ctx.moveTo(x0 + radius, y1 + radius); ctx.arc(x0 + radius, y1 + radius, radius, startAngle, endAngle); ctx.closePath(); if (stage === 0) { ctx.fill(); } else { ctx.stroke(); } startAngle = endAngle; } } }); } } // ------------------------------------------------------------------------ // Chart Task // ------------------------------------------------------------------------ pluginManager.addTasks([['chart', _chartTask]]); /** Implements the Chart Task */ function _chartTask(anime: Animation, _wkTask: WorkTask, params: BaseChartTaskParams, stage: uint, args: ABeamerArgs): TaskResult { switch (stage) { case TS_INIT: let cType = params.chartType; if (typeof cType === 'string') { cType = ChartTypes[cType] as ChartTypes; } const data = params.data; if (!data.length) { throwErr(`Series have empty data`); } let animator: _ChartVirtualAnimator; if (params.animeSelector) { animator = new _ChartVirtualAnimator(); animator.selector = params.animeSelector; animator.params = params; args.story.addVirtualAnimator(animator); } const elAdapters = args.scene.getElementAdapters(anime.selector); args.vars.elCount = elAdapters.length; elAdapters.forEach((elAdapter, elIndex) => { args.vars.elIndex = elIndex; let chart: _WkChart; switch (cType) { case ChartTypes.pie: chart = new _WkPieChart(args); break; case ChartTypes.marker: case ChartTypes.bar: case ChartTypes.line: case ChartTypes.area: case ChartTypes.mixed: chart = new _WkAxisChart(args); break; default: throwI8n(Msgs.UnknownType, { p: params.chartType }); } chart._init(elAdapter, cType as ChartTypes, animator); chart._initData(data); chart._initChart(params); chart._drawChart(params); if (animator) { animator.charts.push(chart); } }); break; } return TR_EXIT; } // ------------------------------------------------------------------------ // Testing // ------------------------------------------------------------------------ /* const testValues = [3.33, 8.4, 10, 12, 45, 0.12, 100, 1000, 12400, 95000, -10, -12, -89.3, -3.4, -400]; testValues.forEach(v => { _calcBestMax(v); }); */ }
the_stack
import * as React from 'react'; import { range } from 'lodash'; import { FormattedMessage, injectIntl } from 'react-intl'; // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore import dayjs from 'dayjs'; import { DayKey, TimeWindowProps, State, DayOptions, TimeWindowTexts } from './TimeWindow.types'; import * as S from './TimeWindow.styles'; import { getDateFromDayValue } from './utils'; import Grid from './Grid/Grid'; import SelectionCount from '../SelectionCount/SelectionCount'; import { FilterDefinition } from '../../RangeFilter.types'; import { DEFAULT_RANGE_END, DEFAULT_RANGE_START, TIME_FORMAT } from '../../constants'; import AddButton from '../AddButton/AddButton'; import RangeFormContainer from './RangeFormContainer/RangeFormContainer'; import Day from './Day/Day'; import SelectionHint from '../SelectionHint/SelectionHint'; import { DateLimitMode } from './RangeFormContainer/RangeForm/RangeForm.types'; export const DEFAULT_LIMIT_MODE: DateLimitMode = 'Range'; class TimeWindowBase extends React.PureComponent<TimeWindowProps, State> { // eslint-disable-next-line react/destructuring-assignment state: State = { activeDays: this.props.daily ? [0] : [], controlKeyPressed: false }; private wrapperRef = React.createRef<HTMLDivElement>(); static defaultProps: Partial<TimeWindowProps> = { days: {}, numberOfDays: 1, showSelectAll: false, valueSelectionModes: ['Range', 'Hour'], dayTemplate: (index): { dayOfWeek: number } => ({ dayOfWeek: Number(index) + 1 }), dayFormatter: (dayKey: DayKey): React.ReactNode => ( <FormattedMessage id={`DS.DATE-RANGE-PICKER.WEEKDAYS-SHORT-${dayKey}`} /> ), }; componentDidMount(): void { const wrapper = this.wrapperRef; if (wrapper?.current && wrapper.current !== null) { // focus on wrapper to enable listening for keydown without having to click on wrapper wrapper.current.focus(); } } componentDidUpdate(prevProps: Readonly<TimeWindowProps>, prevState: Readonly<State>): void { const hasCommonRange = this.haveActiveDaysCommonRange(); if (prevState.isRangeDefined !== hasCommonRange) { // eslint-disable-next-line react/no-did-update-set-state this.setState(state => ({ ...state, isRangeDefined: hasCommonRange })); } } isDayRestricted = (dayKey: DayKey): boolean => { const { days } = this.props; return !!days[dayKey] && days[dayKey].restricted; }; checkActiveDay = (dayKey: DayKey): void => { const { isRangeDefined } = this.state; if (!this.isDayRestricted(dayKey) && isRangeDefined && !this.haveActiveDaysCommonRange()) this.checkDay(dayKey); const { activeDays, controlKeyPressed, shiftKeyPressed } = this.state; let updatedActiveDay: DayKey[] = []; if (controlKeyPressed) { updatedActiveDay = activeDays.includes(dayKey) ? activeDays : [...activeDays, dayKey]; } else if (activeDays.length > 0 && shiftKeyPressed) { updatedActiveDay = activeDays[0] < dayKey ? range(+activeDays[0], +dayKey + 1) : range(+dayKey, +activeDays[0] + 1); } else { updatedActiveDay = [dayKey]; } this.setState(state => ({ ...state, activeDays: updatedActiveDay })); }; uncheckActiveDay = (dayKey: DayKey): void => { const { activeDays, controlKeyPressed } = this.state; let updatedActiveDay: DayKey[] = []; if (controlKeyPressed) { updatedActiveDay = activeDays.filter(day => day !== dayKey); } this.setState(state => ({ ...state, activeDays: updatedActiveDay })); this.removeDaySelection(dayKey); }; handleToggleDay = (dayKey: DayKey, forcedState?: boolean): void => { const { activeDays, controlKeyPressed } = this.state; if (typeof forcedState !== 'undefined') { if (controlKeyPressed && forcedState) { activeDays.includes(dayKey) ? this.uncheckActiveDay(dayKey) : this.checkActiveDay(dayKey); return; } forcedState ? this.checkActiveDay(dayKey) : this.uncheckActiveDay(dayKey); } else { activeDays.includes(dayKey) ? this.uncheckActiveDay(dayKey) : this.checkActiveDay(dayKey); } }; handleDayChange = (dayKey: DayKey, dayChanges: Partial<DayOptions>): void => { const { onChange, days } = this.props; onChange({ ...days, [dayKey]: { ...this.getDayValue(dayKey), ...(dayChanges as DayOptions), }, }); }; removeDaySelection = (dayKey: DayKey): void => { const { onChange, days } = this.props; const updatedDays = days; delete updatedDays[dayKey]; onChange(updatedDays); }; checkDay = (dayKey: DayKey): void => { const { onCheckDay } = this.props; this.handleDayChange(dayKey, { start: DEFAULT_RANGE_START, stop: DEFAULT_RANGE_END, restricted: true, display: true, }); onCheckDay && onCheckDay(dayKey); }; handleDayTimeChange = (value: [Date, Date], dayKey: DayKey): void => { this.handleDayChange(dayKey, { restricted: true, start: dayjs(value[0]).format(TIME_FORMAT), stop: dayjs(value[1]).format(TIME_FORMAT), }); }; handleMultipleDayTimeChange = (value: [Date, Date]): void => { const { onChange, days } = this.props; const { activeDays } = this.state; const updatedDays = {}; activeDays.forEach(k => { updatedDays[k] = { day: k, start: dayjs(value[0]).format(TIME_FORMAT), stop: dayjs(value[1]).format(TIME_FORMAT), restricted: true, }; }); onChange({ ...days, ...updatedDays }); }; handleRangeDelete = (): void => { const { onChange, days } = this.props; const { activeDays } = this.state; const updatedDays = days; activeDays.forEach(k => { delete updatedDays[k]; }); onChange({ ...updatedDays }); }; handleClearSelection = (): void => { this.setState({ activeDays: [] }); }; handleSelectAll = (): void => { const keys = this.getAllKeys(); const { onSelectAll } = this.props; this.setState({ activeDays: keys }, () => { onSelectAll && onSelectAll(); }); }; getDayValue = (dayKey: DayKey): Partial<FilterDefinition> => { const { days, dayTemplate, customDays, daily, valueSelectionModes } = this.props; let dayValue = {}; if (daily) dayValue = days; else if (days[dayKey]) dayValue = days[dayKey]; else if (typeof dayKey === 'number') dayValue = dayTemplate(dayKey); else if (customDays && customDays[dayKey]?.template && customDays[dayKey]?.template !== null) { dayValue = customDays[dayKey].template as object; } return { start: DEFAULT_RANGE_START, stop: DEFAULT_RANGE_END, restricted: false, display: false, inverted: false, mode: valueSelectionModes[0] || DEFAULT_LIMIT_MODE, ...dayValue, }; }; getDayLabel = (dayKey: DayKey, long?: boolean): string | object | React.ReactNode => { const { dayFormatter, customDays } = this.props; let label; if (typeof dayKey === 'string' && customDays && customDays[dayKey]) { label = customDays[dayKey][long ? 'longLabel' : 'label'] || customDays[dayKey].label; } if (!label) label = dayFormatter(dayKey, long); return label; }; handleRangePaste = (dayKeys: DayKey): void => { const { rangeClipboard } = this.props; const { activeDays } = this.state; if (rangeClipboard?.stop && rangeClipboard?.start) { activeDays.length > 1 ? this.handleMultipleDayTimeChange([ getDateFromDayValue(rangeClipboard.start), getDateFromDayValue(rangeClipboard.stop), ]) : this.handleDayTimeChange( [getDateFromDayValue(rangeClipboard.start), getDateFromDayValue(rangeClipboard.stop)], dayKeys ); } }; handleRangeCopy = (): void => { const { onRangeCopy } = this.props; const { activeDays } = this.state; const dayValue = this.getDayValue(activeDays[0]); onRangeCopy && onRangeCopy({ start: dayValue.start, stop: dayValue.stop }); }; getAllKeys = (): DayKey[] => { const { numberOfDays, customDays } = this.props; let keys = range(numberOfDays); if (customDays) keys = [...keys, ...((Object.keys(customDays) as unknown) as number[])]; return keys; }; renderDay = (dayKey: DayKey): JSX.Element => { const { customDays, intl, readOnly, texts } = this.props; const { activeDays } = this.state; const isRestricted = this.isDayRestricted(dayKey); const isActive = activeDays.includes(dayKey); let Component; if (typeof dayKey === 'string' && customDays && customDays[dayKey]) { const { component: CustomComponent } = customDays[dayKey]; if (CustomComponent) Component = CustomComponent; } if (!Component) { Component = Day; } return ( <Component key={dayKey} dayKey={dayKey} data-attr={dayKey} label={this.getDayLabel(dayKey)} restricted={isRestricted} active={isActive} readOnly={readOnly} intl={intl} onToggle={this.handleToggleDay} texts={texts} /> ); }; handleRangeAdd = (): void => { const { daily } = this.props; if (!daily && !this.haveActiveDaysCommonRange()) { this.handleMultipleDayTimeChange([ getDateFromDayValue(DEFAULT_RANGE_START), getDateFromDayValue(DEFAULT_RANGE_END), ]); } this.setState({ isRangeDefined: true }); }; renderRangeForm = (dayKeys: DayKey | DayKey[]): React.ReactNode => { const { activeDays } = this.state; const { hideHeader, monthlyFilterPeriod, monthlyFilter, daily, days, onChange, texts, valueSelectionModes, renderRangeFormSuffix, timePickerProps, disabled, } = this.props; return ( <RangeFormContainer disabled={disabled} onChange={onChange} days={days} activeDays={activeDays} dayKeys={dayKeys} getDayLabel={this.getDayLabel} getDayValue={this.getDayValue} onMultipleDayTimeChange={this.handleMultipleDayTimeChange} onDayTimeChange={this.handleDayTimeChange} onRangeClear={disabled ? undefined : this.handleRangeDelete} onRangeCopy={disabled ? undefined : this.handleRangeCopy} onRangePaste={(): void => this.handleRangePaste(dayKeys as DayKey)} hideHeader={hideHeader} monthlyFilter={monthlyFilter} monthlyFilterPeriod={monthlyFilterPeriod} onRangeDelete={daily ? undefined : this.handleRangeDelete} texts={(texts || {}) as TimeWindowTexts} renderSuffix={renderRangeFormSuffix} timePickerProps={timePickerProps} valueSelectionModes={valueSelectionModes} /> ); }; haveActiveDaysCommonRange = (): boolean => { const { activeDays } = this.state; const { days } = this.props; let previousDay: DayOptions | undefined; const activeDaysHaveDifferentRanges = activeDays.some((dayIndex): boolean => { const currentDay = days[dayIndex as number]; if (!currentDay) { return true; } if (!previousDay) { previousDay = currentDay; return false; } const areRangeDifferent = currentDay?.start !== previousDay?.start || currentDay?.stop !== previousDay?.stop; previousDay = currentDay; return areRangeDifferent; }); return !activeDaysHaveDifferentRanges; }; handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>): void => { if (e.key === 'Shift') { this.setState(state => ({ ...state, controlKeyPressed: false, shiftKeyPressed: true })); } if (e.key === 'Control' || e.key === 'Meta') { this.setState(state => ({ ...state, controlKeyPressed: true, shiftKeyPressed: false })); } }; handleKeyUp = (e: React.KeyboardEvent<HTMLDivElement>): void => { if (e.key === 'Control' || e.key === 'Meta') { this.setState(state => ({ ...state, controlKeyPressed: false })); } if (e.key === 'Shift') { this.setState(state => ({ ...state, shiftKeyPressed: false })); } }; render(): JSX.Element { const { days, numberOfDays, daily, intl, texts, disabled, ...rest } = this.props; const { activeDays, isRangeDefined } = this.state; const keys = this.getAllKeys(); const singleMode = keys.length === 1; const rangeFormKey = singleMode ? keys[0] : activeDays; const shouldRenderRangeForm = (!!activeDays.length && isRangeDefined) || !!daily; const shouldRenderSelectionHint = !activeDays.length && !disabled; const shouldRenderAddButton = !!activeDays.length && !daily && !isRangeDefined && !disabled; return ( <S.TimeWindowContainer tabIndex={0} ref={this.wrapperRef} onKeyDown={this.handleKeyDown} onKeyUp={this.handleKeyUp} > {!singleMode && ( <Grid onUnselectAll={this.handleClearSelection} onSelectAll={this.handleSelectAll} showUnselectAll={activeDays?.length > 0} renderDay={this.renderDay} keys={keys as number[]} days={days} intl={intl} numberOfDays={numberOfDays} texts={texts} {...rest} title={ <SelectionCount selectedDayCount={activeDays.length} label={intl.formatMessage({ id: 'DS.DATE-RANGE-PICKER.SELECTED', defaultMessage: 'Selected: ' })} /> } /> )} {shouldRenderRangeForm && this.renderRangeForm(rangeFormKey)} {shouldRenderSelectionHint && ( <SelectionHint message={intl.formatMessage({ id: 'DS.DATE-RANGE-PICKER.SELECT-DAYS-DESCRIPTION' })} /> )} {shouldRenderAddButton && ( <S.AddButtonWrapper> <AddButton label={intl.formatMessage({ id: 'DS.DATE-RANGE-PICKER.ADD-TIME', defaultMessage: 'Add time' })} onClick={this.handleRangeAdd} /> </S.AddButtonWrapper> )} </S.TimeWindowContainer> ); } } export default injectIntl(TimeWindowBase);
the_stack
import { Component, OnInit, ViewChild, AfterViewInit, ViewEncapsulation } from '@angular/core'; import { MatDialog, MatDialogRef } from '@angular/material/dialog'; import { ActivatedRoute, Router } from '@angular/router'; import { Hotkey, HotkeysService } from 'angular2-hotkeys'; import { AboutComponent } from './dialogs/about/about.component'; import { AdvisoryComponent } from './dialogs/advisory/advisory.component'; import { AssessmentDocumentsComponent } from './dialogs/assessment-documents/assessment-documents.component'; import { ChangePasswordComponent } from './dialogs/change-password/change-password.component'; import { ConfirmComponent } from './dialogs/confirm/confirm.component'; import { EditUserComponent } from './dialogs/edit-user/edit-user.component'; import { EnableProtectedComponent } from './dialogs/enable-protected/enable-protected.component'; import { GlobalParametersComponent } from './dialogs/global-parameters/global-parameters.component'; import { KeyboardShortcutsComponent } from './dialogs/keyboard-shortcuts/keyboard-shortcuts.component'; import { TermsOfUseComponent } from './dialogs/terms-of-use/terms-of-use.component'; import { CreateUser } from './models/user.model'; import { AssessmentService } from './services/assessment.service'; import { AuthenticationService } from './services/authentication.service'; import { ConfigService } from './services/config.service'; import { NgbAccordion } from '@ng-bootstrap/ng-bootstrap'; import { ExcelExportComponent } from './dialogs/excel-export/excel-export.component'; import { AggregationService } from './services/aggregation.service'; import { LocalStoreManager } from './services/storage.service'; declare var $: any; @Component({ moduleId: module.id, selector: 'app-root', templateUrl: './app.component.html', encapsulation: ViewEncapsulation.None, // tslint:disable-next-line:use-host-property-decorator host: { class: 'd-flex flex-column flex-11a w-100' } }) export class AppComponent implements OnInit, AfterViewInit { docUrl: string; dialogRef: MatDialogRef<any>; isFooterVisible: boolean = false; @ViewChild('acc') accordion: NgbAccordion; constructor( public auth: AuthenticationService, public assessSvc: AssessmentService, public configSvc: ConfigService, public aggregationSvc: AggregationService, public dialog: MatDialog, public router: Router, private _hotkeysService: HotkeysService, storageManager: LocalStoreManager ) { storageManager.initialiseStorageSyncListener(); } ngOnInit() { this.docUrl = this.configSvc.docUrl; if (localStorage.getItem("returnPath")) { if (!Number(localStorage.getItem("redirectid"))) { this.hasPath(localStorage.getItem("returnPath")); } } this.setupShortCutKeys(); localStorage.setItem('isAcetApp', (this.configSvc.installationMode === "ACET").toString()); localStorage.setItem('isTsaApp', (this.configSvc.installationMode === "TSA").toString()); } ngAfterViewInit() { setTimeout(() => { this.isFooterOpen(); }, 200); } hasPath(rpath: string) { if (rpath != null) { localStorage.removeItem("returnPath"); this.router.navigate([rpath], { queryParamsHandling: "preserve" }); } } /** * Indicates if the user is currently within the Module Builder pages. * TODO: Hard-coded paths could be replaced by asking the BreadcrumbComponent * or the SetBuilderService for Module Builder paths. */ isModuleBuilder(rpath: string) { if (!rpath) { return false; } if (rpath === '/set-list' || rpath.indexOf('/set-detail') > -1 || rpath.indexOf('/requirement-list') > -1 || rpath.indexOf('/standard-documents') > -1 || rpath.indexOf('/ref-document') > -1 || rpath.indexOf('/requirement-detail') > -1 || rpath.indexOf('/question-list') > -1 || rpath.indexOf('/add-question') > -1) { return true; } return false; } goHome() { this.assessSvc.dropAssessment(); this.router.navigate(['/home']); } about() { if (this.dialog.openDialogs[0]) { return; } this.dialogRef = this.dialog.open(AboutComponent); this.dialogRef .afterClosed() .subscribe(); } termsOfUse() { if (this.dialog.openDialogs[0]) { return; } this.dialogRef = this.dialog.open(TermsOfUseComponent); this.dialogRef .afterClosed() .subscribe(); } advisory() { if (this.dialog.openDialogs[0]) { return; } this.dialogRef = this.dialog.open(AdvisoryComponent); this.dialogRef .afterClosed() .subscribe(); } editUser() { if (this.dialog.openDialogs[0]) { return; } this.dialogRef = this.dialog.open(EditUserComponent); this.dialogRef .afterClosed() .subscribe( (data: CreateUser) => { if (data && data.primaryEmail) { // don't send anything unless there's something sane to send this.auth.updateUser(data).subscribe(() => this.auth.setUserInfo(data)); } this.dialogRef = undefined; }, error => console.log(error.message) ); } resetPassword() { if (this.dialog.openDialogs[0]) { return; } this.dialogRef = this.dialog.open(ChangePasswordComponent, { width: '300px', data: { primaryEmail: this.auth.email() } }); this.dialogRef.afterClosed().subscribe(); } isAssessment() { return localStorage.getItem('assessmentId'); } showAssessDocs() { if (this.dialog.openDialogs[0]) { return; } // , {width: '800px', height: "500px"} this.dialogRef = this.dialog.open(AssessmentDocumentsComponent); this.dialogRef .afterClosed() .subscribe(); } editParameters() { if (this.dialog.openDialogs[0]) { return; } this.dialogRef = this.dialog.open(GlobalParametersComponent); this.dialogRef .afterClosed() .subscribe(); } enableProtectedFeature() { if (this.dialog.openDialogs[0]) { return; } this.dialogRef = this.dialog.open(EnableProtectedComponent); } showKeyboardShortcuts() { if (this.dialog.openDialogs[0]) { return; } this.dialogRef = this.dialog.open(KeyboardShortcutsComponent); } showExcelExportDialog() { const doNotShowLocal = localStorage.getItem('doNotShowExcelExport'); const doNotShow = doNotShowLocal && doNotShowLocal == 'true' ? true : false; if (this.dialog.openDialogs[0] || doNotShow) { this.exportToExcel(); return; } this.dialogRef = this.dialog.open(ExcelExportComponent); this.dialogRef .afterClosed() .subscribe(); } exportToExcel() { window.location.href = this.configSvc.apiUrl + 'ExcelExport?token=' + localStorage.getItem('userToken'); } navigateTrend() { this.aggregationSvc.mode = 'TREND'; this.router.navigate(['/trend']); } navigateCompare() { this.aggregationSvc.mode = 'COMPARE'; this.router.navigate(['/compare']); } // ----------------------------- setupShortCutKeys() { // About this._hotkeysService.add(new Hotkey('alt+a', (event: KeyboardEvent): boolean => { this.about(); return false; // Prevent bubbling })); // Accessibility Features this._hotkeysService.add(new Hotkey('alt+c', (event: KeyboardEvent): boolean => { switch(this.configSvc.installationMode || '') { case "ACET": window.open(this.docUrl + "AccessibilityFeatures/index_acet.htm", "_blank"); break; default: window.open(this.docUrl + "ApplicationDocuments/AccessibilityStatement.pdf", "_blank"); } return false; // Prevent bubbling })); // User Guide this._hotkeysService.add(new Hotkey('alt+g', (event: KeyboardEvent): boolean => { switch(this.configSvc.installationMode || '') { case "ACET": window.open(this.docUrl + "htmlhelp_acet/index.htm", "_blank"); break; default: window.open(this.docUrl + "htmlhelp/index.htm", "_blank"); } return false; // Prevent bubbling })); // Resource Library this._hotkeysService.add(new Hotkey('alt+l', (event: KeyboardEvent): boolean => { this.router.navigate(['resource-library']); return false; // Prevent bubbling })); // Parameter Editor this._hotkeysService.add(new Hotkey('alt+m', (event: KeyboardEvent): boolean => { return false; // Prevent bubbling })); // New Assessment this._hotkeysService.add(new Hotkey('alt+n', (event: KeyboardEvent): boolean => { const dialogRef = this.dialog.open(ConfirmComponent); dialogRef.componentInstance.confirmMessage = "Are you sure you want to create a new assessment? "; dialogRef.afterClosed().subscribe(result => { if (result) { this.assessSvc.newAssessment(); } }); return false; // Prevent bubbling })); // User Guide (PDF) this._hotkeysService.add(new Hotkey('alt+p', (event: KeyboardEvent): boolean => { window.open(this.docUrl + "cdDocs/UserGuide.pdf", "_blank"); return false; // Prevent bubbling })); // Questionnaires // this._hotkeysService.add(new Hotkey('alt+q', (event: KeyboardEvent): boolean => { // return false; // Prevent bubbling // })); // Protected Features this._hotkeysService.add(new Hotkey('alt+r', (event: KeyboardEvent): boolean => { this.enableProtectedFeature(); return false; // Prevent bubbling })); // Assessment Documents this._hotkeysService.add(new Hotkey('alt+t', (event: KeyboardEvent): boolean => { return false; // Prevent bubbling })); // Advisory this._hotkeysService.add(new Hotkey('alt+v', (event: KeyboardEvent): boolean => { this.advisory(); return false; // Prevent bubbling })); // Keyboard Shortcuts this._hotkeysService.add(new Hotkey('?', (event: KeyboardEvent): boolean => { this.showKeyboardShortcuts(); return false; // Prevent bubbling })); } showNavBarRight() { if (this.auth.isLocal) { return false; } return this.router.url !== '/resource-library'; } isFooterOpen() { if (!!this.accordion) { return this.accordion.isExpanded('footerPanel'); } return false; } }
the_stack
import { Pipe, PipeTransform } from '@angular/core'; import { ImageElement, StarRating } from '../../../interfaces/final-object.interface'; import { randomizeArray } from '../../../node/utility'; import { orderBy } from 'natural-orderby'; export type SortType = 'default' | 'alphabetAsc' | 'alphabetDesc' | 'alphabetAsc2' | 'alphabetDesc2' | 'aspectRatioAsc' | 'aspectRatioDesc' | 'createdAsc' | 'createdDesc' | 'folderSizeAsc' | 'folderSizeDesc' | 'fpsAsc' | 'fpsDesc' | 'hash' // only used by the duplicateFinderPipe | 'modifiedAsc' | 'modifiedDesc' | 'random' | 'sizeAsc' | 'sizeDesc' | 'starAsc' | 'starDesc' | 'tagsAsc' | 'tagsDesc' | 'timeAsc' | 'timeDesc' | 'timesPlayedAsc' | 'timesPlayedDesc' | 'yearAsc' | 'yearDesc'; @Pipe({ name: 'sortingPipe' }) export class SortingPipe implements PipeTransform { /** * Helper function for sorting * Always moved the `up` folder to the top * Sorts everything else according to the `property` * @param x * @param y * @param property * @param decreasing -- boolean to tell whether `ascending` or `descending` */ sortFunctionLol( x: ImageElement, y: ImageElement, property: string, decreasing: boolean ): number { // up button first if (x.fileName === '*UP*') { return -1; } else if (y.fileName === '*UP*') { return 1; } if (property === 'alphabetical') { if (x.fileName.toLowerCase() < y.fileName.toLowerCase()) { return decreasing ? -1 : 1; } if (x.fileName.toLowerCase() > y.fileName.toLowerCase()) { return decreasing ? 1 : -1; } else { return 0; } } if (property === 'tags') { if ((x.tags || []).length < (y.tags || []).length) { return decreasing ? -1 : 1; } if ((x.tags || []).length > (y.tags || []).length) { return decreasing ? 1 : -1; } else { return 0; } } if (property === 'hash') { if (x.hash < y.hash) { return -1; } if (x.hash > y.hash) { return 1; } else { return 0; } } // handle `year` case: show properties that are not empty first if (property === 'year') { if (decreasing) { return (x.year || Infinity) - (y.year || Infinity); } else { return (y.year || 0) - (x.year || 0); } } // handle `stars` case: show properties that are not empty first if (property === 'stars') { if (decreasing) { return ( x.stars === <StarRating><unknown>0.5 ? Infinity : x.stars) - (y.stars === <StarRating><unknown>0.5 ? Infinity : y.stars); } else { return ( y.stars === <StarRating><unknown>0.5 ? 0 : y.stars) - (x.stars === <StarRating><unknown>0.5 ? 0 : x.stars); } } if (property === 'aspectRatio') { const xAspectRatio = x.width / x.height; const yAspectRatio = y.width / y.height; if (xAspectRatio < yAspectRatio) { if (decreasing) { return 1; } else { return -1; } } if (xAspectRatio > yAspectRatio) { if (decreasing) { return -1; } else { return 1; } } else { return 0; } } if (property === 'folderSize') { // want non-folders to be considered "less than" a folder so give negative value by default. let xDisplay = -Infinity; let yDisplay = -Infinity; if (x.cleanName === '*FOLDER*') { xDisplay = parseInt(x.fileSizeDisplay, 10); } if (y.cleanName === '*FOLDER*') { yDisplay = parseInt(y.fileSizeDisplay, 10); } if (xDisplay < yDisplay ) { return decreasing ? 1 : -1; } if (xDisplay > yDisplay) { return decreasing ? -1 : 1; } else { return 0; } } if (x[property] > y[property]) { return decreasing ? 1 : -1; } else if (x[property] === y[property]) { return 0; } else { return decreasing ? -1 : 1; } } /** * Return the same array randomized on next search * @param galleryArray * @param sortingType - sorting method * @param forceSortUpdateHack - hack to force the sorting update * @param skip - whether to sort or return as is (needed for DUPLICATE SEARCH) */ transform( galleryArray: ImageElement[], sortingType: SortType, forceSortUpdateHack: number, skip: boolean ): ImageElement[] { // console.log('SORTING RUNNING'); // console.log(sortingType); if (skip) { // console.log('skipping !!!'); return galleryArray; } else if (sortingType === 'random') { if (galleryArray.length === 0) { return []; // else `galleryArray[0] errors out! } const currentIndex = (galleryArray[0].fileName === '*UP*' ? 1 : 0); // skip 'up button' if present return randomizeArray(galleryArray, currentIndex); } else if (sortingType === 'default') { return galleryArray; // sorting order set via `alphabetizeFinalArray` in `main-support.ts` // no need to `.slice()` as all other sorting types do it } else if (sortingType === 'alphabetAsc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'alphabetical', true); }); } else if (sortingType === 'alphabetDesc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'alphabetical', false); }); } else if (sortingType === 'alphabetAsc2') { if (galleryArray.length && galleryArray[0].fileName === '*UP*') { const tempGallery: ImageElement[] = galleryArray.slice(); const tempUp: ImageElement = tempGallery.shift(); // remove the first element (*UP*) return [tempUp, ...orderBy(tempGallery, 'fileName', 'asc')]; } else { return orderBy(galleryArray, 'fileName', 'asc'); } } else if (sortingType === 'alphabetDesc2') { if (galleryArray.length && galleryArray[0].fileName === '*UP*') { const tempGallery: ImageElement[] = galleryArray.slice(); const tempUp: ImageElement = tempGallery.shift(); // remove the first element (*UP*) return [tempUp, ...orderBy(tempGallery, 'fileName', 'desc')]; } else { return orderBy(galleryArray, 'fileName', 'desc'); } } else if (sortingType === 'sizeAsc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'fileSize', true); }); } else if (sortingType === 'sizeDesc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'fileSize', false); }); } else if (sortingType === 'timeAsc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'duration', true); }); } else if (sortingType === 'timeDesc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'duration', false); }); } else if (sortingType === 'starAsc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'stars', true); }); } else if (sortingType === 'starDesc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'stars', false); }); } else if (sortingType === 'yearAsc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'year', true); }); } else if (sortingType === 'yearDesc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'year', false); }); } else if (sortingType === 'timesPlayedAsc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'timesPlayed', true); }); } else if (sortingType === 'timesPlayedDesc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'timesPlayed', false); }); } else if (sortingType === 'modifiedAsc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'mtime', true); }); } else if (sortingType === 'modifiedDesc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'mtime', false); }); } else if (sortingType === 'createdAsc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'birthtime', true); }); } else if (sortingType === 'createdDesc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'birthtime', false); }); } else if (sortingType === 'hash') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'hash', true); }); } else if (sortingType === 'tagsAsc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'tags', true); }); } else if (sortingType === 'tagsDesc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'tags', false); }); } else if (sortingType === 'aspectRatioAsc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'aspectRatio', false); }); } else if (sortingType === 'aspectRatioDesc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'aspectRatio', true); }); } else if (sortingType === 'folderSizeAsc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'folderSize', false); }); } else if (sortingType === 'folderSizeDesc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'folderSize', true); }); } else if (sortingType === 'fpsAsc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'fps', true); }); } else if (sortingType === 'fpsDesc') { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'fps', false); }); } else { return galleryArray.slice().sort((x: ImageElement, y: ImageElement): any => { return this.sortFunctionLol(x, y, 'index', true); }); } } }
the_stack
import { QuerySnapshot, DocumentData, WithFieldValue, PartialWithFieldValue, SetOptions, } from '@google-cloud/firestore'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import {expect, use} from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; import * as extend from 'extend'; import {firestore} from '../protos/firestore_v1_proto_api'; import { CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, GeoPoint, Query, QueryDocumentSnapshot, setLogFunction, Timestamp, WriteResult, } from '../src'; import {autoId, Deferred} from '../src/util'; import {TEST_BUNDLE_ID, verifyMetadata} from '../test/bundle'; import { bundleToElementArray, Post, postConverter, postConverterMerge, verifyInstance, } from '../test/util/helpers'; import {BulkWriter} from '../src/bulk-writer'; import {Status} from 'google-gax'; import {QueryPartition} from '../src/query-partition'; import {CollectionGroup} from '../src/collection-group'; import IBundleElement = firestore.IBundleElement; use(chaiAsPromised); const version = require('../../package.json').version; class DeferredPromise<T> { resolve: Function; reject: Function; promise: Promise<T> | null; constructor() { this.resolve = () => { throw new Error('DeferredPromise.resolve has not been initialized'); }; this.reject = () => { throw new Error('DeferredPromise.reject has not been initialized'); }; this.promise = null; } } if (process.env.NODE_ENV === 'DEBUG') { setLogFunction(console.log); } function getTestRoot(firestore: Firestore) { return firestore.collection(`node_${version}_${autoId()}`); } describe('Firestore class', () => { let firestore: Firestore; let randomCol: CollectionReference; beforeEach(() => { firestore = new Firestore(); randomCol = getTestRoot(firestore); }); afterEach(() => verifyInstance(firestore)); it('has collection() method', () => { const ref = firestore.collection('col'); expect(ref.id).to.equal('col'); }); it('has doc() method', () => { const ref = firestore.doc('col/doc'); expect(ref.id).to.equal('doc'); }); it('has getAll() method', () => { const ref1 = randomCol.doc('doc1'); const ref2 = randomCol.doc('doc2'); return Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'a'})]) .then(() => { return firestore.getAll(ref1, ref2); }) .then(docs => { expect(docs.length).to.equal(2); }); }); it('getAll() supports array destructuring', () => { const ref1 = randomCol.doc('doc1'); const ref2 = randomCol.doc('doc2'); return Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'a'})]) .then(() => { return firestore.getAll(...[ref1, ref2]); }) .then(docs => { expect(docs.length).to.equal(2); }); }); it('getAll() supports field mask', () => { const ref1 = randomCol.doc('doc1'); return ref1 .set({foo: 'a', bar: 'b'}) .then(() => { return firestore.getAll(ref1, {fieldMask: ['foo']}); }) .then(docs => { expect(docs[0].data()).to.deep.equal({foo: 'a'}); }); }); it('getAll() supports array destructuring with field mask', () => { const ref1 = randomCol.doc('doc1'); const ref2 = randomCol.doc('doc2'); return Promise.all([ref1.set({f: 'a', b: 'b'}), ref2.set({f: 'a', b: 'b'})]) .then(() => { return firestore.getAll(...[ref1, ref2], {fieldMask: ['f']}); }) .then(docs => { expect(docs[0].data()).to.deep.equal({f: 'a'}); expect(docs[1].data()).to.deep.equal({f: 'a'}); }); }); it('getAll() supports generics', async () => { const ref1 = randomCol.doc('doc1').withConverter(postConverter); const ref2 = randomCol.doc('doc2').withConverter(postConverter); await ref1.set(new Post('post1', 'author1')); await ref2.set(new Post('post2', 'author2')); const docs = await firestore.getAll(ref1, ref2); expect(docs[0].data()!.toString()).to.deep.equal('post1, by author1'); expect(docs[1].data()!.toString()).to.deep.equal('post2, by author2'); }); it('cannot make calls after the client has been terminated', () => { const ref1 = randomCol.doc('doc1'); return firestore .terminate() .then(() => { return ref1.set({foo: 100}); }) .then(() => Promise.reject('set() should have failed')) .catch(err => { expect(err.message).to.equal('The client has already been terminated'); }); }); it('throws an error if terminate() is called with active listeners', async () => { const ref = randomCol.doc('doc-1'); const unsubscribe = ref.onSnapshot(() => { // No-op }); await expect(firestore.terminate()).to.eventually.be.rejectedWith( 'All onSnapshot() listeners must be unsubscribed, and all BulkWriter ' + 'instances must be closed before terminating the client. There are 1 ' + 'active listeners and 0 open BulkWriter instances.' ); unsubscribe(); }); it('throws an error if terminate() is called with pending BulkWriter operations', async () => { const writer = firestore.bulkWriter(); const ref = randomCol.doc('doc-1'); writer.set(ref, {foo: 'bar'}); await expect(firestore.terminate()).to.eventually.be.rejectedWith( 'All onSnapshot() listeners must be unsubscribed, and all BulkWriter ' + 'instances must be closed before terminating the client. There are 0 ' + 'active listeners and 1 open BulkWriter instances.' ); }); }); describe('CollectionGroup class', () => { const desiredPartitionCount = 3; const documentCount = 2 * 128 + 127; // Minimum partition size is 128. let firestore: Firestore; let randomColl: CollectionReference; let collectionGroup: CollectionGroup; before(async () => { firestore = new Firestore({}); randomColl = getTestRoot(firestore); collectionGroup = firestore.collectionGroup(randomColl.id); const batch = firestore.batch(); for (let i = 0; i < documentCount; ++i) { batch.create(randomColl.doc(), {title: 'post', author: 'author'}); } await batch.commit(); }); async function getPartitions<T>( collectionGroup: CollectionGroup<T>, desiredPartitionsCount: number ): Promise<QueryPartition<T>[]> { const partitions: QueryPartition<T>[] = []; for await (const partition of collectionGroup.getPartitions( desiredPartitionsCount )) { partitions.push(partition); } return partitions; } async function verifyPartitions<T>( partitions: QueryPartition<T>[] ): Promise<QueryDocumentSnapshot<T>[]> { expect(partitions.length).to.not.be.greaterThan(desiredPartitionCount); expect(partitions[0].startAt).to.be.undefined; for (let i = 0; i < partitions.length - 1; ++i) { // The cursor value is a single DocumentReference expect( (partitions[i].endBefore![0] as DocumentReference<T>).isEqual( partitions[i + 1].startAt![0] as DocumentReference<T> ) ).to.be.true; } expect(partitions[partitions.length - 1].endBefore).to.be.undefined; // Validate that we can use the partitions to read the original documents. const documents: QueryDocumentSnapshot<T>[] = []; for (const partition of partitions) { documents.push(...(await partition.toQuery().get()).docs); } expect(documents.length).to.equal(documentCount); return documents; } it('partition query', async () => { const partitions = await getPartitions( collectionGroup, desiredPartitionCount ); await verifyPartitions(partitions); }); it('partition query with manual cursors', async () => { const partitions = await getPartitions( collectionGroup, desiredPartitionCount ); const documents: QueryDocumentSnapshot<DocumentData>[] = []; for (const partition of partitions) { let partitionedQuery: Query = collectionGroup; if (partition.startAt) { partitionedQuery = partitionedQuery.startAt(...partition.startAt); } if (partition.endBefore) { partitionedQuery = partitionedQuery.endBefore(...partition.endBefore); } documents.push(...(await partitionedQuery.get()).docs); } expect(documents.length).to.equal(documentCount); }); it('partition query with converter', async () => { const collectionGroupWithConverter = collectionGroup.withConverter(postConverter); const partitions = await getPartitions( collectionGroupWithConverter, desiredPartitionCount ); const documents = await verifyPartitions(partitions); for (const document of documents) { expect(document.data()).to.be.an.instanceOf(Post); } }); it('empty partition query', async () => { const desiredPartitionCount = 3; const collectionGroupId = randomColl.doc().id; const collectionGroup = firestore.collectionGroup(collectionGroupId); const partitions = await getPartitions( collectionGroup, desiredPartitionCount ); expect(partitions.length).to.equal(1); expect(partitions[0].startAt).to.be.undefined; expect(partitions[0].endBefore).to.be.undefined; }); }); describe('CollectionReference class', () => { let firestore: Firestore; let randomCol: CollectionReference; beforeEach(() => { firestore = new Firestore({}); randomCol = getTestRoot(firestore); }); afterEach(() => verifyInstance(firestore)); it('has firestore property', () => { const ref = firestore.collection('col'); expect(ref.firestore).to.be.an.instanceOf(Firestore); }); it('has id property', () => { const ref = firestore.collection('col'); expect(ref.id).to.equal('col'); }); it('has parent property', () => { const ref = firestore.collection('col/doc/col'); expect(ref.parent!.id).to.equal('doc'); }); it('has path property', () => { const ref = firestore.collection('col/doc/col'); expect(ref.path).to.equal('col/doc/col'); }); it('has doc() method', () => { let ref = firestore.collection('col').doc('doc'); expect(ref.id).to.equal('doc'); ref = firestore.collection('col').doc(); expect(ref.id).to.have.length(20); }); it('has add() method', () => { return randomCol .add({foo: 'a'}) .then(ref => { return ref.get(); }) .then(doc => { expect(doc.get('foo')).to.equal('a'); }); }); it('lists missing documents', async () => { const batch = firestore.batch(); batch.set(randomCol.doc('a'), {}); batch.set(randomCol.doc('b/b/b'), {}); batch.set(randomCol.doc('c'), {}); await batch.commit(); const documentRefs = await randomCol.listDocuments(); const documents = await firestore.getAll(...documentRefs); const existingDocs = documents.filter(doc => doc.exists); const missingDocs = documents.filter(doc => !doc.exists); expect(existingDocs.map(doc => doc.id)).to.have.members(['a', 'c']); expect(missingDocs.map(doc => doc.id)).to.have.members(['b']); }); it('supports withConverter()', async () => { const ref = await firestore .collection('col') .withConverter(postConverter) .add(new Post('post', 'author')); const postData = await ref.get(); const post = postData.data(); expect(post).to.not.be.undefined; expect(post!.toString()).to.equal('post, by author'); }); }); describe('DocumentReference class', () => { let firestore: Firestore; let randomCol: CollectionReference; beforeEach(() => { firestore = new Firestore(); randomCol = getTestRoot(firestore); }); afterEach(() => verifyInstance(firestore)); it('has firestore property', () => { const ref = firestore.doc('col/doc'); expect(ref.firestore).to.be.an.instanceOf(Firestore); }); it('has id property', () => { const ref = firestore.doc('col/doc'); expect(ref.id).to.equal('doc'); }); it('has parent property', () => { const ref = firestore.doc('col/doc'); expect(ref.parent.id).to.equal('col'); }); it('has path property', () => { const ref = firestore.doc('col/doc'); expect(ref.path).to.equal('col/doc'); }); it('has collection() method', () => { const ref = firestore.doc('col/doc').collection('subcol'); expect(ref.id).to.equal('subcol'); }); it('has create()/get() method', () => { const ref = randomCol.doc(); return ref .create({foo: 'a'}) .then(() => { return ref.get(); }) .then(doc => { expect(doc.get('foo')).to.equal('a'); }); }); it('has set() method', () => { const allSupportedTypesObject: {[field: string]: unknown} = { stringValue: 'a', trueValue: true, falseValue: false, integerValue: 10, largeIntegerValue: 1234567890000, doubleValue: 0.1, infinityValue: Infinity, negativeInfinityValue: -Infinity, objectValue: {foo: 'bar', '😀': '😜'}, emptyObject: {}, dateValue: new Timestamp(479978400, 123000000), zeroDateValue: new Timestamp(0, 0), pathValue: firestore.doc('col1/ref1'), arrayValue: ['foo', 42, 'bar'], emptyArray: [], nilValue: null, geoPointValue: new GeoPoint(50.1430847, -122.947778), zeroGeoPointValue: new GeoPoint(0, 0), bytesValue: Buffer.from([0x01, 0x02]), }; const ref = randomCol.doc('doc'); return ref .set(allSupportedTypesObject) .then(() => { return ref.get(); }) .then(doc => { const data = doc.data()!; expect(data.pathValue.path).to.equal( (allSupportedTypesObject.pathValue as DocumentReference).path ); delete data.pathValue; delete allSupportedTypesObject.pathValue; expect(data).to.deep.equal(allSupportedTypesObject); }); }); it('supports NaNs', () => { const nanObject = { nanValue: NaN, }; const ref = randomCol.doc('doc'); return ref .set(nanObject) .then(() => { return ref.get(); }) .then(doc => { const actualValue = doc.data()!.nanValue; expect(actualValue).to.be.a('number'); expect(actualValue).to.be.NaN; }); }); it('round-trips BigInts', () => { const bigIntValue = BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1); const firestore = new Firestore({useBigInt: true}); const randomCol = getTestRoot(firestore); const ref = randomCol.doc('doc'); return ref .set({bigIntValue}) .then(() => ref.get()) .then(doc => ref.set(doc.data()!)) .then(() => ref.get()) .then(doc => { const actualValue = doc.data()!.bigIntValue; expect(actualValue).to.be.a('bigint'); expect(actualValue).to.equal(bigIntValue); }); }); it('supports server timestamps', () => { const baseObject = { a: 'bar', b: {remove: 'bar'}, d: {keep: 'bar'}, f: FieldValue.serverTimestamp(), }; const updateObject = { a: FieldValue.serverTimestamp(), b: {c: FieldValue.serverTimestamp()}, 'd.e': FieldValue.serverTimestamp(), }; const ref = randomCol.doc('doc'); let setTimestamp: Timestamp; return ref .set(baseObject) .then(() => { return ref.get(); }) .then(doc => { setTimestamp = doc.get('f'); expect(setTimestamp).to.be.an.instanceOf(Timestamp); expect(doc.data()).to.deep.equal({ a: 'bar', b: {remove: 'bar'}, d: {keep: 'bar'}, f: setTimestamp, }); return ref.update(updateObject); }) .then(() => { return ref.get(); }) .then(doc => { const updateTimestamp = doc.get('a'); expect(setTimestamp).to.be.an.instanceOf(Timestamp); expect(doc.data()).to.deep.equal({ a: updateTimestamp, b: {c: updateTimestamp}, d: {e: updateTimestamp, keep: 'bar'}, f: setTimestamp, }); }); }); it('supports increment()', () => { const baseData = {sum: 1}; const updateData = {sum: FieldValue.increment(1)}; const expectedData = {sum: 2}; const ref = randomCol.doc('doc'); return ref .set(baseData) .then(() => ref.update(updateData)) .then(() => ref.get()) .then(doc => { expect(doc.data()).to.deep.equal(expectedData); }); }); it('supports increment() with set() with merge', () => { const baseData = {sum: 1}; const updateData = {sum: FieldValue.increment(1)}; const expectedData = {sum: 2}; const ref = randomCol.doc('doc'); return ref .set(baseData) .then(() => ref.set(updateData, {merge: true})) .then(() => ref.get()) .then(doc => { expect(doc.data()).to.deep.equal(expectedData); }); }); it('supports arrayUnion()', () => { const baseObject = { a: [], b: ['foo'], c: {d: ['foo']}, }; const updateObject = { a: FieldValue.arrayUnion('foo', 'bar'), b: FieldValue.arrayUnion('foo', 'bar'), 'c.d': FieldValue.arrayUnion('foo', 'bar'), }; const expectedObject = { a: ['foo', 'bar'], b: ['foo', 'bar'], c: {d: ['foo', 'bar']}, }; const ref = randomCol.doc('doc'); return ref .set(baseObject) .then(() => ref.update(updateObject)) .then(() => ref.get()) .then(doc => { expect(doc.data()).to.deep.equal(expectedObject); }); }); it('supports arrayRemove()', () => { const baseObject = { a: [], b: ['foo', 'foo', 'baz'], c: {d: ['foo', 'bar', 'baz']}, }; const updateObject = { a: FieldValue.arrayRemove('foo'), b: FieldValue.arrayRemove('foo'), 'c.d': FieldValue.arrayRemove('foo', 'bar'), }; const expectedObject = { a: [], b: ['baz'], c: {d: ['baz']}, }; const ref = randomCol.doc('doc'); return ref .set(baseObject) .then(() => ref.update(updateObject)) .then(() => ref.get()) .then(doc => { expect(doc.data()).to.deep.equal(expectedObject); }); }); it('supports set() with merge', () => { const ref = randomCol.doc('doc'); return ref .set({'a.1': 'foo', nested: {'b.1': 'bar'}}) .then(() => ref.set({'a.2': 'foo', nested: {'b.2': 'bar'}}, {merge: true}) ) .then(() => ref.get()) .then(doc => { const data = doc.data(); expect(data).to.deep.equal({ 'a.1': 'foo', 'a.2': 'foo', nested: { 'b.1': 'bar', 'b.2': 'bar', }, }); }); }); it('supports server timestamps for merge', () => { const ref = randomCol.doc('doc'); return ref .set({a: 'b'}) .then(() => ref.set({c: FieldValue.serverTimestamp()}, {merge: true})) .then(() => ref.get()) .then(doc => { const updateTimestamp = doc.get('c'); expect(updateTimestamp).to.be.an.instanceOf(Timestamp); expect(doc.data()).to.deep.equal({ a: 'b', c: updateTimestamp, }); }); }); it('has update() method', () => { const ref = randomCol.doc('doc'); return ref .set({foo: 'a'}) .then(res => { return ref.update({foo: 'b'}, {lastUpdateTime: res.writeTime}); }) .then(() => { return ref.get(); }) .then(doc => { expect(doc.get('foo')).to.equal('b'); }); }); it('enforces that updated document exists', () => { return randomCol .doc() .update({foo: 'b'}) .catch(err => { expect(err.message).to.match(/No document to update/); }); }); it('has delete() method', () => { let deleted = false; const ref = randomCol.doc('doc'); return ref .set({foo: 'a'}) .then(() => { return ref.delete(); }) .then(() => { deleted = true; return ref.get(); }) .then(result => { expect(deleted).to.be.true; expect(result.exists).to.be.false; }); }); it('can delete() a non-existing document', () => { const ref = firestore.collection('col').doc(); return ref.delete(); }); it('will fail to delete document with exists: true if doc does not exist', () => { const ref = randomCol.doc(); return ref .delete({exists: true}) .then(() => Promise.reject('Delete should have failed')) .catch((err: Error) => { expect(err.message).to.contain('NOT_FOUND: No document to update'); }); }); it('supports non-alphanumeric field names', () => { const ref = randomCol.doc('doc'); return ref .set({'!.\\`': {'!.\\`': 'value'}}) .then(() => { return ref.get(); }) .then(doc => { expect(doc.data()).to.deep.equal({'!.\\`': {'!.\\`': 'value'}}); return ref.update(new FieldPath('!.\\`', '!.\\`'), 'new-value'); }) .then(() => { return ref.get(); }) .then(doc => { expect(doc.data()).to.deep.equal({'!.\\`': {'!.\\`': 'new-value'}}); }); }); it('has listCollections() method', () => { const collections = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']; const promises: Array<Promise<{}>> = []; for (const collection of collections) { promises.push(randomCol.doc(`doc/${collection}/doc`).create({})); } return Promise.all(promises) .then(() => { return randomCol.doc('doc').listCollections(); }) .then(response => { expect(response).to.have.length(collections.length); for (let i = 0; i < response.length; ++i) { expect(response[i].id).to.equal(collections[i]); } }); }); // tslint:disable-next-line:only-arrow-function it('can add and delete fields sequentially', function () { this.timeout(30 * 1000); const ref = randomCol.doc('doc'); const actions = [ () => ref.create({}), () => ref.delete(), () => ref.create({a: {b: 'c'}}), () => ref.set({}, {merge: true}), () => ref.set({}), () => ref.set({a: {b: 'c'}}), () => ref.set({a: {d: 'e'}}, {merge: true}), () => ref.set({a: {d: FieldValue.delete()}}, {merge: true}), () => ref.set({a: {b: FieldValue.delete()}}, {merge: true}), () => ref.set({a: {e: 'foo'}}, {merge: true}), () => ref.set({f: 'foo'}, {merge: true}), () => ref.set({f: {g: 'foo'}}, {merge: true}), () => ref.update({'f.h': 'foo'}), () => ref.update({'f.g': FieldValue.delete()}), () => ref.update({'f.h': FieldValue.delete()}), () => ref.update({f: FieldValue.delete()}), () => ref.update({'i.j': {}}), () => ref.update({'i.j': {k: 'foo'}}), () => ref.update({'i.j': {l: {}}}), () => ref.update({i: FieldValue.delete()}), () => ref.update({a: FieldValue.delete()}), ]; const expectedState = [ {}, null, {a: {b: 'c'}}, {a: {b: 'c'}}, {}, {a: {b: 'c'}}, {a: {b: 'c', d: 'e'}}, {a: {b: 'c'}}, {a: {}}, {a: {e: 'foo'}}, {a: {e: 'foo'}, f: 'foo'}, {a: {e: 'foo'}, f: {g: 'foo'}}, {a: {e: 'foo'}, f: {g: 'foo', h: 'foo'}}, {a: {e: 'foo'}, f: {h: 'foo'}}, {a: {e: 'foo'}, f: {}}, {a: {e: 'foo'}}, {a: {e: 'foo'}, i: {j: {}}}, {a: {e: 'foo'}, i: {j: {k: 'foo'}}}, {a: {e: 'foo'}, i: {j: {l: {}}}}, {a: {e: 'foo'}}, {}, ]; let promise = Promise.resolve(); for (let i = 0; i < actions.length; ++i) { promise = promise .then(() => actions[i]()) .then(() => { return ref.get(); }) .then(snap => { if (!snap.exists) { expect(expectedState[i]).to.be.null; } else { expect(snap.data()).to.deep.equal(expectedState[i]); } }); } return promise; }); // tslint:disable-next-line:only-arrow-function it('can add and delete fields with server timestamps', function () { this.timeout(10 * 1000); const ref = randomCol.doc('doc'); const actions = [ () => ref.create({ time: FieldValue.serverTimestamp(), a: {b: FieldValue.serverTimestamp()}, }), () => ref.set({ time: FieldValue.serverTimestamp(), a: {c: FieldValue.serverTimestamp()}, }), () => ref.set( { time: FieldValue.serverTimestamp(), a: {d: FieldValue.serverTimestamp()}, }, {merge: true} ), () => ref.set( { time: FieldValue.serverTimestamp(), e: FieldValue.serverTimestamp(), }, {merge: true} ), () => ref.set( { time: FieldValue.serverTimestamp(), e: {f: FieldValue.serverTimestamp()}, }, {merge: true} ), () => ref.update({ time: FieldValue.serverTimestamp(), 'g.h': FieldValue.serverTimestamp(), }), () => ref.update({ time: FieldValue.serverTimestamp(), 'g.j': {k: FieldValue.serverTimestamp()}, }), ]; const expectedState = [ (times: number[]) => { return {time: times[0], a: {b: times[0]}}; }, (times: number[]) => { return {time: times[1], a: {c: times[1]}}; }, (times: number[]) => { return {time: times[2], a: {c: times[1], d: times[2]}}; }, (times: number[]) => { return {time: times[3], a: {c: times[1], d: times[2]}, e: times[3]}; }, (times: number[]) => { return { time: times[4], a: {c: times[1], d: times[2]}, e: {f: times[4]}, }; }, (times: number[]) => { return { time: times[5], a: {c: times[1], d: times[2]}, e: {f: times[4]}, g: {h: times[5]}, }; }, (times: number[]) => { return { time: times[6], a: {c: times[1], d: times[2]}, e: {f: times[4]}, g: {h: times[5], j: {k: times[6]}}, }; }, ]; let promise = Promise.resolve(); const times: number[] = []; for (let i = 0; i < actions.length; ++i) { promise = promise .then(() => actions[i]()) .then(() => { return ref.get(); }) .then(snap => { times.push(snap.get('time')); expect(snap.data()).to.deep.equal(expectedState[i](times)); }); } return promise; }); describe('watch', () => { const currentDeferred = new DeferredPromise<DocumentSnapshot>(); function resetPromise() { currentDeferred.promise = new Promise((resolve, reject) => { currentDeferred.resolve = resolve; currentDeferred.reject = reject; }); } function waitForSnapshot(): Promise<DocumentSnapshot> { return currentDeferred.promise!.then(snapshot => { resetPromise(); return snapshot as DocumentSnapshot; }); } beforeEach(() => resetPromise()); it('handles changing a doc', () => { const ref = randomCol.doc('doc'); let readTime: Timestamp; let createTime: Timestamp; let updateTime: Timestamp; const unsubscribe = ref.onSnapshot( snapshot => { currentDeferred.resolve(snapshot); }, err => { currentDeferred.reject(err); } ); return waitForSnapshot() .then(snapshot => { expect(snapshot.exists).to.be.false; // Add the document. return ref.set({foo: 'a'}); }) .then(() => { return waitForSnapshot(); }) .then(snapshot => { expect(snapshot.exists).to.be.true; expect(snapshot.get('foo')).to.equal('a'); readTime = snapshot.readTime; createTime = snapshot.createTime!; updateTime = snapshot.updateTime!; // Update documents. return ref.set({foo: 'b'}); }) .then(() => { return waitForSnapshot(); }) .then(snapshot => { expect(snapshot.exists).to.be.true; expect(snapshot.get('foo')).to.equal('b'); expect(snapshot.createTime!.isEqual(createTime)).to.be.true; expect(snapshot.readTime.toMillis()).to.be.greaterThan( readTime.toMillis() ); expect(snapshot.updateTime!.toMillis()).to.be.greaterThan( updateTime.toMillis() ); unsubscribe(); }); }); it('handles deleting a doc', () => { const ref = randomCol.doc('doc'); const unsubscribe = ref.onSnapshot( snapshot => { currentDeferred.resolve(snapshot); }, err => { currentDeferred.reject(err); } ); return waitForSnapshot() .then(snapshot => { expect(snapshot.exists).to.be.false; // Add the document. return ref.set({foo: 'a'}); }) .then(() => { return waitForSnapshot(); }) .then(snapshot => { expect(snapshot.exists).to.be.true; // Delete the document. return ref.delete(); }) .then(() => { return waitForSnapshot(); }) .then(snapshot => { expect(snapshot.exists).to.be.false; unsubscribe(); }); }); it('handles multiple docs', done => { const doc1 = randomCol.doc(); const doc2 = randomCol.doc(); // Documents transition from non-existent to existent to non-existent. const exists1 = [false, true, false]; const exists2 = [false, true, false]; const promises: Array<Promise<WriteResult>> = []; // Code blocks to run after each step. const run = [ () => { promises.push(doc1.set({foo: 'foo'})); promises.push(doc2.set({foo: 'foo'})); }, () => { promises.push(doc1.delete()); promises.push(doc2.delete()); }, () => { unsubscribe1(); unsubscribe2(); Promise.all(promises).then(() => done()); }, ]; const maybeRun = () => { if (exists1.length === exists2.length) { run.shift()!(); } }; const unsubscribe1 = doc1.onSnapshot(snapshot => { expect(snapshot.exists).to.equal(exists1.shift()); maybeRun(); }); const unsubscribe2 = doc2.onSnapshot(snapshot => { expect(snapshot.exists).to.equal(exists2.shift()); maybeRun(); }); }); it('handles multiple streams on same doc', done => { const doc = randomCol.doc(); // Document transitions from non-existent to existent to non-existent. const exists1 = [false, true, false]; const exists2 = [false, true, false]; const promises: Array<Promise<WriteResult>> = []; // Code blocks to run after each step. const run = [ () => { promises.push(doc.set({foo: 'foo'})); }, () => { promises.push(doc.delete()); }, () => { unsubscribe1(); unsubscribe2(); Promise.all(promises).then(() => done()); }, ]; const maybeRun = () => { if (exists1.length === exists2.length) { run.shift()!(); } }; const unsubscribe1 = doc.onSnapshot(snapshot => { expect(snapshot.exists).to.equal(exists1.shift()); maybeRun(); }); const unsubscribe2 = doc.onSnapshot(snapshot => { expect(snapshot.exists).to.equal(exists2.shift()); maybeRun(); }); }); it('handles more than 100 concurrent listeners', async () => { const ref = randomCol.doc('doc'); const emptyResults: Array<Deferred<void>> = []; const documentResults: Array<Deferred<void>> = []; const unsubscribeCallbacks: Array<() => void> = []; // A single GAPIC client can only handle 100 concurrent streams. We set // up 100+ long-lived listeners to verify that Firestore pools requests // across multiple clients. for (let i = 0; i < 150; ++i) { emptyResults[i] = new Deferred<void>(); documentResults[i] = new Deferred<void>(); unsubscribeCallbacks[i] = randomCol .where('i', '>', i) .onSnapshot(snapshot => { if (snapshot.size === 0) { emptyResults[i].resolve(); } else if (snapshot.size === 1) { documentResults[i].resolve(); } }); } await Promise.all(emptyResults.map(d => d.promise)); await ref.set({i: 1337}); await Promise.all(documentResults.map(d => d.promise)); unsubscribeCallbacks.forEach(c => c()); }); it('handles query snapshots with converters', async () => { const setupDeferred = new Deferred<void>(); const resultsDeferred = new Deferred<QuerySnapshot<Post>>(); const ref = randomCol.doc('doc').withConverter(postConverter); const unsubscribe = randomCol .where('title', '==', 'post') .withConverter(postConverter) .onSnapshot(snapshot => { if (snapshot.size === 0) { setupDeferred.resolve(); } if (snapshot.size === 1) { resultsDeferred.resolve(snapshot); } }); await setupDeferred.promise; await ref.set(new Post('post', 'author')); const snapshot = await resultsDeferred.promise; expect(snapshot.docs[0].data().toString()).to.equal('post, by author'); unsubscribe(); }); }); it('supports withConverter()', async () => { const ref = firestore .collection('col') .doc('doc') .withConverter(postConverter); await ref.set(new Post('post', 'author')); const postData = await ref.get(); const post = postData.data(); expect(post).to.not.be.undefined; expect(post!.toString()).to.equal('post, by author'); }); it('supports primitive types with valid converter', async () => { type Primitive = number; const primitiveConverter = { toFirestore(value: Primitive): DocumentData { return {value}; }, fromFirestore(snapshot: QueryDocumentSnapshot): Primitive { const data = snapshot.data(); return data.value; }, }; type ArrayValue = number[]; const arrayConverter = { toFirestore(value: ArrayValue): DocumentData { return {values: value}; }, fromFirestore(snapshot: QueryDocumentSnapshot): ArrayValue { const data = snapshot.data(); return data.values; }, }; const coll = firestore.collection('tests'); const ref = coll.doc('number').withConverter(primitiveConverter); await ref.set(3); const result = await ref.get(); expect(result.data()).to.equal(3); const ref2 = coll.doc('array').withConverter(arrayConverter); await ref2.set([1, 2, 3]); const result2 = await ref2.get(); expect(result2.data()).to.deep.equal([1, 2, 3]); }); }); describe('Query class', () => { interface PaginatedResults { pages: number; docs: QueryDocumentSnapshot[]; } let firestore: Firestore; let randomCol: CollectionReference; const paginateResults = ( query: Query, startAfter?: unknown ): Promise<PaginatedResults> => { return (startAfter ? query.startAfter(startAfter) : query) .get() .then(snapshot => { if (snapshot.empty) { return {pages: 0, docs: []}; } else { const docs = snapshot.docs; return paginateResults(query, docs[docs.length - 1]).then( nextPage => { return { pages: nextPage.pages + 1, docs: docs.concat(nextPage.docs), }; } ); } }); }; async function addDocs( ...docs: DocumentData[] ): Promise<DocumentReference[]> { let id = 0; // Guarantees consistent ordering for the first documents const refs: DocumentReference[] = []; for (const doc of docs) { const ref = randomCol.doc('doc' + id++); await ref.set(doc); refs.push(ref); } return refs; } function expectDocs(result: QuerySnapshot, ...data: DocumentData[]) { expect(result.size).to.equal(data.length); result.forEach(doc => { expect(doc.data()).to.deep.equal(data.shift()); }); } beforeEach(() => { firestore = new Firestore({}); randomCol = getTestRoot(firestore); }); afterEach(() => verifyInstance(firestore)); it('has firestore property', () => { const ref = randomCol.limit(0); expect(ref.firestore).to.be.an.instanceOf(Firestore); }); it('has select() method', () => { const ref = randomCol.doc('doc'); return ref .set({foo: 'bar', bar: 'foo'}) .then(() => { return randomCol.select('foo').get(); }) .then(res => { expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); }); }); it('select() supports empty fields', () => { const ref = randomCol.doc('doc'); return ref .set({foo: 'bar', bar: 'foo'}) .then(() => { return randomCol.select().get(); }) .then(res => { expect(res.docs[0].ref.id).to.deep.equal('doc'); expect(res.docs[0].data()).to.deep.equal({}); }); }); it('has where() method', () => { const ref = randomCol.doc('doc'); return ref .set({foo: 'bar'}) .then(() => { return randomCol.where('foo', '==', 'bar').get(); }) .then(res => { expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); }); }); it('supports NaN and Null', () => { const ref = randomCol.doc('doc'); return ref .set({foo: NaN, bar: null}) .then(() => { return randomCol.where('foo', '==', NaN).where('bar', '==', null).get(); }) .then(res => { expect( typeof res.docs[0].get('foo') === 'number' && isNaN(res.docs[0].get('foo')) ); expect(res.docs[0].get('bar')).to.equal(null); }); }); it('supports array-contains', () => { return Promise.all([ randomCol.add({foo: ['bar']}), randomCol.add({foo: []}), ]) .then(() => randomCol.where('foo', 'array-contains', 'bar').get()) .then(res => { expect(res.size).to.equal(1); expect(res.docs[0].get('foo')).to.deep.equal(['bar']); }); }); it('supports !=', async () => { await addDocs( {zip: NaN}, {zip: 91102}, {zip: 98101}, {zip: 98103}, {zip: [98101]}, {zip: ['98101', {zip: 98101}]}, {zip: {zip: 98101}}, {zip: null} ); let res = await randomCol.where('zip', '!=', 98101).get(); expectDocs( res, {zip: NaN}, {zip: 91102}, {zip: 98103}, {zip: [98101]}, {zip: ['98101', {zip: 98101}]}, {zip: {zip: 98101}} ); res = await randomCol.where('zip', '!=', NaN).get(); expectDocs( res, {zip: 91102}, {zip: 98101}, {zip: 98103}, {zip: [98101]}, {zip: ['98101', {zip: 98101}]}, {zip: {zip: 98101}} ); res = await randomCol.where('zip', '!=', null).get(); expectDocs( res, {zip: NaN}, {zip: 91102}, {zip: 98101}, {zip: 98103}, {zip: [98101]}, {zip: ['98101', {zip: 98101}]}, {zip: {zip: 98101}} ); }); it('supports != with document ID', async () => { const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); const res = await randomCol .where(FieldPath.documentId(), '!=', refs[0].id) .get(); expectDocs(res, {count: 2}, {count: 3}); }); it('supports not-in', async () => { await addDocs( {zip: 98101}, {zip: 91102}, {zip: 98103}, {zip: [98101]}, {zip: ['98101', {zip: 98101}]}, {zip: {zip: 98101}} ); let res = await randomCol.where('zip', 'not-in', [98101, 98103]).get(); expectDocs( res, {zip: 91102}, {zip: [98101]}, {zip: ['98101', {zip: 98101}]}, {zip: {zip: 98101}} ); res = await randomCol.where('zip', 'not-in', [NaN]).get(); expectDocs( res, {zip: 91102}, {zip: 98101}, {zip: 98103}, {zip: [98101]}, {zip: ['98101', {zip: 98101}]}, {zip: {zip: 98101}} ); res = await randomCol.where('zip', 'not-in', [null]).get(); expect(res.size).to.equal(0); }); it('supports not-in with document ID array', async () => { const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); const res = await randomCol .where(FieldPath.documentId(), 'not-in', [refs[0].id, refs[1]]) .get(); expectDocs(res, {count: 3}); }); it('supports "in"', async () => { await addDocs( {zip: 98101}, {zip: 91102}, {zip: 98103}, {zip: [98101]}, {zip: ['98101', {zip: 98101}]}, {zip: {zip: 98101}} ); const res = await randomCol.where('zip', 'in', [98101, 98103]).get(); expectDocs(res, {zip: 98101}, {zip: 98103}); }); it('supports "in" with document ID array', async () => { const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); const res = await randomCol .where(FieldPath.documentId(), 'in', [refs[0].id, refs[1]]) .get(); expectDocs(res, {count: 1}, {count: 2}); }); it('supports array-contains-any', async () => { await addDocs( {array: [42]}, {array: ['a', 42, 'c']}, {array: [41.999, '42', {a: [42]}]}, {array: [42], array2: ['sigh']}, {array: [43]}, {array: [{a: 42}]}, {array: 42} ); const res = await randomCol .where('array', 'array-contains-any', [42, 43]) .get(); expectDocs( res, {array: [42]}, {array: ['a', 42, 'c']}, { array: [42], array2: ['sigh'], }, {array: [43]} ); }); it('can query by FieldPath.documentId()', () => { const ref = randomCol.doc('foo'); return ref .set({}) .then(() => { return randomCol.where(FieldPath.documentId(), '>=', 'bar').get(); }) .then(res => { expect(res.docs.length).to.equal(1); }); }); it('has orderBy() method', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); let res = await randomCol.orderBy('foo').get(); expectDocs(res, {foo: 'a'}, {foo: 'b'}); res = await randomCol.orderBy('foo', 'desc').get(); expectDocs(res, {foo: 'b'}, {foo: 'a'}); }); it('can order by FieldPath.documentId()', () => { const ref1 = randomCol.doc('doc1'); const ref2 = randomCol.doc('doc2'); return Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]) .then(() => { return randomCol.orderBy(FieldPath.documentId()).get(); }) .then(res => { expect(res.docs[0].data()).to.deep.equal({foo: 'a'}); expect(res.docs[1].data()).to.deep.equal({foo: 'b'}); }); }); it('has limit() method', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); const res = await randomCol.orderBy('foo').limit(1).get(); expectDocs(res, {foo: 'a'}); }); it('has limitToLast() method', async () => { await addDocs({doc: 1}, {doc: 2}, {doc: 3}); const res = await randomCol.orderBy('doc').limitToLast(2).get(); expectDocs(res, {doc: 2}, {doc: 3}); }); it('limitToLast() supports Query cursors', async () => { await addDocs({doc: 1}, {doc: 2}, {doc: 3}, {doc: 4}, {doc: 5}); const res = await randomCol .orderBy('doc') .startAt(2) .endAt(4) .limitToLast(5) .get(); expectDocs(res, {doc: 2}, {doc: 3}, {doc: 4}); }); it('has offset() method', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); const res = await randomCol.orderBy('foo').offset(1).get(); expectDocs(res, {foo: 'b'}); }); it('supports Unicode in document names', async () => { const collRef = randomCol.doc('доброеутро').collection('coll'); await collRef.add({}); const snapshot = await collRef.get(); expect(snapshot.size).to.equal(1); }); it('supports pagination', () => { const batch = firestore.batch(); for (let i = 0; i < 10; ++i) { batch.set(randomCol.doc('doc' + i), {val: i}); } const query = randomCol.orderBy('val').limit(3); return batch .commit() .then(() => paginateResults(query)) .then(results => { expect(results.pages).to.equal(4); expect(results.docs).to.have.length(10); }); }); it('supports pagination with where() clauses', () => { const batch = firestore.batch(); for (let i = 0; i < 10; ++i) { batch.set(randomCol.doc('doc' + i), {val: i}); } const query = randomCol.where('val', '>=', 1).limit(3); return batch .commit() .then(() => paginateResults(query)) .then(results => { expect(results.pages).to.equal(3); expect(results.docs).to.have.length(9); }); }); it('supports pagination with array-contains filter', () => { const batch = firestore.batch(); for (let i = 0; i < 10; ++i) { batch.set(randomCol.doc('doc' + i), {array: ['foo']}); } const query = randomCol.where('array', 'array-contains', 'foo').limit(3); return batch .commit() .then(() => paginateResults(query)) .then(results => { expect(results.pages).to.equal(4); expect(results.docs).to.have.length(10); }); }); it('has startAt() method', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); const res = await randomCol.orderBy('foo').startAt('b').get(); expectDocs(res, {foo: 'b'}); }); it('startAt() adds implicit order by for DocumentReference', async () => { const references = await addDocs({foo: 'a'}, {foo: 'b'}); const res = await randomCol.startAt(references[1]).get(); expectDocs(res, {foo: 'b'}); }); it('has startAfter() method', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); const res = await randomCol.orderBy('foo').startAfter('a').get(); expectDocs(res, {foo: 'b'}); }); it('has endAt() method', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); const res = await randomCol.orderBy('foo').endAt('b').get(); expectDocs(res, {foo: 'a'}, {foo: 'b'}); }); it('has endBefore() method', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); const res = await randomCol.orderBy('foo').endBefore('b').get(); expectDocs(res, {foo: 'a'}); }); it('has stream() method', done => { let received = 0; const ref1 = randomCol.doc('doc1'); const ref2 = randomCol.doc('doc2'); Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]).then(() => { return randomCol .stream() .on('data', d => { expect(d).to.be.an.instanceOf(DocumentSnapshot); ++received; }) .on('end', () => { expect(received).to.equal(2); done(); }); }); }); it('stream() supports readable[Symbol.asyncIterator]()', async () => { let received = 0; await randomCol.doc().set({foo: 'bar'}); await randomCol.doc().set({foo: 'bar'}); const stream = randomCol.stream(); for await (const doc of stream) { expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); ++received; } expect(received).to.equal(2); }); it('can query collection groups', async () => { // Use `randomCol` to get a random collection group name to use but ensure // it starts with 'b' for predictable ordering. const collectionGroup = 'b' + randomCol.id; const docPaths = [ `abc/123/${collectionGroup}/cg-doc1`, `abc/123/${collectionGroup}/cg-doc2`, `${collectionGroup}/cg-doc3`, `${collectionGroup}/cg-doc4`, `def/456/${collectionGroup}/cg-doc5`, `${collectionGroup}/virtual-doc/nested-coll/not-cg-doc`, `x${collectionGroup}/not-cg-doc`, `${collectionGroup}x/not-cg-doc`, `abc/123/${collectionGroup}x/not-cg-doc`, `abc/123/x${collectionGroup}/not-cg-doc`, `abc/${collectionGroup}`, ]; const batch = firestore.batch(); for (const docPath of docPaths) { batch.set(firestore.doc(docPath), {x: 1}); } await batch.commit(); const querySnapshot = await firestore .collectionGroup(collectionGroup) .get(); expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ 'cg-doc1', 'cg-doc2', 'cg-doc3', 'cg-doc4', 'cg-doc5', ]); }); it('can query collection groups with startAt / endAt by arbitrary documentId', async () => { // Use `randomCol` to get a random collection group name to use but // ensure it starts with 'b' for predictable ordering. const collectionGroup = 'b' + randomCol.id; const docPaths = [ `a/a/${collectionGroup}/cg-doc1`, `a/b/a/b/${collectionGroup}/cg-doc2`, `a/b/${collectionGroup}/cg-doc3`, `a/b/c/d/${collectionGroup}/cg-doc4`, `a/c/${collectionGroup}/cg-doc5`, `${collectionGroup}/cg-doc6`, 'a/b/nope/nope', ]; const batch = firestore.batch(); for (const docPath of docPaths) { batch.set(firestore.doc(docPath), {x: 1}); } await batch.commit(); let querySnapshot = await firestore .collectionGroup(collectionGroup) .orderBy(FieldPath.documentId()) .startAt('a/b') .endAt('a/b0') .get(); expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ 'cg-doc2', 'cg-doc3', 'cg-doc4', ]); querySnapshot = await firestore .collectionGroup(collectionGroup) .orderBy(FieldPath.documentId()) .startAfter('a/b') .endBefore(`a/b/${collectionGroup}/cg-doc3`) .get(); expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); }); it('can query collection groups with where filters on arbitrary documentId', async () => { // Use `randomCol` to get a random collection group name to use but // ensure it starts with 'b' for predictable ordering. const collectionGroup = 'b' + randomCol.id; const docPaths = [ `a/a/${collectionGroup}/cg-doc1`, `a/b/a/b/${collectionGroup}/cg-doc2`, `a/b/${collectionGroup}/cg-doc3`, `a/b/c/d/${collectionGroup}/cg-doc4`, `a/c/${collectionGroup}/cg-doc5`, `${collectionGroup}/cg-doc6`, 'a/b/nope/nope', ]; const batch = firestore.batch(); for (const docPath of docPaths) { batch.set(firestore.doc(docPath), {x: 1}); } await batch.commit(); let querySnapshot = await firestore .collectionGroup(collectionGroup) .where(FieldPath.documentId(), '>=', 'a/b') .where(FieldPath.documentId(), '<=', 'a/b0') .get(); expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ 'cg-doc2', 'cg-doc3', 'cg-doc4', ]); querySnapshot = await firestore .collectionGroup(collectionGroup) .where(FieldPath.documentId(), '>', 'a/b') .where(FieldPath.documentId(), '<', `a/b/${collectionGroup}/cg-doc3`) .get(); expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); }); it('can query large collections', async () => { // @grpc/grpc-js v0.4.1 failed to deliver the full set of query results for // larger collections (https://github.com/grpc/grpc-node/issues/895); const batch = firestore.batch(); for (let i = 0; i < 100; ++i) { batch.create(randomCol.doc(), {}); } await batch.commit(); const snapshot = await randomCol.get(); expect(snapshot.size).to.equal(100); }); describe('watch', () => { interface ExpectedChange { type: string; doc: DocumentSnapshot; } const currentDeferred = new DeferredPromise<QuerySnapshot>(); const snapshot = (id: string, data: DocumentData) => { const ref = randomCol.doc(id); const fields = ref.firestore._serializer!.encodeFields(data); return randomCol.firestore.snapshot_( { name: 'projects/ignored/databases/(default)/documents/' + ref._path.relativeName, fields, createTime: {seconds: 0, nanos: 0}, updateTime: {seconds: 0, nanos: 0}, }, {seconds: 0, nanos: 0} ); }; const docChange = ( type: string, id: string, data: DocumentData ): ExpectedChange => { return { type, doc: snapshot(id, data), }; }; const added = (id: string, data: DocumentData) => docChange('added', id, data); const modified = (id: string, data: DocumentData) => docChange('modified', id, data); const removed = (id: string, data: DocumentData) => docChange('removed', id, data); function resetPromise() { currentDeferred.promise = new Promise((resolve, reject) => { currentDeferred.resolve = resolve; currentDeferred.reject = reject; }); } function waitForSnapshot(): Promise<QuerySnapshot> { return currentDeferred.promise!.then(snapshot => { resetPromise(); return snapshot; }); } function snapshotsEqual( actual: QuerySnapshot, expected: {docs: DocumentSnapshot[]; docChanges: ExpectedChange[]} ) { let i; expect(actual.size).to.equal(expected.docs.length); for (i = 0; i < expected.docs.length && i < actual.size; i++) { expect(actual.docs[i].ref.id).to.equal(expected.docs[i].ref.id); expect(actual.docs[i].data()).to.deep.equal(expected.docs[i].data()); } const actualDocChanges = actual.docChanges(); expect(actualDocChanges.length).to.equal(expected.docChanges.length); for (i = 0; i < expected.docChanges.length; i++) { expect(actualDocChanges[i].type).to.equal(expected.docChanges[i].type); expect(actualDocChanges[i].doc.ref.id).to.equal( expected.docChanges[i].doc.ref.id ); expect(actualDocChanges[i].doc.data()).to.deep.equal( expected.docChanges[i].doc.data() ); expect(actualDocChanges[i].doc.readTime).to.exist; expect(actualDocChanges[i].doc.createTime).to.exist; expect(actualDocChanges[i].doc.updateTime).to.exist; } expect(actual.readTime).to.exist; } beforeEach(() => resetPromise()); it('handles changing a doc', () => { const ref1 = randomCol.doc('doc1'); const ref2 = randomCol.doc('doc2'); const unsubscribe = randomCol.onSnapshot( snapshot => { currentDeferred.resolve(snapshot); }, err => { currentDeferred.reject!(err); } ); return waitForSnapshot() .then(results => { snapshotsEqual(results, {docs: [], docChanges: []}); // Add a result. return ref1.set({foo: 'a'}); }) .then(() => { return waitForSnapshot(); }) .then(results => { snapshotsEqual(results, { docs: [snapshot('doc1', {foo: 'a'})], docChanges: [added('doc1', {foo: 'a'})], }); // Add another result. return ref2.set({foo: 'b'}); }) .then(() => { return waitForSnapshot(); }) .then(results => { snapshotsEqual(results, { docs: [snapshot('doc1', {foo: 'a'}), snapshot('doc2', {foo: 'b'})], docChanges: [added('doc2', {foo: 'b'})], }); // Change a result. return ref2.set({bar: 'c'}); }) .then(() => { return waitForSnapshot(); }) .then(results => { snapshotsEqual(results, { docs: [snapshot('doc1', {foo: 'a'}), snapshot('doc2', {bar: 'c'})], docChanges: [modified('doc2', {bar: 'c'})], }); unsubscribe(); }); }); it("handles changing a doc so it doesn't match", () => { const ref1 = randomCol.doc('doc1'); const ref2 = randomCol.doc('doc2'); const query = randomCol.where('included', '==', 'yes'); const unsubscribe = query.onSnapshot( snapshot => { currentDeferred.resolve(snapshot); }, err => { currentDeferred.reject(err); } ); return waitForSnapshot() .then(results => { snapshotsEqual(results, {docs: [], docChanges: []}); // Add a result. return ref1.set({included: 'yes'}); }) .then(() => { return waitForSnapshot(); }) .then(results => { snapshotsEqual(results, { docs: [snapshot('doc1', {included: 'yes'})], docChanges: [added('doc1', {included: 'yes'})], }); // Add another result. return ref2.set({included: 'yes'}); }) .then(() => { return waitForSnapshot(); }) .then(results => { snapshotsEqual(results, { docs: [ snapshot('doc1', {included: 'yes'}), snapshot('doc2', {included: 'yes'}), ], docChanges: [added('doc2', {included: 'yes'})], }); // Change a result. return ref2.set({included: 'no'}); }) .then(() => { return waitForSnapshot(); }) .then(results => { snapshotsEqual(results, { docs: [snapshot('doc1', {included: 'yes'})], docChanges: [removed('doc2', {included: 'yes'})], }); unsubscribe(); }); }); it('handles deleting a doc', () => { const ref1 = randomCol.doc('doc1'); const ref2 = randomCol.doc('doc2'); const unsubscribe = randomCol.onSnapshot( snapshot => { currentDeferred.resolve(snapshot); }, err => { currentDeferred.reject(err); } ); return waitForSnapshot() .then(results => { snapshotsEqual(results, {docs: [], docChanges: []}); // Add a result. return ref1.set({included: 'yes'}); }) .then(() => { return waitForSnapshot(); }) .then(results => { snapshotsEqual(results, { docs: [snapshot('doc1', {included: 'yes'})], docChanges: [added('doc1', {included: 'yes'})], }); // Add another result. return ref2.set({included: 'yes'}); }) .then(() => { return waitForSnapshot(); }) .then(results => { snapshotsEqual(results, { docs: [ snapshot('doc1', {included: 'yes'}), snapshot('doc2', {included: 'yes'}), ], docChanges: [added('doc2', {included: 'yes'})], }); // Delete a result. return ref2.delete(); }) .then(() => { return waitForSnapshot(); }) .then(results => { snapshotsEqual(results, { docs: [snapshot('doc1', {included: 'yes'})], docChanges: [removed('doc2', {included: 'yes'})], }); unsubscribe(); }); }); it('orders limitToLast() correctly', async () => { const ref1 = randomCol.doc('doc1'); const ref2 = randomCol.doc('doc2'); const ref3 = randomCol.doc('doc3'); await ref1.set({doc: 1}); await ref2.set({doc: 2}); await ref3.set({doc: 3}); const unsubscribe = randomCol .orderBy('doc') .limitToLast(2) .onSnapshot(snapshot => currentDeferred.resolve(snapshot)); const results = await waitForSnapshot(); snapshotsEqual(results, { docs: [snapshot('doc2', {doc: 2}), snapshot('doc3', {doc: 3})], docChanges: [added('doc2', {doc: 2}), added('doc3', {doc: 3})], }); unsubscribe(); }); }); }); describe('Transaction class', () => { let firestore: Firestore; let randomCol: CollectionReference; beforeEach(() => { firestore = new Firestore({}); randomCol = getTestRoot(firestore); }); afterEach(() => verifyInstance(firestore)); it('has get() method', () => { const ref = randomCol.doc('doc'); return ref .set({foo: 'bar'}) .then(() => { return firestore.runTransaction(updateFunction => { return updateFunction.get(ref).then(doc => { return Promise.resolve(doc.get('foo')); }); }); }) .then(res => { expect(res).to.equal('bar'); }); }); it('has getAll() method', () => { const ref1 = randomCol.doc('doc1'); const ref2 = randomCol.doc('doc2'); return Promise.all([ref1.set({}), ref2.set({})]) .then(() => { return firestore.runTransaction(updateFunction => { return updateFunction.getAll(ref1, ref2).then(docs => { return Promise.resolve(docs.length); }); }); }) .then(res => { expect(res).to.equal(2); }); }); it('getAll() supports array destructuring', () => { const ref1 = randomCol.doc('doc1'); const ref2 = randomCol.doc('doc2'); return Promise.all([ref1.set({}), ref2.set({})]) .then(() => { return firestore.runTransaction(updateFunction => { return updateFunction.getAll(...[ref1, ref2]).then(docs => { return Promise.resolve(docs.length); }); }); }) .then(res => { expect(res).to.equal(2); }); }); it('getAll() supports field mask', () => { const ref1 = randomCol.doc('doc1'); return ref1.set({foo: 'a', bar: 'b'}).then(() => { return firestore .runTransaction(updateFunction => { return updateFunction .getAll(ref1, {fieldMask: ['foo']}) .then(([doc]) => doc); }) .then(doc => { expect(doc.data()).to.deep.equal({foo: 'a'}); }); }); }); it('getAll() supports array destructuring with field mask', () => { const ref1 = randomCol.doc('doc1'); const ref2 = randomCol.doc('doc2'); return Promise.all([ ref1.set({f: 'a', b: 'b'}), ref2.set({f: 'a', b: 'b'}), ]).then(() => { return firestore .runTransaction(updateFunction => { return updateFunction .getAll(...[ref1, ref2], {fieldMask: ['f']}) .then(docs => docs); }) .then(docs => { expect(docs[0].data()).to.deep.equal({f: 'a'}); expect(docs[1].data()).to.deep.equal({f: 'a'}); }); }); }); it('getAll() supports withConverter()', async () => { const ref1 = randomCol.doc('doc1').withConverter(postConverter); const ref2 = randomCol.doc('doc2').withConverter(postConverter); await ref1.set(new Post('post1', 'author1')); await ref2.set(new Post('post2', 'author2')); const docs = await firestore.runTransaction(updateFunction => { return updateFunction.getAll(ref1, ref2); }); expect(docs[0].data()!.toString()).to.equal('post1, by author1'); expect(docs[1].data()!.toString()).to.equal('post2, by author2'); }); it('set() and get() support withConverter()', async () => { const ref = randomCol.doc('doc1').withConverter(postConverter); await ref.set(new Post('post', 'author')); await firestore.runTransaction(async txn => { await txn.get(ref); await txn.set(ref, new Post('new post', 'author')); }); const doc = await ref.get(); expect(doc.data()!.toString()).to.equal('new post, by author'); }); it('has get() with query', () => { const ref = randomCol.doc('doc'); const query = randomCol.where('foo', '==', 'bar'); return ref .set({foo: 'bar'}) .then(() => { return firestore.runTransaction(updateFunction => { return updateFunction.get(query).then(res => { return Promise.resolve(res.docs[0].get('foo')); }); }); }) .then(res => { expect(res).to.equal('bar'); }); }); it('has set() method', () => { const ref = randomCol.doc('doc'); return firestore .runTransaction(updateFunction => { updateFunction.set(ref, {foo: 'foobar'}); return Promise.resolve(); }) .then(() => { return ref.get(); }) .then(doc => { expect(doc.get('foo')).to.equal('foobar'); }); }); it('has update() method', () => { const ref = randomCol.doc('doc'); return ref .set({ boo: ['ghost', 'sebastian'], moo: 'chicken', }) .then(() => { return firestore.runTransaction(updateFunction => { return updateFunction.get(ref).then(() => { updateFunction.update(ref, { boo: FieldValue.arrayRemove('sebastian'), moo: 'cow', }); }); }); }) .then(() => { return ref.get(); }) .then(doc => { expect(doc.data()).to.deep.equal({ boo: ['ghost'], moo: 'cow', }); }); }); it('has delete() method', () => { let success = false; const ref = randomCol.doc('doc'); return ref .set({foo: 'bar'}) .then(() => { return firestore.runTransaction(updateFunction => { updateFunction.delete(ref); return Promise.resolve(); }); }) .then(() => { success = true; return ref.get(); }) .then(result => { expect(success).to.be.true; expect(result.exists).to.be.false; }); }); it('does not retry transaction that fail with FAILED_PRECONDITION', async () => { const ref = firestore.collection('col').doc(); let attempts = 0; await expect( firestore.runTransaction(async transaction => { ++attempts; transaction.update(ref, {foo: 'b'}); }) ).to.eventually.be.rejectedWith('No document to update'); expect(attempts).to.equal(1); }); it('retries transactions that fail with contention', async () => { const ref = randomCol.doc('doc'); let attempts = 0; // Create two transactions that both read and update the same document. // `contentionPromise` is used to ensure that both transactions are active // on commit, which causes one of transactions to fail with Code ABORTED // and be retried. const contentionPromise = [new Deferred<void>(), new Deferred<void>()]; const firstTransaction = firestore.runTransaction(async transaction => { ++attempts; await transaction.get(ref); contentionPromise[0].resolve(); await contentionPromise[1].promise; transaction.set(ref, {first: true}, {merge: true}); }); const secondTransaction = firestore.runTransaction(async transaction => { ++attempts; await transaction.get(ref); contentionPromise[1].resolve(); await contentionPromise[0].promise; transaction.set(ref, {second: true}, {merge: true}); }); await firstTransaction; await secondTransaction; expect(attempts).to.equal(3); const finalSnapshot = await ref.get(); expect(finalSnapshot.data()).to.deep.equal({first: true, second: true}); }); it('supports read-only transactions', async () => { const ref = randomCol.doc('doc'); await ref.set({foo: 'bar'}); const snapshot = await firestore.runTransaction( updateFunction => updateFunction.get(ref), {readOnly: true} ); expect(snapshot.exists).to.be.true; }); it('supports read-only transactions with custom read-time', async () => { const ref = randomCol.doc('doc'); const writeResult = await ref.set({foo: 1}); await ref.set({foo: 2}); const snapshot = await firestore.runTransaction( updateFunction => updateFunction.get(ref), {readOnly: true, readTime: writeResult.writeTime} ); expect(snapshot.exists).to.be.true; expect(snapshot.get('foo')).to.equal(1); }); it('fails read-only with writes', async () => { let attempts = 0; const ref = randomCol.doc('doc'); try { await firestore.runTransaction( async updateFunction => { ++attempts; updateFunction.set(ref, {}); }, {readOnly: true} ); expect.fail(); } catch (e) { expect(attempts).to.equal(1); expect(e.code).to.equal(Status.INVALID_ARGUMENT); } }); }); describe('WriteBatch class', () => { let firestore: Firestore; let randomCol: CollectionReference; beforeEach(() => { firestore = new Firestore({}); randomCol = getTestRoot(firestore); }); afterEach(() => verifyInstance(firestore)); it('supports empty batches', () => { return firestore.batch().commit(); }); it('has create() method', () => { const ref = randomCol.doc(); const batch = firestore.batch(); batch.create(ref, {foo: 'a'}); return batch .commit() .then(() => { return ref.get(); }) .then(doc => { expect(doc.get('foo')).to.equal('a'); }); }); it('has set() method', () => { const ref = randomCol.doc('doc'); const batch = firestore.batch(); batch.set(ref, {foo: 'a'}); return batch .commit() .then(() => { return ref.get(); }) .then(doc => { expect(doc.get('foo')).to.equal('a'); }); }); it('set supports partials', async () => { const ref = randomCol.doc('doc').withConverter(postConverterMerge); await ref.set(new Post('walnut', 'author')); const batch = firestore.batch(); batch.set(ref, {title: 'olive'}, {merge: true}); return batch .commit() .then(() => { return ref.get(); }) .then(doc => { expect(doc.get('title')).to.equal('olive'); expect(doc.get('author')).to.equal('author'); }); }); it('set()', () => { const ref = randomCol.doc('doc'); const batch = firestore.batch(); batch.set(ref, {foo: 'a'}); return batch .commit() .then(() => { return ref.get(); }) .then(doc => { expect(doc.get('foo')).to.equal('a'); }); }); it('has a full stack trace if set() errors', () => { // Use an invalid document name that the backend will reject. const ref = randomCol.doc('__doc__'); const batch = firestore.batch(); batch.set(ref, {foo: 'a'}); return batch .commit() .then(() => Promise.reject('commit() should have failed')) .catch((err: Error) => { expect(err.stack).to.contain('WriteBatch.commit'); }); }); it('has update() method', () => { const ref = randomCol.doc('doc'); const batch = firestore.batch(); batch.set(ref, {foo: 'a'}); batch.update(ref, {foo: 'b'}); return batch .commit() .then(() => { return ref.get(); }) .then(doc => { expect(doc.get('foo')).to.equal('b'); }); }); it('omits document transforms from write results', () => { const batch = firestore.batch(); batch.set(randomCol.doc(), {foo: 'a'}); batch.set(randomCol.doc(), {foo: FieldValue.serverTimestamp()}); return batch.commit().then(writeResults => { expect(writeResults).to.have.length(2); }); }); it('enforces that updated document exists', () => { const ref = randomCol.doc(); const batch = firestore.batch(); batch.update(ref, {foo: 'b'}); return batch .commit() .then(() => { expect.fail(); }) .catch(err => { expect(err.message.match(/No document to update/)); }); }); it('has delete() method', () => { let success = false; const ref = randomCol.doc('doc'); const batch = firestore.batch(); batch.set(ref, {foo: 'a'}); batch.delete(ref); return batch .commit() .then(() => { success = true; return ref.get(); }) .then(result => { expect(success).to.be.true; expect(result.exists).to.be.false; }); }); }); describe('QuerySnapshot class', () => { let firestore: Firestore; let querySnapshot: Promise<QuerySnapshot>; beforeEach(() => { firestore = new Firestore({}); const randomCol = getTestRoot(firestore); const ref1 = randomCol.doc('doc1'); const ref2 = randomCol.doc('doc2'); querySnapshot = Promise.all([ ref1.set({foo: 'a'}), ref2.set({foo: 'a'}), ]).then(() => { return randomCol.get(); }); }); afterEach(() => verifyInstance(firestore)); it('has query property', () => { return querySnapshot .then(snapshot => { return snapshot.query.get(); }) .then(snapshot => { expect(snapshot.size).to.equal(2); }); }); it('has empty property', () => { return querySnapshot .then(snapshot => { expect(snapshot.empty).to.be.false; expect(snapshot.readTime).to.exist; return snapshot.query.where('foo', '==', 'bar').get(); }) .then(snapshot => { expect(snapshot.empty).to.be.true; expect(snapshot.readTime).to.exist; }); }); it('has size property', () => { return querySnapshot.then(snapshot => { expect(snapshot.size).to.equal(2); }); }); it('has docs property', () => { return querySnapshot.then(snapshot => { expect(snapshot.docs).to.have.length(2); expect(snapshot.docs[0].get('foo')).to.equal('a'); }); }); it('has forEach() method', () => { let count = 0; return querySnapshot.then(snapshot => { snapshot.forEach(doc => { expect(doc.get('foo')).to.equal('a'); ++count; }); expect(count).to.equal(2); }); }); }); describe('BulkWriter class', () => { let firestore: Firestore; let randomCol: CollectionReference; let writer: BulkWriter; beforeEach(() => { firestore = new Firestore({}); writer = firestore.bulkWriter(); randomCol = getTestRoot(firestore); }); afterEach(() => verifyInstance(firestore)); it('has create() method', async () => { const ref = randomCol.doc('doc1'); const singleOp = writer.create(ref, {foo: 'bar'}); await writer.close(); const result = await ref.get(); expect(result.data()).to.deep.equal({foo: 'bar'}); const writeTime = (await singleOp).writeTime; expect(writeTime).to.not.be.null; }); it('has set() method', async () => { const ref = randomCol.doc('doc1'); const singleOp = writer.set(ref, {foo: 'bar'}); await writer.close(); const result = await ref.get(); expect(result.data()).to.deep.equal({foo: 'bar'}); const writeTime = (await singleOp).writeTime; expect(writeTime).to.not.be.null; }); it('has update() method', async () => { const ref = randomCol.doc('doc1'); await ref.set({foo: 'bar'}); const singleOp = writer.update(ref, {foo: 'bar2'}); await writer.close(); const result = await ref.get(); expect(result.data()).to.deep.equal({foo: 'bar2'}); const writeTime = (await singleOp).writeTime; expect(writeTime).to.not.be.null; }); it('has delete() method', async () => { const ref = randomCol.doc('doc1'); await ref.set({foo: 'bar'}); const singleOp = writer.delete(ref); await writer.close(); const result = await ref.get(); expect(result.exists).to.be.false; // TODO(b/158502664): Remove this check once we can get write times. const deleteResult = await singleOp; expect(deleteResult.writeTime).to.deep.equal(new Timestamp(0, 0)); }); it('can write to the same document twice', async () => { const ref = randomCol.doc('doc1'); const op1 = writer.set(ref, {foo: 'bar'}); const op2 = writer.set(ref, {foo: 'bar2'}); await writer.close(); const result = await ref.get(); // The order of writes is not guaranteed. expect(result.get('foo')).to.not.be.undefined; const writeTime1 = (await op1).writeTime; const writeTime2 = (await op2).writeTime; expect(writeTime1).to.not.be.null; expect(writeTime2).to.not.be.null; }); it('can terminate once BulkWriter is closed', async () => { const ref = randomCol.doc('doc1'); writer.set(ref, {foo: 'bar'}); await writer.close(); return firestore.terminate(); }); describe('recursiveDelete()', () => { async function countDocumentChildren( ref: DocumentReference ): Promise<number> { let count = 0; const collections = await ref.listCollections(); for (const collection of collections) { count += await countCollectionChildren(collection); } return count; } async function countCollectionChildren( ref: CollectionReference ): Promise<number> { let count = 0; const docs = await ref.listDocuments(); for (const doc of docs) { count += (await countDocumentChildren(doc)) + 1; } return count; } beforeEach(async () => { // ROOT-DB // └── randomCol // ├── anna // └── bob // └── parentsCol // ├── charlie // └── daniel // └── childCol // ├── ernie // └── francis const batch = firestore.batch(); batch.set(randomCol.doc('anna'), {name: 'anna'}); batch.set(randomCol.doc('bob'), {name: 'bob'}); batch.set(randomCol.doc('bob/parentsCol/charlie'), {name: 'charlie'}); batch.set(randomCol.doc('bob/parentsCol/daniel'), {name: 'daniel'}); batch.set(randomCol.doc('bob/parentsCol/daniel/childCol/ernie'), { name: 'ernie', }); batch.set(randomCol.doc('bob/parentsCol/daniel/childCol/francis'), { name: 'francis', }); await batch.commit(); }); it('on top-level collection', async () => { await firestore.recursiveDelete(randomCol); expect(await countCollectionChildren(randomCol)).to.equal(0); }); it('on nested collection', async () => { const coll = randomCol.doc('bob').collection('parentsCol'); await firestore.recursiveDelete(coll); expect(await countCollectionChildren(coll)).to.equal(0); expect(await countCollectionChildren(randomCol)).to.equal(2); }); it('on nested document', async () => { const doc = randomCol.doc('bob/parentsCol/daniel'); await firestore.recursiveDelete(doc); const docSnap = await doc.get(); expect(docSnap.exists).to.be.false; expect(await countDocumentChildren(randomCol.doc('bob'))).to.equal(1); expect(await countCollectionChildren(randomCol)).to.equal(3); }); it('on leaf document', async () => { const doc = randomCol.doc('bob/parentsCol/daniel/childCol/ernie'); await firestore.recursiveDelete(doc); const docSnap = await doc.get(); expect(docSnap.exists).to.be.false; expect(await countCollectionChildren(randomCol)).to.equal(5); }); it('does not affect other collections', async () => { // Add other nested collection that shouldn't be deleted. const collB = firestore.collection('doggos'); await collB.doc('doggo').set({name: 'goodboi'}); await firestore.recursiveDelete(collB); expect(await countCollectionChildren(randomCol)).to.equal(6); expect(await countCollectionChildren(collB)).to.equal(0); }); it('with custom BulkWriter instance', async () => { const bulkWriter = firestore.bulkWriter(); let callbackCount = 0; bulkWriter.onWriteResult(() => { callbackCount++; }); await firestore.recursiveDelete(randomCol, bulkWriter); expect(callbackCount).to.equal(6); }); }); it('can retry failed writes with a provided callback', async () => { let retryCount = 0; let code: Status = -1; writer.onWriteError(error => { retryCount = error.failedAttempts; return error.failedAttempts < 3; }); // Use an invalid document name that the backend will reject. const ref = randomCol.doc('__doc__'); writer.create(ref, {foo: 'bar'}).catch(err => { code = err.code; }); await writer.close(); expect(retryCount).to.equal(3); expect(code).to.equal(Status.INVALID_ARGUMENT); }); }); describe('Client initialization', () => { const ops: Array<[string, (coll: CollectionReference) => Promise<unknown>]> = [ ['CollectionReference.get()', randomColl => randomColl.get()], ['CollectionReference.add()', randomColl => randomColl.add({})], [ 'CollectionReference.stream()', randomColl => { const deferred = new Deferred<void>(); randomColl.stream().on('finish', () => { deferred.resolve(); }); return deferred.promise; }, ], [ 'CollectionReference.listDocuments()', randomColl => randomColl.listDocuments(), ], [ 'CollectionReference.onSnapshot()', randomColl => { const deferred = new Deferred<void>(); const unsubscribe = randomColl.onSnapshot(() => { unsubscribe(); deferred.resolve(); }); return deferred.promise; }, ], ['DocumentReference.get()', randomColl => randomColl.doc().get()], ['DocumentReference.create()', randomColl => randomColl.doc().create({})], ['DocumentReference.set()', randomColl => randomColl.doc().set({})], [ 'DocumentReference.update()', async randomColl => { const update = randomColl.doc().update('foo', 'bar'); await expect(update).to.eventually.be.rejectedWith( 'No document to update' ); }, ], ['DocumentReference.delete()', randomColl => randomColl.doc().delete()], [ 'DocumentReference.listCollections()', randomColl => randomColl.doc().listCollections(), ], [ 'DocumentReference.onSnapshot()', randomColl => { const deferred = new Deferred<void>(); const unsubscribe = randomColl.doc().onSnapshot(() => { unsubscribe(); deferred.resolve(); }); return deferred.promise; }, ], [ 'CollectionGroup.getPartitions()', async randomColl => { const partitions = randomColl.firestore .collectionGroup('id') .getPartitions(2); // eslint-disable-next-line @typescript-eslint/no-unused-vars for await (const _ of partitions); }, ], [ 'Firestore.runTransaction()', randomColl => randomColl.firestore.runTransaction(t => t.get(randomColl)), ], [ 'Firestore.getAll()', randomColl => randomColl.firestore.getAll(randomColl.doc()), ], [ 'Firestore.batch()', randomColl => randomColl.firestore.batch().commit(), ], ['Firestore.terminate()', randomColl => randomColl.firestore.terminate()], ]; for (const [description, op] of ops) { it(`succeeds for ${description}`, () => { const firestore = new Firestore(); const randomCol = getTestRoot(firestore); return op(randomCol); }); } }); describe('Bundle building', () => { let firestore: Firestore; let testCol: CollectionReference; beforeEach(async () => { firestore = new Firestore({}); testCol = getTestRoot(firestore); const ref1 = testCol.doc('doc1'); const ref2 = testCol.doc('doc2'); const ref3 = testCol.doc('doc3'); const ref4 = testCol.doc('doc4'); await Promise.all([ ref1.set({name: '1', sort: 1, value: 'string value'}), ref2.set({name: '2', sort: 2, value: 42}), ref3.set({name: '3', sort: 3, value: {nested: 'nested value'}}), ref4.set({ name: '4', sort: 4, value: FieldValue.serverTimestamp(), }), ]); }); afterEach(() => verifyInstance(firestore)); it('succeeds when there are no results', async () => { const bundle = firestore.bundle(TEST_BUNDLE_ID); const query = testCol.where('value', '==', '42'); const snap = await query.get(); bundle.add('query', snap); // `elements` is expected to be [bundleMeta, query]. const elements = await bundleToElementArray(bundle.build()); const meta = (elements[0] as IBundleElement).metadata; verifyMetadata(meta!, snap.readTime.toProto().timestampValue!, 0); const namedQuery = (elements[1] as IBundleElement).namedQuery; // Verify saved query. expect(namedQuery).to.deep.equal({ name: 'query', readTime: snap.readTime.toProto().timestampValue, // TODO(wuandy): Fix query.toProto to skip undefined fields, so we can stop using `extend` here. bundledQuery: extend( true, {}, { parent: query.toProto().parent, structuredQuery: query.toProto().structuredQuery, } ), }); }); it('succeeds when added document does not exist', async () => { const bundle = firestore.bundle(TEST_BUNDLE_ID); const snap = await testCol.doc('doc5-not-exist').get(); bundle.add(snap); // `elements` is expected to be [bundleMeta, docMeta]. const elements = await bundleToElementArray(bundle.build()); expect(elements.length).to.equal(2); const meta = (elements[0] as IBundleElement).metadata; verifyMetadata(meta!, snap.readTime.toProto().timestampValue!, 1); const docMeta = (elements[1] as IBundleElement).documentMetadata; expect(docMeta).to.deep.equal({ name: snap.toDocumentProto().name, readTime: snap.readTime.toProto().timestampValue, exists: false, }); }); it('succeeds to save limit and limitToLast queries', async () => { const bundle = firestore.bundle(TEST_BUNDLE_ID); const limitQuery = testCol.orderBy('sort', 'desc').limit(1); const limitSnap = await limitQuery.get(); const limitToLastQuery = testCol.orderBy('sort', 'asc').limitToLast(1); const limitToLastSnap = await limitToLastQuery.get(); bundle.add('limitQuery', limitSnap); bundle.add('limitToLastQuery', limitToLastSnap); // `elements` is expected to be [bundleMeta, limitQuery, limitToLastQuery, doc4Meta, doc4Snap]. const elements = await bundleToElementArray(await bundle.build()); const meta = (elements[0] as IBundleElement).metadata; verifyMetadata( meta!, limitToLastSnap.readTime.toProto().timestampValue!, 1 ); let namedQuery1 = (elements[1] as IBundleElement).namedQuery; let namedQuery2 = (elements[2] as IBundleElement).namedQuery; // We might need to swap them. if (namedQuery1!.name === 'limitToLastQuery') { const temp = namedQuery2; namedQuery2 = namedQuery1; namedQuery1 = temp; } // Verify saved limit query. expect(namedQuery1).to.deep.equal({ name: 'limitQuery', readTime: limitSnap.readTime.toProto().timestampValue, bundledQuery: extend( true, {}, { parent: limitQuery.toProto().parent, structuredQuery: limitQuery.toProto().structuredQuery, limitType: 'FIRST', } ), }); // `limitToLastQuery`'s structured query should be the same as this one. This together with // `limitType` can re-construct a limitToLast client query by client SDKs. const q = testCol.orderBy('sort', 'asc').limit(1); // Verify saved limitToLast query. expect(namedQuery2).to.deep.equal({ name: 'limitToLastQuery', readTime: limitToLastSnap.readTime.toProto().timestampValue, bundledQuery: extend( true, {}, { parent: q.toProto().parent, structuredQuery: q.toProto().structuredQuery, limitType: 'LAST', } ), }); // Verify bundled document const docMeta = (elements[3] as IBundleElement).documentMetadata; expect(docMeta).to.deep.equal({ name: limitToLastSnap.docs[0].toDocumentProto().name, readTime: limitToLastSnap.readTime.toProto().timestampValue, exists: true, queries: ['limitQuery', 'limitToLastQuery'], }); const bundledDoc = (elements[4] as IBundleElement).document; // The `valueType` is auxiliary and does not exist in proto. const expected = limitToLastSnap.docs[0].toDocumentProto(); // eslint-disable-next-line @typescript-eslint/no-explicit-any delete (expected.fields!.name as any).valueType; // eslint-disable-next-line @typescript-eslint/no-explicit-any delete (expected.fields!.sort as any).valueType; // eslint-disable-next-line @typescript-eslint/no-explicit-any delete (expected.fields!.value as any).valueType; expect(bundledDoc).to.deep.equal(expected); }); }); describe('Types test', () => { let firestore: Firestore; let randomCol: CollectionReference; let doc: DocumentReference; class TestObject { constructor( readonly outerString: string, readonly outerArr: string[], readonly nested: { innerNested: { innerNestedNum: number; }; innerArr: number[]; timestamp: Timestamp; } ) {} } const testConverter = { toFirestore(testObj: WithFieldValue<TestObject>) { return {...testObj}; }, fromFirestore(snapshot: QueryDocumentSnapshot): TestObject { const data = snapshot.data(); return new TestObject(data.outerString, data.outerArr, data.nested); }, }; const initialData = { outerString: 'foo', outerArr: [], nested: { innerNested: { innerNestedNum: 2, }, innerArr: FieldValue.arrayUnion(2), timestamp: FieldValue.serverTimestamp(), }, }; beforeEach(async () => { firestore = new Firestore({}); randomCol = getTestRoot(firestore); doc = randomCol.doc(); await doc.set(initialData); }); afterEach(() => verifyInstance(firestore)); describe('Nested partial support', () => { const testConverterMerge = { toFirestore( testObj: PartialWithFieldValue<TestObject>, options?: SetOptions ) { if (options) { expect(testObj).to.not.be.an.instanceOf(TestObject); } else { expect(testObj).to.be.an.instanceOf(TestObject); } return {...testObj}; }, fromFirestore(snapshot: QueryDocumentSnapshot): TestObject { const data = snapshot.data(); return new TestObject(data.outerString, data.outerArr, data.nested); }, }; it('supports FieldValues', async () => { const ref = doc.withConverter(testConverterMerge); // Allow Field Values in nested partials. await ref.set( { outerString: FieldValue.delete(), nested: { innerNested: { innerNestedNum: FieldValue.increment(1), }, innerArr: FieldValue.arrayUnion(2), timestamp: FieldValue.serverTimestamp(), }, }, {merge: true} ); // Allow setting FieldValue on entire object field. await ref.set( { nested: FieldValue.delete(), }, {merge: true} ); }); it('validates types in outer and inner fields', async () => { const ref = doc.withConverter(testConverterMerge); // Check top-level fields. await ref.set( { // @ts-expect-error Should fail to transpile. outerString: 3, // @ts-expect-error Should fail to transpile. outerArr: null, }, {merge: true} ); // Check nested fields. await ref.set( { nested: { innerNested: { // @ts-expect-error Should fail to transpile. innerNestedNum: 'string', }, // @ts-expect-error Should fail to transpile. innerArr: null, }, }, {merge: true} ); await ref.set( { // @ts-expect-error Should fail to transpile. nested: 3, }, {merge: true} ); }); it('checks for nonexistent properties', async () => { const ref = doc.withConverter(testConverterMerge); // Top-level property. await ref.set( { // @ts-expect-error Should fail to transpile. nonexistent: 'foo', }, {merge: true} ); // Nested property await ref.set( { nested: { // @ts-expect-error Should fail to transpile. nonexistent: 'foo', }, }, {merge: true} ); }); it('allows omitting fields', async () => { const ref = doc.withConverter(testConverterMerge); // Omit outer fields. await ref.set( { outerString: '', nested: { innerNested: { innerNestedNum: FieldValue.increment(1), }, innerArr: FieldValue.arrayUnion(2), timestamp: FieldValue.serverTimestamp(), }, }, {merge: true} ); // Omit inner fields await ref.set( { outerString: '', outerArr: [], nested: { innerNested: { innerNestedNum: FieldValue.increment(1), }, timestamp: FieldValue.serverTimestamp(), }, }, {merge: true} ); }); }); describe('NestedPartial', () => { const testConverterMerge = { toFirestore( testObj: PartialWithFieldValue<TestObject>, options?: SetOptions ) { if (options) { expect(testObj).to.not.be.an.instanceOf(TestObject); } else { expect(testObj).to.be.an.instanceOf(TestObject); } return {...testObj}; }, fromFirestore(snapshot: QueryDocumentSnapshot): TestObject { const data = snapshot.data(); return new TestObject(data.outerString, data.outerArr, data.nested); }, }; it('supports FieldValues', async () => { const ref = doc.withConverter(testConverterMerge); // Allow Field Values in nested partials. await ref.set( { outerString: FieldValue.delete(), nested: { innerNested: { innerNestedNum: FieldValue.increment(1), }, innerArr: FieldValue.arrayUnion(2), timestamp: FieldValue.serverTimestamp(), }, }, {merge: true} ); // Allow setting FieldValue on entire object field. await ref.set( { nested: FieldValue.delete(), }, {merge: true} ); }); it('validates types in outer and inner fields', async () => { const ref = doc.withConverter(testConverterMerge); // Check top-level fields. await ref.set( { // @ts-expect-error Should fail to transpile. outerString: 3, // @ts-expect-error Should fail to transpile. outerArr: null, }, {merge: true} ); // Check nested fields. await ref.set( { nested: { innerNested: { // @ts-expect-error Should fail to transpile. innerNestedNum: 'string', }, // @ts-expect-error Should fail to transpile. innerArr: null, }, }, {merge: true} ); await ref.set( { // @ts-expect-error Should fail to transpile. nested: 3, }, {merge: true} ); }); it('checks for nonexistent properties', async () => { const ref = doc.withConverter(testConverterMerge); // Top-level property. await ref.set( { // @ts-expect-error Should fail to transpile. nonexistent: 'foo', }, {merge: true} ); // Nested property await ref.set( { nested: { // @ts-expect-error Should fail to transpile. nonexistent: 'foo', }, }, {merge: true} ); }); }); describe('WithFieldValue', () => { it('supports FieldValues', async () => { const ref = doc.withConverter(testConverter); // Allow Field Values and nested partials. await ref.set({ outerString: 'foo', outerArr: [], nested: { innerNested: { innerNestedNum: FieldValue.increment(1), }, innerArr: FieldValue.arrayUnion(2), timestamp: FieldValue.serverTimestamp(), }, }); }); it('requires all outer fields to be present', async () => { const ref = doc.withConverter(testConverter); // @ts-expect-error Should fail to transpile. await ref.set({ outerArr: [], nested: { innerNested: { innerNestedNum: FieldValue.increment(1), }, innerArr: FieldValue.arrayUnion(2), timestamp: FieldValue.serverTimestamp(), }, }); }); it('requires all inner fields to be present', async () => { const ref = doc.withConverter(testConverter); await ref.set({ outerString: '', outerArr: [], // @ts-expect-error Should fail to transpile. nested: { innerNested: { innerNestedNum: FieldValue.increment(1), }, timestamp: FieldValue.serverTimestamp(), }, }); }); it('validates inner and outer fields', async () => { const ref = doc.withConverter(testConverter); await ref.set({ outerString: 'foo', // @ts-expect-error Should fail to transpile. outerArr: 2, nested: { innerNested: { // @ts-expect-error Should fail to transpile. innerNestedNum: 'string', }, innerArr: FieldValue.arrayUnion(2), timestamp: FieldValue.serverTimestamp(), }, }); }); it('checks for nonexistent properties', async () => { const ref = doc.withConverter(testConverter); // Top-level nonexistent fields should error await ref.set({ outerString: 'foo', // @ts-expect-error Should fail to transpile. outerNum: 3, outerArr: [], nested: { innerNested: { innerNestedNum: 2, }, innerArr: FieldValue.arrayUnion(2), timestamp: FieldValue.serverTimestamp(), }, }); // Nested nonexistent fields should error await ref.set({ outerString: 'foo', outerNum: 3, outerArr: [], nested: { innerNested: { // @ts-expect-error Should fail to transpile. nonexistent: 'string', innerNestedNum: 2, }, innerArr: FieldValue.arrayUnion(2), timestamp: FieldValue.serverTimestamp(), }, }); }); it('allows certain types for not others', async () => { const withTryCatch = async ( fn: () => Promise<WriteResult> ): Promise<void> => { try { await fn(); } catch { // This is expected. } }; // These tests exist to establish which object types are allowed to be // passed in by default when `T = DocumentData`. Some objects extend // the Javascript `{}`, which is why they're allowed whereas others // throw an error. // @ts-expect-error This should fail to transpile. await withTryCatch(() => doc.set(1)); // @ts-expect-error This should fail to transpile. await withTryCatch(() => doc.set('foo')); // @ts-expect-error This should fail to transpile. await withTryCatch(() => doc.set(false)); // @ts-expect-error This should fail to transpile. await withTryCatch(() => doc.set(undefined)); // @ts-expect-error This should fail to transpile. await withTryCatch(() => doc.set(null)); await withTryCatch(() => doc.set([0])); await withTryCatch(() => doc.set(new Set<string>())); await withTryCatch(() => doc.set(new Map<string, number>())); }); describe('used as a type', () => { class ObjectWrapper<T> { withFieldValueT(value: WithFieldValue<T>): WithFieldValue<T> { return value; } withPartialFieldValueT( value: PartialWithFieldValue<T> ): PartialWithFieldValue<T> { return value; } // Wrapper to avoid having Firebase types in non-Firebase code. withT(value: T): void { this.withFieldValueT(value); } // Wrapper to avoid having Firebase types in non-Firebase code. withPartialT(value: Partial<T>): void { this.withPartialFieldValueT(value); } } it('supports passing in the object as `T`', () => { interface Foo { id: string; foo: number; } const foo = new ObjectWrapper<Foo>(); foo.withFieldValueT({id: '', foo: FieldValue.increment(1)}); foo.withPartialFieldValueT({foo: FieldValue.increment(1)}); foo.withT({id: '', foo: 1}); foo.withPartialT({foo: 1}); }); it('does not allow primitive types to use FieldValue', () => { type Bar = number; const bar = new ObjectWrapper<Bar>(); // @ts-expect-error This should fail to transpile. bar.withFieldValueT(FieldValue.increment(1)); // @ts-expect-error This should fail to transpile. bar.withPartialFieldValueT(FieldValue.increment(1)); }); }); }); describe('UpdateData', () => { it('supports FieldValues', async () => { const ref = doc.withConverter(testConverter); await ref.update({ outerString: FieldValue.delete(), nested: { innerNested: { innerNestedNum: FieldValue.increment(2), }, innerArr: FieldValue.arrayUnion(3), }, }); }); it('validates inner and outer fields', async () => { const ref = doc.withConverter(testConverter); await ref.update({ // @ts-expect-error Should fail to transpile. outerString: 3, nested: { innerNested: { // @ts-expect-error Should fail to transpile. innerNestedNum: 'string', }, // @ts-expect-error Should fail to transpile. innerArr: 2, }, }); }); it('supports string-separated fields', async () => { const ref = doc.withConverter(testConverter); await ref.update({ // @ts-expect-error Should fail to transpile. outerString: 3, // @ts-expect-error Should fail to transpile. 'nested.innerNested.innerNestedNum': 'string', // @ts-expect-error Should fail to transpile. 'nested.innerArr': 3, 'nested.timestamp': FieldValue.serverTimestamp(), }); // String comprehension works in nested fields. await ref.update({ nested: { innerNested: { // @ts-expect-error Should fail to transpile. innerNestedNum: 'string', }, // @ts-expect-error Should fail to transpile. innerArr: 3, }, }); }); it('supports optional fields', async () => { interface TestObjectOptional { optionalStr?: string; nested?: { requiredStr: string; }; } const testConverterOptional = { toFirestore(testObj: WithFieldValue<TestObjectOptional>) { return {...testObj}; }, fromFirestore(snapshot: QueryDocumentSnapshot): TestObjectOptional { const data = snapshot.data(); return { optionalStr: data.optionalStr, nested: data.nested, }; }, }; const ref = doc.withConverter(testConverterOptional); await ref.update({ optionalStr: 'foo', }); await ref.update({ optionalStr: 'foo', }); await ref.update({ nested: { requiredStr: 'foo', }, }); await ref.update({ 'nested.requiredStr': 'foo', }); }); it('supports null fields', async () => { interface TestObjectOptional { optionalStr?: string; nested?: { strOrNull: string | null; }; } const testConverterOptional = { toFirestore(testObj: WithFieldValue<TestObjectOptional>) { return {...testObj}; }, fromFirestore(snapshot: QueryDocumentSnapshot): TestObjectOptional { const data = snapshot.data(); return { optionalStr: data.optionalStr, nested: data.nested, }; }, }; const ref = doc.withConverter(testConverterOptional); await ref.update({ nested: { strOrNull: null, }, }); await ref.update({ 'nested.strOrNull': null, }); }); it('supports union fields', async () => { interface TestObjectUnion { optionalStr?: string; nested?: | { requiredStr: string; } | {requiredNumber: number}; } const testConverterUnion = { toFirestore(testObj: WithFieldValue<TestObjectUnion>) { return {...testObj}; }, fromFirestore(snapshot: QueryDocumentSnapshot): TestObjectUnion { const data = snapshot.data(); return { optionalStr: data.optionalStr, nested: data.nested, }; }, }; const ref = doc.withConverter(testConverterUnion); await ref.update({ nested: { requiredStr: 'foo', }, }); await ref.update({ 'nested.requiredStr': 'foo', }); await ref.update({ // @ts-expect-error Should fail to transpile. 'nested.requiredStr': 1, }); await ref.update({ 'nested.requiredNumber': 1, }); await ref.update({ // @ts-expect-error Should fail to transpile. 'nested.requiredNumber': 'foo', }); await ref.update({ // @ts-expect-error Should fail to transpile. 'nested.requiredNumber': null, }); }); it('checks for nonexistent fields', async () => { const ref = doc.withConverter(testConverter); // Top-level fields. await ref.update({ // @ts-expect-error Should fail to transpile. nonexistent: 'foo', }); // Nested Fields. await ref.update({ nested: { // @ts-expect-error Should fail to transpile. nonexistent: 'foo', }, }); // String fields. await ref.update({ // @ts-expect-error Should fail to transpile. nonexistent: 'foo', }); await ref.update({ // @ts-expect-error Should fail to transpile. 'nested.nonexistent': 'foo', }); }); }); describe('methods', () => { it('CollectionReference.add()', async () => { const ref = randomCol.withConverter(testConverter); // Requires all fields to be present // @ts-expect-error Should fail to transpile. await ref.add({ outerArr: [], nested: { innerNested: { innerNestedNum: 2, }, innerArr: [], timestamp: FieldValue.serverTimestamp(), }, }); }); it('WriteBatch.set()', () => { const ref = doc.withConverter(testConverter); const batch = firestore.batch(); // Requires full object if {merge: true} is not set. // @ts-expect-error Should fail to transpile. batch.set(ref, { outerArr: [], nested: { innerNested: { innerNestedNum: FieldValue.increment(1), }, innerArr: FieldValue.arrayUnion(2), timestamp: FieldValue.serverTimestamp(), }, }); batch.set( ref, { outerArr: [], nested: { innerNested: { innerNestedNum: FieldValue.increment(1), }, innerArr: FieldValue.arrayUnion(2), timestamp: FieldValue.serverTimestamp(), }, }, {merge: true} ); }); it('WriteBatch.update()', () => { const ref = doc.withConverter(testConverter); const batch = firestore.batch(); batch.update(ref, { outerArr: [], nested: { 'innerNested.innerNestedNum': FieldValue.increment(1), innerArr: FieldValue.arrayUnion(2), timestamp: FieldValue.serverTimestamp(), }, }); }); it('Transaction.set()', async () => { const ref = doc.withConverter(testConverter); return firestore.runTransaction(async tx => { // Requires full object if {merge: true} is not set. // @ts-expect-error Should fail to transpile. tx.set(ref, { outerArr: [], nested: { innerNested: { innerNestedNum: FieldValue.increment(1), }, innerArr: FieldValue.arrayUnion(2), timestamp: FieldValue.serverTimestamp(), }, }); tx.set( ref, { outerArr: [], nested: { innerNested: { innerNestedNum: FieldValue.increment(1), }, innerArr: FieldValue.arrayUnion(2), timestamp: FieldValue.serverTimestamp(), }, }, {merge: true} ); }); }); it('Transaction.update()', async () => { const ref = doc.withConverter(testConverter); return firestore.runTransaction(async tx => { tx.update(ref, { outerArr: [], nested: { innerNested: { innerNestedNum: FieldValue.increment(1), }, innerArr: FieldValue.arrayUnion(2), timestamp: FieldValue.serverTimestamp(), }, }); }); }); }); });
the_stack
import { assetDataUtils } from '@0x/order-utils'; import { BigNumber, NULL_BYTES } from '@0x/utils'; import { ZERO } from '../../common/constants'; import { createBuySellLimitSteps, createBuySellMarketSteps, getUnlockTokenStepIfNeeded, getUnlockZrxStepIfNeeded, getWrapEthStepIfNeeded, } from '../../util/steps_modals_generation'; import { tokenFactory } from '../../util/test-utils'; import { unitsInTokenAmount } from '../../util/tokens'; import { OrderFeeData, OrderSide, Step, StepKind, StepToggleTokenLock, StepWrapEth, TokenBalance, } from '../../util/types'; const DEFAULT_FEE_DATA = { makerFeeAssetData: NULL_BYTES, takerFeeAssetData: NULL_BYTES, makerFee: ZERO, takerFee: ZERO, }; const tokenDefaults = { primaryColor: 'white', decimals: 18, displayDecimals: 2, }; const wethToken = { ...tokenDefaults, address: '0x100', symbol: 'weth', name: 'wETH', }; const TOKENS = { ZRX: tokenFactory.build({ decimals: 18, symbol: 'zrx' }), MKR: tokenFactory.build({ decimals: 18, symbol: 'mkr' }), REP: tokenFactory.build({ decimals: 18, symbol: 'rep' }), DGD: tokenFactory.build({ decimals: 18, symbol: 'dgd' }), MLN: tokenFactory.build({ decimals: 18, symbol: 'mln' }), WETH: tokenFactory.build({ decimals: 18, symbol: 'weth' }), }; const tokenBalances: TokenBalance[] = [ { balance: new BigNumber(1), token: { ...tokenDefaults, ...TOKENS.ZRX, }, isUnlocked: true, }, { balance: new BigNumber(1), token: { ...tokenDefaults, ...TOKENS.MKR, }, isUnlocked: true, }, { balance: new BigNumber(1), token: { ...tokenDefaults, ...TOKENS.REP, }, isUnlocked: true, }, { balance: new BigNumber(1), token: { ...tokenDefaults, ...TOKENS.DGD, }, isUnlocked: true, }, { balance: new BigNumber(1), token: { ...tokenDefaults, ...TOKENS.MLN, }, isUnlocked: true, }, ]; describe('Buy sell limit steps for zrx/weth', () => { it('should create just one buy limit step if base and quote tokens are unlocked', async () => { // given const baseToken = TOKENS.ZRX; const quoteToken = TOKENS.WETH; const wethTokenBalance = { balance: ZERO, token: wethToken, isUnlocked: true, }; const amount: BigNumber = ZERO; const price: BigNumber = ZERO; const side: OrderSide = OrderSide.Buy; const makerFee = unitsInTokenAmount('1', 18); const makerFeeAssetData = assetDataUtils.encodeERC20AssetData(baseToken.address); // when const feeData: OrderFeeData = { ...DEFAULT_FEE_DATA, makerFee, makerFeeAssetData, }; const buySellLimitFlow: Step[] = createBuySellLimitSteps( baseToken, quoteToken, tokenBalances, wethTokenBalance, amount, price, side, feeData, ); // then expect(buySellLimitFlow).toHaveLength(1); expect(buySellLimitFlow[0].kind).toBe(StepKind.BuySellLimit); }); it('Should create two steps, buy and unlock step if creating a buy limit order for an X/Y market with Y locked', async () => { // given const baseToken = TOKENS.ZRX; const quoteToken = TOKENS.WETH; const wethTokenBalance = { balance: ZERO, token: wethToken, isUnlocked: false, }; const amount: BigNumber = ZERO; const price: BigNumber = ZERO; const side: OrderSide = OrderSide.Buy; const makerFee = unitsInTokenAmount('1', 18); const makerFeeAssetData = assetDataUtils.encodeERC20AssetData(baseToken.address); // when const feeData: OrderFeeData = { ...DEFAULT_FEE_DATA, makerFee, makerFeeAssetData, }; // when const buySellLimitFlow: Step[] = createBuySellLimitSteps( baseToken, quoteToken, tokenBalances, wethTokenBalance, amount, price, side, feeData, ); // then expect(buySellLimitFlow).toHaveLength(2); expect(buySellLimitFlow[0].kind).toBe(StepKind.ToggleTokenLock); expect(buySellLimitFlow[1].kind).toBe(StepKind.BuySellLimit); }); it('Should create two steps, buy and unlock step if creating a sell limit order for an X/Y market with X locked', async () => { // given const baseToken = TOKENS.ZRX; const quoteToken = TOKENS.WETH; // Base token zrx is locked tokenBalances[0].isUnlocked = false; const wethTokenBalance = { balance: ZERO, token: wethToken, isUnlocked: true, }; const amount: BigNumber = ZERO; const price: BigNumber = ZERO; const side: OrderSide = OrderSide.Sell; const makerFee = unitsInTokenAmount('1', 18); const makerFeeAssetData = assetDataUtils.encodeERC20AssetData(baseToken.address); // when const feeData: OrderFeeData = { ...DEFAULT_FEE_DATA, makerFee, makerFeeAssetData, }; // when const buySellLimitFlow: Step[] = createBuySellLimitSteps( baseToken, quoteToken, tokenBalances, wethTokenBalance, amount, price, side, feeData, ); // then expect(buySellLimitFlow).toHaveLength(2); expect(buySellLimitFlow[0].kind).toBe(StepKind.ToggleTokenLock); expect(buySellLimitFlow[1].kind).toBe(StepKind.BuySellLimit); }); it('Should create a unlock zrx step if MAKER FEE is positive and if zrx is locked', async () => { // given const baseToken = TOKENS.MKR; const quoteToken = TOKENS.WETH; const wethTokenBalance = { balance: ZERO, token: wethToken, isUnlocked: true, }; // Base token zrx is locked tokenBalances[0].isUnlocked = false; const amount: BigNumber = ZERO; const price: BigNumber = ZERO; const side: OrderSide = OrderSide.Buy; const makerFee = unitsInTokenAmount('1', 18); const makerFeeAssetData = assetDataUtils.encodeERC20AssetData(TOKENS.ZRX.address); // when const feeData: OrderFeeData = { ...DEFAULT_FEE_DATA, makerFee, makerFeeAssetData, }; // when const buySellLimitFlow: Step[] = createBuySellLimitSteps( baseToken, quoteToken, tokenBalances, wethTokenBalance, amount, price, side, feeData, ); // then expect(buySellLimitFlow).toHaveLength(2); expect(buySellLimitFlow[0].kind).toBe(StepKind.ToggleTokenLock); expect(buySellLimitFlow[1].kind).toBe(StepKind.BuySellLimit); }); }); describe('Buy sell market steps for zrx/weth', () => { it('should create just one buy market step if base and quote tokens are unlocked', async () => { // given const baseToken = TOKENS.ZRX; const quoteToken = TOKENS.WETH; // Unlocks base zrx token tokenBalances[0].isUnlocked = true; const wethTokenBalance = { balance: ZERO, token: wethToken, isUnlocked: true, }; const ethBalance = ZERO; const amount: BigNumber = ZERO; const side: OrderSide = OrderSide.Buy; const amountOfWethNeededForOrders = ZERO; // when const feeData = DEFAULT_FEE_DATA; // when const buySellMarketFlow: Step[] = createBuySellMarketSteps( baseToken, quoteToken, tokenBalances, wethTokenBalance, ethBalance, amount, side, amountOfWethNeededForOrders, feeData, ); // then expect(buySellMarketFlow).toHaveLength(1); expect(buySellMarketFlow[0].kind).toBe(StepKind.BuySellMarket); }); it('Should create a unlock zrx step if TAKER FEE is positive and if zrx is locked', async () => { // given const baseToken = TOKENS.MKR; const quoteToken = TOKENS.WETH; const wethTokenBalance = { balance: ZERO, token: wethToken, isUnlocked: true, }; const ethBalance = ZERO; // Base token zrx is locked tokenBalances[0].isUnlocked = false; const amount: BigNumber = ZERO; const side: OrderSide = OrderSide.Buy; const takerFee = unitsInTokenAmount('1', 18); const amountOfWethNeededForOrders = ZERO; const takerFeeAssetData = assetDataUtils.encodeERC20AssetData(TOKENS.ZRX.address); // when const feeData: OrderFeeData = { ...DEFAULT_FEE_DATA, takerFee, takerFeeAssetData, }; // when const buySellMarketFlow: Step[] = createBuySellMarketSteps( baseToken, quoteToken, tokenBalances, wethTokenBalance, ethBalance, amount, side, amountOfWethNeededForOrders, feeData, ); // then expect(buySellMarketFlow).toHaveLength(2); expect(buySellMarketFlow[0].kind).toBe(StepKind.ToggleTokenLock); expect(buySellMarketFlow[1].kind).toBe(StepKind.BuySellMarket); }); }); describe('getUnlockTokenStepIfNeeded', () => { it('if the token is locked, should return a toggle lock step', async () => { // given const lockedToken = TOKENS.MKR; // locks mkr token tokenBalances[1].isUnlocked = false; const wethTokenBalance = { balance: ZERO, token: wethToken, isUnlocked: true, }; // when const unlockStep: StepToggleTokenLock | null = getUnlockTokenStepIfNeeded( lockedToken, tokenBalances, wethTokenBalance, ); // then expect(unlockStep).not.toBeNull(); if (unlockStep) { expect(unlockStep.kind).toBe(StepKind.ToggleTokenLock); } }); it('if the token is unlocked, should return null', async () => { // given const lockedToken = TOKENS.MKR; // unlock mkr token tokenBalances[1].isUnlocked = true; const wethTokenBalance = { balance: ZERO, token: wethToken, isUnlocked: true, }; // when const unlockStep: StepToggleTokenLock | null = getUnlockTokenStepIfNeeded( lockedToken, tokenBalances, wethTokenBalance, ); // then expect(unlockStep).toBeNull(); }); }); describe('getWrapEthStepIfNeeded', () => { it('if the weth balance is less than the amount multiplied by price, should return a wrap eth step', async () => { // given const wethTokenBalance = { balance: ZERO, token: wethToken, isUnlocked: true, }; const amount: BigNumber = new BigNumber(10); const price: BigNumber = new BigNumber(1); const side: OrderSide = OrderSide.Buy; // when const stepWrapEth: StepWrapEth | null = getWrapEthStepIfNeeded(amount, price, side, wethTokenBalance); // then expect(stepWrapEth).not.toBeNull(); if (stepWrapEth) { expect(stepWrapEth.kind).toBe(StepKind.WrapEth); } }); it('if the weth balance is bigger than the amount multiplied by price, should not return a wrap eth step', async () => { // given const wethTokenBalance = { balance: new BigNumber(11), token: wethToken, isUnlocked: true, }; const amount: BigNumber = new BigNumber(10); const price: BigNumber = new BigNumber(1); const side: OrderSide = OrderSide.Buy; // when const stepWrapEth: StepWrapEth | null = getWrapEthStepIfNeeded(amount, price, side, wethTokenBalance); // then expect(stepWrapEth).toBeNull(); }); it('If creating sell order, should not return a wrap eth step', async () => { // given const wethTokenBalance = { balance: new BigNumber(11), token: wethToken, isUnlocked: true, }; const amount: BigNumber = new BigNumber(10); const price: BigNumber = new BigNumber(1); const side: OrderSide = OrderSide.Sell; // when const stepWrapEth: StepWrapEth | null = getWrapEthStepIfNeeded(amount, price, side, wethTokenBalance); // then expect(stepWrapEth).toBeNull(); }); }); describe('getUnlockZrxStepIfNeeded', () => { it('should return toggle lock step for zrx if zrx is locked', async () => { // given // Locks zrx tokenBalances[0].isUnlocked = false; // when const stepLockZrx: StepToggleTokenLock | null = getUnlockZrxStepIfNeeded(tokenBalances); // then expect(stepLockZrx).not.toBeNull(); if (stepLockZrx) { expect(stepLockZrx.kind).toBe(StepKind.ToggleTokenLock); } }); it('should return null if zrx is locked', async () => { // given // Unlocks zrx tokenBalances[0].isUnlocked = true; // when const stepLockZrx: StepToggleTokenLock | null = getUnlockZrxStepIfNeeded(tokenBalances); // then expect(stepLockZrx).toBeNull(); }); });
the_stack
import * as monaco from '@ali/monaco-editor-core/esm/vs/editor/editor.api'; import type * as vscode from 'vscode'; import { DocumentSelector, HoverProvider, CancellationToken, DefinitionProvider, ReferenceProvider } from 'vscode'; import { DocumentFilter } from 'vscode-languageserver-protocol'; import { Autowired, Injectable, ConstructorOf } from '@opensumi/di'; import { Uri, URI, LRUMap, DisposableCollection } from '@opensumi/ide-core-common'; import { IEditorDocumentModelService, LanguageSelector } from '@opensumi/ide-editor/lib/browser'; import { ExtensionDocumentDataManager, IExtHostLanguages } from '@opensumi/ide-extension/lib/common/vscode'; import { MonacoModelIdentifier, testGlob } from '@opensumi/ide-extension/lib/common/vscode'; import { fromLanguageSelector } from '@opensumi/ide-extension/lib/common/vscode/converter'; import { Disposable } from '@opensumi/ide-extension/lib/common/vscode/ext-types'; import { SerializedDocumentFilter, Hover, Position, Definition, DefinitionLink, ReferenceContext, Location, } from '@opensumi/ide-extension/lib/common/vscode/model.api'; import { ExtHostDocumentData } from '@opensumi/ide-extension/lib/hosted/api/vscode/doc/ext-data.host'; import { Adapter } from '@opensumi/ide-extension/lib/hosted/api/vscode/ext.host.language'; import { DefinitionAdapter } from '@opensumi/ide-extension/lib/hosted/api/vscode/language/definition'; import { HoverAdapter } from '@opensumi/ide-extension/lib/hosted/api/vscode/language/hover'; import { ReferenceAdapter } from '@opensumi/ide-extension/lib/hosted/api/vscode/language/reference'; import { ITextModel } from '@opensumi/ide-monaco/lib/browser/monaco-api/types'; @Injectable() class LiteDocumentDataManager implements Partial<ExtensionDocumentDataManager> { @Autowired(IEditorDocumentModelService) private readonly docManager: IEditorDocumentModelService; getDocumentData(path: Uri | string) { const uri = path.toString(); const docRef = this.docManager.getModelReference(new URI(path)); if (!docRef) { return undefined; } const model = docRef.instance.getMonacoModel(); const docModel = { lines: model.getLinesContent(), eol: docRef.instance.eol, languageId: docRef.instance.languageId, versionId: model.getVersionId(), dirty: docRef.instance.dirty, }; return new ExtHostDocumentData( { $trySaveDocument() { return docRef.instance.save(); }, } as any, Uri.parse(uri), docModel.lines, docModel.eol, docModel.languageId, docModel.versionId, docModel.dirty, ); } } /** * IExtHostLanguages 的简单实现 * 主要保留以下几个 API 供 lsif 服务使用 * * registerHoverProvider * * registerDefinitionProvider * * registerReferenceProvider */ @Injectable() export class SimpleLanguageService implements Partial<IExtHostLanguages> { private callId = 0; private adaptersMap = new Map<number, Adapter>(); private readonly disposables = new Map<number, monaco.IDisposable>(); private languageFeatureEnabled = new LRUMap<string, boolean>(200, 100); @Autowired(LiteDocumentDataManager) private readonly documents: ExtensionDocumentDataManager; private nextCallId(): number { return this.callId++; } private createDisposable(callId: number): Disposable { return new Disposable(() => { this.adaptersMap.delete(callId); }); } private addNewAdapter(adapter: Adapter): number { const callId = this.nextCallId(); this.adaptersMap.set(callId, adapter); return callId; } // tslint:disable-next-line:no-any private withAdapter<A, R>( handle: number, constructor: ConstructorOf<A>, callback: (adapter: A) => Promise<R>, ): Promise<R> { const adapter = this.adaptersMap.get(handle); if (!(adapter instanceof constructor)) { return Promise.reject(new Error('no adapter found')); } return callback(adapter as A); } private transformDocumentSelector(selector: vscode.DocumentSelector): SerializedDocumentFilter[] { if (Array.isArray(selector)) { return selector.map((sel) => this.doTransformDocumentSelector(sel)!); } return [this.doTransformDocumentSelector(selector)!]; } private doTransformDocumentSelector(selector: string | vscode.DocumentFilter): SerializedDocumentFilter | undefined { if (typeof selector === 'string') { return { $serialized: true, language: selector, }; } if (selector) { return { $serialized: true, language: selector.language, scheme: selector.scheme, pattern: selector.pattern, }; } return undefined; } async getLanguages(): Promise<string[]> { return this.$getLanguages(); } // TODO: I need this // ### Hover begin registerHoverProvider(selector: DocumentSelector, provider: HoverProvider): Disposable { const callId = this.addNewAdapter(new HoverAdapter(provider, this.documents)); this.$registerHoverProvider(callId, this.transformDocumentSelector(selector)); return this.createDisposable(callId); } $provideHover( handle: number, resource: any, position: Position, token: CancellationToken, ): Promise<Hover | undefined> { return this.withAdapter(handle, HoverAdapter, (adapter) => adapter.provideHover(resource, position, token)); } // TODO: I need this $registerHoverProvider(handle: number, selector: SerializedDocumentFilter[]): void { const languageSelector = fromLanguageSelector(selector); const hoverProvider = this.createHoverProvider(handle, languageSelector); const disposable = new DisposableCollection(); for (const language of this.getUniqueLanguages()) { if (this.matchLanguage(languageSelector, language)) { disposable.push(monaco.languages.registerHoverProvider(language, hoverProvider)); } } this.disposables.set(handle, disposable); } protected createHoverProvider(handle: number, selector?: LanguageSelector): monaco.languages.HoverProvider { return { provideHover: (model, position, token) => { if (!this.matchModel(selector, MonacoModelIdentifier.fromModel(model))) { return undefined!; } if (!this.isLanguageFeatureEnabled(model)) { return undefined!; } return this.$provideHover(handle, model.uri, position, token).then((v) => v!); }, }; } // ### Hover end // TODO: I need this // ### Definition provider begin registerDefinitionProvider(selector: DocumentSelector, provider: DefinitionProvider): Disposable { const callId = this.addNewAdapter(new DefinitionAdapter(provider, this.documents)); this.$registerDefinitionProvider(callId, this.transformDocumentSelector(selector)); return this.createDisposable(callId); } $provideDefinition( handle: number, resource: Uri, position: Position, token: CancellationToken, ): Promise<Definition | DefinitionLink[] | undefined> { return this.withAdapter(handle, DefinitionAdapter, (adapter) => adapter.provideDefinition(resource, position, token), ); } $registerDefinitionProvider(handle: number, selector: SerializedDocumentFilter[]): void { const languageSelector = fromLanguageSelector(selector); const definitionProvider = this.createDefinitionProvider(handle, languageSelector); const disposable = new DisposableCollection(); for (const language of this.getUniqueLanguages()) { if (this.matchLanguage(languageSelector, language)) { disposable.push(monaco.languages.registerDefinitionProvider(language, definitionProvider)); } } this.disposables.set(handle, disposable); } protected createDefinitionProvider( handle: number, selector: LanguageSelector | undefined, ): monaco.languages.DefinitionProvider { return { provideDefinition: async (model, position, token) => { if (!this.matchModel(selector, MonacoModelIdentifier.fromModel(model))) { return undefined!; } if (!this.isLanguageFeatureEnabled(model)) { return undefined!; } const result = await this.$provideDefinition(handle, model.uri, position, token); if (!result) { return undefined!; } if (Array.isArray(result)) { const definitionLinks: monaco.languages.LocationLink[] = []; for (const item of result) { definitionLinks.push({ ...item, uri: monaco.Uri.revive(item.uri) }); } return definitionLinks as monaco.languages.LocationLink[]; } else { // single Location return { uri: monaco.Uri.revive(result.uri), range: result.range, } as monaco.languages.Definition; } }, }; } // ### Definition provider end // TODO: I need this // ### Code Reference Provider begin registerReferenceProvider(selector: DocumentSelector, provider: ReferenceProvider): Disposable { const callId = this.addNewAdapter(new ReferenceAdapter(provider, this.documents)); this.$registerReferenceProvider(callId, this.transformDocumentSelector(selector)); return this.createDisposable(callId); } $provideReferences( handle: number, resource: Uri, position: Position, context: ReferenceContext, token: CancellationToken, ): Promise<Location[] | undefined> { return this.withAdapter(handle, ReferenceAdapter, (adapter) => adapter.provideReferences(resource, position, context, token), ); } // TODO: I need this $registerReferenceProvider(handle: number, selector: SerializedDocumentFilter[]): void { const languageSelector = fromLanguageSelector(selector); const referenceProvider = this.createReferenceProvider(handle, languageSelector); const disposable = new DisposableCollection(); for (const language of this.getUniqueLanguages()) { if (this.matchLanguage(languageSelector, language)) { disposable.push(monaco.languages.registerReferenceProvider(language, referenceProvider)); } } this.disposables.set(handle, disposable); } protected createReferenceProvider( handle: number, selector: LanguageSelector | undefined, ): monaco.languages.ReferenceProvider { return { provideReferences: (model, position, context, token) => { if (!this.isLanguageFeatureEnabled(model)) { return undefined!; } if (!this.matchModel(selector, MonacoModelIdentifier.fromModel(model))) { return undefined!; } return this.$provideReferences(handle, model.uri, position, context, token).then((result) => { if (!result) { return undefined!; } if (Array.isArray(result)) { const references: monaco.languages.Location[] = []; for (const item of result) { references.push({ ...item, uri: monaco.Uri.revive(item.uri) }); } return references; } return undefined!; }); }, }; } // ### Code Reference Provider end protected getUniqueLanguages(): string[] { const languages: string[] = []; // 会有重复 const allLanguages = monaco.languages.getLanguages().map((l) => l.id); for (const language of allLanguages) { if (languages.indexOf(language) === -1) { languages.push(language); } } return languages; } protected matchLanguage(selector: LanguageSelector | undefined, languageId: string): boolean { if (Array.isArray(selector)) { return selector.some((filter) => this.matchLanguage(filter, languageId)); } if (DocumentFilter.is(selector)) { return !selector.language || selector.language === languageId; } return selector === languageId; } protected matchModel(selector: LanguageSelector | undefined, model: MonacoModelIdentifier): boolean { if (Array.isArray(selector)) { return selector.some((filter) => this.matchModel(filter, model)); } if (DocumentFilter.is(selector)) { if (!!selector.language && selector.language !== model.languageId) { return false; } if (!!selector.scheme && selector.scheme !== model.uri.scheme) { return false; } if (!!selector.pattern && !testGlob(selector.pattern, model.uri.path)) { return false; } return true; } return selector === model.languageId; } isLanguageFeatureEnabled(model: ITextModel) { const uriString = model.uri.toString(); if (!this.languageFeatureEnabled.has(uriString)) { this.languageFeatureEnabled.set(uriString, model.getValueLength() < 2 * 1024 * 1024); } return this.languageFeatureEnabled.get(uriString); } $getLanguages(): string[] { return monaco.languages.getLanguages().map((l) => l.id); } }
the_stack
import { GlobalProps } from 'ojs/ojvcomponent'; import { ComponentChildren } from 'preact'; import 'geojson'; import { DataProvider } from '../ojdataprovider'; import { dvtBaseComponent, dvtBaseComponentEventMap, dvtBaseComponentSettableProperties } from '../ojdvt-base'; import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..'; export interface ojThematicMap<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> extends dvtBaseComponent<ojThematicMapSettableProperties<K1, K2, K3, D1, D2, D3>> { animationDuration?: number; animationOnDisplay?: 'auto' | 'none'; areaData?: DataProvider<K1, D1> | null; as?: string; focusRenderer?: ((context: ojThematicMap.RendererContext<K1, K2, K3, D1, D2, D3>) => { insert: SVGElement; } | void) | null; hiddenCategories?: string[]; highlightMatch?: 'any' | 'all'; highlightedCategories?: string[]; hoverBehavior?: 'dim' | 'none'; hoverRenderer?: ((context: ojThematicMap.RendererContext<K1, K2, K3, D1, D2, D3>) => { insert: SVGElement; } | void) | null; initialZooming?: 'auto' | 'none'; isolatedItem?: K1; labelDisplay?: 'on' | 'off' | 'auto'; labelType?: 'long' | 'short'; linkData?: DataProvider<K2, D2> | null; mapProvider: { geo: GeoJSON.Feature<GeoJSON.Polygon | GeoJSON.MultiPolygon> | GeoJSON.FeatureCollection<GeoJSON.Polygon | GeoJSON.MultiPolygon>; propertiesKeys: { id: string; longLabel?: string; shortLabel?: string; }; }; markerData?: DataProvider<K3, D3> | null; markerZoomBehavior?: 'zoom' | 'fixed'; maxZoom?: number; panning?: 'auto' | 'none'; renderer?: ((context: ojThematicMap.RendererContext<K1, K2, K3, D1, D2, D3>) => { insert: SVGElement; } | void) | null; selection?: Array<K1 | K2 | K3>; selectionMode?: 'none' | 'single' | 'multiple'; selectionRenderer?: ((context: ojThematicMap.RendererContext<K1, K2, K3, D1, D2, D3>) => { insert: SVGElement; } | void) | null; styleDefaults?: { areaSvgStyle?: Partial<CSSStyleDeclaration>; dataAreaDefaults?: { borderColor?: string; hoverColor?: string; selectedInnerColor?: string; selectedOuterColor?: string; }; dataMarkerDefaults?: { borderColor?: string; borderStyle?: 'none' | 'solid'; borderWidth?: number; color?: string; height?: number; labelStyle?: Partial<CSSStyleDeclaration>; opacity?: number; shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string; width?: number; }; hoverBehaviorDelay?: number; labelStyle?: Partial<CSSStyleDeclaration>; linkDefaults?: { color?: string; width?: number; }; }; tooltip?: { renderer: ((context: ojThematicMap.TooltipContext<K1, K2, K3, D1, D2, D3>) => ({ insert: Element | string; } | { preventDefault: boolean; })); }; tooltipDisplay?: 'auto' | 'labelAndShortDesc' | 'none' | 'shortDesc'; touchResponse?: 'touchStart' | 'auto'; zooming?: 'auto' | 'none'; translations: { areasRegion?: string; componentName?: string; labelAndValue?: string; labelClearSelection?: string; labelCountWithTotal?: string; labelDataVisualization?: string; labelInvalidData?: string; labelNoData?: string; linksRegion?: string; markersRegion?: string; stateCollapsed?: string; stateDrillable?: string; stateExpanded?: string; stateHidden?: string; stateIsolated?: string; stateMaximized?: string; stateMinimized?: string; stateSelected?: string; stateUnselected?: string; stateVisible?: string; }; addEventListener<T extends keyof ojThematicMapEventMap<K1, K2, K3, D1, D2, D3>>(type: T, listener: (this: HTMLElement, ev: ojThematicMapEventMap<K1, K2, K3, D1, D2, D3>[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojThematicMapSettableProperties<K1, K2, K3, D1, D2, D3>>(property: T): ojThematicMap<K1, K2, K3, D1, D2, D3>[T]; getProperty(property: string): any; setProperty<T extends keyof ojThematicMapSettableProperties<K1, K2, K3, D1, D2, D3>>(property: T, value: ojThematicMapSettableProperties<K1, K2, K3, D1, D2, D3>[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojThematicMapSettableProperties<K1, K2, K3, D1, D2, D3>>): void; setProperties(properties: ojThematicMapSettablePropertiesLenient<K1, K2, K3, D1, D2, D3>): void; getContextByNode(node: Element): ojThematicMap.NodeContext | null; } export namespace ojThematicMap { // tslint:disable-next-line interface-over-type-literal type animationDurationChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["animationDuration"]>; // tslint:disable-next-line interface-over-type-literal type animationOnDisplayChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["animationOnDisplay"]>; // tslint:disable-next-line interface-over-type-literal type areaDataChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["areaData"]>; // tslint:disable-next-line interface-over-type-literal type asChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["as"]>; // tslint:disable-next-line interface-over-type-literal type focusRendererChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["focusRenderer"]>; // tslint:disable-next-line interface-over-type-literal type hiddenCategoriesChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["hiddenCategories"]>; // tslint:disable-next-line interface-over-type-literal type highlightMatchChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["highlightMatch"]>; // tslint:disable-next-line interface-over-type-literal type highlightedCategoriesChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["highlightedCategories"]>; // tslint:disable-next-line interface-over-type-literal type hoverBehaviorChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["hoverBehavior"]>; // tslint:disable-next-line interface-over-type-literal type hoverRendererChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["hoverRenderer"]>; // tslint:disable-next-line interface-over-type-literal type initialZoomingChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["initialZooming"]>; // tslint:disable-next-line interface-over-type-literal type isolatedItemChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["isolatedItem"]>; // tslint:disable-next-line interface-over-type-literal type labelDisplayChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["labelDisplay"]>; // tslint:disable-next-line interface-over-type-literal type labelTypeChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["labelType"]>; // tslint:disable-next-line interface-over-type-literal type linkDataChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["linkData"]>; // tslint:disable-next-line interface-over-type-literal type mapProviderChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["mapProvider"]>; // tslint:disable-next-line interface-over-type-literal type markerDataChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["markerData"]>; // tslint:disable-next-line interface-over-type-literal type markerZoomBehaviorChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["markerZoomBehavior"]>; // tslint:disable-next-line interface-over-type-literal type maxZoomChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["maxZoom"]>; // tslint:disable-next-line interface-over-type-literal type panningChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["panning"]>; // tslint:disable-next-line interface-over-type-literal type rendererChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["renderer"]>; // tslint:disable-next-line interface-over-type-literal type selectionChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["selection"]>; // tslint:disable-next-line interface-over-type-literal type selectionModeChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["selectionMode"]>; // tslint:disable-next-line interface-over-type-literal type selectionRendererChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["selectionRenderer"]>; // tslint:disable-next-line interface-over-type-literal type styleDefaultsChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["styleDefaults"]>; // tslint:disable-next-line interface-over-type-literal type tooltipChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["tooltip"]>; // tslint:disable-next-line interface-over-type-literal type tooltipDisplayChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["tooltipDisplay"]>; // tslint:disable-next-line interface-over-type-literal type touchResponseChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["touchResponse"]>; // tslint:disable-next-line interface-over-type-literal type zoomingChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["zooming"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type trackResizeChanged<K1, K2, K3, D1 extends Area<K1> | any, D2 extends Link<K2, K1 | K3> | any, D3 extends Marker<K3> | any> = dvtBaseComponent.trackResizeChanged<ojThematicMapSettableProperties<K1, K2, K3, D1, D2, D3>>; // tslint:disable-next-line interface-over-type-literal type Area<K, D = any> = { categories?: string[]; color?: string; id?: K; label?: string; labelStyle?: Partial<CSSStyleDeclaration>; location: string; opacity?: number; selectable?: 'auto' | 'off'; shortDesc?: (string | ((context: AreaShortDescContext<K, D>) => string)); svgClassName?: string; svgStyle?: Partial<CSSStyleDeclaration>; }; // tslint:disable-next-line interface-over-type-literal type AreaShortDescContext<K1, D1> = { data: Area<K1, D1>; id: K1; itemData: D1 | null; label: string; location: string | null; locationName: string | null; x: number; y: number; }; // tslint:disable-next-line interface-over-type-literal type AreaTemplateContext = { componentElement: Element; data: object; index: number; key: any; }; // tslint:disable-next-line interface-over-type-literal type DataContext = { color: string; label: string; selected: boolean; tooltip: string; }; // tslint:disable-next-line interface-over-type-literal type Link<K1, K2, D1 = any> = { categories?: string[]; color?: string; endLocation: { id?: K2; location?: string; x?: number; y?: number; }; id?: K1; selectable?: 'auto' | 'off'; shortDesc?: (string | ((context: LinkShortDescContext<K1, K2, D1>) => string)); startLocation: { id?: K2; location?: string; x?: number; y?: number; }; svgClassName?: string; svgStyle?: Partial<CSSStyleDeclaration>; width?: number; }; // tslint:disable-next-line interface-over-type-literal type LinkShortDescContext<K1, K2, D1> = { data: Link<K1, K2, D1>; id: K1; itemData: D1 | null; label: string; }; // tslint:disable-next-line interface-over-type-literal type LinkTemplateContext = { componentElement: Element; data: object; index: number; key: any; }; // tslint:disable-next-line interface-over-type-literal type Marker<K3, D3 = any> = { borderColor?: string; borderStyle?: 'solid' | 'none'; borderWidth?: number; categories?: string[]; color?: string; height?: number; id?: K3; label?: string; labelPosition?: 'bottom' | 'center' | 'top'; labelStyle?: Partial<CSSStyleDeclaration>; location?: string; opacity?: number; rotation?: number; selectable?: 'auto' | 'off'; shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string; shortDesc?: (string | ((context: MarkerShortDescContext<K3, D3>) => string)); source?: string; sourceHover?: string; sourceHoverSelected?: string; sourceSelected?: string; svgClassName?: string; svgStyle?: Partial<CSSStyleDeclaration>; value?: number; width?: number; x?: number; y?: number; }; // tslint:disable-next-line interface-over-type-literal type MarkerShortDescContext<K3, D3> = { data: Marker<K3>; id: K3; itemData: D3 | null; label: string; location: string | null; locationName: string | null; x: number; y: number; }; // tslint:disable-next-line interface-over-type-literal type MarkerTemplateContext = { componentElement: Element; data: object; index: number; key: any; }; // tslint:disable-next-line interface-over-type-literal type NodeContext = { index: number; subId: string; }; // tslint:disable-next-line interface-over-type-literal type RendererContext<K1, K2, K3, D1, D2, D3> = { color: string; componentElement: Element; data: Area<K1, D1> | Link<K2, K1 | K3, D2> | Marker<K3, D3>; id: K1 | K2 | K3; itemData: D1 | D2 | D3 | null; label: string; location: string | null; parentElement: Element; previousState: { focused: boolean; hovered: boolean; selected: boolean; }; renderDefaultFocus: (() => void); renderDefaultHover: (() => void); renderDefaultSelection: (() => void); root: Element | null; state: { focused: boolean; hovered: boolean; selected: boolean; }; x: number | null; y: number | null; }; // tslint:disable-next-line interface-over-type-literal type TooltipContext<K1, K2, K3, D1, D2, D3> = { color: string | null; componentElement: Element; data: Area<K1, D1> | Link<K2, K1 | K3, D2> | Marker<K3, D3> | null; id: K1 | K2 | K3 | null; itemData: D1 | D2 | D3 | null; label: string | null; location: string | null; locationName: string | null; parentElement: Element; tooltip: string; x: number; y: number; }; } export interface ojThematicMapEventMap<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> extends dvtBaseComponentEventMap<ojThematicMapSettableProperties<K1, K2, K3, D1, D2, D3>> { 'animationDurationChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["animationDuration"]>; 'animationOnDisplayChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["animationOnDisplay"]>; 'areaDataChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["areaData"]>; 'asChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["as"]>; 'focusRendererChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["focusRenderer"]>; 'hiddenCategoriesChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["hiddenCategories"]>; 'highlightMatchChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["highlightMatch"]>; 'highlightedCategoriesChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["highlightedCategories"]>; 'hoverBehaviorChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["hoverBehavior"]>; 'hoverRendererChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["hoverRenderer"]>; 'initialZoomingChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["initialZooming"]>; 'isolatedItemChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["isolatedItem"]>; 'labelDisplayChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["labelDisplay"]>; 'labelTypeChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["labelType"]>; 'linkDataChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["linkData"]>; 'mapProviderChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["mapProvider"]>; 'markerDataChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["markerData"]>; 'markerZoomBehaviorChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["markerZoomBehavior"]>; 'maxZoomChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["maxZoom"]>; 'panningChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["panning"]>; 'rendererChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["renderer"]>; 'selectionChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["selection"]>; 'selectionModeChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["selectionMode"]>; 'selectionRendererChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["selectionRenderer"]>; 'styleDefaultsChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["styleDefaults"]>; 'tooltipChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["tooltip"]>; 'tooltipDisplayChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["tooltipDisplay"]>; 'touchResponseChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["touchResponse"]>; 'zoomingChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["zooming"]>; 'trackResizeChanged': JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["trackResize"]>; } export interface ojThematicMapSettableProperties<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> extends dvtBaseComponentSettableProperties { animationDuration?: number; animationOnDisplay?: 'auto' | 'none'; areaData?: DataProvider<K1, D1> | null; as?: string; focusRenderer?: ((context: ojThematicMap.RendererContext<K1, K2, K3, D1, D2, D3>) => { insert: SVGElement; } | void) | null; hiddenCategories?: string[]; highlightMatch?: 'any' | 'all'; highlightedCategories?: string[]; hoverBehavior?: 'dim' | 'none'; hoverRenderer?: ((context: ojThematicMap.RendererContext<K1, K2, K3, D1, D2, D3>) => { insert: SVGElement; } | void) | null; initialZooming?: 'auto' | 'none'; isolatedItem?: K1; labelDisplay?: 'on' | 'off' | 'auto'; labelType?: 'long' | 'short'; linkData?: DataProvider<K2, D2> | null; mapProvider: { geo: GeoJSON.Feature<GeoJSON.Polygon | GeoJSON.MultiPolygon> | GeoJSON.FeatureCollection<GeoJSON.Polygon | GeoJSON.MultiPolygon>; propertiesKeys: { id: string; longLabel?: string; shortLabel?: string; }; }; markerData?: DataProvider<K3, D3> | null; markerZoomBehavior?: 'zoom' | 'fixed'; maxZoom?: number; panning?: 'auto' | 'none'; renderer?: ((context: ojThematicMap.RendererContext<K1, K2, K3, D1, D2, D3>) => { insert: SVGElement; } | void) | null; selection?: Array<K1 | K2 | K3>; selectionMode?: 'none' | 'single' | 'multiple'; selectionRenderer?: ((context: ojThematicMap.RendererContext<K1, K2, K3, D1, D2, D3>) => { insert: SVGElement; } | void) | null; styleDefaults?: { areaSvgStyle?: Partial<CSSStyleDeclaration>; dataAreaDefaults?: { borderColor?: string; hoverColor?: string; selectedInnerColor?: string; selectedOuterColor?: string; }; dataMarkerDefaults?: { borderColor?: string; borderStyle?: 'none' | 'solid'; borderWidth?: number; color?: string; height?: number; labelStyle?: Partial<CSSStyleDeclaration>; opacity?: number; shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string; width?: number; }; hoverBehaviorDelay?: number; labelStyle?: Partial<CSSStyleDeclaration>; linkDefaults?: { color?: string; width?: number; }; }; tooltip?: { renderer: ((context: ojThematicMap.TooltipContext<K1, K2, K3, D1, D2, D3>) => ({ insert: Element | string; } | { preventDefault: boolean; })); }; tooltipDisplay?: 'auto' | 'labelAndShortDesc' | 'none' | 'shortDesc'; touchResponse?: 'touchStart' | 'auto'; zooming?: 'auto' | 'none'; translations: { areasRegion?: string; componentName?: string; labelAndValue?: string; labelClearSelection?: string; labelCountWithTotal?: string; labelDataVisualization?: string; labelInvalidData?: string; labelNoData?: string; linksRegion?: string; markersRegion?: string; stateCollapsed?: string; stateDrillable?: string; stateExpanded?: string; stateHidden?: string; stateIsolated?: string; stateMaximized?: string; stateMinimized?: string; stateSelected?: string; stateUnselected?: string; stateVisible?: string; }; } export interface ojThematicMapSettablePropertiesLenient<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> extends Partial<ojThematicMapSettableProperties<K1, K2, K3, D1, D2, D3>> { [key: string]: any; } export interface ojThematicMapArea<K1 = any, D1 = any> extends dvtBaseComponent<ojThematicMapAreaSettableProperties<K1, D1>> { categories?: string[]; color?: string; label?: string; labelStyle?: Partial<CSSStyleDeclaration>; location: string; opacity?: number; selectable?: 'auto' | 'off'; shortDesc?: (string | ((context: ojThematicMap.AreaShortDescContext<K1, D1>) => string)); svgClassName?: string; svgStyle?: Partial<CSSStyleDeclaration>; addEventListener<T extends keyof ojThematicMapAreaEventMap<K1, D1>>(type: T, listener: (this: HTMLElement, ev: ojThematicMapAreaEventMap<K1, D1>[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojThematicMapAreaSettableProperties<K1, D1>>(property: T): ojThematicMapArea<K1, D1>[T]; getProperty(property: string): any; setProperty<T extends keyof ojThematicMapAreaSettableProperties<K1, D1>>(property: T, value: ojThematicMapAreaSettableProperties<K1, D1>[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojThematicMapAreaSettableProperties<K1, D1>>): void; setProperties(properties: ojThematicMapAreaSettablePropertiesLenient<K1, D1>): void; } export namespace ojThematicMapArea { // tslint:disable-next-line interface-over-type-literal type categoriesChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["categories"]>; // tslint:disable-next-line interface-over-type-literal type colorChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["color"]>; // tslint:disable-next-line interface-over-type-literal type labelChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["label"]>; // tslint:disable-next-line interface-over-type-literal type labelStyleChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["labelStyle"]>; // tslint:disable-next-line interface-over-type-literal type locationChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["location"]>; // tslint:disable-next-line interface-over-type-literal type opacityChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["opacity"]>; // tslint:disable-next-line interface-over-type-literal type selectableChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["selectable"]>; // tslint:disable-next-line interface-over-type-literal type shortDescChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["shortDesc"]>; // tslint:disable-next-line interface-over-type-literal type svgClassNameChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["svgClassName"]>; // tslint:disable-next-line interface-over-type-literal type svgStyleChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["svgStyle"]>; } export interface ojThematicMapAreaEventMap<K1 = any, D1 = any> extends dvtBaseComponentEventMap<ojThematicMapAreaSettableProperties<K1, D1>> { 'categoriesChanged': JetElementCustomEvent<ojThematicMapArea<K1, D1>["categories"]>; 'colorChanged': JetElementCustomEvent<ojThematicMapArea<K1, D1>["color"]>; 'labelChanged': JetElementCustomEvent<ojThematicMapArea<K1, D1>["label"]>; 'labelStyleChanged': JetElementCustomEvent<ojThematicMapArea<K1, D1>["labelStyle"]>; 'locationChanged': JetElementCustomEvent<ojThematicMapArea<K1, D1>["location"]>; 'opacityChanged': JetElementCustomEvent<ojThematicMapArea<K1, D1>["opacity"]>; 'selectableChanged': JetElementCustomEvent<ojThematicMapArea<K1, D1>["selectable"]>; 'shortDescChanged': JetElementCustomEvent<ojThematicMapArea<K1, D1>["shortDesc"]>; 'svgClassNameChanged': JetElementCustomEvent<ojThematicMapArea<K1, D1>["svgClassName"]>; 'svgStyleChanged': JetElementCustomEvent<ojThematicMapArea<K1, D1>["svgStyle"]>; } export interface ojThematicMapAreaSettableProperties<K1 = any, D1 = any> extends dvtBaseComponentSettableProperties { categories?: string[]; color?: string; label?: string; labelStyle?: Partial<CSSStyleDeclaration>; location: string; opacity?: number; selectable?: 'auto' | 'off'; shortDesc?: (string | ((context: ojThematicMap.AreaShortDescContext<K1, D1>) => string)); svgClassName?: string; svgStyle?: Partial<CSSStyleDeclaration>; } export interface ojThematicMapAreaSettablePropertiesLenient<K1 = any, D1 = any> extends Partial<ojThematicMapAreaSettableProperties<K1, D1>> { [key: string]: any; } export interface ojThematicMapLink<K1 = any, K2 = any, D1 = any> extends dvtBaseComponent<ojThematicMapLinkSettableProperties<K1, K2, D1>> { categories?: string[]; color?: string; endLocation: { id?: any; location?: string; x?: number; y?: number; }; selectable?: 'auto' | 'off'; shortDesc?: (string | ((context: ojThematicMap.LinkShortDescContext<K1, K2, D1>) => string)); startLocation: { id?: any; location?: string; x?: number; y?: number; }; svgClassName?: string; svgStyle?: Partial<CSSStyleDeclaration>; width?: number; addEventListener<T extends keyof ojThematicMapLinkEventMap<K1, K2, D1>>(type: T, listener: (this: HTMLElement, ev: ojThematicMapLinkEventMap<K1, K2, D1>[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojThematicMapLinkSettableProperties<K1, K2, D1>>(property: T): ojThematicMapLink<K1, K2, D1>[T]; getProperty(property: string): any; setProperty<T extends keyof ojThematicMapLinkSettableProperties<K1, K2, D1>>(property: T, value: ojThematicMapLinkSettableProperties<K1, K2, D1>[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojThematicMapLinkSettableProperties<K1, K2, D1>>): void; setProperties(properties: ojThematicMapLinkSettablePropertiesLenient<K1, K2, D1>): void; } export namespace ojThematicMapLink { // tslint:disable-next-line interface-over-type-literal type categoriesChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["categories"]>; // tslint:disable-next-line interface-over-type-literal type colorChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["color"]>; // tslint:disable-next-line interface-over-type-literal type endLocationChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["endLocation"]>; // tslint:disable-next-line interface-over-type-literal type selectableChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["selectable"]>; // tslint:disable-next-line interface-over-type-literal type shortDescChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["shortDesc"]>; // tslint:disable-next-line interface-over-type-literal type startLocationChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["startLocation"]>; // tslint:disable-next-line interface-over-type-literal type svgClassNameChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["svgClassName"]>; // tslint:disable-next-line interface-over-type-literal type svgStyleChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["svgStyle"]>; // tslint:disable-next-line interface-over-type-literal type widthChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["width"]>; } export interface ojThematicMapLinkEventMap<K1 = any, K2 = any, D1 = any> extends dvtBaseComponentEventMap<ojThematicMapLinkSettableProperties<K1, K2, D1>> { 'categoriesChanged': JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["categories"]>; 'colorChanged': JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["color"]>; 'endLocationChanged': JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["endLocation"]>; 'selectableChanged': JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["selectable"]>; 'shortDescChanged': JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["shortDesc"]>; 'startLocationChanged': JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["startLocation"]>; 'svgClassNameChanged': JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["svgClassName"]>; 'svgStyleChanged': JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["svgStyle"]>; 'widthChanged': JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["width"]>; } export interface ojThematicMapLinkSettableProperties<K1 = any, K2 = any, D1 = any> extends dvtBaseComponentSettableProperties { categories?: string[]; color?: string; endLocation: { id?: any; location?: string; x?: number; y?: number; }; selectable?: 'auto' | 'off'; shortDesc?: (string | ((context: ojThematicMap.LinkShortDescContext<K1, K2, D1>) => string)); startLocation: { id?: any; location?: string; x?: number; y?: number; }; svgClassName?: string; svgStyle?: Partial<CSSStyleDeclaration>; width?: number; } export interface ojThematicMapLinkSettablePropertiesLenient<K1 = any, K2 = any, D1 = any> extends Partial<ojThematicMapLinkSettableProperties<K1, K2, D1>> { [key: string]: any; } export interface ojThematicMapMarker<K3 = any, D3 = any> extends dvtBaseComponent<ojThematicMapMarkerSettableProperties<K3, D3>> { borderColor?: string; borderStyle?: 'solid' | 'none'; borderWidth?: number; categories?: string[]; color?: string; height?: number; label?: string; labelPosition?: 'bottom' | 'center' | 'top'; labelStyle?: Partial<CSSStyleDeclaration>; location?: string; opacity?: number; rotation?: number; selectable?: 'auto' | 'off'; shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string; shortDesc?: (string | ((context: ojThematicMap.MarkerShortDescContext<K3, D3>) => string)); source?: string; sourceHover?: string; sourceHoverSelected?: string; sourceSelected?: string; svgClassName?: string; svgStyle?: Partial<CSSStyleDeclaration>; value?: number; width?: number; x?: number | null; y?: number | null; addEventListener<T extends keyof ojThematicMapMarkerEventMap<K3, D3>>(type: T, listener: (this: HTMLElement, ev: ojThematicMapMarkerEventMap<K3, D3>[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojThematicMapMarkerSettableProperties<K3, D3>>(property: T): ojThematicMapMarker<K3, D3>[T]; getProperty(property: string): any; setProperty<T extends keyof ojThematicMapMarkerSettableProperties<K3, D3>>(property: T, value: ojThematicMapMarkerSettableProperties<K3, D3>[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojThematicMapMarkerSettableProperties<K3, D3>>): void; setProperties(properties: ojThematicMapMarkerSettablePropertiesLenient<K3, D3>): void; } export namespace ojThematicMapMarker { // tslint:disable-next-line interface-over-type-literal type borderColorChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["borderColor"]>; // tslint:disable-next-line interface-over-type-literal type borderStyleChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["borderStyle"]>; // tslint:disable-next-line interface-over-type-literal type borderWidthChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["borderWidth"]>; // tslint:disable-next-line interface-over-type-literal type categoriesChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["categories"]>; // tslint:disable-next-line interface-over-type-literal type colorChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["color"]>; // tslint:disable-next-line interface-over-type-literal type heightChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["height"]>; // tslint:disable-next-line interface-over-type-literal type labelChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["label"]>; // tslint:disable-next-line interface-over-type-literal type labelPositionChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["labelPosition"]>; // tslint:disable-next-line interface-over-type-literal type labelStyleChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["labelStyle"]>; // tslint:disable-next-line interface-over-type-literal type locationChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["location"]>; // tslint:disable-next-line interface-over-type-literal type opacityChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["opacity"]>; // tslint:disable-next-line interface-over-type-literal type rotationChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["rotation"]>; // tslint:disable-next-line interface-over-type-literal type selectableChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["selectable"]>; // tslint:disable-next-line interface-over-type-literal type shapeChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["shape"]>; // tslint:disable-next-line interface-over-type-literal type shortDescChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["shortDesc"]>; // tslint:disable-next-line interface-over-type-literal type sourceChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["source"]>; // tslint:disable-next-line interface-over-type-literal type sourceHoverChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["sourceHover"]>; // tslint:disable-next-line interface-over-type-literal type sourceHoverSelectedChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["sourceHoverSelected"]>; // tslint:disable-next-line interface-over-type-literal type sourceSelectedChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["sourceSelected"]>; // tslint:disable-next-line interface-over-type-literal type svgClassNameChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["svgClassName"]>; // tslint:disable-next-line interface-over-type-literal type svgStyleChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["svgStyle"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["value"]>; // tslint:disable-next-line interface-over-type-literal type widthChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["width"]>; // tslint:disable-next-line interface-over-type-literal type xChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["x"]>; // tslint:disable-next-line interface-over-type-literal type yChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["y"]>; } export interface ojThematicMapMarkerEventMap<K3 = any, D3 = any> extends dvtBaseComponentEventMap<ojThematicMapMarkerSettableProperties<K3, D3>> { 'borderColorChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["borderColor"]>; 'borderStyleChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["borderStyle"]>; 'borderWidthChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["borderWidth"]>; 'categoriesChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["categories"]>; 'colorChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["color"]>; 'heightChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["height"]>; 'labelChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["label"]>; 'labelPositionChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["labelPosition"]>; 'labelStyleChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["labelStyle"]>; 'locationChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["location"]>; 'opacityChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["opacity"]>; 'rotationChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["rotation"]>; 'selectableChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["selectable"]>; 'shapeChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["shape"]>; 'shortDescChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["shortDesc"]>; 'sourceChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["source"]>; 'sourceHoverChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["sourceHover"]>; 'sourceHoverSelectedChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["sourceHoverSelected"]>; 'sourceSelectedChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["sourceSelected"]>; 'svgClassNameChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["svgClassName"]>; 'svgStyleChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["svgStyle"]>; 'valueChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["value"]>; 'widthChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["width"]>; 'xChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["x"]>; 'yChanged': JetElementCustomEvent<ojThematicMapMarker<K3, D3>["y"]>; } export interface ojThematicMapMarkerSettableProperties<K3 = any, D3 = any> extends dvtBaseComponentSettableProperties { borderColor?: string; borderStyle?: 'solid' | 'none'; borderWidth?: number; categories?: string[]; color?: string; height?: number; label?: string; labelPosition?: 'bottom' | 'center' | 'top'; labelStyle?: Partial<CSSStyleDeclaration>; location?: string; opacity?: number; rotation?: number; selectable?: 'auto' | 'off'; shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string; shortDesc?: (string | ((context: ojThematicMap.MarkerShortDescContext<K3, D3>) => string)); source?: string; sourceHover?: string; sourceHoverSelected?: string; sourceSelected?: string; svgClassName?: string; svgStyle?: Partial<CSSStyleDeclaration>; value?: number; width?: number; x?: number | null; y?: number | null; } export interface ojThematicMapMarkerSettablePropertiesLenient<K3 = any, D3 = any> extends Partial<ojThematicMapMarkerSettableProperties<K3, D3>> { [key: string]: any; } export type ThematicMapElement<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = ojThematicMap<K1, K2, K3, D1, D2, D3>; export type ThematicMapAreaElement<K1 = any, D1 = any> = ojThematicMapArea<K1, D1>; export type ThematicMapLinkElement<K1 = any, K2 = any, D1 = any> = ojThematicMapLink<K1>; export type ThematicMapMarkerElement<K3 = any, D3 = any> = ojThematicMapMarker<K3>; export namespace ThematicMapElement { // tslint:disable-next-line interface-over-type-literal type animationDurationChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["animationDuration"]>; // tslint:disable-next-line interface-over-type-literal type animationOnDisplayChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["animationOnDisplay"]>; // tslint:disable-next-line interface-over-type-literal type areaDataChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["areaData"]>; // tslint:disable-next-line interface-over-type-literal type asChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["as"]>; // tslint:disable-next-line interface-over-type-literal type focusRendererChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["focusRenderer"]>; // tslint:disable-next-line interface-over-type-literal type hiddenCategoriesChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["hiddenCategories"]>; // tslint:disable-next-line interface-over-type-literal type highlightMatchChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["highlightMatch"]>; // tslint:disable-next-line interface-over-type-literal type highlightedCategoriesChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["highlightedCategories"]>; // tslint:disable-next-line interface-over-type-literal type hoverBehaviorChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["hoverBehavior"]>; // tslint:disable-next-line interface-over-type-literal type hoverRendererChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["hoverRenderer"]>; // tslint:disable-next-line interface-over-type-literal type initialZoomingChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["initialZooming"]>; // tslint:disable-next-line interface-over-type-literal type isolatedItemChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["isolatedItem"]>; // tslint:disable-next-line interface-over-type-literal type labelDisplayChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["labelDisplay"]>; // tslint:disable-next-line interface-over-type-literal type labelTypeChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["labelType"]>; // tslint:disable-next-line interface-over-type-literal type linkDataChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["linkData"]>; // tslint:disable-next-line interface-over-type-literal type mapProviderChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["mapProvider"]>; // tslint:disable-next-line interface-over-type-literal type markerDataChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["markerData"]>; // tslint:disable-next-line interface-over-type-literal type markerZoomBehaviorChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["markerZoomBehavior"]>; // tslint:disable-next-line interface-over-type-literal type maxZoomChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["maxZoom"]>; // tslint:disable-next-line interface-over-type-literal type panningChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["panning"]>; // tslint:disable-next-line interface-over-type-literal type rendererChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["renderer"]>; // tslint:disable-next-line interface-over-type-literal type selectionChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["selection"]>; // tslint:disable-next-line interface-over-type-literal type selectionModeChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["selectionMode"]>; // tslint:disable-next-line interface-over-type-literal type selectionRendererChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["selectionRenderer"]>; // tslint:disable-next-line interface-over-type-literal type styleDefaultsChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["styleDefaults"]>; // tslint:disable-next-line interface-over-type-literal type tooltipChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["tooltip"]>; // tslint:disable-next-line interface-over-type-literal type tooltipDisplayChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["tooltipDisplay"]>; // tslint:disable-next-line interface-over-type-literal type touchResponseChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["touchResponse"]>; // tslint:disable-next-line interface-over-type-literal type zoomingChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = JetElementCustomEvent<ojThematicMap<K1, K2, K3, D1, D2, D3>["zooming"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type trackResizeChanged<K1, K2, K3, D1 extends ojThematicMap.Area<K1> | any, D2 extends ojThematicMap.Link<K2, K1 | K3> | any, D3 extends ojThematicMap.Marker<K3> | any> = dvtBaseComponent.trackResizeChanged<ojThematicMapSettableProperties<K1, K2, K3, D1, D2, D3>>; // tslint:disable-next-line interface-over-type-literal type Area<K, D = any> = { categories?: string[]; color?: string; id?: K; label?: string; labelStyle?: Partial<CSSStyleDeclaration>; location: string; opacity?: number; selectable?: 'auto' | 'off'; shortDesc?: (string | ((context: ojThematicMap.AreaShortDescContext<K, D>) => string)); svgClassName?: string; svgStyle?: Partial<CSSStyleDeclaration>; }; // tslint:disable-next-line interface-over-type-literal type AreaTemplateContext = { componentElement: Element; data: object; index: number; key: any; }; // tslint:disable-next-line interface-over-type-literal type Link<K1, K2, D1 = any> = { categories?: string[]; color?: string; endLocation: { id?: K2; location?: string; x?: number; y?: number; }; id?: K1; selectable?: 'auto' | 'off'; shortDesc?: (string | ((context: ojThematicMap.LinkShortDescContext<K1, K2, D1>) => string)); startLocation: { id?: K2; location?: string; x?: number; y?: number; }; svgClassName?: string; svgStyle?: Partial<CSSStyleDeclaration>; width?: number; }; // tslint:disable-next-line interface-over-type-literal type LinkTemplateContext = { componentElement: Element; data: object; index: number; key: any; }; // tslint:disable-next-line interface-over-type-literal type MarkerShortDescContext<K3, D3> = { data: ojThematicMap.Marker<K3>; id: K3; itemData: D3 | null; label: string; location: string | null; locationName: string | null; x: number; y: number; }; // tslint:disable-next-line interface-over-type-literal type NodeContext = { index: number; subId: string; }; // tslint:disable-next-line interface-over-type-literal type TooltipContext<K1, K2, K3, D1, D2, D3> = { color: string | null; componentElement: Element; data: ojThematicMap.Area<K1, D1> | ojThematicMap.Link<K2, K1 | K3, D2> | ojThematicMap.Marker<K3, D3> | null; id: K1 | K2 | K3 | null; itemData: D1 | D2 | D3 | null; label: string | null; location: string | null; locationName: string | null; parentElement: Element; tooltip: string; x: number; y: number; }; } export namespace ThematicMapAreaElement { // tslint:disable-next-line interface-over-type-literal type categoriesChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["categories"]>; // tslint:disable-next-line interface-over-type-literal type colorChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["color"]>; // tslint:disable-next-line interface-over-type-literal type labelChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["label"]>; // tslint:disable-next-line interface-over-type-literal type labelStyleChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["labelStyle"]>; // tslint:disable-next-line interface-over-type-literal type locationChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["location"]>; // tslint:disable-next-line interface-over-type-literal type opacityChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["opacity"]>; // tslint:disable-next-line interface-over-type-literal type selectableChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["selectable"]>; // tslint:disable-next-line interface-over-type-literal type shortDescChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["shortDesc"]>; // tslint:disable-next-line interface-over-type-literal type svgClassNameChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["svgClassName"]>; // tslint:disable-next-line interface-over-type-literal type svgStyleChanged<K1 = any, D1 = any> = JetElementCustomEvent<ojThematicMapArea<K1, D1>["svgStyle"]>; } export namespace ThematicMapLinkElement { // tslint:disable-next-line interface-over-type-literal type categoriesChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["categories"]>; // tslint:disable-next-line interface-over-type-literal type colorChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["color"]>; // tslint:disable-next-line interface-over-type-literal type endLocationChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["endLocation"]>; // tslint:disable-next-line interface-over-type-literal type selectableChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["selectable"]>; // tslint:disable-next-line interface-over-type-literal type shortDescChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["shortDesc"]>; // tslint:disable-next-line interface-over-type-literal type startLocationChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["startLocation"]>; // tslint:disable-next-line interface-over-type-literal type svgClassNameChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["svgClassName"]>; // tslint:disable-next-line interface-over-type-literal type svgStyleChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["svgStyle"]>; // tslint:disable-next-line interface-over-type-literal type widthChanged<K1 = any, K2 = any, D1 = any> = JetElementCustomEvent<ojThematicMapLink<K1, K2, D1>["width"]>; } export namespace ThematicMapMarkerElement { // tslint:disable-next-line interface-over-type-literal type borderColorChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["borderColor"]>; // tslint:disable-next-line interface-over-type-literal type borderStyleChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["borderStyle"]>; // tslint:disable-next-line interface-over-type-literal type borderWidthChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["borderWidth"]>; // tslint:disable-next-line interface-over-type-literal type categoriesChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["categories"]>; // tslint:disable-next-line interface-over-type-literal type colorChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["color"]>; // tslint:disable-next-line interface-over-type-literal type heightChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["height"]>; // tslint:disable-next-line interface-over-type-literal type labelChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["label"]>; // tslint:disable-next-line interface-over-type-literal type labelPositionChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["labelPosition"]>; // tslint:disable-next-line interface-over-type-literal type labelStyleChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["labelStyle"]>; // tslint:disable-next-line interface-over-type-literal type locationChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["location"]>; // tslint:disable-next-line interface-over-type-literal type opacityChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["opacity"]>; // tslint:disable-next-line interface-over-type-literal type rotationChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["rotation"]>; // tslint:disable-next-line interface-over-type-literal type selectableChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["selectable"]>; // tslint:disable-next-line interface-over-type-literal type shapeChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["shape"]>; // tslint:disable-next-line interface-over-type-literal type shortDescChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["shortDesc"]>; // tslint:disable-next-line interface-over-type-literal type sourceChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["source"]>; // tslint:disable-next-line interface-over-type-literal type sourceHoverChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["sourceHover"]>; // tslint:disable-next-line interface-over-type-literal type sourceHoverSelectedChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["sourceHoverSelected"]>; // tslint:disable-next-line interface-over-type-literal type sourceSelectedChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["sourceSelected"]>; // tslint:disable-next-line interface-over-type-literal type svgClassNameChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["svgClassName"]>; // tslint:disable-next-line interface-over-type-literal type svgStyleChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["svgStyle"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["value"]>; // tslint:disable-next-line interface-over-type-literal type widthChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["width"]>; // tslint:disable-next-line interface-over-type-literal type xChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["x"]>; // tslint:disable-next-line interface-over-type-literal type yChanged<K3 = any, D3 = any> = JetElementCustomEvent<ojThematicMapMarker<K3, D3>["y"]>; } export interface ThematicMapIntrinsicProps extends Partial<Readonly<ojThematicMapSettableProperties<any, any, any, any, any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { onanimationDurationChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['animationDurationChanged']) => void; onanimationOnDisplayChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['animationOnDisplayChanged']) => void; onareaDataChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['areaDataChanged']) => void; onasChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['asChanged']) => void; onfocusRendererChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['focusRendererChanged']) => void; onhiddenCategoriesChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['hiddenCategoriesChanged']) => void; onhighlightMatchChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['highlightMatchChanged']) => void; onhighlightedCategoriesChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['highlightedCategoriesChanged']) => void; onhoverBehaviorChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['hoverBehaviorChanged']) => void; onhoverRendererChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['hoverRendererChanged']) => void; oninitialZoomingChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['initialZoomingChanged']) => void; onisolatedItemChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['isolatedItemChanged']) => void; onlabelDisplayChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['labelDisplayChanged']) => void; onlabelTypeChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['labelTypeChanged']) => void; onlinkDataChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['linkDataChanged']) => void; onmapProviderChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['mapProviderChanged']) => void; onmarkerDataChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['markerDataChanged']) => void; onmarkerZoomBehaviorChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['markerZoomBehaviorChanged']) => void; onmaxZoomChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['maxZoomChanged']) => void; onpanningChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['panningChanged']) => void; onrendererChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['rendererChanged']) => void; onselectionChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['selectionChanged']) => void; onselectionModeChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['selectionModeChanged']) => void; onselectionRendererChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['selectionRendererChanged']) => void; onstyleDefaultsChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['styleDefaultsChanged']) => void; ontooltipChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['tooltipChanged']) => void; ontooltipDisplayChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['tooltipDisplayChanged']) => void; ontouchResponseChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['touchResponseChanged']) => void; onzoomingChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['zoomingChanged']) => void; ontrackResizeChanged?: (value: ojThematicMapEventMap<any, any, any, any, any, any>['trackResizeChanged']) => void; children?: ComponentChildren; } export interface ThematicMapAreaIntrinsicProps extends Partial<Readonly<ojThematicMapAreaSettableProperties<any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { oncategoriesChanged?: (value: ojThematicMapAreaEventMap<any, any>['categoriesChanged']) => void; oncolorChanged?: (value: ojThematicMapAreaEventMap<any, any>['colorChanged']) => void; onlabelChanged?: (value: ojThematicMapAreaEventMap<any, any>['labelChanged']) => void; onlabelStyleChanged?: (value: ojThematicMapAreaEventMap<any, any>['labelStyleChanged']) => void; onlocationChanged?: (value: ojThematicMapAreaEventMap<any, any>['locationChanged']) => void; onopacityChanged?: (value: ojThematicMapAreaEventMap<any, any>['opacityChanged']) => void; onselectableChanged?: (value: ojThematicMapAreaEventMap<any, any>['selectableChanged']) => void; onshortDescChanged?: (value: ojThematicMapAreaEventMap<any, any>['shortDescChanged']) => void; onsvgClassNameChanged?: (value: ojThematicMapAreaEventMap<any, any>['svgClassNameChanged']) => void; onsvgStyleChanged?: (value: ojThematicMapAreaEventMap<any, any>['svgStyleChanged']) => void; children?: ComponentChildren; } export interface ThematicMapLinkIntrinsicProps extends Partial<Readonly<ojThematicMapLinkSettableProperties<any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { oncategoriesChanged?: (value: ojThematicMapLinkEventMap<any>['categoriesChanged']) => void; oncolorChanged?: (value: ojThematicMapLinkEventMap<any>['colorChanged']) => void; onendLocationChanged?: (value: ojThematicMapLinkEventMap<any>['endLocationChanged']) => void; onselectableChanged?: (value: ojThematicMapLinkEventMap<any>['selectableChanged']) => void; onshortDescChanged?: (value: ojThematicMapLinkEventMap<any>['shortDescChanged']) => void; onstartLocationChanged?: (value: ojThematicMapLinkEventMap<any>['startLocationChanged']) => void; onsvgClassNameChanged?: (value: ojThematicMapLinkEventMap<any>['svgClassNameChanged']) => void; onsvgStyleChanged?: (value: ojThematicMapLinkEventMap<any>['svgStyleChanged']) => void; onwidthChanged?: (value: ojThematicMapLinkEventMap<any>['widthChanged']) => void; children?: ComponentChildren; } export interface ThematicMapMarkerIntrinsicProps extends Partial<Readonly<ojThematicMapMarkerSettableProperties<any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { onborderColorChanged?: (value: ojThematicMapMarkerEventMap<any>['borderColorChanged']) => void; onborderStyleChanged?: (value: ojThematicMapMarkerEventMap<any>['borderStyleChanged']) => void; onborderWidthChanged?: (value: ojThematicMapMarkerEventMap<any>['borderWidthChanged']) => void; oncategoriesChanged?: (value: ojThematicMapMarkerEventMap<any>['categoriesChanged']) => void; oncolorChanged?: (value: ojThematicMapMarkerEventMap<any>['colorChanged']) => void; onheightChanged?: (value: ojThematicMapMarkerEventMap<any>['heightChanged']) => void; onlabelChanged?: (value: ojThematicMapMarkerEventMap<any>['labelChanged']) => void; onlabelPositionChanged?: (value: ojThematicMapMarkerEventMap<any>['labelPositionChanged']) => void; onlabelStyleChanged?: (value: ojThematicMapMarkerEventMap<any>['labelStyleChanged']) => void; onlocationChanged?: (value: ojThematicMapMarkerEventMap<any>['locationChanged']) => void; onopacityChanged?: (value: ojThematicMapMarkerEventMap<any>['opacityChanged']) => void; onrotationChanged?: (value: ojThematicMapMarkerEventMap<any>['rotationChanged']) => void; onselectableChanged?: (value: ojThematicMapMarkerEventMap<any>['selectableChanged']) => void; onshapeChanged?: (value: ojThematicMapMarkerEventMap<any>['shapeChanged']) => void; onshortDescChanged?: (value: ojThematicMapMarkerEventMap<any>['shortDescChanged']) => void; onsourceChanged?: (value: ojThematicMapMarkerEventMap<any>['sourceChanged']) => void; onsourceHoverChanged?: (value: ojThematicMapMarkerEventMap<any>['sourceHoverChanged']) => void; onsourceHoverSelectedChanged?: (value: ojThematicMapMarkerEventMap<any>['sourceHoverSelectedChanged']) => void; onsourceSelectedChanged?: (value: ojThematicMapMarkerEventMap<any>['sourceSelectedChanged']) => void; onsvgClassNameChanged?: (value: ojThematicMapMarkerEventMap<any>['svgClassNameChanged']) => void; onsvgStyleChanged?: (value: ojThematicMapMarkerEventMap<any>['svgStyleChanged']) => void; onvalueChanged?: (value: ojThematicMapMarkerEventMap<any>['valueChanged']) => void; onwidthChanged?: (value: ojThematicMapMarkerEventMap<any>['widthChanged']) => void; onxChanged?: (value: ojThematicMapMarkerEventMap<any>['xChanged']) => void; onyChanged?: (value: ojThematicMapMarkerEventMap<any>['yChanged']) => void; children?: ComponentChildren; } declare global { namespace preact.JSX { interface IntrinsicElements { "oj-thematic-map": ThematicMapIntrinsicProps; "oj-thematic-map-area": ThematicMapAreaIntrinsicProps; "oj-thematic-map-link": ThematicMapLinkIntrinsicProps; "oj-thematic-map-marker": ThematicMapMarkerIntrinsicProps; } } }
the_stack
import * as React from 'react'; import { initializeComponentRef, getRTL, classNamesFunction, getNativeProps, htmlElementProperties, } from '../../Utilities'; import { FocusZone, FocusZoneDirection } from '../../FocusZone'; import { Link } from '../../Link'; import { Icon } from '../../Icon'; import { IconButton } from '../../Button'; import { DirectionalHint } from '../../common/DirectionalHint'; import { ResizeGroup } from '../../ResizeGroup'; import { TooltipHost, TooltipOverflowMode } from '../../Tooltip'; import type { IProcessedStyleSet } from '../../Styling'; import type { IContextualMenuItem, IContextualMenuItemProps } from '../../ContextualMenu'; import type { IBreadcrumbProps, IBreadcrumbItem, IDividerAsProps, IBreadcrumbData, IBreadcrumbStyleProps, IBreadcrumbStyles, } from './Breadcrumb.types'; import { composeRenderFunction } from '../../Utilities'; /** @deprecated Use IBreadcrumbData */ export type IBreadCrumbData = IBreadcrumbData; const getClassNames = classNamesFunction<IBreadcrumbStyleProps, IBreadcrumbStyles>(); const OVERFLOW_KEY = 'overflow'; const nullFunction = (): null => null; const nonActionableItemProps: Partial<IContextualMenuItemProps> = { styles: props => { const { theme } = props; return { root: { selectors: { '&.is-disabled': { color: theme.semanticColors.bodyText, }, }, }, }; }, }; /** * {@docCategory Breadcrumb} */ export class BreadcrumbBase extends React.Component<IBreadcrumbProps, any> { public static defaultProps: IBreadcrumbProps = { items: [], maxDisplayedItems: 999, overflowIndex: 0, }; private _classNames: IProcessedStyleSet<IBreadcrumbStyles>; private _focusZone = React.createRef<FocusZone>(); constructor(props: IBreadcrumbProps) { super(props); initializeComponentRef(this); this._validateProps(props); } /** * Sets focus to the first breadcrumb link. */ public focus(): void { if (this._focusZone.current) { this._focusZone.current.focus(); } } public render(): JSX.Element { this._validateProps(this.props); const { onReduceData = this._onReduceData, onGrowData = this._onGrowData, overflowIndex, maxDisplayedItems, items, className, theme, styles, } = this.props; const renderedItems = [...items]; const renderedOverflowItems = renderedItems.splice(overflowIndex!, renderedItems.length - maxDisplayedItems!); const breadcrumbData: IBreadcrumbData = { props: this.props, renderedItems, renderedOverflowItems, }; this._classNames = getClassNames(styles, { className, theme: theme!, }); return ( <ResizeGroup onRenderData={this._onRenderBreadcrumb} onReduceData={onReduceData} onGrowData={onGrowData} data={breadcrumbData} /> ); } /** * Remove the first rendered item past the overlow point and put it and the end the overflow set. */ private _onReduceData = (data: IBreadcrumbData): IBreadcrumbData | undefined => { let { renderedItems, renderedOverflowItems } = data; const { overflowIndex } = data.props; const movedItem = renderedItems[overflowIndex!]; if (!movedItem) { return undefined; } renderedItems = [...renderedItems]; renderedItems.splice(overflowIndex!, 1); renderedOverflowItems = [...renderedOverflowItems, movedItem]; return { ...data, renderedItems, renderedOverflowItems }; }; /** * Remove the last item of the overflow set and insert the item as the start of the rendered set past the overflow * point. */ private _onGrowData = (data: IBreadcrumbData): IBreadcrumbData | undefined => { let { renderedItems, renderedOverflowItems } = data; const { overflowIndex, maxDisplayedItems } = data.props; renderedOverflowItems = [...renderedOverflowItems]; const movedItem = renderedOverflowItems.pop(); if (!movedItem || renderedItems.length >= maxDisplayedItems!) { return undefined; } renderedItems = [...renderedItems]; renderedItems.splice(overflowIndex!, 0, movedItem); return { ...data, renderedItems, renderedOverflowItems }; }; private _onRenderBreadcrumb = (data: IBreadcrumbData) => { const { ariaLabel, dividerAs: DividerType = Icon as React.ElementType<IDividerAsProps>, onRenderItem, overflowAriaLabel, overflowIndex, onRenderOverflowIcon, overflowButtonAs, } = data.props; const { renderedOverflowItems, renderedItems } = data; const contextualItems = renderedOverflowItems.map( (item): IContextualMenuItem => { const isActionable = !!(item.onClick || item.href); return { text: item.text, name: item.text, key: item.key, onClick: item.onClick ? this._onBreadcrumbClicked.bind(this, item) : null, href: item.href, disabled: !isActionable, itemProps: isActionable ? undefined : nonActionableItemProps, }; }, ); // Find index of last rendered item so the divider icon // knows not to render on that item const lastItemIndex = renderedItems.length - 1; const hasOverflowItems = renderedOverflowItems && renderedOverflowItems.length !== 0; const itemElements: JSX.Element[] = renderedItems.map((item, index) => { let finalOnRenderItem = this._onRenderItem; if (item.onRender) { finalOnRenderItem = composeRenderFunction(item.onRender, finalOnRenderItem); } if (onRenderItem) { finalOnRenderItem = composeRenderFunction(onRenderItem, finalOnRenderItem); } return ( <li className={this._classNames.listItem} key={item.key || String(index)}> {finalOnRenderItem(item)} {(index !== lastItemIndex || (hasOverflowItems && index === overflowIndex! - 1)) && ( <DividerType className={this._classNames.chevron} iconName={getRTL(this.props.theme) ? 'ChevronLeft' : 'ChevronRight'} item={item} /> )} </li> ); }); if (hasOverflowItems) { const iconProps = !onRenderOverflowIcon ? { iconName: 'More' } : {}; const onRenderMenuIcon = onRenderOverflowIcon ? onRenderOverflowIcon : nullFunction; const OverflowButton = overflowButtonAs ? overflowButtonAs : IconButton; itemElements.splice( overflowIndex!, 0, <li className={this._classNames.overflow} key={OVERFLOW_KEY}> <OverflowButton className={this._classNames.overflowButton} iconProps={iconProps} role="button" aria-haspopup="true" ariaLabel={overflowAriaLabel} onRenderMenuIcon={onRenderMenuIcon} menuProps={{ items: contextualItems, directionalHint: DirectionalHint.bottomLeftEdge, }} /> {overflowIndex !== lastItemIndex + 1 && ( <DividerType className={this._classNames.chevron} iconName={getRTL(this.props.theme) ? 'ChevronLeft' : 'ChevronRight'} item={renderedOverflowItems[renderedOverflowItems.length - 1]} /> )} </li>, ); } const nativeProps = getNativeProps<React.HTMLAttributes<HTMLDivElement>>(this.props, htmlElementProperties, [ 'className', ]); return ( <div className={this._classNames.root} role="navigation" aria-label={ariaLabel} {...nativeProps}> <FocusZone componentRef={this._focusZone} direction={FocusZoneDirection.horizontal} {...this.props.focusZoneProps} > <ol className={this._classNames.list}>{itemElements}</ol> </FocusZone> </div> ); }; private _onRenderItem = (item?: IBreadcrumbItem) => { if (!item) { return null; } const { as, href, onClick, isCurrentItem, text, onRenderContent, ...additionalProps } = item; let finalOnRenderContent = defaultOnRenderCrumbContent; if (onRenderContent) { finalOnRenderContent = composeRenderFunction(onRenderContent, finalOnRenderContent); } if (this.props.onRenderItemContent) { finalOnRenderContent = composeRenderFunction(this.props.onRenderItemContent, finalOnRenderContent); } if (onClick || href) { return ( <Link {...additionalProps} as={as} className={this._classNames.itemLink} href={href} aria-current={isCurrentItem ? 'page' : undefined} // eslint-disable-next-line react/jsx-no-bind onClick={this._onBreadcrumbClicked.bind(this, item)} > <TooltipHost content={text} overflowMode={TooltipOverflowMode.Parent} {...this.props.tooltipHostProps}> {finalOnRenderContent(item)} </TooltipHost> </Link> ); } else { const Tag = as || 'span'; return ( <Tag {...additionalProps} className={this._classNames.item}> <TooltipHost content={text} overflowMode={TooltipOverflowMode.Parent} {...this.props.tooltipHostProps}> {finalOnRenderContent(item)} </TooltipHost> </Tag> ); } }; private _onBreadcrumbClicked = (item: IBreadcrumbItem, ev: React.MouseEvent<HTMLElement>) => { if (item.onClick) { item.onClick(ev, item); } }; /** * Validate incoming props * @param props - Props to validate */ private _validateProps(props: IBreadcrumbProps): void { const { maxDisplayedItems, overflowIndex, items } = props; if ( overflowIndex! < 0 || (maxDisplayedItems! > 1 && overflowIndex! > maxDisplayedItems! - 1) || (items.length > 0 && overflowIndex! > items.length - 1) ) { throw new Error('Breadcrumb: overflowIndex out of range'); } } } function defaultOnRenderCrumbContent(item?: IBreadcrumbItem): JSX.Element | null { return item ? <>{item.text}</> : null; }
the_stack
import AppConfig from 'config/config'; import { BadgeStyle, BadgeStyleConfig } from 'config/config-types'; import { convertText, CaseType } from 'utils/textUtils'; import { TableMetadata } from 'interfaces/TableMetadata'; import { ResourceType } from '../interfaces'; import { AnalyticsConfig, FilterConfig, LinkConfig, NoticeType, TourConfig, } from './config-types'; export const DEFAULT_DATABASE_ICON_CLASS = 'icon-database icon-color'; export const DEFAULT_DASHBOARD_ICON_CLASS = 'icon-dashboard icon-color'; const WILDCARD_SIGN = '*'; const RESOURCE_SEPARATOR = '.'; const ANNOUNCEMENTS_LINK_LABEL = 'Announcements'; const hasWildcard = (n) => n.indexOf(WILDCARD_SIGN) > -1; const withComputedMessage = (notice: NoticeType, resourceName) => { if (typeof notice.messageHtml === 'function') { notice.messageHtml = notice.messageHtml(resourceName); } return notice; }; const resourceMatches = (key: string, resource: string) => { if (key === resource || key === WILDCARD_SIGN) { return true; } if (key.includes(WILDCARD_SIGN)) { const wildcardIndex = key.indexOf(WILDCARD_SIGN); const inverseWildcardIndex = -1 * (key.length - wildcardIndex - 1); if ( key.slice(0, wildcardIndex) === resource.slice(0, wildcardIndex) && (wildcardIndex === key.length - 1 || key.slice(inverseWildcardIndex) === resource.slice(inverseWildcardIndex)) ) { return true; } } return false; }; /** * Returns the display name for a given source id for a given resource type. * If a configuration or display name does not exist for the given id, the id * is returned. */ export function getSourceDisplayName( sourceId: string, resource: ResourceType ): string { const config = AppConfig.resourceConfig[resource]; if ( !config || !config.supportedSources || !config.supportedSources[sourceId] ) { return sourceId; } return config.supportedSources[sourceId].displayName; } /** * Returns an icon class for a given source id for a given resource type, * which should be a value defined in `static/css/_icons.scss`. * If a configuration or icon class does not exist for the given id, the default * icon class for the given resource type is returned. */ export function getSourceIconClass( sourceId: string, resource: ResourceType ): string { const config = AppConfig.resourceConfig[resource]; if ( !config || !config.supportedSources || !config.supportedSources[sourceId] ) { if (resource === ResourceType.dashboard) { return DEFAULT_DASHBOARD_ICON_CLASS; } if (resource === ResourceType.table) { return DEFAULT_DATABASE_ICON_CLASS; } if (resource === ResourceType.feature) { return DEFAULT_DATABASE_ICON_CLASS; } return ''; } return config.supportedSources[sourceId].iconClass; } /** * Returns notices for the given resource name if present */ export function getResourceNotices( resourceType: ResourceType, resourceName: string ): NoticeType | false { const { notices } = AppConfig.resourceConfig[resourceType]; if (notices && notices[resourceName]) { const thisNotice = notices[resourceName]; return withComputedMessage(thisNotice, resourceName); } const wildcardNoticesKeys = Object.keys(notices).filter(hasWildcard); if (wildcardNoticesKeys.length) { const wildcardNoticesArray = new Array(1); let hasNotice: boolean = false; wildcardNoticesKeys.forEach((key) => { const decomposedKey = key.split(RESOURCE_SEPARATOR); const decomposedResource = resourceName.split(RESOURCE_SEPARATOR); for (let i = 0; i < decomposedKey.length; i++) { if (resourceMatches(decomposedKey[i], decomposedResource[i])) { if (i === decomposedKey.length - 1) { wildcardNoticesArray[0] = notices[key]; hasNotice = true; } continue; } break; } }); if (hasNotice) { const [noticeFromWildcard] = wildcardNoticesArray; return withComputedMessage(noticeFromWildcard, resourceName); } } return false; } /** * Returns the displayName for the given resourceType */ export function getDisplayNameByResource(resourceType: ResourceType): string { return AppConfig.resourceConfig[resourceType].displayName; } /** * Returns the filterCategories for the given resourceType */ export function getFilterConfigByResource( resourceType: ResourceType ): FilterConfig | undefined { return AppConfig.resourceConfig[resourceType].filterCategories; } /** * Returns AnalyticsConfig. */ export function getAnalyticsConfig(): AnalyticsConfig { return AppConfig.analytics; } /** * Returns the stat type name for the unique value stat type * @returns string or undefined */ export function getUniqueValueStatTypeName(): string | undefined { return AppConfig.resourceConfig[ResourceType.table].stats ?.uniqueValueTypeName; } /* * Given a badge name, this will return a badge style and a display name. * If these are not specified by config, it will default to some simple rules: * use BadgeStyle.DEFAULT and badge name as display name. */ export function getBadgeConfig(badgeName: string): BadgeStyleConfig { const config: object = AppConfig.badges[badgeName] || {}; return { style: BadgeStyle.DEFAULT, displayName: convertText(badgeName, CaseType.TITLE_CASE), ...config, }; } /** * Returns whether or not feedback features should be enabled */ export function feedbackEnabled(): boolean { return AppConfig.mailClientFeatures.feedbackEnabled; } /** * Returns whether or not feedback features should be enabled */ export function announcementsEnabled(): boolean { return AppConfig.announcements.enabled; } /** * Returns whether or not dashboard features should be shown */ export function indexDashboardsEnabled(): boolean { return AppConfig.indexDashboards.enabled; } /** * Returns whether or not ML features should be shown */ export function indexFeaturesEnabled(): boolean { return AppConfig.indexFeatures.enabled; } /** * Returns whether or not user features should be shown */ export function indexUsersEnabled(): boolean { return AppConfig.indexUsers.enabled; } /** * Returns whether or not the issue tracking feature should be shown */ export function issueTrackingEnabled(): boolean { return AppConfig.issueTracking.enabled; } /** * Returns the string that will prepopulate the issue description * text field with a template to suggest more detailed information * to be provided by the user when an issue is reported */ export function getIssueDescriptionTemplate(): string | undefined { return AppConfig.issueTracking.issueDescriptionTemplate; } /** * Returns whether users are able to override the default project in which to create the issue */ export function issueTrackingProjectSelectionEnabled(): boolean { const config = AppConfig.issueTracking.projectSelection; return config ? config.enabled : false; } /** * Returns the title for the selection field that allows more specificity in what you ask the user to enter */ export function getProjectSelectionTitle(): string { const config = AppConfig.issueTracking.projectSelection; return config ? config.title : ''; } /** * Returns the hint to show the user what type of value is expected, such as the name of the default project */ export function getProjectSelectionHint(): string | undefined { const config = AppConfig.issueTracking.projectSelection; return config ? config.inputHint : ''; } /** * Returns whether or not notification features should be enabled */ export function notificationsEnabled(): boolean { return AppConfig.mailClientFeatures.notificationsEnabled; } /** * Returns whether or not to show all tags */ export function showAllTags(): boolean { return AppConfig.browse.showAllTags; } /** * Returns a list of curated tag names */ export function getCuratedTags(): string[] { return AppConfig.browse.curatedTags; } /** * Returns a list of table sort options */ export function getTableSortCriterias() { const config = AppConfig.resourceConfig[ResourceType.table]; if (config && config.sortCriterias) { return config.sortCriterias; } return {}; } /** * Checks if nav links are active */ const isNavLinkActive = (link: LinkConfig): boolean => { if (!announcementsEnabled()) { return link.label !== ANNOUNCEMENTS_LINK_LABEL; } return true; }; /* * Returns the updated list of navigation links given the other * configuration options state */ export function getNavLinks(): LinkConfig[] { return AppConfig.navLinks.filter(isNavLinkActive); } /** * Returns whether to enable the table `explore` feature */ export function exploreEnabled(): boolean { return AppConfig.tableProfile.isExploreEnabled; } /** * Generates the explore URL from a table metadata object * * @param tableData */ export function generateExploreUrl(tableData: TableMetadata): string { const { partition } = tableData; if (partition.is_partitioned) { return AppConfig.tableProfile.exploreUrlGenerator( tableData.database, tableData.cluster, tableData.schema, tableData.name, partition.key, partition.value ); } return AppConfig.tableProfile.exploreUrlGenerator( tableData.database, tableData.cluster, tableData.schema, tableData.name ); } /** * Gets the max length for items with a configurable max length. * Currently only applied to `editableText`, but method can be extended for future cases */ export function getMaxLength(key: string) { return AppConfig.editableText[key]; } /** * Returns the display name for a given description source id for a given resource type. * If a configuration or display name does not exist for the given description source id, the id * is returned. */ export function getDescriptionSourceDisplayName(sourceId: string): string { const config = AppConfig.resourceConfig[ResourceType.table]; if ( config && config.supportedDescriptionSources && config.supportedDescriptionSources[sourceId] && config.supportedDescriptionSources[sourceId].displayName ) { return config.supportedDescriptionSources[sourceId].displayName; } return sourceId; } /** * Returns the icon path for a given description source id for a given resource type. * If a configuration does not exist for the given description source id, empty string * is returned. */ export function getDescriptionSourceIconPath(sourceId: string): string { const config = AppConfig.resourceConfig[ResourceType.table]; if ( config && config.supportedDescriptionSources && config.supportedDescriptionSources[sourceId] && config.supportedDescriptionSources[sourceId].iconPath ) { return config.supportedDescriptionSources[sourceId].iconPath; } return ''; } /** * Returns the desired number format in which we want to format any number * Used for formatting column stats * If a configuration does not exist, None is returned */ export function getNumberFormat() { return AppConfig.numberFormat; } /** * Returns documentTitle. */ export function getDocumentTitle(): string { return AppConfig.documentTitle; } /** * Returns logoTitle. */ export function getLogoTitle(): string { return AppConfig.logoTitle; } /** * Returns whether the in-app table lineage list is enabled. */ export function isFeatureListLineageEnabled() { return AppConfig.featureLineage.inAppListEnabled; } /** * Returns whether the in-app table lineage list is enabled. */ export function isTableListLineageEnabled() { return AppConfig.tableLineage.inAppListEnabled; } /** * Returns whether the in-app column list lineage is enabled. */ export function isColumnListLineageEnabled() { return AppConfig.columnLineage.inAppListEnabled; } /** * Returns whether the in-app table lineage page is enabled. */ export function isTableLineagePageEnabled() { return AppConfig.tableLineage.inAppPageEnabled; } /** * Returns whether the in-app column lineage page is enabled. */ export function isColumnLineagePageEnabled() { return AppConfig.columnLineage.inAppPageEnabled; } /** * Returns the lineage link for a given column */ export function getColumnLineageLink( tableData: TableMetadata, columnName: string ) { return AppConfig.columnLineage.urlGenerator( tableData.database, tableData.cluster, tableData.schema, tableData.name, columnName ); } /** * Returns whether table data quality checks are enabled */ export function isTableQualityCheckEnabled() { return AppConfig.tableQualityChecks.isEnabled; } /** * Returns whether Available badges section should be shown in Home Page */ export function isShowBadgesInHomeEnabled() { return AppConfig.browse.showBadgesInHome; } /** * Returns whether or not nested columns are enabled */ export function isNestedColumnsEnabled() { return AppConfig.nestedColumns.isEnabled; } /** * Returns the maximum number of columns allowed to show nested columns */ export function getMaxNestedColumns() { return AppConfig.nestedColumns.maxNestedColumns; } /** * Returns the configuration for the Product Tour */ export function getProductToursFor(path: string): TourConfig[] | null { let result: TourConfig[] | null = null; if (AppConfig.productTour[path] && AppConfig.productTour[path].length) { result = AppConfig.productTour[path]; } const wildcardPathKeys = Object.keys(AppConfig.productTour).filter( hasWildcard ); if (wildcardPathKeys.length) { wildcardPathKeys.forEach((key) => { const decomposedKey = key.substring(0, key.length - 1); if (path.startsWith(decomposedKey)) { result = AppConfig.productTour[key]; } }); } return result; }
the_stack
import { Linter } from './Linter'; declare class ESLintBase { /** * Creates a new instance of the main ESLint API. * @param options The options for this instance. */ constructor(options?: ESLint.ESLintOptions); /** * This method calculates the configuration for a given file, which can be useful for debugging purposes. * - It resolves and merges extends and overrides settings into the top level configuration. * - It resolves the parser setting to absolute paths. * - It normalizes the plugins setting to align short names. (e.g., eslint-plugin-foo → foo) * - It adds the processor setting if a legacy file extension processor is matched. * - It doesn't interpret the env setting to the globals and parserOptions settings, so the result object contains * the env setting as is. * @param filePath The path to the file whose configuration you would like to calculate. Directory paths are forbidden * because ESLint cannot handle the overrides setting. * @returns The promise that will be fulfilled with a configuration object. */ calculateConfigForFile(filePath: string): Promise<Linter.Config>; /** * This method checks if a given file is ignored by your configuration. * @param filePath The path to the file you want to check. * @returns The promise that will be fulfilled with whether the file is ignored or not. If the file is ignored, then * it will return true. */ isPathIgnored(filePath: string): Promise<boolean>; /** * This method lints the files that match the glob patterns and then returns the results. * @param patterns The lint target files. This can contain any of file paths, directory paths, and glob patterns. * @returns The promise that will be fulfilled with an array of LintResult objects. */ lintFiles(patterns: string | string[]): Promise<ESLint.LintResult[]>; /** * This method lints the given source code text and then returns the results. * * By default, this method uses the configuration that applies to files in the current working directory (the cwd * constructor option). If you want to use a different configuration, pass options.filePath, and ESLint will load the * same configuration that eslint.lintFiles() would use for a file at options.filePath. * * If the options.filePath value is configured to be ignored, this method returns an empty array. If the * options.warnIgnored option is set along with the options.filePath option, this method returns a LintResult object. * In that case, the result may contain a warning that indicates the file was ignored. * @param code The source code text to check. * @param options The options. * @returns The promise that will be fulfilled with an array of LintResult objects. This is an array (despite there * being only one lint result) in order to keep the interfaces between this and the eslint.lintFiles() * method similar. */ lintText(code: string, options?: ESLint.LintTextOptions): Promise<ESLint.LintResult[]>; /** * This method loads a formatter. Formatters convert lint results to a human- or machine-readable string. * @param name TThe path to the file you want to check. * The following values are allowed: * - undefined. In this case, loads the "stylish" built-in formatter. * - A name of built-in formatters. * - A name of third-party formatters. For examples: * -- `foo` will load eslint-formatter-foo. * -- `@foo` will load `@foo/eslint-formatter`. * -- `@foo/bar` will load `@foo/eslint-formatter-bar`. * - A path to the file that defines a formatter. The path must contain one or more path separators (/) in order to distinguish if it's a path or not. For example, start with ./. * @returns The promise that will be fulfilled with a Formatter object. */ loadFormatter(name?: string): Promise<ESLint.Formatter>; /** * This method copies the given results and removes warnings. The returned value contains only errors. * @param results The LintResult objects to filter. * @returns The filtered LintResult objects. */ static getErrorResults(results: ESLint.LintResult): ESLint.LintResult; /** * This method writes code modified by ESLint's autofix feature into its respective file. If any of the modified * files don't exist, this method does nothing. * @param results The LintResult objects to write. * @returns The promise that will be fulfilled after all files are written. */ static outputFixes(results: ESLint.LintResult): Promise<void>; /** * The version text. */ static readonly version: string; } declare namespace ESLint { interface ESLintOptions { /** * If false is present, ESLint suppresses directive comments in source code. * If this option is false, it overrides the noInlineConfig setting in your configurations. */ allowInlineConfig?: boolean; /** * Configuration object, extended by all configurations used with this instance. * You can use this option to define the default settings that will be used if your configuration files don't * configure it. */ baseConfig?: Linter.Config | null; /** * If true is present, the eslint.lintFiles() method caches lint results and uses it if each target file is not * changed. Please mind that ESLint doesn't clear the cache when you upgrade ESLint plugins. In that case, you have * to remove the cache file manually. The eslint.lintText() method doesn't use caches even if you pass the * options.filePath to the method. */ cache?: boolean; /** * The eslint.lintFiles() method writes caches into this file. */ cacheLocation?: string; /** * The working directory. This must be an absolute path. */ cwd?: string; /** * Unless set to false, the eslint.lintFiles() method will throw an error when no target files are found. */ errorOnUnmatchedPattern?: boolean; /** * If you pass directory paths to the eslint.lintFiles() method, ESLint checks the files in those directories that * have the given extensions. For example, when passing the src/ directory and extensions is [".js", ".ts"], ESLint * will lint *.js and *.ts files in src/. If extensions is null, ESLint checks *.js files and files that match * overrides[].files patterns in your configuration. * Note: This option only applies when you pass directory paths to the eslint.lintFiles() method. * If you pass glob patterns, ESLint will lint all files matching the glob pattern regardless of extension. */ extensions?: string[] | null; /** * If true is present, the eslint.lintFiles() and eslint.lintText() methods work in autofix mode. * If a predicate function is present, the methods pass each lint message to the function, then use only the * lint messages for which the function returned true. */ fix?: boolean | ((message: LintMessage) => boolean); /** * The types of the rules that the eslint.lintFiles() and eslint.lintText() methods use for autofix. */ fixTypes?: string[]; /** * If false is present, the eslint.lintFiles() method doesn't interpret glob patterns. */ globInputPaths?: boolean; /** * If false is present, the eslint.lintFiles() method doesn't respect `.eslintignore` files or ignorePatterns in * your configuration. */ ignore?: boolean; /** * The path to a file ESLint uses instead of `$CWD/.eslintignore`. * If a path is present and the file doesn't exist, this constructor will throw an error. */ ignorePath?: string; /** * Configuration object, overrides all configurations used with this instance. * You can use this option to define the settings that will be used even if your configuration files configure it. */ overrideConfig?: Linter.ConfigOverride | null; /** * The path to a configuration file, overrides all configurations used with this instance. * The options.overrideConfig option is applied after this option is applied. */ overrideConfigFile?: string | null; /** * The plugin implementations that ESLint uses for the plugins setting of your configuration. * This is a map-like object. Those keys are plugin IDs and each value is implementation. */ plugins?: Record<string, Linter.Plugin> | null; /** * The severity to report unused eslint-disable directives. * If this option is a severity, it overrides the reportUnusedDisableDirectives setting in your configurations. */ reportUnusedDisableDirectives?: Linter.SeverityString | null; /** * The path to a directory where plugins should be resolved from. * If null is present, ESLint loads plugins from the location of the configuration file that contains the plugin * setting. * If a path is present, ESLint loads all plugins from there. */ resolvePluginsRelativeTo?: string | null; /** * An array of paths to directories to load custom rules from. */ rulePaths?: string[]; /** * If false is present, ESLint doesn't load configuration files (.eslintrc.* files). * Only the configuration of the constructor options is valid. */ useEslintrc?: boolean; } interface DeprecatedRuleInfo { /** * The rule ID. */ ruleId: string; /** * The rule IDs that replace this deprecated rule. */ replacedBy: string[]; } /** * The LintResult value is the information of the linting result of each file. */ interface LintResult { /** * The number of errors. This includes fixable errors. */ errorCount: number; /** * The absolute path to the file of this result. This is the string "<text>" if the file path is unknown (when you * didn't pass the options.filePath option to the eslint.lintText() method). */ filePath: string; /** * The number of errors that can be fixed automatically by the fix constructor option. */ fixableErrorCount: number; /** * The number of warnings that can be fixed automatically by the fix constructor option. */ fixableWarningCount: number; /** * The array of LintMessage objects. */ messages: Linter.LintMessage[]; /** * The source code of the file that was linted, with as many fixes applied as possible. */ output?: string; /** * The original source code text. This property is undefined if any messages didn't exist or the output * property exists. */ source?: string; /** * The information about the deprecated rules that were used to check this file. */ usedDeprecatedRules: DeprecatedRuleInfo[]; /** * The number of warnings. This includes fixable warnings. */ warningCount: number; } interface LintTextOptions { /** * The path to the file of the source code text. If omitted, the result.filePath becomes the string "<text>". */ filePath?: string; /** * If true is present and the options.filePath is a file ESLint should ignore, this method returns a lint result * contains a warning message. */ warnIgnored?: boolean; } /** * The LintMessage value is the information of each linting error. */ interface LintMessage { /** * The 1-based column number of the begin point of this message. */ column: number; /** * The 1-based column number of the end point of this message. This property is undefined if this message * is not a range. */ endColumn: number | undefined; /** * The 1-based line number of the end point of this message. This property is undefined if this * message is not a range. */ endLine: number | undefined; /** * The EditInfo object of autofix. This property is undefined if this message is not fixable. */ fix: EditInfo | undefined; /** * The 1-based line number of the begin point of this message. */ line: number; /** * The error message */ message: string; /** * The rule name that generates this lint message. If this message is generated by the ESLint core rather than * rules, this is null. */ ruleId: string | null; /** * The severity of this message. 1 means warning and 2 means error. */ severity: 1 | 2; /** * The list of suggestions. Each suggestion is the pair of a description and an EditInfo object to fix code. API * users such as editor integrations can choose one of them to fix the problem of this message. This property is * undefined if this message doesn't have any suggestions. */ suggestions: { desc: string; fix: EditInfo; }[] | undefined; } /** * The EditInfo value is information to edit text. * * This edit information means replacing the range of the range property by the text property value. It's like * sourceCodeText.slice(0, edit.range[0]) + edit.text + sourceCodeText.slice(edit.range[1]). Therefore, it's an add * if the range[0] and range[1] property values are the same value, and it's removal if the text property value is * empty string. */ interface EditInfo { /** * The pair of 0-based indices in source code text to remove. */ range: [number, number]; /** * The text to add. */ text: string; } /** * The Formatter value is the object to convert the LintResult objects to text. */ interface Formatter { /** * The method to convert the LintResult objects to text */ format(results: LintResult[]): string; } } declare const _ESLint: typeof ESLintBase; /** * The ESLint class is the primary class to use in Node.js applications. * This class depends on the Node.js fs module and the file system, so you cannot use it in browsers. * * If you want to lint code on browsers, use the Linter class instead. * * @since 7.0.0 */ declare class ESLint extends _ESLint { } export { ESLint }; //# sourceMappingURL=ESLint.d.ts.map
the_stack
import "geckodriver" import * as process from "process" const env = process.env import * as fs from "fs" import * as os from "os" import * as path from "path" import * as webdriver from "selenium-webdriver" import * as Until from "selenium-webdriver/lib/until" const {By} = webdriver import {Options} from "selenium-webdriver/firefox" import { getNewestFileIn, sendKeys } from "./utils"; jest.setTimeout(100000) // API docs because I waste too much time looking for them every time I go back to this: // https://seleniumhq.github.io/selenium/docs/api/javascript/ describe("webdriver", () => { function iframeLoaded(driver) { return driver.wait(Until.elementLocated(By.id("cmdline_iframe"))) } async function getDriver() { const extensionPath = await getNewestFileIn(path.resolve("web-ext-artifacts")) if (extensionPath === undefined) { throw new Error("Couldn't find extension path"); } const options = (new Options()) .setPreference("xpinstall.signatures.required", false) .addExtensions(extensionPath) if (env["HEADLESS"]) { options.headless(); } const driver = new webdriver.Builder() .forBrowser("firefox") .setFirefoxOptions(options) .build() // Wait until addon is loaded and :tutor is displayed await iframeLoaded(driver) // And wait a bit more otherwise Tridactyl won't be happy await driver.sleep(500) return driver } async function getDriverAndProfileDirs() { const rootDir = os.tmpdir() // First, find out what profile the driver is using const profiles = fs.readdirSync(rootDir).map(p => path.join(rootDir, p)) const driver = await getDriver() const newProfiles = fs.readdirSync(rootDir).map(p => path.join(rootDir, p)) .filter(p => p.match("moz") && !profiles.includes(p)) // Tridactyl's tmp profile detection is broken on windows and OSX if (["win32", "darwin"].includes(os.platform())) { await sendKeys(driver, `:set profiledir ${newProfiles[0]}<CR>`) await driver.sleep(1000) } return { driver, newProfiles } } async function killDriver(driver) { try { await driver.close() } catch(e) {} try { await driver.quit() } catch(e) {} } async function untilTabUrlMatches(driver, tabId, pattern) { let match do { match = (await driver.executeScript(`return tri.browserBg.tabs.get(${tabId})`)) .url .match(pattern) } while (!match) return match } async function newTabWithoutChangingOldTabs (driver, callback) { const tabsBefore = await driver.executeScript("return tri.browserBg.tabs.query({})") const result = await callback(tabsBefore); const tabsAfter = await driver.wait(async () => { let tabsAfter do { tabsAfter = await driver.executeScript("return tri.browserBg.tabs.query({})") } while (tabsAfter.length == tabsBefore.length) return tabsAfter }) // A single new tab has been created expect(tabsAfter.length).toBe(tabsBefore.length + 1) // None of the previous tabs changed, except maybe for their index const newtab = tabsAfter.find(tab2 => !tabsBefore.find(tab => tab.id == tab2.id)) const notNewTabs = tabsAfter.slice() notNewTabs.splice(tabsAfter.findIndex(tab => tab == newtab), 1) const ignoreValues = { active: false, // the previously-active tab isn't necessarily active anymore highlighted: true, // changing tabs changes highlights index: 0, // indexes might not be the same depending on whether the new tab is lastAccessed: 0, // lastAccessed has also changed for the previously-active tab } for (let i = 0; i < tabsBefore.length; ++i) { let copy1 = Object.assign({}, tabsBefore[i], ignoreValues) let copy2 = Object.assign({}, notNewTabs[i], ignoreValues) expect(copy1).toEqual(copy2) } return [newtab, result] } // A simple ternany doesn't work inline :( function testbutskipplatforms(...platforms){ if (platforms.includes(os.platform())) { return test.skip } return test } test("`:rssexec` works", async () => { const driver = await getDriver() try { await sendKeys(driver, ":set rsscmd js " + "const elem=document.createElement('span');" + "elem.id='rsscmdExecuted';" + "elem.innerText=`%u`;" + "document.body.appendChild(elem)<CR>") // First, make sure completions are offered await driver.get("file:///" + process.cwd() + "/e2e_tests/html/rss.html") const iframe = await iframeLoaded(driver) await sendKeys(driver, ":rssexec ") await driver.switchTo().frame(iframe) const elements = await driver.findElements(By.className("RssCompletionOption")) expect(elements.length).toBeGreaterThan(3) const url = await elements[0].getAttribute("innerText") // Then, make sure rsscmd is executed and has the right arguments await sendKeys(driver, "<Tab><CR>") await (driver.switchTo() as any).parentFrame() const elem = await driver.wait(Until.elementLocated(By.id("rsscmdExecuted"))) expect(url).toMatch(await elem.getAttribute("innerText")) } catch (e) { fail(e) } finally { await killDriver(driver) } }) test("`:editor` works", async () => { const driver = await getDriver() try { const addedText = "There are %l lines and %c characters in this textarea." if (os.platform() == "win32") { await sendKeys(driver, `:set editorcmd echo | set /p text="${addedText}" >> %f<CR>`) } else { await sendKeys(driver, `:set editorcmd /bin/echo -n '${addedText}' >> %f<CR>`) } const areaId = "editorTest" await driver.executeScript(` const area = document.createElement("textarea") area.id = "${areaId}" document.body.appendChild(area) area.focus() `) const text = "This is a line\nThis is another\nThis is a third." await sendKeys(driver, text + "<C-i>") await driver.sleep(1000) expect(await driver.executeScript(`return document.getElementById("${areaId}").value`)) .toEqual(text + addedText.replace("%l", "3").replace("%c", "" + text.split("\n")[2].length)) } catch (e) { fail(e) } finally { await killDriver(driver) } }) testbutskipplatforms("darwin")("`:guiset` works", async () => { const { driver, newProfiles } = await getDriverAndProfileDirs() try { // Then, make sure `:guiset` is offering completions const iframe = await iframeLoaded(driver) await sendKeys(driver, ":guiset ") await driver.switchTo().frame(iframe) const elements = await driver.findElements(By.className("GuisetCompletionOption")) expect(elements.length).toBeGreaterThan(0) // Use whatever the first suggestion is await sendKeys(driver, "<Tab> <Tab><CR>") await driver.sleep(2000) expect(await driver.executeScript(`return document.getElementById("tridactyl-input").value`)) .toEqual("userChrome.css written. Please restart Firefox to see the changes.") expect(newProfiles.find(p => fs .readdirSync(path.join(p, "chrome")) .find(files => files.match("userChrome.css$"))) ).toBeDefined() } catch (e) { fail(e) } finally { await killDriver(driver) } }) test("`:colourscheme` works", async () => { const driver = await getDriver() try { expect(await driver.executeScript(`return document.documentElement.className`)) .toMatch("TridactylOwnNamespace TridactylThemeDefault") await sendKeys(driver, ":colourscheme dark<CR>") await driver.sleep(100) expect(await driver.executeScript(`return document.documentElement.className`)) .toMatch("TridactylOwnNamespace TridactylThemeDark") } catch (e) { fail(e) } finally { await killDriver(driver) } }) test("`:setpref` works", async () => { const { driver, newProfiles } = await getDriverAndProfileDirs() try { await sendKeys(driver, `:setpref a.b.c "d"<CR>`) await driver.sleep(2000) const file = fs.readFileSync(path.join(newProfiles[0], "user.js"), { encoding: "utf-8" }) expect(file).toMatch(/user_pref\("a.b.c", "d"\);/) } catch (e) { fail(e) } finally { await killDriver(driver) } }) test("`:tabopen<CR>` opens the newtab page.", async () => { const driver = await getDriver() return newTabWithoutChangingOldTabs(driver, async (tabsBefore) => { await sendKeys(driver, ":tabopen<CR>") }).then(async ([newtab, _]) => { // The new tab is active expect(newtab.active).toEqual(true) // Its url is the newtab page's url await driver.wait(untilTabUrlMatches(driver, newtab.id, new RegExp("moz-extension://.*/static/newtab.html")), 10000) }).finally(() => killDriver(driver)) }) test("`:tabopen https://example.org<CR>` opens example.org.", async () => { const driver = await getDriver() return newTabWithoutChangingOldTabs(driver, async () => { await sendKeys(driver, ":tabopen https://example.org<CR>") }).then(async ([newtab, _]) => { expect(newtab.active).toEqual(true) await driver.wait(untilTabUrlMatches(driver, newtab.id, "https://example.org"), 10000) }).finally(() => killDriver(driver)) }) test("`:tabopen qwant https://example.org<CR>` opens qwant.", async () => { const driver = await getDriver() return newTabWithoutChangingOldTabs(driver, async () => { await sendKeys(driver, ":tabopen qwant https://example.org<CR>") }).then(async ([newtab, _]) => { expect(newtab.active).toEqual(true) await driver.wait(untilTabUrlMatches(driver, newtab.id, new RegExp("^https://www.qwant.com/.*example.org")), 10000) }).finally(() => killDriver(driver)) }) // test("`:tabopen test<CR>` opens google.", async () => { // const driver = await getDriver() // return newTabWithoutChangingOldTabs(driver, async () => { // await sendKeys(driver, ":tabopen test<CR>") // }).then(async ([newtab, _]) => { // expect(newtab.active).toEqual(true) // await driver.wait(untilTabUrlMatches(driver, newtab.id, new RegExp("^https://www.google.com/.*test")), 10000) // }).finally(() => killDriver(driver)) // }) // test("`:tabopen example.org<CR>` opens example.org.", async () => { // const driver = await getDriver() // return newTabWithoutChangingOldTabs(driver, async () => { // await sendKeys(driver, ":tabopen example.org<CR>") // }).then(async ([newtab, _]) => { // expect(newtab.active).toEqual(true) // await driver.wait(untilTabUrlMatches(driver, newtab.id, "example.org"), 10000) // }).finally(() => killDriver(driver)) // }) // test("`:tabopen search duckduckgo<CR>` opens google.", async () => { // const driver = await getDriver() // return newTabWithoutChangingOldTabs(driver, async () => { // await sendKeys(driver, ":tabopen search duckduckgo<CR>") // }).then(async ([newtab, _]) => { // expect(newtab.active).toEqual(true) // await driver.wait(untilTabUrlMatches(driver, newtab.id, new RegExp("^https://www.google.com/search.*duckduckgo")), 10000) // }).finally(() => killDriver(driver)) // }) // test("`:tabopen -b about:blank<CR>` opens a background tab.", async () => { // const driver = await getDriver() // return newTabWithoutChangingOldTabs(driver, async () => { // await sendKeys(driver, ":tabopen -b about:blank<CR>") // }).then(async ([newtab, _]) => { // expect(newtab.active).toEqual(false) // await driver.wait(untilTabUrlMatches(driver, newtab.id, "about:blank")) // }).finally(() => killDriver(driver)) // }) // test("`:tabopen -c work about:blank<CR>` opens about:blank in a container.", async () => { // const driver = await getDriver() // return newTabWithoutChangingOldTabs(driver, async () => { // await sendKeys(driver, ":tabopen -c work about:blank<CR>") // }).then(async ([newtab, _]) => { // expect(newtab.active).toEqual(true) // expect(newtab.cookieStoreId).toMatch("firefox-container-") // await driver.wait(untilTabUrlMatches(driver, newtab.id, "about:blank")) // }).finally(() => killDriver(driver)) // }) // test("`:tabopen -b -c work search qwant<CR>` opens about:blank in a container.", async () => { // const driver = await getDriver() // return newTabWithoutChangingOldTabs(driver, async () => { // await sendKeys(driver, ":tabopen -b -c work search qwant<CR>") // }).then(async ([newtab, _]) => { // expect(newtab.active).toEqual(false) // expect(newtab.cookieStoreId).toMatch("firefox-container-") // await driver.wait(untilTabUrlMatches(driver, newtab.id, new RegExp("^https://www.google.com/search.*qwant"))) // }).finally(() => killDriver(driver)) // }) }) // vim: tabstop=4 shiftwidth=4 expandtab
the_stack
import { Event, IGroup, ICanvas, IShape } from '@antv/g-base'; import { get, size, assign, each, isNumber } from '@antv/util'; import { ext } from '@antv/matrix-util'; import Trend, { TrendCfg } from './trend'; import Handler from './handler'; import { isString } from '@antv/util'; import ControllerBtn, { ControllerCfg } from './controllerBtn'; import { ShapeStyle, IAbstractGraph as IGraph } from '@antv/g6-core'; import { VALUE_CHANGE, TIMELINE_START, TIMEBAR_CONFIG_CHANGE, PLAY_PAUSE_BTN, NEXT_STEP_BTN, PRE_STEP_BTN, TIMELINE_END, } from './constant'; const transform = ext.transform; /** * 一些默认的样式配置 */ export const BACKGROUND_STYLE = { fill: '#416180', opacity: 0.05, }; const SIMPLE_BACKGROUND_STYLE = { fill: '#416180', opacity: 0.15, radius: 5, }; export const FOREGROUND_STYLE = { fill: '#5B8FF9', opacity: 0.3, cursor: 'grab', }; export const DEFAULT_HANDLER_WIDTH = 2; export const HANDLER_STYLE = { width: DEFAULT_HANDLER_WIDTH, height: 24, }; export const TEXT_STYLE = { textBaseline: 'middle', fill: '#000', opacity: 0.45, }; export const TICK_LABEL_STYLE = { textAlign: 'center', textBaseline: 'top', fill: '#607889', opacity: 0.35, } export const TICK_LINE_STYLE = { lineWidth: 1, stroke: '#ccc', } export type SliderOption = Partial<{ readonly width?: number; readonly height?: number; readonly backgroundStyle?: ShapeStyle; readonly foregroundStyle?: ShapeStyle; // 滑块样式 readonly handlerStyle?: { width?: number; height?: number; style?: ShapeStyle; }; readonly textStyle?: ShapeStyle; // 初始位置 readonly start: number; readonly end: number; // 滑块文本 readonly minText: string; readonly maxText: string; }>; export type TickCfg = { readonly ticks?: { date: string; value: string; }[]; readonly tickLabelFormatter?: (d: any) => string | undefined; readonly tickLabelStyle?: ShapeStyle; readonly tickLineStyle?: ShapeStyle; }; interface TrendTimeBarConfig extends SliderOption { readonly graph: IGraph; readonly canvas: ICanvas; readonly group: IGroup; // position size readonly x: number; readonly y: number; readonly width: number; readonly height: number; readonly padding: number; readonly type: 'trend' | 'simple'; // style readonly trendCfg?: TrendCfg; readonly backgroundStyle?: ShapeStyle; readonly foregroundStyle?: ShapeStyle; readonly tick?: TickCfg; readonly controllerCfg: ControllerCfg; // 自定义标签格式化函数 } export default class TrendTimeBar { private group: IGroup; private graph: IGraph; private canvas: ICanvas; // 位置大小配置 public x: number; public y: number; public width: number; public height: number; private padding: number; private trendCfg: TrendCfg; private timeBarType: 'trend' | 'simple'; private controllerCfg: ControllerCfg; // 样式配置 private backgroundStyle: any; private foregroundStyle: any; private handlerStyle: any; private textStyle: any; /* 前景框,选中的区域 */ private foregroundShape: IShape; /* 左侧(上侧)的按钮 */ private minHandlerShape: Handler; /* 左侧文本 */ private minTextShape: IShape; /* 由侧(下侧)的按钮 */ private maxHandlerShape: Handler; /* 右侧文本 */ private maxTextShape: IShape; private textList: IShape[]; // 交互相关的数据信息 private start: number; private end: number; private minText: string; private maxText: string; private currentHandler: Handler | IShape; private prevX: number = 0; /** 刻度位置预处理 */ private tickPosList: number[]; private ticks: { date: string; value: string; }[]; /** 是否处于播放状态 */ private isPlay: boolean; // 调整后的播放速度 private currentSpeed: number; private currentMode: 'single' | 'range'; /** 动画 id */ private playHandler: number; private controllerBtnGroup: ControllerBtn; private trendComponent: Trend; private fontFamily: string; private tickLabelFormatter: (d: any) => string | undefined; private tickLabelStyle: ShapeStyle; private tickLineStyle: ShapeStyle; constructor(cfg: TrendTimeBarConfig) { const { x = 0, y = 0, width = 100, height, padding = 10, trendCfg, controllerCfg = { speed: 1, }, backgroundStyle = {}, foregroundStyle = {}, handlerStyle = {}, textStyle = {}, // 缩略轴的初始位置 start = 0, end = 1, minText = '', maxText = '', group, graph, canvas, tick = { tickLabelStyle: {}, tickLineStyle: {}, tickLabelFormatter: (d: string) => { return d; }, ticks: [] } as TickCfg, type, } = cfg; this.graph = graph; this.canvas = canvas; this.group = group; this.timeBarType = type; // position size this.x = x; this.y = y; this.width = width; this.height = height; this.padding = padding; this.ticks = tick.ticks; this.trendCfg = trendCfg; this.controllerCfg = controllerCfg; this.currentSpeed = controllerCfg.speed || 1; this.tickLabelFormatter = tick.tickLabelFormatter; // style if (type === 'trend') { this.backgroundStyle = { ...BACKGROUND_STYLE, ...backgroundStyle }; } else if (type === 'simple') { this.backgroundStyle = { ...SIMPLE_BACKGROUND_STYLE, ...backgroundStyle }; } this.foregroundStyle = { ...FOREGROUND_STYLE, ...foregroundStyle }; this.handlerStyle = { ...HANDLER_STYLE, ...handlerStyle }; this.textStyle = { ...TEXT_STYLE, ...textStyle }; this.tickLabelStyle = { ...TICK_LABEL_STYLE, ...tick.tickLabelStyle }; this.tickLineStyle = { ...TICK_LINE_STYLE, ...tick.tickLineStyle }; this.currentMode = 'range'; // 初始信息 this.start = start; this.end = end; this.minText = minText; this.maxText = maxText; // 初始化 fontFamily,如果有浏览器,取 body 上的字体,防止文字更新时局部渲染造成的重影 this.fontFamily = typeof window !== 'undefined' ? window.getComputedStyle(document.body, null).getPropertyValue('font-family') || 'Arial, sans-serif' : 'Arial, sans-serif'; this.renderSlider(); } /** * 更新配置 * @param cfg */ public update(cfg: Partial<TrendTimeBarConfig>) { const { x, y, width, height, minText, maxText, start, end } = cfg; // start、end 只能是 0~1 范围 this.start = Math.min(1, Math.max(start, 0)); this.end = Math.min(1, Math.max(end, 0)); // 如果传了则更新,没有传则不更新 // @ts-ignore assign(this, { x, y, width, height, minText, maxText, }); // 更新 ui,不自动绘制 this.updateUI(); } public setText(minText: string, maxText: string) { this.minTextShape.attr('text', minText); this.maxTextShape.attr('text', maxText); } /** * 初始化组件结构 * @private */ private renderSlider() { const { width, height, timeBarType } = this; // 趋势图数据 if (timeBarType === 'trend' && size(get(this.trendCfg, 'data'))) { const trendComponent = new Trend({ x: this.x, y: this.y, width, height, ...this.trendCfg, group: this.group, }); this.trendComponent = trendComponent; } const sliderGroup = this.group.addGroup({ name: 'slider-group', }); // 1. 背景 sliderGroup.addShape('rect', { attrs: { x: 0, y: 0, width, height, ...this.backgroundStyle, }, name: 'background' }); const textGroup = this.group.addGroup(); // 2. 左右文字 if (timeBarType === 'trend') { this.minTextShape = textGroup.addShape('text', { attrs: { x: 0, y: height / 2 + this.y, textAlign: 'right', text: this.minText, silent: false, fontFamily: this.fontFamily || 'Arial, sans-serif', stroke: '#fff', lineWidth: 5, ...this.textStyle, }, capture: false, name: 'min-text-shape' }); this.maxTextShape = textGroup.addShape('text', { attrs: { y: height / 2 + this.y, textAlign: 'left', text: this.maxText, silent: false, fontFamily: this.fontFamily || 'Arial, sans-serif', stroke: '#fff', lineWidth: 5, ...this.textStyle, }, capture: false, name: 'max-text-shape' }); } else { this.minTextShape = textGroup.addShape('text', { attrs: { x: 0, y: this.y - 10, textAlign: 'center', text: this.minText, silent: false, fontFamily: this.fontFamily || 'Arial, sans-serif', stroke: '#fff', lineWidth: 5, ...this.textStyle, }, capture: false, name: 'min-text-shape' }); this.maxTextShape = textGroup.addShape('text', { attrs: { y: this.y - 10, textAlign: 'center', text: this.maxText, silent: false, fontFamily: this.fontFamily || 'Arial, sans-serif', stroke: '#fff', lineWidth: 5, ...this.textStyle, }, capture: false, name: 'max-text-shape' }); } // 3. 前景 选中背景框 this.foregroundShape = this.group.addGroup().addShape('rect', { attrs: { x: 0, y: this.y, height, ...this.foregroundStyle, }, name: 'foreground-shape' }); this.foregroundShape.on('mousedown', (e) => { e.target.attr('cursor', 'grabbing'); }); this.foregroundShape.on('mouseup', (e) => { e.target.attr('cursor', this.foregroundStyle.cursor || 'grab'); }); // 滑块相关的大小信息 const handlerWidth = get(this.handlerStyle, 'width', 2); const handlerHeight = get(this.handlerStyle, 'height', 24); const minHandleGroup = this.group.addGroup({ name: 'minHandlerShape', }); // 4. 左右滑块 this.minHandlerShape = new Handler({ name: 'minHandlerShape', group: minHandleGroup, type: timeBarType, x: this.x, y: this.y, width: handlerWidth, height: handlerHeight, style: this.handlerStyle, }); const maxHandleGroup = this.group.addGroup({ name: 'maxHandlerShape', }); this.maxHandlerShape = new Handler({ name: 'maxHandlerShape', group: maxHandleGroup, type: timeBarType, x: this.x, y: this.y, width: handlerWidth, height: handlerHeight, style: this.handlerStyle, }); // 缩略图下面的时间刻度 const tickData = this.ticks; const interval = width / (tickData.length - 1); this.tickPosList = []; if (this.textList && this.textList.length) { this.textList.forEach((text) => { text.destroy(); }); } let lastX = -Infinity; const rotate = this.tickLabelStyle.rotate; delete this.tickLabelStyle.rotate; this.textList = tickData.map((data, index) => { this.tickPosList.push(this.x + index * interval); let label; if (this.tickLabelFormatter) { label = this.tickLabelFormatter(data); if (!isString(label) && label) { // return true label = data.date; } } else { label = data.date; } // 文本刻度 const textX = this.x + index * interval, textY = this.y + height + 5; const text = this.group.addShape('text', { attrs: { x: textX, y: textY, text: label, fontFamily: this.fontFamily || 'Arial, sans-serif', ...this.tickLabelStyle }, name: 'tick-label' }); if (isNumber(rotate) && index !== tickData.length - 1) { const matrix = transform( [1, 0, 0, 0, 1, 0, 0, 0, 1], [ ['t', -textX!, -textY!], ['r', rotate], ['t', textX - 5, textY + 2], ], ); text.attr({ textAlign: 'left', matrix, }); } if (index === 0) { text.attr({ textAlign: 'left', }); } else if (index !== tickData.length - 1) { text.attr({ textAlign: 'right', }); } // 文本刻度上面的竖线 const line = this.group.addShape('line', { attrs: { x1: this.x + index * interval, y1: this.y + height + 2, x2: this.x + index * interval, y2: this.y + height + 6, ...this.tickLineStyle }, name: 'tick-line' }); line.toBack(); const bbox = text.getBBox(); // 抽样,标签与标签间距不小于 10 if (bbox.minX > lastX) { text.show(); line.show(); lastX = bbox.minX + bbox.width + 10; } else { text.hide(); line.hide(); } return text; }); // 渲染播放、快进和后退的控制按钮 this.controllerBtnGroup = new ControllerBtn({ group: this.group, x: this.x, y: this.y + height + 25, width, height: 35, ...this.controllerCfg, }); // 初始化 minText 和 maxText,方便计算它们的 bbox this.updateStartEnd(0); // 根据 start end 更新 ui 的位置信息 this.updateUI(); // 移动到对应的位置 sliderGroup.move(this.x, this.y); // 绑定事件鼠标事件 this.bindEvents(); } /** * 绑定事件: * - 点击 * - 滑动 * - 拖拽 * - 滚动 * @private */ private bindEvents() { // 1. 左滑块的滑动 const minHandleShapeGroup = this.group.find((group) => group.get('name') === 'minHandlerShape'); if (minHandleShapeGroup) { minHandleShapeGroup.on( 'minHandlerShape-handler:mousedown', this.onMouseDown(this.minHandlerShape), ); minHandleShapeGroup.on( 'minHandlerShape-handler:touchstart', this.onMouseDown(this.minHandlerShape), ); } const maxHandleShapeGroup = this.group.find((group) => group.get('name') === 'maxHandlerShape'); // 2. 右滑块的滑动 if (maxHandleShapeGroup) { maxHandleShapeGroup.on( 'maxHandlerShape-handler:mousedown', this.onMouseDown(this.maxHandlerShape), ); maxHandleShapeGroup.on( 'maxHandlerShape-handler:touchstart', this.onMouseDown(this.maxHandlerShape), ); } // 3. 前景选中区域 this.foregroundShape.on('mousedown', this.onMouseDown(this.foregroundShape)); this.foregroundShape.on('touchstart', this.onMouseDown(this.foregroundShape)); // 播放区按钮控制 /** 播放/暂停事件 */ this.group.on(`${PLAY_PAUSE_BTN}:click`, () => { this.isPlay = !this.isPlay; this.currentHandler = this.maxHandlerShape; this.changePlayStatus(); }); // 处理前进一步的事件 this.group.on(`${NEXT_STEP_BTN}:click`, () => { this.currentHandler = this.maxHandlerShape; this.updateStartEnd(0.01); this.updateUI(); }); // 处理后退一步的事件 this.group.on(`${PRE_STEP_BTN}:click`, () => { this.currentHandler = this.maxHandlerShape; this.updateStartEnd(-0.01); this.updateUI(); }); this.group.on(TIMEBAR_CONFIG_CHANGE, ({ type, speed }) => { this.currentSpeed = speed; this.currentMode = type; if (type === 'single') { this.minHandlerShape.hide(); this.foregroundShape.hide(); this.minTextShape.hide(); } else if (type === 'range') { this.minHandlerShape.show(); this.foregroundShape.show(); this.minTextShape.show(); } }); } private onMouseDown = (handler: Handler | IShape) => (e: Event) => { // 1. 记录点击的滑块 this.currentHandler = handler; const event = e.originalEvent as MouseEvent; // 2. 存储当前点击位置 event.stopPropagation(); event.preventDefault(); // 兼容移动端获取数据 this.prevX = get(event, 'touches.0.pageX', event.pageX); // 3. 开始滑动的时候,绑定 move 和 up 事件 const containerDOM = this.canvas.get('container'); containerDOM.addEventListener('mousemove', this.onMouseMove); containerDOM.addEventListener('mouseup', this.onMouseUp); containerDOM.addEventListener('mouseleave', this.onMouseUp); // 移动端事件 containerDOM.addEventListener('touchmove', this.onMouseMove); containerDOM.addEventListener('touchend', this.onMouseUp); containerDOM.addEventListener('touchcancel', this.onMouseUp); }; private onMouseMove = (e: MouseEvent) => { // 滑动过程中,计算偏移,更新滑块,然后 emit 数据出去 e.stopPropagation(); e.preventDefault(); const x = get(e, 'touches.0.pageX', e.pageX); // 横向的 slider 只处理 x const offsetX = x - this.prevX; const offsetXRange = this.adjustOffsetRange(offsetX / this.width); // 更新 start end range 范围 this.updateStartEnd(offsetXRange); // 更新 ui this.updateUI(); this.prevX = x; }; private onMouseUp = () => { // 结束之后,取消绑定的事件 if (this.currentHandler) { this.currentHandler = undefined; } const containerDOM = this.canvas.get('container'); if (containerDOM) { containerDOM.removeEventListener('mousemove', this.onMouseMove); containerDOM.removeEventListener('mouseup', this.onMouseUp); // 防止滑动到 canvas 外部之后,状态丢失 containerDOM.removeEventListener('mouseleave', this.onMouseUp); // 移动端事件 containerDOM.removeEventListener('touchmove', this.onMouseMove); containerDOM.removeEventListener('touchend', this.onMouseUp); containerDOM.removeEventListener('touchcancel', this.onMouseUp); } }; /** 输入当前圆点位置,输出离哪个 tick 的位置最近 */ private adjustTickIndex(timeSelectX: number) { for (let i = 0; i < this.tickPosList.length - 1; i++) { if (this.tickPosList[i] <= timeSelectX && timeSelectX <= this.tickPosList[i + 1]) { return Math.abs(this.tickPosList[i] - timeSelectX) < Math.abs(timeSelectX - this.tickPosList[i + 1]) ? i : i + 1; } } return 0; } /** * 调整 offsetRange,因为一些范围的限制 * @param offsetRange */ private adjustOffsetRange(offsetRange: number): number { // 针对不同的滑动组件,处理的方式不同 switch (this.currentHandler) { case this.minHandlerShape: { const min = 0 - this.start; const max = 1 - this.start; return Math.min(max, Math.max(min, offsetRange)); } case this.maxHandlerShape: { const min = 0 - this.end; const max = 1 - this.end; return Math.min(max, Math.max(min, offsetRange)); } case this.foregroundShape: { const min = 0 - this.start; const max = 1 - this.end; return Math.min(max, Math.max(min, offsetRange)); } default: return 0; } } /** * 更新起始、结束的控制块位置、文本、范围值(原始值) * @param offsetRange */ private updateStartEnd(offsetRange: number) { const minData = this.ticks[this.adjustTickIndex(this.start * this.width)]; const maxData = this.ticks[this.adjustTickIndex(this.end * this.width)]; if (!this.currentHandler) { this.minText = this.tickLabelFormatter ? this.tickLabelFormatter(minData) : minData?.date; this.maxText = this.tickLabelFormatter ? this.tickLabelFormatter(maxData) : maxData?.date; return; } // 操作不同的组件,反馈不一样 switch (this.currentHandler) { case this.minHandlerShape: // 拖动最小滑块时使用当前最大值设置最大值的文本,以便恢复到默认值 this.maxText = this.maxTextShape.attr('text'); this.start += offsetRange; this.minText = this.tickLabelFormatter ? this.tickLabelFormatter(minData) : minData.date; break; case this.maxHandlerShape: // 拖动最大滑块时使用当前最小值设置最小值的文本,以便恢复到默认值 this.minText = this.minTextShape.attr('text'); this.end += offsetRange; this.maxText = this.tickLabelFormatter ? this.tickLabelFormatter(maxData) : maxData.date; break; case this.foregroundShape: this.start += offsetRange; this.end += offsetRange; this.minText = this.tickLabelFormatter ? this.tickLabelFormatter(minData) : minData.date; this.maxText = this.tickLabelFormatter ? this.tickLabelFormatter(maxData) : maxData.date; break; default: break; } } /** * 根据移动的比例来更新 ui,更新范围(0-1 范围的比例值) * @private */ private updateUI() { if (this.start < 0) { this.start = 0; } if (this.end > 1) { this.end = 1; } const min = this.x + this.start * this.width; const max = this.x + this.end * this.width; // 1. foreground this.foregroundShape.attr('x', min); this.foregroundShape.attr('width', max - min); // 滑块相关的大小信息 const handlerWidth = get(this.handlerStyle, 'width', DEFAULT_HANDLER_WIDTH); // 设置文本 this.setText(this.minText, this.maxText); const [minAttrs, maxAttrs] = this.dodgeText([min, max]); // 2. 左侧滑块和文字位置 this.minHandlerShape.setX(min - handlerWidth / 2); each(minAttrs, (v, k) => this.minTextShape.attr(k, v)); // 3. 右侧滑块和文字位置 this.maxHandlerShape.setX(max - handlerWidth / 2); each(maxAttrs, (v, k) => this.maxTextShape.attr(k, v)); if (this.currentMode === 'range') { // 因为存储的 start、end 可能不一定是按大小存储的,所以排序一下,对外是 end >= start this.graph.emit(VALUE_CHANGE, { value: [this.start, this.end].sort() }); } else if (this.currentMode === 'single') { this.graph.emit(VALUE_CHANGE, { value: [this.end, this.end] }); } } /** * 调整 text 的位置,自动躲避 * 根据位置,调整返回新的位置 * @param range */ private dodgeText(range: [number, number]): [object, object] { const TEXTPADDING = 2; const handlerWidth = get(this.handlerStyle, 'width', DEFAULT_HANDLER_WIDTH); let minTextShape = this.minTextShape; let maxTextShape = this.maxTextShape; let [min, max] = range; let sorted = false; // 如果交换了位置,则对应的 min max 也交换 if (min > max) { [min, max] = [max, min]; [minTextShape, maxTextShape] = [maxTextShape, minTextShape]; sorted = true; } // 避让规则,优先显示在两侧,只有显示不下的时候,才显示在中间 const minBBox = minTextShape.getBBox(); const maxBBox = maxTextShape.getBBox(); let minAttrs = null; let maxAttrs = null; if (this.timeBarType === 'trend') { minAttrs = min - minBBox.width < this.x + TEXTPADDING ? { x: min + handlerWidth / 2 + TEXTPADDING, textAlign: 'left' } : { x: min - handlerWidth / 2 - TEXTPADDING, textAlign: 'right' }; maxAttrs = max + maxBBox.width > this.x + this.width ? { x: max - handlerWidth / 2 - TEXTPADDING, textAlign: 'right' } : { x: max + handlerWidth / 2 + TEXTPADDING, textAlign: 'left' }; } else if (this.timeBarType === 'simple') { minAttrs = minTextShape.attr('x') > minBBox.width // 左边滑块文本位置小于其宽度代表文字超过左边届 ? { x: min, textAlign: 'center' } : { x: min, textAlign: 'left' }; maxAttrs = maxTextShape.attr('x') > this.width - maxBBox.width // 有边滑块文本位置大于宽度代表文字超过右边界 ? { x: max, textAlign: 'right' } : { x: max, textAlign: 'center' }; } return !sorted ? [minAttrs, maxAttrs] : [maxAttrs, minAttrs]; } private startPlay() { return typeof window !== 'undefined' ? window.requestAnimationFrame(() => { const { ticks, width } = this; const speed = this.currentSpeed; const tickInterval = width / ticks.length; const offsetX = tickInterval / (((10 - speed) * 1000) / 60); const offsetXRange = this.adjustOffsetRange(offsetX / this.width); this.updateStartEnd(offsetXRange); this.updateUI(); if (this.isPlay) { this.playHandler = this.startPlay(); } }) : undefined; } private changePlayStatus(isSync = true) { this.controllerBtnGroup.playButton.update({ isPlay: this.isPlay, }); if (this.isPlay) { // 开始播放 this.playHandler = this.startPlay(); this.graph.emit(TIMELINE_START, null); } else { // 结束播放 if (this.playHandler) { if (typeof window !== 'undefined') window.cancelAnimationFrame(this.playHandler); if (isSync) { this.graph.emit(TIMELINE_END, null); } } } } public destory() { this.graph.off(VALUE_CHANGE, () => { /* do nothing */}); const group = this.group; const minHandleShapeGroup = group.find((g) => g.get('name') === 'minHandlerShape'); if (minHandleShapeGroup) { minHandleShapeGroup.off('minHandlerShape-handler:mousedown'); minHandleShapeGroup.off('minHandlerShape-handler:touchstart'); minHandleShapeGroup.destroy(); } const maxHandleShapeGroup = group.find((g) => g.get('name') === 'maxHandlerShape'); // 2. 右滑块的滑动 if (maxHandleShapeGroup) { maxHandleShapeGroup.off('maxHandlerShape-handler:mousedown'); maxHandleShapeGroup.off('maxHandlerShape-handler:touchstart'); maxHandleShapeGroup.destroy(); } // 3. 前景选中区域 this.foregroundShape.off('mousedown'); this.foregroundShape.off('touchstart'); this.foregroundShape.destroy(); group.off(`${PLAY_PAUSE_BTN}:click`); group.off(`${NEXT_STEP_BTN}:click`); group.off(`${PRE_STEP_BTN}:click`); group.off(TIMEBAR_CONFIG_CHANGE); group.destroy(); if (this.trendComponent) { this.trendComponent.destory(); } } }
the_stack
import Page = require('../../../base/Page'); import Response = require('../../../http/response'); import V1 = require('../V1'); import { SerializableClass } from '../../../interfaces'; /** * Initialize the SourceIpMappingList * * @param version - Version of the resource */ declare function SourceIpMappingList(version: V1): SourceIpMappingListInstance; /** * Options to pass to update * * @property sipDomainSid - The unique string that identifies a SIP Domain */ interface SourceIpMappingInstanceUpdateOptions { sipDomainSid: string; } interface SourceIpMappingListInstance { /** * @param sid - sid of instance */ (sid: string): SourceIpMappingContext; /** * create a SourceIpMappingInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ create(opts: SourceIpMappingListInstanceCreateOptions, callback?: (error: Error | null, item: SourceIpMappingInstance) => any): Promise<SourceIpMappingInstance>; /** * Streams SourceIpMappingInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Function to process each record */ each(callback?: (item: SourceIpMappingInstance, done: (err?: Error) => void) => void): void; /** * Streams SourceIpMappingInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Function to process each record */ each(opts?: SourceIpMappingListInstanceEachOptions, callback?: (item: SourceIpMappingInstance, done: (err?: Error) => void) => void): void; /** * Constructs a source_ip_mapping * * @param sid - The unique string that identifies the resource */ get(sid: string): SourceIpMappingContext; /** * Retrieve a single target page of SourceIpMappingInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ getPage(callback?: (error: Error | null, items: SourceIpMappingPage) => any): Promise<SourceIpMappingPage>; /** * Retrieve a single target page of SourceIpMappingInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param targetUrl - API-generated URL for the requested results page * @param callback - Callback to handle list of records */ getPage(targetUrl?: string, callback?: (error: Error | null, items: SourceIpMappingPage) => any): Promise<SourceIpMappingPage>; /** * Lists SourceIpMappingInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ list(callback?: (error: Error | null, items: SourceIpMappingInstance[]) => any): Promise<SourceIpMappingInstance[]>; /** * Lists SourceIpMappingInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ list(opts?: SourceIpMappingListInstanceOptions, callback?: (error: Error | null, items: SourceIpMappingInstance[]) => any): Promise<SourceIpMappingInstance[]>; /** * Retrieve a single page of SourceIpMappingInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ page(callback?: (error: Error | null, items: SourceIpMappingPage) => any): Promise<SourceIpMappingPage>; /** * Retrieve a single page of SourceIpMappingInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ page(opts?: SourceIpMappingListInstancePageOptions, callback?: (error: Error | null, items: SourceIpMappingPage) => any): Promise<SourceIpMappingPage>; /** * Provide a user-friendly representation */ toJSON(): any; } /** * Options to pass to create * * @property ipRecordSid - The unique string that identifies an IP Record * @property sipDomainSid - The unique string that identifies a SIP Domain */ interface SourceIpMappingListInstanceCreateOptions { ipRecordSid: string; sipDomainSid: string; } /** * Options to pass to each * * @property callback - * Function to process each record. If this and a positional * callback are passed, this one will be used * @property done - Function to be called upon completion of streaming * @property limit - * Upper limit for the number of records to return. * each() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no pageSize is defined but a limit is defined, * each() will attempt to read the limit with the most efficient * page size, i.e. min(limit, 1000) */ interface SourceIpMappingListInstanceEachOptions { callback?: (item: SourceIpMappingInstance, done: (err?: Error) => void) => void; done?: Function; limit?: number; pageSize?: number; } /** * Options to pass to list * * @property limit - * Upper limit for the number of records to return. * list() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no page_size is defined but a limit is defined, * list() will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) */ interface SourceIpMappingListInstanceOptions { limit?: number; pageSize?: number; } /** * Options to pass to page * * @property pageNumber - Page Number, this value is simply for client state * @property pageSize - Number of records to return, defaults to 50 * @property pageToken - PageToken provided by the API */ interface SourceIpMappingListInstancePageOptions { pageNumber?: number; pageSize?: number; pageToken?: string; } interface SourceIpMappingPayload extends SourceIpMappingResource, Page.TwilioResponsePayload { } interface SourceIpMappingResource { date_created: Date; date_updated: Date; ip_record_sid: string; sid: string; sip_domain_sid: string; url: string; } interface SourceIpMappingSolution { } declare class SourceIpMappingContext { /** * Initialize the SourceIpMappingContext * * @param version - Version of the resource * @param sid - The unique string that identifies the resource */ constructor(version: V1, sid: string); /** * fetch a SourceIpMappingInstance * * @param callback - Callback to handle processed record */ fetch(callback?: (error: Error | null, items: SourceIpMappingInstance) => any): Promise<SourceIpMappingInstance>; /** * remove a SourceIpMappingInstance * * @param callback - Callback to handle processed record */ remove(callback?: (error: Error | null, items: SourceIpMappingInstance) => any): Promise<boolean>; /** * Provide a user-friendly representation */ toJSON(): any; /** * update a SourceIpMappingInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ update(opts: SourceIpMappingInstanceUpdateOptions, callback?: (error: Error | null, items: SourceIpMappingInstance) => any): Promise<SourceIpMappingInstance>; } declare class SourceIpMappingInstance extends SerializableClass { /** * Initialize the SourceIpMappingContext * * @param version - Version of the resource * @param payload - The instance payload * @param sid - The unique string that identifies the resource */ constructor(version: V1, payload: SourceIpMappingPayload, sid: string); private _proxy: SourceIpMappingContext; dateCreated: Date; dateUpdated: Date; /** * fetch a SourceIpMappingInstance * * @param callback - Callback to handle processed record */ fetch(callback?: (error: Error | null, items: SourceIpMappingInstance) => any): Promise<SourceIpMappingInstance>; ipRecordSid: string; /** * remove a SourceIpMappingInstance * * @param callback - Callback to handle processed record */ remove(callback?: (error: Error | null, items: SourceIpMappingInstance) => any): Promise<boolean>; sid: string; sipDomainSid: string; /** * Provide a user-friendly representation */ toJSON(): any; /** * update a SourceIpMappingInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ update(opts: SourceIpMappingInstanceUpdateOptions, callback?: (error: Error | null, items: SourceIpMappingInstance) => any): Promise<SourceIpMappingInstance>; url: string; } declare class SourceIpMappingPage extends Page<V1, SourceIpMappingPayload, SourceIpMappingResource, SourceIpMappingInstance> { /** * Initialize the SourceIpMappingPage * * @param version - Version of the resource * @param response - Response from the API * @param solution - Path solution */ constructor(version: V1, response: Response<string>, solution: SourceIpMappingSolution); /** * Build an instance of SourceIpMappingInstance * * @param payload - Payload response from the API */ getInstance(payload: SourceIpMappingPayload): SourceIpMappingInstance; /** * Provide a user-friendly representation */ toJSON(): any; } export { SourceIpMappingContext, SourceIpMappingInstance, SourceIpMappingInstanceUpdateOptions, SourceIpMappingList, SourceIpMappingListInstance, SourceIpMappingListInstanceCreateOptions, SourceIpMappingListInstanceEachOptions, SourceIpMappingListInstanceOptions, SourceIpMappingListInstancePageOptions, SourceIpMappingPage, SourceIpMappingPayload, SourceIpMappingResource, SourceIpMappingSolution }
the_stack
import * as path from 'path'; import * as express from 'express'; import { expect } from 'chai'; import * as request from 'supertest'; import { createApp } from './common/app'; import { OpenApiValidatorOpts, ValidateSecurityOpts, OpenAPIV3, } from '../src/framework/types'; // NOTE/TODO: These tests modify eovConf.validateSecurity.handlers // Thus test execution order matters :-( describe('security.handlers', () => { let app = null; let basePath = null; const eovConf: OpenApiValidatorOpts = { apiSpec: path.join('test', 'resources', 'security.yaml'), validateSecurity: { handlers: { ApiKeyAuth: (req, scopes, schema) => { throw Error('custom api key handler failed'); }, }, }, }; before(async () => { // Set up the express app app = await createApp(eovConf, 3005); basePath = app.basePath; app.use( `${basePath}`, express .Router() .get(`/api_key`, (req, res) => res.json({ logged_in: true })) .get(`/bearer`, (req, res) => res.json({ logged_in: true })) .get(`/basic`, (req, res) => res.json({ logged_in: true })) .get(`/cookie_auth`, (req, res) => res.json({ logged_in: true })) .get(`/oauth2`, (req, res) => res.json({ logged_in: true })) .get(`/openid`, (req, res) => res.json({ logged_in: true })) .get(`/api_key_or_anonymous`, (req, res) => res.json({ logged_in: true }), ) .get('/no_security', (req, res) => res.json({ logged_in: true })), ); }); after(() => { app.server.close(); }); it('should return 200 if no security', async () => request(app).get(`${basePath}/no_security`).expect(200)); it('should return 401 if apikey handler throws exception', async () => request(app) .get(`${basePath}/api_key`) .set('X-API-Key', 'test') .expect(401) .then((r) => { const body = r.body; expect(body.errors).to.be.an('array'); expect(body.errors).to.have.length(1); expect(body.errors[0].message).to.equals( 'custom api key handler failed', ); })); it('should return 401 if apikey handler returns false', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.ApiKeyAuth = <any>function (req, scopes, schema) { expect(scopes).to.be.an('array').with.length(0); return false; }; return request(app) .get(`${basePath}/api_key`) .set('X-API-Key', 'test') .expect(401) .then((r) => { const body = r.body; expect(body.errors).to.be.an('array'); expect(body.errors).to.have.length(1); expect(body.errors[0].message).to.equals('unauthorized'); }); }); it('should return 401 if apikey handler returns Promise with false', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.ApiKeyAuth = <any>function (req, scopes, schema) { expect(scopes).to.be.an('array').with.length(0); return Promise.resolve(false); }; return request(app) .get(`${basePath}/api_key`) .set('X-API-Key', 'test') .expect(401) .then((r) => { const body = r.body; expect(body.errors).to.be.an('array'); expect(body.errors).to.have.length(1); expect(body.errors[0].message).to.equals('unauthorized'); }); }); it('should return 401 if cookie auth handler returns Promise with false', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.CookieAuth = <any>function (req, scopes, schema) { expect(scopes).to.be.an('array').with.length(0); return Promise.resolve(false); }; return request(app) .get(`${basePath}/cookie_auth`) .set('Cookie', ['JSESSIONID=12345667', 'myApp-other=blah']) .expect(401) .then((r) => { const body = r.body; expect(body.errors).to.be.an('array'); expect(body.errors).to.have.length(1); expect(body.errors[0].message).to.equals('unauthorized'); }); }); it('should return 401 if apikey handler returns Promise reject with custom message', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.ApiKeyAuth = (req, scopes, schema) => { expect(scopes).to.be.an('array').with.length(0); return Promise.reject(new Error('rejected promise')); }; return request(app) .get(`${basePath}/api_key`) .set('X-API-Key', 'test') .expect(401) .then((r) => { const body = r.body; expect(body.errors).to.be.an('array'); expect(body.errors).to.have.length(1); expect(body.errors[0].message).to.equals('rejected promise'); }); }); it('should return 401 if apikey header is missing', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.ApiKeyAuth = (req, scopes, schema) => true; return request(app) .get(`${basePath}/api_key`) .expect(401) .then((r) => { const body = r.body; expect(body.errors).to.be.an('array'); expect(body.errors).to.have.length(1); expect(body.errors[0].message).to.include('X-API-Key'); }); }); it('should return 200 if apikey header exists and handler returns true', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.ApiKeyAuth = function ( req, scopes, schema: OpenAPIV3.ApiKeySecurityScheme, ) { expect(schema.type).to.equal('apiKey'); expect(schema.in).to.equal('header'); expect(schema.name).to.equal('X-API-Key'); expect(scopes).to.be.an('array').with.length(0); return true; }; return request(app) .get(`${basePath}/api_key`) .set('X-API-Key', 'test') .expect(200); }); it('should return 404 if apikey header exists and handler returns true but path doesnt exist', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.ApiKeyAuth = ( req, scopes, schema: OpenAPIV3.ApiKeySecurityScheme, ) => { expect(schema.type).to.equal('apiKey'); expect(schema.in).to.equal('header'); expect(schema.name).to.equal('X-API-Key'); expect(scopes).to.be.an('array').with.length(0); return true; }; return request(app) .get(`${basePath}/api_key_but_invalid_path`) .set('X-API-Key', 'test') .expect(404); }); it('should return 401 if auth header is missing for basic auth', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.BasicAuth = (req, scopes, schema) => true; return request(app) .get(`${basePath}/basic`) .expect(401) .then((r) => { const body = r.body; expect(body.errors).to.be.an('array'); expect(body.errors).to.have.length(1); expect(body.errors[0].message).to.include('Authorization'); }); }); it('should return 401 if auth header has malformed basic auth', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.BasicAuth = (req, scopes, schema) => true; return request(app) .get(`${basePath}/basic`) .set('Authorization', 'XXXX') .expect(401) .then((r) => { const body = r.body; expect(body.errors).to.be.an('array'); expect(body.errors).to.have.length(1); expect(body.errors[0].message).to.include( "Authorization header with scheme 'Basic' required", ); }); }); it('should return 401 if auth header is missing for bearer auth', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.BearerAuth = (req, scopes, schema) => true; return request(app) .get(`${basePath}/bearer`) .expect(401) .then((r) => { const body = r.body; expect(body.errors).to.be.an('array'); expect(body.errors).to.have.length(1); expect(body.errors[0].message).to.include('Authorization'); }); }); it('should return 401 if auth header has malformed bearer auth', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.BearerAuth = (req, scopes, schema) => true; return request(app) .get(`${basePath}/bearer`) .set('Authorization', 'XXXX') .expect(401) .then((r) => { const body = r.body; expect(body.errors).to.be.an('array'); expect(body.errors).to.have.length(1); expect(body.errors[0].message).to.include( "Authorization header with scheme 'Bearer' required", ); }); }); it('should return 200 if bearer auth succeeds', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.BearerAuth = ( req, scopes, schema: OpenAPIV3.HttpSecurityScheme, ) => { expect(schema.type).to.equal('http'); expect(schema.scheme).to.equal('bearer'); expect(scopes).to.be.an('array').with.length(0); return true; }; return request(app) .get(`${basePath}/bearer`) .set('Authorization', 'Bearer XXXX') .expect(200); }); it('should return 200 if oauth2 auth succeeds', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.OAuth2 = function ( req, scopes, schema: OpenAPIV3.OAuth2SecurityScheme, ) { expect(schema.type).to.equal('oauth2'); expect(schema).to.have.property('flows'); expect(scopes).to.be.an('array').with.length(2); return true; }; return request(app).get(`${basePath}/oauth2`).expect(200); }); it('should return 403 if oauth2 handler throws 403', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.OAuth2 = function ( req, scopes: string[], schema: OpenAPIV3.OAuth2SecurityScheme, ) { expect(schema.type).to.equal('oauth2'); expect(schema).to.have.property('flows'); expect(scopes).to.be.an('array').with.length(2); throw { status: 403, message: 'forbidden' }; }; return request(app) .get(`${basePath}/oauth2`) .expect(403) .then((r) => { const body = r.body; expect(r.body.message).to.equal('forbidden'); }); }); it('should return 200 if openid auth succeeds', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.OpenID = ( req, scopes, schema: OpenAPIV3.OpenIdSecurityScheme, ) => { expect(schema.type).to.equal('openIdConnect'); expect(schema).to.have.property('openIdConnectUrl'); expect(scopes).to.be.an('array').with.length(2); return true; }; return request(app).get(`${basePath}/openid`).expect(200); }); it('should return 500 if security handlers are defined, but not for all securities', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; delete validateSecurity.handlers.OpenID; validateSecurity.handlers.Test = ( req, scopes, schema: OpenAPIV3.OpenIdSecurityScheme, ) => { expect(schema.type).to.equal('openIdConnect'); expect(schema).to.have.property('openIdConnectUrl'); expect(scopes).to.be.an('array').with.length(2); return true; }; return request(app) .get(`${basePath}/openid`) .expect(500) .then((r) => { const body = r.body; const msg = "a security handler for 'OpenID' does not exist"; expect(body.message).to.equal(msg); expect(body.errors[0].message).to.equal(msg); expect(body.errors[0].path).to.equal(`${basePath}/openid`); }); }); it('should return 200 if api_key or anonymous and no api key is supplied', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.ApiKeyAuth = <any>((req, scopes, schema) => true); return request(app).get(`${basePath}/api_key_or_anonymous`).expect(200); }); it('should return 200 if api_key or anonymous and api key is supplied', async () => { const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity; validateSecurity.handlers.ApiKeyAuth = <any>((req, scopes, schema) => true); return request(app) .get(`${basePath}/api_key_or_anonymous`) .set('x-api-key', 'XXX') .expect(200); }); }); describe('when securities declare: (apikey && bearer) || basic', () => { let app = null; let basePath = null; const eovConf: OpenApiValidatorOpts = { apiSpec: path.join('test', 'resources', 'security.yaml'), }; before(async () => { app = await createApp(eovConf, 3005); basePath = app.basePath; app.use( `${basePath}`, express .Router() .get('/apikey_and_bearer_or_basic', (req, res) => res.json({ logged_in: true }), ), ); }); after(() => { app.server.close(); }); it('should return 401 if not X-Api-Key is missing', async () => request(app) .get(`${basePath}/apikey_and_bearer_or_basic`) .set('Authorization', 'Bearer XXXX') // Bearer .expect(401) .then((r) => { const body = r.body; expect(body.errors).to.be.an('array'); expect(body.errors).to.have.length(1); expect(body.message).to.include("'X-API-Key' header required"); })); it('should return 401 if Bearer token is missing', async () => { eovConf.validateSecurity = true; return request(app) .get(`${basePath}/apikey_and_bearer_or_basic`) .set('X-Api-Key', 'XXX') // api key .expect(401) .then((r) => { const body = r.body; expect(body.errors).to.be.an('array'); expect(body.errors).to.have.length(1); expect(body.message).to.include('Authorization header required'); }); }); it('should return 200 when X-Api-Key and Bearer token are present', async () => { eovConf.validateSecurity = true; return request(app) .get(`${basePath}/apikey_and_bearer_or_basic`) .set('Authorization', 'Bearer XXXX') // Bearer .set('X-Api-Key', 'XXX') // api key .expect(200); }); it('should return 200 when Basic auth is present', async () => { eovConf.validateSecurity = true; return request(app) .get(`${basePath}/apikey_and_bearer_or_basic`) .set('Authorization', 'Basic XXXX') .expect(200); }); });
the_stack
import test from 'ava' import mocker, { Mocker } from '../../' test('Should return an new instance of mocker', async (t) => { t.deepEqual(mocker(), new Mocker()) }) test('Should iterate root level too with fields in models', async (t) => { let length = 1 let expectedResult = { user: ['firstName'] } let user = { static: 'firstName' } let db = await mocker().schema('user', user, length).build() t.deepEqual(db, expectedResult) }) test('Virtuals should be eliminated in the final object and can be accesible during generation', async (t) => { let model = { exampleVirtual: { incrementalId: 0, virtual: true }, id: { function: function () { return this.object.exampleVirtual } }, deep: { more: { field: { static: 'im here', virtual: true } } }, deep2: { more: { field: { static: 'im here' } } } } let expectedResult = { id: 0, deep2: { more: { field: 'im here' } } } let db = await mocker().schema('situation', model, 1).build() t.deepEqual(db.situation[0], expectedResult) }) test('Should iterate over more complex levels (deeper & function used...)', async (t) => { let model = { name: { firstName: { static: 'firstName' }, lastName: { static: 'lastName' }, much: { deeper: { function: function () { return ( this.object.name.firstName + ' ' + this.object.name.lastName ) } }, more: { deeper: { function: function () { return ( this.object.name.firstName + ' ' + this.object.name.lastName ) } }, level: { deeper: { function: function () { return ( this.object.name.firstName + ' ' + this.object.name.lastName ) } }, awesome: { deeper: { function: function () { return ( this.object.name.firstName + ' ' + this.object.name.lastName ) } }, deeper2: { function: function () { return ( this.object.name.firstName + ' ' + this.object.name.lastName ) } } } } } } } } let expectedResult = { name: { firstName: 'firstName', lastName: 'lastName', much: { deeper: 'firstName lastName', more: { deeper: 'firstName lastName', level: { deeper: 'firstName lastName', awesome: { deeper: 'firstName lastName', deeper2: 'firstName lastName' } } } } } } let db = await mocker().schema('situation', model, 1).build() t.deepEqual(db.situation[0], expectedResult) }) test('Should work with conditional keys', async (t) => { let conditional = { condition: { static: 'a' }, 'object.condition==="a",a': { static: 'conditionLinkedToA' }, 'object.condition==="b",b': { static: 'conditionLinkedToB' } } let expectedResult = { condition: 'a', a: 'conditionLinkedToA' } let db = await mocker().schema('situation', conditional, 1).build() t.deepEqual(db.situation[0], expectedResult) }) test('Should work with conditional keys II', async (t) => { let conditional = { condition: { faker: 'helpers.randomize(["email", "user"])' }, 'object.condition==="email",show': { static: 'email' }, 'object.condition==="user",show': { static: 'user' }, 'object.condition==="email",email': { hasOne: 'emails' }, 'object.condition==="user",user': { hasOne: 'users' } } let user = { faker: 'name.findName' } let email = { faker: 'internet.email' } let db = await mocker() .schema('users', user, 2) .schema('emails', email, 2) .schema('situation', conditional, 3) .build() t.true(true) // t.deepEqual(db.situation[0], expectedResult) }) test('Should not affect init values to next entity', async (t) => { let length = 10 let request = { type: { values: ['kitty', 'pitxi', 'txuri'] } } let request2 = { type: { static: 'staticValue' } } let db = await mocker() .schema('request', request, { uniqueField: 'type' }) .schema('request2', request2, 10) .build() t.notDeepEqual(db.request, db.request2) db.request2.forEach((r2) => { db.request.forEach((r) => { t.notDeepEqual(r2, r) }) }) }) test('Should generate more entities', async (t) => { let length = 10 let model1 = { request: { id: { faker: 'random.number' }, title: { faker: 'lorem.sentence' }, number: { faker: 'random.number' } } } let model2 = { request: { id: { faker: 'random.number' }, title: { faker: 'lorem.sentence' }, number: { faker: 'random.number' } } } let data = await mocker() .schema('act', model1, length) .schema('act2', model2, length) .build() t.true(Object.keys(data).length === 2) t.deepEqual(Object.keys(data), Array('act', 'act2')) t.true(data.act.length === length) t.true(data.act2.length === length) data.act.forEach((d) => { t.true(Object.keys(d).length === Object.keys(model1).length) t.deepEqual(Object.keys(d), Object.keys(model1)) t.deepEqual(Object.keys(d.request), Object.keys(model1.request)) }) data.act2.forEach((d) => { t.true(Object.keys(d).length === Object.keys(model2).length) t.deepEqual(Object.keys(d), Object.keys(model2)) t.deepEqual(Object.keys(d.request), Object.keys(model2.request)) }) }) test('Should uniqueField works', async (t) => { let cat = { name: ['txuri', 'pitxi', 'kitty'] } let cat2 = { name: ['txuri', 'pitxi', 'kitty'] } let result = [{ name: 'txuri' }, { name: 'pitxi' }, { name: 'kitty' }] let data = await mocker() .schema('cat', cat, { uniqueField: 'name' }) .schema('cat2', cat2, { uniqueField: 'name' }) .build() t.deepEqual(data.cat, data.cat2) t.deepEqual(data.cat, result) t.deepEqual(data.cat2, result) }) test('Should max works', async (t) => { let cat = { name: { values: ['txuri', 'pitxi', 'kitty'] } } let data = await mocker() .schema('cat', cat, { max: 10 }) .schema('cat2', cat, { max: 40 }) .build() t.true(data.cat.length <= 10) t.true(data.cat2.length <= 40) }) /* test('Should max and min works', async t => { let cat = { name: ['txuri', 'pitxi', 'kitty'] } let data = await mocker() .schema('cat', cat, { min: 5, max: 10 }) .schema('cat2', cat, { min: 10, max: 40 }) .build() t.true(data.cat.length <= 10) t.true(data.cat.length >= 5) t.true(data.cat2.length <= 40) t.true(data.cat2.length >= 10) }) test('Should generate correctly with 2 ways of uniqueField', function(done) { var cat = { name: ['txuri', 'pitxi', 'kitty'] }; var cat2 = { name: { values: ['txuri', 'pitxi', 'kitty'] } }; var result = [ { name: 'txuri' }, { name: 'pitxi' }, { name: 'kitty' } ] var m = mocker() .schema('cat', cat, {uniqueField: 'name'}) .schema('cat2', cat2, {uniqueField: 'name'}) .build(function(data){ try { expect(data.cat) .to.deep.equal(data.cat2) .to.deep.equal(result) .to.not.be.undefined .to.not.be.null done() } catch (x) { done(x) } }) })*/ test('Should be awesome', async (t) => { t.true(true) })
the_stack
import { AssertError } from '../errors/internal-error'; import { ComponentItem } from '../items/component-item'; import { LayoutManager } from '../layout-manager'; import { DomConstants } from '../utils/dom-constants'; import { DragListener } from '../utils/drag-listener'; import { numberToPixels, pixelsToNumber } from '../utils/utils'; import { Tab } from './tab'; /** @internal */ export class TabsContainer { // There is one tab per ComponentItem in stack. However they may not be ordered the same private readonly _tabs: Tab[] = []; private readonly _dropdownElement: HTMLElement; private readonly _element: HTMLElement; private _lastVisibleTabIndex = -1; private _dropdownActive = false; get tabs(): Tab[] { return this._tabs; } get tabCount(): number { return this._tabs.length; } get lastVisibleTabIndex(): number { return this._lastVisibleTabIndex; } get element(): HTMLElement { return this._element; } get dropdownElement(): HTMLElement { return this._dropdownElement; } get dropdownActive(): boolean { return this._dropdownActive; } constructor(private _layoutManager: LayoutManager, private _componentRemoveEvent: TabsContainer.ComponentItemRemoveEvent, private _componentFocusEvent: TabsContainer.ComponentItemFocusEvent, private _componentDragStartEvent: TabsContainer.ComponentItemDragStartEvent, private _dropdownActiveChangedEvent: TabsContainer.DropdownActiveChangedEvent, ) { this._element = document.createElement('section'); this._element.classList.add(DomConstants.ClassName.Tabs); this._dropdownElement = document.createElement('section'); this._dropdownElement.classList.add(DomConstants.ClassName.TabDropdownList); this._dropdownElement.style.display = 'none'; } destroy(): void { for (let i = 0; i < this._tabs.length; i++) { this._tabs[i].destroy(); } } /** * Creates a new tab and associates it with a contentItem * @param index - The position of the tab */ createTab(componentItem: ComponentItem, index: number): void { //If there's already a tab relating to the //content item, don't do anything for (let i = 0; i < this._tabs.length; i++) { if (this._tabs[i].componentItem === componentItem) { return; } } const tab = new Tab(this._layoutManager, componentItem, (item) => this.handleTabCloseEvent(item), (item) => this.handleTabFocusEvent(item), (x, y, dragListener, item) => this.handleTabDragStartEvent(x, y, dragListener, item)); if (this._tabs.length === 0) { this._tabs.push(tab); this._element.appendChild(tab.element); } else { if (index === undefined) { index = this._tabs.length; } if (index > 0) { this._tabs[index - 1].element.insertAdjacentElement('afterend', tab.element); } else { this._tabs[0].element.insertAdjacentElement('beforebegin', tab.element); } this._tabs.splice(index, 0, tab); } } removeTab(componentItem: ComponentItem): void { // componentItem cannot be ActiveComponentItem for (let i = 0; i < this._tabs.length; i++) { if (this._tabs[i].componentItem === componentItem) { const tab = this._tabs[i]; tab.destroy(); this._tabs.splice(i, 1); return; } } throw new Error('contentItem is not controlled by this header'); } processActiveComponentChanged(newActiveComponentItem: ComponentItem): void { let activeIndex = -1; for (let i = 0; i < this._tabs.length; i++) { const isActive = this._tabs[i].componentItem === newActiveComponentItem; this._tabs[i].setActive(isActive); if (isActive) { activeIndex = i; } } if (activeIndex < 0) { throw new AssertError('HSACI56632'); } else { if (this._layoutManager.layoutConfig.settings.reorderOnTabMenuClick) { /** * If the tab selected was in the dropdown, move everything down one to make way for this one to be the first. * This will make sure the most used tabs stay visible. */ if (this._lastVisibleTabIndex !== -1 && activeIndex > this._lastVisibleTabIndex) { const activeTab = this._tabs[activeIndex]; for (let j = activeIndex; j > 0; j--) { this._tabs[j] = this._tabs[j - 1]; } this._tabs[0] = activeTab; // updateTabSizes will always be called after this and it will reposition tab elements } } } } /** * Pushes the tabs to the tab dropdown if the available space is not sufficient */ updateTabSizes(availableWidth: number, activeComponentItem: ComponentItem | undefined): void { let dropDownActive = false; const success = this.tryUpdateTabSizes(dropDownActive, availableWidth, activeComponentItem); if (!success) { dropDownActive = true; // this will always succeed this.tryUpdateTabSizes(dropDownActive, availableWidth, activeComponentItem) } if (dropDownActive !== this._dropdownActive) { this._dropdownActive = dropDownActive; this._dropdownActiveChangedEvent(); } } tryUpdateTabSizes(dropdownActive: boolean, availableWidth: number, activeComponentItem: ComponentItem | undefined): boolean { if (this._tabs.length > 0) { if (activeComponentItem === undefined) { throw new Error('non-empty tabs must have active component item'); } let cumulativeTabWidth = 0; let tabOverlapAllowanceExceeded = false; const tabOverlapAllowance = this._layoutManager.layoutConfig.settings.tabOverlapAllowance; const activeIndex = this._tabs.indexOf(activeComponentItem.tab); const activeTab = this._tabs[activeIndex]; this._lastVisibleTabIndex = -1; for (let i = 0; i < this._tabs.length; i++) { const tabElement = this._tabs[i].element; //Put the tab in the tabContainer so its true width can be checked if (tabElement.parentElement !== this._element) { this._element.appendChild(tabElement); } const tabMarginRightPixels = getComputedStyle(activeTab.element).marginRight; const tabMarginRight = pixelsToNumber(tabMarginRightPixels); const tabWidth = tabElement.offsetWidth + tabMarginRight; cumulativeTabWidth += tabWidth; //Include the active tab's width if it isn't already //This is to ensure there is room to show the active tab let visibleTabWidth = 0; if (activeIndex <= i) { visibleTabWidth = cumulativeTabWidth; } else { const activeTabMarginRightPixels = getComputedStyle(activeTab.element).marginRight; const activeTabMarginRight = pixelsToNumber(activeTabMarginRightPixels); visibleTabWidth = cumulativeTabWidth + activeTab.element.offsetWidth + activeTabMarginRight; } // If the tabs won't fit, check the overlap allowance. if (visibleTabWidth > availableWidth) { //Once allowance is exceeded, all remaining tabs go to menu. if (!tabOverlapAllowanceExceeded) { //No overlap for first tab or active tab //Overlap spreads among non-active, non-first tabs let overlap: number; if (activeIndex > 0 && activeIndex <= i) { overlap = (visibleTabWidth - availableWidth) / (i - 1); } else { overlap = (visibleTabWidth - availableWidth) / i; } //Check overlap against allowance. if (overlap < tabOverlapAllowance) { for (let j = 0; j <= i; j++) { const marginLeft = (j !== activeIndex && j !== 0) ? '-' + numberToPixels(overlap) : ''; this._tabs[j].element.style.zIndex = numberToPixels(i - j); this._tabs[j].element.style.marginLeft = marginLeft; } this._lastVisibleTabIndex = i; if (tabElement.parentElement !== this._element) { this._element.appendChild(tabElement); } } else { tabOverlapAllowanceExceeded = true; } } else if (i === activeIndex) { //Active tab should show even if allowance exceeded. (We left room.) tabElement.style.zIndex = 'auto'; tabElement.style.marginLeft = ''; if (tabElement.parentElement !== this._element) { this._element.appendChild(tabElement); } } if (tabOverlapAllowanceExceeded && i !== activeIndex) { if (dropdownActive) { //Tab menu already shown, so we just add to it. tabElement.style.zIndex = 'auto'; tabElement.style.marginLeft = ''; if (tabElement.parentElement !== this._dropdownElement) { this._dropdownElement.appendChild(tabElement); } } else { //We now know the tab menu must be shown, so we have to recalculate everything. return false; } } } else { this._lastVisibleTabIndex = i; tabElement.style.zIndex = 'auto'; tabElement.style.marginLeft = ''; if (tabElement.parentElement !== this._element) { this._element.appendChild(tabElement); } } } } return true; } /** * Shows drop down for additional tabs when there are too many to display. */ showAdditionalTabsDropdown(): void { this._dropdownElement.style.display = ''; } /** * Hides drop down for additional tabs when there are too many to display. */ hideAdditionalTabsDropdown(): void { this._dropdownElement.style.display = 'none'; } private handleTabCloseEvent(componentItem: ComponentItem) { this._componentRemoveEvent(componentItem); } private handleTabFocusEvent(componentItem: ComponentItem) { this._componentFocusEvent(componentItem); } private handleTabDragStartEvent(x: number, y: number, dragListener: DragListener, componentItem: ComponentItem) { this._componentDragStartEvent(x, y, dragListener, componentItem); } } /** @internal */ export namespace TabsContainer { export type ComponentItemRemoveEvent = (this: void, componentItem: ComponentItem) => void; export type ComponentItemFocusEvent = (this: void, componentItem: ComponentItem) => void; export type ComponentItemDragStartEvent = (this: void, x: number, y: number, dragListener: DragListener, componentItem: ComponentItem) => void; export type DropdownActiveChangedEvent = (this: void) => void; }
the_stack
import {Feature, MapBrowserEvent, View} from "ol"; import {Extent, getCenter} from "ol/extent"; import {defaults as defaultInteractions, DragPan, Interaction, DragBox, Snap} from "ol/interaction.js"; import PointerInteraction from 'ol/interaction/Pointer'; import Draw from "ol/interaction/Draw.js"; import Style from "ol/style/Style"; import Collection from 'ol/Collection'; import {shiftKeyOnly, never} from 'ol/events/condition'; import {Modify} from "ol/interaction"; import Polygon from "ol/geom/Polygon"; import ImageLayer from "ol/layer/Image"; import Layer from "ol/layer/Layer"; import VectorLayer from "ol/layer/Vector"; import Map from "ol/Map"; import Projection from "ol/proj/Projection"; import Static from "ol/source/ImageStatic.js"; import VectorSource from "ol/source/Vector"; import * as React from "react"; import "./styles.css"; import Utils from "./utils"; import {FeatureCategory, IRegion} from "../../../../models/applicationState"; interface IImageMapProps { imageUri: string; imageWidth: number; imageHeight: number; imageAngle?: number; featureStyler?: (feature) => Style; tableBorderFeatureStyler?: (feature) => Style; tableIconFeatureStyler?: (feature, resolution) => Style; tableIconBorderFeatureStyler?: (feature) => Style; checkboxFeatureStyler?: (feature) => Style; labelFeatureStyler?: (feature) => Style; drawRegionStyler?: () => Style; drawnRegionStyler?: (feature) => Style; modifyStyler?: () => Style; initEditorMap?: boolean; initPredictMap?: boolean; initLayoutMap?: boolean; enableFeatureSelection?: boolean; handleFeatureSelect?: (feature: any, isTaggle: boolean, category: FeatureCategory) => void; handleFeatureDoubleClick?: (feature: any, isTaggle: boolean, category: FeatureCategory) => void; groupSelectMode?: boolean; handleIsPointerOnImage?: (isPointerOnImage: boolean) => void; isPointerOnImage?: boolean; drawRegionMode?: boolean; isSnapped?: boolean; handleIsSnapped?: (snapped: boolean) => void; handleVertexDrag?: (dragging: boolean) => void; isVertexDragging?: boolean; handleDrawing?: (drawing: boolean) => void; isDrawing?: boolean; handleRegionSelectByGroup?: (selectedRegions: IRegion[]) => void; handleFeatureSelectByGroup?: (feature) => IRegion; hoveringFeature?: string; onMapReady: () => void; handleTableToolTipChange?: (display: string, width: number, height: number, top: number, left: number, rows: number, columns: number, featureID: string) => void; addDrawnRegionFeatureProps?: (feature) => void; updateFeatureAfterModify?: (features) => any; } export class ImageMap extends React.Component<IImageMapProps> { private map: Map; private imageLayer: ImageLayer; private textVectorLayer: VectorLayer; private tableBorderVectorLayer: VectorLayer; private tableIconVectorLayer: VectorLayer; private tableIconBorderVectorLayer: VectorLayer; private checkboxVectorLayer: VectorLayer; private labelVectorLayer: VectorLayer; private drawRegionVectorLayer: VectorLayer; private drawnLabelVectorLayer: VectorLayer; private mapElement: HTMLDivElement | null = null; private dragPan: DragPan; private draw: Draw; private dragBox: DragBox; private modify: Modify; private snap: Snap; private drawnFeatures: Collection = new Collection([], { unique: true }); public modifyStartFeatureCoordinates: any = {}; private imageExtent: number[]; private countPointerDown: number = 0; private isSwiping: boolean = false; private readonly IMAGE_LAYER_NAME = "imageLayer"; private readonly TEXT_VECTOR_LAYER_NAME = "textVectorLayer"; private readonly TABLE_BORDER_VECTOR_LAYER_NAME = "tableBorderVectorLayer"; private readonly TABLE_ICON_VECTOR_LAYER_NAME = "tableIconVectorLayer"; private readonly TABLE_ICON_BORDER_VECTOR_LAYER_NAME = "tableIconBorderVectorLayer"; private readonly CHECKBOX_VECTOR_LAYER_NAME = "checkboxBorderVectorLayer"; private readonly LABEL_VECTOR_LAYER_NAME = "labelledVectorLayer"; private readonly DRAWN_REGION_LABEL_VECTOR_LAYER_NAME = "drawnRegionLabelledVectorLayer"; private readonly DRAWN_REGION_VECTOR_LAYER_NAME = "drawnRegionVectorLayer"; private ignorePointerMoveEventCount: number = 5; private pointerMoveEventCount: number = 0; private imageLayerFilter = { layerFilter: (layer: Layer) => layer.get("name") === this.IMAGE_LAYER_NAME, }; private textVectorLayerFilter = { layerFilter: (layer: Layer) => layer.get("name") === this.TEXT_VECTOR_LAYER_NAME, }; private checkboxLayerFilter = { layerFilter: (layer: Layer) => layer.get("name") === this.CHECKBOX_VECTOR_LAYER_NAME, }; private tableIconBorderVectorLayerFilter = { layerFilter: (layer: Layer) => layer.get("name") === this.TABLE_ICON_BORDER_VECTOR_LAYER_NAME, }; private labelVectorLayerFilter = { layerFilter: (layer: Layer) => layer.get("name") === this.LABEL_VECTOR_LAYER_NAME, }; private drawnLabelVectorLayerFilter = { layerFilter: (layer: Layer) => layer.get("name") === this.DRAWN_REGION_LABEL_VECTOR_LAYER_NAME, }; private drawnRegionVectorLayerFilter = { layerFilter: (layer: Layer) => layer.get("name") === this.DRAWN_REGION_VECTOR_LAYER_NAME, }; constructor(props: IImageMapProps) { super(props); this.imageExtent = [0, 0, this.props.imageWidth, this.props.imageHeight]; } public componentDidMount() { if (this.props.initEditorMap) { this.initEditorMap(); } else if (this.props.initPredictMap) { this.initPredictMap(); } else if (this.props.initLayoutMap) { this.initLayoutMap(); } } public componentDidUpdate(prevProps: IImageMapProps) { if (this.props.initEditorMap || this.props.initLayoutMap) { if (this.props?.drawRegionMode) { this.removeInteraction(this.dragBox); this.initializeDraw(); this.addInteraction(this.draw); this.initializeModify(); this.addInteraction(this.modify); this.addInteraction(this.snap); if (this.props?.isPointerOnImage) { if (this.props.isSnapped) { this.removeInteraction(this.draw); } if (this.props.isDrawing) { this.removeInteraction(this.snap); } } else { this.removeInteraction(this.draw); this.removeInteraction(this.modify); this.removeInteraction(this.snap); } } else { this.removeInteraction(this.draw); this.addInteraction(this.dragBox); this.initializeModify(); this.addInteraction(this.modify); this.addInteraction(this.snap); if (!this.props?.isPointerOnImage) { this.removeInteraction(this.modify); this.removeInteraction(this.dragBox); } } if (!this.props.isPointerOnImage && prevProps.isPointerOnImage && this.props.isVertexDragging) { this.cancelModify(); } } if (prevProps.imageUri !== this.props.imageUri || prevProps.imageAngle !== this.props.imageAngle) { this.imageExtent = [0, 0, this.props.imageWidth, this.props.imageHeight]; this.setImage(this.props.imageUri, this.imageExtent); } } public render() { return ( <div onMouseLeave={this.handlePonterLeaveImageMap} onMouseEnter={this.handlePointerEnterImageMap} className="map-wrapper" > <div style={{ cursor: this.getCursor() }} id="map" className="map" ref={(el) => this.mapElement = el} /> </div> ); } public resetAllLayerVisibility = () => { this.toggleCheckboxFeatureVisibility(true); this.toggleLabelFeatureVisibility(true); this.toggleTableFeatureVisibility(true); this.toggleTextFeatureVisibility(true); this.toggleDrawnRegionsFeatureVisibility(true); } /** * Hide/Display table features */ public toggleTableFeatureVisibility = (visible: boolean = false) => { this.tableBorderVectorLayer.setVisible(visible || !this.tableBorderVectorLayer.getVisible()); this.tableIconVectorLayer.setVisible(visible || !this.tableIconVectorLayer.getVisible()); this.tableIconBorderVectorLayer.setVisible(visible || !this.tableIconBorderVectorLayer.getVisible()); } public toggleLabelFeatureVisibility = (visible: boolean = false) => { this.labelVectorLayer.setVisible(visible || !this.labelVectorLayer.getVisible()); let drawLabelVectorLayerVisibility = this.drawnLabelVectorLayer.getVisible(); this.drawnLabelVectorLayer.setVisible(visible || !drawLabelVectorLayerVisibility); drawLabelVectorLayerVisibility = this.drawnLabelVectorLayer.getVisible(); const drawnLabelFeatures = this.getAllDrawnLabelFeatures(); if (!drawLabelVectorLayerVisibility) { drawnLabelFeatures?.forEach((feature) => { this.removeFromDrawnFeatures(feature); }); } else { drawnLabelFeatures?.forEach((feature) => { this.pushToDrawnFeatures(feature); }); } } public toggleDrawnRegionsFeatureVisibility = (visible: boolean = false) => { let drawRegionVectorLayerVisibility = this.drawRegionVectorLayer.getVisible(); this.drawRegionVectorLayer.setVisible(visible || !drawRegionVectorLayerVisibility); drawRegionVectorLayerVisibility = this.drawRegionVectorLayer.getVisible(); const drawnRegionFeatures = this.getAllDrawnRegionFeatures(); if (!drawRegionVectorLayerVisibility) { drawnRegionFeatures?.forEach((feature) => { this.removeFromDrawnFeatures(feature); }); } else { drawnRegionFeatures?.forEach((feature) => { this.pushToDrawnFeatures(feature); }); } } private pushToDrawnFeatures = (feature, drawnFeatures: Collection = this.drawnFeatures) => { const itemAlreadyExists = drawnFeatures.getArray().indexOf(feature) !== -1 if (!itemAlreadyExists) { drawnFeatures.push(feature); } } private removeFromDrawnFeatures = (feature, drawnFeatures: Collection = this.drawnFeatures) => { const itemAlreadyExists = drawnFeatures.getArray().indexOf(feature) !== -1 if (itemAlreadyExists) { drawnFeatures.remove(feature); } } /** * Hide/Display checkbox features */ public toggleCheckboxFeatureVisibility = (visible: boolean = false) => { this.checkboxVectorLayer.setVisible(visible || !this.checkboxVectorLayer.getVisible()); } public getResolutionForZoom = (zoom: number) => { if (this.map && this.map.getView()) { return this.map.getView().getResolutionForZoom(zoom); } else { return null; } } /** * Hide/Display text features */ public toggleTextFeatureVisibility = (visible: boolean = false) => { this.textVectorLayer.setVisible(visible || !this.textVectorLayer.getVisible()); } /** * Add one text feature to the map */ public addFeature = (feature: Feature) => { this.textVectorLayer.getSource().addFeature(feature); } public addCheckboxFeature = (feature: Feature) => { this.checkboxVectorLayer.getSource().addFeature(feature); } public addLabelFeature = (feature: Feature) => { this.labelVectorLayer.getSource().addFeature(feature); } public addDrawnLabelFeature = (feature: Feature) => { this.drawnLabelVectorLayer.getSource().addFeature(feature); } public addTableBorderFeature = (feature: Feature) => { this.tableBorderVectorLayer.getSource().addFeature(feature); } public addTableIconFeature = (feature: Feature) => { this.tableIconVectorLayer.getSource().addFeature(feature); } public addTableIconBorderFeature = (feature: Feature) => { this.tableIconBorderVectorLayer.getSource().addFeature(feature); } /** * Add features to the map */ public addFeatures = (features: Feature[]) => { this.textVectorLayer.getSource().addFeatures(features); } public addCheckboxFeatures = (features: Feature[]) => { this.checkboxVectorLayer.getSource().addFeatures(features); } public addLabelFeatures = (features: Feature[]) => { this.labelVectorLayer.getSource().addFeatures(features); } public addDrawnLabelFeatures = (features: Feature[]) => { this.drawnLabelVectorLayer.getSource().addFeatures(features); } public addTableBorderFeatures = (features: Feature[]) => { this.tableBorderVectorLayer.getSource().addFeatures(features); } public addTableIconFeatures = (features: Feature[]) => { this.tableIconVectorLayer.getSource().addFeatures(features); } public addTableIconBorderFeatures = (features: Feature[]) => { this.tableIconBorderVectorLayer.getSource().addFeatures(features); } public addDrawnRegionFeatures = (features: Feature[]) => { this.drawRegionVectorLayer.getSource().addFeatures(features); } /** * Add interaction to the map */ public addInteraction = (interaction: Interaction) => { if (undefined === this.map.getInteractions().array_.find((existingInteraction) => { return interaction.constructor === existingInteraction.constructor; })) { this.map.addInteraction(interaction); } } /** * Get all features from the map */ public getAllFeatures = () => { return this.textVectorLayer.getSource().getFeatures(); } public getAllCheckboxFeatures = () => { return this.checkboxVectorLayer.getSource().getFeatures(); } public getAllLabelFeatures = () => { return this.labelVectorLayer.getSource().getFeatures(); } public getAllDrawnLabelFeatures = () => { return this.drawnLabelVectorLayer.getSource().getFeatures(); } public getAllDrawnRegionFeatures = () => { return this.drawRegionVectorLayer.getSource().getFeatures(); } public getFeatureByID = (featureID) => { return this.textVectorLayer.getSource().getFeatureById(featureID); } public getCheckboxFeatureByID = (featureID) => { return this.checkboxVectorLayer.getSource().getFeatureById(featureID); } public getTableBorderFeatureByID = (featureID) => { return this.tableBorderVectorLayer.getSource().getFeatureById(featureID); } public getTableIconFeatureByID = (featureID) => { return this.tableIconVectorLayer.getSource().getFeatureById(featureID); } public getTableIconBorderFeatureByID = (featureID) => { return this.tableIconBorderVectorLayer.getSource().getFeatureById(featureID); } public getDrawnRegionFeatureByID = (featureID) => { return this.drawRegionVectorLayer.getSource().getFeatureById(featureID); } public getLabelFeatureByID = (featureID) => { return this.labelVectorLayer.getSource().getFeatureById(featureID); } public getDrawnLabelFeatureByID = (featureID) => { return this.drawnLabelVectorLayer.getSource().getFeatureById(featureID); } /** * Remove specific feature object from the map */ public removeFeature = (feature: Feature) => { if (feature && this.getFeatureByID(feature.getId())) { this.textVectorLayer.getSource().removeFeature(feature); } } public removeCheckboxFeature = (feature: Feature) => { if (feature && this.getCheckboxFeatureByID(feature.getId())) { this.checkboxVectorLayer.getSource().removeFeature(feature); } } public removeLabelFeature = (feature: Feature) => { if (feature && this.getLabelFeatureByID(feature.getId())) { this.labelVectorLayer.getSource().removeFeature(feature); } } public removeDrawnLabelFeature = (feature: Feature) => { if (feature && this.getDrawnLabelFeatureByID(feature.getId())) { this.drawnLabelVectorLayer.getSource().removeFeature(feature); } } public removeDrawnRegionFeature = (feature: Feature) => { if (feature && this.getDrawnRegionFeatureByID(feature.getId())) { this.drawRegionVectorLayer.getSource().removeFeature(feature); } } /** * Remove all features from the map */ public removeAllFeatures = () => { if (this.props.handleTableToolTipChange) { this.props.handleTableToolTipChange("none", 0, 0, 0, 0, 0, 0, null); } this.textVectorLayer?.getSource().clear(); this.tableBorderVectorLayer?.getSource().clear(); this.tableIconVectorLayer?.getSource().clear(); this.tableIconBorderVectorLayer?.getSource().clear(); this.checkboxVectorLayer?.getSource().clear(); this.labelVectorLayer?.getSource().clear(); if (this.props.initEditorMap) { this.clearDrawnRegions(); } } private clearDrawnRegions = () => { this.drawRegionVectorLayer?.getSource().clear(); this.drawnLabelVectorLayer?.getSource().clear(); this.drawnFeatures = new Collection([], { unique: true }); this.drawRegionVectorLayer.getSource().on("addfeature", (evt) => { this.pushToDrawnFeatures(evt.feature, this.drawnFeatures); }); this.drawRegionVectorLayer.getSource().on("removefeature", (evt) => { this.removeFromDrawnFeatures(evt.feature, this.drawnFeatures); }); this.drawnLabelVectorLayer.getSource().on("addfeature", (evt) => { this.pushToDrawnFeatures(evt.feature, this.drawnFeatures); }); this.drawnLabelVectorLayer.getSource().on("removefeature", (evt) => { this.removeFromDrawnFeatures(evt.feature, this.drawnFeatures); }); this.removeInteraction(this.snap); this.initializeSnap(); this.addInteraction(this.snap) this.removeInteraction(this.modify); this.initializeModify(); this.addInteraction(this.modify); } public removeAllLabelFeatures = () => { this.labelVectorLayer?.getSource().clear(); } public removeAllDrawnLabelFeatures = () => { this.getAllDrawnLabelFeatures().forEach((feature) => { this.removeFromDrawnFeatures(feature); }); this.drawnLabelVectorLayer?.getSource().clear(); } /** * Remove interaction from the map */ public removeInteraction = (interaction: Interaction) => { const existingInteraction = this.map.getInteractions().array_.find((existingInteraction) => { return interaction.constructor === existingInteraction.constructor; }); if (existingInteraction !== undefined) { this.map.removeInteraction(existingInteraction); } } public updateSize = () => { if (this.map) { this.map.updateSize(); } } /** * Get the image extent (left, top, right, bottom) */ public getImageExtent = () => { return this.imageExtent; } /** * Get features at specific extend */ public getFeaturesInExtent = (extent: Extent): Feature[] => { const features: Feature[] = []; this.textVectorLayer.getSource().forEachFeatureInExtent(extent, (feature) => { features.push(feature); }); return features; } public zoomIn = () => { this.map.getView().setZoom(this.map.getView().getZoom() + 0.3); } public zoomOut = () => { this.map.getView().setZoom(this.map.getView().getZoom() - 0.3); } public resetZoom = () => { this.map.getView().setZoom(0); } private initPredictMap = () => { const projection = this.createProjection(this.imageExtent); const layers = this.initializePredictLayers(projection); this.initializeMap(projection, layers); this.initializeDragPan(); } private initEditorMap = () => { const projection = this.createProjection(this.imageExtent); const layers = this.initializeEditorLayers(projection); this.initializeMap(projection, layers); this.map.on("pointerdown", this.handlePointerDown); this.map.on("pointermove", this.handlePointerMove); this.map.on("pointermove", this.handlePointerMoveOnTableIcon); this.map.on("pointerup", this.handlePointerUp); this.map.on("dblclick", this.handleDoubleClick); this.initializeDefaultSelectionMode(); this.initializeDragPan(); } private initLayoutMap = () => { const projection = this.createProjection(this.imageExtent); const layers = this.initializeEditorLayers(projection); this.initializeMap(projection, layers); this.map.on("pointerdown", this.handlePointerDown); this.map.on("pointermove", this.handlePointerMove); this.map.on("pointermove", this.handlePointerMoveOnTableIcon); this.map.on("pointerup", this.handlePointerUp); this.map.on("dblclick", this.handleDoubleClick); this.initializeDefaultSelectionMode(); this.initializeDragPan(); } private setImage = (imageUri: string, imageExtent: number[]) => { const projection = this.createProjection(imageExtent); this.imageLayer.setSource(this.createImageSource(imageUri, projection, imageExtent)); const mapView = this.createMapView(projection, imageExtent); this.map.setView(mapView); } private createProjection = (imageExtend: number[]) => { return new Projection({ code: "xkcd-image", units: "pixels", extent: imageExtend, }); } private createMapView = (projection: Projection, imageExtend: number[]) => { const minZoom = this.getMinimumZoom(); const rotation = (this.props.imageAngle) ? Utils.degreeToRadians((this.props.imageAngle + 360) % 360) : 0; return new View({ projection, center: getCenter(imageExtend), rotation, zoom: minZoom, minZoom, }); } private createImageSource = (imageUri: string, projection: Projection, imageExtend: number[]) => { return new Static({ url: imageUri, projection, imageExtent: imageExtend, }); } private getMinimumZoom = () => { // In openlayers, the image will be projected into 256x256 pixels, // and image will be 2x larger at each zoom level. // https://openlayers.org/en/latest/examples/min-zoom.html const containerAspectRatio = (this.mapElement) ? (this.mapElement.clientHeight / this.mapElement.clientWidth) : 1; const imageAspectRatio = this.props.imageHeight / this.props.imageWidth; if (imageAspectRatio > containerAspectRatio) { // Fit to width return Math.LOG2E * Math.log(this.mapElement!.clientHeight / 256); } else { // Fit to height return Math.LOG2E * Math.log(this.mapElement!.clientWidth / 256); } } private handlePointerDown = (event: MapBrowserEvent) => { if (this.props.isSnapped) { this.props.handleVertexDrag(true); return; } if (!this.props.enableFeatureSelection) { return; } const eventPixel = this.map.getEventPixel(event.originalEvent); const filter = this.getLayerFilterAtPixel(eventPixel); const isPixelOnFeature = !!filter; if (isPixelOnFeature && !this.props.isSnapped) { this.setDragPanInteraction(false); } if (filter && this.props.handleFeatureSelect) { this.map.forEachFeatureAtPixel( eventPixel, (feature) => { this.props.handleFeatureSelect(feature, true, filter.category); }, filter.layerfilter, ); } } private handleDoubleClick = (event: MapBrowserEvent) => { const eventPixel = this.map.getEventPixel(event.originalEvent); const filter = this.getLayerFilterAtPixel(eventPixel); if (filter && this.props.handleFeatureDoubleClick) { this.map.forEachFeatureAtPixel( eventPixel, (feature) => { this.props.handleFeatureDoubleClick(feature, true, filter.category); }, filter.layerfilter, ); } } private getLayerFilterAtPixel = (eventPixel: any) => { const isPointerOnLabelledFeature = this.map.hasFeatureAtPixel( eventPixel, this.labelVectorLayerFilter); if (isPointerOnLabelledFeature) { return { layerfilter: this.labelVectorLayerFilter, category: FeatureCategory.Label, }; } const isPointerOnCheckboxFeature = this.map.hasFeatureAtPixel( eventPixel, this.checkboxLayerFilter); if (isPointerOnCheckboxFeature) { return { layerfilter: this.checkboxLayerFilter, category: FeatureCategory.Checkbox, }; } const isPointerOnTextFeature = this.map.hasFeatureAtPixel( eventPixel, this.textVectorLayerFilter); if (isPointerOnTextFeature) { return { layerfilter: this.textVectorLayerFilter, category: FeatureCategory.Text, }; } const isPointerOnDrawnRegionFeature = this.map.hasFeatureAtPixel( eventPixel, this.drawnRegionVectorLayerFilter); if (isPointerOnDrawnRegionFeature) { return { layerfilter: this.drawnRegionVectorLayerFilter, category: FeatureCategory.DrawnRegion, }; } const isPointerOnDrawnLabelFeature = this.map.hasFeatureAtPixel( eventPixel, this.drawnLabelVectorLayerFilter); if (isPointerOnDrawnLabelFeature) { return { layerfilter: this.drawnLabelVectorLayerFilter, category: FeatureCategory.DrawnRegion, }; } return null; } private handlePointerMoveOnTableIcon = (event: MapBrowserEvent) => { if (this.props.handleTableToolTipChange) { const eventPixel = this.map.getEventPixel(event.originalEvent); const isPointerOnTableIconFeature = this.map.hasFeatureAtPixel(eventPixel, this.tableIconBorderVectorLayerFilter); if (isPointerOnTableIconFeature) { const features = this.map.getFeaturesAtPixel(eventPixel, this.tableIconBorderVectorLayerFilter); if (features.length > 0) { const feature = features[0]; if (feature && this.props.hoveringFeature !== feature.get("id")) { const geometry = feature.getGeometry(); const coordinates = geometry.getCoordinates(); if (coordinates && coordinates.length > 0) { const pixels = []; pixels.push(this.map.getPixelFromCoordinate(coordinates[0][0])); pixels.push(this.map.getPixelFromCoordinate(coordinates[0][1])); pixels.push(this.map.getPixelFromCoordinate(coordinates[0][2])); pixels.push(this.map.getPixelFromCoordinate(coordinates[0][3])); const flattenedLines = [].concat(...pixels); const xAxisValues = flattenedLines.filter((value, index) => index % 2 === 0); const yAxisValues = flattenedLines.filter((value, index) => index % 2 === 1); const left = Math.min(...xAxisValues); const top = Math.min(...yAxisValues); const right = Math.max(...xAxisValues); const bottom = Math.max(...yAxisValues); const width = right - left; const height = bottom - top; this.props.handleTableToolTipChange("block", width + 2, height + 2, top + 43, left - 1, feature.get("rows"), feature.get("columns"), feature.get("id")); } } } } else { if (this.props.hoveringFeature !== null) { this.props.handleTableToolTipChange("none", 0, 0, 0, 0, 0, 0, null); } } } } private handlePointerMove = (event: MapBrowserEvent) => { if (this.shouldIgnorePointerMove()) { return; } // disable vertical scrolling for iOS Safari event.preventDefault(); const eventPixel = this.map.getEventPixel(event.originalEvent); this.map.forEachFeatureAtPixel( eventPixel, (feature) => { if (this.props.handleFeatureSelect) { this.props.handleFeatureSelect(feature, false /*isTaggle*/, FeatureCategory.Text); } }, this.textVectorLayerFilter); } private handlePointerUp = () => { if (this.props.isDrawing) { this.props.handleDrawing(false); return; } if (this.props.isVertexDragging) { this.props.handleVertexDrag(false); return; } if (!this.props.enableFeatureSelection) { return; } this.setDragPanInteraction(true); this.removeInteraction(this.modify); this.initializeModify(); this.addInteraction(this.modify) } private setDragPanInteraction = (dragPanEnabled: boolean) => { if (dragPanEnabled) { this.addInteraction(this.dragPan) this.setSwiping(false); } else { this.removeInteraction(this.dragPan) this.setSwiping(true); } } public setSwiping = (swiping: boolean) => { this.isSwiping = swiping; } private shouldIgnorePointerMove = () => { if (!this.props.enableFeatureSelection) { return true; } if (!this.isSwiping) { return true; } return false; } public cancelDrawing = () => { this.removeInteraction(this.draw) this.initializeDraw(); this.addInteraction(this.draw); } public cancelModify = () => { Object.entries(this.modifyStartFeatureCoordinates).forEach((featureCoordinate) => { let feature = this.getDrawnRegionFeatureByID(featureCoordinate[0]); if (!feature) { feature = this.getDrawnLabelFeatureByID(featureCoordinate[0]); } if (feature.getGeometry().flatCoordinates.join(",") !== featureCoordinate[1]) { const oldFlattenedCoordinates = (featureCoordinate[1] as string).split(",").map(parseFloat); const oldCoordinates = []; for (let i = 0; i < oldFlattenedCoordinates.length; i += 2) { oldCoordinates.push([ oldFlattenedCoordinates[i], oldFlattenedCoordinates[i + 1], ]); } feature.getGeometry().setCoordinates([oldCoordinates]); } }); this.modifyStartFeatureCoordinates = {}; this.removeInteraction(this.modify); this.initializeModify(); this.addInteraction(this.modify); this.props.handleIsSnapped(false); } private initializeDefaultSelectionMode = () => { this.initializeSnapCheck(); this.initializePointerOnImageCheck(); this.initializeDragBox(); this.initializeModify(); this.initializeSnap(); this.initializeDraw(); this.addInteraction(this.dragBox); this.addInteraction(this.modify); this.addInteraction(this.snap); } private initializeDraw = () => { const boundingExtent = (coordinates) => { const extent = createEmpty(); coordinates.forEach((coordinate) => { extendCoordinate(extent, coordinate); }); return extent; } const createEmpty = () => { return [Infinity, Infinity, -Infinity, -Infinity]; } const extendCoordinate = (extent, coordinate) => { if (coordinate[0] < extent[0]) { extent[0] = coordinate[0]; } if (coordinate[0] > extent[2]) { extent[2] = coordinate[0]; } if (coordinate[1] < extent[1]) { extent[1] = coordinate[1]; } if (coordinate[1] > extent[3]) { extent[3] = coordinate[1]; } } this.draw = new Draw({ source: this.drawRegionVectorLayer.getSource(), style: this.props.drawRegionStyler, geometryFunction: (coordinates, optGeometry) => { const extent = boundingExtent(/** @type {LineCoordType} */(coordinates)); const boxCoordinates = [[ [extent[0], extent[3]], [extent[2], extent[3]], [extent[2], extent[1]], [extent[0], extent[1]] ]]; let geometry = optGeometry; if (geometry) { geometry.setCoordinates(boxCoordinates); } else { geometry = new Polygon(boxCoordinates); } return geometry; }, freehand: true, stopClick: true, }); this.draw.on('drawstart', (drawEvent) => { this.props.handleDrawing(true); }); this.draw.on('drawend', (drawEvent) => { this.props.addDrawnRegionFeatureProps(drawEvent.feature); }); } private initializeModify = () => { this.modify = new Modify({ deleteCondition: never, insertVertexCondition: never, style: this.props.modifyStyler, features: this.drawnFeatures, }); this.modify.handleUpEvent_old = this.modify.handleUpEvent; this.modify.handleUpEvent = function (evt) { try { this.handleUpEvent_old(evt); } catch (ex) { // do nothing } } this.modify.on('modifystart', (modifyEvent) => { const features = modifyEvent.features.getArray(); let featureCoordinates = []; features.forEach((feature) => { feature.getGeometry().getCoordinates()[0].forEach((coordinate) => { featureCoordinates.push(coordinate[0]) featureCoordinates.push(coordinate[1]) }); this.modifyStartFeatureCoordinates[feature.getId()] = featureCoordinates.join(","); featureCoordinates = []; }); }); this.modify.on('modifyend', (modifyEvent) => { const features = modifyEvent.features.getArray(); this.props.updateFeatureAfterModify(features); }); } private initializeSnap = () => { this.snap = new Snap({ edge: false, vertex: true, features: this.drawnFeatures, }); } private initializeDragPan = () => { this.dragPan = new DragPan(); this.setDragPanInteraction(true); } private initializeDragBox = () => { this.dragBox = new DragBox({ condition: shiftKeyOnly, className: "ol-dragbox-style", });; this.dragBox.on('boxend', () => { const featureMap = {}; const extent = this.dragBox.getGeometry().getExtent(); const regionsToAdd: IRegion[] = []; if (this.labelVectorLayer.getVisible()) { this.labelVectorLayer.getSource().forEachFeatureInExtent(extent, (feature) => { const selectedRegion = this.props.handleFeatureSelectByGroup(feature); if (selectedRegion) { featureMap[feature.get("id")] = true; regionsToAdd.push(selectedRegion); } }); } if (this.textVectorLayer.getVisible()) { this.textVectorLayer.getSource().forEachFeatureInExtent(extent, (feature) => { const selectedRegion = this.props.handleFeatureSelectByGroup(feature); if (selectedRegion && !featureMap.hasOwnProperty(feature.get("id"))) { regionsToAdd.push(selectedRegion); } }); } if (regionsToAdd.length > 0) { this.props.handleRegionSelectByGroup(regionsToAdd); } }); } private initializeSnapCheck = () => { const snapCheck = new Interaction({ handleEvent: (evt: MapBrowserEvent) => { if (!this.props.isVertexDragging && this.props.handleIsSnapped) { this.props.handleIsSnapped(this.snap.snapTo(evt.pixel, evt.coordinate, evt.map).snapped && this.props.isPointerOnImage) } return true; } }); this.addInteraction(snapCheck); } private initializePointerOnImageCheck = () => { const checkIfPointerOnMap = new PointerInteraction({ handleEvent: (evt: MapBrowserEvent) => { const eventPixel = this.map.getEventPixel(evt.originalEvent); const test = this.map.forEachLayerAtPixel( eventPixel, () => { return true }, this.imageLayerFilter); if (this.props.handleIsPointerOnImage) { if (!Boolean(test) && this.props.isPointerOnImage) { this.props.handleIsPointerOnImage(false); } else if (!this.props.isPointerOnImage && Boolean(test)) { this.props.handleIsPointerOnImage(true); } } return true } }); this.addInteraction(checkIfPointerOnMap); } private getCursor = () => { if (this.props.initEditorMap) { if (this.props.isVertexDragging) { return "grabbing"; } else if (this.props.isSnapped) { return "grab"; } else if (this.props?.groupSelectMode || this.props?.drawRegionMode) { if (this.props.isPointerOnImage) { return "crosshair"; } else { return "default"; } } else { return "default"; } } else { return "default"; } } private handlePonterLeaveImageMap = () => { if (this.props.initEditorMap) { if (this.props.isDrawing) { this.cancelDrawing(); } if(this.props.handleIsPointerOnImage) { this.props.handleIsPointerOnImage(false); } } } private handlePointerEnterImageMap = () => { this.setDragPanInteraction(true); } private initializeEditorLayers = (projection: Projection) => { this.initializeImageLayer(projection); this.initializeTextLayer(); this.initializeTableLayers(); this.initializeCheckboxLayers(); this.initializeLabelLayer(); this.initializeDrawnRegionLabelLayer(); this.initializeDrawnRegionLayer(); return [this.imageLayer, this.textVectorLayer, this.tableBorderVectorLayer, this.tableIconBorderVectorLayer, this.tableIconVectorLayer, this.checkboxVectorLayer, this.drawRegionVectorLayer, this.labelVectorLayer, this.drawnLabelVectorLayer]; } private initializePredictLayers = (projection: Projection) => { this.initializeImageLayer(projection); this.initializeTextLayer(); this.initializeLabelLayer(); return [this.imageLayer, this.textVectorLayer, this.labelVectorLayer]; } private initializeImageLayer = (projection: Projection) => { this.imageLayer = new ImageLayer({ source: this.createImageSource(this.props.imageUri, projection, this.imageExtent), name: this.IMAGE_LAYER_NAME, }); } private initializeTextLayer = () => { const textOptions: any = {}; textOptions.name = this.TEXT_VECTOR_LAYER_NAME; textOptions.style = this.props.featureStyler; textOptions.source = new VectorSource(); this.textVectorLayer = new VectorLayer(textOptions); } private initializeTableLayers = () => { const tableBorderOptions: any = {}; tableBorderOptions.name = this.TABLE_BORDER_VECTOR_LAYER_NAME; tableBorderOptions.style = this.props.tableBorderFeatureStyler; tableBorderOptions.source = new VectorSource(); this.tableBorderVectorLayer = new VectorLayer(tableBorderOptions); const tableIconOptions: any = {}; tableIconOptions.name = this.TABLE_ICON_VECTOR_LAYER_NAME; tableIconOptions.style = this.props.tableIconFeatureStyler; tableIconOptions.updateWhileAnimating = true; tableIconOptions.updateWhileInteracting = true; tableIconOptions.source = new VectorSource(); this.tableIconVectorLayer = new VectorLayer(tableIconOptions); const tableIconBorderOptions: any = {}; tableIconBorderOptions.name = this.TABLE_ICON_BORDER_VECTOR_LAYER_NAME; tableIconBorderOptions.style = this.props.tableIconBorderFeatureStyler; tableIconBorderOptions.source = new VectorSource(); this.tableIconBorderVectorLayer = new VectorLayer(tableIconBorderOptions); } private initializeCheckboxLayers = () => { const checkboxOptions: any = {}; checkboxOptions.name = this.CHECKBOX_VECTOR_LAYER_NAME; checkboxOptions.style = this.props.checkboxFeatureStyler; checkboxOptions.source = new VectorSource(); this.checkboxVectorLayer = new VectorLayer(checkboxOptions); } private initializeDrawnRegionLayer = () => { const drawnRegionOptions: any = {}; drawnRegionOptions.name = this.DRAWN_REGION_VECTOR_LAYER_NAME; drawnRegionOptions.style = this.props.drawnRegionStyler; drawnRegionOptions.source = new VectorSource(); drawnRegionOptions.source.on("addfeature", (evt) => { this.pushToDrawnFeatures(evt.feature); }); drawnRegionOptions.source.on("removefeature", (evt) => { this.removeFromDrawnFeatures(evt.feature); }); this.drawRegionVectorLayer = new VectorLayer(drawnRegionOptions); } private initializeLabelLayer = () => { const labelOptions: any = {}; labelOptions.name = this.LABEL_VECTOR_LAYER_NAME; labelOptions.style = this.props.labelFeatureStyler; labelOptions.source = new VectorSource(); this.labelVectorLayer = new VectorLayer(labelOptions); } private initializeDrawnRegionLabelLayer = () => { const drawnRegionLabelOptions: any = {}; drawnRegionLabelOptions.name = this.DRAWN_REGION_VECTOR_LAYER_NAME; drawnRegionLabelOptions.style = this.props.labelFeatureStyler; drawnRegionLabelOptions.source = new VectorSource(); drawnRegionLabelOptions.source.on('addfeature', (evt) => { if (this.drawnLabelVectorLayer.getVisible()) { this.pushToDrawnFeatures(evt.feature) } }); drawnRegionLabelOptions.source.on('removefeature', (evt) => { this.removeFromDrawnFeatures(evt.feature) }); this.drawnLabelVectorLayer = new VectorLayer(drawnRegionLabelOptions); } private initializeMap = (projection, layers) => { this.map = new Map({ controls: [], interactions: defaultInteractions({ shiftDragZoom: false, doubleClickZoom: false, pinchRotate: false, }), target: "map", layers, view: this.createMapView(projection, this.imageExtent), }); } }
the_stack
import * as React from 'react'; import { FocusTrapZone } from '@fluentui/react/lib/FocusTrapZone'; import { FocusZone, FocusZoneDirection } from '@fluentui/react/lib/FocusZone'; import type { IFocusTrapZoneProps, IFocusTrapZone } from '@fluentui/react/lib/FocusTrapZone'; import { mount } from '@cypress/react'; import type { FTZTestGlobals } from './types'; import { rootClass } from './shared'; describe('FocusTrapZone', () => { // These are basic tests of different props, but due to the reliance on focus behavior they're // best done in the browser. describe('Respects default and explicit prop values', () => { const PropValues = (props: IFocusTrapZoneProps) => { const [buttonClicked, setButtonClicked] = React.useState(''); return ( <div className={rootClass} onClick={ev => setButtonClicked((ev.target as HTMLButtonElement).textContent || '')}> <span id="buttonClicked" style={{ display: 'block' /* avoid inherited div styling */ }}> clicked {buttonClicked} </span> <button>before</button> <FocusTrapZone {...props}> <button>first</button> <button>mid</button> <button className="last-class" id="last"> last </button> </FocusTrapZone> <button>after</button> </div> ); }; it('Focuses first child on mount', () => { mount(<PropValues />); cy.focused().should('have.text', 'first'); }); it('Does not focus first child on mount with disableFirstFocus', () => { mount(<PropValues disableFirstFocus />); // Verify nothing is focused (note that document.activeElement will be body, but cy.focused() // uses :focus, and that's not set on body even if it's active) cy.focused().should('not.exist'); }); it('Can click children inside the FTZ', () => { mount(<PropValues />); // wait for first focus to finish cy.focused().should('have.text', 'first'); // focus inside the FTZ cy.contains('mid').realClick(); cy.focused().should('have.text', 'mid'); }); it('Restores focus to FTZ when clicking outside FTZ', () => { mount(<PropValues />); // wait for first focus to finish to avoid timing issue cy.focused().should('have.text', 'first'); // try to click on button outside FTZ cy.contains('before').realClick(); // it focuses first button inside FTZ instead cy.focused().should('have.text', 'first'); // and the click isn't respected cy.get('#buttonClicked').should('have.text', 'clicked '); }); it('Restores focus to FTZ when programmatically focusing outside FTZ', () => { mount(<PropValues />); // wait for first focus to finish to avoid timing issue cy.focused().should('have.text', 'first'); cy.contains('after').focus(); cy.focused().should('have.text', 'first'); }); it('Allows clicks outside FTZ with isClickableOutsideFocusTrap but restores focus inside', () => { mount(<PropValues isClickableOutsideFocusTrap />); // wait for first focus to finish to avoid timing issue cy.focused().should('have.text', 'first'); // click the button and verify it worked (the story updates the text when a button is clicked) cy.contains('before').realClick(); cy.get('#buttonClicked').should('have.text', 'clicked before'); // but focus is kept within the FTZ cy.focused().should('have.text', 'first'); }); it('Focuses first element when focus enters FTZ with tab', () => { mount(<PropValues disableFirstFocus forceFocusInsideTrap={false} />); // Start by programmatically focusing an element outside // (clicking it won't work in this case because that would send focus inside the trap) cy.contains('before').focus(); cy.focused().should('have.text', 'before'); // Tab to send focus to the first bumper, which passes focus on to the first element inside cy.realPress('Tab'); cy.focused().should('have.text', 'first'); }); it('Focuses last element when focus enters FTZ with shift+tab', () => { mount(<PropValues disableFirstFocus />); // Start by programmatically focusing an element outside // (clicking it won't work in this case because that would send focus inside the trap) cy.contains('after').focus(); cy.focused().should('have.text', 'after'); // Shift+tab will send focus to the last bumper, which passes focus on to the last element inside cy.realPress(['Shift', 'Tab']); cy.focused().should('have.text', 'last'); }); // TODO: investigate why this intermittently fails and re-enable. // It succeeds if you set disableFirstFocus: true, but the failure with first focus enabled // may reflect an actual bug in the function component conversion. Also, the intermittent // failure may indicate a timing issue with either the effects within FTZ, or with cypress. xit('Does not restore focus to FTZ when forceFocusInsideTrap is false', () => { mount(<PropValues forceFocusInsideTrap />); // wait for first focus to finish to avoid timing issue cy.focused().should('have.text', 'first'); // click a button outside => respected cy.contains('after').realClick(); cy.focused().should('have.text', 'after'); // focus back inside cy.contains('mid').realClick(); cy.focused().should('have.text', 'mid'); // programmatic focus outside => respected cy.contains('after').focus(); cy.focused().should('have.text', 'after'); }); it('Does not focus first on mount while disabled', () => { mount(<PropValues disabled />); // verify story rendered (to make sure we're not checking the base state of the page) cy.contains('first').should('exist'); cy.focused().should('not.exist'); }); it('Focuses on firstFocusableSelector on mount', () => { mount(<PropValues firstFocusableSelector="last-class" />); cy.focused().should('have.text', 'last'); }); it('Does not focus on firstFocusableSelector on mount while disabled', () => { mount(<PropValues firstFocusableSelector="last-class" disabled />); // verify story rendered (to make sure we're not checking the base state of the page) cy.contains('first').should('exist'); cy.focused().should('not.exist'); }); it('Falls back to first focusable element with invalid firstFocusableSelector', () => { mount(<PropValues firstFocusableSelector="invalidSelector" />); cy.focused().should('have.text', 'first'); }); it('Focuses on firstFocusableTarget selector on mount', () => { mount(<PropValues firstFocusableTarget="#last" />); cy.focused().should('have.text', 'last'); }); it('Focuses on firstFocusableTarget callback on mount', () => { // eslint-disable-next-line react/jsx-no-bind mount(<PropValues firstFocusableTarget={element => element.querySelector('#last')} />); cy.focused().should('have.text', 'last'); }); it('Does not focus on firstFocusableTarget selector on mount while disabled', () => { mount(<PropValues firstFocusableTarget="#last" disabled />); // verify story rendered (to make sure we're not checking the base state of the page) cy.contains('first').should('exist'); cy.focused().should('not.exist'); }); it('Does not focus on firstFocusableTarget callback on mount while disabled', () => { // eslint-disable-next-line react/jsx-no-bind mount(<PropValues firstFocusableTarget={element => element.querySelector('#last')} disabled />); // verify story rendered (to make sure we're not checking the base state of the page) cy.contains('first').should('exist'); cy.focused().should('not.exist'); }); it('Falls back to first focusable element with invalid firstFocusableTarget selector', () => { mount(<PropValues firstFocusableTarget=".invalidSelector" />); cy.focused().should('have.text', 'first'); }); it('Falls back to first focusable element with invalid firstFocusableTarget callback', () => { // eslint-disable-next-line react/jsx-no-bind mount(<PropValues firstFocusableTarget={() => null} />); cy.focused().should('have.text', 'first'); }); }); describe('Tab and shift-tab wrap at extreme ends of the FTZ', () => { const TabWrappingButtonFocusZone = () => { return ( <div className={rootClass}> <FocusTrapZone forceFocusInsideTrap={false}> <div> <button>first</button> </div> <FocusZone direction={FocusZoneDirection.horizontal}> <div> <button>fzFirst</button> </div> <div> <div> <button>fzMid1</button> <button>fzMid2</button> <button>fzLast</button> </div> </div> </FocusZone> </FocusTrapZone> </div> ); }; const TabWrappingMultiFocusZone = () => { return ( <div className={rootClass}> <FocusTrapZone forceFocusInsideTrap={false}> <FocusZone direction={FocusZoneDirection.horizontal}> <div> <button>fz1First</button> </div> <div> <button>fz1Mid</button> </div> <div> <button>fz1Last</button> </div> </FocusZone> <FocusZone direction={FocusZoneDirection.horizontal}> <div> <div> <button>fz2First</button> <button>fz2Mid</button> <button>fz2Last</button> </div> </div> </FocusZone> </FocusTrapZone> </div> ); }; const TabWrappingFocusZoneBumpers = () => { return ( <div className={rootClass}> <button>before</button> <FocusTrapZone forceFocusInsideTrap={false}> <FocusZone direction={FocusZoneDirection.horizontal}> <button>fz1First</button> <button>fz1Mid</button> <button>fz1Last</button> </FocusZone> <button>mid</button> <FocusZone direction={FocusZoneDirection.horizontal}> <button>fz2First</button> <button>fz2Mid</button> <button>fz2Last</button> </FocusZone> </FocusTrapZone> <button>after</button> </div> ); }; it('can tab between a button and a FocusZone', () => { mount(<TabWrappingButtonFocusZone />); // initial focus goes to the button cy.focused().should('have.text', 'first'); // shift+tab to focus first bumper => wraps to FocusZone => first button inside it cy.realPress(['Shift', 'Tab']); cy.focused().should('have.text', 'fzFirst'); // tab to focus last bumper => wraps to first button cy.realPress('Tab'); cy.focused().should('have.text', 'first'); }); it('can tab between multiple FocusZones with different button structures', () => { // This story has a FTZ containing two FocusZones (both containing buttons) mount(<TabWrappingMultiFocusZone />); // initial focus goes into the first FocusZone cy.focused().should('have.text', 'fz1First'); // shift+tab to focus first bumper => wraps to second FocusZone => first button inside it cy.realPress(['Shift', 'Tab']); cy.focused().should('have.text', 'fz2First'); // tab to focus last bumper => wraps to first FocusZone => first button inside it cy.realPress('Tab'); cy.focused().should('have.text', 'fz1First'); }); it( 'can trap focus when FTZ bookmark elements are FocusZones, ' + 'and those elements have inner elements focused that are not the first inner element', () => { // This story has a FTZ containing a FocusZone (with buttons), a button, and another FocusZone (with buttons). // "Bookmark" refers to the first and last elements inside the FTZ. mount(<TabWrappingFocusZoneBumpers />); // wait for first focus to finish to avoid timing issue cy.focused().should('have.text', 'fz1First'); // Focus the middle button in the first FZ. cy.contains('fz1First').click().realPress('ArrowRight'); cy.focused().should('have.text', 'fz1Mid'); // Focus the middle button in the second FZ. cy.contains('fz2Mid').click().realPress('ArrowRight'); cy.focused().should('have.text', 'fz2Last'); // tab to focus last bumper => wraps to first FocusZone => previously focused button inside it cy.realPress('Tab'); cy.focused().should('have.text', 'fz1Mid'); // shift+tab to focus first bumper => wraps to last FocusZone => previously focused button inside it cy.realPress(['Shift', 'Tab']); cy.focused().should('have.text', 'fz2Last'); }, ); }); describe('Tab and shift-tab when the FTZ contains 0 tabbable items', () => { const NoTabbableItems = (props: IFocusTrapZoneProps) => { return ( // don't render until props have been set <div className={rootClass}> <button>before</button> <FocusTrapZone forceFocusInsideTrap {...props}> <button tabIndex={-1}>first</button> <button tabIndex={-1}>mid</button> <button tabIndex={-1}>last</button> </FocusTrapZone> <button>after</button> </div> ); }; it('focuses first focusable element when focusing first bumper', () => { mount(<NoTabbableItems />); // wait for first focus to finish to avoid timing issue cy.focused().should('have.text', 'first'); cy.contains('last').realClick(); cy.focused().should('have.text', 'last'); // shift+tab focuses the first bumper (since the buttons inside aren't keyboard-focusable) // => sends focus to first element cy.realPress(['Shift', 'Tab']); cy.focused().should('have.text', 'first'); }); it('focuses first focusable element when focusing last bumper', () => { mount(<NoTabbableItems />); // wait for first focus to finish to avoid timing issue cy.focused().should('have.text', 'first'); cy.contains('mid').realClick(); cy.focused().should('have.text', 'mid'); // tab wraps around to focus first bumper (??) => sends focus to first element cy.realPress('Tab'); cy.focused().should('have.text', 'first'); }); it('focuses first focusable element when focusing outside of FTZ with 0 tabbable items', () => { mount(<NoTabbableItems />); // wait for first focus to finish to avoid timing issue cy.focused().should('have.text', 'first'); cy.contains('mid').realClick(); cy.focused().should('have.text', 'mid'); // try to focus on button outside FTZ cy.contains('before').realClick(); // it focuses first button inside FTZ instead cy.focused().should('have.text', 'first'); }); it('focuses previously focused element when focusing outside of FTZ with 0 tabbable items', () => { mount(<NoTabbableItems focusPreviouslyFocusedInnerElement />); // wait for first focus to finish to avoid timing issue cy.focused().should('have.text', 'first'); cy.contains('mid').realClick(); cy.focused().should('have.text', 'mid'); // try to focus on button outside FTZ cy.contains('before').realClick(); // it focuses last focused button inside FTZ instead cy.focused().should('have.text', 'mid'); }); }); describe('Imperatively focusing the FTZ', () => { let imperativeFocus: () => void = () => null; const ImperativeFocus = (props: IFocusTrapZoneProps) => { const focusTrapZoneRef = React.useRef<IFocusTrapZone>(null); React.useEffect(() => { imperativeFocus = () => focusTrapZoneRef.current?.focus(); }, []); return ( // don't render until props have been set props && ( <div className={rootClass}> <FocusTrapZone disableFirstFocus componentRef={focusTrapZoneRef} {...props}> <button>first</button> <FocusZone> <button>mid</button> <button>last</button> </FocusZone> </FocusTrapZone> <button>after</button> </div> ) ); }; it('goes to previously focused element when focusing the FTZ', async () => { mount(<ImperativeFocus focusPreviouslyFocusedInnerElement />); // Manually focusing FTZ when FTZ has never had focus within should go to 1st focusable inner element. imperativeFocus(); cy.focused().should('have.text', 'first'); // Focus inside the trap zone, not the first element. cy.contains('last').realClick(); cy.focused().should('have.text', 'last'); // Focus outside the trap zone cy.contains('after').realClick(); cy.focused().should('have.text', 'after'); // Manually focusing FTZ should return to originally focused inner element. imperativeFocus(); cy.focused().should('have.text', 'last'); }); it('goes to first focusable element when focusing the FTZ', async () => { mount(<ImperativeFocus focusPreviouslyFocusedInnerElement={false} />); // Manually focusing FTZ when FTZ has never had focus within should go to 1st focusable inner element. imperativeFocus(); cy.focused().should('have.text', 'first'); // Focus inside the trap zone, not the first element. cy.contains('last').realClick(); cy.focused().should('have.text', 'last'); // Focus outside the trap zone cy.contains('after').realClick(); cy.focused().should('have.text', 'after'); // Manually focusing FTZ should go to the first focusable element. imperativeFocus(); cy.focused().should('have.text', 'first'); }); }); describe('focus stack', () => { const getFocusStack: NonNullable<FTZTestGlobals['getFocusStack']> = () => FocusTrapZone.focusStack; const FocusStack = () => { // Whether to render each FocusTrapZone const [shouldRender, setShouldRender] = React.useState([true, false, false, false, false]); const updateFTZ = (num: 1 | 2 | 3 | 4, newValue: boolean) => { setShouldRender(prevValues => { const newValues = [...prevValues]; newValues[num] = newValue; return newValues; }); }; // React.useEffect(() => { // getFocusStack = () => FocusTrapZone.focusStack; // }, []); return ( <div className={rootClass}> <FocusTrapZone id="ftz0"> ftz0 <button onClick={() => updateFTZ(1, true)}>add ftz1</button> <button onClick={() => updateFTZ(3, true)}>add ftz3</button> <button onClick={() => updateFTZ(4, true)}>add ftz4</button> </FocusTrapZone> {shouldRender[1] && ( <FocusTrapZone id="ftz1"> ftz1 <button onClick={() => updateFTZ(2, true)}>add ftz2</button> </FocusTrapZone> )} {shouldRender[2] && ( <FocusTrapZone id="ftz2"> ftz2 <button onClick={() => updateFTZ(1, false)}>remove ftz1</button> <button onClick={() => updateFTZ(2, false)}>remove ftz2</button> </FocusTrapZone> )} {shouldRender[3] && ( <FocusTrapZone id="ftz3" forceFocusInsideTrap={false}> ftz3 <button onClick={() => updateFTZ(3, false)}>remove ftz3</button> </FocusTrapZone> )} {shouldRender[4] && ( <FocusTrapZone id="ftz4" disabled> ftz4 </FocusTrapZone> )} </div> ); }; it('maintains a proper stack of FocusTrapZones as more are mounted/unmounted', () => { // TODO: try to find a way to test this concept without looking this deeply into the implementation // or using global functions // // This test needs to look at FocusTrapZone.focusStack (at least with current implementation), // and the easiest way to do that in cypress is having the story expose a getFocusStack() global. // (Rendering FocusTrapZone.focusStack in the story doesn't work because updates to the array // don't trigger React updates, so it gets out of date.) mount(<FocusStack />); // There should now be one focus trap zone. cy.get('#ftz0').should('exist'); cy.focused().should('have.text', 'add ftz1'); // first button in ftz0 cy.then(() => expect(getFocusStack()).to.deep.equal(['ftz0'])); // add ftz1 and verify there are now two FTZs in the stack cy.contains('add ftz1').realClick(); cy.get('#ftz1').should('exist'); cy.focused().should('have.text', 'add ftz2'); // first button in ftz1 cy.then(() => expect(getFocusStack()).to.deep.equal(['ftz0', 'ftz1'])); // add ftz2 => three FTZ in stack cy.contains('add ftz2').realClick(); cy.get('#ftz2').should('exist'); cy.focused().should('have.text', 'remove ftz1'); // first button in ftz2 cy.then(() => expect(getFocusStack()).to.deep.equal(['ftz0', 'ftz1', 'ftz2'])); // remove ftz1 => two FTZ in stack cy.contains('remove ftz1').realClick(); cy.get('#ftz1').should('not.exist'); cy.focused().should('have.text', 'remove ftz1'); // first button in ftz2 cy.then(() => expect(getFocusStack()).to.deep.equal(['ftz0', 'ftz2'])); // remove ftz2 => one FTZ in stack cy.contains('remove ftz2').realClick(); cy.get('#ftz2').should('not.exist'); // expect(getFocusStack()).to.deep.equal(['ftz0']); // ftz2 will try to return focus to its initiator (the button in ftz1), but that button is gone, // so focus goes to document.body cy.focused().should('not.exist'); // add ftz3 => two FTZ in stack // (even though ftz3 has forceFocusInsideTrap=false) cy.contains('add ftz3').realClick(); cy.get('#ftz3').should('exist'); cy.focused().should('have.text', 'remove ftz3'); // first button in ftz3 cy.then(() => expect(getFocusStack()).to.deep.equal(['ftz0', 'ftz3'])); // remove ftz3 => one FTZ in stack cy.contains('remove ftz3').realClick(); cy.get('#ftz3').should('not.exist'); cy.then(() => expect(getFocusStack()).to.deep.equal(['ftz0'])); // ftz3 returns focus to initiator after unmount cy.focused().should('have.text', 'add ftz3'); // add ftz4 => still only one FTZ in stack because ftz4 is disabled cy.contains('add ftz4').realClick(); cy.get('#ftz4').should('exist'); cy.focused().should('have.text', 'add ftz4'); // clicked button in ftz0 cy.then(() => expect(getFocusStack()).to.deep.equal(['ftz0'])); }); }); });
the_stack
interface List<T> extends Array<T> {} interface Type {} interface _ComponentArg { /** * The CSS selector that triggers the instantiation of a directive. * * Angular only allows directives to trigger on CSS selectors that do not cross element boundaries. * * `selector` may be declared as one of the following: * * - `element-name`: select by element name. * - `.class`: select by class name. * - `[attribute]`: select by attribute name. * - `[attribute=value]`: select by attribute name and value. * - `:not(sub_selector)`: select only if the element does not match the `sub_selector`. * - `selector1, selector2`: select if either `selector1` or `selector2` matches. * * * ## Example * * Suppose we have a directive with an `input[type=text]` selector. * * And the following HTML: * * ```html * <form> * <input type="text"> * <input type="radio"> * <form> * ``` * * The directive would only be instantiated on the `<input type="text">` element. * */ selector: string; /** * Enumerates the set of properties that accept data binding for a directive. * * The `properties` property defines a set of `directiveProperty` to `bindingProperty` * key-value pairs: * * - `directiveProperty` specifies the component property where the value is written. * - `bindingProperty` specifies the DOM property where the value is read from. * * You can include a {@link Pipe} when specifying a `bindingProperty` to allow for data transformation and structural * change detection of the value. These pipes will be evaluated in the context of this component. * * * ## Syntax * * ``` * @Directive({ * properties: { * 'directiveProperty1': 'bindingProperty1', * 'directiveProperty2': 'bindingProperty2 | pipe1 | ...', * ... * } * } * ``` * * * ## Basic Property Binding * * We can easily build a simple `Tooltip` directive that exposes a `tooltip` property, which can be used in templates * with standard Angular syntax. For example: * * ``` * @Directive({ * selector: '[tooltip]', * properties: { * 'text': 'tooltip' * } * }) * class Tooltip { * set text(text) { * // This will get called every time the 'tooltip' binding changes with the new value. * } * } * ``` * * We can then bind to the `tooltip' property as either an expression (`someExpression`) or as a string literal, as * shown in the HTML template below: * * ```html * <div [tooltip]="someExpression">...</div> * <div tooltip="Some Text">...</div> * ``` * * Whenever the `someExpression` expression changes, the `properties` declaration instructs * Angular to update the `Tooltip`'s `text` property. * * * * ## Bindings With Pipes * * You can also use pipes when writing binding definitions for a directive. * * For example, we could write a binding that updates the directive on structural changes, rather than on reference * changes, as normally occurs in change detection. * * See {@link Pipe} and {@link keyValDiff} documentation for more details. * * ``` * @Directive({ * selector: '[class-set]', * properties: { * 'classChanges': 'classSet | keyValDiff' * } * }) * class ClassSet { * set classChanges(changes:KeyValueChanges) { * // This will get called every time the `class-set` expressions changes its structure. * } * } * ``` * * The template that this directive is used in may also contain its own pipes. For example: * * ```html * <div [class-set]="someExpression | somePipe"> * ``` * * In this case, the two pipes compose as if they were inlined: `someExpression | somePipe | keyValDiff`. * */ properties?: Object; /** * Specifies which DOM hostListeners a directive listens to. * * The `hostListeners` property defines a set of `event` to `method` key-value pairs: * * - `event1`: the DOM event that the directive listens to. * - `statement`: the statement to execute when the event occurs. * If the evalutation of the statement returns `false`, then `preventDefault`is applied on the DOM event. * * To listen to global events, a target must be added to the event name. * The target can be `window`, `document` or `body`. * * When writing a directive event binding, you can also refer to the following local variables: * - `$event`: Current event object which triggered the event. * - `$target`: The source of the event. This will be either a DOM element or an Angular directive. * (will be implemented in later release) * * * ## Syntax * * ``` * @Directive({ * hostListeners: { * 'event1': 'onMethod1(arguments)', * 'target:event2': 'onMethod2(arguments)', * ... * } * } * ``` * * ## Basic Event Binding: * * Suppose you want to write a directive that triggers on `change` events in the DOM and on `resize` events in window. * You would define the event binding as follows: * * ``` * @Directive({ * selector: 'input', * hostListeners: { * 'change': 'onChange($event)', * 'window:resize': 'onResize($event)' * } * }) * class InputDirective { * onChange(event:Event) { * } * onResize(event:Event) { * } * } * ``` * * Here the `onChange` method of `InputDirective` is invoked whenever the DOM element fires the 'change' event. * */ hostListeners?: Object; /** * Defines the set of injectable objects that are visible to a Component and its children. * * The `injectables` defined in the Component annotation allow you to configure a set of bindings for the component's * injector. * * When a component is instantiated, Angular creates a new child Injector, which is configured with the bindings in * the Component `injectables` annotation. The injectable objects then become available for injection to the component * itself and any of the directives in the component's template, i.e. they are not available to the directives which * are children in the component's light DOM. * * * The syntax for configuring the `injectables` injectable is identical to {@link Injector} injectable configuration. * See {@link Injector} for additional detail. * * * ## Simple Example * * Here is an example of a class that can be injected: * * ``` * class Greeter { * greet(name:string) { * return 'Hello ' + name + '!'; * } * } * * @Component({ * selector: 'greet', * injectables: [ * Greeter * ] * }) * @View({ * template: `{{greeter.greet('world')}}!`, * directives: Child * }) * class HelloWorld { * greeter:Greeter; * * constructor(greeter:Greeter) { * this.greeter = greeter; * } * } * ``` */ injectables?: List<any>; /** * Specifies a set of lifecycle hostListeners in which the directive participates. * * See {@link onChange}, {@link onDestroy}, {@link onAllChangesDone} for details. */ lifecycle?: List<any>; /** * Defines the used change detection strategy. * * When a component is instantiated, Angular creates a change detector, which is responsible for propagating * the component's bindings. * * The `changeDetection` property defines, whether the change detection will be checked every time or only when the component * tells it to do so. */ changeDetection?: string; } interface _ViewArg { /** * Specifies a template URL for an angular component. * * NOTE: either `templateUrl` or `template` should be used, but not both. */ templateUrl?: string; /** * Specifies an inline template for an angular component. * * NOTE: either `templateUrl` or `template` should be used, but not both. */ template?: string; /** * Specifies a list of directives that can be used within a template. * * Directives must be listed explicitly to provide proper component encapsulation. */ directives?: List<Type>; } declare module "angular2/angular2" { /** * Bootstrapping for Angular applications. * * You instantiate an Angular application by explicitly specifying a component to use as the root component for your * application via the `bootstrap()` method. * * ## Simple Example * * Assuming this `index.html`: * * ```html * <html> * <!-- load Angular script tags here. --> * <body> * <my-app>loading...</my-app> * </body> * </html> * ``` * * An application is bootstrapped inside an existing browser DOM, typically `index.html`. Unlike Angular 1, Angular 2 * does not compile/process bindings in `index.html`. This is mainly for security reasons, as well as architectural * changes in Angular 2. This means that `index.html` can safely be processed using server-side technologies such as * bindings. Bindings can thus use double-curly `{{ syntax }}` without collision from Angular 2 component double-curly * `{{ syntax }}`. * * We can use this script code: * * ``` * @Component({ * selector: 'my-app' * }) * @View({ * template: 'Hello {{ name }}!' * }) * class MyApp { * name:string; * * constructor() { * this.name = 'World'; * } * } * * main() { * return bootstrap(MyApp); * } * ``` * * When the app developer invokes `bootstrap()` with the root component `MyApp` as its argument, Angular performs the * following tasks: * * 1. It uses the component's `selector` property to locate the DOM element which needs to be upgraded into * the angular component. * 2. It creates a new child injector (from the platform injector) and configures the injector with the component's * `injectables`. Optionally, you can also override the injector configuration for an app by invoking * `bootstrap` with the `componentInjectableBindings` argument. * 3. It creates a new `Zone` and connects it to the angular application's change detection domain instance. * 4. It creates a shadow DOM on the selected component's host element and loads the template into it. * 5. It instantiates the specified component. * 6. Finally, Angular performs change detection to apply the initial data bindings for the application. * * * ## Instantiating Multiple Applications on a Single Page * * There are two ways to do this. * * * ### Isolated Applications * * Angular creates a new application each time that the `bootstrap()` method is invoked. When multiple applications * are created for a page, Angular treats each application as independent within an isolated change detection and * `Zone` domain. If you need to share data between applications, use the strategy described in the next * section, "Applications That Share Change Detection." * * * ### Applications That Share Change Detection * * If you need to bootstrap multiple applications that share common data, the applications must share a common * change detection and zone. To do that, create a meta-component that lists the application components in its template. * By only invoking the `bootstrap()` method once, with the meta-component as its argument, you ensure that only a * single change detection zone is created and therefore data can be shared across the applications. * * * ## Platform Injector * * When working within a browser window, there are many singleton resources: cookies, title, location, and others. * Angular services that represent these resources must likewise be shared across all Angular applications that * occupy the same browser window. For this reason, Angular creates exactly one global platform injector which stores * all shared services, and each angular application injector has the platform injector as its parent. * * Each application has its own private injector as well. When there are multiple applications on a page, Angular treats * each application injector's services as private to that application. * * * # API * - `appComponentType`: The root component which should act as the application. This is a reference to a `Type` * which is annotated with `@Component(...)`. * - `componentInjectableBindings`: An additional set of bindings that can be added to `injectables` for the * {@link Component} to override default injection behavior. * - `errorReporter`: `function(exception:any, stackTrace:string)` a default error reporter for unhandled exceptions. * * Returns a `Promise` with the application`s private {@link Injector}. * */ function bootstrap(appComponentType: any): void; /** * Declare reusable UI building blocks for an application. * * Each Angular component requires a single `@Component` and at least one `@View` annotation. The `@Component` * annotation specifies when a component is instantiated, and which properties and hostListeners it binds to. * * When a component is instantiated, Angular * - creates a shadow DOM for the component. * - loads the selected template into the shadow DOM. * - creates a child {@link Injector} which is configured with the `injectables` for the {@link Component}. * * All template expressions and statements are then evaluated against the component instance. * * For details on the `@View` annotation, see {@link View}. * * ## Example * * ``` * @Component({ * selector: 'greet' * }) * @View({ * template: 'Hello {{name}}!' * }) * class Greet { * name: string; * * constructor() { * this.name = 'World'; * } * } * ``` * * * Dynamically loading a component at runtime: * * Regular Angular components are statically resolved. Dynamic components allows to resolve a component at runtime * instead by providing a placeholder into which a regular Angular component can be dynamically loaded. Once loaded, * the dynamically-loaded component becomes permanent and cannot be changed. * Dynamic components are declared just like components, but without a `@View` annotation. * * * ## Example * * Here we have `DynamicComp` which acts as the placeholder for `HelloCmp`. At runtime, the dynamic component * `DynamicComp` requests loading of the `HelloCmp` component. * * There is nothing special about `HelloCmp`, which is a regular Angular component. It can also be used in other static * locations. * * ``` * @Component({ * selector: 'dynamic-comp' * }) * class DynamicComp { * helloCmp:HelloCmp; * constructor(loader:DynamicComponentLoader, location:ElementRef) { * loader.load(HelloCmp, location).then((helloCmp) => { * this.helloCmp = helloCmp; * }); * } * } * * @Component({ * selector: 'hello-cmp' * }) * @View({ * template: "{{greeting}}" * }) * class HelloCmp { * greeting:string; * constructor() { * this.greeting = "hello"; * } * } * ``` * */ function Component(arg: _ComponentArg): (target: any) => any; /** * Declares the available HTML templates for an application. * * Each angular component requires a single `@Component` and at least one `@View` annotation. The @View * annotation specifies the HTML template to use, and lists the directives that are active within the template. * * When a component is instantiated, the template is loaded into the component's shadow root, and the * expressions and statements in the template are evaluated against the component. * * For details on the `@Component` annotation, see {@link Component}. * * ## Example * * ``` * @Component({ * selector: 'greet' * }) * @View({ * template: 'Hello {{name}}!', * directives: [GreetUser, Bold] * }) * class Greet { * name: string; * * constructor() { * this.name = 'World'; * } * } * ``` * */ function View(arg: _ViewArg): (target: any) => any; /** * The `For` directive instantiates a template once per item from an iterable. The context for each * instantiated template inherits from the outer context with the given loop variable set to the * current item from the iterable. * * It is possible to alias the `index` to a local variable that will be set to the current loop * iteration in the template context. * * When the contents of the iterator changes, `For` makes the corresponding changes to the DOM: * * * When an item is added, a new instance of the template is added to the DOM. * * When an item is removed, its template instance is removed from the DOM. * * When items are reordered, their respective templates are reordered in the DOM. * * # Example * * ``` * <ul> * <li *ng-for="#error of errors; #i = index"> * Error {{i}} of {{errors.length}}: {{error.message}} * </li> * </ul> * ``` * * # Syntax * * - `<li *ng-for="#item of items; #i = index">...</li>` * - `<li template="ng-for #item of items; #i=index">...</li>` * - `<template [ng-for]="#item" [of]="items" #i="index"><li>...</li></template>` * */ function NgFor(): void; /** * Removes or recreates a portion of the DOM tree based on an {expression}. * * If the expression assigned to `if` evaluates to a false value then the element is removed from the * DOM, otherwise a clone of the element is reinserted into the DOM. * * # Example: * * ``` * <div *ng-if="errorCount > 0" class="error"> * <!-- Error message displayed when the errorCount property on the current context is greater than 0. --> * {{errorCount}} errors detected * </div> * ``` * * # Syntax * * - `<div *ng-if="condition">...</div>` * - `<div template="ng-if condition">...</div>` * - `<template [ng-if]="condition"><div>...</div></template>` * */ function NgIf(): void; /** * The `NonBindable` directive tells Angular not to compile or bind the contents of the current * DOM element. This is useful if the element contains what appears to be Angular directives and * bindings but which should be ignored by Angular. This could be the case if you have a site that * displays snippets of code, for instance. * * Example: * * ``` * <div>Normal: {{1 + 2}}</div> // output "Normal: 3" * <div ng-non-bindable>Ignored: {{1 + 2}}</div> // output "Ignored: {{1 + 2}}" * ``` * */ function NgNonBindable(): void; /** * The `Switch` directive is used to conditionally swap DOM structure on your template based on a * scope expression. * Elements within `Switch` but without `SwitchWhen` or `SwitchDefault` directives will be * preserved at the location as specified in the template. * * `Switch` simply chooses nested elements and makes them visible based on which element matches * the value obtained from the evaluated expression. In other words, you define a container element * (where you place the directive), place an expression on the **`[switch]="..."` attribute**), * define any inner elements inside of the directive and place a `[switch-when]` attribute per * element. * The when attribute is used to inform Switch which element to display when the expression is * evaluated. If a matching expression is not found via a when attribute then an element with the * default attribute is displayed. * * # Example: * * ``` * <ANY [switch]="expression"> * <template [switch-when]="whenExpression1">...</template> * <template [switch-when]="whenExpression1">...</template> * <template [switch-default]>...</template> * </ANY> * ``` * */ function NgSwitch(): void; var Observable: any; var EventEmitter: any; var DomRenderer: any; var DOCUMENT_TOKEN: any; var ASTWithSource: any; var AST: any; var AstTransformer: any; var AccessMember: any; var LiteralArray: any; var ImplicitReceiver: any; var Lexer: any; var Parser: any; var Locals: any; var ExpressionChangedAfterItHasBeenChecked: any; var ChangeDetectionError: any; var ProtoChangeDetector: any; var ChangeDispatcher: any; var ChangeDetector: any; var ChangeDetection: any; var CHECK_ONCE: any; var CHECK_ALWAYS: any; var DETACHED: any; var CHECKED: any; var ON_PUSH: any; var DEFAULT: any; var DynamicProtoChangeDetector: any; var JitProtoChangeDetector: any; var BindingRecord: any; var DirectiveIndex: any; var DirectiveRecord: any; var DynamicChangeDetector: any; var ChangeDetectorRef: any; var PipeRegistry: any; var uninitialized: any; var WrappedValue: any; var Pipe: any; var NullPipe: any; var NullPipeFactory: any; var defaultPipes: any; var DynamicChangeDetection: any; var JitChangeDetection: any; var defaultPipeRegistry: any; var ___esModule: any; var ViewRef: any; var ProtoViewRef: any; var ViewContainerRef: any; var ElementRef: any; var AncestorAnnotation: any; var ParentAnnotation: any; interface OnChange {} var ViewAnnotation: any; interface ApplicationRef {} var appComponentRefToken: any; var appComponentAnnotatedTypeToken: any; var QueryAnnotation: any; var AttributeAnnotation: any; interface QueryList {} interface CompilerCache {} interface Compiler {} interface TemplateLoader {} interface ShadowDomStrategy {} interface NativeShadowDomStrategy {} interface EmulatedScopedShadowDomStrategy {} interface EmulatedUnscopedShadowDomStrategy {} interface ComponentRef {} interface DynamicComponentLoader {} var ComponentAnnotation: any; var DirectiveAnnotation: any; var onDestroy: any; var onChange: any; var onAllChangesDone: any; var Directive: any; var Ancestor: any; var Parent: any; var Attribute: any; var Query: any; var coreDirectives: any; interface CSSClass {} interface NgSwitchWhen {} interface NgSwitchDefault {} var VALID: any; var INVALID: any; interface Control {} interface ControlGroup {} interface ControlArray {} interface DefaultValueAccessor {} interface CheckboxControlValueAccessor {} interface ControlDirective {} interface ControlGroupDirective {} var formDirectives: any; interface Validators {} interface RequiredValidatorDirective {} interface FormBuilder {} interface EventBinding {} interface ElementBinder {} interface DirectiveBinder {} interface ProtoViewDto {} interface DirectiveMetadata {} interface RenderProtoViewRef {} interface RenderViewRef {} interface ViewDefinition {} interface RenderCompiler {} interface Renderer {} interface EventDispatcher {} } declare module "angular2/di" { /** * Provides an API for imperatively constructing {@link Binding}s. * * This is only relevant for JavaScript. See {@link BindingBuilder}. * * ## Example * * ```javascript * bind(MyInterface).toClass(MyClass) * * ``` * */ function bind(token: any): any; var Injector: any; var Binding: any; var ResolvedBinding: any; var Dependency: any; var Key: any; var KeyRegistry: any; var TypeLiteral: any; var NoBindingError: any; var AbstractBindingError: any; var AsyncBindingError: any; var CyclicDependencyError: any; var InstantiationError: any; var InvalidBindingError: any; var NoAnnotationError: any; var OpaqueToken: any; var ___esModule: any; var InjectAnnotation: any; var InjectPromiseAnnotation: any; var InjectLazyAnnotation: any; var OptionalAnnotation: any; var InjectableAnnotation: any; var DependencyAnnotation: any; var Inject: any; var InjectPromise: any; var InjectLazy: any; var Optional: any; var Injectable: any; } declare module "angular2/router" { var Router: any; var RouterOutlet: any; var RouterLink: any; var RouteParams: any; var routerInjectables: any; var RouteConfigAnnotation: any; var RouteConfig: any; }
the_stack
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Config } from '../../../environments/environment'; import { PriceListVO, TaxVO, TaxConfigVO, PromotionVO, PromotionCouponVO, CartVO, PromotionTestVO, SearchContextVO, SearchResultVO, AttributeVO, Pair } from '../model/index'; import { ErrorEventBus } from './error-event-bus.service'; import { Util } from './util'; import { LogUtil } from './../log/index'; import { catchError, map } from 'rxjs/operators'; import { Observable, throwError } from 'rxjs'; /** * Shop service has all methods to work with shop. */ @Injectable() export class PricingService { private _serviceBaseUrl = Config.API + 'service/pricing'; // URL to web api /** * Construct service, which has methods to work with information related to shop(s). * @param http http client. */ constructor (private http: HttpClient) { LogUtil.debug('PricingService constructed'); } /** * Get list of all price lists, which are accessible to manage or view, * @returns {Observable<T>} */ getFilteredPriceLists(filter:SearchContextVO):Observable<SearchResultVO<PriceListVO>> { let body = JSON.stringify(filter); return this.http.post<SearchResultVO<PriceListVO>>(this._serviceBaseUrl + '/prices/search', body, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } /** * Get price list, which are accessible to manage or view, * @returns {Observable<T>} */ getPriceListById(priceId:number):Observable<PriceListVO> { return this.http.get<PriceListVO>(this._serviceBaseUrl + '/prices/' + priceId) .pipe(catchError(this.handleError)); } /** * Create/update price list. * @param price price list * @returns {Observable<T>} */ savePriceList(price:PriceListVO):Observable<PriceListVO> { let body = JSON.stringify(price); if (price.skuPriceId > 0) { return this.http.put<PriceListVO>(this._serviceBaseUrl + '/prices', body, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } else { return this.http.post<PriceListVO>(this._serviceBaseUrl + '/prices', body, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } } /** * Remove price list. * @param price list price list * @returns {Observable<T>} */ removePriceList(price:PriceListVO):Observable<boolean> { return this.http.delete(this._serviceBaseUrl + '/prices/' + price.skuPriceId, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError), map(res => true)); } /** * Get list of all taxes, which are accessible to manage or view, * @returns {Observable<T>} */ getFilteredTax(filter:SearchContextVO):Observable<SearchResultVO<TaxVO>> { let body = JSON.stringify(filter); return this.http.post<SearchResultVO<TaxVO>>(this._serviceBaseUrl + '/taxes/search', body, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } /** * Get tax, which are accessible to manage or view, * @returns {Observable<T>} */ getTaxById(taxId:number):Observable<TaxVO> { return this.http.get<TaxVO>(this._serviceBaseUrl + '/taxes/' + taxId, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } /** * Create/update tax. * @param tax tax * @returns {Observable<T>} */ saveTax(tax:TaxVO):Observable<TaxVO> { let body = JSON.stringify(tax); if (tax.taxId > 0) { return this.http.put<TaxVO>(this._serviceBaseUrl + '/taxes', body, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } else { return this.http.post<TaxVO>(this._serviceBaseUrl + '/taxes', body, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } } /** * Remove tax. * @param tax tax * @returns {Observable<T>} */ removeTax(tax:TaxVO):Observable<boolean> { return this.http.delete(this._serviceBaseUrl + '/taxes/' + tax.taxId, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError), map(res => true)); } /** * Get list of all tax configs, which are accessible to manage or view, * @returns {Observable<T>} */ getFilteredTaxConfig(filter:SearchContextVO):Observable<SearchResultVO<TaxConfigVO>> { let body = JSON.stringify(filter); return this.http.post<SearchResultVO<TaxConfigVO>>(this._serviceBaseUrl + '/taxconfigs/search', body, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } /** * Get tax config, which are accessible to manage or view, * @returns {Observable<T>} */ getTaxConfigById(taxConfigId:number):Observable<TaxConfigVO> { return this.http.get<TaxConfigVO>(this._serviceBaseUrl + '/taxconfigs/' + taxConfigId, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } /** * Create tax config. * @param taxConfig config * @returns {Observable<T>} */ createTaxConfig(taxConfig:TaxConfigVO):Observable<TaxConfigVO> { let body = JSON.stringify(taxConfig); return this.http.post<TaxConfigVO>(this._serviceBaseUrl + '/taxconfigs', body, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } /** * Remove tax config. * @param taxConfig tax config * @returns {Observable<T>} */ removeTaxConfig(taxConfig:TaxConfigVO):Observable<boolean> { return this.http.delete(this._serviceBaseUrl + '/taxconfigs/' + taxConfig.taxConfigId, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError), map(res => true)); } /** * Test rule for given shop in specified currency, * @returns {Observable<T>} */ testPromotions(test:PromotionTestVO):Observable<CartVO> { let body = JSON.stringify(test); return this.http.post<CartVO>(this._serviceBaseUrl + '/promotions/test', body, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } /** * Get promotions options, which are accessible to manage or view, * @returns {Observable<T>} */ getPromotionOptions():Observable<Pair<AttributeVO, AttributeVO[]>[]> { return this.http.get<Pair<AttributeVO, AttributeVO[]>[]>(this._serviceBaseUrl + '/promotions/options', { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } /** * Get list of all promotions, which are accessible to manage or view, * @returns {Observable<T>} */ getFilteredPromotions(filter:SearchContextVO):Observable<SearchResultVO<PromotionVO>> { let body = JSON.stringify(filter); return this.http.post<SearchResultVO<PromotionVO>>(this._serviceBaseUrl + '/promotions/search', body, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } /** * Get promotion, which are accessible to manage or view, * @returns {Observable<T>} */ getPromotionById(promotionId:number):Observable<PromotionVO> { return this.http.get<PromotionVO>(this._serviceBaseUrl + '/promotions/' + promotionId, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } /** * Create/update promotion. * @param promotion promotion * @returns {Observable<T>} */ savePromotion(promotion:PromotionVO):Observable<PromotionVO> { let body = JSON.stringify(promotion); if (promotion.promotionId > 0) { return this.http.put<PromotionVO>(this._serviceBaseUrl + '/promotions', body, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } else { return this.http.post<PromotionVO>(this._serviceBaseUrl + '/promotions', body, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } } /** * Remove promotion. * @param promotion promotion * @returns {Observable<T>} */ removePromotion(promotion:PromotionVO):Observable<boolean> { return this.http.delete(this._serviceBaseUrl + '/promotions/' + promotion.promotionId, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError), map(res => true)); } /** * Update promotion state. * @param promotion promotion * @param state enabled or disabled * @returns {Observable<T>} */ updatePromotionDisabledFlag(promotion:PromotionVO, state:boolean):Observable<boolean> { LogUtil.debug('PricingService change state promotion ' + promotion.promotionId + ' to ' + state ? 'online' : 'offline'); let body = JSON.stringify({ disabled: state }); return this.http.post(this._serviceBaseUrl + '/promotions/' + promotion.promotionId + '/status', body, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError), map(res => true)); } /** * Get list of all promotion coupons, which are accessible to manage or view, * @returns {Observable<T>} */ getFilteredPromotionCoupons(filter:SearchContextVO):Observable<SearchResultVO<PromotionCouponVO>> { let body = JSON.stringify(filter); return this.http.post<SearchResultVO<PromotionCouponVO>>(this._serviceBaseUrl + '/promotioncoupons/search', body, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError)); } /** * Create promotion coupons. * @param coupons coupons * @returns {Observable<T>} */ createPromotionCoupons(coupons:PromotionCouponVO):Observable<boolean> { let body = JSON.stringify(coupons); return this.http.post(this._serviceBaseUrl + '/promotioncoupons', body, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError), map(res => true)); } /** * Remove promotion coupon. * @param coupon coupon * @returns {Observable<T>} */ removePromotionCoupon(coupon:PromotionCouponVO):Observable<boolean> { return this.http.delete(this._serviceBaseUrl + '/promotioncoupons/' + coupon.promotioncouponId, { headers: Util.requestOptions() }) .pipe(catchError(this.handleError), map(res => true)); } private handleError (error:any) { LogUtil.error('PricingService Server error: ', error); ErrorEventBus.getErrorEventBus().emit(error); let message = Util.determineErrorMessage(error); return throwError(message.message || 'Server error'); } }
the_stack
"use strict"; import esprima = require("esprima"); import util = require("util"); import esutils = require("esutils"); import hoist = require("./ast-hoist"); import argfinder = require("./argfinder"); import escodegen = require("escodegen"); // debug import scoping = require("./scoping"); var BinaryOpRemap = { '<<': 'bit32.lshift', '>>>': 'bit32.rshift', '>>': 'bit32.arshift', '===': 'rawequal', '!==': 'rawequal', /* not added separately */ '&': 'bit32.band', '^': 'bit32.bxor', '|': 'bit32.bor', '+': '__PlusOp',// NOTE needs to be somehow duplicated in the runtime.eval '<': '__CmpLess', '<=': '__CmpLessEqual', '>': '__CmpGreater', '>=': '__CmpGreaterEqual', 'in': '__ContainsKey', 'instanceof': '__InstanceOf', }; var BinaryOpRemapValues = []; for (var x in BinaryOpRemap) { BinaryOpRemapValues.push(BinaryOpRemap[x]); } var Intrinsics = [ // NOTE needs to be somehow duplicated in the runtime.eval '__ToString', '__ToBoolean', '__ToPrimitive', '__ToObject', '__ToNumber', '__Get', '__Put', '__PlusOp', '__Delete', '__InstanceOf', '__CallMember', '__Call', '__Typeof', '__DefineFunction', '__New', '__ContainsKey', '__Sink', '__TernarySave', '__TernaryReplace', '__TernaryRestore', '__Iterate', '__RefCheck', '__MakeArguments', '__MakeArray', '__MakeObject', '__LastXpCall', 'rawset', 'rawget', 'Infinity', 'NaN', 'print', '', '', ]; function unique(arr) { var u = {}, a = []; for (var i = 0, l = arr.length; i < l; ++i) { if (!u.hasOwnProperty(arr[i])) { a.push(arr[i]); u[arr[i]] = 1; } } return a; } function EmitProgram(ast: esprima.Syntax.Program, emit: (s: string) => void, alloc: () => number) { // hack var scope = new scoping.ScopeStack(); scope.pushObjectIdent("__JsGlobalObjects", "program"); var identList = argfinder.analyze(ast.body); //console.log(util.inspect(identList)); scope.pushLexical(['__JsGlobalObjects', '__Singletons', 'undefined'].concat(identList.vars), ['eval'].concat(identList .funcs, BinaryOpRemapValues, Intrinsics), [], 'builtins-and-toplevels'); var fPredeclare = unique(identList.funcs); fPredeclare.forEach(function (f) { emit("local "); EmitName({ type: 'Identifier', name: f }, emit, alloc); emit("\r\n"); }); emit("\r\n-- BEGIN\r\n"); EmitBlock(ast, emit, alloc, scope, false); emit("\r\n-- END\r\n"); scope.popScope(); // for completeness } function EmitVariableDeclaration(ex: esprima.Syntax.VariableDeclaration, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { for (var i = 0; i < ex.declarations.length; i++) { var vd = ex.declarations[i]; EmitVariableDeclarator(vd, emit, alloc, scope); } } function EmitVariableDeclarator(vd: esprima.Syntax.VariableDeclarator, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { emit("local "); EmitName(vd.id, emit, alloc); // identifier emit(" = "); EmitExpression(vd.init, emit, alloc, scope, 0, false); emit("\r\n"); } function EmitExpression(ex: esprima.Syntax.Expression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack, statementContext: number, isRef: boolean) { if (!ex) { emit('nil'); return; } switch (ex.type) { case "CallExpression": EmitCall(<esprima.Syntax.CallExpression>ex, emit, alloc, scope, statementContext != 0); break; case "SequenceExpression": EmitSequence(<esprima.Syntax.SequenceExpression>ex, emit, alloc, scope, statementContext != 0); break; case "NewExpression": EmitNew(<esprima.Syntax.NewExpression>ex, emit, alloc, scope); break; case "AssignmentExpression": if (statementContext) { EmitAssignment(<esprima.Syntax.AssignmentExpression>ex, emit, alloc, scope); } else { var rightA = <esprima.Syntax.AssignmentExpression>ex; emit('((function() '); EmitAssignment(rightA, emit, alloc, scope); emit('; return '); EmitExpression(rightA.left, emit, alloc, scope, 0, false); emit(' end)())'); } break; case "BinaryExpression": EmitBinary(<esprima.Syntax.BinaryExpression>ex, emit, alloc, scope, statementContext != 0); break; case "LogicalExpression": EmitLogical(<esprima.Syntax.LogicalExpression>ex, emit, alloc, scope); break; case "ConditionalExpression": EmitConditional(<esprima.Syntax.ConditionalExpression>ex, emit, alloc, scope); break; case "UpdateExpression": EmitUpdate(<esprima.Syntax.UpdateExpression>ex, emit, alloc, scope, statementContext != 0); break; case "ArrayExpression": EmitArray(<esprima.Syntax.ArrayExpression>ex, emit, alloc, scope); break; case "ObjectExpression": EmitObject(<esprima.Syntax.ObjectExpression>ex, emit, alloc, scope); break; case "MemberExpression": EmitMember(<esprima.Syntax.MemberExpression>ex, emit, alloc, scope, statementContext != 0, isRef); break; case "UnaryExpression": EmitUnary(<esprima.Syntax.UnaryExpression>ex, emit, alloc, scope); break; case "FunctionExpression": EmitFunctionExpr(<esprima.Syntax.FunctionExpression>ex, emit, alloc, scope); break; case "Identifier": EmitIdentifier(<esprima.Syntax.Identifier>ex, emit, alloc, scope, isRef); break; case "ThisExpression": emit("self"); break; case "Literal": EmitLiteral(<esprima.Syntax.Literal>ex, emit, alloc, scope); break; default: emit("--[[2"); emit(ex.type); emit("]]"); console.log(util.inspect(ex, false, 999, true)); break; } emit(" "); } function EmitTryStatement(ast: esprima.Syntax.TryStatement, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { //console.log(util.inspect(ast, false, 999, true)); // TODO we're fucking optimistic var statusName = "__TryStatus" + alloc(); var returnValue = "__TryReturnValue" + alloc(); var catchReturnValue = "__CatchReturnValue" + alloc(); var finalizer = "__TryFinalizer" + alloc(); var handler = "__TryHandler" + alloc(); emit("--TryBody\r\nlocal " + statusName + "," + returnValue + " = xpcall(function ()\r\n"); EmitStatement(ast.block, emit, alloc, scope, false); emit(" end, __XpCall)\r\n"); //emit("print( " + statusName + "," + returnValue + ")\r\n"); if (ast.finalizer) { emit("--Finally\r\nlocal " + finalizer + "=(function() "); EmitStatement(ast.finalizer, emit, alloc, scope, false); emit(" end)"); } var ah = ast.handlers; if (ah.length == 0) { } else if (ah.length == 1) { var h = ah[0]; var paramName = h.param.name; emit("--Catch\r\nlocal " + handler + "=(function(" + paramName + ") "); scope.pushLexical([paramName], [], [], 'catch'); EmitStatement(h.body, emit, alloc, scope, false); scope.popScope(); emit(" end)"); } else { emit("--[[MultipleCatchClauses]]"); } var erf = (ast.finalizer) ? (finalizer + "();") : ""; // Early Return emit("--EarlyReturn\r\n if " + statusName + " and nil~=" + returnValue + " then " + erf + " return " + returnValue + " end;\r\n"); // Catch if (ah.length) { emit("--CheckCatch\r\n if not " + statusName + " then " + catchReturnValue + "=" + handler + "(" + returnValue + ".data or " + returnValue + ") end;\r\n"); emit("--CheckCatchValue\r\n if nil~=" + catchReturnValue + " then return " + catchReturnValue + " end;"); } // Just Finally if (ast.finalizer) { emit("--JustFinalizer\r\n" + finalizer + "()"); } // handlerS, not handler! } var NonSinkableExpressionTypes = ['VariableDeclaration', 'AssignmentExpression', 'CallExpression', 'UpdateExpression', 'SequenceExpression']; function EmitForStatement(ast: esprima.Syntax.ForStatement, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { //console.log(util.inspect(ast, false, 999, true)); if (ast.init) { var ait = ast.init.type; if (NonSinkableExpressionTypes.indexOf(ait) == -1) { emit("__Sink("); } EmitVariableDeclaratorOrExpression(ast.init, emit, alloc, scope); if (NonSinkableExpressionTypes.indexOf(ait) == -1) { emit(")"); } } emit("\r\nwhile __ToBoolean("); if (ast.test) { EmitExpression(ast.test, emit, alloc, scope, 0, false); } else { emit("true"); } emit(") do\r\n"); if (ast.body) { EmitStatement(<esprima.Syntax.BlockStatement>ast.body, emit, alloc, scope, true); } if (topContinueTargetLabelId) { emit("::" + topContinueTargetLabelId + "::\r\n"); topContinueTargetLabelId = null; } emit("\r\n-- BODY END\r\n"); if (ast.update) { var aut = ast.update.type; if (NonSinkableExpressionTypes.indexOf(aut) == -1) { emit("__Sink("); } EmitExpression(ast.update, emit, alloc, scope, 1, false); if (NonSinkableExpressionTypes.indexOf(aut) == -1) { emit(")"); } } emit(" end --For\r\n"); // any breaks? } function EmitForInStatement(ast: esprima.Syntax.ForInStatement, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { //console.log(util.inspect(ast, false, 999, true)); //console.log(escodegen.generate(ast)); if (ast.left.type == 'VariableDeclaration') { EmitVariableDeclaration(<esprima.Syntax.VariableDeclaration><any>ast.left, emit, alloc, scope); } var tmpIdent2 = '_tmp' + alloc(); emit("for "); if (ast.left.type == 'VariableDeclaration') { var vd = <esprima.Syntax.VariableDeclaration><any>ast.left; EmitName(vd.declarations[0].id, emit, alloc); scope.pushLexical([vd.declarations[0].id.name, tmpIdent2], [], [], 'for-in'); } else if (ast.left.type == 'Identifier') { var vi = <esprima.Syntax.Identifier><any>ast.left; EmitName(vi, emit, alloc); scope.pushLexical([vi.name, tmpIdent2], [], [], 'for-in'); } else { emit("--[[ ForIn WTF, unknown ast.left ]]"); } emit(","); EmitName({ type: 'Identifier', name: tmpIdent2 }, emit, alloc); emit(" in "); EmitCall({ type: 'CallExpression', callee: { 'type': 'Identifier', 'name': '__Iterate' }, arguments: [ast.right] }, emit, alloc, scope, false); emit(" do\r\n"); EmitStatement(<esprima.Syntax.BlockStatement>ast.body, emit, alloc, scope, true); if (topContinueTargetLabelId) { emit("::" + topContinueTargetLabelId + "::\r\n"); topContinueTargetLabelId = null; } emit(" end --ForIn\r\n"); // any breaks? scope.popScope(); } function EmitVariableDeclaratorOrExpression(ast: esprima.Syntax.VariableDeclaratorOrExpression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { if (ast.type == 'VariableDeclaration') { EmitVariableDeclaration(<esprima.Syntax.VariableDeclaration><any>ast, emit, alloc, scope); } else if (esutils.ast.isExpression(ast)) { EmitExpression(ast, emit, alloc, scope, 1, false); } else { emit("--[[5"); emit(ast.type); emit("]]"); console.log(util.inspect(ast, false, 999, true)); } } function EmitIdentifier(ast: esprima.Syntax.Identifier, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack, isRef: boolean) { var r = scope.lookupReference(ast.name); if (r.type == 'Lexical') { EmitName(ast, emit, alloc); } else if (r.type == 'Object') { if (!isRef) { var rcIndex = alloc(); emit("__RefCheck("); EmitMember({ type: 'MemberExpression', computed: false, object: { type: 'Identifier', name: r.ident }, property: ast }, emit, alloc, scope, false, isRef); emit("," + rcIndex + ")"); } else { // set non-local prop EmitMember({ type: 'MemberExpression', computed: false, object: { type: 'Identifier', name: r.ident }, property: ast }, emit, alloc, scope, false, isRef); } } else { emit("--[[ EmitIdentifier WTF ]]nil"); } } function EmitName(ast: esprima.Syntax.Identifier, emit: (s: string) => void, alloc: () => number) { var ein = (<esprima.Syntax.Identifier>ast).name; ein = ein.replace(/\$/g, "_USD_"); if (Object.prototype.hasOwnProperty.call(reservedLuaKeys, ein)) { ein = '_R_' + ein; // TODO better name mangling } emit(ein); } function EmitFunctionExpr(ast: esprima.Syntax.FunctionExpression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { //console.log(util.inspect(ast, false, 999, true)); var identList = argfinder.analyze(ast.body); var hasArguments = identList.refs.indexOf('arguments') != -1; var arglist: string[] = []; emit("__DefineFunction(function (self"); if (hasArguments) { arglist.push('arguments'); emit(", ...)\r\n") emit("local __argCnt"); } for (var si = 0; si < ast.params.length; si++) { emit(","); var arg = <esprima.Syntax.Identifier>ast.params[si]; arglist.push(arg.name); EmitName(arg, emit, alloc); } if (hasArguments) { emit("=select('#', ...)"); if (ast.params.length) { emit(", ..."); } emit("\r\nlocal arguments=__MakeArguments(__argCnt,{...})\r\n"); } else { emit(")\r\n"); // arglist close } var fPredeclare = unique(identList.funcs); fPredeclare.forEach(function (f) { emit("local "); EmitName({ type: 'Identifier', name: f }, emit, alloc); emit("\r\n"); }); scope.pushLexical(identList.vars, identList.funcs, arglist, 'function'); EmitStatement(ast.body, emit, alloc, scope, false); scope.popScope(); emit(" end) --FunctionExpr\r\n"); // any breaks? } function EmitArray(ast: esprima.Syntax.ArrayExpression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { emit("__MakeArray({"); for (var si = 0; si < ast.elements.length; si++) { emit("[" + si + "]="); var arg = ast.elements[si]; EmitExpression(arg, emit, alloc, scope, 0, false); emit(", "); } emit("[\"length\"]=" + ast.elements.length); emit("})"); } function EmitSequence(ast: esprima.Syntax.SequenceExpression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack, StatementContext: boolean) { if (!StatementContext) { emit("({"); } for (var si = 0; si < ast.expressions.length; si++) { var arg = ast.expressions[si]; var et = arg.type; var sinkThisExpr = StatementContext && NonSinkableExpressionTypes.indexOf(et) == -1; if (sinkThisExpr) { emit(" __Sink("); } EmitExpression(arg, emit, alloc, scope, (StatementContext && !sinkThisExpr) ? 1 : 0, false); if (sinkThisExpr) { emit(")"); } if (si != ast.expressions.length - 1) { emit(StatementContext ? "\r\n" : ", "); } } if (!StatementContext) { emit("})["); // TODO this is awful, optimize this emit(ast.expressions.length.toString()); emit("]"); } } function EmitObject(ast: esprima.Syntax.ObjectExpression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { emit("__MakeObject({"); for (var si = 0; si < ast.properties.length; si++) { var arg = ast.properties[si]; emit("["); // always coerced to string, as per js spec if (arg.key.type == 'Literal') { emit(JSON.stringify('' + arg.key.value)); } else if (arg.key.type == 'Identifier') { // identifiers already ok emit("\""); EmitName(arg.key, emit, alloc) emit("\""); } else { emit("--[[ EmitObject invalid key " + util.inspect(arg.key) + " ]]"); } emit("]="); EmitExpression(arg.value, emit, alloc, scope, 0, false); if (si != ast.properties.length - 1) { emit(", "); } } emit("})"); } function EmitFunctionDeclaration(ast: esprima.Syntax.FunctionDeclaration, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { //emit("local "); //console.log(scope.currentScope()); //EmitExpression(ast.id, emit, alloc, scope, 0, true); //emit(";"); EmitExpression(ast.id, emit, alloc, scope, 0, true); emit(" = "); EmitFunctionExpr(ast, emit, alloc, scope); } var blockAbortStatements = ['ReturnStatement', 'BreakStatement']; function EmitBlock(ast: esprima.Syntax.BlockStatement, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack, pendingContinueInThisBlock: boolean) { if (ast.type != 'BlockStatement' && ast.type != 'Program') { emit("--[[3"); emit(ast.type); emit("]]"); console.log(util.inspect(ast, false, 999, true)); return; } for (var si = 0; si < ast.body.length; si++) { var arg = ast.body[si]; var breaker = blockAbortStatements.indexOf(arg.type) != -1; if (pendingContinueInThisBlock && breaker/*&& topContinueTargetLabelId*/) emit(" do "); EmitStatement(arg, emit, alloc, scope, false); if (pendingContinueInThisBlock && breaker/*&& topContinueTargetLabelId*/) emit(" end "); // because there MAY be label after return if (breaker) break; // in lua?.. emit("\r\n"); } } function EmitAssignment(ast: esprima.Syntax.AssignmentExpression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { var aop = ast.operator; EmitExpression(ast.left, emit, alloc, scope, 0, true); if (aop == '=') { emit(aop); EmitExpression(ast.right, emit, alloc, scope, 0, false); } else { emit('='); EmitBinary({ type: 'BinaryExpression', operator: aop.substr(0, aop.length - 1), left: ast.left, right: ast.right }, emit, alloc, scope, false); } } function EmitUpdate(ast: esprima.Syntax.UpdateExpression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack, StatementContext: boolean) { //console.log(util.inspect(ast, false, 999, true)); var aop = ast.operator; if (aop != '++' && aop != '--') { emit("--[[6"); emit(ast.type); emit("]]"); console.log(util.inspect(ast, false, 999, true)); return; } if (!StatementContext) { emit('((function( ) '); if (!ast.prefix) { var tx = "__tmp" + alloc(); var itx = { 'type': 'Identifier', 'name': tx }; EmitAssignment({ type: 'AssignmentExpression', operator: '=', left: itx, right: ast.argument }, emit, alloc, scope); emit(";") } } EmitAssignment({ type: 'AssignmentExpression', operator: aop.substr(0, 1) + '=', left: ast.argument, right: { type: 'Literal', value: 1, raw: '1' } }, emit, alloc, scope); if (!StatementContext) { emit('; return '); EmitExpression(ast.prefix ? ast.argument : itx, emit, alloc, scope, 0, false); emit(' end)())'); } else { emit(";"); } } function EmitUnary(ast: esprima.Syntax.UnaryExpression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { var aop = ast.operator; if (aop == 'typeof') { emit("__Typeof"); emit("("); EmitExpression(ast.argument, emit, alloc, scope, 0, false); emit(")"); } else if (aop == '~') { emit("bit32.bnot"); emit("("); EmitExpression(ast.argument, emit, alloc, scope, 0, false); emit(")"); } else if (aop == 'delete') { EmitDelete(ast, emit, alloc, scope); } else if (aop == 'void') { emit("nil"); } else if (aop == '!') { emit("(not __ToBoolean("); EmitExpression(ast.argument, emit, alloc, scope, 0, false); emit("))"); } else if (aop == '+' || aop == '-') { emit(aop == '-' ? "(-__ToNumber(" : "(__ToNumber("); // TODO ToNumber EmitExpression(ast.argument, emit, alloc, scope, 0, false); emit("))"); } else { emit("--[[5"); emit(ast.type); emit("]]"); console.log(util.inspect(ast, false, 999, true)); return; } } function EmitDelete(ast: esprima.Syntax.UnaryExpression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { //console.log(util.inspect(ast)); if (ast.argument.type == 'MemberExpression') { var ma = <esprima.Syntax.MemberExpression>ast.argument; emit("__Delete"); // TODO emit callexpr emit("("); EmitExpression(ma.object, emit, alloc, scope, 0, true); emit(", \""); emit(ma.property.name); emit("\")"); } else if (ast.argument.type == 'Identifier') { var mm = <esprima.Syntax.Identifier>ast.argument; emit("__Delete"); emit("("); EmitExpression({ type: 'ThisExpression' }, emit, alloc, scope, 0, true); emit(", \""); emit(mm.name); // TODO error-prone emit("\")"); } else if (ast.argument.type == 'ThisExpression') { emit("(true)"); // totally correct per ECMA-262 } else { emit("(false)"); // maybe correct } } function EmitStatement(stmt: esprima.Syntax.Statement, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack, pendingContinueInThisBlock: boolean, defaultBreakTarget?: string) { //console.warn(stmt.type); switch (stmt.type) { case "ReturnStatement": EmitReturn(<esprima.Syntax.ReturnStatement>stmt, emit, alloc, scope); break; case "AssignmentExpression": EmitAssignment(<esprima.Syntax.AssignmentExpression>stmt, emit, alloc, scope); break; case "ThrowStatement": EmitThrow(<esprima.Syntax.ThrowStatement>stmt, emit, alloc, scope); break; case "EmptyStatement": emit("\r\n"); break; case "BreakStatement": EmitBreak(<esprima.Syntax.BreakStatement>stmt, emit, alloc, scope, defaultBreakTarget); break; case "IfStatement": EmitIf(<esprima.Syntax.IfStatement>stmt, emit, alloc, scope); break; case "SwitchStatement": EmitSwitch(<esprima.Syntax.SwitchStatement>stmt, emit, alloc, scope); break; case "WithStatement": EmitWith(<esprima.Syntax.WithStatement>stmt, emit, alloc, scope); break; case "ForStatement": EmitForStatement(<esprima.Syntax.ForStatement>stmt, emit, alloc, scope); break; case "TryStatement": EmitTryStatement(<esprima.Syntax.TryStatement>stmt, emit, alloc, scope); break; case "ForInStatement": EmitForInStatement(<esprima.Syntax.ForInStatement>stmt, emit, alloc, scope); break; case "DoWhileStatement": EmitDoWhileStatement(<esprima.Syntax.DoWhileStatement>stmt, emit, alloc, scope); break; case "WhileStatement": EmitWhileStatement(<esprima.Syntax.WhileStatement>stmt, emit, alloc, scope); break; case "BlockStatement": EmitBlock(<esprima.Syntax.BlockStatement>stmt, emit, alloc, scope, pendingContinueInThisBlock); break; case "LabeledStatement": EmitLabeled(<esprima.Syntax.LabeledStatement>stmt, emit, alloc, scope); break; case "ContinueStatement": EmitContinue(<esprima.Syntax.ContinueStatement>stmt, emit, alloc, scope); break; case "ExpressionStatement": var et = ((<esprima.Syntax.ExpressionStatement>stmt).expression).type; if (NonSinkableExpressionTypes.indexOf(et) == -1) { emit(" __Sink("); } EmitExpression((<esprima.Syntax.ExpressionStatement>stmt).expression, emit, alloc, scope, 1, false); if (NonSinkableExpressionTypes.indexOf(et) == -1) { emit(")"); } break; case "VariableDeclaration": EmitVariableDeclaration((<esprima.Syntax.VariableDeclaration>stmt), emit, alloc, scope); break; case "FunctionDeclaration": EmitFunctionDeclaration((<esprima.Syntax.FunctionDeclaration>stmt), emit, alloc, scope); emit("\r\n"); break; default: emit("--[[1"); emit(stmt.type); emit("]]"); console.log(util.inspect(stmt, false, 999, true)); break; } emit("\r\n"); } // HACK var topContinueTargetLabelId: string = null; function EmitContinue(ast: esprima.Syntax.ContinueStatement, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { if (ast.label) { emit(" goto "); EmitName(ast.label, emit, alloc); } else { var pc = "__Continue" + alloc(); topContinueTargetLabelId = pc; emit(" goto " + pc); // TODO 2 nonlabeled continue in the same loop } } function EmitLabeled(ast: esprima.Syntax.LabeledStatement, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { emit("::"); EmitName(ast.label, emit, alloc); emit(":: "); EmitStatement(ast.body, emit, alloc, scope, false); emit("::"); EmitName(ast.label, emit, alloc); emit("__After:: "); } function EmitDoWhileStatement(ast: esprima.Syntax.DoWhileStatement, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { emit("repeat "); EmitStatement(<esprima.Syntax.BlockStatement>ast.body, emit, alloc, scope, true); if (topContinueTargetLabelId) { emit("::" + topContinueTargetLabelId + "::\r\n"); topContinueTargetLabelId = null; } emit(" until not __ToBoolean("); EmitExpression(ast.test, emit, alloc, scope, 0, false); emit(")"); } function EmitWhileStatement(ast: esprima.Syntax.WhileStatement, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { emit("while __ToBoolean("); EmitExpression(ast.test, emit, alloc, scope, 0, false); emit(") do "); EmitStatement(<esprima.Syntax.BlockStatement>ast.body, emit, alloc, scope, true); if (topContinueTargetLabelId) { emit("::" + topContinueTargetLabelId + "::\r\n"); topContinueTargetLabelId = null; } emit(" end "); } function EmitIf(ast: esprima.Syntax.IfStatement, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { emit("if __ToBoolean("); EmitExpression(ast.test, emit, alloc, scope, 0, false); emit(" ) then\r\n"); EmitStatement(ast.consequent, emit, alloc, scope, false); if (ast.alternate) { emit(" else\r\n"); EmitStatement(ast.alternate, emit, alloc, scope, false); } emit(" end\r\n"); } function EmitSwitch(ast: esprima.Syntax.SwitchStatement, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { var testHolder = "__tmp" + alloc(); var labelPrefix = "__Switch" + alloc(); emit("\r\nlocal " + testHolder + " = ("); EmitExpression(ast.discriminant, emit, alloc, scope, 0, false); emit(") -- SwitchStmt\r\n"); scope.pushLexical([testHolder], [], [], 'switch'); var defaultCase: esprima.Syntax.SwitchCase = null; var dci: string; var emitTest = function (test, i) { EmitIf({ type: 'IfStatement', test: <esprima.Syntax.BinaryExpression>{ type: 'BinaryExpression', operator: '===', left: { type: 'Identifier', name: testHolder }, right: ci.test }, consequent: <esprima.Syntax.BreakStatement>{ type: 'BreakStatement', label: { type: 'Identifier', name: labelPrefix + "_" + i, force: true } }, alternate: null }, emit, alloc, scope); emit("\r\n"); } for (var i = 0; i < ast.cases.length; i++) { var ci = ast.cases[i]; if (ci.test) { emitTest(ci.test, i); } else { defaultCase = ci; dci = labelPrefix + "_" + i; } } if (defaultCase) { emit(" goto " + dci + "\r\n"); } for (var i = 0; i < ast.cases.length; i++) { var ci = ast.cases[i]; emit("\r\n::" + labelPrefix + "_" + i + ":: do\r\n"); ci.consequent.forEach(function (st) { EmitStatement(st, emit, alloc, scope, false, labelPrefix + "_End"); }); emit(" end\r\n"); } emit("::" + labelPrefix + "_End::"); emit("\r\n -- SwitchStmtEnd\r\n"); scope.popScope(); } function EmitWith(ast: esprima.Syntax.WithStatement, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { // todo strict mode // scoping is kinda wrong var scopeHolder = "__tmp" + alloc(); emit("\r\nlocal " + scopeHolder + " = __ToObject("); EmitExpression(ast.object, emit, alloc, scope, 0, false); emit(") -- WithStmt\r\n"); scope.pushObjectIdent(scopeHolder, "with"); scope.pushLexical(['__JsGlobalObjects', '__Singletons', 'undefined', scopeHolder], ['eval'].concat(BinaryOpRemapValues, Intrinsics), [], 'builtins-and-toplevels'); //console.log("EE"); EmitStatement(ast.body, emit, alloc, scope, false); scope.popScope(); scope.popScope(); emit("\r\n -- WithStmtEnd\r\n"); } function EmitReturn(ast: esprima.Syntax.ReturnStatement, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { emit("\r\nreturn "); EmitExpression(ast.argument, emit, alloc, scope, 0, false); } function EmitThrow(ast: esprima.Syntax.ThrowStatement, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { emit("error({[\"data\"]="); // TODO proper exceptions EmitExpression(ast.argument, emit, alloc, scope, 0, false); emit("})"); } function EmitBreak(ast: esprima.Syntax.BreakStatement, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack, defaultBreakTarget?: string) { if (ast.label) { emit(" goto "); EmitName(ast.label, emit, alloc); if (!(<any>ast.label).force) { emit("__After"); } } else if (defaultBreakTarget) { emit(" goto " + defaultBreakTarget); } else { emit("break"); } emit(" "); } function EmitBinary(ast: esprima.Syntax.BinaryExpression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack, StatementContext: boolean) { var aop = ast.operator; if (aop in BinaryOpRemap) { if (aop == '!==') { emit("(not "); } EmitCall({ type: 'CallExpression', callee: { 'type': 'Identifier', 'name': BinaryOpRemap[aop] }, arguments: [ast.left, ast.right] }, emit, alloc, scope, StatementContext); if (aop == '!==') { emit(")"); } } else { if (aop == '!=') { aop = '~='; } emit("("); EmitExpression(ast.left, emit, alloc, scope, 0, false); emit(aop); EmitExpression(ast.right, emit, alloc, scope, 0, false); emit(")"); } } function EmitLogical(ast: esprima.Syntax.BinaryExpression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { var aop = ast.operator; if (aop == '||') { aop = ' or '; } if (aop == '&&') { aop = ' and '; } emit("(__TernaryRestore(__TernarySave("); EmitExpression(ast.left, emit, alloc, scope, 0, false); emit(")"); emit(aop); emit("__TernaryReplace("); EmitExpression(ast.right, emit, alloc, scope, 0, false); emit(")))"); } function EmitConditional(ast: esprima.Syntax.ConditionalExpression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { emit("(__TernaryRestore(__TernarySave("); EmitExpression(ast.test, emit, alloc, scope, 0, false); emit(") and __TernaryReplace("); EmitExpression(ast.consequent, emit, alloc, scope, 0, false); emit(") or __TernaryReplace("); EmitExpression(ast.alternate, emit, alloc, scope, 0, false); emit(")))"); } var reservedLuaKeys = { 'true': true, 'false': true, 'null': true, 'in': true, 'try': true, 'class': true, 'break': true, 'do': true, 'while': true, 'until': true, 'for': true, 'and': true, 'else': true, 'elseif': true, 'end': true, 'function': true, 'if': true, 'local': true, 'nil': true, 'not': true, 'or': true, 'repeat': true, 'return': true, 'then': true, 'goto': true, } function EmitMember(ast: esprima.Syntax.MemberExpression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack, StatementContext: boolean, isRef: boolean) { //if(ast.property.name=='Step') { // console.log(util.inspect(ast, false, 999, true)); //} // var argIndexer = ast.object.type == 'Identifier' && (<esprima.Syntax.Identifier>ast.object).name == 'arguments'; if (ast.property.type == 'Identifier' && !ast.computed) { var id = <esprima.Syntax.Identifier>ast.property; var isReserved = !!reservedLuaKeys[id.name]; if (ast.object.type == 'Literal') { emit("("); } // ToObject here? EmitExpression(ast.object, emit, alloc, scope, 0, false); if (ast.object.type == 'Literal') { emit(")"); } emit(isReserved ? "[\"" : "."); EmitName(id, emit, alloc); emit(isReserved ? "\"]" : ""); } else { if (ast.object.type == 'Literal') { emit("("); } EmitExpression(ast.object, emit, alloc, scope, 0, false); // TODO emit SetPropCheck if (ast.object.type == 'Literal') { emit(")"); } emit("["); EmitExpression(ast.property, emit, alloc, scope, 0, false); //if (argIndexer) { // emit("+1"); //} emit("]"); } } function EmitCall(ast: esprima.Syntax.CallExpression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack, StatementContext: boolean) { if (ast.callee.type == 'MemberExpression') { var me = <esprima.Syntax.MemberExpression>ast.callee; emit("__CallMember("); EmitExpression(me.object, emit, alloc, scope, 0, false); emit(","); if (me.property.type == 'Identifier') { emit("\""); EmitName(<esprima.Syntax.Identifier>me.property, emit, alloc); emit("\""); } else if (me.property.type == 'Literal') { EmitExpression(me.property, emit, alloc, scope, 0, false); } else { emit("-- [[ EmitCall unknown property " + util.inspect(me.property) + "--]]"); } emit(ast.arguments.length ? "," : ""); } else if (ast.callee.type == 'Literal') { emit("__LiteralCallFail("); } else if (ast.callee.type == 'FunctionExpression') { // IIFE pattern emit(StatementContext ? " do end (" : "("); EmitExpression(ast.callee, emit, alloc, scope, 0, false); emit(")(self"); // avoid "ambiguous syntax" if (ast.arguments.length) emit(","); } else if (ast.callee.type == 'Identifier') { var act = <esprima.Syntax.Identifier>ast.callee; var nameIsBuiltin = (BinaryOpRemapValues.indexOf(act.name) != -1) || (Intrinsics.indexOf(act.name) != -1); EmitExpression(ast.callee, emit, alloc, scope, 0, false); emit(nameIsBuiltin ? "(" : "(self"); if (!nameIsBuiltin && ast.arguments.length) emit(","); } else { emit("--[[WTF Call " + util.inspect(ast) + " --]]"); } for (var si = 0; si < ast.arguments.length; si++) { var arg = ast.arguments[si]; if (si) emit(","); EmitExpression(arg, emit, alloc, scope, 0, false); } emit(")"); } function EmitNew(ast: esprima.Syntax.CallExpression, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { emit("__New("); EmitExpression(ast.callee, emit, alloc, scope, 0, false); for (var si = 0; si < ast.arguments.length; si++) { emit(", "); var arg = ast.arguments[si]; EmitExpression(arg, emit, alloc, scope, 0, false); } emit(")"); } function EmitLiteral(ex: esprima.Syntax.Literal, emit: (s: string) => void, alloc: () => number, scope: scoping.ScopeStack) { //console.log(util.inspect(ex, false, 999, true)); if (ex.value instanceof RegExp) { //console.log("R"); emit("__New(RegExp,"); var rparts = (<string>(<any>ex).raw).split('/'); emit(JSON.stringify(rparts[1])); // body emit(","); emit(JSON.stringify(rparts[2])); // flags emit(")"); } else { //console.log(ex.raw); emit(JSON.stringify(ex.value)); // TODO } } export function convertFile(source: string, fn: string, printCode: boolean): string { var allocIndex = 0; var alloc = function () { allocIndex++; return allocIndex; } var ast = esprima.parse(source); var a2 = hoist(ast, true); //console.log(escodegen.generate(a2)) if (printCode) { console.log(util.inspect(ast, false, 999, true)) } var luasrc = ""; var emit = function (code) { luasrc += code; //process.stdout.write(code); } EmitProgram(a2, emit, alloc); return luasrc; }
the_stack
import { Container, createContainer, Provider, resolveContainer } from 'frint-di'; import find = require('lodash/find'); import findIndex = require('lodash/findIndex'); import get = require('lodash/get'); import omit = require('lodash/omit'); import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { Observable } from 'rxjs/Observable'; import { of as of$ } from 'rxjs/observable/of'; import { concatMap as concatMap$ } from 'rxjs/operators/concatMap'; import { find as find$ } from 'rxjs/operators/find'; import { first as first$ } from 'rxjs/operators/first'; import { map as map$ } from 'rxjs/operators/map'; function makeInstanceKey(region = null, regionKey = null, multi = false) { if ( !multi || (!region && !regionKey) ) { return 'default'; } let key = ''; if (region) { key = region; } if (regionKey) { key = `${region}_${regionKey}`; } return key; } export interface Methods { [key: string]: (...args: any[]) => any; } export interface ProviderNames { component: string; container: string; store: string; app: string; parentApp: string; rootApp: string; region: string; } export interface RegisterAppOptions { name?: string; multi?: boolean; regions?: string[]; initialize?: () => void; } export interface FrintProvider extends Provider { cascade?: boolean; scoped?: boolean; } const defaultProviderNames = { component: 'component', container: 'container', store: 'store', app: 'app', parentApp: 'parentApp', rootApp: 'rootApp', region: 'region', }; export interface AppRegistration { appClass: AppClass; name: string; regions: any[]; instances: { [name: string]: App }; multi: boolean; initialize?: () => void; } export interface AppOptions { name?: string; methods?: Methods; parentApp?: App; providers?: FrintProvider[]; providerNames?: ProviderNames; initialize?: () => void; beforeDestroy?: () => void; } export interface AppClass { frintAppName?: string; new(opts?: AppOptions): App; } export class App { [method: string]: any; public container: Container; private options: AppOptions; private _appsCollection: AppRegistration[]; private _apps$: BehaviorSubject<AppRegistration[]>; constructor(opts: AppOptions) { this.options = { name: null, methods: {}, parentApp: null, providers: [], providerNames: defaultProviderNames, // lifecycle callbacks // tslint:disable-next-line:no-empty initialize: () => {}, // tslint:disable-next-line:no-empty beforeDestroy: () => {}, // override ...opts, }; // errors if (!this.options.name) { throw new Error('Must provide `name` in options'); } // expose methods as class properties Object.keys(this.options.methods).forEach(methodName => { const method = this.options.methods[methodName]; if (typeof method === 'function') { if (this[methodName] !== undefined) { throw new Error(`Cannot overwrite app's \`${methodName}\` property or method with options method.`); } this[methodName] = method.bind(this); } }); // children - create Observable if root this._appsCollection = []; this._apps$ = new BehaviorSubject(this._appsCollection); // container const container = createContainer([ { name: this.options.providerNames.app, useDefinedValue: this }, { name: this.options.providerNames.parentApp, useDefinedValue: this.getParentApp() }, { name: this.options.providerNames.rootApp, useDefinedValue: this.getRootApp() }, ], { containerName: this.options.providerNames.container, }); this.container = resolveContainer(container); // root app's providers this._registerRootProviders(); // self providers this.options.providers.forEach((provider) => { this.container.register(provider); }); this.options.initialize.bind(this)(); } public getContainer() { return this.container; } public getRootApp() { const parents = this.getParentApps(); if (parents.length === 0) { return this; } return parents.pop(); } public getParentApp() { return this.options[this.options.providerNames.parentApp] as App || null; } public getParentApps() { function findParents(app: App, parents: App[] = []): App[] { const parentApp = app.getParentApp(); if (!parentApp) { return parents; } parents.push(parentApp); return findParents(parentApp, parents); } return findParents(this); } public getOption(key) { return get(this.options, key); } public getName() { return this.getOption('name'); } public getProviders() { return this.options.providers; } public getProvider(name) { return find(this.options.providers, (p) => { return p.name === name; }); } public get<T>(providerName) { const value = this.container.get<T>(providerName); if (typeof value !== 'undefined') { return value; } return null; } public getApps$(regionName = null) { if (!regionName) { return this._apps$; } return this._apps$ .pipe(map$((collection) => { return collection .filter((w) => { return w.regions.indexOf(regionName) > -1; }); })); } public registerApp(appClass: AppClass = App, opts: RegisterAppOptions = {}) { const options = { multi: false, ...opts, }; if (typeof options.name !== 'undefined') { Object.defineProperty(appClass, 'frintAppName', { value: options.name, configurable: true, }); } const existingIndex = findIndex(this._appsCollection, (w) => { return w.name === appClass.frintAppName; }); if (existingIndex !== -1) { throw new Error(`App '${appClass.frintAppName}' has been already registered before.`); } this._appsCollection.push({ ...options, name: appClass.frintAppName, appClass, instances: {}, regions: options.regions || [], }); if (options.multi === false) { this.instantiateApp(appClass.frintAppName); } this._apps$.next(this._appsCollection); } public hasAppInstance(name, region = null, regionKey = null) { const instance = this.getAppInstance(name, region, regionKey); if (instance && typeof instance !== 'undefined') { return true; } return false; } public getAppInstance(name, region = null, regionKey = null) { const index = findIndex(this._appsCollection, a => { return a.name === name; }); if (index === -1) { return null; } const app = this._appsCollection[index]; const instanceKey = makeInstanceKey(region, regionKey, app.multi); const instance = app.instances[instanceKey]; if (!instance || typeof instance === 'undefined') { return null; } return instance; } public getAppOnceAvailable$(name, region = null, regionKey = null) { const rootApp = this.getRootApp(); const w = rootApp.getAppInstance(name, region, regionKey); if (w) { return of$(w); } return rootApp._apps$ .pipe( concatMap$(y => y), find$(app => app.name === name), map$((x) => { const instanceKey = makeInstanceKey(region, regionKey, x.multi); return x.instances[instanceKey]; }), first$() ); } public instantiateApp(name, region = null, regionKey = null) { const index = findIndex(this._appsCollection, a => { return a.appClass.frintAppName === name; }); if (index === -1) { throw new Error(`No app found with name '${name}'.`); } const w = this._appsCollection[index]; const key = makeInstanceKey(region, regionKey, w.multi); this._appsCollection[index].instances[key] = new w.appClass({ ...omit(w, ['AppClass', 'instances']) as AppOptions, name: (w.appClass as any).frintAppName, parentApp: this, }); return this._appsCollection[index].instances[key]; } public destroyApp(name, region = null, regionKey = null) { const index = findIndex(this._appsCollection, a => { if (!a || !a.appClass) { return false; } return a.appClass.frintAppName === name; }); if (index === -1) { throw new Error(`No app found with name '${name}'.`); } const w = this._appsCollection[index]; const key = makeInstanceKey(region, regionKey, w.multi); if (typeof this._appsCollection[index].instances[key] === 'undefined') { throw new Error(`No instance with key '${key}' found for app with name '${name}'.`); } this._appsCollection[index].instances[key].beforeDestroy(); delete this._appsCollection[index].instances[key]; } public beforeDestroy() { return this.options.beforeDestroy.bind(this)(); } private _registerRootProviders() { const parentApps = this.getParentApps(); if (parentApps.length === 0) { return; } parentApps.reverse().forEach((parentApp) => { parentApp.getProviders().forEach((parentProvider) => { // do not cascade if (!parentProvider.cascade) { return; } const definedProvider = Object.assign( {}, omit(parentProvider, [ 'useClass', 'useValue', 'useFactory' ]) ) as Provider; // non-scoped if (!parentProvider.scoped) { this.container.register({ ...definedProvider, useValue: parentApp.get(parentProvider.name), }); return; } // scoped if ('useValue' in parentProvider) { // `useValue` providers have no impact with scoping this.container.register({ ...definedProvider, useValue: parentApp.get(parentProvider.name) }); return; } if ('useClass' in parentProvider) { this.container.register({ ...definedProvider, useClass: parentProvider.useClass, }); return; } if ('useFactory' in parentProvider) { this.container.register({ ...definedProvider, useFactory: parentProvider.useFactory }); } }); }); } }
the_stack
import Base from '~/src/command/base' import http from '~/src/library/http' import md5 from 'md5' import url from 'url' import moment from 'moment' import _ from 'lodash' import fs from 'fs' import path from 'path' import shelljs from 'shelljs' import decodeHtml from 'decode-html' import PathConfig from '~/src/config/path' import DATE_FORMAT from '~/src/constant/date_format' import CommonUtil from '~/src/library/util/common' import logger from '~/src/library/logger' import StringUtil from '~/src/library/util/string' import TypeTaskConfig from '~/src/type/namespace/task_config' class GenerateBase extends Base { imageQuilty: TypeTaskConfig.imageQuilty = 'hd' imgUriPool: Set<string> = new Set() bookname = '' /** * 作者uid, 根据uid在图片池中生成pdf预览图片 */ currentAuthorUid = '' get htmlCachePath() { return path.resolve(PathConfig.htmlCachePath, this.bookname) } get htmlCacheHtmlPath() { return path.resolve(this.htmlCachePath, 'html') } get htmlCachePdfPath() { return path.resolve(this.htmlCachePath, 'pdf') } // 用于生成pdf的图片应该放在公共图片库中, 以方便缓存, 避免每次重新生成 get html2ImageCache_ImagePath() { return path.resolve(PathConfig.imgCachePath, 'pdf_resource', this.currentAuthorUid, 'html2image') } // 用于生成pdf的html应该和html同一层级 get html2ImageCache_HtmlPath() { return path.resolve(this.htmlCachePath, 'html_to_pdf') } get htmlCacheCssPath() { return path.resolve(this.htmlCachePath, 'css') } get htmlCacheFontPath() { return path.resolve(this.htmlCachePath, 'font') } get htmlCacheImgPath() { return path.resolve(this.htmlCachePath, 'image') } get htmlOutputPath() { return path.resolve(PathConfig.htmlOutputPath, this.bookname) } static get signature() { return ` Generate:Base ` } static get description() { return '生成电子书' } /** * 重置html2pdf的图片缓存文件夹 */ resetHtml2pdfImageCache() { this.log(`重置html2pdf的图片缓存文件夹`) shelljs.rm('-rf', this.html2ImageCache_ImagePath) shelljs.mkdir('-p', this.html2ImageCache_ImagePath) } // 初始化静态资源(电子书 & html目录) initStaticRecource() { this.log(`删除旧目录`) this.log(`删除旧html资源目录:${this.htmlCachePath}`) shelljs.rm('-rf', this.htmlCachePath) this.log(`旧html资源目录删除完毕`) this.log(`删除旧html输出目录:${this.htmlOutputPath}`) shelljs.rm('-rf', this.htmlOutputPath) this.log(`旧html输出目录删除完毕`) this.log(`创建电子书:${this.bookname}对应文件夹`) shelljs.mkdir('-p', PathConfig.imgCachePath) shelljs.mkdir('-p', this.htmlCachePath) shelljs.mkdir('-p', this.htmlCacheHtmlPath) shelljs.mkdir('-p', this.htmlCacheCssPath) shelljs.mkdir('-p', this.htmlCacheFontPath) shelljs.mkdir('-p', this.htmlCacheImgPath) shelljs.mkdir('-p', this.htmlCachePdfPath) shelljs.mkdir('-p', this.html2ImageCache_ImagePath) shelljs.mkdir('-p', this.html2ImageCache_HtmlPath) shelljs.mkdir('-p', this.htmlOutputPath) this.log(`电子书:${this.bookname}对应文件夹创建完毕`) } processContent(content: string) { let that = this // 删除noscript标签内的元素 function removeNoScript(rawHtml: string) { rawHtml = _.replace(rawHtml, /<\/br>/g, '') rawHtml = _.replace(rawHtml, /<br>/g, '<br/>') rawHtml = _.replace(rawHtml, /href="\/\/link.zhihu.com'/g, 'href="https://link.zhihu.com') // 修复跳转链接 rawHtml = _.replace(rawHtml, /\<noscript\>.*?\<\/noscript\>/g, '') return rawHtml } // 替换图片地址(假定所有图片都在img文件夹下) function replaceImgSrc(rawHtml: string, isRaw = false) { rawHtml = _.replace(rawHtml, /img src="data:image.+?"/g, 'img') // 处理图片 const imgContentList = rawHtml.match(/<img.+?>/g) let processedImgContentList = [] if (imgContentList === null) { // html中没有图片 return rawHtml } // 单条rawHtml直接replace替换性能开销太大, 所以应该先拆分, 然后再整体合成一个字符串 let rawHtmlWithoutImgContentList = rawHtml.split(/<img.+?>/g) for (let imgContent of imgContentList) { let imgSrc = _.get(imgContent.match(`(?<=src=["']).+(?=["'])`), 0, '') let processedImgContent = imgContent if (that.imageQuilty === 'none' || imgSrc === '') { // 无图 processedImgContent = '' } else { if (imgSrc.startsWith('//')) { imgSrc = 'https:' + imgSrc } processedImgContent = `<img src="${imgSrc}"/>` // 统一处理图片 //<img style='width: 1rem;height: 1rem' src='//h5.sinaimg.cn/upload/2015/09/25/3/timeline_card_small_web_default.png'> } // 支持多看内读图 processedImgContent = `<div class="duokan-image-single">${processedImgContent}</div>` if (that.imageQuilty === 'none') { // 没有图片, 也就不需要处理了, 直接跳过即可 processedImgContentList.push(processedImgContent) continue } // 将图片地址提取到图片池中 // 将html内图片地址替换为html内的地址 let matchImgSrc = processedImgContent.match(/(?<= src=")[^"]+/) let rawImgSrc = _.get(matchImgSrc, [0], '') // 新浪微博旧代码中, 图片地址被html encode过, 导致拿不到图片, 因此需要反解码一下 rawImgSrc = decodeHtml(rawImgSrc) if (rawImgSrc.length > 0) { that.imgUriPool.add(rawImgSrc) } let filename = that.getImgName(rawImgSrc) let htmlImgUri = '../image/' + filename processedImgContent = _.replace(processedImgContent, rawImgSrc, htmlImgUri) processedImgContentList.push(processedImgContent) } // 拼接 rawHtmlWithoutImgContentList 和 processImgContentList 成 rawHtml let strMergeList = [] for (let index = 0; index < rawHtmlWithoutImgContentList.length; index++) { strMergeList.push(rawHtmlWithoutImgContentList[index]) strMergeList.push(_.get(processedImgContentList, [index], '')) } let processedHtml = strMergeList.join('') return processedHtml } content = removeNoScript(content) let tinyContentList = content.split(`<div data-key='single-page'`).map(value => { return replaceImgSrc(value) }) content = tinyContentList.join(`<div data-key='single-page'`) return content } /** * 下载图片 */ async downloadImg() { let index = 0 for (let src of this.imgUriPool) { index++ let filename = this.getImgName(src) let cacheUri = path.resolve(PathConfig.imgCachePath, filename) // 检查缓存中是否有该文件 if (fs.existsSync(cacheUri)) { this.log(`[第${index}张图片]-0-将第${index}/${this.imgUriPool.size}张图片已存在,自动跳过`) continue } // 分批下载 this.log(`[第${index}张图片]-0-将第${index}/${this.imgUriPool.size}张图片添加到任务队列中`) await CommonUtil.asyncAppendPromiseWithDebounce(this.asyncDownloadImg(index, src, cacheUri)) } this.log(`清空任务队列`) await CommonUtil.asyncAppendPromiseWithDebounce(this.emptyPromiseFunction(), true) this.log(`所有图片下载完毕`) } private async asyncDownloadImg(index: number, src: string, cacheUri: string) { await CommonUtil.asyncSleep(1) // 确保下载日志可以和下载成功的日志一起输出, 保证日志完整性, 方便debug this.log(`[第${index}张图片]-1-准备下载第${index}/${this.imgUriPool.size}张图片, src => ${src}`) let imgContent = await http.downloadImg(src).catch(e => { this.log(`[第${index}张图片]-1-2-第${index}/${this.imgUriPool.size}张图片下载失败, 自动跳过`) this.log(`[第${index}张图片]-1-3-错误原因 =>`, e.message) return '' }) if (imgContent === '') { this.log(`[第${index}张图片]-1-4-下载失败, 图片内容为空`) return } this.log(`[第${index}张图片]-2-第${index}/${this.imgUriPool.size}张图片下载完成, src => ${src}`) // 调用writeFileSync时间长了之后可能会卡在这上边, 导致程序无响应, 因此改用promise试一下 this.log(`[第${index}张图片]-3-准备写入文件:${cacheUri}`) await CommonUtil.asyncSleep(10) fs.writeFileSync(cacheUri, imgContent) this.log(`[第${index}张图片]-4-第${index}/${this.imgUriPool.size}张图片储存完毕`) } async asyncCopyImgToCache(imgCachePath: string) { let index = 0 for (let src of this.imgUriPool) { index++ let filename = this.getImgName(src) // 避免文件名不存在的情况 if (filename === '') { continue } let imgCacheUri = path.resolve(PathConfig.imgCachePath, filename) let imgToUri = path.resolve(imgCachePath, filename) if (fs.existsSync(imgCacheUri)) { fs.copyFileSync(imgCacheUri, imgToUri) this.log(`第${index}/${this.imgUriPool.size}张图片复制完毕`) } else { this.log(`第${index}/${this.imgUriPool.size}张图片不存在, 自动跳过`) this.log(`src => ${src}`) } if (index % 100 === 0) { // 每复制100张图片休眠0.1秒, 避免页面因快速复制卡死 await CommonUtil.asyncSleep(1000 * 0.1) } } this.log(`全部图片复制完毕`) } copyStaticResource() { // css for (let filename of ['bootstrap.css', 'customer.css', 'markdown.css', 'normalize.css']) { let copyFromUri = path.resolve(PathConfig.resourcePath, 'css', filename) let copyToUri = path.resolve(this.htmlCacheCssPath, filename) fs.copyFileSync(copyFromUri, copyToUri) } // font for (let filename of ['iconfont.ttf']) { let copyFromUri = path.resolve(PathConfig.resourcePath, 'font', filename) let copyToUri = path.resolve(this.htmlCacheFontPath, filename) fs.copyFileSync(copyFromUri, copyToUri) } // 图片资源 for (let filename of ['cover.jpg', 'kanshan.png', 'sprite.svg']) { let copyFromUri = path.resolve(PathConfig.resourcePath, 'image', filename) let copyToUri = path.resolve(this.htmlCacheImgPath, filename) fs.copyFileSync(copyFromUri, copyToUri) } // 设置封面 let coverCopyFromUri = path.resolve(PathConfig.resourcePath, 'image', 'cover.jpg') let coverCopyToUri = path.resolve(this.htmlCacheImgPath, 'cover.jpg') fs.copyFileSync(coverCopyFromUri, coverCopyToUri) } async asyncProcessStaticResource() { this.log(`内容列表预处理完毕, 准备下载图片`) // 下载图片 this.log(`开始下载图片, 共${this.imgUriPool.size}张待下载`) await this.downloadImg() this.log(`图片下载完毕`) this.log(`将图片从图片池复制到电子书文件夹中`) await this.asyncCopyImgToCache(this.htmlCacheImgPath) this.log(`图片复制完毕`) this.log(`复制静态资源`) this.copyStaticResource() this.log(`静态资源复制完毕`) } async asyncCopyToDist() { this.log(`将输出电子书复制到结果目录中`) shelljs.cp('-r', path.resolve(this.htmlCachePath, './*'), path.resolve(this.htmlOutputPath)) this.log(`电子书复制完毕`) } /** * 根据图片地址生成图片名 * @param src */ getImgName(src: string) { // 直接将路径信息md5 let filename = '' try { let srcMd5 = md5(src) let urlObj = new url.URL(src) let pathname = urlObj.pathname if (path.extname(pathname) === '') { // 避免没有后缀名 pathname = `${pathname}.jpg` } if (pathname.length > 50) { // 文件名不能过长, 否则用户无法直接删除该文件 pathname = pathname.substr(pathname.length - 50, 50) } filename = StringUtil.encodeFilename(`${srcMd5}_${pathname}`) } catch (e) { // 非url, 不需要进行处理, 返回空即可 logger.warn(`[警告]传入值src:${src}不是合法url, 将返回空filename`) } return filename } } export default GenerateBase
the_stack
import * as assert from 'assert'; import {describe, it, before, afterEach} from 'mocha'; import { PluginLoader, PluginLoaderState, PluginWrapper, } from '../src/trace-plugin-loader'; import {alwaysTrace} from '../src/tracing-policy'; import {TestLogger} from './logger'; import {getBaseConfig, NoPropagation} from './utils'; export interface SimplePluginLoaderConfig { // An object which contains paths to files that should be loaded as plugins // upon loading a module with a given name. plugins: {[pluginName: string]: string}; } const SEARCH_PATH = `${__dirname}/fixtures/loader/node_modules`; const PROCESS_VERSION = process.version.slice(1); const clearRequireCache = () => { Object.keys(require.cache).forEach(key => delete require.cache[key]); }; describe('Trace Plugin Loader', () => { let logger: TestLogger; const makePluginLoader = (config: SimplePluginLoaderConfig) => { return new PluginLoader( Object.assign({tracerConfig: getBaseConfig()}, config), {tracePolicy: alwaysTrace(), logger, propagation: new NoPropagation()} ); }; before(() => { module.paths.push(SEARCH_PATH); PluginLoader.setPluginSearchPathForTestingOnly(SEARCH_PATH); logger = new TestLogger(); }); afterEach(() => { logger.clearLogs(); clearRequireCache(); }); describe('interface', () => { describe('state', () => { it('returns NO_HOOK when first called', () => { const pluginLoader = makePluginLoader({plugins: {}}); assert.strictEqual(pluginLoader.state, PluginLoaderState.NO_HOOK); }); }); describe('activate', () => { it('transitions from NO_HOOK to ACTIVATED, enabling require hook', () => { let requireHookCalled = false; const pluginLoader = makePluginLoader({plugins: {}}); // TODO(kjin): Stop using index properties. pluginLoader['enableRequireHook'] = () => (requireHookCalled = true); pluginLoader.activate(); assert.strictEqual(pluginLoader.state, PluginLoaderState.ACTIVATED); assert.ok(requireHookCalled); }); it('throws if internal state is already ACTIVATED', () => { let requireHookCalled = false; const pluginLoader = makePluginLoader({plugins: {}}).activate(); assert.strictEqual(pluginLoader.state, PluginLoaderState.ACTIVATED); // TODO(kjin): Stop using index properties. pluginLoader['enableRequireHook'] = () => (requireHookCalled = true); assert.throws(() => pluginLoader.activate()); assert.ok(!requireHookCalled); }); it('throws if internal state is DEACTIVATED', () => { // There is currently no reason to transition back and forth. // This behavior may change in the future. let requireHookCalled = false; const pluginLoader = makePluginLoader({plugins: {}}) .activate() .deactivate(); assert.strictEqual(pluginLoader.state, PluginLoaderState.DEACTIVATED); // TODO(kjin): Stop using index properties. pluginLoader['enableRequireHook'] = () => (requireHookCalled = true); assert.throws(() => pluginLoader.activate()); assert.ok(!requireHookCalled); }); }); describe('deactivate', () => { class TestPluginWrapper implements PluginWrapper { unapplyCalled = false; isSupported(): boolean { return false; } unapplyAll(): void { this.unapplyCalled = true; } applyPlugin<T>(moduleExports: T): T { return moduleExports; } } it('transitions state from ACTIVATED to DEACTIVATED, unapplying plugins', () => { const pluginLoader = makePluginLoader({plugins: {}}).activate(); assert.strictEqual(pluginLoader.state, PluginLoaderState.ACTIVATED); const plugin = new TestPluginWrapper(); // TODO(kjin): Stop using index properties. pluginLoader['pluginMap'].set('foo', plugin); pluginLoader.deactivate(); assert.strictEqual(pluginLoader.state, PluginLoaderState.DEACTIVATED); assert.ok(plugin.unapplyCalled); }); }); }); describe('static interface', () => { describe('parseModuleString', () => { it('parses module strings', () => { const p = PluginLoader.parseModuleString; assert.deepStrictEqual(p('m'), {name: 'm', file: ''}); assert.deepStrictEqual(p('m/f'), {name: 'm', file: 'f'}); assert.deepStrictEqual(p('m/d/f'), {name: 'm', file: 'd/f'}); assert.deepStrictEqual(p('m\\d\\f'), {name: 'm', file: 'd/f'}); assert.deepStrictEqual(p('@o\\m\\d\\f'), {name: '@o/m', file: 'd/f'}); assert.deepStrictEqual(p('@o/m/d/f'), {name: '@o/m', file: 'd/f'}); assert.deepStrictEqual(p('@o/m/d/f'), {name: '@o/m', file: 'd/f'}); }); }); }); describe('patching behavior', () => { it('ensures that module fixtures contain the right values', () => { // Ensure that module fixtures contain values that we expect. assert.strictEqual(require('small-number').value, 0); assert.strictEqual(require('large-number'), 1e100); assert.strictEqual(require('my-version-1.0'), '1.0.0'); assert.strictEqual(require('my-version-1.0-pre'), '1.0.0-pre'); assert.strictEqual(require('my-version-1.1'), '1.1.0'); assert.strictEqual(require('my-version-2.0'), '2.0.0'); }); it("doesn't patch before activation", () => { const loader = makePluginLoader({ plugins: {'small-number': 'plugin-small-number'}, }); assert.strictEqual(require('small-number').value, 0); loader.deactivate(); }); it("doesn't patch modules for which plugins aren't specified", () => { const loader = makePluginLoader({plugins: {}}).activate(); assert.strictEqual(require('small-number').value, 0); loader.deactivate(); }); it('patches modules when activated, with no plugin file field specifying the main file', () => { const loader = makePluginLoader({ plugins: {'small-number': 'plugin-small-number'}, }).activate(); assert.strictEqual(require('small-number').value, 1); // Make sure requiring doesn't patch twice assert.strictEqual(require('small-number').value, 1); assert.strictEqual( logger.getNumLogsWith('info', '[small-number@0.0.1]'), 1 ); loader.deactivate(); }); it('accepts absolute paths in configuration', () => { const loader = makePluginLoader({ plugins: {'small-number': `${SEARCH_PATH}/plugin-small-number`}, }).activate(); assert.strictEqual(require('small-number').value, 1); assert.strictEqual( logger.getNumLogsWith('info', '[small-number@0.0.1]'), 1 ); loader.deactivate(); }); it('unpatches modules when deactivated', () => { const loader = makePluginLoader({ plugins: {'small-number': 'plugin-small-number'}, }).activate(); require('small-number'); loader.deactivate(); assert.strictEqual(require('small-number').value, 0); // One each for activate/deactivate assert.strictEqual( logger.getNumLogsWith('info', '[small-number@0.0.1]'), 2 ); }); it('intercepts and patches internal files', () => { const loader = makePluginLoader({ plugins: {'large-number': 'plugin-large-number'}, }).activate(); assert.strictEqual(require('large-number'), 2e100); loader.deactivate(); }); ['http', 'url', '[core]'].forEach(key => { it(`intercepts and patches core modules with key "${key}"`, () => { const loader = makePluginLoader({ plugins: {[key]: 'plugin-core'}, }).activate(); const input = {protocol: 'http:', host: 'hi'}; assert.strictEqual(require('url').format(input), 'patched-value'); loader.deactivate(); assert.strictEqual(require('url').format(input), 'http://hi'); // One each for activate/deactivate assert.strictEqual( logger.getNumLogsWith('info', `[${key}@${PROCESS_VERSION}:url]`), 2 ); }); }); it("doesn't load plugins with falsey paths", () => { const loader = makePluginLoader({ plugins: {'small-number': ''}, }).activate(); assert.strictEqual(require('small-number').value, 0); loader.deactivate(); }); it('uses version ranges to determine how to patch internals', () => { const loader = makePluginLoader({ plugins: {'my-version': 'plugin-my-version-1'}, }).activate(); assert.strictEqual(require('my-version-1.0'), '1.0.0-patched'); // v1.1 has different internals. assert.strictEqual(require('my-version-1.1'), '1.1.0-patched'); assert.strictEqual(require('my-version-2.0'), '2.0.0'); // warns for my-version-2.0 that nothing matches assert.strictEqual( logger.getNumLogsWith('warn', '[my-version@2.0.0]'), 1 ); loader.deactivate(); }); it('patches pre-releases, but warns', () => { const loader = makePluginLoader({ plugins: {'my-version': 'plugin-my-version-1'}, }).activate(); assert.strictEqual(require('my-version-1.0-pre'), '1.0.0-pre-patched'); assert.strictEqual( logger.getNumLogsWith('warn', '[my-version@1.0.0-pre]'), 1 ); loader.deactivate(); }); it('throws when the plugin throws', () => { const loader = makePluginLoader({ plugins: {'my-version': 'plugin-my-version-2'}, }).activate(); let threw = false; try { require('my-version-1.0'); } catch (e) { threw = true; } assert.ok(threw); loader.deactivate(); }); it('warns when a module is patched by a non-conformant plugin', () => { const loader = makePluginLoader({ plugins: {'[core]': 'plugin-core'}, }).activate(); // Reasons for possible warnings issued are listed as comments. require('crypto'); // neither patch nor intercept require('os'); // both patch and intercept require('dns'); // two Patch objects for a single file // Do not warn when there is no patch/intercept function. assert.strictEqual( logger.getNumLogsWith('warn', `[[core]@${PROCESS_VERSION}:crypto]`), 0 ); assert.strictEqual( logger.getNumLogsWith('warn', `[[core]@${PROCESS_VERSION}:os]`), 1 ); assert.strictEqual( logger.getNumLogsWith('warn', `[[core]@${PROCESS_VERSION}:dns]`), 1 ); loader.deactivate(); }); }); });
the_stack
import { WList } from '../list/list'; import { WAbstractList } from '../list/abstract-list'; import { WListLevel } from '../list/list-level'; import { WTabStop, WParagraphFormat } from '../format/paragraph-format'; import { WCellFormat, WTableFormat, WRowFormat, WStyle, WListFormat, WCharacterFormat } from '../format/index'; import { WBorder, WBorders, WShading } from '../format/index'; import { LayoutViewer } from '../index'; import { IWidget, LineWidget, ParagraphWidget, BlockContainer, BodyWidget, TextElementBox, Page, ElementBox, FieldElementBox, TableWidget, TableRowWidget, TableCellWidget, ImageElementBox, HeaderFooterWidget, HeaderFooters, ContentControl, ListTextElementBox, BookmarkElementBox, EditRangeStartElementBox, EditRangeEndElementBox, ChartElementBox, ChartDataTable, ChartTitleArea, ChartDataFormat, ChartLayout, ChartArea, ChartLegend, ChartCategoryAxis, CommentElementBox, CommentCharacterElementBox, TextFormField, CheckBoxFormField, DropDownFormField, ShapeElementBox, ContentControlProperties, FootnoteElementBox, ShapeBase } from '../viewer/page'; import { BlockWidget } from '../viewer/page'; import { isNullOrUndefined } from '@syncfusion/ej2-base'; import { HelperMethods } from '../editor/editor-helper'; import { StreamWriter } from '@syncfusion/ej2-file-utils'; import { TextPosition } from '../selection'; import { DocumentHelper } from '../viewer'; import { WLevelOverride } from '../list'; import { DocumentEditor } from '../../document-editor'; import { Revision } from '../track-changes/track-changes'; /** * Exports the document to Sfdt format. */ export class SfdtExport { /* eslint-disable @typescript-eslint/no-explicit-any */ private startLine: LineWidget = undefined; private endLine: LineWidget = undefined; private endOffset: number = undefined; private endCell: TableCellWidget = undefined; private startColumnIndex: number = undefined; private endColumnIndex: number = undefined; private lists: number[] = undefined; private document: any = undefined; private writeInlineStyles: boolean = undefined; private nextBlock: any; private blockContent: boolean = false; private startContent: boolean = false; private multipleLineContent: boolean = false; private nestedContent: boolean = false; private contentType: string; private editRangeId: number = -1; private selectedCommentsId: string[] = []; private selectedRevisionId: string[] = []; private startBlock: BlockWidget; private endBlock: BlockWidget; private nestedBlockContent: boolean = false; private nestedBlockEnabled: boolean = false; private blocks: any = []; private contentInline: any = []; private isContentControl: boolean = false; private isBlockClosed: boolean = true; /** * @private */ private isExport: boolean = true; /** * @private */ public isPartialExport: boolean = false; private documentHelper: DocumentHelper; private checkboxOrDropdown: boolean = false; /** * @private */ public copyWithTrackChange: boolean = false; public constructor(documentHelper: DocumentHelper) { this.documentHelper = documentHelper; } private get viewer(): LayoutViewer { return this.documentHelper.owner.viewer; } private get owner(): DocumentEditor { return this.documentHelper.owner; } private getModuleName(): string { return 'SfdtExport'; } private clear(): void { this.writeInlineStyles = undefined; this.startLine = undefined; this.endLine = undefined; this.lists = undefined; this.document = undefined; this.endCell = undefined; this.startColumnIndex = undefined; this.endColumnIndex = undefined; this.selectedCommentsId = []; this.selectedRevisionId = []; this.startBlock = undefined; this.endBlock = undefined; this.isPartialExport = false; } /** * Serialize the data as Syncfusion document text. * * @private */ public serialize(): string { return JSON.stringify(this.write()); } /** * @private * @param documentHelper - Specifies document helper instance. * @returns {Promise<Blob>} */ public saveAsBlob(documentHelper: DocumentHelper): Promise<Blob> { const streamWriter: StreamWriter = new StreamWriter(); streamWriter.write(this.serialize()); const blob: Blob = streamWriter.buffer; streamWriter.destroy(); let promise: Promise<Blob>; return new Promise((resolve: Function, reject: Function) => { resolve(blob); }); } private updateEditRangeId(): void { let index: number = -1; for (let i: number = 0; i < this.documentHelper.editRanges.keys.length; i++) { const keys: string[] = this.documentHelper.editRanges.keys; for (let j: number = 0; j < keys[i].length; j++) { const editRangeStart: EditRangeStartElementBox[] = this.documentHelper.editRanges.get(keys[i]); for (let z: number = 0; z < editRangeStart.length; z++) { index++; editRangeStart[z].editRangeId = index; editRangeStart[z].editRangeEnd.editRangeId = index; } } } } /** * @private */ /* eslint-disable */ public write(line?: LineWidget, startOffset?: number, endLine?: LineWidget, endOffset?: number, writeInlineStyles?: boolean, isExport?: boolean): any { if (writeInlineStyles) { this.writeInlineStyles = true; } this.Initialize(); this.updateEditRangeId(); if (line instanceof LineWidget && endLine instanceof LineWidget) { this.isExport = false; if (!isNullOrUndefined(isExport)) { this.isExport = isExport; } // For selection let startPara: ParagraphWidget = line.paragraph; let endPara: ParagraphWidget = endLine.paragraph; if (this.isPartialExport) { this.startBlock = this.getParentBlock(startPara); this.endBlock = this.getParentBlock(endPara); } let startCell: TableCellWidget = startPara.associatedCell; let endCell: TableCellWidget = endPara.associatedCell; // Creates section let bodyWidget: BlockContainer = startPara.bodyWidget as BlockContainer; let section: any = this.createSection(line.paragraph.bodyWidget as BlockContainer); this.document.sections.push(section); if (startCell === endCell || isNullOrUndefined(endCell)) { this.startLine = line; this.endLine = endLine; this.endOffset = endOffset; } else { // Todo: Handle nested table cases if (startCell instanceof TableCellWidget) { let startTable: TableWidget = startCell.getContainerTable(); let endTable: TableWidget = endCell.getContainerTable(); if (startTable.tableFormat === endTable.tableFormat) { this.endCell = endCell; if (this.endCell.ownerTable !== startCell.ownerTable && startCell.ownerTable.associatedCell && startCell.ownerTable.associatedCell.ownerTable === this.endCell.ownerTable && (startCell.ownerTable.associatedCell.childWidgets.indexOf(startCell.ownerTable) === 0)) { startCell = startCell.ownerTable.associatedCell; } this.endColumnIndex = this.endCell.columnIndex + this.endCell.cellFormat.columnSpan; this.startColumnIndex = startCell.columnIndex; } } else { this.endCell = endCell; } } let nextBlock: BlockWidget; if ((startCell === endCell && !this.isPartialExport) || isNullOrUndefined(startCell)) { let paragraph: any = this.createParagraph(line.paragraph); section.blocks.push(paragraph); let lastBlock: BlockWidget = line.paragraph; nextBlock = this.writeParagraph(line.paragraph, paragraph, section.blocks, line.indexInOwner, startOffset); if (this.isPartialExport) { nextBlock = this.getNextBlock(nextBlock, lastBlock); section = this.document.sections[this.document.sections.length - 1]; } while (nextBlock) { lastBlock = nextBlock; nextBlock = this.writeBlock(nextBlock, 0, section.blocks); if (this.isPartialExport && isNullOrUndefined(nextBlock)) { nextBlock = this.getNextBlock(nextBlock, lastBlock); section = this.document.sections[this.document.sections.length - 1]; } } // Todo:continue in next section } else { // Specially handled for nested table cases // selection start inside table and end in paragraph outside table if (isNullOrUndefined(endCell) && startCell.ownerTable.associatedCell) { let startTable: TableWidget = startCell.getContainerTable(); let lastRow: TableRowWidget = startTable.childWidgets[startTable.childWidgets.length - 1] as TableRowWidget; let endCell: TableCellWidget = lastRow.childWidgets[lastRow.childWidgets.length - 1] as TableCellWidget; if (endCell.ownerTable !== startCell.ownerTable && startCell.ownerTable.associatedCell && (startCell.ownerTable.associatedCell.childWidgets.indexOf(startCell.ownerTable) === 0)) { while (startCell.ownerTable !== endCell.ownerTable) { startCell = startCell.ownerTable.associatedCell; } } this.endColumnIndex = endCell.columnIndex + endCell.cellFormat.columnSpan; this.startColumnIndex = startCell.columnIndex; } let table: any = this.createTable(startCell.ownerTable); section.blocks.push(table); let lastBlock: BlockWidget = startCell.ownerTable; nextBlock = this.writeTable(startCell.ownerTable, table, startCell.ownerRow.indexInOwner, section.blocks); if (this.isPartialExport) { nextBlock = this.getNextBlock(nextBlock, lastBlock); section = this.document.sections[this.document.sections.length - 1]; } while (nextBlock) { lastBlock = nextBlock; nextBlock = this.writeBlock(nextBlock, 0, section.blocks); if (this.isPartialExport) { nextBlock = this.getNextBlock(nextBlock, lastBlock); section = this.document.sections[this.document.sections.length - 1]; } } } } else { this.isExport = true; if (this.documentHelper.pages.length > 0) { let page: Page = this.documentHelper.pages[0]; this.writePage(page); } } this.writeStyles(this.documentHelper); this.writeLists(this.documentHelper); this.writeComments(this.documentHelper); this.writeRevisions(this.documentHelper); this.writeCustomXml(this.documentHelper); this.footnotes(this.documentHelper); this.endnotes(this.documentHelper); let doc: Document = this.document; this.clear(); return doc; } private getNextBlock(nextBlock: BlockWidget, lastBlock: BlockWidget): BlockWidget { if (isNullOrUndefined(nextBlock) && this.isPartialExport && this.endBlock && !this.endBlock.equals(lastBlock)) { nextBlock = lastBlock.getSplitWidgets().pop().nextRenderedWidget as BlockWidget; if (nextBlock && lastBlock.bodyWidget.index !== nextBlock.bodyWidget.index) { let section: any = this.createSection(nextBlock.bodyWidget as BlockContainer); this.document.sections.push(section); } else { nextBlock = undefined; } } return nextBlock; } /** * @private */ public Initialize(): void { this.lists = []; this.document = {}; this.document.sections = []; this.document.characterFormat = this.writeCharacterFormat(this.documentHelper.characterFormat); this.document.paragraphFormat = this.writeParagraphFormat(this.documentHelper.paragraphFormat); this.document.defaultTabWidth = this.documentHelper.defaultTabWidth; this.document.trackChanges = this.owner.enableTrackChanges; this.document.enforcement = this.documentHelper.isDocumentProtected; this.document.hashValue = this.documentHelper.hashValue; this.document.saltValue = this.documentHelper.saltValue; this.document.formatting = this.documentHelper.restrictFormatting; this.document.protectionType = this.documentHelper.protectionType; this.document.dontUseHTMLParagraphAutoSpacing = this.documentHelper.dontUseHtmlParagraphAutoSpacing; this.document.formFieldShading = this.documentHelper.owner.documentEditorSettings.formFieldSettings.applyShading; this.document.compatibilityMode = this.documentHelper.compatibilityMode; } /** * @private */ public writePage(page: Page): any { if (page.bodyWidgets.length > 0) { let nextBlock: BodyWidget = page.bodyWidgets[0]; do { nextBlock = this.writeBodyWidget(nextBlock, 0); } while (!isNullOrUndefined(nextBlock)); } return this.document; } private writeBodyWidget(bodyWidget: BodyWidget, index: number): BodyWidget { if (!(bodyWidget instanceof BodyWidget)) { return undefined; } let section: any = this.createSection(bodyWidget); this.document.sections.push(section); this.writeHeaderFooters(this.documentHelper.headersFooters[bodyWidget.index], section); let firstBlock: BlockWidget = bodyWidget.childWidgets[index] as BlockWidget; do { firstBlock = this.writeBlock(firstBlock as BlockWidget, 0, section.blocks); } while (firstBlock); let next: BodyWidget = bodyWidget; do { bodyWidget = next; next = next.nextRenderedWidget as BodyWidget; if (isNullOrUndefined(next) && !isNullOrUndefined(bodyWidget.page.nextPage) && !isNullOrUndefined(bodyWidget.page.nextPage)) { next = bodyWidget.page.nextPage.bodyWidgets[0]; } } while (next instanceof BodyWidget && next.index === bodyWidget.index); return next; } private writeHeaderFooters(hfs: HeaderFooters, section: any): void { if (isNullOrUndefined(hfs)) { return; } section.headersFooters.header = this.writeHeaderFooter(hfs[0]); section.headersFooters.footer = this.writeHeaderFooter(hfs[1]); section.headersFooters.evenHeader = this.writeHeaderFooter(hfs[2]); section.headersFooters.evenFooter = this.writeHeaderFooter(hfs[3]); section.headersFooters.firstPageHeader = this.writeHeaderFooter(hfs[4]); section.headersFooters.firstPageFooter = this.writeHeaderFooter(hfs[5]); } private writeHeaderFooter(widget: HeaderFooterWidget): any { if (isNullOrUndefined(widget) || widget.isEmpty) { return undefined; } let headerFooter: any = {}; if (widget && widget.childWidgets && widget.childWidgets.length > 0) { headerFooter.blocks = []; let firstBlock: BlockWidget = widget.firstChild as BlockWidget; do { firstBlock = this.writeBlock(firstBlock, 0, headerFooter.blocks); } while (firstBlock); } return headerFooter; } private createSection(bodyWidget: BlockContainer): any { let section: any = {}; section.sectionFormat = {}; section.sectionFormat.pageWidth = bodyWidget.sectionFormat.pageWidth; section.sectionFormat.pageHeight = bodyWidget.sectionFormat.pageHeight; section.sectionFormat.leftMargin = bodyWidget.sectionFormat.leftMargin; section.sectionFormat.rightMargin = bodyWidget.sectionFormat.rightMargin; section.sectionFormat.topMargin = bodyWidget.sectionFormat.topMargin; section.sectionFormat.bottomMargin = bodyWidget.sectionFormat.bottomMargin; section.sectionFormat.differentFirstPage = bodyWidget.sectionFormat.differentFirstPage; section.sectionFormat.differentOddAndEvenPages = bodyWidget.sectionFormat.differentOddAndEvenPages; section.sectionFormat.headerDistance = bodyWidget.sectionFormat.headerDistance; section.sectionFormat.footerDistance = bodyWidget.sectionFormat.footerDistance; section.sectionFormat.bidi = bodyWidget.sectionFormat.bidi; if (bodyWidget.sectionFormat.restartPageNumbering) { section.sectionFormat.restartPageNumbering = bodyWidget.sectionFormat.restartPageNumbering; section.sectionFormat.pageStartingNumber = bodyWidget.sectionFormat.pageStartingNumber; } if (!isNullOrUndefined(bodyWidget.page.endnoteWidget || bodyWidget.page.footnoteWidget)) { section.sectionFormat.endnoteNumberFormat = bodyWidget.sectionFormat.endnoteNumberFormat; section.sectionFormat.footNoteNumberFormat = bodyWidget.sectionFormat.footNoteNumberFormat; section.sectionFormat.restartIndexForFootnotes = bodyWidget.sectionFormat.restartIndexForFootnotes; section.sectionFormat.restartIndexForEndnotes = bodyWidget.sectionFormat.restartIndexForEndnotes; section.sectionFormat.initialFootNoteNumber = bodyWidget.sectionFormat.initialFootNoteNumber; section.sectionFormat.initialEndNoteNumber = bodyWidget.sectionFormat.initialEndNoteNumber; } section.blocks = []; section.headersFooters = {}; return section; } private writeBlock(widget: BlockWidget, index: number, blocks: any): BlockWidget { if (!(widget instanceof BlockWidget)) { return undefined; } if (widget instanceof ParagraphWidget) { if (widget.hasOwnProperty('contentControlProperties') && widget.contentControlProperties.type !== 'BuildingBlockGallery') { let block: any = this.blockContentControl(widget); if (!isNullOrUndefined(block) && this.isBlockClosed) { blocks.push(block); this.blocks = []; } return this.nextBlock; } else { let paragraph: any = this.createParagraph(widget); blocks.push(paragraph); return this.writeParagraph(widget, paragraph, blocks); } } else { let tableWidget: TableWidget = widget as TableWidget; if (tableWidget.hasOwnProperty('contentControlProperties') && tableWidget.contentControlProperties.type !== 'BuildingBlockGallery') { let block: any = this.tableContentControl(tableWidget); if (this.isBlockClosed) { blocks.push(block); } return this.nextBlock; } let table: any = this.createTable(tableWidget); blocks.push(table); return this.writeTable(tableWidget, table, 0, blocks); } } private writeParagraphs(widget: ParagraphWidget): any { let blocks: any = this.blocks; let child: LineWidget = widget.childWidgets[0] as LineWidget; let firstElement: ElementBox = child.children[0]; let secondElement: ElementBox = child.children[1]; if (firstElement instanceof ListTextElementBox || secondElement instanceof ListTextElementBox) { firstElement = child.children[2]; secondElement = child.children[3]; } if (this.nestedBlockEnabled) { blocks = []; } if ((firstElement instanceof ContentControl && secondElement instanceof ContentControl && !this.nestedBlockContent) || (this.blockContent && firstElement instanceof ContentControl && !this.nestedBlockContent)) { let nestedBlocks: boolean = false; if (secondElement instanceof ContentControl) { if ((secondElement as ContentControl).contentControlWidgetType === 'Block') { nestedBlocks = true; } } if ((nestedBlocks || (this.blockContent && firstElement instanceof ContentControl && !this.nestedBlockContent && (firstElement as ContentControl).type === 0 && (firstElement as ContentControl).contentControlWidgetType === 'Block'))) { this.nestedBlockContent = true; this.nestedBlockEnabled = true; let block: any = this.blockContentControl(widget); if (!isNullOrUndefined(block)) { this.blocks.push(block); } } else { let paragraph: any = this.createParagraph(widget); blocks.push(paragraph); this.nextBlock = this.writeParagraph(widget, paragraph, blocks); } } else { let paragraph: any = this.createParagraph(widget); blocks.push(paragraph); this.nextBlock = this.writeParagraph(widget, paragraph, blocks); } if (!this.blockContent) { return blocks; } else if (!this.nestedBlockContent && this.nestedBlockEnabled) { this.nestedBlockEnabled = false; return blocks; } } private contentControlProperty(contentControlPropertie: ContentControlProperties): any { let contentControlProperties: any = {}; let contentControlListItems: any = []; contentControlProperties.lockContentControl = contentControlPropertie.lockContentControl; contentControlProperties.lockContents = contentControlPropertie.lockContents; contentControlProperties.tag = contentControlPropertie.tag; contentControlProperties.color = contentControlPropertie.color; contentControlProperties.title = contentControlPropertie.title; if (!isNullOrUndefined(contentControlPropertie.appearance)) { contentControlProperties.appearance = contentControlPropertie.appearance; } contentControlProperties.type = contentControlPropertie.type; contentControlProperties.hasPlaceHolderText = contentControlPropertie.hasPlaceHolderText; contentControlProperties.multiline = contentControlPropertie.multiline; contentControlProperties.isTemporary = contentControlPropertie.isTemporary; if (!isNullOrUndefined(contentControlPropertie.isChecked)) { contentControlProperties.isChecked = contentControlPropertie.isChecked; } if (!isNullOrUndefined(contentControlPropertie.uncheckedState)) { contentControlProperties.uncheckedState = this.tounCheckedState(contentControlPropertie.uncheckedState); } if (!isNullOrUndefined(contentControlPropertie.checkedState)) { contentControlProperties.checkedState = this.toCheckedState(contentControlPropertie.checkedState); } if (!isNullOrUndefined(contentControlPropertie.dateCalendarType)) { contentControlProperties.dateCalendarType = contentControlPropertie.dateCalendarType; } if (!isNullOrUndefined(contentControlPropertie.dateStorageFormat)) { contentControlProperties.dateStorageFormat = contentControlPropertie.dateStorageFormat; } if (!isNullOrUndefined(contentControlPropertie.dateDisplayLocale)) { contentControlProperties.dateDisplayLocale = contentControlPropertie.dateDisplayLocale; } if (!isNullOrUndefined(contentControlPropertie.dateDisplayFormat)) { contentControlProperties.dateDisplayFormat = contentControlPropertie.dateDisplayFormat; } if (!isNullOrUndefined(contentControlPropertie.xmlMapping)) { contentControlProperties.xmlMapping = contentControlPropertie.xmlMapping; } if (!isNullOrUndefined(contentControlPropertie.characterFormat)) { contentControlProperties.characterFormat = this.writeCharacterFormat(contentControlPropertie.characterFormat); } contentControlProperties.contentControlListItems = contentControlPropertie.contentControlListItems; return contentControlProperties; } private tounCheckedState(state: any): any { let unCheckedState: any = {}; unCheckedState.font = state.font; unCheckedState.value = state.value; return unCheckedState; } private toCheckedState(state: any): any { let checkedState: any = {}; checkedState.font = state.font; checkedState.value = state.value; return checkedState; } private blockContentControl(widget: ParagraphWidget): any { let block: any = {}; if (widget.childWidgets.length === 0) { this.nextBlock = widget.nextWidget; return undefined; } block.blocks = this.writeParagraphs(widget); if (!isNullOrUndefined(block.blocks)) { let child: LineWidget = widget.childWidgets[0] as LineWidget; let firstChild: ElementBox = child.children[0]; let secondChild: ElementBox = child.children[1]; if (firstChild instanceof ListTextElementBox || secondChild instanceof ListTextElementBox) { firstChild = child.children[2]; secondChild = child.children[3]; } if ((firstChild instanceof ContentControl && secondChild instanceof ContentControl && !this.nestedBlockContent) || (this.blockContent && firstChild instanceof ContentControl && !this.nestedBlockContent)) { if (!(secondChild instanceof ContentControl)) { block.contentControlProperties = this.contentControlProperty(firstChild.contentControlProperties); return block; } else if ((secondChild as ContentControl).contentControlWidgetType === 'Block') { block.contentControlProperties = this.contentControlProperty(secondChild.contentControlProperties); } else { block.contentControlProperties = this.contentControlProperty(widget.contentControlProperties); } } else { block.contentControlProperties = this.contentControlProperty(widget.contentControlProperties); } return block; } } private tableContentControl(tableWidget: TableWidget): any { let block: any = {}; block.blocks = this.tableContentControls(tableWidget); if (!isNullOrUndefined(this.nextBlock)) { if (tableWidget.contentControlProperties === this.nextBlock.contentControlProperties) { return this.blocks = block.blocks; } } block.contentControlProperties = this.contentControlProperty(tableWidget.contentControlProperties); return block; } private tableContentControls(tableWidget: TableWidget): any { let blocks: any = []; if (!this.isBlockClosed) { blocks = this.blocks; } let table: any = this.createTable(tableWidget); blocks.push(table); this.nextBlock = this.writeTable(tableWidget, table, 0, blocks); return blocks; } private writeParagraph(paragraphWidget: ParagraphWidget, paragraph: any, blocks: any, lineIndex?: number, start?: number): BlockWidget { if (isNullOrUndefined(lineIndex)) { lineIndex = 0; } if (isNullOrUndefined(start)) { start = 0; } let next: BlockWidget = paragraphWidget; while (next instanceof ParagraphWidget) { if (this.writeLines(next, lineIndex, start, paragraph.inlines)) { return undefined; } lineIndex = 0; start = 0; paragraphWidget = next; next = paragraphWidget.nextSplitWidget as ParagraphWidget; } next = paragraphWidget.nextRenderedWidget as BlockWidget; if (isNullOrUndefined(next) && paragraphWidget.containerWidget instanceof BodyWidget && !isNullOrUndefined((paragraphWidget.containerWidget as BodyWidget).page.nextPage) && !isNullOrUndefined((paragraphWidget.containerWidget as BodyWidget).page.nextPage.bodyWidgets)) { next = (paragraphWidget.containerWidget as BodyWidget).page.nextPage.bodyWidgets[0].childWidgets[0] as BlockWidget; } return (next instanceof BlockWidget && paragraphWidget.containerWidget.index === next.containerWidget.index) ? next : undefined; } private writeInlines(paragraph: ParagraphWidget, line: LineWidget, inlines: any): void { this.contentInline = []; let lineWidget: LineWidget = line.clone(); let isformField: boolean = false; let bidi: boolean = paragraph.paragraphFormat.bidi; if (bidi || this.documentHelper.layout.isContainsRtl(lineWidget)) { this.documentHelper.layout.reArrangeElementsForRtl(lineWidget, bidi); } for (let i: number = 0; i < lineWidget.children.length; i++) { let element: ElementBox = lineWidget.children[i]; if (this.isExport && this.checkboxOrDropdown) { if (isformField && element instanceof TextElementBox) { continue; } if (element instanceof FieldElementBox && element.fieldType === 2) { isformField = true; } } if (element instanceof ListTextElementBox) { continue; } if (element instanceof FootnoteElementBox) { inlines.push(this.writeInlinesFootNote(paragraph, element, line, inlines)); continue; } if ((element instanceof ContentControl && !isNullOrUndefined(element.contentControlProperties) && element.contentControlProperties.type !== 'BuildingBlockGallery') || this.startContent || this.blockContent) { if (inlines.length > 0) { this.writeInlinesContentControl(element, line, inlines, i); } continue; } else { let inline: any = this.writeInline(element); if (!isNullOrUndefined(inline)) { inlines.push(inline); } } if (this.isExport && element instanceof FieldElementBox && element.fieldType === 1) { isformField = false; this.checkboxOrDropdown = false; } } } private inlineContentControl(element: ElementBox, nextElement: any, inlines?: any): any { let inline: any = {}; let nestedContentInline: any = []; if (!isNullOrUndefined(inlines)) { if (this.nestedContent) { inlines = inlines[inlines.length - 1].inlines; inline = this.inlineContentControls(element, inlines[inlines.length - 1].inlines); let nestedContentinline: any = this.nestedContentProperty(nextElement, inlines[inlines.length - 1]); if (!isNullOrUndefined(nestedContentinline)) { this.contentInline.push(inline); nestedContentInline = []; } } else { this.inlineContentControls(element, inlines[inlines.length - 1].inlines); } } else { if (this.nestedContent) { inline.inlines = this.inlineContentControls(element, undefined, nestedContentInline); let nestedContentinline: any = this.nestedContentProperty(nextElement, inline); if (!isNullOrUndefined(nestedContentinline) || this.multipleLineContent) { this.contentInline.push(inline); nestedContentInline = []; } } else { inline.inlines = this.inlineContentControls(element, this.contentInline); } } if (!isNullOrUndefined(nextElement)) { if (nextElement.type === 1 && !this.nestedContent) { if (this.multipleLineContent) { inlines[inlines.length - 1].contentControlProperties = this.contentControlProperty(nextElement.contentControlProperties); this.multipleLineContent = false; return; } else { inline.contentControlProperties = this.contentControlProperty(nextElement.contentControlProperties); } return inline; } } else if (this.startContent) { this.multipleLineContent = true; return inline; } } private nestedContentProperty(nextElement: any, inline: any, inlines?: any): any { if (!isNullOrUndefined(nextElement)) { if (nextElement.type === 1) { inline.contentControlProperties = this.contentControlProperty(nextElement.contentControlProperties); return inline; } else if (this.startContent) { this.multipleLineContent = true; return inline; } } else if (this.startContent) { this.multipleLineContent = true; return inline; } } private inlineContentControls(element: ElementBox, contentInline: any, nestedContentInline?: any): any { let inline: any = this.writeInline(element); if (!isNullOrUndefined(nestedContentInline)) { nestedContentInline.push(inline); return nestedContentInline; } contentInline.push(inline); return contentInline; } /* eslint-disable */ private writeInline(element: ElementBox): any { let inline: any = {}; if (element.removedIds.length > 0) { for (let i: number = 0; i < element.removedIds.length; i++) { element.revisions[i] = this.documentHelper.revisionsInternal.get(element.removedIds[i]); } } inline.characterFormat = this.writeCharacterFormat(element.characterFormat); if (element instanceof FieldElementBox) { inline.fieldType = element.fieldType; if (element.fieldType === 0) { inline.hasFieldEnd = true; if (element.formFieldData) { inline.formFieldData = {}; inline.formFieldData.name = element.formFieldData.name; inline.formFieldData.enabled = element.formFieldData.enabled; inline.formFieldData.helpText = element.formFieldData.helpText; inline.formFieldData.statusText = element.formFieldData.statusText; if (element.formFieldData instanceof TextFormField) { inline.formFieldData.textInput = {}; inline.formFieldData.textInput.type = (element.formFieldData as TextFormField).type; inline.formFieldData.textInput.maxLength = (element.formFieldData as TextFormField).maxLength; inline.formFieldData.textInput.defaultValue = (element.formFieldData as TextFormField).defaultValue; inline.formFieldData.textInput.format = (element.formFieldData as TextFormField).format; } else if (element.formFieldData instanceof CheckBoxFormField) { inline.formFieldData.checkBox = {}; this.checkboxOrDropdown = true; inline.formFieldData.checkBox.sizeType = (element.formFieldData as CheckBoxFormField).sizeType; inline.formFieldData.checkBox.size = (element.formFieldData as CheckBoxFormField).size; inline.formFieldData.checkBox.defaultValue = (element.formFieldData as CheckBoxFormField).defaultValue; inline.formFieldData.checkBox.checked = (element.formFieldData as CheckBoxFormField).checked; } else { inline.formFieldData.dropDownList = {}; this.checkboxOrDropdown = true; inline.formFieldData.dropDownList.dropDownItems = (element.formFieldData as DropDownFormField).dropdownItems; inline.formFieldData.dropDownList.selectedIndex = (element.formFieldData as DropDownFormField).selectedIndex; } } } if (element.fieldCodeType && element.fieldCodeType !== '') { inline.fieldCodeType = element.fieldCodeType; } } else if (element instanceof ChartElementBox) { this.writeChart(element, inline); } else if (element instanceof ImageElementBox) { inline.imageString = element.imageString; inline.metaFileImageString = element.metaFileImageString; inline.isMetaFile = element.isMetaFile; inline.isCompressed = element.isCompressed; inline.width = HelperMethods.convertPixelToPoint(element.width); inline.height = HelperMethods.convertPixelToPoint(element.height); inline.iscrop = element.isCrop; if (element.isCrop) { inline.bottom = element.bottom; inline.right = element.right; inline.left = element.left; inline.top = element.top; inline.getimagewidth = element.cropWidthScale; inline.getimageheight = element.cropHeightScale; } inline.name = element.name; inline.alternativeText = element.alternativeText; inline.title = element.title; inline.visible = element.visible; inline.widthScale = element.widthScale; inline.heightScale = element.heightScale; inline.verticalPosition = HelperMethods.convertPixelToPoint(element.verticalPosition); inline.verticalOrigin = element.verticalOrigin; inline.verticalAlignment = element.verticalAlignment; inline.horizontalPosition = HelperMethods.convertPixelToPoint(element.horizontalPosition); inline.horizontalOrigin = element.horizontalOrigin; inline.horizontalAlignment = element.horizontalAlignment; inline.allowOverlap = element.allowOverlap; inline.textWrappingStyle = element.textWrappingStyle; inline.textWrappingType = element.textWrappingType; inline.layoutInCell = element.layoutInCell; inline.zOrderPosition = element.zOrderPosition; } else if (element instanceof BookmarkElementBox) { inline.bookmarkType = element.bookmarkType; inline.name = element.name; } else if (element instanceof TextElementBox) { // replacing the no break hyphen character by '-' if (element.text.indexOf('\u001e') !== -1) { inline.text = element.text.replace(/\u001e/g, '-'); } else if (element.text.indexOf('\u001f') !== -1) { inline.text = element.text.replace(/\u001f/g, ''); } else if (element.revisions.length !== 0) { if (!this.isExport && this.owner.enableTrackChanges && !this.isPartialExport) { this.copyWithTrackChange = true; for (let x: number = 0; x < element.revisions.length; x++) { let revision: Revision = element.revisions[x]; if (this.selectedRevisionId.indexOf(revision.revisionID) === -1) { this.selectedRevisionId.push(revision.revisionID); } if (element.revisions[x].revisionType === 'Deletion') { element.revisions.pop(); } else if (element.revisions[x].revisionType === 'Insertion') { element.revisions.pop(); inline.text = element.text; } else { inline.text = element.text; } } } else { inline.text = element.text; } } else { inline.text = element.text; } } else if (element instanceof EditRangeStartElementBox) { inline.user = element.user; inline.group = element.group; inline.columnFirst = element.columnFirst; inline.columnLast = element.columnLast; inline.editRangeId = element.editRangeId.toString(); } else if (element instanceof EditRangeEndElementBox) { inline.editableRangeStart = { 'user': element.editRangeStart.user, 'group': element.editRangeStart.group, 'columnFirst': element.editRangeStart.columnFirst, 'columnLast': element.editRangeStart.columnLast }; inline.editRangeId = element.editRangeId.toString(); } else if (element instanceof CommentCharacterElementBox) { if (!this.isExport && element.commentType === 0) { this.selectedCommentsId.push(element.commentId); } inline.commentCharacterType = element.commentType; inline.commentId = element.commentId; } else if (element instanceof ShapeElementBox) { this.writeShape(element, inline); } else { inline = undefined; } if (element.revisions.length > 0) { inline.revisionIds = []; for (let x: number = 0; x < element.revisions.length; x++) { //revisionIdes[x] = element.revisions[x]; if (this.selectedRevisionId.indexOf(element.revisions[x].revisionID) === -1) { this.selectedRevisionId.push(element.revisions[x].revisionID); } inline.revisionIds.push(element.revisions[x].revisionID); //this.document.revisionIdes.push(inline.revisionIds) } } /*if(element.removedIds.length > 0){ inline.revisionIds = []; for(let x:number = 0;x < element.removedIds.length; x++){ inline.revisionIds.push(element.removedIds); } }*/ return inline; } private writeShape(element: ShapeElementBox, inline: any): void { inline.shapeId = element.shapeId; inline.name = element.name; inline.alternativeText = element.alternativeText; inline.title = element.title; inline.visible = element.visible; inline.width = HelperMethods.convertPixelToPoint(element.width); inline.height = HelperMethods.convertPixelToPoint(element.height); inline.widthScale = element.widthScale; inline.heightScale = element.heightScale; inline.verticalPosition = HelperMethods.convertPixelToPoint(element.verticalPosition); inline.verticalOrigin = element.verticalOrigin; inline.verticalAlignment = element.verticalAlignment; inline.verticalRelativePercent = element.verticalRelativePercent; inline.horizontalPosition = HelperMethods.convertPixelToPoint(element.horizontalPosition); inline.horizontalOrigin = element.horizontalOrigin; inline.horizontalAlignment = element.horizontalAlignment; inline.horizontalRelativePercent = element.horizontalRelativePercent; inline.zOrderPosition = element.zOrderPosition; inline.allowOverlap = element.allowOverlap; inline.textWrappingStyle = element.textWrappingStyle; inline.textWrappingType = element.textWrappingType; inline.distanceBottom = HelperMethods.convertPixelToPoint(element.distanceBottom); inline.distanceLeft = HelperMethods.convertPixelToPoint(element.distanceLeft); inline.distanceRight = HelperMethods.convertPixelToPoint(element.distanceRight); inline.distanceTop = HelperMethods.convertPixelToPoint(element.distanceTop); inline.layoutInCell = element.layoutInCell; inline.lockAnchor = element.lockAnchor; inline.autoShapeType = element.autoShapeType; if (element.fillFormat) { inline.fillFormat = {}; inline.fillFormat.color = element.fillFormat.color; inline.fillFormat.fill = element.fillFormat.fill; } if (element.lineFormat) { inline.lineFormat = {}; inline.lineFormat.lineFormatType = element.lineFormat.lineFormatType; inline.lineFormat.color = element.lineFormat.color; inline.lineFormat.weight = element.lineFormat.weight; inline.lineFormat.lineStyle = element.lineFormat.dashStyle; inline.lineFormat.line = element.lineFormat.line; } if (element.textFrame) { inline.textFrame = {}; inline.textFrame.textVerticalAlignment = element.textFrame.textVerticalAlignment; inline.textFrame.leftMargin = HelperMethods.convertPixelToPoint(element.textFrame.marginLeft); inline.textFrame.rightMargin = HelperMethods.convertPixelToPoint(element.textFrame.marginRight); inline.textFrame.topMargin = HelperMethods.convertPixelToPoint(element.textFrame.marginTop); inline.textFrame.bottomMargin = HelperMethods.convertPixelToPoint(element.textFrame.marginBottom); inline.textFrame.blocks = []; for (let j: number = 0; j < element.textFrame.childWidgets.length; j++) { let textFrameBlock: BlockWidget = element.textFrame.childWidgets[j] as BlockWidget; this.writeBlock(textFrameBlock, 0, inline.textFrame.blocks); } } } public writeChart(element: ChartElementBox, inline: any): void { inline.chartLegend = {}; inline.chartTitleArea = {}; inline.chartArea = {}; inline.plotArea = {}; inline.chartCategory = []; inline.chartSeries = []; inline.chartPrimaryCategoryAxis = {}; inline.chartPrimaryValueAxis = {}; this.writeChartTitleArea(element.chartTitleArea, inline.chartTitleArea); this.writeChartArea(element.chartArea, inline.chartArea); this.writeChartArea(element.chartPlotArea, inline.plotArea); this.writeChartCategory(element, inline.chartCategory); this.createChartSeries(element, inline.chartSeries); this.writeChartLegend(element.chartLegend, inline.chartLegend); this.writeChartCategoryAxis(element.chartPrimaryCategoryAxis, inline.chartPrimaryCategoryAxis); this.writeChartCategoryAxis(element.chartPrimaryValueAxis, inline.chartPrimaryValueAxis); if (element.chartDataTable.showSeriesKeys !== undefined) { inline.chartDataTable = {}; this.writeChartDataTable(element.chartDataTable, inline.chartDataTable); } inline.chartTitle = element.title; inline.chartType = element.type; inline.gapWidth = element.chartGapWidth; inline.overlap = element.chartOverlap; inline.height = HelperMethods.convertPixelToPoint(element.height); inline.width = HelperMethods.convertPixelToPoint(element.width); } private writeChartTitleArea(titleArea: ChartTitleArea, chartTitleArea: any): void { chartTitleArea.fontName = titleArea.chartfontName; chartTitleArea.fontSize = titleArea.chartFontSize; chartTitleArea.layout = {}; chartTitleArea.dataFormat = this.writeChartDataFormat(titleArea.dataFormat); this.writeChartLayout(titleArea.layout, chartTitleArea.layout); } private writeChartDataFormat(format: ChartDataFormat): any { let chartDataFormat: any = {}; chartDataFormat.fill = {}; chartDataFormat.line = {}; chartDataFormat.fill.foreColor = format.fill.color; chartDataFormat.fill.rgb = format.fill.rgb; chartDataFormat.line.color = format.line.color; chartDataFormat.line.rgb = format.line.rgb; return chartDataFormat; } private writeChartLayout(layout: ChartLayout, chartLayout: any): void { chartLayout.layoutX = layout.chartLayoutLeft; chartLayout.layoutY = layout.chartLayoutTop; } private writeChartArea(area: ChartArea, chartArea: any): void { chartArea.foreColor = area.chartForeColor; } private writeChartLegend(legend: ChartLegend, chartLegend: any): void { chartLegend.position = legend.chartLegendPostion; chartLegend.chartTitleArea = {}; this.writeChartTitleArea(legend.chartTitleArea, chartLegend.chartTitleArea); } private writeChartCategoryAxis(categoryAxis: ChartCategoryAxis, primaryCategoryAxis: any): void { primaryCategoryAxis.chartTitle = categoryAxis.categoryAxisTitle; primaryCategoryAxis.chartTitleArea = {}; this.writeChartTitleArea(categoryAxis.chartTitleArea, primaryCategoryAxis.chartTitleArea); primaryCategoryAxis.categoryType = categoryAxis.categoryAxisType; primaryCategoryAxis.fontSize = categoryAxis.axisFontSize; primaryCategoryAxis.fontName = categoryAxis.axisFontName; primaryCategoryAxis.numberFormat = categoryAxis.categoryNumberFormat; primaryCategoryAxis.maximumValue = categoryAxis.max; primaryCategoryAxis.minimumValue = categoryAxis.min; primaryCategoryAxis.majorUnit = categoryAxis.interval; primaryCategoryAxis.hasMajorGridLines = categoryAxis.majorGridLines; primaryCategoryAxis.hasMinorGridLines = categoryAxis.minorGridLines; primaryCategoryAxis.majorTickMark = categoryAxis.majorTick; primaryCategoryAxis.minorTickMark = categoryAxis.minorTick; primaryCategoryAxis.tickLabelPosition = categoryAxis.tickPosition; } private writeChartDataTable(chartDataTable: ChartDataTable, dataTable: any): void { dataTable.showSeriesKeys = chartDataTable.showSeriesKeys; dataTable.hasHorzBorder = chartDataTable.hasHorzBorder; dataTable.hasVertBorder = chartDataTable.hasVertBorder; dataTable.hasBorders = chartDataTable.hasBorders; } private writeChartCategory(element: any, chartCategory: any): void { let data: any = element.chartCategory; chartCategory.chartData = []; for (let i: number = 0; i < data.length; i++) { let xData: any = data[i]; let categories: any = this.createChartCategory(xData, element.chartType); chartCategory.push(categories); } } private createChartCategory(data: any, type: string): any { let chartCategory: any = {}; chartCategory.chartData = []; this.writeChartData(data, chartCategory.chartData, type); chartCategory.categoryXName = data.categoryXName; return chartCategory; } private writeChartData(element: any, chartData: any, type: string): any { let data: any = element.chartData; for (let i: number = 0; i < data.length; i++) { let yData: any = data[i]; let yCategory: any = this.createChartData(yData, type); chartData.push(yCategory); } } private createChartData(data: any, type: string): any { let chartData: any = {}; chartData.yValue = data.yValue; if (type === 'Bubble') { chartData.size = data.size; } return chartData; } private createChartSeries(element: any, chartSeries: any): any { let data: any = element.chartSeries; let type: string = element.chartType; for (let i: number = 0; i < data.length; i++) { let yData: any = data[i]; let series: any = this.writeChartSeries(yData, type); chartSeries.push(series); } } private writeChartSeries(series: any, type: string): any { let isPieType: boolean = (type === 'Pie' || type === 'Doughnut'); let chartSeries: any = {}; let errorBar: any = {}; let errorBarData: any = series.errorBar; chartSeries.dataPoints = []; chartSeries.seriesName = series.seriesName; if (isPieType) { if (!isNullOrUndefined(series.firstSliceAngle)) { chartSeries.firstSliceAngle = series.firstSliceAngle; } if (type === 'Doughnut') { chartSeries.holeSize = series.doughnutHoleSize; } } if (!isNullOrUndefined(series.dataLabels.labelPosition)) { let dataLabel: any = this.writeChartDataLabels(series.dataLabels); chartSeries.dataLabel = dataLabel; } if (!isNullOrUndefined(series.seriesFormat.markerStyle)) { let seriesFormat: any = {}; let format: any = series.seriesFormat; seriesFormat.markerStyle = format.markerStyle; seriesFormat.markerSize = format.numberValue; seriesFormat.markerColor = format.markerColor; chartSeries.seriesFormat = seriesFormat; } if (!isNullOrUndefined(errorBarData.type)) { errorBar.type = errorBarData.type; errorBar.direction = errorBarData.direction; errorBar.endStyle = errorBarData.endStyle; errorBar.numberValue = errorBarData.numberValue; chartSeries.errorBar = errorBarData; } if (series.trendLines.length > 0) { chartSeries.trendLines = []; for (let i: number = 0; i < series.trendLines.length; i++) { let trendLine: any = this.writeChartTrendLines(series.trendLines[i]); chartSeries.trendLines.push(trendLine); } } for (let i: number = 0; i < series.chartDataFormat.length; i++) { let format: any = this.writeChartDataFormat(series.chartDataFormat[i]); chartSeries.dataPoints.push(format); } return chartSeries; } private writeChartDataLabels(dataLabels: any): any { let dataLabel: any = {}; dataLabel.position = dataLabels.position; dataLabel.fontName = dataLabels.fontName; dataLabel.fontColor = dataLabels.fontColor; dataLabel.fontSize = dataLabels.fontSize; dataLabel.isLegendKey = dataLabels.isLegendKey; dataLabel.isBubbleSize = dataLabels.isBubbleSize; dataLabel.isCategoryName = dataLabels.isCategoryName; dataLabel.isSeriesName = dataLabels.isSeriesName; dataLabel.isValue = dataLabels.isValue; dataLabel.isPercentage = dataLabels.isPercentage; dataLabel.isLeaderLines = dataLabels.isLeaderLines; return dataLabel; } private writeChartTrendLines(trendLines: any): any { let trendLine: any = {}; trendLine.name = trendLines.trendLineName; trendLine.type = trendLines.trendLineType; trendLine.forward = trendLines.forwardValue; trendLine.backward = trendLines.backwardValue; trendLine.intercept = trendLines.interceptValue; trendLine.isDisplayEquation = trendLines.isDisplayEquation; trendLine.isDisplayRSquared = trendLines.isDisplayRSquared; return trendLine; } private writeLines(paragraph: ParagraphWidget, lineIndex: number, offset: number, inlines: any): boolean { let startIndex: number = lineIndex; let endParagraph: boolean = this.endLine instanceof LineWidget && this.endLine.paragraph === paragraph; let endIndex: number = endParagraph ? this.endLine.indexInOwner : paragraph.childWidgets.length - 1; for (let i: number = startIndex; i <= endIndex; i++) { let child: LineWidget = paragraph.childWidgets[i] as LineWidget; if (this.endLine === child || (lineIndex === i && offset !== 0)) { this.writeLine(child, (this.startLine !== this.endLine && child !== this.startLine) ? 0 : offset, inlines); } else { this.writeInlines(paragraph, child, inlines); } } return endParagraph; } private writeLine(line: LineWidget, offset: number, inlines: any): void { this.contentInline = []; let isContentStarted: boolean = false; let contentControl: boolean = false; let isEnd: boolean = line === this.endLine; let lineWidget: LineWidget = line.clone(); let bidi: boolean = line.paragraph.paragraphFormat.bidi; if (bidi || this.documentHelper.layout.isContainsRtl(lineWidget)) { this.documentHelper.layout.reArrangeElementsForRtl(lineWidget, bidi); } let started: boolean = false; let ended: boolean = false; let length: number = 0; for (let j: number = 0; j < lineWidget.children.length; j++) { let element: ElementBox = lineWidget.children[j]; if (element instanceof ListTextElementBox) { continue; } let inline: any = undefined; length += element.length; started = length > offset; if (element instanceof ContentControl) { if (!started) { isContentStarted = element.type === 0 ? true : false; } contentControl = true; } if (element instanceof TextElementBox && element.hasOwnProperty('contentControlProperties') && started && !contentControl) { isContentStarted = true; } if (element instanceof ContentControl) { if (isContentStarted) { if (element.type === 1) { isContentStarted = false; } } if (contentControl) { if (element.type === 1) { contentControl = false; } } } ended = isEnd && length >= this.endOffset; if (!started || isContentStarted) { continue; } if ((element instanceof ContentControl && !isNullOrUndefined(element.contentControlProperties) && element.contentControlProperties.type !== 'BuildingBlockGallery') || this.startContent || this.blockContent) { if (ended) { this.startContent = false; break; } this.writeInlinesContentControl(element, line, inlines, j); continue; } inline = this.writeInline(element); inlines[inlines.length] = inline; if (length > offset || ended) { if (inline.hasOwnProperty('text')) { let startIndex: number = length - element.length; let indexInInline: number = offset - startIndex; let endIndex: number = ended ? this.endOffset - startIndex : element.length; inline.text = inline.text.substring(indexInInline, endIndex); } offset = -1; } if (ended) { break; } } } private writeInlinesFootNote(paragraph: any, element: any, line: any, inlines: any): any { let inline: any = {}; inline.footnoteType = element.footnoteType; inline.characterFormat = {}; inline.characterFormat = this.writeCharacterFormat(element.characterFormat); inline.blocks = []; for (let i: number = 0; i < element.blocks.length; i++) { this.writeBlock(element.blocks[i], 0, inline.blocks); } inline.symbolCode = element.symbolCode; inline.symbolFontName = element.symbolFontName; inline.customMarker = element.customMarker; return inline; } private writeInlinesContentControl(element: ElementBox, lineWidget: LineWidget, inlines: any, i: number): any { if (element instanceof ContentControl) { if (element.contentControlWidgetType === 'Block') { this.isBlockClosed = false; if (this.blockContent && element.type === 0) { this.nestedBlockContent = true; return true; } else if (this.nestedBlockContent && element.type === 1) { this.nestedBlockContent = false; return true; } this.blockContent = (element.type === 0) ? true : false; if (lineWidget.children[i - 1] instanceof ContentControl) { if ((lineWidget.children[i - 1] as ContentControl).contentControlWidgetType === 'Block') { this.blockContent = true; } } if (!this.blockContent) { this.isBlockClosed = true; } return true; } } if (element instanceof ContentControl) { if (this.startContent && element.type === 0) { this.nestedContent = true; return true; } else if (this.startContent && this.nestedContent) { let inline: any = {}; inline.inlines = this.contentInline; if (this.contentInline.length > 0) { let nestedContent: any = this.nestedContentProperty(lineWidget.children[i + 1], inline); inlines.push(nestedContent); this.contentInline = []; } if (this.multipleLineContent) { inline = inlines[inlines.length - 1]; this.nestedContentProperty(lineWidget.children[i + 1], inline); this.multipleLineContent = false; } this.nestedContent = false; return true; } this.contentType = element.contentControlWidgetType; this.startContent = (element.type === 0) ? true : false; return true; } if (this.startContent && ((this.contentType === 'Inline'))) { if (this.multipleLineContent) { this.inlineContentControl(element, lineWidget.children[i + 1], inlines); this.contentInline = []; } else { let contentinline: any = this.inlineContentControl(element, lineWidget.children[i + 1]); if (!isNullOrUndefined(contentinline)) { if (this.nestedContent && this.multipleLineContent) { let inline: any = {}; inline.inlines = this.contentInline; inlines.push(inline); } else { inlines.push(contentinline); this.contentInline = []; return false; } } } } else { let inline: any = this.writeInline(element); if (!isNullOrUndefined(inline)) { inlines.push(inline); } } } private createParagraph(paragraphWidget: ParagraphWidget): any { let paragraph: any = {}; let isParaSelected: boolean = false; if (this.documentHelper.selection && !this.documentHelper.selection.isEmpty && !this.isExport) { let endPos: TextPosition = this.documentHelper.selection.end; if (!this.documentHelper.selection.isForward) { endPos = this.documentHelper.selection.start; } let lastLine: LineWidget = endPos.paragraph.childWidgets[endPos.paragraph.childWidgets.length - 1] as LineWidget; isParaSelected = this.documentHelper.selection.isParagraphLastLine(lastLine) && endPos.currentWidget === lastLine && endPos.offset === this.documentHelper.selection.getLineLength(lastLine) + 1; } else { isParaSelected = true; } paragraph.paragraphFormat = this.writeParagraphFormat(isParaSelected ? paragraphWidget.paragraphFormat : new WParagraphFormat(paragraphWidget)); paragraph.characterFormat = this.writeCharacterFormat(isParaSelected ? paragraphWidget.characterFormat : new WCharacterFormat(paragraphWidget)); paragraph.inlines = []; return paragraph; } /** * @private */ public writeCharacterFormat(format: WCharacterFormat, isInline?: boolean): any { let characterFormat: any = {}; HelperMethods.writeCharacterFormat(characterFormat, isInline, format); characterFormat.boldBidi = isInline ? format.bold : format.getValue('bold'); characterFormat.italicBidi = isInline ? format.italic : format.getValue('italic'); characterFormat.fontSizeBidi = isInline ? format.fontSize : format.getValue('fontSize'); characterFormat.fontFamilyBidi = isInline ? format.fontFamily : format.getValue('fontFamily'); if (this.writeInlineStyles && !isInline) { characterFormat.inlineFormat = this.writeCharacterFormat(format, true); } return characterFormat; } private writeParagraphFormat(format: WParagraphFormat, isInline?: boolean): any { let paragraphFormat: any = {}; paragraphFormat.leftIndent = isInline ? format.leftIndent : format.getValue('leftIndent'); paragraphFormat.rightIndent = isInline ? format.rightIndent : format.getValue('rightIndent'); paragraphFormat.firstLineIndent = isInline ? format.firstLineIndent : format.getValue('firstLineIndent'); paragraphFormat.textAlignment = isInline ? format.textAlignment : format.getValue('textAlignment'); paragraphFormat.beforeSpacing = isInline ? format.beforeSpacing : format.getValue('beforeSpacing'); paragraphFormat.afterSpacing = isInline ? format.afterSpacing : format.getValue('afterSpacing'); paragraphFormat.lineSpacing = isInline ? format.lineSpacing : format.getValue('lineSpacing'); paragraphFormat.lineSpacingType = isInline ? format.lineSpacingType : format.getValue('lineSpacingType'); paragraphFormat.styleName = !isNullOrUndefined(format.baseStyle) ? format.baseStyle.name : undefined; paragraphFormat.outlineLevel = isInline ? format.outlineLevel : format.getValue('outlineLevel'); paragraphFormat.listFormat = this.writeListFormat(format.listFormat, isInline); paragraphFormat.tabs = this.writeTabs(format.tabs); paragraphFormat.bidi = isInline ? format.bidi : format.getValue('bidi'); paragraphFormat.keepLinesTogether = isInline ? format.keepLinesTogether : format.getValue('keepLinesTogether'); paragraphFormat.keepWithNext = isInline ? format.keepWithNext : format.getValue('keepWithNext'); paragraphFormat.contextualSpacing = isInline ? format.contextualSpacing : format.getValue('contextualSpacing'); paragraphFormat.widowControl = isInline ? format.widowControl : format.getValue('widowControl'); if (this.writeInlineStyles && !isInline) { paragraphFormat.inlineFormat = this.writeParagraphFormat(format, true); } return paragraphFormat; } private writeTabs(tabStops: WTabStop[]): any { if (isNullOrUndefined(tabStops) || tabStops.length < 1) { return undefined; } let tabs: any = []; for (let i: number = 0; i < tabStops.length; i++) { let tabStop: WTabStop = tabStops[i]; let tab: any = {}; tab.position = tabStop.position; tab.deletePosition = tabStop.deletePosition; tab.tabJustification = tabStop.tabJustification; tab.tabLeader = tabStop.tabLeader; tabs.push(tab); } return tabs; } /** * @private */ public writeListFormat(format: WListFormat, isInline?: boolean): any { let listFormat: any = {}; let listIdValue: Object = format.getValue('listId'); if (!isNullOrUndefined(listIdValue)) { listFormat.listId = listIdValue; if (this.lists.indexOf(format.listId) < 0) { this.lists.push(format.listId); } } let listLevelNumber: Object = format.getValue('listLevelNumber'); if (!isNullOrUndefined(listLevelNumber)) { listFormat.listLevelNumber = listLevelNumber; } return listFormat; } private writeTable(tableWidget: TableWidget, table: any, index: number, blocks: any): BlockWidget { let widget: IWidget = tableWidget.childWidgets[index]; if (widget instanceof TableRowWidget) { if (this.writeRow(widget, table.rows)) { return undefined; } } let next: BlockWidget = tableWidget; do { tableWidget = next as TableWidget; next = tableWidget.nextSplitWidget as TableWidget; } while (next instanceof BlockWidget); next = tableWidget.nextRenderedWidget as BlockWidget; return (next instanceof BlockWidget && next.containerWidget.index === tableWidget.containerWidget.index) ? next : undefined; } private writeRow(rowWidget: TableRowWidget, rows: any): boolean { if (!(rowWidget instanceof TableRowWidget)) { return false; } let row: any = this.createRow(rowWidget); rows.push(row); for (let i: number = 0; i < rowWidget.childWidgets.length; i++) { let widget: IWidget = rowWidget.childWidgets[i]; if (widget instanceof TableCellWidget) { if (rowWidget.index === widget.rowIndex && (isNullOrUndefined(this.startColumnIndex) || widget.columnIndex >= this.startColumnIndex) && (isNullOrUndefined(this.endColumnIndex) || widget.columnIndex < this.endColumnIndex)) { if (this.writeCell(widget, row.cells)) { return true; } } } } let next: TableRowWidget = rowWidget; do { rowWidget = next; next = rowWidget.nextRenderedWidget as TableRowWidget; if (!isNullOrUndefined(rowWidget.ownerTable.bodyWidget) && next && ((rowWidget.ownerTable.index !== next.ownerTable.index && rowWidget.ownerTable.bodyWidget.sectionIndex === next.ownerTable.bodyWidget.sectionIndex) || rowWidget.ownerTable.bodyWidget.sectionIndex !== next.ownerTable.bodyWidget.sectionIndex)) { next = undefined; } } while (next instanceof TableRowWidget && next.index === rowWidget.index); return this.writeRow(next, rows); } private writeCell(cellWidget: TableCellWidget, cells: any): boolean { let cell: any = this.createCell(cellWidget); cells.push(cell); let firstBlock: BlockWidget = cellWidget.firstChild as BlockWidget; do { firstBlock = this.writeBlock(firstBlock as BlockWidget, 0, cell.blocks); } while (firstBlock); return this.endCell instanceof TableCellWidget ? this.endCell.cellFormat === cellWidget.cellFormat : false; } private createTable(tableWidget: TableWidget): any { let table: any = {}; table.rows = []; table.grid = []; for (let i: number = 0; i < tableWidget.tableHolder.columns.length; i++) { table.grid[i] = tableWidget.tableHolder.columns[i].preferredWidth; } table.tableFormat = this.writeTableFormat(tableWidget.tableFormat); table.description = tableWidget.description; table.title = tableWidget.title; table.columnCount = tableWidget.tableHolder.columns.length; this.writeTablePositioning(table, tableWidget); return table; } private writeTablePositioning(table: any, tableWidget: TableWidget): void { if (tableWidget.wrapTextAround) { table.wrapTextAround = tableWidget.wrapTextAround; table.positioning = {}; table.positioning.allowOverlap = tableWidget.positioning.allowOverlap; table.positioning.distanceBottom = HelperMethods.convertPixelToPoint(tableWidget.positioning.distanceBottom); table.positioning.distanceLeft = HelperMethods.convertPixelToPoint(tableWidget.positioning.distanceLeft); table.positioning.distanceRight = HelperMethods.convertPixelToPoint(tableWidget.positioning.distanceRight); table.positioning.distanceTop = HelperMethods.convertPixelToPoint(tableWidget.positioning.distanceTop); if (!isNullOrUndefined(tableWidget.positioning.verticalAlignment)) { table.positioning.verticalAlignment = tableWidget.positioning.verticalAlignment; } if (!isNullOrUndefined(tableWidget.positioning.verticalOrigin)) { table.positioning.verticalOrigin = tableWidget.positioning.verticalOrigin; } table.positioning.verticalPosition = tableWidget.positioning.verticalPosition; if (!isNullOrUndefined(tableWidget.positioning.horizontalAlignment)) { table.positioning.horizontalAlignment = tableWidget.positioning.horizontalAlignment; } if (!isNullOrUndefined(tableWidget.positioning.horizontalOrigin)) { table.positioning.horizontalOrigin = tableWidget.positioning.horizontalOrigin; } table.positioning.horizontalPosition = tableWidget.positioning.horizontalPosition; } } private createRow(rowWidget: TableRowWidget): any { let row: any = {}; row.cells = []; row.rowFormat = this.writeRowFormat(rowWidget.rowFormat); if (rowWidget.hasOwnProperty('contentControlProperties')) { row.contentControlProperties = this.contentControlProperty(rowWidget.contentControlProperties); } return row; } private createCell(cellWidget: TableCellWidget): any { let cell: any = {}; cell.blocks = []; cell.cellFormat = this.writeCellFormat(cellWidget.cellFormat); cell.columnIndex = cellWidget.columnIndex; if (cellWidget.hasOwnProperty('contentControlProperties')) { cell.contentControlProperties = this.contentControlProperty(cellWidget.contentControlProperties); } return cell; } private writeShading(wShading: WShading): any { let shading: any = {}; shading.backgroundColor = wShading.hasValue('backgroundColor') ? wShading.backgroundColor : undefined; shading.foregroundColor = wShading.hasValue('foregroundColor') ? wShading.foregroundColor : undefined; shading.textureStyle = wShading.hasValue('textureStyle') ? wShading.textureStyle : undefined; return shading; } private writeBorder(wBorder: WBorder): any { let border: any = {}; border.color = wBorder.hasValue('color') ? wBorder.color : undefined; border.hasNoneStyle = wBorder.hasValue('hasNoneStyle') ? wBorder.hasNoneStyle : undefined; border.lineStyle = wBorder.hasValue('lineStyle') ? wBorder.lineStyle : undefined; border.lineWidth = wBorder.hasValue('lineWidth') ? wBorder.lineWidth : undefined; border.shadow = wBorder.hasValue('shadow') ? wBorder.shadow : undefined; border.space = wBorder.hasValue('space') ? wBorder.space : undefined; return border; } private writeBorders(wBorders: WBorders): any { let borders: any = {}; borders.top = this.writeBorder(wBorders.top); borders.left = this.writeBorder(wBorders.left); borders.right = this.writeBorder(wBorders.right); borders.bottom = this.writeBorder(wBorders.bottom); borders.diagonalDown = this.writeBorder(wBorders.diagonalDown); borders.diagonalUp = this.writeBorder(wBorders.diagonalUp); borders.horizontal = this.writeBorder(wBorders.horizontal); borders.vertical = this.writeBorder(wBorders.vertical); return borders; } private writeCellFormat(wCellFormat: WCellFormat): any { let cellFormat: any = {}; cellFormat.borders = this.writeBorders(wCellFormat.borders); cellFormat.shading = this.writeShading(wCellFormat.shading); cellFormat.topMargin = wCellFormat.hasValue('topMargin') ? wCellFormat.topMargin : undefined; cellFormat.rightMargin = wCellFormat.hasValue('rightMargin') ? wCellFormat.rightMargin : undefined; cellFormat.leftMargin = wCellFormat.hasValue('leftMargin') ? wCellFormat.leftMargin : undefined; cellFormat.bottomMargin = wCellFormat.hasValue('bottomMargin') ? wCellFormat.bottomMargin : undefined; cellFormat.preferredWidth = wCellFormat.hasValue('preferredWidth') ? wCellFormat.preferredWidth : undefined; cellFormat.preferredWidthType = wCellFormat.hasValue('preferredWidthType') ? wCellFormat.preferredWidthType : undefined; cellFormat.cellWidth = wCellFormat.hasValue('cellWidth') ? wCellFormat.cellWidth : undefined; cellFormat.columnSpan = wCellFormat.columnSpan; cellFormat.rowSpan = wCellFormat.rowSpan; cellFormat.verticalAlignment = wCellFormat.hasValue('verticalAlignment') ? wCellFormat.verticalAlignment : undefined; return cellFormat; } private writeRowFormat(wRowFormat: WRowFormat): any { let rowFormat: any = {}; let revisionIds: any = []; rowFormat.height = wRowFormat.hasValue('height') ? wRowFormat.height : undefined; rowFormat.allowBreakAcrossPages = wRowFormat.hasValue('allowBreakAcrossPages') ? wRowFormat.allowBreakAcrossPages : undefined; rowFormat.heightType = wRowFormat.hasValue('heightType') ? wRowFormat.heightType : undefined; rowFormat.isHeader = wRowFormat.hasValue('isHeader') ? wRowFormat.isHeader : undefined; rowFormat.borders = this.writeBorders(wRowFormat.borders); rowFormat.gridBefore = wRowFormat.gridBefore; rowFormat.gridBeforeWidth = wRowFormat.hasValue('gridBeforeWidth') ? wRowFormat.gridBeforeWidth : undefined; rowFormat.gridBeforeWidthType = wRowFormat.hasValue('gridBeforeWidthType') ? wRowFormat.gridBeforeWidthType : undefined; rowFormat.gridAfter = wRowFormat.gridAfter; rowFormat.gridAfterWidth = wRowFormat.hasValue('gridAfterWidth') ? wRowFormat.gridAfterWidth : undefined; rowFormat.gridAfterWidthType = wRowFormat.hasValue('gridAfterWidthType') ? wRowFormat.gridAfterWidthType : undefined; rowFormat.leftMargin = wRowFormat.hasValue('leftMargin') ? wRowFormat.leftMargin : undefined; rowFormat.topMargin = wRowFormat.hasValue('topMargin') ? wRowFormat.topMargin : undefined; rowFormat.rightMargin = wRowFormat.hasValue('rightMargin') ? wRowFormat.rightMargin : undefined; rowFormat.bottomMargin = wRowFormat.hasValue('bottomMargin') ? wRowFormat.bottomMargin : undefined; rowFormat.leftIndent = wRowFormat.hasValue('leftIndent') ? wRowFormat.leftIndent : undefined; for (let j: number = 0; j < wRowFormat.revisions.length; j++) { rowFormat.revisionIds = this.writeRowRevisions(wRowFormat.revisions[j], revisionIds); } return rowFormat; } private writeRowRevisions(wrevisions: Revision, revisionIds: any): any { if (this.selectedRevisionId.indexOf(wrevisions.revisionID) === -1) { this.selectedRevisionId.push(wrevisions.revisionID); } revisionIds.push(wrevisions.revisionID); return revisionIds; } private writeTableFormat(wTableFormat: WTableFormat): any { let tableFormat: any = {}; tableFormat.borders = this.writeBorders(wTableFormat.borders); tableFormat.shading = this.writeShading(wTableFormat.shading); tableFormat.cellSpacing = wTableFormat.hasValue('cellSpacing') ? wTableFormat.cellSpacing : undefined; tableFormat.leftIndent = wTableFormat.hasValue('leftIndent') ? wTableFormat.leftIndent : undefined; tableFormat.tableAlignment = wTableFormat.hasValue('tableAlignment') ? wTableFormat.tableAlignment : undefined; tableFormat.topMargin = wTableFormat.hasValue('topMargin') ? wTableFormat.topMargin : undefined; tableFormat.rightMargin = wTableFormat.hasValue('rightMargin') ? wTableFormat.rightMargin : undefined; tableFormat.leftMargin = wTableFormat.hasValue('leftMargin') ? wTableFormat.leftMargin : undefined; tableFormat.bottomMargin = wTableFormat.hasValue('bottomMargin') ? wTableFormat.bottomMargin : undefined; tableFormat.preferredWidth = wTableFormat.hasValue('preferredWidth') ? wTableFormat.preferredWidth : undefined; tableFormat.preferredWidthType = wTableFormat.hasValue('preferredWidthType') ? wTableFormat.preferredWidthType : undefined; tableFormat.bidi = wTableFormat.hasValue('bidi') ? wTableFormat.bidi : undefined; tableFormat.allowAutoFit = wTableFormat.hasValue('allowAutoFit') ? wTableFormat.allowAutoFit : undefined; return tableFormat; } private footnotes(documentHelper: DocumentHelper): void { for (let i: number = 0; i < documentHelper.footnotes.separator.length; i++) { this.seprators(documentHelper); } } private seprators(documentHelper: any): any { if (documentHelper.footnotes.separator.length > 0) { this.document.footnotes = {}; this.document.footnotes.separator = []; for (let i: number = 0; i < documentHelper.footnotes.separator.length; i++) { this.writeBlock(documentHelper.footnotes.separator[i], 0, this.document.footnotes.separator); } } if (documentHelper.footnotes.continuationSeparator.length > 0) { this.document.footnotes.continuationSeparator = []; for (let i: number = 0; i < documentHelper.footnotes.continuationSeparator.length; i++) { this.writeBlock(documentHelper.footnotes.continuationSeparator[i], 0, this.document.footnotes.continuationSeparator); } } if (documentHelper.footnotes.continuationNotice.length > 0) { this.document.footnotes.continuationNotice = []; for (let i: number = 0; i < documentHelper.footnotes.continuationNotice.length; i++) { this.writeBlock(documentHelper.footnotes.continuationNotice[i], 0, this.document.footnotes.continuationNotice); } } } private endnotes(documentHelper: DocumentHelper): void { for (let i: number = 0; i < this.documentHelper.endnotes.separator.length; i++) { this.endnoteSeparator(documentHelper); } } private endnoteSeparator(documentHelper: DocumentHelper): void { if (documentHelper.endnotes.separator.length > 0) { this.document.endnotes = {}; this.document.endnotes.separator = []; for (let i: number = 0; i < documentHelper.endnotes.separator.length; i++) { this.writeBlock(documentHelper.endnotes.separator[i], 0, this.document.endnotes.separator); } } if (documentHelper.endnotes.continuationSeparator.length > 0) { this.document.endnotes.continuationSeparator = []; for (let i: number = 0; i < documentHelper.endnotes.continuationSeparator.length; i++) { this.writeBlock(documentHelper.endnotes.continuationSeparator[i], 0, this.document.endnotes.continuationSeparator); } } if (documentHelper.endnotes.continuationNotice.length > 0) { this.document.endnotes.continuationNotice = []; for (let i: number = 0; i < documentHelper.endnotes.continuationNotice.length; i++) { this.writeBlock(documentHelper.endnotes.continuationNotice[i], 0, this.document.endnotes.continuationNotice); } } } private writeStyles(documentHelper: DocumentHelper): void { let styles: Object[] = []; this.document.styles = []; for (let i: number = 0; i < documentHelper.styles.length; i++) { this.document.styles.push(this.writeStyle(documentHelper.styles.getItem(i) as WStyle)); } } private writeStyle(style: WStyle): any { let wStyle: any = {}; wStyle.name = style.name; if (style.type === 'Paragraph') { wStyle.type = 'Paragraph'; wStyle.paragraphFormat = this.writeParagraphFormat((style as any).paragraphFormat); wStyle.characterFormat = this.writeCharacterFormat((style as any).characterFormat); } if (style.type === 'Character') { wStyle.type = 'Character'; wStyle.characterFormat = this.writeCharacterFormat((style as any).characterFormat); } if (!isNullOrUndefined(style.basedOn)) { wStyle.basedOn = style.basedOn.name; } if (!isNullOrUndefined(style.link)) { wStyle.link = style.link.name; } if (!isNullOrUndefined(style.next)) { wStyle.next = style.next.name; } return wStyle; } public writeRevisions(documentHelper: DocumentHelper): void { this.document.revisions = []; for (let i: number = 0; i < documentHelper.owner.revisions.changes.length; i++) { if (this.isExport || (!this.isExport && this.selectedRevisionId.indexOf(documentHelper.owner.revisions.changes[i].revisionID) !== -1)) { this.document.revisions.push(this.writeRevision(documentHelper.owner.revisions.changes[i])); } } } private writeRevision(revisions: Revision): any { let revision: any = {}; revision.author = revisions.author; revision.date = revisions.date; revision.revisionType = revisions.revisionType; revision.revisionId = revisions.revisionID; return revision; } public writeComments(documentHelper: DocumentHelper): void { this.document.comments = []; for (let i: number = 0; i < documentHelper.comments.length; i++) { if (this.isExport || (!this.isExport && this.selectedCommentsId.indexOf(this.documentHelper.comments[i].commentId) !== -1)) { this.document.comments.push(this.writeComment(this.documentHelper.comments[i])); } } } public writeCustomXml(documentHelper: DocumentHelper): void { this.document.customXml = []; for (let i: number = 0; i < documentHelper.customXmlData.length; i++) { let customXml: any = {}; let key: string = documentHelper.customXmlData.keys[i]; customXml.itemID = key; let xmlValue: string = this.documentHelper.customXmlData.get(key); customXml.xml = xmlValue; this.document.customXml.push(customXml); } } private writeComment(comments: CommentElementBox): any { let comment: any = {}; comment.commentId = comments.commentId; comment.author = comments.author; comment.date = comments.date; comment.blocks = []; comment.blocks.push(this.commentInlines(comments.text)); comment.done = comments.isResolved; comment.replyComments = []; for (let i: number = 0; i < comments.replyComments.length; i++) { comment.replyComments.push(this.writeComment(comments.replyComments[i])); } return comment; } private commentInlines(ctext: string): any { let blocks: any = {}; blocks.inlines = [{ text: ctext }]; return blocks; } private writeLists(documentHelper: DocumentHelper): void { let abstractLists: number[] = []; this.document.lists = []; for (let i: number = 0; i < documentHelper.lists.length; i++) { let list: WList = documentHelper.lists[i]; if (this.lists.indexOf(list.listId) > -1) { this.document.lists.push(this.writeList(list)); if (abstractLists.indexOf(list.abstractListId) < 0) { abstractLists.push(list.abstractListId); } } } this.document.abstractLists = []; for (let i: number = 0; i < documentHelper.abstractLists.length; i++) { let abstractList: WAbstractList = documentHelper.abstractLists[i]; if (abstractLists.indexOf(abstractList.abstractListId) > -1) { this.document.abstractLists.push(this.writeAbstractList(abstractList)); } } } private writeAbstractList(wAbstractList: WAbstractList): any { let abstractList: any = {}; abstractList.abstractListId = wAbstractList.abstractListId; abstractList.levels = []; for (let i: number = 0; i < wAbstractList.levels.length; i++) { abstractList.levels[i] = this.writeListLevel(wAbstractList.levels[i]); } return abstractList; } private writeList(wList: WList): any { let list: any = {}; list.abstractListId = wList.abstractListId; list.levelOverrides = []; for (let i: number = 0; i < wList.levelOverrides.length; i++) { list.levelOverrides.push(this.writeLevelOverrides(wList.levelOverrides[i])); } list.listId = wList.listId; return list; } private writeLevelOverrides(wlevel: WLevelOverride): any { let levelOverrides: any = {}; levelOverrides.levelNumber = wlevel.levelNumber; if (wlevel.overrideListLevel) { levelOverrides.overrideListLevel = this.writeListLevel(wlevel.overrideListLevel); } levelOverrides.startAt = wlevel.startAt; return levelOverrides; } private writeListLevel(wListLevel: WListLevel): any { let listLevel: any = {}; listLevel.characterFormat = this.writeCharacterFormat(wListLevel.characterFormat); listLevel.paragraphFormat = this.writeParagraphFormat(wListLevel.paragraphFormat); listLevel.followCharacter = wListLevel.followCharacter; listLevel.listLevelPattern = wListLevel.listLevelPattern; listLevel.numberFormat = wListLevel.numberFormat; listLevel.restartLevel = wListLevel.restartLevel; listLevel.startAt = wListLevel.startAt; return listLevel; } private getParentBlock(widget: BlockWidget): BlockWidget { if (widget.isInsideTable) { widget = this.owner.documentHelper.layout.getParentTable(widget); } return widget; } /** * @private * @returns {void} */ public destroy(): void { this.lists = undefined; this.endLine = undefined; this.startLine = undefined; this.endOffset = undefined; this.documentHelper = undefined; } /* eslint-enable @typescript-eslint/no-explicit-any */ }
the_stack
import * as React from "react"; import * as R from "../../../../resources"; import * as globals from "../../../../globals"; import { ContextedComponent } from "../../../../context_component"; import { PopupView } from "../../../../controllers/popup_controller"; import { classNames } from "../../../../utils"; import { strings } from "../../../../../strings"; import { ActionButton, Label, Image as FluentUIImage, DefaultButton, TextField, } from "@fluentui/react"; import { defaultLabelStyle, defultBindButtonSize, FluentActionButton, FluentButton, } from "./fluentui_customized_components"; import { ImageMappingDragStateWrapper, ImageMappingTextFieldStyles, } from "./styles"; export interface ImageDescription { src: string; width: number; height: number; name?: string; } export interface InputImageProps { value?: ImageDescription; onChange?: (value: ImageDescription) => boolean; label?: string; } export class InputImage extends ContextedComponent< InputImageProps, { dragOver: boolean } > { public state = { dragOver: false }; public element: HTMLSpanElement; public resolveImage(value: ImageDescription) { return value; } public emitOnChange(images: ImageUploaderItem[]) { if (images.length == 1) { this.props.onChange({ src: images[0].dataURL, width: images[0].width, height: images[0].height, }); } } public startChooseImage = () => { globals.popupController.popupAt( (context) => { return ( <PopupView context={context}> <ImageChooser value={this.props.value} onChoose={(image: ImageDescription) => { context.close(); if (this.props.onChange) { this.props.onChange(image); } }} /> </PopupView> ); }, { anchor: this.element } ); }; protected handleDragEnter = () => { this.setState({ dragOver: true }); }; protected handleDragLeave = () => { this.setState({ dragOver: false }); }; protected handleDragOver = (e: React.DragEvent<HTMLDivElement>) => { e.preventDefault(); }; protected handleDrop = (e: React.DragEvent<HTMLDivElement>) => { e.preventDefault(); this.setState({ dragOver: false }); if (e.dataTransfer.types.indexOf("text/uri-list") >= 0) { const uriList = e.dataTransfer.getData("text/uri-list") as string; const uris = uriList .replace(/\r/g, "") .split("\n") .map((x) => x.trim()) .filter((x) => !x.startsWith("#")); ImageUploader.ParseURIs(uris) .then((r) => { this.emitOnChange(r); }) .catch(() => {}); } if (e.dataTransfer.files.length > 0) { ImageUploader.ParseFiles(e.dataTransfer.files).then((r) => { this.emitOnChange(r); }); } }; public render() { const isNone = this.props.value == null; const image = isNone ? null : this.resolveImage(this.props.value); let imageDisplayURL = image ? image.src : null; if (imageDisplayURL) { if (imageDisplayURL.startsWith("data:")) { imageDisplayURL = "(data url)"; } } return ( <span className={classNames( "charticulator__widget-control-input-image", ["is-none", isNone], ["is-drag-over", this.state.dragOver] )} ref={(e) => (this.element = e)} onDragEnter={this.handleDragEnter} onDragLeave={this.handleDragLeave} onDragOver={this.handleDragOver} onDrop={this.handleDrop} onClick={this.startChooseImage} // style={{ marginBottom: "5px" }} > {this.state.dragOver ? ( <div style={{ width: "100%" }}> {this.props.label ? ( <Label styles={defaultLabelStyle} style={{ padding: 0 }}> {this.props.label} </Label> ) : null} <span className="el-drag-over-attrubutes"> {strings.objects.image.dropImage} </span> </div> ) : ( <div style={{ width: "100%" }}> {this.props.label ? ( <Label styles={defaultLabelStyle} style={{ padding: 0 }}> {this.props.label} </Label> ) : null} <FluentActionButton style={{ width: "100%", height: defultBindButtonSize.height }} > <ActionButton styles={{ root: { height: defultBindButtonSize.height, }, }} text={isNone ? strings.core.none : imageDisplayURL} iconProps={{ imageProps: { src: isNone ? R.getSVGIcon("FileImage") : image.src, style: { height: "16px", width: "16px", }, }, }} /> </FluentActionButton> </div> )} </span> ); } } export interface ImageChooserProps { value?: ImageDescription; onChoose?: (value: ImageDescription) => void; } export class ImageChooser extends ContextedComponent<ImageChooserProps, {}> { public render() { return ( <div className="charticulator__image-chooser"> <ImageUploader focusOnMount={true} onUpload={(images) => { if (images.length == 1) { this.props.onChoose({ src: images[0].dataURL, width: images[0].width, height: images[0].height, }); } }} /> </div> ); } } export interface ImageUploaderProps { placeholder?: string; focusOnMount: boolean; onUpload?: (images: ImageUploaderItem[]) => void; onClear?: () => void; } export interface ImageUploaderState { dragOver: boolean; } export interface ImageUploaderItem { name: string; width: number; height: number; dataURL: string; } export class ImageUploader extends React.Component< ImageUploaderProps, ImageUploaderState > { public state: ImageUploaderState = { dragOver: false }; protected refContainer: HTMLDivElement; public componentDidMount() {} public componentWillUnmount() {} public static ReadFileAsImage( name: string, file: File | Blob ): Promise<ImageUploaderItem> { return new Promise<ImageUploaderItem>((resolve) => { const reader = new FileReader(); reader.onload = () => { const img = new Image(); img.onload = () => { resolve({ name, width: img.width, height: img.height, dataURL: reader.result as string, }); }; img.src = reader.result as string; }; reader.readAsDataURL(file); }); } public static ParseFiles(files: FileList): Promise<ImageUploaderItem[]> { const result: Promise<ImageUploaderItem>[] = []; const readFile = (file: File) => { result.push(this.ReadFileAsImage(file.name, file)); }; for (let i = 0; i < files.length; i++) { const file = files[i]; readFile(file); } return Promise.all(result); } public static ParseURIs(uris: string[]): Promise<ImageUploaderItem[]> { return Promise.all( uris.map((uri) => fetch(uri) .then((result) => result.blob()) .then((blob) => { return new Promise<ImageUploaderItem>((resolve, reject) => { if (!blob.type.startsWith("image/")) { reject(new Error("not an image")); } else { // TODO check changes resolve(this.ReadFileAsImage("blob", blob)); } }); }) ) ); } protected handleDragEnter = () => { this.setState({ dragOver: true }); }; protected handleDragLeave = () => { this.setState({ dragOver: false }); }; protected handleDragOver = (e: React.DragEvent<HTMLDivElement>) => { e.preventDefault(); }; protected handleDrop = (e: React.DragEvent<HTMLDivElement>) => { e.preventDefault(); this.setState({ dragOver: false }); if (e.dataTransfer.types.indexOf("text/uri-list") >= 0) { const uriList = e.dataTransfer.getData("text/uri-list") as string; const uris = uriList .replace(/\r/g, "") .split("\n") .map((x) => x.trim()) .filter((x) => !x.startsWith("#")); ImageUploader.ParseURIs(uris) .then((r) => { this.emitOnUpload(r); }) .catch((e) => { this.showError(e); }); } if (e.dataTransfer.files.length > 0) { ImageUploader.ParseFiles(e.dataTransfer.files).then((r) => { this.emitOnUpload(r); }); } }; protected handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => { if (e.clipboardData.files.length > 0) { e.preventDefault(); ImageUploader.ParseFiles(e.clipboardData.files) .then((r) => { this.emitOnUpload(r); }) .catch((e) => { this.showError(e); }); } }; protected handleOpenFile = () => { const inputFile = document.createElement("input"); inputFile.setAttribute("type", "file"); inputFile.onchange = () => { if (inputFile.files.length > 0) { ImageUploader.ParseFiles(inputFile.files).then((r) => { this.emitOnUpload(r); }); } }; inputFile.click(); }; protected handleClearFile = () => { if (this.props.onClear) { this.props.onClear(); } }; // eslint-disable-next-line protected showError(error: any) { // FIXME: ignore error for now } protected emitOnUpload(result: ImageUploaderItem[]) { if (this.props.onUpload) { this.props.onUpload(result); } } public render() { return ( <div className="charticulator__image-uploader" ref={(e) => (this.refContainer = e)} onDragEnter={this.handleDragEnter} onDragLeave={this.handleDragLeave} onDragOver={this.handleDragOver} onDrop={this.handleDrop} > {this.state.dragOver ? ( <ImageMappingDragStateWrapper> {strings.objects.image.dropImage} </ImageMappingDragStateWrapper> ) : ( <span className="el-input-wrapper"> <TextField value={ this.props.placeholder || strings.objects.image.defaultPlaceholder } disabled styles={ImageMappingTextFieldStyles} onPaste={this.handlePaste} /> <FluentButton marginTop="0px"> <DefaultButton styles={{ root: { minWidth: "unset", ...defultBindButtonSize, marginLeft: 5, }, }} iconProps={{ iconName: "OpenFolderHorizontal", }} onClick={this.handleOpenFile} /> </FluentButton> </span> )} </div> ); } } export class InputImageProperty extends InputImage { public render() { const isNone = this.props.value == null; const image = isNone ? null : this.resolveImage(this.props.value); let imageDisplayURL = image ? image.name : null; if (imageDisplayURL) { if (imageDisplayURL.startsWith("data:")) { imageDisplayURL = "(data url)"; } } return ( <span className={classNames( "charticulator__widget-control-input-image", ["is-none", isNone], ["is-drag-over", this.state.dragOver] )} ref={(e) => (this.element = e)} onDragEnter={this.handleDragEnter} onDragLeave={this.handleDragLeave} onDragOver={this.handleDragOver} onDrop={this.handleDrop} > {this.state.dragOver ? ( <span className="el-drag-over"> {strings.objects.image.dropImage} </span> ) : ( [ <FluentUIImage key="image" src={isNone ? R.getSVGIcon("FileImage") : image.src} width={30} height={30} />, <ImageUploader key={0} placeholder={isNone ? strings.core.none : imageDisplayURL} focusOnMount={true} onUpload={(images) => { if (images.length == 1) { if (this.props.onChange) { this.props.onChange({ src: images[0].dataURL, width: images[0].width, height: images[0].height, name: images[0].name, }); } } }} />, ] )} </span> ); } }
the_stack
// eslint-disable-next-line node/no-extraneous-import import {Probot, createProbot, ProbotOctokit} from 'probot'; // eslint-disable-next-line node/no-extraneous-import import {Octokit} from '@octokit/rest'; import nock from 'nock'; import sinon from 'sinon'; import {describe, it, afterEach, beforeEach} from 'mocha'; import * as assert from 'assert'; import {logger} from 'gcf-utils'; import * as policy from '../src/policy'; import * as bq from '../src/export'; import * as changer from '../src/changer'; import {policyBot} from '../src/bot'; import * as gh from '../src/issue'; nock.disableNetConnect(); describe('bot', () => { let probot: Probot; beforeEach(() => { probot = createProbot({ defaults: { githubToken: 'abc123', Octokit: ProbotOctokit.defaults({ retry: {enabled: false}, throttle: {enabled: false}, }), }, }); probot.load(policyBot); }); afterEach(() => { nock.cleanAll(); sinon.restore(); }); it('should skip runs on non-approved orgs', async () => { const repo = 'nodejs-storage'; const org = 'not-an-approved-org'; await probot.receive({ // eslint-disable-next-line @typescript-eslint/no-explicit-any name: 'schedule.repository' as any, payload: { repository: { name: repo, owner: { login: org, }, }, organization: { login: org, }, cron_org: org, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any, id: 'abc123', }); // we are relying on the lack of nocks or stubs to signal that this exited // successfully, skipping all of the interesting stuff. }); it('should run the check and saves the result', async () => { const repo = 'nodejs-storage'; const org = 'googleapis'; const fakeRepo = { full_name: 'googleapis/nodejs-storage', } as policy.GitHubRepo; const fakeResult = {} as policy.PolicyResult; const p = new policy.Policy(new Octokit(), console); const c = new changer.Changer(new Octokit(), fakeRepo); const getPolicyStub = sinon.stub(policy, 'getPolicy').returns(p); const getChangerStub = sinon.stub(changer, 'getChanger').returns(c); const getRepoStub = sinon.stub(p, 'getRepo').resolves(fakeRepo); const checkPolicyStub = sinon .stub(p, 'checkRepoPolicy') .resolves(fakeResult); const exportStub = sinon.stub(bq, 'exportToBigQuery').resolves(); const submitFixesStub = sinon.stub(c, 'submitFixes').resolves(); await probot.receive({ // eslint-disable-next-line @typescript-eslint/no-explicit-any name: 'schedule.repository' as any, payload: { repository: { name: repo, owner: { login: org, }, }, organization: { login: org, }, cron_org: org, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any, id: 'abc123', }); assert.ok(getPolicyStub.calledOnce); assert.ok(getChangerStub.calledOnce); assert.ok(getRepoStub.calledOnce); assert.ok(checkPolicyStub.calledOnce); assert.ok(exportStub.calledOnce); assert.ok(submitFixesStub.calledOnce); }); it('should run checks for sample repos in GoogleCloudPlatform', async () => { const repo = 'nodejs-docs-samples'; const org = 'GoogleCloudPlatform'; const fakeRepo = { topics: ['samples'], full_name: 'googleapis/nodejs-storage', } as policy.GitHubRepo; const fakeResult = {} as policy.PolicyResult; const p = new policy.Policy(new Octokit(), console); const c = new changer.Changer(new Octokit(), fakeRepo); const getPolicyStub = sinon.stub(policy, 'getPolicy').returns(p); const getChangerStub = sinon.stub(changer, 'getChanger').returns(c); const getRepoStub = sinon.stub(p, 'getRepo').resolves(fakeRepo); const checkPolicyStub = sinon .stub(p, 'checkRepoPolicy') .resolves(fakeResult); const exportStub = sinon.stub(bq, 'exportToBigQuery').resolves(); const submitFixesStub = sinon.stub(c, 'submitFixes').resolves(); await probot.receive({ // eslint-disable-next-line @typescript-eslint/no-explicit-any name: 'schedule.repository' as any, payload: { repository: { name: repo, owner: { login: org, }, }, organization: { login: org, }, cron_org: org, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any, id: 'abc123', }); assert.ok(getChangerStub.calledOnce); assert.ok(getPolicyStub.calledOnce); assert.ok(getRepoStub.calledOnce); assert.ok(checkPolicyStub.calledOnce); assert.ok(exportStub.calledOnce); assert.ok(submitFixesStub.calledOnce); }); it('should raise error if checkRepoPolicy throws', async () => { const repo = 'nodejs-docs-samples'; const org = 'GoogleCloudPlatform'; const fakeRepo = { topics: ['samples'], full_name: 'googleapis/nodejs-storage', } as policy.GitHubRepo; const p = new policy.Policy(new Octokit(), console); const getPolicyStub = sinon.stub(policy, 'getPolicy').returns(p); const getRepoStub = sinon.stub(p, 'getRepo').resolves(fakeRepo); const checkPolicyStub = sinon .stub(p, 'checkRepoPolicy') .throws(Error('reading file failed')); await assert.rejects( probot.receive({ // eslint-disable-next-line @typescript-eslint/no-explicit-any name: 'schedule.repository' as any, payload: { repository: { name: repo, owner: { login: org, }, }, organization: { login: org, }, cron_org: org, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any, id: 'abc123', }), /reading file failed/ ); assert.ok(getPolicyStub.calledOnce); assert.ok(getRepoStub.calledOnce); assert.ok(checkPolicyStub.calledOnce); }); it('should skip archived repos', async () => { const repo = 'nodejs-storage'; const org = 'googleapis'; const fakeRepo = {archived: true} as policy.GitHubRepo; const p = new policy.Policy(new Octokit(), console); const getPolicyStub = sinon.stub(policy, 'getPolicy').returns(p); const getRepoStub = sinon.stub(p, 'getRepo').resolves(fakeRepo); await probot.receive({ // eslint-disable-next-line @typescript-eslint/no-explicit-any name: 'schedule.repository' as any, payload: { repository: { name: repo, owner: { login: org, }, }, organization: { login: org, }, cron_org: org, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any, id: 'abc123', }); assert.ok(getRepoStub.calledOnce); assert.ok(getPolicyStub.calledOnce); }); it('should skip private repos', async () => { const repo = 'nodejs-storage'; const org = 'googleapis'; const fakeRepo = {private: true} as policy.GitHubRepo; const p = new policy.Policy(new Octokit(), console); const getPolicyStub = sinon.stub(policy, 'getPolicy').returns(p); const getRepoStub = sinon.stub(p, 'getRepo').resolves(fakeRepo); await probot.receive({ // eslint-disable-next-line @typescript-eslint/no-explicit-any name: 'schedule.repository' as any, payload: { repository: { name: repo, owner: { login: org, }, }, organization: { login: org, }, cron_org: org, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any, id: 'abc123', }); assert.ok(getRepoStub.calledOnce); assert.ok(getPolicyStub.calledOnce); }); it('should skip GoogleCloudPlatform repos without magic repo topics', async () => { const repo = 'nodejs-storage'; const org = 'GoogleCloudPlatform'; const fakeRepo = {} as policy.GitHubRepo; const p = new policy.Policy(new Octokit(), console); const getPolicyStub = sinon.stub(policy, 'getPolicy').returns(p); const getRepoStub = sinon.stub(p, 'getRepo').resolves(fakeRepo); await probot.receive({ // eslint-disable-next-line @typescript-eslint/no-explicit-any name: 'schedule.repository' as any, payload: { repository: { name: repo, owner: { login: org, }, }, organization: { login: org, }, cron_org: org, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any, id: 'abc123', }); assert.ok(getRepoStub.calledOnce); assert.ok(getPolicyStub.calledOnce); }); it('should still succeed if submitFixes fails, and log a result', async () => { const repo = 'nodejs-storage'; const org = 'googleapis'; const fakeRepo = { full_name: 'googleapis/nodejs-storage', } as policy.GitHubRepo; const fakeResult = {} as policy.PolicyResult; const p = new policy.Policy(new Octokit(), console); const c = new changer.Changer(new Octokit(), fakeRepo); const getPolicyStub = sinon.stub(policy, 'getPolicy').returns(p); const getChangerStub = sinon.stub(changer, 'getChanger').returns(c); const getRepoStub = sinon.stub(p, 'getRepo').resolves(fakeRepo); const checkPolicyStub = sinon .stub(p, 'checkRepoPolicy') .resolves(fakeResult); const exportStub = sinon.stub(bq, 'exportToBigQuery').resolves(); const submitFixesStub = sinon.stub(c, 'submitFixes').throws(); const openIssueStub = sinon.stub(gh, 'openIssue').resolves(); const errStub = sinon.stub(logger, 'error'); await probot.receive({ // eslint-disable-next-line @typescript-eslint/no-explicit-any name: 'schedule.repository' as any, payload: { repository: { name: repo, owner: { login: org, }, }, organization: { login: org, }, cron_org: org, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any, id: 'abc123', }); assert.ok(getChangerStub.calledOnce); assert.ok(getPolicyStub.calledOnce); assert.ok(getRepoStub.calledOnce); assert.ok(checkPolicyStub.calledOnce); assert.ok(exportStub.calledOnce); assert.ok(submitFixesStub.calledOnce); assert.ok(errStub.calledOnce); assert.ok(openIssueStub.calledOnce); }); });
the_stack
import childProcess from 'child_process' import yaml from 'yaml' import mapPorts from './map-ports' export interface IDockerComposeOptions { cwd?: string executablePath?: string config?: string | string[] configAsString?: string log?: boolean composeOptions?: string[] | (string | string[])[] commandOptions?: string[] | (string | string[])[] env?: NodeJS.ProcessEnv callback?: (chunk: Buffer, streamSource?: 'stdout' | 'stderr') => void } export type DockerComposePortResult = { address: string port: number } export type DockerComposeVersionResult = { version: string } export type DockerComposeConfigResult = { config: { version: Record<string, string> services: Record<string, string | Record<string, string>> volumes: Record<string, string> } } export type DockerComposeConfigServicesResult = { services: string[] } export type DockerComposeConfigVolumesResult = { volumes: string[] } export interface IDockerComposeLogOptions extends IDockerComposeOptions { follow?: boolean } export interface IDockerComposeBuildOptions extends IDockerComposeOptions { parallel?: boolean } export interface IDockerComposePushOptions extends IDockerComposeOptions { ignorePushFailures?: boolean } export interface IDockerComposeResult { exitCode: number | null out: string err: string } export type TypedDockerComposeResult<T> = { exitCode: number | null out: string err: string data: T } const nonEmptyString = (v: string) => v !== '' export type DockerComposePsResult = { services: Array<{ name: string command: string state: string ports: Array<{ mapped?: { address: string; port: number } exposed: { port: number; protocol: string } }> }> } export const mapPsOutput = (output: string): DockerComposePsResult => { const services = output .split(`\n`) .filter(nonEmptyString) .filter((_, index) => index > 1) .map((line) => { const [ nameFragment, commandFragment, stateFragment, untypedPortsFragment ] = line.split(/\s{3,}/) return { name: nameFragment.trim(), command: commandFragment.trim(), state: stateFragment.trim(), ports: mapPorts(untypedPortsFragment.trim()) } }) return { services } } /** * Converts supplied yml files to cli arguments * https://docs.docker.com/compose/reference/overview/#use--f-to-specify-name-and-path-of-one-or-more-compose-files */ const configToArgs = (config): string[] => { if (typeof config === 'undefined') { return [] } else if (typeof config === 'string') { return ['-f', config] } else if (config instanceof Array) { return config.reduce( (args, item): string[] => args.concat(['-f', item]), [] ) } throw new Error(`Invalid argument supplied: ${config}`) } /** * Converts docker-compose commandline options to cli arguments */ const composeOptionsToArgs = (composeOptions): string[] => { let composeArgs: string[] = [] composeOptions.forEach((option: string[] | string): void => { if (option instanceof Array) { composeArgs = composeArgs.concat(option) } if (typeof option === 'string') { composeArgs = composeArgs.concat([option]) } }) return composeArgs } /** * Executes docker-compose command with common options */ export const execCompose = ( command, args, options: IDockerComposeOptions = {} ): Promise<IDockerComposeResult> => new Promise((resolve, reject): void => { const composeOptions = options.composeOptions || [] const commandOptions = options.commandOptions || [] let composeArgs = composeOptionsToArgs(composeOptions) const isConfigProvidedAsString = !!options.configAsString const configArgs = isConfigProvidedAsString ? ['-f', '-'] : configToArgs(options.config) composeArgs = composeArgs.concat( configArgs.concat( [command].concat(composeOptionsToArgs(commandOptions), args) ) ) const cwd = options.cwd const env = options.env || undefined const executablePath = options.executablePath || 'docker-compose' const childProc = childProcess.spawn(executablePath, composeArgs, { cwd, env }) childProc.on('error', (err): void => { reject(err) }) const result: IDockerComposeResult = { exitCode: null, err: '', out: '' } childProc.stdout.on('data', (chunk): void => { result.out += chunk.toString() options.callback?.(chunk, 'stdout') }) childProc.stderr.on('data', (chunk): void => { result.err += chunk.toString() options.callback?.(chunk, 'stderr') }) childProc.on('exit', (exitCode): void => { result.exitCode = exitCode if (exitCode === 0) { resolve(result) } else { reject(result) } }) if (isConfigProvidedAsString) { childProc.stdin.write(options.configAsString) childProc.stdin.end() } if (options.log) { childProc.stdout.pipe(process.stdout) childProc.stderr.pipe(process.stderr) } }) /** * Determines whether or not to use the default non-interactive flag -d for up commands */ const shouldUseDefaultNonInteractiveFlag = function ( options: IDockerComposeOptions = {} ): boolean { const commandOptions = options.commandOptions || [] const containsOtherNonInteractiveFlag = commandOptions.reduce( (memo: boolean, item: string | string[]) => { return ( memo && !item.includes('--abort-on-container-exit') && !item.includes('--no-start') ) }, true ) return containsOtherNonInteractiveFlag } export const upAll = function ( options?: IDockerComposeOptions ): Promise<IDockerComposeResult> { const args = shouldUseDefaultNonInteractiveFlag(options) ? ['-d'] : [] return execCompose('up', args, options) } export const upMany = function ( services: string[], options?: IDockerComposeOptions ): Promise<IDockerComposeResult> { const args = shouldUseDefaultNonInteractiveFlag(options) ? ['-d'].concat(services) : services return execCompose('up', args, options) } export const upOne = function ( service: string, options?: IDockerComposeOptions ): Promise<IDockerComposeResult> { const args = shouldUseDefaultNonInteractiveFlag(options) ? ['-d', service] : [service] return execCompose('up', args, options) } export const down = function ( options?: IDockerComposeOptions ): Promise<IDockerComposeResult> { return execCompose('down', [], options) } export const stop = function ( options?: IDockerComposeOptions ): Promise<IDockerComposeResult> { return execCompose('stop', [], options) } export const stopOne = function ( service: string, options?: IDockerComposeOptions ): Promise<IDockerComposeResult> { return execCompose('stop', [service], options) } export const pauseOne = function ( service: string, options?: IDockerComposeOptions ): Promise<IDockerComposeResult> { return execCompose('pause', [service], options) } export const unpauseOne = function ( service: string, options?: IDockerComposeOptions ): Promise<IDockerComposeResult> { return execCompose('unpause', [service], options) } export const kill = function ( options?: IDockerComposeOptions ): Promise<IDockerComposeResult> { return execCompose('kill', [], options) } export const rm = function ( options?: IDockerComposeOptions, ...services: string[] ): Promise<IDockerComposeResult> { return execCompose('rm', ['-f', ...services], options) } export const exec = function ( container: string, command: string | string[], options?: IDockerComposeOptions ): Promise<IDockerComposeResult> { const args = Array.isArray(command) ? command : command.split(/\s+/) return execCompose('exec', ['-T', container].concat(args), options) } export const run = function ( container: string, command: string | string[], options?: IDockerComposeOptions ): Promise<IDockerComposeResult> { const args = Array.isArray(command) ? command : command.split(/\s+/) return execCompose('run', ['-T', container].concat(args), options) } export const buildAll = function ( options: IDockerComposeBuildOptions = {} ): Promise<IDockerComposeResult> { return execCompose('build', options.parallel ? ['--parallel'] : [], options) } export const buildMany = function ( services: string[], options: IDockerComposeBuildOptions = {} ): Promise<IDockerComposeResult> { return execCompose( 'build', options.parallel ? ['--parallel'].concat(services) : services, options ) } export const buildOne = function ( service: string, options?: IDockerComposeBuildOptions ): Promise<IDockerComposeResult> { return execCompose('build', [service], options) } export const pullAll = function ( options: IDockerComposeOptions = {} ): Promise<IDockerComposeResult> { return execCompose('pull', [], options) } export const pullMany = function ( services: string[], options: IDockerComposeOptions = {} ): Promise<IDockerComposeResult> { return execCompose('pull', services, options) } export const pullOne = function ( service: string, options?: IDockerComposeOptions ): Promise<IDockerComposeResult> { return execCompose('pull', [service], options) } export const config = async function ( options?: IDockerComposeOptions ): Promise<TypedDockerComposeResult<DockerComposeConfigResult>> { try { const result = await execCompose('config', [], options) const config = yaml.parse(result.out) return { ...result, data: { config } } } catch (error) { return Promise.reject(error) } } export const configServices = async function ( options?: IDockerComposeOptions ): Promise<TypedDockerComposeResult<DockerComposeConfigServicesResult>> { try { const result = await execCompose('config', ['--services'], options) const services = result.out.split('\n').filter(nonEmptyString) return { ...result, data: { services } } } catch (error) { return Promise.reject(error) } } export const configVolumes = async function ( options?: IDockerComposeOptions ): Promise<TypedDockerComposeResult<DockerComposeConfigVolumesResult>> { try { const result = await execCompose('config', ['--volumes'], options) const volumes = result.out.split('\n').filter(nonEmptyString) return { ...result, data: { volumes } } } catch (error) { return Promise.reject(error) } } export const ps = async function ( options?: IDockerComposeOptions ): Promise<TypedDockerComposeResult<DockerComposePsResult>> { try { const result = await execCompose('ps', [], options) const data = mapPsOutput(result.out) return { ...result, data } } catch (error) { return Promise.reject(error) } } export const push = function ( options: IDockerComposePushOptions = {} ): Promise<IDockerComposeResult> { return execCompose( 'push', options.ignorePushFailures ? ['--ignore-push-failures'] : [], options ) } export const restartAll = function ( options?: IDockerComposeOptions ): Promise<IDockerComposeResult> { return execCompose('restart', [], options) } export const restartMany = function ( services: string[], options?: IDockerComposeOptions ): Promise<IDockerComposeResult> { return execCompose('restart', services, options) } export const restartOne = function ( service: string, options?: IDockerComposeOptions ): Promise<IDockerComposeResult> { return restartMany([service], options) } export const logs = function ( services: string | string[], options: IDockerComposeLogOptions = {} ): Promise<IDockerComposeResult> { let args = Array.isArray(services) ? services : [services] if (options.follow) { args = ['--follow', ...args] } return execCompose('logs', args, options) } export const port = async function ( service: string, containerPort: string | number, options?: IDockerComposeOptions ): Promise<TypedDockerComposeResult<DockerComposePortResult>> { const args = [service, containerPort] try { const result = await execCompose('port', args, options) const [address, port] = result.out.split(':') return { ...result, data: { address, port: Number(port) } } } catch (error) { return Promise.reject(error) } } export const version = async function ( options?: IDockerComposeOptions ): Promise<TypedDockerComposeResult<DockerComposeVersionResult>> { try { const result = await execCompose('version', ['--short'], options) const version = result.out.replace('\n', '') return { ...result, data: { version } } } catch (error) { return Promise.reject(error) } } export default { upAll, upMany, upOne, down, stop, stopOne, pauseOne, unpauseOne, kill, rm, exec, run, buildAll, buildMany, buildOne, pullAll, pullMany, pullOne, config, configServices, configVolumes, ps, push, restartAll, restartMany, restartOne, logs, port, version }
the_stack
'use strict'; import type { Kernel, KernelMessage, Session } from '@jupyterlab/services'; import type { JSONObject } from '@lumino/coreutils'; import type { Slot } from '@lumino/signaling'; import { Observable } from 'rxjs/Observable'; import { ReplaySubject } from 'rxjs/ReplaySubject'; import { Event, EventEmitter } from 'vscode'; import { ServerStatus } from '../../datascience-ui/interactive-common/mainState'; import { WrappedError } from '../common/errors/types'; import { traceError, traceInfo, traceInfoIfCI, traceWarning } from '../common/logger'; import { Resource } from '../common/types'; import { createDeferred, sleep, waitForPromise } from '../common/utils/async'; import * as localize from '../common/utils/localize'; import { noop } from '../common/utils/misc'; import { sendTelemetryEvent } from '../telemetry'; import { getResourceType } from './common'; import { Telemetry } from './constants'; import { JupyterInvalidKernelError } from './jupyter/jupyterInvalidKernelError'; import { JupyterWaitForIdleError } from './jupyter/jupyterWaitForIdleError'; import { kernelConnectionMetadataHasKernelSpec } from './jupyter/kernels/helpers'; import { JupyterKernelPromiseFailedError } from './jupyter/kernels/jupyterKernelPromiseFailedError'; import { KernelConnectionMetadata } from './jupyter/kernels/types'; import { suppressShutdownErrors } from './raw-kernel/rawKernel'; import { trackKernelResourceInformation } from './telemetry/telemetry'; import { IJupyterSession, ISessionWithSocket, KernelSocketInformation } from './types'; /** * Exception raised when starting a Jupyter Session fails. * * @export * @class JupyterSessionStartError * @extends {Error} */ export class JupyterSessionStartError extends WrappedError { constructor(originalException: Error) { super(originalException.message, originalException); sendTelemetryEvent(Telemetry.StartSessionFailedJupyter, undefined, undefined, originalException, true); } } export abstract class BaseJupyterSession implements IJupyterSession { protected get session(): ISessionWithSocket | undefined { return this._session; } protected kernelConnectionMetadata?: KernelConnectionMetadata; public get kernelSocket(): Observable<KernelSocketInformation | undefined> { return this._kernelSocket; } public get onSessionStatusChanged(): Event<ServerStatus> { if (!this.onStatusChangedEvent) { this.onStatusChangedEvent = new EventEmitter<ServerStatus>(); } return this.onStatusChangedEvent.event; } public get onIOPubMessage(): Event<KernelMessage.IIOPubMessage> { if (!this.ioPubEventEmitter) { this.ioPubEventEmitter = new EventEmitter<KernelMessage.IIOPubMessage>(); } return this.ioPubEventEmitter.event; } public get status(): ServerStatus { return this.getServerStatus(); } public get isConnected(): boolean { return this.connected; } protected onStatusChangedEvent: EventEmitter<ServerStatus> = new EventEmitter<ServerStatus>(); protected statusHandler: Slot<ISessionWithSocket, Kernel.Status>; protected connected: boolean = false; protected restartSessionPromise: Promise<ISessionWithSocket | undefined> | undefined; private _session: ISessionWithSocket | undefined; private _kernelSocket = new ReplaySubject<KernelSocketInformation | undefined>(); private ioPubEventEmitter = new EventEmitter<KernelMessage.IIOPubMessage>(); private ioPubHandler: Slot<ISessionWithSocket, KernelMessage.IIOPubMessage>; private unhandledMessageHandler: Slot<ISessionWithSocket, KernelMessage.IMessage>; constructor( protected resource: Resource, private restartSessionUsed: (id: Kernel.IKernelConnection) => void, public workingDirectory: string ) { this.statusHandler = this.onStatusChanged.bind(this); this.ioPubHandler = (_s, m) => this.ioPubEventEmitter.fire(m); this.unhandledMessageHandler = (_s, m) => { traceInfo(`Unhandled message found: ${m.header.msg_type}`); }; } public dispose(): Promise<void> { return this.shutdown(); } // Abstracts for each Session type to implement public abstract waitForIdle(timeout: number): Promise<void>; public async shutdown(): Promise<void> { if (this.session) { try { traceInfo('Shutdown session - current session'); await this.shutdownSession(this.session, this.statusHandler, false); traceInfo('Shutdown session - get restart session'); if (this.restartSessionPromise) { const restartSession = await this.restartSessionPromise; traceInfo('Shutdown session - shutdown restart session'); await this.shutdownSession(restartSession, undefined, true); } } catch { noop(); } this.setSession(undefined); this.restartSessionPromise = undefined; } if (this.onStatusChangedEvent) { this.onStatusChangedEvent.dispose(); } traceInfo('Shutdown session -- complete'); } public async interrupt(timeout: number): Promise<void> { if (this.session && this.session.kernel) { traceInfo(`Interrupting kernel: ${this.session.kernel.name}`); // Listen for session status changes this.session.statusChanged.connect(this.statusHandler); await this.waitForKernelPromise( this.session.kernel.interrupt(), timeout, localize.DataScience.interruptingKernelFailed() ); } } public async requestKernelInfo(): Promise<KernelMessage.IInfoReplyMsg | undefined> { if (!this.session) { throw new Error('Cannot request KernelInfo, Session not initialized.'); } if (this.session.kernel?.info) { const content = await this.session.kernel.info; const infoMsg: KernelMessage.IInfoReplyMsg = { content, channel: 'shell', metadata: {}, // eslint-disable-next-line @typescript-eslint/no-explicit-any parent_header: {} as any, // eslint-disable-next-line @typescript-eslint/no-explicit-any header: {} as any }; return Promise.resolve(infoMsg); } return this.session.kernel?.requestKernelInfo(); } public async changeKernel( resource: Resource, kernelConnection: KernelConnectionMetadata, timeoutMS: number ): Promise<void> { this.resource = resource; let newSession: ISessionWithSocket | undefined; // If we are already using this kernel in an active session just return back const currentKernelSpec = this.kernelConnectionMetadata && kernelConnectionMetadataHasKernelSpec(this.kernelConnectionMetadata) ? this.kernelConnectionMetadata.kernelSpec : undefined; const kernelSpecToUse = kernelConnectionMetadataHasKernelSpec(kernelConnection) ? kernelConnection.kernelSpec : undefined; if (this.session && currentKernelSpec && kernelSpecToUse && this.kernelConnectionMetadata) { // If we have selected the same kernel connection, then nothing to do. if (this.kernelConnectionMetadata.id === kernelConnection.id) { traceInfoIfCI(`Kernels are the same, no switching necessary.`); return; } } trackKernelResourceInformation(resource, { kernelConnection }); newSession = await this.createNewKernelSession(resource, kernelConnection, timeoutMS); // This is just like doing a restart, kill the old session (and the old restart session), and start new ones if (this.session) { this.shutdownSession(this.session, this.statusHandler, false).ignoreErrors(); this.restartSessionPromise?.then((r) => this.shutdownSession(r, undefined, true)).ignoreErrors(); // NOSONAR } traceInfoIfCI(`Switched notebook kernel to ${kernelSpecToUse?.display_name}`); // Update our kernel connection metadata. this.kernelConnectionMetadata = kernelConnection; // Save the new session this.setSession(newSession); // Listen for session status changes this.session?.statusChanged.connect(this.statusHandler); // NOSONAR } public async restart(timeout: number): Promise<void> { if (this.session?.isRemoteSession && this.session.kernel) { await this.session.kernel.restart(); return; } // Start the restart session now in case it wasn't started if (!this.restartSessionPromise) { this.startRestartSession(timeout); } // Just kill the current session and switch to the other if (this.restartSessionPromise) { traceInfo(`Restarting ${this.session?.kernel?.id}`); // Save old state for shutdown const oldSession = this.session; const oldStatusHandler = this.statusHandler; // Just switch to the other session. It should already be ready this.setSession(await this.restartSessionPromise); if (!this.session) { throw new Error(localize.DataScience.sessionDisposed()); } if (this.session.kernel) { this.restartSessionUsed(this.session.kernel); traceInfo(`Got new session ${this.session.kernel.id}`); // Rewire our status changed event. this.session.statusChanged.connect(this.statusHandler); } this.restartSessionPromise = undefined; traceInfo('Started new restart session'); if (oldStatusHandler && oldSession) { oldSession.statusChanged.disconnect(oldStatusHandler); } this.shutdownSession(oldSession, undefined, false).ignoreErrors(); } else { throw new Error(localize.DataScience.sessionDisposed()); } } public requestExecute( content: KernelMessage.IExecuteRequestMsg['content'], disposeOnDone?: boolean, metadata?: JSONObject ): Kernel.IShellFuture<KernelMessage.IExecuteRequestMsg, KernelMessage.IExecuteReplyMsg> { if (!this.session?.kernel) { throw new Error(localize.DataScience.sessionDisposed()); } return this.session.kernel.requestExecute(content, disposeOnDone, metadata); } public requestDebug( content: KernelMessage.IDebugRequestMsg['content'], disposeOnDone?: boolean ): Kernel.IControlFuture<KernelMessage.IDebugRequestMsg, KernelMessage.IDebugReplyMsg> { if (!this.session?.kernel) { throw new Error(localize.DataScience.sessionDisposed()); } return this.session.kernel.requestDebug(content, disposeOnDone); } public requestInspect( content: KernelMessage.IInspectRequestMsg['content'] ): Promise<KernelMessage.IInspectReplyMsg> { if (!this.session?.kernel) { throw new Error(localize.DataScience.sessionDisposed()); } return this.session.kernel.requestInspect(content); } public requestComplete( content: KernelMessage.ICompleteRequestMsg['content'] ): Promise<KernelMessage.ICompleteReplyMsg> { if (!this.session?.kernel) { throw new Error(localize.DataScience.sessionDisposed()); } return this.session.kernel.requestComplete(content); } public sendInputReply(content: string) { if (this.session && this.session.kernel) { // eslint-disable-next-line @typescript-eslint/no-explicit-any this.session.kernel.sendInputReply({ value: content, status: 'ok' }); } } public registerCommTarget( targetName: string, callback: (comm: Kernel.IComm, msg: KernelMessage.ICommOpenMsg) => void | PromiseLike<void> ) { if (this.session && this.session.kernel) { this.session.kernel.registerCommTarget(targetName, callback); } else { throw new Error(localize.DataScience.sessionDisposed()); } } public registerMessageHook( msgId: string, hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean> ): void { if (this.session?.kernel) { return this.session.kernel.registerMessageHook(msgId, hook); } else { throw new Error(localize.DataScience.sessionDisposed()); } } public removeMessageHook( msgId: string, hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean> ): void { if (this.session?.kernel) { return this.session.kernel.removeMessageHook(msgId, hook); } else { throw new Error(localize.DataScience.sessionDisposed()); } } // Sub classes need to implement their own restarting specific code protected abstract startRestartSession(timeout: number): void; // Sub classes need to implement their own kernel change specific code protected abstract createNewKernelSession( resource: Resource, kernelConnection: KernelConnectionMetadata, timeoutMS: number ): Promise<ISessionWithSocket>; protected async waitForIdleOnSession( session: ISessionWithSocket | undefined, timeout: number, isRestartSession?: boolean ): Promise<void> { if (session && session.kernel) { traceInfo(`Waiting for idle on (kernel): ${session.kernel.id} -> ${session.kernel.status}`); // When our kernel connects and gets a status message it triggers the ready promise const deferred = createDeferred<string>(); const handler = (_session: Kernel.IKernelConnection, status: Kernel.Status) => { if (status == 'idle') { deferred.resolve(status); } }; session.kernel.statusChanged?.connect(handler); if (session.kernel.status == 'idle') { deferred.resolve(session.kernel.status); } const result = await Promise.race([deferred.promise, sleep(timeout)]); session.kernel.statusChanged?.disconnect(handler); traceInfo(`Finished waiting for idle on (kernel): ${session.kernel.id} -> ${session.kernel.status}`); if (result.toString() == 'idle') { return; } // If we throw an exception, make sure to shutdown the session as it's not usable anymore this.shutdownSession(session, this.statusHandler, isRestartSession).ignoreErrors(); throw new JupyterWaitForIdleError(localize.DataScience.jupyterLaunchTimedOut()); } else { throw new JupyterInvalidKernelError(undefined); } } // Changes the current session. protected setSession(session: ISessionWithSocket | undefined) { const oldSession = this._session; if (this.ioPubHandler && oldSession) { oldSession.iopubMessage.disconnect(this.ioPubHandler); } if (this.unhandledMessageHandler && oldSession) { oldSession.unhandledMessage.disconnect(this.unhandledMessageHandler); } this._session = session; if (session && session.iopubMessage) { session.iopubMessage.connect(this.ioPubHandler); } if (session && session.unhandledMessage) { session.unhandledMessage.connect(this.unhandledMessageHandler); } // If we have a new session, then emit the new kernel connection information. if (session && oldSession !== session && session.kernel) { if (!session.kernelSocketInformation) { traceError(`Unable to find WebSocket connection associated with kernel ${session.kernel.id}`); this._kernelSocket.next(undefined); } else { this._kernelSocket.next({ options: { clientId: session.kernel.clientId, id: session.kernel.id, model: { ...session.kernel.model }, userName: session.kernel.username }, socket: session.kernelSocketInformation.socket }); } } } protected async shutdownSession( session: ISessionWithSocket | undefined, statusHandler: Slot<ISessionWithSocket, Kernel.Status> | undefined, isRequestToShutDownRestartSession: boolean | undefined ): Promise<void> { if (session && session.kernel) { const kernelIdForLogging = `${session.kernel.id}, ${session.kernelConnectionMetadata?.id}`; traceInfo(`shutdownSession ${kernelIdForLogging} - start`); try { if (statusHandler) { session.statusChanged.disconnect(statusHandler); } if (!this.canShutdownSession(session, isRequestToShutDownRestartSession)) { traceInfo(`Session cannot be shutdown ${session.kernelConnectionMetadata?.id}`); session.dispose(); return; } try { traceInfo(`Session can be shutdown ${session.kernelConnectionMetadata?.id}`); suppressShutdownErrors(session.kernel); // Shutdown may fail if the process has been killed if (!session.isDisposed) { await waitForPromise(session.shutdown(), 1000); } } catch { noop(); } if (session && !session.isDisposed) { session.dispose(); } } catch (e) { // Ignore, just trace. traceWarning(e); } traceInfo(`shutdownSession ${kernelIdForLogging} - shutdown complete`); } } private canShutdownSession(session: ISessionWithSocket, isRequestToShutDownRestartSession: boolean | undefined) { // We can never shut down existing (live) kernels. if (session.kernelConnectionMetadata?.kind === 'connectToLiveKernel') { return false; } // We can always shutdown restart sessions. if (isRequestToShutDownRestartSession) { return true; } // If this Interactive Window, then always shutdown sessions (even with remote Jupyter). if (session.resource && getResourceType(session.resource) === 'interactive') { return true; } // If we're in notebooks and using Remote Jupyter connections, then never shutdown the sessions. if (session.resource && getResourceType(session.resource) === 'notebook' && session.isRemoteSession === true) { return false; } return true; } private getServerStatus(): ServerStatus { if (this.session && this.session.kernel) { switch (this.session.kernel.status) { case 'busy': return ServerStatus.Busy; case 'dead': case 'terminating': return ServerStatus.Dead; case 'idle': return ServerStatus.Idle; case 'restarting': case 'autorestarting': return ServerStatus.Restarting; case 'starting': return ServerStatus.Starting; default: return ServerStatus.NotStarted; } } return ServerStatus.NotStarted; } private async waitForKernelPromise( kernelPromise: Promise<void>, timeout: number, errorMessage: string ): Promise<void | null> { // Wait for this kernel promise to happen try { await waitForPromise(kernelPromise, timeout); } catch (e) { // TODO: This will never get throw, `waitForPromise` never throws when there's a timeout, // TODO: Review usages of `JupyterKernelPromiseFailedError` it might never get thrown. if (!e) { // We timed out. Throw a specific exception throw new JupyterKernelPromiseFailedError(errorMessage); } throw e; } } private onStatusChanged(_s: Session.ISessionConnection) { if (this.onStatusChangedEvent) { this.onStatusChangedEvent.fire(this.getServerStatus()); } } }
the_stack
import * as vscode from 'vscode'; import { getLocation, Location, parse } from 'jsonc-parser'; import * as nls from 'vscode-nls'; import { provideInstalledExtensionProposals } from './extensionsProposals'; const localize = nls.loadMessageBundle(); const OVERRIDE_IDENTIFIER_REGEX = /\[([^\[\]]*)\]/g; export class SettingsDocument { constructor(private document: vscode.TextDocument) { } public provideCompletionItems(position: vscode.Position, _token: vscode.CancellationToken): vscode.ProviderResult<vscode.CompletionItem[] | vscode.CompletionList> { const location = getLocation(this.document.getText(), this.document.offsetAt(position)); const range = this.document.getWordRangeAtPosition(position) || new vscode.Range(position, position); // window.title if (location.path[0] === 'window.title') { return this.provideWindowTitleCompletionItems(location, range); } // files.association if (location.path[0] === 'files.associations') { return this.provideFilesAssociationsCompletionItems(location, range); } // files.exclude, search.exclude if (location.path[0] === 'files.exclude' || location.path[0] === 'search.exclude') { return this.provideExcludeCompletionItems(location, range); } // files.defaultLanguage if (location.path[0] === 'files.defaultLanguage') { return this.provideLanguageCompletionItems(location, range).then(items => { // Add special item '${activeEditorLanguage}' return [this.newSimpleCompletionItem(JSON.stringify('${activeEditorLanguage}'), range, localize('activeEditor', "Use the language of the currently active text editor if any")), ...items]; }); } // settingsSync.ignoredExtensions if (location.path[0] === 'settingsSync.ignoredExtensions') { let ignoredExtensions = []; try { ignoredExtensions = parse(this.document.getText())['settingsSync.ignoredExtensions']; } catch (e) {/* ignore error */ } return provideInstalledExtensionProposals(ignoredExtensions, '', range, true); } // remote.extensionKind if (location.path[0] === 'remote.extensionKind' && location.path.length === 2 && location.isAtPropertyKey) { let alreadyConfigured: string[] = []; try { alreadyConfigured = Object.keys(parse(this.document.getText())['remote.extensionKind']); } catch (e) {/* ignore error */ } return provideInstalledExtensionProposals(alreadyConfigured, `: [\n\t"ui"\n]`, range, true); } // remote.portsAttributes if (location.path[0] === 'remote.portsAttributes' && location.path.length === 2 && location.isAtPropertyKey) { return this.providePortsAttributesCompletionItem(range); } return this.provideLanguageOverridesCompletionItems(location, position); } private provideWindowTitleCompletionItems(_location: Location, range: vscode.Range): vscode.ProviderResult<vscode.CompletionItem[]> { const completions: vscode.CompletionItem[] = []; completions.push(this.newSimpleCompletionItem('${activeEditorShort}', range, localize('activeEditorShort', "the file name (e.g. myFile.txt)"))); completions.push(this.newSimpleCompletionItem('${activeEditorMedium}', range, localize('activeEditorMedium', "the path of the file relative to the workspace folder (e.g. myFolder/myFileFolder/myFile.txt)"))); completions.push(this.newSimpleCompletionItem('${activeEditorLong}', range, localize('activeEditorLong', "the full path of the file (e.g. /Users/Development/myFolder/myFileFolder/myFile.txt)"))); completions.push(this.newSimpleCompletionItem('${activeFolderShort}', range, localize('activeFolderShort', "the name of the folder the file is contained in (e.g. myFileFolder)"))); completions.push(this.newSimpleCompletionItem('${activeFolderMedium}', range, localize('activeFolderMedium', "the path of the folder the file is contained in, relative to the workspace folder (e.g. myFolder/myFileFolder)"))); completions.push(this.newSimpleCompletionItem('${activeFolderLong}', range, localize('activeFolderLong', "the full path of the folder the file is contained in (e.g. /Users/Development/myFolder/myFileFolder)"))); completions.push(this.newSimpleCompletionItem('${rootName}', range, localize('rootName', "name of the workspace (e.g. myFolder or myWorkspace)"))); completions.push(this.newSimpleCompletionItem('${rootPath}', range, localize('rootPath', "file path of the workspace (e.g. /Users/Development/myWorkspace)"))); completions.push(this.newSimpleCompletionItem('${folderName}', range, localize('folderName', "name of the workspace folder the file is contained in (e.g. myFolder)"))); completions.push(this.newSimpleCompletionItem('${folderPath}', range, localize('folderPath', "file path of the workspace folder the file is contained in (e.g. /Users/Development/myFolder)"))); completions.push(this.newSimpleCompletionItem('${appName}', range, localize('appName', "e.g. VS Code"))); completions.push(this.newSimpleCompletionItem('${remoteName}', range, localize('remoteName', "e.g. SSH"))); completions.push(this.newSimpleCompletionItem('${dirty}', range, localize('dirty', "an indicator for when the active editor has unsaved changes"))); completions.push(this.newSimpleCompletionItem('${separator}', range, localize('separator', "a conditional separator (' - ') that only shows when surrounded by variables with values"))); return Promise.resolve(completions); } private provideFilesAssociationsCompletionItems(location: Location, range: vscode.Range): vscode.ProviderResult<vscode.CompletionItem[]> { const completions: vscode.CompletionItem[] = []; if (location.path.length === 2) { // Key if (!location.isAtPropertyKey || location.path[1] === '') { completions.push(this.newSnippetCompletionItem({ label: localize('assocLabelFile', "Files with Extension"), documentation: localize('assocDescriptionFile', "Map all files matching the glob pattern in their filename to the language with the given identifier."), snippet: location.isAtPropertyKey ? '"*.${1:extension}": "${2:language}"' : '{ "*.${1:extension}": "${2:language}" }', range })); completions.push(this.newSnippetCompletionItem({ label: localize('assocLabelPath', "Files with Path"), documentation: localize('assocDescriptionPath', "Map all files matching the absolute path glob pattern in their path to the language with the given identifier."), snippet: location.isAtPropertyKey ? '"/${1:path to file}/*.${2:extension}": "${3:language}"' : '{ "/${1:path to file}/*.${2:extension}": "${3:language}" }', range })); } else { // Value return this.provideLanguageCompletionItemsForLanguageOverrides(location, range); } } return Promise.resolve(completions); } private provideExcludeCompletionItems(location: Location, range: vscode.Range): vscode.ProviderResult<vscode.CompletionItem[]> { const completions: vscode.CompletionItem[] = []; // Key if (location.path.length === 1) { completions.push(this.newSnippetCompletionItem({ label: localize('fileLabel', "Files by Extension"), documentation: localize('fileDescription', "Match all files of a specific file extension."), snippet: location.isAtPropertyKey ? '"**/*.${1:extension}": true' : '{ "**/*.${1:extension}": true }', range })); completions.push(this.newSnippetCompletionItem({ label: localize('filesLabel', "Files with Multiple Extensions"), documentation: localize('filesDescription', "Match all files with any of the file extensions."), snippet: location.isAtPropertyKey ? '"**/*.{ext1,ext2,ext3}": true' : '{ "**/*.{ext1,ext2,ext3}": true }', range })); completions.push(this.newSnippetCompletionItem({ label: localize('derivedLabel', "Files with Siblings by Name"), documentation: localize('derivedDescription', "Match files that have siblings with the same name but a different extension."), snippet: location.isAtPropertyKey ? '"**/*.${1:source-extension}": { "when": "$(basename).${2:target-extension}" }' : '{ "**/*.${1:source-extension}": { "when": "$(basename).${2:target-extension}" } }', range })); completions.push(this.newSnippetCompletionItem({ label: localize('topFolderLabel', "Folder by Name (Top Level)"), documentation: localize('topFolderDescription', "Match a top level folder with a specific name."), snippet: location.isAtPropertyKey ? '"${1:name}": true' : '{ "${1:name}": true }', range })); completions.push(this.newSnippetCompletionItem({ label: localize('topFoldersLabel', "Folders with Multiple Names (Top Level)"), documentation: localize('topFoldersDescription', "Match multiple top level folders."), snippet: location.isAtPropertyKey ? '"{folder1,folder2,folder3}": true' : '{ "{folder1,folder2,folder3}": true }', range })); completions.push(this.newSnippetCompletionItem({ label: localize('folderLabel', "Folder by Name (Any Location)"), documentation: localize('folderDescription', "Match a folder with a specific name in any location."), snippet: location.isAtPropertyKey ? '"**/${1:name}": true' : '{ "**/${1:name}": true }', range })); } // Value else { completions.push(this.newSimpleCompletionItem('false', range, localize('falseDescription', "Disable the pattern."))); completions.push(this.newSimpleCompletionItem('true', range, localize('trueDescription', "Enable the pattern."))); completions.push(this.newSnippetCompletionItem({ label: localize('derivedLabel', "Files with Siblings by Name"), documentation: localize('siblingsDescription', "Match files that have siblings with the same name but a different extension."), snippet: '{ "when": "$(basename).${1:extension}" }', range })); } return Promise.resolve(completions); } private provideLanguageCompletionItems(_location: Location, range: vscode.Range, formatFunc: (string: string) => string = (l) => JSON.stringify(l)): Thenable<vscode.CompletionItem[]> { return vscode.languages.getLanguages() .then(languages => languages.map(l => this.newSimpleCompletionItem(formatFunc(l), range))); } private async provideLanguageCompletionItemsForLanguageOverrides(_location: Location, range: vscode.Range): Promise<vscode.CompletionItem[]> { const languages = await vscode.languages.getLanguages(); const completionItems = []; for (const language of languages) { const item = new vscode.CompletionItem(JSON.stringify(language)); item.kind = vscode.CompletionItemKind.Property; item.range = range; completionItems.push(item); } return completionItems; } private async provideLanguageOverridesCompletionItems(location: Location, position: vscode.Position): Promise<vscode.CompletionItem[]> { if (location.path.length === 1 && location.previousNode && typeof location.previousNode.value === 'string' && location.previousNode.value.startsWith('[')) { const startPosition = this.document.positionAt(location.previousNode.offset + 1); const endPosition = startPosition.translate(undefined, location.previousNode.value.length); const donotSuggestLanguages: string[] = []; const languageOverridesRanges: vscode.Range[] = []; let matches = OVERRIDE_IDENTIFIER_REGEX.exec(location.previousNode.value); let lastLanguageOverrideRange: vscode.Range | undefined; while (matches?.length) { lastLanguageOverrideRange = new vscode.Range(this.document.positionAt(location.previousNode.offset + 1 + matches.index), this.document.positionAt(location.previousNode.offset + 1 + matches.index + matches[0].length)); languageOverridesRanges.push(lastLanguageOverrideRange); /* Suggest the configured language if the position is in the match range */ if (!lastLanguageOverrideRange.contains(position)) { donotSuggestLanguages.push(matches[1].trim()); } matches = OVERRIDE_IDENTIFIER_REGEX.exec(location.previousNode.value); } const lastLanguageOverrideEndPosition = lastLanguageOverrideRange ? lastLanguageOverrideRange.end : startPosition; if (lastLanguageOverrideEndPosition.isBefore(endPosition)) { languageOverridesRanges.push(new vscode.Range(lastLanguageOverrideEndPosition, endPosition)); } const languageOverrideRange = languageOverridesRanges.find(range => range.contains(position)); /** * Skip if suggestsions are for first language override range * Since VSCode registers language overrides to the schema, JSON language server does suggestions for first language override. */ if (languageOverrideRange && !languageOverrideRange.isEqual(languageOverridesRanges[0])) { const languages = await vscode.languages.getLanguages(); const completionItems = []; for (const language of languages) { if (!donotSuggestLanguages.includes(language)) { const item = new vscode.CompletionItem(`[${language}]`); item.kind = vscode.CompletionItemKind.Property; item.range = languageOverrideRange; completionItems.push(item); } } return completionItems; } } return []; } private providePortsAttributesCompletionItem(range: vscode.Range): vscode.CompletionItem[] { return [this.newSnippetCompletionItem( { label: '\"3000\"', documentation: 'Single Port Attribute', range, snippet: '\n \"${1:3000}\": {\n \"label\": \"${2:Application}\",\n \"onAutoForward\": \"${3:openPreview}\"\n }\n' }), this.newSnippetCompletionItem( { label: '\"5000-6000\"', documentation: 'Ranged Port Attribute', range, snippet: '\n \"${1:40000-55000}\": {\n \"onAutoForward\": \"${2:ignore}\"\n }\n' }), this.newSnippetCompletionItem( { label: '\".+\\\\/server.js\"', documentation: 'Command Match Port Attribute', range, snippet: '\n \"${1:.+\\\\/server.js\}\": {\n \"label\": \"${2:Application}\",\n \"onAutoForward\": \"${3:openPreview}\"\n }\n' }) ]; } private newSimpleCompletionItem(text: string, range: vscode.Range, description?: string, insertText?: string): vscode.CompletionItem { const item = new vscode.CompletionItem(text); item.kind = vscode.CompletionItemKind.Value; item.detail = description; item.insertText = insertText ? insertText : text; item.range = range; return item; } private newSnippetCompletionItem(o: { label: string; documentation?: string; snippet: string; range: vscode.Range }): vscode.CompletionItem { const item = new vscode.CompletionItem(o.label); item.kind = vscode.CompletionItemKind.Value; item.documentation = o.documentation; item.insertText = new vscode.SnippetString(o.snippet); item.range = o.range; return item; } }
the_stack
import { Event, EventEmitter, TreeDataProvider, TreeItem, TreeItemCollapsibleState, window, workspace, } from 'vscode'; import { IWorkspaceMember, ICodeCoverage } from '../forceCode'; import * as path from 'path'; import * as fs from 'fs-extra'; import { isEmptyUndOrNull } from '../util'; import { MAX_TIME_BETWEEN_FILE_CHANGES, notifications } from '.'; export enum ClassType { CoveredClass = 'Sufficient Coverage', UncoveredClass = 'Insufficient Coverage', NoCoverageData = 'No Coverage Data', TestClass = 'Test Classes', NotInOrg = 'Not In Current Org', NotInSrc = 'Open Files Not In Src', NoShow = 'NoShow', Subclass = 'Subclass', } const folderWSMember: IWorkspaceMember = { name: 'FOLDER', path: '', type: ClassType.NoShow, id: '', coverage: new Map<string, ICodeCoverage>(), }; export class CodeCovViewService implements TreeDataProvider<FCFile> { private static instance: CodeCovViewService; private classes: Array<FCFile> = new Array<FCFile>(); private _onDidChangeTreeData: EventEmitter<FCFile | undefined> = new EventEmitter< FCFile | undefined >(); public readonly onDidChangeTreeData: Event<FCFile | undefined> = this._onDidChangeTreeData.event; public static getInstance() { if (!CodeCovViewService.instance) { notifications.writeLog('Starting Code Coverage Service...'); CodeCovViewService.instance = new CodeCovViewService(); } return CodeCovViewService.instance; } public constructor() { window.onDidChangeActiveTextEditor(_event => { this.refresh(); }); } public refresh() { this._onDidChangeTreeData.fire(); } public addClass(wsMember: IWorkspaceMember) { const index: number = this.classes.findIndex(curClass => { return curClass.getWsMember().path === wsMember.path; }); if (index !== -1) { this.classes[index].setWsMember(wsMember); } else { var newClass: FCFile = new FCFile( wsMember.name, TreeItemCollapsibleState.None, this, wsMember ); this.classes.push(newClass); } this.refresh(); } public findByNameAndType(name: string, type: string): FCFile | undefined { if (isEmptyUndOrNull(this.classes)) { return undefined; } return this.classes.find(cur => { return cur.getWsMember().name === name && cur.getWsMember().type === type; }); } public findByType(type: string): FCFile[] | undefined { if (isEmptyUndOrNull(this.classes)) { return undefined; } return this.classes.filter(cur => { return cur.getWsMember().type === type; }); } public findByPath(pa: string): FCFile | undefined { if (isEmptyUndOrNull(this.classes)) { return undefined; } return this.classes.find(cur => { return cur.getWsMember().path === pa; }); } public findById(id: string): FCFile | undefined { if (isEmptyUndOrNull(this.classes)) { return undefined; } return this.classes.find(cur => { return cur.getWsMember().id === id; }); } public removeClasses(fcfiles: FCFile[]) { fcfiles.forEach(cur => { this.removeClass(cur); }); } public removeClass(fcfile: FCFile): boolean { const index = this.classes.indexOf(fcfile); if (index !== -1) { this.classes.splice(index, 1); this.refresh(); return true; } return false; } public clear() { delete this.classes; this.classes = []; this.refresh(); } public getTreeItem(element: FCFile): TreeItem { return element; } public getChildren(element?: FCFile): FCFile[] { if (!element) { var fcFiles: FCFile[] = []; // This is the root node Object.entries(ClassType).forEach(val => { if (val[1] !== ClassType.NoShow && val[1] !== ClassType.Subclass) { var newFCFile: FCFile = new FCFile( val[1], TreeItemCollapsibleState.Collapsed, this, folderWSMember ); newFCFile.setType(val[1]); fcFiles.push(newFCFile); } }); //fcFiles.sort(this.sortFunc); return fcFiles; } else if (element.getWsMember().type === ClassType.NoShow) { if (element.label === ClassType.NotInSrc) { var fcFiles: FCFile[] = []; if (workspace.textDocuments) { workspace.textDocuments.forEach(curEd => { if ( !curEd.fileName.startsWith(window.forceCode.projectRoot) && curEd.uri.scheme === 'file' ) { const fName = curEd.fileName.split(path.sep).pop(); if (fName) { var newFCFile: FCFile = new FCFile( fName, TreeItemCollapsibleState.None, this, folderWSMember ); newFCFile.setType(ClassType.NotInSrc); newFCFile.command = { command: 'ForceCode.openOnClick', title: '', arguments: [curEd.fileName], }; newFCFile.tooltip = `WARNING: This file isn\'t located in the current PROJECT PATH\n(${window.forceCode.projectRoot})`; fcFiles.push(newFCFile); } } }); } return fcFiles; } else { this.classes.sort(this.sortFunc); return this.classes.filter(res => { return res.getType() === element.getType(); }); } } else if ( element.getType() === ClassType.CoveredClass || element.getType() === ClassType.UncoveredClass ) { var fcFiles: FCFile[] = []; for (let [key, value] of element.getWsMember().coverage) { var total: number = value.NumLinesCovered + value.NumLinesUncovered; var percent = Math.floor((value.NumLinesCovered / total) * 100); if (key !== 'overall' && value.ApexTestClass && percent !== 0) { var newFCFile: FCFile = new FCFile( `${percent}% ${key}`, TreeItemCollapsibleState.None, this, folderWSMember, element ); newFCFile.setType(ClassType.Subclass); newFCFile.tooltip = newFCFile.label + ' - ' + value.NumLinesCovered + '/' + total + ' lines covered'; fcFiles.push(newFCFile); } } return fcFiles; } return []; } public getParent(element: FCFile): any { if (element.getWsMember().id !== '') { var newFCFile: FCFile = new FCFile( element.getType(), TreeItemCollapsibleState.Expanded, this, folderWSMember ); newFCFile.setType(element.getType()); return newFCFile; } return null; // this is the parent } private sortFunc(a: FCFile, b: FCFile): number { var aStr = a?.label ?.split('% ') .pop() ?.toUpperCase() || ''; var bStr = b?.label ?.split('% ') .pop() ?.toUpperCase() || ''; return aStr.localeCompare(bStr); } } export class FCFile extends TreeItem { public readonly collapsibleState: TreeItemCollapsibleState; private parent: CodeCovViewService; private wsMember!: IWorkspaceMember; private type!: ClassType; private parentFCFile?: FCFile; constructor( name: string, collapsibleState: TreeItemCollapsibleState, parent: CodeCovViewService, wsMember: IWorkspaceMember, parentFCFile?: FCFile ) { super(name, collapsibleState); this.collapsibleState = collapsibleState; this.parent = parent; this.parentFCFile = parentFCFile; this.setWsMember(wsMember); } public setWsMember(newMem: IWorkspaceMember) { this.wsMember = newMem; this.command = { command: 'ForceCode.changeCoverageDecoration', title: '', arguments: [this], }; // we only want classes and triggers if (this.wsMember.type !== 'ApexClass' && this.wsMember.type !== 'ApexTrigger') { this.type = ClassType.NoShow; if (!this.parentFCFile) { this.command = undefined; } return undefined; } super.label = this.wsMember.path.split(path.sep).pop(); this.iconPath = undefined; if (!this.wsMember.id || this.wsMember.id === '') { this.type = ClassType.NotInOrg; return undefined; } this.type = ClassType.UncoveredClass; this.tooltip = this.label; var fileCoverage: ICodeCoverage | undefined = this.wsMember.coverage.get('overall'); if (fileCoverage) { var total: number = fileCoverage.NumLinesCovered + fileCoverage.NumLinesUncovered; var percent = Math.floor((fileCoverage.NumLinesCovered / total) * 100); this.label = percent + '% ' + this.label; this.tooltip = this.label + ' - ' + fileCoverage.NumLinesCovered + '/' + total + ' lines covered'; const imagePath: string = path.join(window.forceCode.storageRoot, 'images'); if (percent >= 75) { this.type = ClassType.CoveredClass; this.iconPath = { dark: path.join(imagePath, 'greenCheck.svg'), light: path.join(imagePath, 'greenCheck.svg'), }; } else { this.iconPath = { dark: path.join(imagePath, 'redEx.svg'), light: path.join(imagePath, 'redEx.svg'), }; } super.collapsibleState = TreeItemCollapsibleState.Collapsed; this.setCoverageTestClass('overall'); // this next check needs changed to something different, as there are problems reading the file } else { var testFile: boolean = false; try { testFile = fs .readFileSync(this.wsMember.path) .toString() .toLowerCase() .includes('@istest'); } catch (e) {} if (testFile) { this.type = ClassType.TestClass; this.contextValue = 'fcTestClass'; } else { this.type = ClassType.NoCoverageData; } } } public updateWsMember(newMem: IWorkspaceMember) { this.parent.addClass(newMem); } public getWsMember(): IWorkspaceMember { return this.wsMember; } public getType(): ClassType { return this.type; } public setType(newType: ClassType) { this.type = newType; } public getParentFCFile(): FCFile | undefined { return this.parentFCFile; } public setCoverageTestClass(newCoverage: string | undefined) { this.wsMember.selectedCoverage = newCoverage || 'overall'; } public addCoverage(testClass: string, coverage: ICodeCoverage) { this.wsMember.coverage.set(testClass, coverage); this.updateWsMember(this.wsMember); } public clearCoverage() { this.wsMember.coverage.clear(); super.collapsibleState = TreeItemCollapsibleState.None; this.updateWsMember(this.wsMember); } // sometimes the times on the dates are a half second off, so this checks for within 2 seconds public compareDates(serverDate: string): boolean { if (!this.wsMember) { return true; } const stat: fs.Stats = fs.statSync(this.wsMember.path); var localMS: number = stat.mtime.getTime(); var serverMS: number = new Date(serverDate).getTime(); if (localMS > serverMS || serverMS - localMS <= MAX_TIME_BETWEEN_FILE_CHANGES) { return true; } notifications.writeLog('Time difference between file changes: ' + (serverMS - localMS)); return false; } }
the_stack
import * as React from 'react'; import * as PropTypes from 'prop-types'; import { Motion, spring, OpaqueConfig } from 'react-motion'; import update from 'immutability-helper'; import MultiRef from 'react-multi-ref'; import OnUpdate from './OnUpdate'; import MoveContainer, { HeightData } from './MoveContainer'; const DEFAULT_HEIGHT: HeightData = { natural: 200, drag: 30 }; function getScrollSpeed(distance: number, speed: number, size: number): number { // If distance is zero, then the result is the max speed. Otherwise, // the result tapers toward zero as it gets closer to the opposite // edge of the region. return Math.round(speed - (speed / size) * distance); } interface Drag { itemKey: string; // The y position of the dragged item when the drag started. This will be // equal to the initial mouseY value. The items not being dragged will be // positioned so that the dragged item's original position lines up with // startY. startY: number; // The y-position that corresponds to the mouse's current location. The // dragged item will be rendered with this as its y-position. mouseY: number; // This is the difference between the raw mouse y value and startY. For // example, if a user clicks the drag handle at a point 5 px below the item's // top, then mouseOffset will be set to 5. As the user moves their mouse, we // update mouseY to be the raw mouse y value minus mouseOffset. mouseOffset: number; } export interface TemplateProps<I, C> { item: I; itemSelected: number; anySelected: number; dragHandleProps: object; commonProps: C; } export interface Props<I, C, T> { itemKey: string | ((item: I) => string); template: new (props: any, context?: any) => T; list: ReadonlyArray<I>; onMoveEnd?: ( newList: ReadonlyArray<I>, movedItem: I, oldIndex: number, newIndex: number ) => void; container?: () => HTMLElement | null | undefined; constrainDrag?: boolean; springConfig?: object; padding?: number; unsetZIndex?: boolean; autoScrollMaxSpeed?: number; autoScrollRegionSize?: number; commonProps?: C; } interface State { useAbsolutePositioning: boolean; dragging: boolean; lastDrag: Drag | null; heights: { [key: string]: HeightData } | null; } export default class DraggableList< I, C, T extends React.Component<Partial<TemplateProps<I, C>>> > extends React.Component<Props<I, C, T>, State> { public static propTypes = { itemKey: PropTypes.oneOfType([PropTypes.string, PropTypes.func]).isRequired, template: PropTypes.func, list: PropTypes.array.isRequired, onMoveEnd: PropTypes.func, container: PropTypes.func, springConfig: PropTypes.object, constrainDrag: PropTypes.bool, padding: PropTypes.number, unsetZIndex: PropTypes.bool, autoScrollMaxSpeed: PropTypes.number.isRequired, autoScrollRegionSize: PropTypes.number.isRequired, commonProps: PropTypes.object, }; public static defaultProps: Partial<Props<any, any, any>> = { springConfig: { stiffness: 300, damping: 50 }, padding: 10, unsetZIndex: false, constrainDrag: false, autoScrollMaxSpeed: 15, autoScrollRegionSize: 30, }; private readonly _itemRefs: MultiRef<string, MoveContainer<I, any, T>> = new MultiRef(); private _autoScrollerTimer: any; private _listRef = React.createRef<HTMLDivElement>(); public state: State = { useAbsolutePositioning: false, dragging: false, lastDrag: null, heights: null, }; public getItemInstance(key: string): T { const ref = this._itemRefs.map.get(key); if (!ref) throw new Error('key not found'); return ref.getTemplate(); } public static getDerivedStateFromProps<I, C, T>( newProps: Props<I, C, T>, state: State ): Partial<State> | null { const { list } = newProps; const { lastDrag } = state; if (lastDrag) { const keyFn = DraggableList._getKeyFn<I>(newProps.itemKey); try { DraggableList._getIndexOfItemWithKey<I>(keyFn, list, lastDrag.itemKey); } catch (err) { // If the dragged item was removed from the list, this block will get hit. // Cancel the drag. return { dragging: false, lastDrag: null }; } } return null; } public componentWillUnmount() { this._handleMouseUp(); } private _handleTouchStart( itemKey: string, pressY: number | undefined, event: TouchEvent | React.TouchEvent ) { event.stopPropagation(); this._handleStartDrag(itemKey, pressY, event.touches[0].pageY); } private _handleMouseDown( itemKey: string, pressY: number | undefined, event: MouseEvent | React.MouseEvent ) { event.preventDefault(); this._handleStartDrag(itemKey, pressY, event.pageY); } private _handleStartDrag( itemKey: string, pressY: number | undefined, pageY: number ) { if (document.documentElement) document.documentElement.style.cursor = 'move'; window.addEventListener('mouseup', this._handleMouseUp); window.addEventListener('touchend', this._handleMouseUp); window.addEventListener('touchmove', this._handleTouchMove); window.addEventListener('mousemove', this._handleMouseMove); // If an element has focus while we drag around the parent, some browsers // try to scroll the parent element to keep the focused element in view. // Stop that. { const listEl = this._listRef.current; if (!listEl) throw new Error('Should not happen'); if ( listEl.contains && document.activeElement && listEl.contains(document.activeElement) && document.activeElement instanceof HTMLElement ) { document.activeElement.blur(); } } const keyFn = this._getKeyFn(); let newHeights = null; if (this.state.heights == null) { const _newHeights: { [key: string]: HeightData } = Object.create(null); this.props.list.forEach((item) => { const key = keyFn(item); const containerRef = this._itemRefs.map.get(key); const refEl = containerRef ? containerRef.getDOMNode().firstElementChild : null; const ref = containerRef ? containerRef.getTemplate() : null; const natural = refEl instanceof HTMLElement ? refEl.offsetHeight : DEFAULT_HEIGHT.natural; const drag = (ref && typeof (ref as any).getDragHeight === 'function' && (ref as any).getDragHeight()) || natural; _newHeights[key] = { natural, drag }; }); newHeights = _newHeights; } // Need to re-render once before we start dragging so that the `y` values // are set using the correct state.heights and then can animate from there. const afterHeights = () => { const itemIndex = this.props.list.map(keyFn).indexOf(itemKey); // pressY will be non-null if the list is currently animating (because the // clicked item has its `y` prop set). pressY will be null if the list is // not currently animating (because the clicked item will be at its // natural position, which is calculatable using _getDistance). const startY = pressY == null ? this._getDistance(0, itemIndex, false) : pressY; const containerEl = this._getContainer(); const containerScroll = !containerEl || containerEl === document.body ? 0 : containerEl.scrollTop; this.setState({ useAbsolutePositioning: true, dragging: true, lastDrag: { itemKey: itemKey, startY, mouseY: startY, mouseOffset: pageY - startY + containerScroll, }, }); }; if (newHeights) { this.setState({ heights: newHeights }, afterHeights); } else { afterHeights(); } } private _handleTouchMove = (e: TouchEvent) => { e.preventDefault(); this._handleMouseMove(e.touches[0]); }; private _handleMouseMove = ({ pageY, clientY, }: MouseEvent | Touch | { pageY: number; clientY: number }) => { const { list } = this.props; const autoScrollMaxSpeed = this.props.autoScrollMaxSpeed!; const autoScrollRegionSize = this.props.autoScrollRegionSize!; const { dragging, lastDrag } = this.state; if (!dragging || !lastDrag) return; const containerEl = this._getContainer(); const dragVisualIndex = this._getDragVisualIndex(); const keyFn = this._getKeyFn(); clearInterval(this._autoScrollerTimer); // If the user has the mouse near the top or bottom of the container and // not at the end of the list, then autoscroll. if (dragVisualIndex !== 0 && dragVisualIndex !== list.length - 1) { let scrollSpeed = 0; const containerRect = containerEl && containerEl !== document.body && containerEl.getBoundingClientRect ? containerEl.getBoundingClientRect() : { top: 0, bottom: Infinity }; // Get the lowest of the screen top and the container top. const top = Math.max(0, containerRect.top); const distanceFromTop = clientY - top; if (distanceFromTop > 0 && distanceFromTop < autoScrollRegionSize) { scrollSpeed = -1 * getScrollSpeed( distanceFromTop, autoScrollMaxSpeed, autoScrollRegionSize ); } else { // Get the lowest of the screen bottom and the container bottom. const bottom = Math.min(window.innerHeight, containerRect.bottom); const distanceFromBottom = bottom - clientY; if ( distanceFromBottom > 0 && distanceFromBottom < autoScrollRegionSize ) { scrollSpeed = getScrollSpeed( distanceFromBottom, autoScrollMaxSpeed, autoScrollRegionSize ); } } if (scrollSpeed !== 0) { this._scrollContainer(scrollSpeed); this._autoScrollerTimer = setTimeout(() => { this._handleMouseMove({ pageY: pageY + (containerEl === document.body ? scrollSpeed : 0), clientY, }); }, 16); } } const containerScroll = !containerEl || containerEl === document.body ? 0 : containerEl.scrollTop; let mouseY = pageY - lastDrag.mouseOffset + containerScroll; if (this.props.constrainDrag) { const visualList = this._getVisualListDuringDrag(); mouseY = Math.max( mouseY, this._getDistanceFromTopDuringDrag( lastDrag, keyFn(visualList[0]), visualList ) ); mouseY = Math.min( mouseY, this._getDistanceFromTopDuringDrag( lastDrag, keyFn(visualList[visualList.length - 1]), visualList ) ); } this.setState({ lastDrag: { ...lastDrag, mouseY } }); }; _handleMouseUp = () => { clearInterval(this._autoScrollerTimer); window.removeEventListener('mouseup', this._handleMouseUp); window.removeEventListener('touchend', this._handleMouseUp); window.removeEventListener('touchmove', this._handleTouchMove); window.removeEventListener('mousemove', this._handleMouseMove); if (document.documentElement) document.documentElement.style.cursor = ''; this._lastScrollDelta = 0; const { list, onMoveEnd } = this.props; const { dragging, lastDrag } = this.state; if (dragging && lastDrag && onMoveEnd) { const dragIndex = this._getDragListIndex(); const newIndex = this._getDragVisualIndex(); if (dragIndex !== newIndex) { const newList = this._getVisualListDuringDrag(); onMoveEnd(newList, list[dragIndex], dragIndex, newIndex); } this.setState({ dragging: false }); } }; _scrollContainer(delta: number) { const containerEl = this._getContainer(); if (!containerEl) return; if (window.scrollBy && containerEl === document.body) { window.scrollBy(0, delta); } else { containerEl.scrollTop += delta; } } private _lastScrollDelta = 0; _adjustScrollAtEnd(delta: number) { const frameDelta = Math.round(delta - this._lastScrollDelta); this._scrollContainer(frameDelta); this._lastScrollDelta += frameDelta; } static _getIndexOfItemWithKey<I>( keyFn: (item: I) => string, list: ReadonlyArray<I>, itemKey: string ): number { for (let i = 0, len = list.length; i < len; i++) { if (keyFn(list[i]) === itemKey) { return i; } } throw new Error('Failed to find drag index'); } _getDragListIndex(): number { const { list } = this.props; const { lastDrag } = this.state; if (!lastDrag) { throw new Error('No drag happened'); } const keyFn = this._getKeyFn(); return DraggableList._getIndexOfItemWithKey(keyFn, list, lastDrag.itemKey); } _getDragVisualIndex(): number { const { list } = this.props; const padding = this.props.padding!; const { dragging, lastDrag } = this.state; if (!dragging || !lastDrag) throw new Error('Should not happen'); const dragListIndex = this._getDragListIndex(); const { mouseY, startY } = lastDrag; const movementFromNatural = mouseY - startY; // 1 down, -1 up, 0 neither const direction = movementFromNatural > 0 ? 1 : movementFromNatural < 0 ? -1 : 0; let newIndex = dragListIndex; if (direction !== 0) { const keyFn = this._getKeyFn(); let reach = Math.abs(movementFromNatural); for ( let i = dragListIndex + direction; i < list.length && i >= 0; i += direction ) { const iDragHeight = this._getItemHeight(keyFn(list[i])).drag; if (reach < iDragHeight / 2 + padding) break; reach -= iDragHeight + padding; newIndex = i; } } return newIndex; } _getVisualListDuringDrag(): ReadonlyArray<I> { const { list } = this.props; const { dragging, lastDrag } = this.state; if (!dragging || !lastDrag) throw new Error( 'Should not happen: _getVisualListDuringDrag called outside of drag' ); const dragListIndex = this._getDragListIndex(); const dragVisualIndex = this._getDragVisualIndex(); return update(list, { $splice: [ [dragListIndex, 1], [dragVisualIndex, 0, list[dragListIndex]], ], }); } _getItemHeight(key: string): HeightData { return this.state.heights != null && key in this.state.heights ? this.state.heights[key] : DEFAULT_HEIGHT; } // Get the distance between the tops of two items in the list. // Does not consider how the dragged item may be rendered in a different position // unless you pass in the re-ordered list as a parameter. _getDistance( start: number, end: number, dragging: boolean, list: ReadonlyArray<I> = this.props.list ): number { if (end < start) { return -this._getDistance(end, start, dragging, list); } const padding = this.props.padding!; const keyFn = this._getKeyFn(); let distance = 0; for (let i = start; i < end; i++) { const height = this._getItemHeight(keyFn(list[i])); distance += (dragging ? height.drag : height.natural) + padding; } return distance; } _getDistanceFromTopDuringDrag( lastDrag: Drag, itemKey: string, visualList: ReadonlyArray<I> ): number { const keyFn = this._getKeyFn(); const index = DraggableList._getIndexOfItemWithKey( keyFn, visualList, itemKey ); const dragListIndex = this._getDragListIndex(); const dragVisualIndex = DraggableList._getIndexOfItemWithKey( keyFn, visualList, lastDrag.itemKey ); let offset = 0; if (dragVisualIndex < dragListIndex) { const dragItemHeight = this._getItemHeight(lastDrag.itemKey); const newCenterHeight = this._getItemHeight( keyFn(visualList[dragListIndex]) ); offset = dragItemHeight.drag - newCenterHeight.drag; } return ( lastDrag.startY + offset + this._getDistance(dragListIndex, index, true, visualList) ); } private _getContainer(): HTMLElement | null | undefined { const { container } = this.props; return container ? container() : null; } private static _getKeyFn<I>( itemKey: string | ((item: I) => string) ): (item: I) => string { return typeof itemKey === 'function' ? itemKey : (x) => (x as any)[itemKey]; } private _getKeyFn(): (item: I) => string { return DraggableList._getKeyFn<I>(this.props.itemKey); } render() { const padding = this.props.padding!; const { list, springConfig, container, template, unsetZIndex, commonProps, } = this.props; const { dragging, lastDrag, useAbsolutePositioning } = this.state; const keyFn = this._getKeyFn(); const anySelected = spring(dragging ? 1 : 0, springConfig); const visualList = dragging ? this._getVisualListDuringDrag() : list; const children = list.map((item, i) => { const key = keyFn(item); const selectedStyle = dragging && lastDrag && lastDrag.itemKey === key ? { itemSelected: spring(1, springConfig), y: lastDrag.mouseY, } : { itemSelected: spring(0, springConfig), y: (useAbsolutePositioning ? spring : (x: number) => x)( dragging && lastDrag ? this._getDistanceFromTopDuringDrag( lastDrag, key, visualList ) : this._getDistance(0, i, false), springConfig ), }; const style = { anySelected, ...selectedStyle, }; const makeDragHandleProps = (getY: () => number | undefined): object => ({ onMouseDown: (e: React.MouseEvent) => this._handleMouseDown(key, getY(), e), onTouchStart: (e: React.TouchEvent) => this._handleTouchStart(key, getY(), e), }); const height = this._getItemHeight(key); return ( <Motion style={style} key={key} children={({ itemSelected, anySelected, y }) => ( <MoveContainer ref={this._itemRefs.ref(key)} y={useAbsolutePositioning ? y : undefined} template={template} padding={padding} item={item} itemSelected={itemSelected} anySelected={anySelected} height={height} zIndex={ unsetZIndex && !useAbsolutePositioning ? 'auto' : lastDrag && lastDrag.itemKey === key ? list.length : i } makeDragHandleProps={makeDragHandleProps} commonProps={commonProps} /> )} /> ); }); let adjustScroll: number | OpaqueConfig = 0; if (!dragging && lastDrag && useAbsolutePositioning) { const dragListIndex = this._getDragListIndex(); adjustScroll = spring( this._getDistance(0, dragListIndex, false) - lastDrag.mouseY, springConfig ); } let heightReserverHeight = 0; let heightReserverMarginBottom = 0; if (list.length) { heightReserverMarginBottom = padding; if (useAbsolutePositioning) { heightReserverHeight = this._getDistance(0, list.length, false) - padding; } } return ( <div style={{ position: 'relative' }} ref={this._listRef}> <Motion style={{ adjustScroll, anySelected }} onRest={() => { if (!dragging) { this.setState({ heights: null, useAbsolutePositioning: false, }); } }} children={({ adjustScroll }) => ( <div style={{ display: useAbsolutePositioning ? 'block' : 'none', height: `${heightReserverHeight}px`, marginBottom: `${heightReserverMarginBottom}px`, }} > {container && ( <OnUpdate cb={() => { if (!dragging && lastDrag && useAbsolutePositioning) { this._adjustScrollAtEnd(adjustScroll); } }} /> )} </div> )} /> {children} </div> ); } }
the_stack
import * as fs from "fs"; import {PathLike} from "fs"; import * as readline from "readline"; interface ClassInfo { /** * 类的id,默认使用类名,不能重复 */ id?: string; /** * 类的类型 */ type: any; /** * 记录装饰器调用的位置 */ pos: any; } /** * 序列化时需要忽略的字段 */ const transientFields = new Map<any, any>(); /** * 被@Serialize装饰的类信息 */ const classInfos = new Map<any, ClassInfo>(); /** * 通过 classId 获取 classInfo * @param {string} id * @returns {ClassInfo} */ export const getClassInfoById = (id: string) => { for (let entry of classInfos) { let classInfo = entry[1]; if (classInfo.id == id) { return classInfo; } } return null; }; export const getClassInfoByConstructor = (constructor: any) => { return classInfos.get(constructor); }; const stackPosReg = new RegExp("^at .* \\((.*)\\)$"); /** * 获取 @Serialize 的装饰位置,以便在后续报错时能指出正确的位置 * @returns {string} */ function getDecoratorPos() { const stack = new Error("test").stack.split("\n"); const pos = stack[3].trim(); const stackPosM = stackPosReg.exec(pos); return stackPosM ? stackPosM[1] : null; } export interface SerializableConfig { classId?: string; } /** * 在js加载的过程中,有这个装饰器的类的类信息会保存到 classInfos 中,用于序列化和反序列化 * @param {SerializableConfig} config * @returns {(target) => void} * @constructor */ export function Serializable(config?: SerializableConfig) { const decoratorPos = getDecoratorPos(); return function (target) { if (!config) config = {}; const id = config.classId || target.name; let existed = classInfos.get(id); if (!existed) { existed = { id: config.classId || target.name, type: target, pos: decoratorPos, transients: transientFields[target], } as ClassInfo; classInfos.set(target, existed); } else { throw new Error("duplicate classId(" + existed.id + ") at: \n" + existed.pos + "\n" + existed.pos); } } } /** * 类在序列化时要忽略的字段 * 不能作用于类静态字段 * @returns {(target: any, field: string) => void} * @constructor */ export function Transient() { return function (target: any, field: string) { const isStatic = target.constructor.name === "Function"; if (isStatic) throw new Error("cannot decorate static field with Transient"); // @Transient 不能作用于类静态成员 const type = target.constructor; let transients = transientFields[type]; if (!transients) { transientFields[type] = transients = {}; } transients[field] = true; }; } export function Assign(target, source) { if (source && target && typeof source == "object" && typeof target == "object") { const transients = transientFields[target.constructor]; if (transients) { for (let field of Object.keys(source)) { if (!transients[field]) { target[field] = source[field]; } } } else { Object.assign(target, source); } } } interface Writer { write(str: string); } /** * 序列化和反序列化工具类,目前在整个框架中只有一个地方用到: * 1. QueueManager 中保存和加载运行状态 */ export class SerializableUtil { static serializeToFile(obj: any, file: PathLike, encoding: string = "utf-8"): Promise<void> { return new Promise((resolve, reject) => { let writeStream = fs.createWriteStream(file, encoding); let serFinish = false; let writeNum = 0; const checkWriteFinish = () => { if (writeNum == 0) { writeStream.close(); resolve(); } }; let buffer = ""; const bufferMaxLen = 1024; const tryFlush = (force: boolean = false) => { if (buffer.length >= bufferMaxLen || (force && buffer.length > 0)) { writeNum++; writeStream.write(buffer, error => { if (error) { reject(error); } else { writeNum--; if (serFinish) { checkWriteFinish(); } } }); buffer = ""; } }; const writer = { write: str => { buffer += str; tryFlush(); } }; this._serialize(obj, writer); serFinish = true; tryFlush(true); checkWriteFinish(); }); } static serializeToString(obj: any): string { let res = ""; const writer = { write: str => { res += str; } }; this._serialize(obj, writer); return res; } private static _serialize(obj: any, writer: Writer): string[] { if (this.isSimpleType(obj)) { writer.write("g.$=" + JSON.stringify(obj) + ";"); return; } // 54进制 const objIdChars = "$ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; const objId = num => { let res = ""; let base = 54; while (num > 0) { res = objIdChars[num % base] + res; num = +(num / base).toFixed(0); } return res || "$"; }; const classes = new Map<any, string>(); const addClassNewFunction = objConstructor => { let c = classes.get(objConstructor); if (c == null) { const classInfo = classInfos.get(objConstructor); if (classInfo) { const classId = classes.size; c = "g.c" + classId; classes.set(objConstructor, c); writer.write(`g.class${classId} = (getClass(${JSON.stringify(classInfo.id)}) || {}).type;${c} = obj => { if (g.class${classId}) { const ins = new g.class${classId}(); Object.assign(ins, obj); return ins; } return obj;};\n`); } } return c; }; const refs = new Map<string, { objIndex: string, keyOrIndex: number | string }[]>(); const addRef = (objIndex: string, keyOrIndex: number | string, refIndex: string) => { let arr = refs.get(refIndex); if (!arr) { refs.set(refIndex, arr = []); } arr.push({ objIndex: objIndex, keyOrIndex: keyOrIndex }); }; const objs = new Map<any, { index: number, symbol: string }>(); objs.set(obj, {index: 0, symbol: "$"}); const objsIt = objs.entries(); let entry; while (entry = objsIt.next().value) { const obj = entry[0]; const objIndex = entry[1].index; const objSymbol = entry[1].symbol; const existedObjRefs = []; const objType = typeof obj; if (obj instanceof Array) { const insArr = new Array(obj.length); let isAllRef = true; for (let i = 0, len = obj.length; i < len; i++) { const value = obj[i]; if (this.isSimpleType(value)) { insArr[i] = value; isAllRef = false; } else { let refObjInfo = objs.get(value); if (refObjInfo == null) { refObjInfo = { index: objs.size, symbol:objId(objs.size) }; objs.set(value, refObjInfo); } if (refObjInfo.index <= objIndex) { existedObjRefs.push([i, refObjInfo.symbol]); } else { addRef(objSymbol, i, refObjInfo.symbol); } } } if (isAllRef) { writer.write(`g.${objSymbol}=new Array(${obj.length});`); } else { const insObjJson = JSON.stringify(insArr); writer.write(`g.${objSymbol}=` + insObjJson + ";"); } } else if (objType == "object") { const objConstructor = obj.constructor; const newF = addClassNewFunction(objConstructor); const transients = transientFields[objConstructor]; let insObj; let insObjs = []; let keyNum = 0; for (let field in obj) { if (transients && transients[field]) { // 忽略字段 continue; } const value = obj[field]; if (this.isSimpleType(value)) { if (keyNum % 1000 == 0) { insObj = {}; insObjs.push(insObj); } insObj[field] = value; keyNum++; } else { let refObjInfo = objs.get(value); if (refObjInfo == null) { refObjInfo = { index: objs.size, symbol:objId(objs.size) }; objs.set(value, refObjInfo); } if (refObjInfo.index <= objIndex) { existedObjRefs.push([field, refObjInfo.symbol]); } else { addRef(objSymbol, field, refObjInfo.symbol); } } } let insObjJson = insObjs.length > 0 ? JSON.stringify(insObjs[0]) : "{}"; writer.write(`g.${objSymbol}=` + (newF ? newF + "(" + insObjJson + ")" : insObjJson) + ";"); for (let i = 1, len = insObjs.length; i < len; i++) { insObjJson = JSON.stringify(insObjs[i]); writer.write(`\nObject.assign(g.${objSymbol}, ${insObjJson});`); } } else if (objType == "function") { const classInfo = classInfos.get(obj); if (classInfo) { writer.write(`g.${objSymbol}=getClass(${JSON.stringify(classInfo.id)});`); } else { writer.write(`g.${objSymbol}=(${obj.toString().replace(/\r?\n/g, ";")});`); } } for (let refInfo of existedObjRefs) { writer.write(`g.${objSymbol}[${typeof refInfo[0] == "number" ? refInfo[0] : JSON.stringify(refInfo[0])}]=g.${refInfo[1]};`); } const refsOfThis = refs.get(objSymbol); if (refsOfThis) { for (let refItem of refsOfThis) { writer.write(`g.${refItem.objIndex}[${typeof refItem.keyOrIndex == "number" ? refItem.keyOrIndex : JSON.stringify(refItem.keyOrIndex)}]=g.${objSymbol};`); } refs.delete(objSymbol); } writer.write("\n"); } } private static isSimpleType(obj: any) { if (obj == null || obj == undefined) return true; const objType = typeof obj; return objType == "string" || objType == "number" || objType == "boolean"; } static deserializeFromString(str: string) { const getClass = id => getClassInfoById(id); const g: any = {}; eval(str); return g.$; } static deserializeFromFile(file: PathLike, encoding: string = "utf-8"): Promise<any> { return new Promise<any>(async (resolve, reject) => { const getClass = id => getClassInfoById(id); const g: any = {}; const lineBuffer = []; let waitReadFinishResolve; const waitReadFinishPromise = new Promise(resolve => waitReadFinishResolve = resolve); const evalLines =() => { let subLinesStr = lineBuffer.join("\n"); try { eval(subLinesStr); } catch (e) { const stacks = e.stack.split("\n"); stacks.splice(1, 0, subLinesStr); e.stack = stacks.join("\n"); waitReadFinishResolve(e); } lineBuffer.splice(0, lineBuffer.length); }; const reader = readline.createInterface({ input: fs.createReadStream(file).setEncoding(encoding) }); reader.on('line', function(line) { lineBuffer.push(line); lineBuffer.length >= 1000 && evalLines(); }); reader.on('close', function(line) { lineBuffer.length > 0 && evalLines(); waitReadFinishResolve(); }); waitReadFinishPromise.then(err => { if (err) { reader.close(); return reject(err); } resolve(g.$); }); }); } } /** * @deprecated */ export class SerializableUtil_v2 { /** * 序列化 * @param obj * @returns {any | string | {}} */ static serialize(obj: any): string[] { if (!this.shouldSerialize(obj)) { return [ "-1", JSON.stringify(obj) ]; } const serializedCaches = new Map<any, string>(); const magicNum = (Math.random() * 10000).toFixed(0); const serializedRes = [magicNum]; // 第一行为magicNum this._serialize(obj, serializedCaches, serializedRes); return serializedRes; } private static shouldSerialize(obj: any) { if (obj == null || obj == undefined) return false; const objType = typeof obj; return !(objType == "string" || objType == "number" || objType == "boolean"); } private static _serialize(obj: any, serializedCaches: Map<any, string>, serializedRes: string[]) { if (!this.shouldSerialize(obj)) { return obj; } let serializedCache = serializedCaches.get(obj); if (serializedCache == undefined) { const objConstructor = obj.constructor; if (typeof obj == "function" || !objConstructor) { // 方法不需要进一步序列化 return undefined; } // 保存当前处理的实例的ref id serializedCache = serializedRes[0] + "_" + serializedCaches.size; serializedCaches.set(obj, serializedCache); let res = null; if (obj instanceof Array) { res = []; (obj as Array<any>).forEach((value, index) => { res.push(this._serialize(value, serializedCaches, serializedRes)); // 数组中每个元素需要进一步序列化 }); } else { let classInfo = classInfos.get(objConstructor); if (res == null) { res = {}; const transients = transientFields[objConstructor]; for (let field in obj) { if (transients && transients[field]) { // 忽略字段 } else res[field] = this._serialize(obj[field], serializedCaches, serializedRes); // 进一步序列化类成员的值 } if (classInfo && classInfo.id) res.serializeClassId = classInfo.id; // 设置 classId,在反序列化时获取类信息 } } serializedRes.push(serializedCache + " " + JSON.stringify(res)); } return "ref(" + serializedCache + ")"; } /** * 反序列化 * @param lines * @returns {any} */ static deserialize(lines: string[]): any { if (lines[0] == "-1") { return JSON.parse(lines[1]); } const deserializedCaches = {}; this._deserialize(lines, deserializedCaches, {}); return deserializedCaches[lines[0] + "_0"]; } private static _deserialize(lines: string[], deserializedCaches: any, refCaches: any): any { const magicNum = lines[0]; const objIdRegex = new RegExp("^ref\\((" + magicNum + "_\\d+)\\)$"); for (let i = 1, len = lines.length; i < len; i++) { const line = lines[i]; const spaceI = line.indexOf(" "); const objId = line.substring(0, spaceI); if (!objId.startsWith(magicNum + "_")) { throw new Error("bad serialized line, wrong magic num: " + line); } let obj = JSON.parse(line.substring(spaceI + 1)); if (obj instanceof Array) { for (let j = 0, objLen = obj.length; j < objLen; j++) { this.checkRefCache(objIdRegex, obj, j, deserializedCaches, refCaches); } } else { const serializeClassId = obj.serializeClassId; const serializeClassInfo = serializeClassId ? getClassInfoById(serializeClassId) : null; if (serializeClassInfo) { delete obj.serializeClassId; const serializeClass = serializeClassInfo.type; const newObj = new serializeClass(); Object.assign(newObj, obj); obj = newObj; } for (let key of Object.keys(obj)) { this.checkRefCache(objIdRegex, obj, key, deserializedCaches, refCaches); } } deserializedCaches[objId] = obj; let refs = refCaches[objId]; if (refs) { for (let ref of refs) { ref.obj[ref.keyOrIndex] = obj; } delete refCaches[objId]; } } } private static checkRefCache(objIdRegex: RegExp, obj: any, keyOrIndex: any, deserializedCaches: any, refCaches: any) { let m; const value = obj[keyOrIndex]; if (typeof value == "string" && (m = objIdRegex.exec(value))) { let refId = m[1]; let refObj = deserializedCaches[refId]; if (refObj) { obj[keyOrIndex] = refObj; } else { let refs = refCaches[refId]; if (refs == null) { refs = []; refCaches[refId] = refs; } refs.push({ obj: obj, keyOrIndex: keyOrIndex }); } } } } /** * @deprecated */ export class SerializableUtil_v1 { /** * 序列化 * @param obj * @returns {any | string | {}} */ static serialize(obj: any) { const serializedCaches = new Map<any, string>(); return this._serialize(obj, serializedCaches, "$"); } private static _serialize(obj: any, serializedCaches: Map<any, string>, path: string) { // console.log(path); if (obj == null || obj == undefined) return obj; // null 和 undefined 不参与序列化 const objType = typeof obj; if (objType == "string" || objType == "number" || objType == "boolean") { return obj; // string | number | boolean 不需要进一步序列化,直接返回原值 } const serializedCache = serializedCaches.get(obj); if (serializedCache !== undefined) { return "ref(" + serializedCache + ")"; // 序列化过程,如果当前处理的实例在之前已经有过序列化,则返回之前实例在序列化后对象中的路径,解决循环引用的问题 } // 保存当前处理的实例的路径 serializedCaches.set(obj, path); let res; const objConstructor = obj.constructor; if (objType == "function" || !objConstructor) { res = obj; // 方法不需要进一步序列化 } else if (obj instanceof Array) { res = []; (obj as Array<any>).forEach((value, index) => { res.push(this._serialize(value, serializedCaches, path + "[" + index + "]")); // 数组中每个元素需要进一步序列化 }); } else { res = {}; let transients = transientFields.get(objConstructor); for (let field in obj) { if (transients && transients[field]) { // 忽略字段 } else res[field] = this._serialize(obj[field], serializedCaches, path + "[" + JSON.stringify(field) + "]"); // 进一步序列化类成员的值 } let classInfo = classInfos.get(objConstructor); if (classInfo && classInfo.id) { res.serializeClassId = classInfo.id; // 设置 classId,在反序列化时获取类信息 } } return res || {}; } /** * 反序列化 * @param obj * @returns {any} */ static deserialize(obj: any): any { return this._deserialize(obj, {}, obj, "$"); } private static _deserialize(obj: any, deserializedCaches: any, root: any, path: string): any { if (obj == null) return obj; const objType = typeof obj; if (objType == "number" || objType == "boolean") { return obj; // number | boolean 不需要反序列化,直接返回 } else if (objType == "string") { const str = obj as string; if (str.startsWith("ref($") && str.endsWith(")")) { const refPath = str.substring(4, str.length - 1); let deserializedCache = deserializedCaches[refPath]; if (deserializedCache === undefined) { const $ = root; try { deserializedCache = deserializedCaches[refPath] = eval(refPath); // 根据绝对路径计算引用表达式的值 } catch (e) { return str; // 根据路径获取值失败,当做普通 string 返回 } } return deserializedCache; } else return obj; // 普通的 string 值,直接返回结果 } let res = null; if (obj instanceof Array) { res = deserializedCaches[path] = []; (obj as Array<any>).forEach((value, index) => { res.push(this._deserialize(value, deserializedCaches, root, path + "[" + index + "]")); // 进一步反序列化数组中每一个元素 }); } else { const serializeClassId = obj.serializeClassId; const serializeClassInfo = serializeClassId ? getClassInfoById(serializeClassId) : null; if (serializeClassInfo) { const serializeClass = serializeClassInfo.type; res = deserializedCaches[path] = new serializeClass(); for (let field of Object.keys(obj)) { if (field != "serializeClassId") res[field] = this._deserialize(obj[field], deserializedCaches, root, path + "[" + JSON.stringify(field) + "]"); } } else { res = deserializedCaches[path] = {}; for (let field of Object.keys(obj)) { res[field] = this._deserialize(obj[field], deserializedCaches, root, path + "[" + JSON.stringify(field) + "]"); } } } return res; } }
the_stack
import Q = require('q'); import assert = require('assert'); import mockHelper = require('../../lib/mockHelper'); import path = require('path'); import fs = require('fs'); import tl = require('../../lib/vsts-task-lib/toolrunner'); let CodeCoverageEnablerFactory = require('../../../Tasks/Common/codecoverage-tools/codecoveragefactory').CodeCoverageEnablerFactory; let xml2js = require('../../../Tasks/Common/codecoverage-tools/node_modules/xml2js'); function setResponseFile(name: string) { process.env['MOCK_RESPONSES'] = path.join(__dirname, name); } describe('Code Coverage enable tool tests', function () { this.timeout(parseInt(process.env.TASK_TEST_TIMEOUT) || 20000); let data = path.join(__dirname, "data"); let buildProps: { [key: string]: string } = {}; buildProps['classfilter'] = "+:com.abc,-:com.xyz"; buildProps['classfilesdirectories'] = "cfd"; buildProps['sourcedirectories'] = "sd"; buildProps['summaryfile'] = "coverage.xml"; buildProps['reportdirectory'] = path.join(data, "CCReport43F6D5EF"); buildProps['ccreporttask'] = "CodeCoverage_9064e1d0"; buildProps['reportbuildfile'] = path.join(data, "CCReportBuildA4D283EG.xml"); before((done) => { Q.longStackSupport = true; done(); }); after(function () { }); /* Maven build tool - Code Coverage */ it('Maven single module build file with Jacoco CC', (done) => { let buildFile = path.join(data, "single_module_pom.xml"); buildProps['buildfile'] = buildFile; let ccEnabler = new CodeCoverageEnablerFactory().getTool("maven", "jacoco"); ccEnabler.enableCodeCoverage(buildProps).then(function () { let content = fs.readFileSync(buildFile, "utf-8"); assert.notEqual(content.indexOf(`<include>**/com/abc.class</include>`), -1, "Include filter must be present"); assert.notEqual(content.indexOf(`<exclude>**/com/xyz.class</exclude>`), -1, "Exclude filter must be present"); assert.notEqual(content.indexOf(`jacoco-maven-plugin`), -1, "Jacoco maven plugin must be enabled"); done(); }).catch(function (err) { done(err); }); }); it('Maven multi module build file with Jacoco CC', (done) => { let buildFile = path.join(data, "multi_module_pom.xml"); buildProps['buildfile'] = buildFile; let ccEnabler = new CodeCoverageEnablerFactory().getTool("maven", "jacoco"); ccEnabler.enableCodeCoverage(buildProps).then(function (resp) { let content = fs.readFileSync(buildFile, "utf-8"); assert.notEqual(content.indexOf(`<include>**/com/abc.class</include>`), -1, "Include filter must be present"); assert.notEqual(content.indexOf(`<exclude>**/com/xyz.class</exclude>`), -1, "Exclude filter must be present"); assert.notEqual(content.indexOf(`jacoco-maven-plugin`), -1, "Jacoco maven plugin must be enabled"); done(); }).catch(function (err) { done(err); }); }); it('Maven single module build with pluginmanagement and plugins - Jacoco CC', (done) => { let buildFile = path.join(data, "pom_with_pluginmanagement_plugins_jac.xml"); buildProps['buildfile'] = buildFile; let ccEnabler = new CodeCoverageEnablerFactory().getTool("maven", "jacoco"); ccEnabler.enableCodeCoverage(buildProps).then(function () { let content = fs.readFileSync(buildFile, "utf-8"); assert.notEqual(content.indexOf(`<include>**/com/abc.class</include>`), -1, "Include filter must be present"); assert.notEqual(content.indexOf(`<exclude>**/com/xyz.class</exclude>`), -1, "Exclude filter must be present"); assert.notEqual(content.indexOf(`jacoco-maven-plugin`), -1, "Jacoco maven plugin must be enabled"); let xmlContent = xml2js.parseString(content, function (err, res) { assert.equal(res.project.build[0].plugins[0].plugin.length, 6, "Jacoco plugin added in the right place"); assert.equal(res.project.build[0].pluginManagement[0].plugins[0].plugin.length, 1, "Jacoco plugin shouldn't be added to pluginmanagement"); }); done(); }).catch(function (err) { done(err); }); }); it('Maven single module build file with Cobertura CC', (done) => { let buildFile = path.join(data, "single_module_pom.xml"); buildProps['buildfile'] = buildFile; let ccEnabler = new CodeCoverageEnablerFactory().getTool("maven", "cobertura"); ccEnabler.enableCodeCoverage(buildProps).then(function (resp) { let content = fs.readFileSync(buildFile, "utf-8"); assert.notEqual(content.indexOf(`<include>com/abc.class</include>`), -1, "Include filter must be present"); assert.notEqual(content.indexOf(`<exclude>com/xyz.class</exclude>`), -1, "Exclude filter must be present"); assert.notEqual(content.indexOf(`cobertura-maven-plugin`), -1, "Cobertura maven plugin must be enabled"); done(); }).catch(function (err) { done(err); }); }); it('Maven single module build with reporting extensions - Cobertura CC', (done) => { let buildFile = path.join(data, "pom_with_reporting_plugins.xml"); buildProps['buildfile'] = buildFile; let ccEnabler = new CodeCoverageEnablerFactory().getTool("maven", "cobertura"); ccEnabler.enableCodeCoverage(buildProps).then(function (resp) { let content = fs.readFileSync(buildFile, "utf-8"); assert.notEqual(content.indexOf(`<include>com/abc.class</include>`), -1, "Include filter must be present"); assert.notEqual(content.indexOf(`<exclude>com/xyz.class</exclude>`), -1, "Exclude filter must be present"); assert.notEqual(content.indexOf(`cobertura-maven-plugin`), -1, "Cobertura maven plugin must be enabled"); let xmlContent = xml2js.parseString(content, function (err, res) { assert.equal(res.project.reporting[0].plugins[0].plugin.length, 3, "Cobertura plugin added in the right place"); }); done(); }).catch(function (err) { done(err); }); }); it('Maven multi module build file with Cobertura CC', (done) => { let buildFile = path.join(data, "multi_module_pom.xml"); buildProps['buildfile'] = buildFile; let ccEnabler = new CodeCoverageEnablerFactory().getTool("maven", "cobertura"); ccEnabler.enableCodeCoverage(buildProps).then(function (resp) { let content = fs.readFileSync(buildFile, "utf-8"); assert.notEqual(content.indexOf(`<include>com/abc.class</include>`), -1, "Include filter must be present"); assert.notEqual(content.indexOf(`<exclude>com/xyz.class</exclude>`), -1, "Exclude filter must be present"); assert.notEqual(content.indexOf(`cobertura-maven-plugin`), -1, "Cobertura maven plugin must be enabled"); done(); }).catch(function (err) { done(err); }); }); it('Maven single module build with pluginmanagement and plugins - Cobertura CC', (done) => { let buildFile = path.join(data, "pom_with_pluginmanagement_plugins_cob.xml"); buildProps['buildfile'] = buildFile; let ccEnabler = new CodeCoverageEnablerFactory().getTool("maven", "cobertura"); ccEnabler.enableCodeCoverage(buildProps).then(function (resp) { let content = fs.readFileSync(buildFile, "utf-8"); assert.notEqual(content.indexOf(`<include>com/abc.class</include>`), -1, "Include filter must be present"); assert.notEqual(content.indexOf(`<exclude>com/xyz.class</exclude>`), -1, "Exclude filter must be present"); assert.notEqual(content.indexOf(`cobertura-maven-plugin`), -1, "Cobertura maven plugin must be enabled"); let xmlContent = xml2js.parseString(content, function (err, res) { assert.equal(res.project.build[0].plugins[0].plugin.length, 6, "Cobertura plugin added in the right place"); assert.equal(res.project.build[0].pluginManagement[0].plugins[0].plugin.length, 1, "Cobertura plugin shouldn't be added to pluginmanagement"); }); done(); }).catch(function (err) { done(err); }); }); /* Gradle build tool - Code Coverage */ it('Gradle single module build file with Jacoco CC', (done) => { let buildFile = path.join(data, "single_module_build.gradle"); buildProps['buildfile'] = buildFile; let ccEnabler = new CodeCoverageEnablerFactory().getTool("gradle", "jacoco"); ccEnabler.enableCodeCoverage(buildProps).then(function (resp) { let content = fs.readFileSync(buildFile, "utf-8"); assert.notEqual(content.indexOf(`def jacocoIncludes = ['com/abc.class']`), -1, "Include filter must be present"); assert.notEqual(content.indexOf(`def jacocoExcludes = ['com/xyz.class']`), -1, "Exclude filter must be present"); assert.notEqual(content.indexOf(`finalizedBy jacocoTestReport`), -1, "Jacoco report task must be present"); assert.notEqual(content.indexOf(`apply plugin: 'jacoco'`), -1, "Jacoco gradle plugin must be enabled"); done(); }).catch(function (err) { done(err); }); }); it('Gradle multi module build file with Jacoco CC', (done) => { let buildFile = path.join(data, "multi_module_build.gradle"); buildProps['buildfile'] = buildFile; buildProps['ismultimodule'] = "true"; let ccEnabler = new CodeCoverageEnablerFactory().getTool("gradle", "jacoco"); ccEnabler.enableCodeCoverage(buildProps).then(function (resp) { let content = fs.readFileSync(buildFile, "utf-8"); assert.notEqual(content.indexOf(`def jacocoExcludes = ['com/xyz.class']`), -1, "Include filter must be present"); assert.notEqual(content.indexOf(`def jacocoIncludes = ['com/abc.class']`), -1, "Exclude filter must be present"); assert.notEqual(content.indexOf(`jacocoRootReport`), -1, "Jacoco task must be enabled"); done(); }).catch(function (err) { done(err); }); }); it('Gradle single module build file with Cobertura CC', (done) => { let buildFile = path.join(data, "single_module_build.gradle"); buildProps['buildfile'] = buildFile; let ccEnabler = new CodeCoverageEnablerFactory().getTool("gradle", "cobertura"); ccEnabler.enableCodeCoverage(buildProps).then(function (resp) { let content = fs.readFileSync(buildFile, "utf-8"); assert.notEqual(content.indexOf(`cobertura.coverageIncludes = ['.*com.abc']`), -1, "Include filter must be present"); assert.notEqual(content.indexOf(`cobertura.coverageExcludes = ['.*com.xyz']`), -1, "Exclude filter must be present"); assert.notEqual(content.indexOf(`net.saliman:gradle-cobertura-plugin`), -1, "Cobertura Plugin must be present"); done(); }).catch(function (err) { done(err); }); }); it('Gradle multi module build file with Cobertura CC', (done) => { let buildFile = path.join(data, "multi_module_build.gradle"); buildProps['buildfile'] = buildFile; buildProps['ismultimodule'] = "true"; let ccEnabler = new CodeCoverageEnablerFactory().getTool("gradle", "cobertura"); ccEnabler.enableCodeCoverage(buildProps).then(function (resp) { let content = fs.readFileSync(buildFile, "utf-8"); assert.notEqual(content.indexOf(`cobertura.coverageIncludes = ['.*com.abc']`), -1, "Include filter must be present"); assert.notEqual(content.indexOf(`cobertura.coverageExcludes = ['.*com.xyz']`), -1, "Exclude filter must be present"); assert.notEqual(content.indexOf(`net.saliman:gradle-cobertura-plugin`), -1, "Cobertura Plugin must be present"); done(); }).catch(function (err) { done(err); }); }); /* Ant build tool - Code Coverage */ it('Ant build file with Jacoco CC', (done) => { let buildFile = path.join(data, "ant_build.xml"); buildProps['buildfile'] = buildFile; buildProps['sourcedirectories'] = ""; let ccEnabler = new CodeCoverageEnablerFactory().getTool("ant", "jacoco"); ccEnabler.enableCodeCoverage(buildProps).then(function (resp) { let content = fs.readFileSync(buildFile, "utf-8"); assert.notEqual(content.indexOf(`excludes="com.xyz"`), -1, "Exclude filter must be present"); assert.notEqual(content.indexOf(`includes="com.abc`), -1, "Include filter must be present"); assert.notEqual(content.indexOf(`jacoco:coverage destfile`), -1, "Jacoco Plugin must be present"); done(); }).catch(function (err) { done(err); }); }); it('Ant build file with Cobertura CC', (done) => { let buildFile = path.join(data, "ant_build.xml"); buildProps['buildfile'] = buildFile; let ccEnabler = new CodeCoverageEnablerFactory().getTool("ant", "cobertura"); ccEnabler.enableCodeCoverage(buildProps).then(function (resp) { let content = fs.readFileSync(buildFile, "utf-8"); assert.notEqual(fs.existsSync(path.join(data, buildProps['reportbuildfile'])), true, "Report file must be present"); assert.notEqual(content.indexOf(`cobertura-classpath`), -1, "Cobertura Plugin must be present"); done(); }).catch(function (err) { done(err); }); }); });
the_stack