text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { Yok } from "../../../yok"; import { assert } from "chai"; import * as _ from "lodash"; import { CommonLoggerStub, HooksServiceStub, DeviceLogProviderStub, } from "../stubs"; import { ApplicationManagerBase } from "../../../mobile/application-manager-base"; import { IDictionary, IHooksService } from "../../../declarations"; import { IInjector } from "../../../definitions/yok"; let currentlyAvailableAppsForDebugging: Mobile.IDeviceApplicationInformation[]; let currentlyInstalledApps: string[]; let currentlyAvailableAppWebViewsForDebugging: IDictionary< Mobile.IDebugWebViewInfo[] >; class ApplicationManager extends ApplicationManagerBase { constructor( $logger: ILogger, $hooksService: IHooksService, $deviceLogProvider: Mobile.IDeviceLogProvider ) { super($logger, $hooksService, $deviceLogProvider); } public async installApplication(packageFilePath: string): Promise<void> { return; } public async uninstallApplication(appIdentifier: string): Promise<void> { return; } public async startApplication( appData: Mobile.IApplicationData ): Promise<void> { return; } public async stopApplication( appData: Mobile.IApplicationData ): Promise<void> { return; } public async getInstalledApplications(): Promise<string[]> { return _.cloneDeep(currentlyInstalledApps); } public async getDebuggableApps(): Promise< Mobile.IDeviceApplicationInformation[] > { return currentlyAvailableAppsForDebugging; } public async getDebuggableAppViews( appIdentifiers: string[] ): Promise<IDictionary<Mobile.IDebugWebViewInfo[]>> { return _.cloneDeep(currentlyAvailableAppWebViewsForDebugging); } } function createTestInjector(): IInjector { const testInjector = new Yok(); testInjector.register("logger", CommonLoggerStub); testInjector.register("hooksService", HooksServiceStub); testInjector.register("applicationManager", ApplicationManager); testInjector.register("deviceLogProvider", DeviceLogProviderStub); return testInjector; } function createAppsAvailableForDebugging( count: number ): Mobile.IDeviceApplicationInformation[] { return _.times(count, (index: number) => ({ deviceIdentifier: "deviceId", appIdentifier: `appId_${index}`, framework: "framework", })); } function createDebuggableWebView(uniqueId: string) { return { description: `description_${uniqueId}`, devtoolsFrontendUrl: `devtoolsFrontendUrl_${uniqueId}`, id: `${uniqueId}`, title: `title_${uniqueId}`, type: `type_${uniqueId}`, url: `url_${uniqueId}`, webSocketDebuggerUrl: `webSocketDebuggerUrl_${uniqueId}`, }; } function createDebuggableWebViews( appInfos: Mobile.IDeviceApplicationInformation[], numberOfViews: number ): IDictionary<Mobile.IDebugWebViewInfo[]> { const result: IDictionary<Mobile.IDebugWebViewInfo[]> = {}; _.each(appInfos, (appInfo, index) => { result[appInfo.appIdentifier] = _.times( numberOfViews, (currentViewIndex: number) => createDebuggableWebView(`${index}_${currentViewIndex}`) ); }); return result; } describe("ApplicationManagerBase", () => { let applicationManager: ApplicationManager; let testInjector: IInjector; const applicationData = { appId: "appId", projectName: "appName", projectDir: "", }; beforeEach(() => { testInjector = createTestInjector(); currentlyAvailableAppsForDebugging = null; currentlyAvailableAppWebViewsForDebugging = null; applicationManager = testInjector.resolve("applicationManager"); }); describe("checkForApplicationUpdates", () => { describe("debuggableApps", () => { it("emits debuggableAppFound when new application is available for debugging", async () => { currentlyAvailableAppsForDebugging = createAppsAvailableForDebugging(2); const foundAppsForDebug: Mobile.IDeviceApplicationInformation[] = []; applicationManager.on( "debuggableAppFound", (d: Mobile.IDeviceApplicationInformation) => { foundAppsForDebug.push(d); if ( foundAppsForDebug.length === currentlyAvailableAppsForDebugging.length ) { _.each( foundAppsForDebug, (f: Mobile.IDeviceApplicationInformation, index: number) => { assert.deepStrictEqual( f, currentlyAvailableAppsForDebugging[index] ); } ); } } ); await applicationManager.checkForApplicationUpdates(); }); it("emits debuggableAppFound when new application is available for debugging (several calls)", async () => { currentlyAvailableAppsForDebugging = createAppsAvailableForDebugging(1); const foundAppsForDebug: Mobile.IDeviceApplicationInformation[] = []; let isFinalCheck = false; applicationManager.on( "debuggableAppFound", (d: Mobile.IDeviceApplicationInformation) => { foundAppsForDebug.push(d); if ( foundAppsForDebug.length === currentlyAvailableAppsForDebugging.length ) { _.each( foundAppsForDebug, (f: Mobile.IDeviceApplicationInformation, index: number) => { assert.deepStrictEqual( f, currentlyAvailableAppsForDebugging[index] ); } ); if (isFinalCheck) { return; } } } ); await applicationManager.checkForApplicationUpdates(); currentlyAvailableAppsForDebugging = createAppsAvailableForDebugging(2); await applicationManager.checkForApplicationUpdates(); currentlyAvailableAppsForDebugging = createAppsAvailableForDebugging(4); isFinalCheck = true; await applicationManager.checkForApplicationUpdates(); }); it("emits debuggableAppLost when application cannot be debugged anymore", async () => { currentlyAvailableAppsForDebugging = createAppsAvailableForDebugging(2); const expectedAppsToBeLost = currentlyAvailableAppsForDebugging, lostAppsForDebug: Mobile.IDeviceApplicationInformation[] = []; applicationManager.on( "debuggableAppLost", (d: Mobile.IDeviceApplicationInformation) => { lostAppsForDebug.push(d); if (lostAppsForDebug.length === expectedAppsToBeLost.length) { _.each( lostAppsForDebug, (f: Mobile.IDeviceApplicationInformation, index: number) => { assert.deepStrictEqual(f, expectedAppsToBeLost[index]); } ); } } ); // First call will raise debuggableAppFound two times. await applicationManager.checkForApplicationUpdates(); currentlyAvailableAppsForDebugging = []; // This call should raise debuggableAppLost two times. await applicationManager.checkForApplicationUpdates(); }); it("emits debuggableAppLost when application cannot be debugged anymore (several calls)", async () => { currentlyAvailableAppsForDebugging = createAppsAvailableForDebugging(4); const lostAppsForDebug: Mobile.IDeviceApplicationInformation[] = []; let isFinalCheck = false; const initialAppsAvailableForDebug = currentlyAvailableAppsForDebugging; applicationManager.on( "debuggableAppLost", (d: Mobile.IDeviceApplicationInformation) => { lostAppsForDebug.push(d); _.each( lostAppsForDebug, (f: Mobile.IDeviceApplicationInformation, index: number) => { assert.deepStrictEqual( f, _.find( initialAppsAvailableForDebug, (t) => t.appIdentifier === f.appIdentifier ) ); } ); if ( lostAppsForDebug.length === initialAppsAvailableForDebug.length && isFinalCheck ) { return; } } ); await applicationManager.checkForApplicationUpdates(); currentlyAvailableAppsForDebugging = createAppsAvailableForDebugging(2); await applicationManager.checkForApplicationUpdates(); currentlyAvailableAppsForDebugging = createAppsAvailableForDebugging(0); isFinalCheck = true; await applicationManager.checkForApplicationUpdates(); }); it("emits debuggableAppFound and debuggableAppLost when applications are changed", async () => { const allAppsForDebug = createAppsAvailableForDebugging(4); currentlyAvailableAppsForDebugging = _.take(allAppsForDebug, 2); const remainingAppsForDebugging = _.difference( allAppsForDebug, currentlyAvailableAppsForDebugging ); const foundAppsForDebug: Mobile.IDeviceApplicationInformation[] = []; // This will raise debuggableAppFound 2 times. await applicationManager.checkForApplicationUpdates(); const foundAppsPromise = new Promise<void>((resolve, reject) => { applicationManager.on( "debuggableAppFound", (d: Mobile.IDeviceApplicationInformation) => { foundAppsForDebug.push(d); if ( foundAppsForDebug.length === remainingAppsForDebugging.length ) { _.each( foundAppsForDebug, (f: Mobile.IDeviceApplicationInformation, index: number) => { assert.deepStrictEqual(f, remainingAppsForDebugging[index]); } ); resolve(); } } ); }); const lostAppsPromise = new Promise<void>((resolve, reject) => { applicationManager.on( "debuggableAppLost", (d: Mobile.IDeviceApplicationInformation) => { assert.deepStrictEqual( d, allAppsForDebug[0], "Debuggable app lost does not match." ); resolve(); } ); }); currentlyAvailableAppsForDebugging = _.drop(allAppsForDebug, 1); await applicationManager.checkForApplicationUpdates(); await Promise.all([foundAppsPromise, lostAppsPromise]); }); it("emits debuggableViewFound when new views are available for debug", (done: mocha.Done) => { currentlyAvailableAppsForDebugging = createAppsAvailableForDebugging(2); const numberOfViewsPerApp = 2; currentlyAvailableAppWebViewsForDebugging = createDebuggableWebViews( currentlyAvailableAppsForDebugging, numberOfViewsPerApp ); const currentDebuggableViews: IDictionary< Mobile.IDebugWebViewInfo[] > = {}; applicationManager.on( "debuggableViewFound", (appIdentifier: string, d: Mobile.IDebugWebViewInfo) => { currentDebuggableViews[appIdentifier] = currentDebuggableViews[appIdentifier] || []; currentDebuggableViews[appIdentifier].push(d); const numberOfFoundViewsPerApp = _.uniq( _.values(currentDebuggableViews).map((arr) => arr.length) ); if ( _.keys(currentDebuggableViews).length === currentlyAvailableAppsForDebugging.length && numberOfFoundViewsPerApp.length === 1 && // for all apps we've found exactly two apps. numberOfFoundViewsPerApp[0] === numberOfViewsPerApp ) { _.each(currentDebuggableViews, (webViews, appId) => { _.each(webViews, (webView) => { const expectedWebView = _.find( currentlyAvailableAppWebViewsForDebugging[appId], (c) => c.id === webView.id ); assert.isTrue(_.isEqual(webView, expectedWebView)); }); }); setTimeout(done, 0); } } ); /* tslint:disable:no-floating-promises */ applicationManager.checkForApplicationUpdates(); /* tslint:enable:no-floating-promises */ }); it("emits debuggableViewLost when views for debug are removed", (done: mocha.Done) => { currentlyAvailableAppsForDebugging = createAppsAvailableForDebugging(2); const numberOfViewsPerApp = 2; currentlyAvailableAppWebViewsForDebugging = createDebuggableWebViews( currentlyAvailableAppsForDebugging, numberOfViewsPerApp ); const expectedResults = _.cloneDeep( currentlyAvailableAppWebViewsForDebugging ); const currentDebuggableViews: IDictionary< Mobile.IDebugWebViewInfo[] > = {}; applicationManager .checkForApplicationUpdates() .then(() => { applicationManager.on( "debuggableViewLost", (appIdentifier: string, d: Mobile.IDebugWebViewInfo) => { currentDebuggableViews[appIdentifier] = currentDebuggableViews[appIdentifier] || []; currentDebuggableViews[appIdentifier].push(d); const numberOfFoundViewsPerApp = _.uniq( _.values(currentDebuggableViews).map((arr) => arr.length) ); if ( _.keys(currentDebuggableViews).length === currentlyAvailableAppsForDebugging.length && numberOfFoundViewsPerApp.length === 1 && // for all apps we've found exactly two apps. numberOfFoundViewsPerApp[0] === numberOfViewsPerApp ) { _.each(currentDebuggableViews, (webViews, appId) => { _.each(webViews, (webView) => { const expectedWebView = _.find( expectedResults[appId], (c) => c.id === webView.id ); assert.isTrue(_.isEqual(webView, expectedWebView)); }); }); setTimeout(done, 0); } } ); currentlyAvailableAppWebViewsForDebugging = _.mapValues( currentlyAvailableAppWebViewsForDebugging, (a) => [] ); return applicationManager.checkForApplicationUpdates(); }) .catch(); }); it("emits debuggableViewFound when new views are available for debug", (done: mocha.Done) => { currentlyAvailableAppsForDebugging = createAppsAvailableForDebugging(2); const numberOfViewsPerApp = 2; currentlyAvailableAppWebViewsForDebugging = createDebuggableWebViews( currentlyAvailableAppsForDebugging, numberOfViewsPerApp ); let expectedViewToBeFound = createDebuggableWebView("uniqueId"); let expectedAppIdentifier = currentlyAvailableAppsForDebugging[0].appIdentifier; let isLastCheck = false; applicationManager .checkForApplicationUpdates() .then(() => { applicationManager.on( "debuggableViewFound", (appIdentifier: string, d: Mobile.IDebugWebViewInfo) => { assert.deepStrictEqual(appIdentifier, expectedAppIdentifier); assert.isTrue(_.isEqual(d, expectedViewToBeFound)); if (isLastCheck) { setTimeout(done, 0); } } ); currentlyAvailableAppWebViewsForDebugging[ expectedAppIdentifier ].push(_.cloneDeep(expectedViewToBeFound)); return applicationManager.checkForApplicationUpdates(); }) .catch() .then(() => { expectedViewToBeFound = createDebuggableWebView("uniqueId1"); currentlyAvailableAppWebViewsForDebugging[ expectedAppIdentifier ].push(_.cloneDeep(expectedViewToBeFound)); return applicationManager.checkForApplicationUpdates(); }) .catch() .then(() => { expectedViewToBeFound = createDebuggableWebView("uniqueId2"); expectedAppIdentifier = currentlyAvailableAppsForDebugging[1].appIdentifier; isLastCheck = true; currentlyAvailableAppWebViewsForDebugging[ expectedAppIdentifier ].push(_.cloneDeep(expectedViewToBeFound)); return applicationManager.checkForApplicationUpdates(); }) .catch(); }); it("emits debuggableViewLost when views for debug are not available anymore", (done: mocha.Done) => { currentlyAvailableAppsForDebugging = createAppsAvailableForDebugging(2); const numberOfViewsPerApp = 2; currentlyAvailableAppWebViewsForDebugging = createDebuggableWebViews( currentlyAvailableAppsForDebugging, numberOfViewsPerApp ); let expectedAppIdentifier = currentlyAvailableAppsForDebugging[0].appIdentifier; let expectedViewToBeLost = currentlyAvailableAppWebViewsForDebugging[ expectedAppIdentifier ].splice(0, 1)[0]; let isLastCheck = false; applicationManager .checkForApplicationUpdates() .then(() => { applicationManager.on( "debuggableViewLost", (appIdentifier: string, d: Mobile.IDebugWebViewInfo) => { assert.deepStrictEqual(appIdentifier, expectedAppIdentifier); assert.isTrue(_.isEqual(d, expectedViewToBeLost)); if (isLastCheck) { setTimeout(done, 0); } } ); return applicationManager.checkForApplicationUpdates(); }) .catch() .then(() => { expectedViewToBeLost = currentlyAvailableAppWebViewsForDebugging[ expectedAppIdentifier ].splice(0, 1)[0]; return applicationManager.checkForApplicationUpdates(); }) .catch() .then(() => { expectedAppIdentifier = currentlyAvailableAppsForDebugging[1].appIdentifier; expectedViewToBeLost = currentlyAvailableAppWebViewsForDebugging[ expectedAppIdentifier ].splice(0, 1)[0]; isLastCheck = true; return applicationManager.checkForApplicationUpdates(); }) .catch(); }); it("emits debuggableViewChanged when view's property is modified (each one except id)", (done: mocha.Done) => { currentlyAvailableAppsForDebugging = createAppsAvailableForDebugging(1); currentlyAvailableAppWebViewsForDebugging = createDebuggableWebViews( currentlyAvailableAppsForDebugging, 2 ); const viewToChange = currentlyAvailableAppWebViewsForDebugging[ currentlyAvailableAppsForDebugging[0].appIdentifier ][0]; const expectedView = _.cloneDeep(viewToChange); expectedView.title = "new title"; applicationManager.on( "debuggableViewChanged", (appIdentifier: string, d: Mobile.IDebugWebViewInfo) => { assert.isTrue(_.isEqual(d, expectedView)); setTimeout(done, 0); } ); applicationManager .checkForApplicationUpdates() .then(() => { viewToChange.title = "new title"; return applicationManager.checkForApplicationUpdates(); }) .catch(); }); it("does not emit debuggableViewChanged when id is modified", (done: mocha.Done) => { currentlyAvailableAppsForDebugging = createAppsAvailableForDebugging(1); currentlyAvailableAppWebViewsForDebugging = createDebuggableWebViews( currentlyAvailableAppsForDebugging, 2 ); const viewToChange = currentlyAvailableAppWebViewsForDebugging[ currentlyAvailableAppsForDebugging[0].appIdentifier ][0]; const expectedView = _.cloneDeep(viewToChange); applicationManager .checkForApplicationUpdates() .then(() => { applicationManager.on( "debuggableViewChanged", (appIdentifier: string, d: Mobile.IDebugWebViewInfo) => { setTimeout( () => done( new Error( "When id is changed, debuggableViewChanged must not be emitted." ) ), 0 ); } ); applicationManager.on( "debuggableViewLost", (appIdentifier: string, d: Mobile.IDebugWebViewInfo) => { assert.isTrue(_.isEqual(d, expectedView)); } ); applicationManager.on( "debuggableViewFound", (appIdentifier: string, d: Mobile.IDebugWebViewInfo) => { expectedView.id = "new id"; assert.isTrue(_.isEqual(d, expectedView)); setTimeout(done, 0); } ); viewToChange.id = "new id"; }) .catch() .then(() => applicationManager.checkForApplicationUpdates()) .catch(); }); }); describe("installed and uninstalled apps", () => { it("reports installed applications when initially there are apps", async () => { currentlyInstalledApps = ["app1", "app2", "app3"]; const reportedInstalledApps: string[] = [], promise = new Promise<void>((resolve, reject) => { applicationManager.on("applicationInstalled", (app: string) => { reportedInstalledApps.push(app); if ( reportedInstalledApps.length === currentlyInstalledApps.length ) { resolve(); } }); }); await applicationManager.checkForApplicationUpdates(); await promise; _.each(currentlyInstalledApps, (c: string, index: number) => { assert.deepStrictEqual(c, reportedInstalledApps[index]); }); assert.deepStrictEqual( reportedInstalledApps.length, currentlyInstalledApps.length ); }); it("reports installed applications when apps are changed between executions", async () => { currentlyInstalledApps = ["app1", "app2", "app3"]; const reportedInstalledApps: string[] = []; let promise: Promise<void>; const testInstalledAppsResults = async () => { promise = new Promise<void>((resolve, reject) => { applicationManager.on("applicationInstalled", (app: string) => { reportedInstalledApps.push(app); if ( reportedInstalledApps.length === currentlyInstalledApps.length ) { applicationManager.removeAllListeners("applicationInstalled"); resolve(); } }); }); await applicationManager.checkForApplicationUpdates(); await promise; _.each(currentlyInstalledApps, (c: string, index: number) => { assert.deepStrictEqual(c, reportedInstalledApps[index]); }); assert.deepStrictEqual( reportedInstalledApps.length, currentlyInstalledApps.length ); }; await testInstalledAppsResults(); currentlyInstalledApps.push("app4", "app5"); await testInstalledAppsResults(); currentlyInstalledApps.push("app6", "app7"); await testInstalledAppsResults(); }); it("reports uninstalled applications when initially there are apps and all are uninstalled", async () => { currentlyInstalledApps = ["app1", "app2", "app3"]; await applicationManager.checkForApplicationUpdates(); const reportedUninstalledApps: string[] = [], initiallyInstalledApps = _.cloneDeep(currentlyInstalledApps), promise = new Promise<void>((resolve, reject) => { currentlyInstalledApps = []; applicationManager.on("applicationUninstalled", (app: string) => { reportedUninstalledApps.push(app); if ( reportedUninstalledApps.length === initiallyInstalledApps.length ) { resolve(); } }); }); await applicationManager.checkForApplicationUpdates(); await promise; _.each(initiallyInstalledApps, (c: string, index: number) => { assert.deepStrictEqual(c, reportedUninstalledApps[index]); }); assert.deepStrictEqual( reportedUninstalledApps.length, initiallyInstalledApps.length ); }); it("reports uninstalled applications when apps are changed between executions", async () => { currentlyInstalledApps = [ "app1", "app2", "app3", "app4", "app5", "app6", ]; // Initialize - all apps are marked as installed. await applicationManager.checkForApplicationUpdates(); const reportedUninstalledApps: string[] = []; let removedApps: string[] = []; let promise: Promise<void>; const testInstalledAppsResults = async () => { promise = new Promise<void>((resolve, reject) => { applicationManager.on("applicationUninstalled", (app: string) => { reportedUninstalledApps.push(app); if (reportedUninstalledApps.length === removedApps.length) { applicationManager.removeAllListeners("applicationUninstalled"); resolve(); } }); }); await applicationManager.checkForApplicationUpdates(); await promise; _.each(removedApps, (c: string, index: number) => { assert.deepStrictEqual(c, reportedUninstalledApps[index]); }); assert.deepStrictEqual( reportedUninstalledApps.length, removedApps.length ); }; while (currentlyInstalledApps.length) { const currentlyRemovedApps = currentlyInstalledApps.splice(0, 2); removedApps = removedApps.concat(currentlyRemovedApps); await testInstalledAppsResults(); } }); it("reports installed and uninstalled apps when apps are changed between executions", async () => { currentlyInstalledApps = [ "app1", "app2", "app3", "app4", "app5", "app6", ]; await applicationManager.checkForApplicationUpdates(); const reportedUninstalledApps: string[] = []; const reportedInstalledApps: string[] = []; let installedApps: string[] = []; let removedApps: string[] = []; let appUninstalledPromise: Promise<void>; let appInstalledPromise: Promise<void>; const testInstalledAppsResults = async () => { appInstalledPromise = new Promise<void>((resolve, reject) => { applicationManager.on("applicationInstalled", (app: string) => { reportedInstalledApps.push(app); if (reportedInstalledApps.length === installedApps.length) { applicationManager.removeAllListeners("applicationInstalled"); resolve(); } }); }); appUninstalledPromise = new Promise<void>((resolve, reject) => { applicationManager.on("applicationUninstalled", (app: string) => { reportedUninstalledApps.push(app); if (reportedUninstalledApps.length === removedApps.length) { applicationManager.removeAllListeners("applicationUninstalled"); resolve(); } }); }); await applicationManager.checkForApplicationUpdates(); await Promise.all([appInstalledPromise, appUninstalledPromise]); _.each(removedApps, (c: string, index: number) => { assert.deepStrictEqual(c, reportedUninstalledApps[index]); }); assert.deepStrictEqual( reportedUninstalledApps.length, removedApps.length ); _.each(installedApps, (c: string, index: number) => { assert.deepStrictEqual(c, reportedInstalledApps[index]); }); assert.deepStrictEqual( reportedInstalledApps.length, installedApps.length ); }; for (let index = 10; index < 13; index++) { const currentlyRemovedApps = currentlyInstalledApps.splice(0, 2); removedApps = removedApps.concat(currentlyRemovedApps); const currentlyAddedApps = [`app${index}`]; currentlyInstalledApps = currentlyInstalledApps.concat( currentlyAddedApps ); installedApps = installedApps.concat(currentlyAddedApps); await testInstalledAppsResults(); } }); }); }); describe("isApplicationInstalled", () => { it("returns true when app is installed", async () => { currentlyInstalledApps = ["app1", "app2"]; assert.isTrue( await applicationManager.isApplicationInstalled("app1"), "app1 is installed, so result of isAppInstalled must be true." ); assert.isTrue( await applicationManager.isApplicationInstalled("app2"), "app2 is installed, so result of isAppInstalled must be true." ); }); it("returns false when app is NOT installed", async () => { currentlyInstalledApps = ["app1", "app2"]; assert.isFalse( await applicationManager.isApplicationInstalled("app3"), "app3 is NOT installed, so result of isAppInstalled must be false." ); assert.isFalse( await applicationManager.isApplicationInstalled("app4"), "app4 is NOT installed, so result of isAppInstalled must be false." ); }); }); describe("restartApplication", () => { it("calls stopApplication with correct arguments", async () => { let passedApplicationData: Mobile.IApplicationData = null; applicationManager.stopApplication = ( appData: Mobile.IApplicationData ) => { passedApplicationData = appData; return Promise.resolve(); }; await applicationManager.restartApplication(applicationData); assert.deepStrictEqual( applicationData, passedApplicationData, "When bundleIdentifier is not passed to restartApplication, stopApplication must be called with application identifier." ); }); it("calls startApplication with correct arguments", async () => { let passedApplicationData: Mobile.IApplicationData = null; applicationManager.startApplication = ( appData: Mobile.IApplicationData ) => { passedApplicationData = appData; return Promise.resolve(); }; await applicationManager.restartApplication(applicationData); assert.deepStrictEqual( passedApplicationData, applicationData, "startApplication must be called with correct args." ); }); it("calls stopApplication and startApplication in correct order", async () => { let isStartApplicationCalled = false; let isStopApplicationCalled = false; applicationManager.stopApplication = ( appData: Mobile.IApplicationData ) => { isStopApplicationCalled = true; return Promise.resolve(); }; applicationManager.startApplication = ( appData: Mobile.IApplicationData ) => { assert.isTrue( isStopApplicationCalled, "When startApplication is called, stopApplication must have been resolved." ); isStartApplicationCalled = true; return Promise.resolve(); }; await applicationManager.restartApplication(applicationData); assert.isTrue(isStopApplicationCalled, "stopApplication must be called."); assert.isTrue( isStartApplicationCalled, "startApplication must be called." ); }); }); describe("tryStartApplication", () => { it("calls startApplication", async () => { let passedApplicationData: Mobile.IApplicationData = null; applicationManager.startApplication = ( appData: Mobile.IApplicationData ) => { passedApplicationData = appData; return Promise.resolve(); }; await applicationManager.tryStartApplication(applicationData); assert.deepStrictEqual(passedApplicationData, applicationData); const secondApplicationData = { appId: "appId2", projectName: "appName2", projectDir: "", }; await applicationManager.tryStartApplication(secondApplicationData); assert.deepStrictEqual(passedApplicationData, secondApplicationData); }); describe("does not throw Error", () => { const error = new Error("Throw!"); let isStartApplicationCalled = false; let logger: CommonLoggerStub; beforeEach(() => { isStartApplicationCalled = false; logger = testInjector.resolve("logger"); }); const assertDoesNotThrow = async (opts?: { shouldStartApplicatinThrow: boolean; }) => { assert.deepStrictEqual(logger.traceOutput, ""); applicationManager.startApplication = async ( appData: Mobile.IApplicationData ) => { if (opts && opts.shouldStartApplicatinThrow) { throw error; } isStartApplicationCalled = true; return Promise.resolve(); }; await applicationManager.tryStartApplication(applicationData); assert.isFalse( isStartApplicationCalled, "startApplication must not be called when there's an error." ); assert.isTrue( logger.traceOutput.indexOf("Throw!") !== -1, "Error message must be shown in trace output." ); assert.isTrue( logger.traceOutput.indexOf("Unable to start application") !== -1, "'Unable to start application' must be shown in trace output." ); }; it("when startApplications throws", async () => { applicationManager.isApplicationInstalled = (appId: string) => Promise.resolve(true); await assertDoesNotThrow({ shouldStartApplicatinThrow: true }); }); }); }); describe("reinstallApplication", () => { it("calls uninstallApplication with correct arguments", async () => { let uninstallApplicationAppIdParam: string; applicationManager.uninstallApplication = (appId: string) => { uninstallApplicationAppIdParam = appId; return Promise.resolve(); }; applicationManager.isApplicationInstalled = (appIdentifier: string) => Promise.resolve(true); await applicationManager.reinstallApplication("appId", "packageFilePath"); assert.deepStrictEqual(uninstallApplicationAppIdParam, "appId"); }); it("calls installApplication with correct arguments", async () => { let installApplicationPackageFilePathParam: string; applicationManager.installApplication = (packageFilePath: string) => { installApplicationPackageFilePathParam = packageFilePath; return Promise.resolve(); }; await applicationManager.reinstallApplication("appId", "packageFilePath"); assert.deepStrictEqual( installApplicationPackageFilePathParam, "packageFilePath" ); }); it("calls uninstallApplication and installApplication in correct order", async () => { let isInstallApplicationCalled = false; let isUninstallApplicationCalled = false; applicationManager.isApplicationInstalled = (appIdentifier: string) => Promise.resolve(true); applicationManager.uninstallApplication = (appId: string) => { assert.isFalse( isInstallApplicationCalled, "When uninstallApplication is called, installApplication should not have been called." ); isUninstallApplicationCalled = true; return Promise.resolve(); }; applicationManager.installApplication = (packageFilePath: string) => { assert.isTrue( isUninstallApplicationCalled, "When installApplication is called, uninstallApplication should have been called." ); isInstallApplicationCalled = true; return Promise.resolve(); }; await applicationManager.reinstallApplication("appId", "packageFilePath"); assert.isTrue( isUninstallApplicationCalled, "uninstallApplication should have been called." ); assert.isTrue( isInstallApplicationCalled, "installApplication should have been called." ); }); }); });
the_stack
import * as React from 'react'; import JqxButton from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxbuttons'; import JqxCheckBox from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxcheckbox'; import JqxListBox from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxlistbox'; import JqxTabs from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxtabs'; class App extends React.PureComponent<{}, {}> { private myTabs = React.createRef<JqxTabs>(); private usernameInput = React.createRef<HTMLInputElement>(); private passwordInput = React.createRef<HTMLInputElement>(); private acceptCheckBox = React.createRef<JqxCheckBox>(); private products = React.createRef<JqxListBox>(); private orderContainer = React.createRef<HTMLDivElement>(); constructor(props: {}) { super(props); this.acceptCheckBoxChange = this.acceptCheckBoxChange.bind(this); this.productsChange = this.productsChange.bind(this); this.productsUnselect = this.productsUnselect.bind(this); } public componentDidMount() { this.addHandlers(); this.validate(true); this.showHint('Validation hints.', '#hintSection'); } public render() { return ( <JqxTabs theme={'material-purple'} ref={this.myTabs} // @ts-ignore width={'100%'} height={230} keyboardNavigation={false} > <ul> <li style={{ marginLeft: 30 }}> Personal info </li> <li>Shopping basket</li> <li>Review order</li> </ul> <div className={"section"}> <div id={"form"}> <div className={"inputContainer"}> Username: <input className={"formInput"} type="text" ref={this.usernameInput} /> </div> <div className={"inputContainer"}> Password: <input className={"formInput"} type="password" ref={this.passwordInput} /> </div> </div> <div id={"hintWrapper"}> <div id={"hintSection"} className={"hint"} /> </div> <div id={"checkBoxWrapper"}> <JqxCheckBox theme={'material-purple'} ref={this.acceptCheckBox} onChange={this.acceptCheckBoxChange} width={250}> I accept the terms and conditions </JqxCheckBox> </div> <div id={"sectionButtonsWrapper"}> <JqxButton theme={'material-purple'} className={"nextButton"} width={50}>Next</JqxButton> </div> </div> <div className={"section"}> <JqxListBox theme={'material-purple'} ref={this.products} onChange={this.productsChange} onUnselect={this.productsUnselect} source={this.getSource()} width={490} height={130} multiple={true} /> <div id={"hintWrapper2"}> <div id={"hintBasket"} className={"hint"} /> </div> <div id={"basketButtonsWrapper"}> <JqxButton theme={'material-purple'} className={"backButton"} width={50}>Back</JqxButton> <JqxButton theme={'material-purple'} className={"nextButton"} width={50}>Next</JqxButton> </div> </div> <div className={"section"}> <div id={"selectedProductsHeader"}> <h4>Selected products</h4> <div ref={this.orderContainer} /> </div> <div id={"selectedProductsButtonsWrapper"}> <JqxButton theme={'material-purple'} className={"backButton"} width={50}>Back</JqxButton> </div> </div> </JqxTabs> ); } private addHandlers = () => { this.usernameInput.current!.addEventListener('keyup', () => { this.validate(true); }); this.usernameInput.current!.addEventListener('change', () => { this.validate(true); }); this.passwordInput.current!.addEventListener('keyup', () => { this.validate(true); }); const nextButtonClass = document.querySelectorAll('.nextButton'); nextButtonClass.forEach(nextButton => { nextButton.addEventListener('click', (e) => { this.validate(true); const selectedTab = this.myTabs.current!.getOptions('selectedItem'); this.myTabs.current!.select(selectedTab + 1); }); }); const backButtonClass = document.querySelectorAll('.backButton'); backButtonClass.forEach(backButton => { backButton.addEventListener('click', () => { this.validate(true); const selectedTab = this.myTabs.current!.getOptions('selectedItem'); this.myTabs.current!.select(selectedTab - 1); }); }); }; // Checking if any product have been selected private isItemSelected = (array: any) => { let count = array.length; if (count === 0) { return false; } while (count) { count -= 1; if (array[count] !== -1 && typeof array[count] !== 'undefined') { return true; } } return false; }; // Validating all wizard tabs private validate = (notify: boolean) => { if (!this.firstTab(notify)) { this.myTabs.current!.disableAt(1); this.myTabs.current!.disableAt(2); return; } else { this.myTabs.current!.enableAt(1); } if (!this.secondTab(notify)) { this.myTabs.current!.disableAt(2); return; } else { this.myTabs.current!.enableAt(2); } }; // Displaying message to the user private showHint = (message: string, selector: string) => { if (typeof selector === 'undefined') { selector = '.hint'; } if (message === '') { message = 'You can continue.'; } // Check is a class or not if (selector.indexOf('.') === 0) { document.getElementsByClassName(selector.slice(1))[0].innerHTML = '<strong>' + message + '</strong>'; } else { document.getElementById(selector.slice(1))!.innerHTML = '<strong>' + message + '</strong>'; } } // Validating the first tab private firstTab = (notify: boolean) => { const username = this.usernameInput.current!.value; const password = this.passwordInput.current!.value; let message = ''; if (username.length < 3) { message += 'You have to enter valid username. <br />'; } if (password.length < 3) { message += 'You have to enter valid password. <br />'; } if (!this.acceptCheckBox.current!.getOptions("checked")) { message += 'You have to accept the terms. <br />'; } if (message !== '') { if (notify) { this.showHint(message, '#hintSection'); } return false; } this.showHint('You can continue.', '#hintSection'); return true; }; // Validating the second tab private secondTab = (notify?: boolean) => { const products = this.products.current!.getOptions("selectedIndexes"); if (!this.isItemSelected(products)) { this.showHint('You have to select at least one item.', '#hintBasket'); return false; } else { this.showHint('You can continue.', '#hintBasket'); } return true; }; // Event handling private acceptCheckBoxChange(event: any): void { this.validate(true); } private productsChange(event: any): void { this.validate(true); const selectedItems = this.products.current!.getOptions('selectedIndexes') let count = selectedItems.length; const parent = this.orderContainer.current!; while (parent.firstChild) { parent.removeChild(parent.firstChild); } while (count) { count--; if (typeof selectedItems[count] !== 'undefined' && selectedItems[count] !== -1) { const currentHtmlContent = parent.innerHTML; parent.innerHTML = currentHtmlContent + '<div style="width: 190px; height: 20px;">' + (this.getSource()[selectedItems[count]].html) + '</div>'; } } } private productsUnselect(event: any): void { this.validate(true); } private getSource = (): any[] => { return [ { html: "<div style='height: 20px; float: left;'><img style='float: left; margin-top: 2px; margin-right: 5px;' src='https://www.jqwidgets.com/react/images/numberinput.png'/><span style='float: left; font-size: 13px; font-family: Verdana Arial;'>jqxNumberInput</span></div>", title: 'jqxNumberInput' }, { html: "<div style='height: 20px; float: left;'><img style='float: left; margin-top: 2px; margin-right: 5px;' src='https://www.jqwidgets.com/react/images/progressbar.png'/><span style='float: left; font-size: 13px; font-family: Verdana Arial;'>jqxProgressBar</span></div>", title: 'jqxProgressBar' }, { html: "<div style='height: 20px; float: left;'><img style='float: left; margin-top: 2px; margin-right: 5px;' src='https://www.jqwidgets.com/react/images/calendar.png'/><span style='float: left; font-size: 13px; font-family: Verdana Arial;'>jqxCalendar</span></div>", title: 'jqxCalendar' }, { html: "<div style='height: 20px; float: left;'><img style='float: left; margin-top: 2px; margin-right: 5px;' src='https://www.jqwidgets.com/react/images/button.png'/><span style='float: left; font-size: 13px; font-family: Verdana Arial;'>jqxButton</span></div>", title: 'jqxButton' }, { html: "<div style='height: 20px; float: left;'><img style='float: left; margin-top: 2px; margin-right: 5px;' src='https://www.jqwidgets.com/react/images/dropdownlist.png'/><span style='float: left; font-size: 13px; font-family: Verdana Arial;'>jqxDropDownList</span></div>", title: 'jqxDropDownList' }, { html: "<div style='height: 20px; float: left;'><img style='float: left; margin-top: 2px; margin-right: 5px;' src='https://www.jqwidgets.com/react/images/listbox.png'/><span style='float: left; font-size: 13px; font-family: Verdana Arial;'>jqxListBox</span></div>", title: 'jqxListBox' }, { html: "<div style='height: 20px; float: left;'><img style='float: left; margin-top: 2px; margin-right: 5px;' src='https://www.jqwidgets.com/react/images/tooltip.png'/><span style='float: left; font-size: 13px; font-family: Verdana Arial;'>jqxTooltip</span></div>", title: 'jqxTooltip' } ]; } } export default App;
the_stack
import { LocalResolver } from '../../compiler_util/expression_converter'; import { ConstantPool } from '../../constant_pool'; import * as core from '../../core'; import { AST, AstMemoryEfficientTransformer, BindingPipe, LiteralArray, LiteralMap } from '../../expression_parser/ast'; import * as i18n from '../../i18n/i18n_ast'; import { InterpolationConfig } from '../../ml_parser/interpolation_config'; import { LexerRange } from '../../ml_parser/lexer'; import * as o from '../../output/output_ast'; import { ParseError, ParseSourceSpan } from '../../parse_util'; import { SelectorMatcher } from '../../selector'; import { BindingParser } from '../../template_parser/binding_parser'; import * as t from '../r3_ast'; import { I18nContext } from './i18n/context'; import { invalid } from './util'; export declare function renderFlagCheckIfStmt(flags: core.RenderFlags, statements: o.Statement[]): o.IfStmt; export declare function prepareEventListenerParameters(eventAst: t.BoundEvent, handlerName?: string | null, scope?: BindingScope | null): o.Expression[]; export declare class TemplateDefinitionBuilder implements t.Visitor<void>, LocalResolver { private constantPool; private level; private contextName; private i18nContext; private templateIndex; private templateName; private directiveMatcher; private directives; private pipeTypeByName; private pipes; private _namespace; private relativeContextFilePath; private i18nUseExternalIds; private _dataIndex; private _bindingContext; private _prefixCode; /** * List of callbacks to generate creation mode instructions. We store them here as we process * the template so bindings in listeners are resolved only once all nodes have been visited. * This ensures all local refs and context variables are available for matching. */ private _creationCodeFns; /** * List of callbacks to generate update mode instructions. We store them here as we process * the template so bindings are resolved only once all nodes have been visited. This ensures * all local refs and context variables are available for matching. */ private _updateCodeFns; /** * Memorizes the last node index for which a select instruction has been generated. * We're initializing this to -1 to ensure the `select(0)` instruction is generated before any * relevant update instructions. */ private _lastNodeIndexWithFlush; /** Temporary variable declarations generated from visiting pipes, literals, etc. */ private _tempVariables; /** * List of callbacks to build nested templates. Nested templates must not be visited until * after the parent template has finished visiting all of its nodes. This ensures that all * local ref bindings in nested templates are able to find local ref values if the refs * are defined after the template declaration. */ private _nestedTemplateFns; /** * This scope contains local variables declared in the update mode block of the template. * (e.g. refs and context vars in bindings) */ private _bindingScope; private _valueConverter; private _unsupported; private i18n; private _pureFunctionSlots; private _bindingSlots; private fileBasedI18nSuffix; private _ngContentReservedSlots; private _ngContentSelectorsOffset; private _implicitReceiverExpr; constructor(constantPool: ConstantPool, parentBindingScope: BindingScope, level: number, contextName: string | null, i18nContext: I18nContext | null, templateIndex: number | null, templateName: string | null, directiveMatcher: SelectorMatcher | null, directives: Set<o.Expression>, pipeTypeByName: Map<string, o.Expression>, pipes: Set<o.Expression>, _namespace: o.ExternalReference, relativeContextFilePath: string, i18nUseExternalIds: boolean); registerContextVariables(variable: t.Variable): void; buildTemplateFunction(nodes: t.Node[], variables: t.Variable[], ngContentSelectorsOffset?: number, i18n?: i18n.AST): o.FunctionExpr; getLocal(name: string): o.Expression | null; notifyImplicitReceiverUse(): void; i18nTranslate(message: i18n.Message, params?: { [name: string]: o.Expression; }, ref?: o.ReadVarExpr, transformFn?: (raw: o.ReadVarExpr) => o.Expression): o.ReadVarExpr; i18nFormatPlaceholderNames(params: { [name: string]: o.Expression; } | undefined, useCamelCase: boolean): { [key: string]: o.Expression; }; i18nAppendBindings(expressions: AST[]): void; i18nBindProps(props: { [key: string]: t.Text | t.BoundText; }): { [key: string]: o.Expression; }; i18nGenerateClosureVar(messageId: string): o.ReadVarExpr; i18nUpdateRef(context: I18nContext): void; i18nStart(span: ParseSourceSpan | null | undefined, meta: i18n.AST, selfClosing?: boolean): void; i18nEnd(span?: ParseSourceSpan | null, selfClosing?: boolean): void; visitContent(ngContent: t.Content): void; getNamespaceInstruction(namespaceKey: string | null): o.ExternalReference; addNamespaceInstruction(nsInstruction: o.ExternalReference, element: t.Element): void; visitElement(element: t.Element): void; /** * Adds an update instruction for an interpolated property or attribute, such as * `prop="{{value}}"` or `attr.title="{{value}}"` */ interpolatedUpdateInstruction(instruction: o.ExternalReference, elementIndex: number, attrName: string, input: t.BoundAttribute, value: any, params: any[]): void; visitTemplate(template: t.Template): void; readonly visitReference: typeof invalid; readonly visitVariable: typeof invalid; readonly visitTextAttribute: typeof invalid; readonly visitBoundAttribute: typeof invalid; readonly visitBoundEvent: typeof invalid; visitBoundText(text: t.BoundText): void; visitText(text: t.Text): void; visitIcu(icu: t.Icu): null; private allocateDataSlot; getConstCount(): number; getVarCount(): number; getNgContentSelectors(): o.Expression | null; private bindingContext; private templatePropertyBindings; private instructionFn; private processStylingInstruction; private creationInstruction; private updateInstruction; private updateInstructionChain; private addSelectInstructionIfNecessary; private allocatePureFunctionSlots; private allocateBindingSlots; /** * Gets an expression that refers to the implicit receiver. The implicit * receiver is always the root level context. */ private getImplicitReceiverExpr; private convertExpressionBinding; private convertPropertyBinding; /** * Gets a list of argument expressions to pass to an update instruction expression. Also updates * the temp variables state with temp variables that were identified as needing to be created * while visiting the arguments. * @param value The original expression we will be resolving an arguments list from. */ private getUpdateInstructionArguments; private matchDirectives; /** * Prepares all attribute expression values for the `TAttributes` array. * * The purpose of this function is to properly construct an attributes array that * is passed into the `elementStart` (or just `element`) functions. Because there * are many different types of attributes, the array needs to be constructed in a * special way so that `elementStart` can properly evaluate them. * * The format looks like this: * * ``` * attrs = [prop, value, prop2, value2, * CLASSES, class1, class2, * STYLES, style1, value1, style2, value2, * BINDINGS, name1, name2, name3, * TEMPLATE, name4, name5, name6, * I18N, name7, name8, ...] * ``` * * Note that this function will fully ignore all synthetic (@foo) attribute values * because those values are intended to always be generated as property instructions. */ private prepareNonRenderAttrs; private toAttrsParam; private prepareRefsParameter; private prepareListenerParameter; } export declare class ValueConverter extends AstMemoryEfficientTransformer { private constantPool; private allocateSlot; private allocatePureFunctionSlots; private definePipe; private _pipeBindExprs; constructor(constantPool: ConstantPool, allocateSlot: () => number, allocatePureFunctionSlots: (numSlots: number) => number, definePipe: (name: string, localName: string, slot: number, value: o.Expression) => void); visitPipe(pipe: BindingPipe, context: any): AST; updatePipeSlotOffsets(bindingSlots: number): void; visitLiteralArray(array: LiteralArray, context: any): AST; visitLiteralMap(map: LiteralMap, context: any): AST; } /** * Function which is executed whenever a variable is referenced for the first time in a given * scope. * * It is expected that the function creates the `const localName = expression`; statement. */ export declare type DeclareLocalVarCallback = (scope: BindingScope, relativeLevel: number) => o.Statement[]; /** * This is used when one refers to variable such as: 'let abc = nextContext(2).$implicit`. * - key to the map is the string literal `"abc"`. * - value `retrievalLevel` is the level from which this value can be retrieved, which is 2 levels * up in example. * - value `lhs` is the left hand side which is an AST representing `abc`. * - value `declareLocalCallback` is a callback that is invoked when declaring the local. * - value `declare` is true if this value needs to be declared. * - value `localRef` is true if we are storing a local reference * - value `priority` dictates the sorting priority of this var declaration compared * to other var declarations on the same retrieval level. For example, if there is a * context variable and a local ref accessing the same parent view, the context var * declaration should always come before the local ref declaration. */ declare type BindingData = { retrievalLevel: number; lhs: o.Expression; declareLocalCallback?: DeclareLocalVarCallback; declare: boolean; priority: number; localRef: boolean; }; export declare class BindingScope implements LocalResolver { bindingLevel: number; private parent; /** Keeps a map from local variables to their BindingData. */ private map; private referenceNameIndex; private restoreViewVariable; private static _ROOT_SCOPE; static readonly ROOT_SCOPE: BindingScope; private constructor(); get(name: string): o.Expression | null; /** * Create a local variable for later reference. * * @param retrievalLevel The level from which this value can be retrieved * @param name Name of the variable. * @param lhs AST representing the left hand side of the `let lhs = rhs;`. * @param priority The sorting priority of this var * @param declareLocalCallback The callback to invoke when declaring this local var * @param localRef Whether or not this is a local ref */ set(retrievalLevel: number, name: string, lhs: o.Expression, priority?: number, declareLocalCallback?: DeclareLocalVarCallback, localRef?: true): BindingScope; getLocal(name: string): (o.Expression | null); notifyImplicitReceiverUse(): void; nestedScope(level: number): BindingScope; /** * Gets or creates a shared context variable and returns its expression. Note that * this does not mean that the shared variable will be declared. Variables in the * binding scope will be only declared if they are used. */ getOrCreateSharedContextVar(retrievalLevel: number): o.ReadVarExpr; getSharedContextName(retrievalLevel: number): o.ReadVarExpr | null; maybeGenerateSharedContextVar(value: BindingData): void; generateSharedContextVar(retrievalLevel: number): void; getComponentProperty(name: string): o.Expression; maybeRestoreView(retrievalLevel: number, localRefLookup: boolean): void; restoreViewStatement(): o.Statement[]; viewSnapshotStatements(): o.Statement[]; isListenerScope(): boolean | null; variableDeclarations(): o.Statement[]; freshReferenceName(): string; } /** * Options that can be used to modify how a template is parsed by `parseTemplate()`. */ export interface ParseTemplateOptions { /** * Include whitespace nodes in the parsed output. */ preserveWhitespaces?: boolean; /** * How to parse interpolation markers. */ interpolationConfig?: InterpolationConfig; /** * The start and end point of the text to parse within the `source` string. * The entire `source` string is parsed if this is not provided. * */ range?: LexerRange; /** * If this text is stored in a JavaScript string, then we have to deal with escape sequences. * * **Example 1:** * * ``` * "abc\"def\nghi" * ``` * * - The `\"` must be converted to `"`. * - The `\n` must be converted to a new line character in a token, * but it should not increment the current line for source mapping. * * **Example 2:** * * ``` * "abc\ * def" * ``` * * The line continuation (`\` followed by a newline) should be removed from a token * but the new line should increment the current line for source mapping. */ escapedString?: boolean; /** * An array of characters that should be considered as leading trivia. * Leading trivia are characters that are not important to the developer, and so should not be * included in source-map segments. A common example is whitespace. */ leadingTriviaChars?: string[]; } /** * Parse a template into render3 `Node`s and additional metadata, with no other dependencies. * * @param template text of the template to parse * @param templateUrl URL to use for source mapping of the parsed template * @param options options to modify how the template is parsed */ export declare function parseTemplate(template: string, templateUrl: string, options?: ParseTemplateOptions): { errors?: ParseError[]; nodes: t.Node[]; styleUrls: string[]; styles: string[]; }; /** * Construct a `BindingParser` with a default configuration. */ export declare function makeBindingParser(interpolationConfig?: InterpolationConfig): BindingParser; export declare function resolveSanitizationFn(context: core.SecurityContext, isAttribute?: boolean): o.ExternalExpr | null; export {};
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { AddSourceIdentifierToSubscriptionCommand, AddSourceIdentifierToSubscriptionCommandInput, AddSourceIdentifierToSubscriptionCommandOutput, } from "./commands/AddSourceIdentifierToSubscriptionCommand"; import { AddTagsToResourceCommand, AddTagsToResourceCommandInput, AddTagsToResourceCommandOutput, } from "./commands/AddTagsToResourceCommand"; import { ApplyPendingMaintenanceActionCommand, ApplyPendingMaintenanceActionCommandInput, ApplyPendingMaintenanceActionCommandOutput, } from "./commands/ApplyPendingMaintenanceActionCommand"; import { CopyDBClusterParameterGroupCommand, CopyDBClusterParameterGroupCommandInput, CopyDBClusterParameterGroupCommandOutput, } from "./commands/CopyDBClusterParameterGroupCommand"; import { CopyDBClusterSnapshotCommand, CopyDBClusterSnapshotCommandInput, CopyDBClusterSnapshotCommandOutput, } from "./commands/CopyDBClusterSnapshotCommand"; import { CreateDBClusterCommand, CreateDBClusterCommandInput, CreateDBClusterCommandOutput, } from "./commands/CreateDBClusterCommand"; import { CreateDBClusterParameterGroupCommand, CreateDBClusterParameterGroupCommandInput, CreateDBClusterParameterGroupCommandOutput, } from "./commands/CreateDBClusterParameterGroupCommand"; import { CreateDBClusterSnapshotCommand, CreateDBClusterSnapshotCommandInput, CreateDBClusterSnapshotCommandOutput, } from "./commands/CreateDBClusterSnapshotCommand"; import { CreateDBInstanceCommand, CreateDBInstanceCommandInput, CreateDBInstanceCommandOutput, } from "./commands/CreateDBInstanceCommand"; import { CreateDBSubnetGroupCommand, CreateDBSubnetGroupCommandInput, CreateDBSubnetGroupCommandOutput, } from "./commands/CreateDBSubnetGroupCommand"; import { CreateEventSubscriptionCommand, CreateEventSubscriptionCommandInput, CreateEventSubscriptionCommandOutput, } from "./commands/CreateEventSubscriptionCommand"; import { CreateGlobalClusterCommand, CreateGlobalClusterCommandInput, CreateGlobalClusterCommandOutput, } from "./commands/CreateGlobalClusterCommand"; import { DeleteDBClusterCommand, DeleteDBClusterCommandInput, DeleteDBClusterCommandOutput, } from "./commands/DeleteDBClusterCommand"; import { DeleteDBClusterParameterGroupCommand, DeleteDBClusterParameterGroupCommandInput, DeleteDBClusterParameterGroupCommandOutput, } from "./commands/DeleteDBClusterParameterGroupCommand"; import { DeleteDBClusterSnapshotCommand, DeleteDBClusterSnapshotCommandInput, DeleteDBClusterSnapshotCommandOutput, } from "./commands/DeleteDBClusterSnapshotCommand"; import { DeleteDBInstanceCommand, DeleteDBInstanceCommandInput, DeleteDBInstanceCommandOutput, } from "./commands/DeleteDBInstanceCommand"; import { DeleteDBSubnetGroupCommand, DeleteDBSubnetGroupCommandInput, DeleteDBSubnetGroupCommandOutput, } from "./commands/DeleteDBSubnetGroupCommand"; import { DeleteEventSubscriptionCommand, DeleteEventSubscriptionCommandInput, DeleteEventSubscriptionCommandOutput, } from "./commands/DeleteEventSubscriptionCommand"; import { DeleteGlobalClusterCommand, DeleteGlobalClusterCommandInput, DeleteGlobalClusterCommandOutput, } from "./commands/DeleteGlobalClusterCommand"; import { DescribeCertificatesCommand, DescribeCertificatesCommandInput, DescribeCertificatesCommandOutput, } from "./commands/DescribeCertificatesCommand"; import { DescribeDBClusterParameterGroupsCommand, DescribeDBClusterParameterGroupsCommandInput, DescribeDBClusterParameterGroupsCommandOutput, } from "./commands/DescribeDBClusterParameterGroupsCommand"; import { DescribeDBClusterParametersCommand, DescribeDBClusterParametersCommandInput, DescribeDBClusterParametersCommandOutput, } from "./commands/DescribeDBClusterParametersCommand"; import { DescribeDBClustersCommand, DescribeDBClustersCommandInput, DescribeDBClustersCommandOutput, } from "./commands/DescribeDBClustersCommand"; import { DescribeDBClusterSnapshotAttributesCommand, DescribeDBClusterSnapshotAttributesCommandInput, DescribeDBClusterSnapshotAttributesCommandOutput, } from "./commands/DescribeDBClusterSnapshotAttributesCommand"; import { DescribeDBClusterSnapshotsCommand, DescribeDBClusterSnapshotsCommandInput, DescribeDBClusterSnapshotsCommandOutput, } from "./commands/DescribeDBClusterSnapshotsCommand"; import { DescribeDBEngineVersionsCommand, DescribeDBEngineVersionsCommandInput, DescribeDBEngineVersionsCommandOutput, } from "./commands/DescribeDBEngineVersionsCommand"; import { DescribeDBInstancesCommand, DescribeDBInstancesCommandInput, DescribeDBInstancesCommandOutput, } from "./commands/DescribeDBInstancesCommand"; import { DescribeDBSubnetGroupsCommand, DescribeDBSubnetGroupsCommandInput, DescribeDBSubnetGroupsCommandOutput, } from "./commands/DescribeDBSubnetGroupsCommand"; import { DescribeEngineDefaultClusterParametersCommand, DescribeEngineDefaultClusterParametersCommandInput, DescribeEngineDefaultClusterParametersCommandOutput, } from "./commands/DescribeEngineDefaultClusterParametersCommand"; import { DescribeEventCategoriesCommand, DescribeEventCategoriesCommandInput, DescribeEventCategoriesCommandOutput, } from "./commands/DescribeEventCategoriesCommand"; import { DescribeEventsCommand, DescribeEventsCommandInput, DescribeEventsCommandOutput, } from "./commands/DescribeEventsCommand"; import { DescribeEventSubscriptionsCommand, DescribeEventSubscriptionsCommandInput, DescribeEventSubscriptionsCommandOutput, } from "./commands/DescribeEventSubscriptionsCommand"; import { DescribeGlobalClustersCommand, DescribeGlobalClustersCommandInput, DescribeGlobalClustersCommandOutput, } from "./commands/DescribeGlobalClustersCommand"; import { DescribeOrderableDBInstanceOptionsCommand, DescribeOrderableDBInstanceOptionsCommandInput, DescribeOrderableDBInstanceOptionsCommandOutput, } from "./commands/DescribeOrderableDBInstanceOptionsCommand"; import { DescribePendingMaintenanceActionsCommand, DescribePendingMaintenanceActionsCommandInput, DescribePendingMaintenanceActionsCommandOutput, } from "./commands/DescribePendingMaintenanceActionsCommand"; import { FailoverDBClusterCommand, FailoverDBClusterCommandInput, FailoverDBClusterCommandOutput, } from "./commands/FailoverDBClusterCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { ModifyDBClusterCommand, ModifyDBClusterCommandInput, ModifyDBClusterCommandOutput, } from "./commands/ModifyDBClusterCommand"; import { ModifyDBClusterParameterGroupCommand, ModifyDBClusterParameterGroupCommandInput, ModifyDBClusterParameterGroupCommandOutput, } from "./commands/ModifyDBClusterParameterGroupCommand"; import { ModifyDBClusterSnapshotAttributeCommand, ModifyDBClusterSnapshotAttributeCommandInput, ModifyDBClusterSnapshotAttributeCommandOutput, } from "./commands/ModifyDBClusterSnapshotAttributeCommand"; import { ModifyDBInstanceCommand, ModifyDBInstanceCommandInput, ModifyDBInstanceCommandOutput, } from "./commands/ModifyDBInstanceCommand"; import { ModifyDBSubnetGroupCommand, ModifyDBSubnetGroupCommandInput, ModifyDBSubnetGroupCommandOutput, } from "./commands/ModifyDBSubnetGroupCommand"; import { ModifyEventSubscriptionCommand, ModifyEventSubscriptionCommandInput, ModifyEventSubscriptionCommandOutput, } from "./commands/ModifyEventSubscriptionCommand"; import { ModifyGlobalClusterCommand, ModifyGlobalClusterCommandInput, ModifyGlobalClusterCommandOutput, } from "./commands/ModifyGlobalClusterCommand"; import { RebootDBInstanceCommand, RebootDBInstanceCommandInput, RebootDBInstanceCommandOutput, } from "./commands/RebootDBInstanceCommand"; import { RemoveFromGlobalClusterCommand, RemoveFromGlobalClusterCommandInput, RemoveFromGlobalClusterCommandOutput, } from "./commands/RemoveFromGlobalClusterCommand"; import { RemoveSourceIdentifierFromSubscriptionCommand, RemoveSourceIdentifierFromSubscriptionCommandInput, RemoveSourceIdentifierFromSubscriptionCommandOutput, } from "./commands/RemoveSourceIdentifierFromSubscriptionCommand"; import { RemoveTagsFromResourceCommand, RemoveTagsFromResourceCommandInput, RemoveTagsFromResourceCommandOutput, } from "./commands/RemoveTagsFromResourceCommand"; import { ResetDBClusterParameterGroupCommand, ResetDBClusterParameterGroupCommandInput, ResetDBClusterParameterGroupCommandOutput, } from "./commands/ResetDBClusterParameterGroupCommand"; import { RestoreDBClusterFromSnapshotCommand, RestoreDBClusterFromSnapshotCommandInput, RestoreDBClusterFromSnapshotCommandOutput, } from "./commands/RestoreDBClusterFromSnapshotCommand"; import { RestoreDBClusterToPointInTimeCommand, RestoreDBClusterToPointInTimeCommandInput, RestoreDBClusterToPointInTimeCommandOutput, } from "./commands/RestoreDBClusterToPointInTimeCommand"; import { StartDBClusterCommand, StartDBClusterCommandInput, StartDBClusterCommandOutput, } from "./commands/StartDBClusterCommand"; import { StopDBClusterCommand, StopDBClusterCommandInput, StopDBClusterCommandOutput, } from "./commands/StopDBClusterCommand"; import { DocDBClient } from "./DocDBClient"; /** * <p>Amazon DocumentDB API documentation</p> */ export class DocDB extends DocDBClient { /** * <p>Adds a source identifier to an existing event notification * subscription.</p> */ public addSourceIdentifierToSubscription( args: AddSourceIdentifierToSubscriptionCommandInput, options?: __HttpHandlerOptions ): Promise<AddSourceIdentifierToSubscriptionCommandOutput>; public addSourceIdentifierToSubscription( args: AddSourceIdentifierToSubscriptionCommandInput, cb: (err: any, data?: AddSourceIdentifierToSubscriptionCommandOutput) => void ): void; public addSourceIdentifierToSubscription( args: AddSourceIdentifierToSubscriptionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AddSourceIdentifierToSubscriptionCommandOutput) => void ): void; public addSourceIdentifierToSubscription( args: AddSourceIdentifierToSubscriptionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AddSourceIdentifierToSubscriptionCommandOutput) => void), cb?: (err: any, data?: AddSourceIdentifierToSubscriptionCommandOutput) => void ): Promise<AddSourceIdentifierToSubscriptionCommandOutput> | void { const command = new AddSourceIdentifierToSubscriptionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Adds metadata tags to an Amazon DocumentDB resource. You can use these tags * with cost allocation reporting to track costs that are associated * with Amazon DocumentDB resources or in a <code>Condition</code> statement in * an Identity and Access Management (IAM) policy for Amazon DocumentDB.</p> */ public addTagsToResource( args: AddTagsToResourceCommandInput, options?: __HttpHandlerOptions ): Promise<AddTagsToResourceCommandOutput>; public addTagsToResource( args: AddTagsToResourceCommandInput, cb: (err: any, data?: AddTagsToResourceCommandOutput) => void ): void; public addTagsToResource( args: AddTagsToResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AddTagsToResourceCommandOutput) => void ): void; public addTagsToResource( args: AddTagsToResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AddTagsToResourceCommandOutput) => void), cb?: (err: any, data?: AddTagsToResourceCommandOutput) => void ): Promise<AddTagsToResourceCommandOutput> | void { const command = new AddTagsToResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Applies a pending maintenance action to a resource (for example, * to an Amazon DocumentDB instance).</p> */ public applyPendingMaintenanceAction( args: ApplyPendingMaintenanceActionCommandInput, options?: __HttpHandlerOptions ): Promise<ApplyPendingMaintenanceActionCommandOutput>; public applyPendingMaintenanceAction( args: ApplyPendingMaintenanceActionCommandInput, cb: (err: any, data?: ApplyPendingMaintenanceActionCommandOutput) => void ): void; public applyPendingMaintenanceAction( args: ApplyPendingMaintenanceActionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ApplyPendingMaintenanceActionCommandOutput) => void ): void; public applyPendingMaintenanceAction( args: ApplyPendingMaintenanceActionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ApplyPendingMaintenanceActionCommandOutput) => void), cb?: (err: any, data?: ApplyPendingMaintenanceActionCommandOutput) => void ): Promise<ApplyPendingMaintenanceActionCommandOutput> | void { const command = new ApplyPendingMaintenanceActionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Copies the specified cluster parameter group.</p> */ public copyDBClusterParameterGroup( args: CopyDBClusterParameterGroupCommandInput, options?: __HttpHandlerOptions ): Promise<CopyDBClusterParameterGroupCommandOutput>; public copyDBClusterParameterGroup( args: CopyDBClusterParameterGroupCommandInput, cb: (err: any, data?: CopyDBClusterParameterGroupCommandOutput) => void ): void; public copyDBClusterParameterGroup( args: CopyDBClusterParameterGroupCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CopyDBClusterParameterGroupCommandOutput) => void ): void; public copyDBClusterParameterGroup( args: CopyDBClusterParameterGroupCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CopyDBClusterParameterGroupCommandOutput) => void), cb?: (err: any, data?: CopyDBClusterParameterGroupCommandOutput) => void ): Promise<CopyDBClusterParameterGroupCommandOutput> | void { const command = new CopyDBClusterParameterGroupCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Copies a snapshot of a cluster.</p> * * <p>To copy a cluster snapshot from a shared manual cluster snapshot, * <code>SourceDBClusterSnapshotIdentifier</code> must be the Amazon * Resource Name (ARN) of the shared cluster snapshot. You can only * copy a shared DB cluster snapshot, whether encrypted or not, in the * same Region.</p> * * <p>To cancel the copy operation after it is in progress, delete the * target cluster snapshot identified by * <code>TargetDBClusterSnapshotIdentifier</code> while that cluster * snapshot is in the <i>copying</i> status.</p> */ public copyDBClusterSnapshot( args: CopyDBClusterSnapshotCommandInput, options?: __HttpHandlerOptions ): Promise<CopyDBClusterSnapshotCommandOutput>; public copyDBClusterSnapshot( args: CopyDBClusterSnapshotCommandInput, cb: (err: any, data?: CopyDBClusterSnapshotCommandOutput) => void ): void; public copyDBClusterSnapshot( args: CopyDBClusterSnapshotCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CopyDBClusterSnapshotCommandOutput) => void ): void; public copyDBClusterSnapshot( args: CopyDBClusterSnapshotCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CopyDBClusterSnapshotCommandOutput) => void), cb?: (err: any, data?: CopyDBClusterSnapshotCommandOutput) => void ): Promise<CopyDBClusterSnapshotCommandOutput> | void { const command = new CopyDBClusterSnapshotCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new Amazon DocumentDB cluster.</p> */ public createDBCluster( args: CreateDBClusterCommandInput, options?: __HttpHandlerOptions ): Promise<CreateDBClusterCommandOutput>; public createDBCluster( args: CreateDBClusterCommandInput, cb: (err: any, data?: CreateDBClusterCommandOutput) => void ): void; public createDBCluster( args: CreateDBClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateDBClusterCommandOutput) => void ): void; public createDBCluster( args: CreateDBClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateDBClusterCommandOutput) => void), cb?: (err: any, data?: CreateDBClusterCommandOutput) => void ): Promise<CreateDBClusterCommandOutput> | void { const command = new CreateDBClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new cluster parameter group.</p> * <p>Parameters in a cluster parameter group apply to all of the * instances in a cluster.</p> * <p>A cluster parameter group is initially created with the default * parameters for the database engine used by instances in the cluster. * In Amazon DocumentDB, you cannot make modifications directly to the * <code>default.docdb3.6</code> cluster parameter group. If your * Amazon DocumentDB cluster is using the default cluster parameter group and you * want to modify a value in it, you must first <a href="https://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_group-create.html"> * create a new parameter group</a> * or <a href="https://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_group-copy.html"> * copy an existing parameter group</a>, * modify it, and then apply the modified parameter group to your * cluster. For the new cluster parameter group and associated settings * to take effect, you must then reboot the instances in the cluster * without failover. For more information, * see <a href="https://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_group-modify.html"> * Modifying Amazon DocumentDB Cluster Parameter Groups</a>. * </p> */ public createDBClusterParameterGroup( args: CreateDBClusterParameterGroupCommandInput, options?: __HttpHandlerOptions ): Promise<CreateDBClusterParameterGroupCommandOutput>; public createDBClusterParameterGroup( args: CreateDBClusterParameterGroupCommandInput, cb: (err: any, data?: CreateDBClusterParameterGroupCommandOutput) => void ): void; public createDBClusterParameterGroup( args: CreateDBClusterParameterGroupCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateDBClusterParameterGroupCommandOutput) => void ): void; public createDBClusterParameterGroup( args: CreateDBClusterParameterGroupCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateDBClusterParameterGroupCommandOutput) => void), cb?: (err: any, data?: CreateDBClusterParameterGroupCommandOutput) => void ): Promise<CreateDBClusterParameterGroupCommandOutput> | void { const command = new CreateDBClusterParameterGroupCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a snapshot of a cluster. </p> */ public createDBClusterSnapshot( args: CreateDBClusterSnapshotCommandInput, options?: __HttpHandlerOptions ): Promise<CreateDBClusterSnapshotCommandOutput>; public createDBClusterSnapshot( args: CreateDBClusterSnapshotCommandInput, cb: (err: any, data?: CreateDBClusterSnapshotCommandOutput) => void ): void; public createDBClusterSnapshot( args: CreateDBClusterSnapshotCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateDBClusterSnapshotCommandOutput) => void ): void; public createDBClusterSnapshot( args: CreateDBClusterSnapshotCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateDBClusterSnapshotCommandOutput) => void), cb?: (err: any, data?: CreateDBClusterSnapshotCommandOutput) => void ): Promise<CreateDBClusterSnapshotCommandOutput> | void { const command = new CreateDBClusterSnapshotCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new instance.</p> */ public createDBInstance( args: CreateDBInstanceCommandInput, options?: __HttpHandlerOptions ): Promise<CreateDBInstanceCommandOutput>; public createDBInstance( args: CreateDBInstanceCommandInput, cb: (err: any, data?: CreateDBInstanceCommandOutput) => void ): void; public createDBInstance( args: CreateDBInstanceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateDBInstanceCommandOutput) => void ): void; public createDBInstance( args: CreateDBInstanceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateDBInstanceCommandOutput) => void), cb?: (err: any, data?: CreateDBInstanceCommandOutput) => void ): Promise<CreateDBInstanceCommandOutput> | void { const command = new CreateDBInstanceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new subnet group. subnet groups must contain at least one subnet in at * least two Availability Zones in the Region.</p> */ public createDBSubnetGroup( args: CreateDBSubnetGroupCommandInput, options?: __HttpHandlerOptions ): Promise<CreateDBSubnetGroupCommandOutput>; public createDBSubnetGroup( args: CreateDBSubnetGroupCommandInput, cb: (err: any, data?: CreateDBSubnetGroupCommandOutput) => void ): void; public createDBSubnetGroup( args: CreateDBSubnetGroupCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateDBSubnetGroupCommandOutput) => void ): void; public createDBSubnetGroup( args: CreateDBSubnetGroupCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateDBSubnetGroupCommandOutput) => void), cb?: (err: any, data?: CreateDBSubnetGroupCommandOutput) => void ): Promise<CreateDBSubnetGroupCommandOutput> | void { const command = new CreateDBSubnetGroupCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates an Amazon DocumentDB event notification subscription. This action requires a topic Amazon Resource Name (ARN) created by using the Amazon DocumentDB console, the Amazon SNS console, or the Amazon SNS API. To obtain an ARN with Amazon SNS, you must create a topic in Amazon SNS and subscribe to the topic. The ARN is displayed in the Amazon SNS console.</p> * <p>You can specify the type of source (<code>SourceType</code>) that you want to be notified of. You can also provide a list of Amazon DocumentDB sources (<code>SourceIds</code>) that trigger the events, and you can provide a list of event categories (<code>EventCategories</code>) for events that you want to be notified of. For example, you can specify <code>SourceType = db-instance</code>, <code>SourceIds = mydbinstance1, mydbinstance2</code> and <code>EventCategories = Availability, Backup</code>.</p> * <p>If you specify both the <code>SourceType</code> and <code>SourceIds</code> (such as <code>SourceType = db-instance</code> and <code>SourceIdentifier = myDBInstance1</code>), you are notified of all the <code>db-instance</code> events for the specified source. If you specify a <code>SourceType</code> but do not specify a <code>SourceIdentifier</code>, you receive notice of the events for that source type for all your Amazon DocumentDB sources. If you do not specify either the <code>SourceType</code> or the <code>SourceIdentifier</code>, you are notified of events generated from all Amazon DocumentDB sources belonging to your customer account.</p> */ public createEventSubscription( args: CreateEventSubscriptionCommandInput, options?: __HttpHandlerOptions ): Promise<CreateEventSubscriptionCommandOutput>; public createEventSubscription( args: CreateEventSubscriptionCommandInput, cb: (err: any, data?: CreateEventSubscriptionCommandOutput) => void ): void; public createEventSubscription( args: CreateEventSubscriptionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateEventSubscriptionCommandOutput) => void ): void; public createEventSubscription( args: CreateEventSubscriptionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateEventSubscriptionCommandOutput) => void), cb?: (err: any, data?: CreateEventSubscriptionCommandOutput) => void ): Promise<CreateEventSubscriptionCommandOutput> | void { const command = new CreateEventSubscriptionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates an Amazon DocumentDB global cluster that can span multiple multiple Regions. The global cluster contains one primary cluster with read-write capability, and up-to give read-only secondary clusters. Global clusters uses storage-based fast replication across regions with latencies less than one second, using dedicated infrastructure with no impact to your workload’s performance.</p> * <p></p> * <p>You can create a global cluster that is initially empty, and then add a primary and a secondary to it. Or you can specify an existing cluster during the create operation, and this cluster becomes the primary of the global cluster. </p> * <note> * <p>This action only applies to Amazon DocumentDB clusters.</p> * </note> */ public createGlobalCluster( args: CreateGlobalClusterCommandInput, options?: __HttpHandlerOptions ): Promise<CreateGlobalClusterCommandOutput>; public createGlobalCluster( args: CreateGlobalClusterCommandInput, cb: (err: any, data?: CreateGlobalClusterCommandOutput) => void ): void; public createGlobalCluster( args: CreateGlobalClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateGlobalClusterCommandOutput) => void ): void; public createGlobalCluster( args: CreateGlobalClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateGlobalClusterCommandOutput) => void), cb?: (err: any, data?: CreateGlobalClusterCommandOutput) => void ): Promise<CreateGlobalClusterCommandOutput> | void { const command = new CreateGlobalClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a previously provisioned cluster. When you delete a cluster, all automated backups for that cluster are deleted and can't be recovered. Manual DB cluster snapshots of the specified cluster are not deleted.</p> * <p></p> */ public deleteDBCluster( args: DeleteDBClusterCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteDBClusterCommandOutput>; public deleteDBCluster( args: DeleteDBClusterCommandInput, cb: (err: any, data?: DeleteDBClusterCommandOutput) => void ): void; public deleteDBCluster( args: DeleteDBClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteDBClusterCommandOutput) => void ): void; public deleteDBCluster( args: DeleteDBClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteDBClusterCommandOutput) => void), cb?: (err: any, data?: DeleteDBClusterCommandOutput) => void ): Promise<DeleteDBClusterCommandOutput> | void { const command = new DeleteDBClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a specified cluster parameter group. The cluster parameter group to be deleted can't be associated with any clusters.</p> */ public deleteDBClusterParameterGroup( args: DeleteDBClusterParameterGroupCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteDBClusterParameterGroupCommandOutput>; public deleteDBClusterParameterGroup( args: DeleteDBClusterParameterGroupCommandInput, cb: (err: any, data?: DeleteDBClusterParameterGroupCommandOutput) => void ): void; public deleteDBClusterParameterGroup( args: DeleteDBClusterParameterGroupCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteDBClusterParameterGroupCommandOutput) => void ): void; public deleteDBClusterParameterGroup( args: DeleteDBClusterParameterGroupCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteDBClusterParameterGroupCommandOutput) => void), cb?: (err: any, data?: DeleteDBClusterParameterGroupCommandOutput) => void ): Promise<DeleteDBClusterParameterGroupCommandOutput> | void { const command = new DeleteDBClusterParameterGroupCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a cluster snapshot. If the snapshot is being copied, the copy operation is terminated.</p> * <note> * <p>The cluster snapshot must be in the <code>available</code> state to be deleted.</p> * </note> */ public deleteDBClusterSnapshot( args: DeleteDBClusterSnapshotCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteDBClusterSnapshotCommandOutput>; public deleteDBClusterSnapshot( args: DeleteDBClusterSnapshotCommandInput, cb: (err: any, data?: DeleteDBClusterSnapshotCommandOutput) => void ): void; public deleteDBClusterSnapshot( args: DeleteDBClusterSnapshotCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteDBClusterSnapshotCommandOutput) => void ): void; public deleteDBClusterSnapshot( args: DeleteDBClusterSnapshotCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteDBClusterSnapshotCommandOutput) => void), cb?: (err: any, data?: DeleteDBClusterSnapshotCommandOutput) => void ): Promise<DeleteDBClusterSnapshotCommandOutput> | void { const command = new DeleteDBClusterSnapshotCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a previously provisioned instance.</p> */ public deleteDBInstance( args: DeleteDBInstanceCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteDBInstanceCommandOutput>; public deleteDBInstance( args: DeleteDBInstanceCommandInput, cb: (err: any, data?: DeleteDBInstanceCommandOutput) => void ): void; public deleteDBInstance( args: DeleteDBInstanceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteDBInstanceCommandOutput) => void ): void; public deleteDBInstance( args: DeleteDBInstanceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteDBInstanceCommandOutput) => void), cb?: (err: any, data?: DeleteDBInstanceCommandOutput) => void ): Promise<DeleteDBInstanceCommandOutput> | void { const command = new DeleteDBInstanceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a subnet group.</p> * <note> * <p>The specified database subnet group must not be associated with any DB * instances.</p> * </note> */ public deleteDBSubnetGroup( args: DeleteDBSubnetGroupCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteDBSubnetGroupCommandOutput>; public deleteDBSubnetGroup( args: DeleteDBSubnetGroupCommandInput, cb: (err: any, data?: DeleteDBSubnetGroupCommandOutput) => void ): void; public deleteDBSubnetGroup( args: DeleteDBSubnetGroupCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteDBSubnetGroupCommandOutput) => void ): void; public deleteDBSubnetGroup( args: DeleteDBSubnetGroupCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteDBSubnetGroupCommandOutput) => void), cb?: (err: any, data?: DeleteDBSubnetGroupCommandOutput) => void ): Promise<DeleteDBSubnetGroupCommandOutput> | void { const command = new DeleteDBSubnetGroupCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes an Amazon DocumentDB event notification subscription.</p> */ public deleteEventSubscription( args: DeleteEventSubscriptionCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteEventSubscriptionCommandOutput>; public deleteEventSubscription( args: DeleteEventSubscriptionCommandInput, cb: (err: any, data?: DeleteEventSubscriptionCommandOutput) => void ): void; public deleteEventSubscription( args: DeleteEventSubscriptionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteEventSubscriptionCommandOutput) => void ): void; public deleteEventSubscription( args: DeleteEventSubscriptionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteEventSubscriptionCommandOutput) => void), cb?: (err: any, data?: DeleteEventSubscriptionCommandOutput) => void ): Promise<DeleteEventSubscriptionCommandOutput> | void { const command = new DeleteEventSubscriptionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a global cluster. The primary and secondary clusters must already be detached or deleted before attempting to delete a global cluster.</p> * <note> * <p>This action only applies to Amazon DocumentDB clusters.</p> * </note> */ public deleteGlobalCluster( args: DeleteGlobalClusterCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteGlobalClusterCommandOutput>; public deleteGlobalCluster( args: DeleteGlobalClusterCommandInput, cb: (err: any, data?: DeleteGlobalClusterCommandOutput) => void ): void; public deleteGlobalCluster( args: DeleteGlobalClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteGlobalClusterCommandOutput) => void ): void; public deleteGlobalCluster( args: DeleteGlobalClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteGlobalClusterCommandOutput) => void), cb?: (err: any, data?: DeleteGlobalClusterCommandOutput) => void ): Promise<DeleteGlobalClusterCommandOutput> | void { const command = new DeleteGlobalClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of certificate authority (CA) certificates provided by Amazon DocumentDB for this account.</p> */ public describeCertificates( args: DescribeCertificatesCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeCertificatesCommandOutput>; public describeCertificates( args: DescribeCertificatesCommandInput, cb: (err: any, data?: DescribeCertificatesCommandOutput) => void ): void; public describeCertificates( args: DescribeCertificatesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeCertificatesCommandOutput) => void ): void; public describeCertificates( args: DescribeCertificatesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeCertificatesCommandOutput) => void), cb?: (err: any, data?: DescribeCertificatesCommandOutput) => void ): Promise<DescribeCertificatesCommandOutput> | void { const command = new DescribeCertificatesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of <code>DBClusterParameterGroup</code> descriptions. If a <code>DBClusterParameterGroupName</code> parameter is specified, the list contains only the description of the specified cluster parameter group. </p> */ public describeDBClusterParameterGroups( args: DescribeDBClusterParameterGroupsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeDBClusterParameterGroupsCommandOutput>; public describeDBClusterParameterGroups( args: DescribeDBClusterParameterGroupsCommandInput, cb: (err: any, data?: DescribeDBClusterParameterGroupsCommandOutput) => void ): void; public describeDBClusterParameterGroups( args: DescribeDBClusterParameterGroupsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeDBClusterParameterGroupsCommandOutput) => void ): void; public describeDBClusterParameterGroups( args: DescribeDBClusterParameterGroupsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeDBClusterParameterGroupsCommandOutput) => void), cb?: (err: any, data?: DescribeDBClusterParameterGroupsCommandOutput) => void ): Promise<DescribeDBClusterParameterGroupsCommandOutput> | void { const command = new DescribeDBClusterParameterGroupsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns the detailed parameter list for a particular cluster parameter * group.</p> */ public describeDBClusterParameters( args: DescribeDBClusterParametersCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeDBClusterParametersCommandOutput>; public describeDBClusterParameters( args: DescribeDBClusterParametersCommandInput, cb: (err: any, data?: DescribeDBClusterParametersCommandOutput) => void ): void; public describeDBClusterParameters( args: DescribeDBClusterParametersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeDBClusterParametersCommandOutput) => void ): void; public describeDBClusterParameters( args: DescribeDBClusterParametersCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeDBClusterParametersCommandOutput) => void), cb?: (err: any, data?: DescribeDBClusterParametersCommandOutput) => void ): Promise<DescribeDBClusterParametersCommandOutput> | void { const command = new DescribeDBClusterParametersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about provisioned Amazon DocumentDB clusters. This API * operation supports pagination. For certain management features * such as cluster and instance lifecycle management, Amazon DocumentDB leverages * operational technology that is shared with Amazon RDS and Amazon * Neptune. Use the <code>filterName=engine,Values=docdb</code> filter * parameter to return only Amazon DocumentDB clusters.</p> */ public describeDBClusters( args: DescribeDBClustersCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeDBClustersCommandOutput>; public describeDBClusters( args: DescribeDBClustersCommandInput, cb: (err: any, data?: DescribeDBClustersCommandOutput) => void ): void; public describeDBClusters( args: DescribeDBClustersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeDBClustersCommandOutput) => void ): void; public describeDBClusters( args: DescribeDBClustersCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeDBClustersCommandOutput) => void), cb?: (err: any, data?: DescribeDBClustersCommandOutput) => void ): Promise<DescribeDBClustersCommandOutput> | void { const command = new DescribeDBClustersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of cluster snapshot attribute names and values for a manual DB * cluster snapshot.</p> * <p>When you share snapshots with other accounts, * <code>DescribeDBClusterSnapshotAttributes</code> returns the <code>restore</code> attribute and a list of IDs for the accounts that are authorized to copy or restore the manual cluster snapshot. If <code>all</code> is included in the list of values for the <code>restore</code> attribute, then the manual cluster snapshot is public and can be copied or restored by all accounts.</p> */ public describeDBClusterSnapshotAttributes( args: DescribeDBClusterSnapshotAttributesCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeDBClusterSnapshotAttributesCommandOutput>; public describeDBClusterSnapshotAttributes( args: DescribeDBClusterSnapshotAttributesCommandInput, cb: (err: any, data?: DescribeDBClusterSnapshotAttributesCommandOutput) => void ): void; public describeDBClusterSnapshotAttributes( args: DescribeDBClusterSnapshotAttributesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeDBClusterSnapshotAttributesCommandOutput) => void ): void; public describeDBClusterSnapshotAttributes( args: DescribeDBClusterSnapshotAttributesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeDBClusterSnapshotAttributesCommandOutput) => void), cb?: (err: any, data?: DescribeDBClusterSnapshotAttributesCommandOutput) => void ): Promise<DescribeDBClusterSnapshotAttributesCommandOutput> | void { const command = new DescribeDBClusterSnapshotAttributesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about cluster snapshots. This API operation supports pagination.</p> */ public describeDBClusterSnapshots( args: DescribeDBClusterSnapshotsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeDBClusterSnapshotsCommandOutput>; public describeDBClusterSnapshots( args: DescribeDBClusterSnapshotsCommandInput, cb: (err: any, data?: DescribeDBClusterSnapshotsCommandOutput) => void ): void; public describeDBClusterSnapshots( args: DescribeDBClusterSnapshotsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeDBClusterSnapshotsCommandOutput) => void ): void; public describeDBClusterSnapshots( args: DescribeDBClusterSnapshotsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeDBClusterSnapshotsCommandOutput) => void), cb?: (err: any, data?: DescribeDBClusterSnapshotsCommandOutput) => void ): Promise<DescribeDBClusterSnapshotsCommandOutput> | void { const command = new DescribeDBClusterSnapshotsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of the available engines.</p> */ public describeDBEngineVersions( args: DescribeDBEngineVersionsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeDBEngineVersionsCommandOutput>; public describeDBEngineVersions( args: DescribeDBEngineVersionsCommandInput, cb: (err: any, data?: DescribeDBEngineVersionsCommandOutput) => void ): void; public describeDBEngineVersions( args: DescribeDBEngineVersionsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeDBEngineVersionsCommandOutput) => void ): void; public describeDBEngineVersions( args: DescribeDBEngineVersionsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeDBEngineVersionsCommandOutput) => void), cb?: (err: any, data?: DescribeDBEngineVersionsCommandOutput) => void ): Promise<DescribeDBEngineVersionsCommandOutput> | void { const command = new DescribeDBEngineVersionsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about provisioned Amazon DocumentDB instances. This API supports pagination.</p> */ public describeDBInstances( args: DescribeDBInstancesCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeDBInstancesCommandOutput>; public describeDBInstances( args: DescribeDBInstancesCommandInput, cb: (err: any, data?: DescribeDBInstancesCommandOutput) => void ): void; public describeDBInstances( args: DescribeDBInstancesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeDBInstancesCommandOutput) => void ): void; public describeDBInstances( args: DescribeDBInstancesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeDBInstancesCommandOutput) => void), cb?: (err: any, data?: DescribeDBInstancesCommandOutput) => void ): Promise<DescribeDBInstancesCommandOutput> | void { const command = new DescribeDBInstancesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of <code>DBSubnetGroup</code> descriptions. If a * <code>DBSubnetGroupName</code> is specified, the list will contain only the descriptions of the specified <code>DBSubnetGroup</code>.</p> */ public describeDBSubnetGroups( args: DescribeDBSubnetGroupsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeDBSubnetGroupsCommandOutput>; public describeDBSubnetGroups( args: DescribeDBSubnetGroupsCommandInput, cb: (err: any, data?: DescribeDBSubnetGroupsCommandOutput) => void ): void; public describeDBSubnetGroups( args: DescribeDBSubnetGroupsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeDBSubnetGroupsCommandOutput) => void ): void; public describeDBSubnetGroups( args: DescribeDBSubnetGroupsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeDBSubnetGroupsCommandOutput) => void), cb?: (err: any, data?: DescribeDBSubnetGroupsCommandOutput) => void ): Promise<DescribeDBSubnetGroupsCommandOutput> | void { const command = new DescribeDBSubnetGroupsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns the default engine and system parameter information for the cluster database * engine.</p> */ public describeEngineDefaultClusterParameters( args: DescribeEngineDefaultClusterParametersCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeEngineDefaultClusterParametersCommandOutput>; public describeEngineDefaultClusterParameters( args: DescribeEngineDefaultClusterParametersCommandInput, cb: (err: any, data?: DescribeEngineDefaultClusterParametersCommandOutput) => void ): void; public describeEngineDefaultClusterParameters( args: DescribeEngineDefaultClusterParametersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeEngineDefaultClusterParametersCommandOutput) => void ): void; public describeEngineDefaultClusterParameters( args: DescribeEngineDefaultClusterParametersCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: DescribeEngineDefaultClusterParametersCommandOutput) => void), cb?: (err: any, data?: DescribeEngineDefaultClusterParametersCommandOutput) => void ): Promise<DescribeEngineDefaultClusterParametersCommandOutput> | void { const command = new DescribeEngineDefaultClusterParametersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Displays a list of categories for all event source types, or, if specified, for a * specified source type. </p> */ public describeEventCategories( args: DescribeEventCategoriesCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeEventCategoriesCommandOutput>; public describeEventCategories( args: DescribeEventCategoriesCommandInput, cb: (err: any, data?: DescribeEventCategoriesCommandOutput) => void ): void; public describeEventCategories( args: DescribeEventCategoriesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeEventCategoriesCommandOutput) => void ): void; public describeEventCategories( args: DescribeEventCategoriesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeEventCategoriesCommandOutput) => void), cb?: (err: any, data?: DescribeEventCategoriesCommandOutput) => void ): Promise<DescribeEventCategoriesCommandOutput> | void { const command = new DescribeEventCategoriesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns events related to instances, security groups, snapshots, and DB parameter groups for the past 14 days. You can obtain events specific to a particular DB instance, security group, snapshot, or parameter group by providing the name as a parameter. By default, the events of the past hour are returned.</p> */ public describeEvents( args: DescribeEventsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeEventsCommandOutput>; public describeEvents( args: DescribeEventsCommandInput, cb: (err: any, data?: DescribeEventsCommandOutput) => void ): void; public describeEvents( args: DescribeEventsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeEventsCommandOutput) => void ): void; public describeEvents( args: DescribeEventsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeEventsCommandOutput) => void), cb?: (err: any, data?: DescribeEventsCommandOutput) => void ): Promise<DescribeEventsCommandOutput> | void { const command = new DescribeEventsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists all the subscription descriptions for a customer account. The description for a subscription includes <code>SubscriptionName</code>, <code>SNSTopicARN</code>, <code>CustomerID</code>, <code>SourceType</code>, <code>SourceID</code>, <code>CreationTime</code>, and <code>Status</code>.</p> * <p>If you specify a <code>SubscriptionName</code>, lists the description for that subscription.</p> */ public describeEventSubscriptions( args: DescribeEventSubscriptionsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeEventSubscriptionsCommandOutput>; public describeEventSubscriptions( args: DescribeEventSubscriptionsCommandInput, cb: (err: any, data?: DescribeEventSubscriptionsCommandOutput) => void ): void; public describeEventSubscriptions( args: DescribeEventSubscriptionsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeEventSubscriptionsCommandOutput) => void ): void; public describeEventSubscriptions( args: DescribeEventSubscriptionsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeEventSubscriptionsCommandOutput) => void), cb?: (err: any, data?: DescribeEventSubscriptionsCommandOutput) => void ): Promise<DescribeEventSubscriptionsCommandOutput> | void { const command = new DescribeEventSubscriptionsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about Amazon DocumentDB global clusters. This API supports pagination.</p> * <note> * <p>This action only applies to Amazon DocumentDB clusters.</p> * </note> */ public describeGlobalClusters( args: DescribeGlobalClustersCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeGlobalClustersCommandOutput>; public describeGlobalClusters( args: DescribeGlobalClustersCommandInput, cb: (err: any, data?: DescribeGlobalClustersCommandOutput) => void ): void; public describeGlobalClusters( args: DescribeGlobalClustersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeGlobalClustersCommandOutput) => void ): void; public describeGlobalClusters( args: DescribeGlobalClustersCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeGlobalClustersCommandOutput) => void), cb?: (err: any, data?: DescribeGlobalClustersCommandOutput) => void ): Promise<DescribeGlobalClustersCommandOutput> | void { const command = new DescribeGlobalClustersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of orderable instance options for the specified engine.</p> */ public describeOrderableDBInstanceOptions( args: DescribeOrderableDBInstanceOptionsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeOrderableDBInstanceOptionsCommandOutput>; public describeOrderableDBInstanceOptions( args: DescribeOrderableDBInstanceOptionsCommandInput, cb: (err: any, data?: DescribeOrderableDBInstanceOptionsCommandOutput) => void ): void; public describeOrderableDBInstanceOptions( args: DescribeOrderableDBInstanceOptionsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeOrderableDBInstanceOptionsCommandOutput) => void ): void; public describeOrderableDBInstanceOptions( args: DescribeOrderableDBInstanceOptionsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeOrderableDBInstanceOptionsCommandOutput) => void), cb?: (err: any, data?: DescribeOrderableDBInstanceOptionsCommandOutput) => void ): Promise<DescribeOrderableDBInstanceOptionsCommandOutput> | void { const command = new DescribeOrderableDBInstanceOptionsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of resources (for example, instances) that have at least one pending * maintenance action.</p> */ public describePendingMaintenanceActions( args: DescribePendingMaintenanceActionsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribePendingMaintenanceActionsCommandOutput>; public describePendingMaintenanceActions( args: DescribePendingMaintenanceActionsCommandInput, cb: (err: any, data?: DescribePendingMaintenanceActionsCommandOutput) => void ): void; public describePendingMaintenanceActions( args: DescribePendingMaintenanceActionsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribePendingMaintenanceActionsCommandOutput) => void ): void; public describePendingMaintenanceActions( args: DescribePendingMaintenanceActionsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribePendingMaintenanceActionsCommandOutput) => void), cb?: (err: any, data?: DescribePendingMaintenanceActionsCommandOutput) => void ): Promise<DescribePendingMaintenanceActionsCommandOutput> | void { const command = new DescribePendingMaintenanceActionsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Forces a failover for a cluster.</p> * <p>A failover for a cluster promotes one of the Amazon DocumentDB replicas (read-only instances) in the cluster to be the primary instance (the cluster writer).</p> * <p>If the primary instance fails, Amazon DocumentDB automatically fails over to an Amazon DocumentDB replica, if one exists. You can force a failover when you want to simulate a failure of a primary instance for testing.</p> */ public failoverDBCluster( args: FailoverDBClusterCommandInput, options?: __HttpHandlerOptions ): Promise<FailoverDBClusterCommandOutput>; public failoverDBCluster( args: FailoverDBClusterCommandInput, cb: (err: any, data?: FailoverDBClusterCommandOutput) => void ): void; public failoverDBCluster( args: FailoverDBClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: FailoverDBClusterCommandOutput) => void ): void; public failoverDBCluster( args: FailoverDBClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: FailoverDBClusterCommandOutput) => void), cb?: (err: any, data?: FailoverDBClusterCommandOutput) => void ): Promise<FailoverDBClusterCommandOutput> | void { const command = new FailoverDBClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists all tags on an Amazon DocumentDB resource.</p> */ public listTagsForResource( args: ListTagsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListTagsForResourceCommandOutput>; public listTagsForResource( args: ListTagsForResourceCommandInput, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void), cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void ): Promise<ListTagsForResourceCommandOutput> | void { const command = new ListTagsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Modifies a setting for an Amazon DocumentDB cluster. You can change one or more database * configuration parameters by specifying these parameters and the new values in the * request. </p> */ public modifyDBCluster( args: ModifyDBClusterCommandInput, options?: __HttpHandlerOptions ): Promise<ModifyDBClusterCommandOutput>; public modifyDBCluster( args: ModifyDBClusterCommandInput, cb: (err: any, data?: ModifyDBClusterCommandOutput) => void ): void; public modifyDBCluster( args: ModifyDBClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ModifyDBClusterCommandOutput) => void ): void; public modifyDBCluster( args: ModifyDBClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ModifyDBClusterCommandOutput) => void), cb?: (err: any, data?: ModifyDBClusterCommandOutput) => void ): Promise<ModifyDBClusterCommandOutput> | void { const command = new ModifyDBClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> Modifies the parameters of a cluster parameter group. To modify more than one * parameter, submit a list of the following: <code>ParameterName</code>, * <code>ParameterValue</code>, and <code>ApplyMethod</code>. A maximum of 20 * parameters can be modified in a single request. </p> * <note> * <p>Changes to dynamic parameters are applied immediately. Changes to static * parameters require a reboot or maintenance window * * before the change can take effect.</p> * </note> * <important> * <p>After you create a cluster parameter group, you should wait at least 5 minutes * before creating your first cluster that uses that cluster parameter group as * the default parameter group. This allows Amazon DocumentDB to fully complete the create action * before the parameter group is used as the default for a new cluster. This step is * especially important for parameters that are critical when creating the default * database for a cluster, such as the character set for the default database * defined by the <code>character_set_database</code> parameter.</p> * </important> */ public modifyDBClusterParameterGroup( args: ModifyDBClusterParameterGroupCommandInput, options?: __HttpHandlerOptions ): Promise<ModifyDBClusterParameterGroupCommandOutput>; public modifyDBClusterParameterGroup( args: ModifyDBClusterParameterGroupCommandInput, cb: (err: any, data?: ModifyDBClusterParameterGroupCommandOutput) => void ): void; public modifyDBClusterParameterGroup( args: ModifyDBClusterParameterGroupCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ModifyDBClusterParameterGroupCommandOutput) => void ): void; public modifyDBClusterParameterGroup( args: ModifyDBClusterParameterGroupCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ModifyDBClusterParameterGroupCommandOutput) => void), cb?: (err: any, data?: ModifyDBClusterParameterGroupCommandOutput) => void ): Promise<ModifyDBClusterParameterGroupCommandOutput> | void { const command = new ModifyDBClusterParameterGroupCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Adds an attribute and values to, or removes an attribute and values from, a manual cluster snapshot.</p> * <p>To share a manual cluster snapshot with other accounts, specify <code>restore</code> as the <code>AttributeName</code>, and use the <code>ValuesToAdd</code> parameter to add a list of IDs of the accounts that are authorized to restore the manual cluster snapshot. Use the value <code>all</code> to make the manual cluster snapshot public, which means that it can be copied or restored by all accounts. Do not add the <code>all</code> value for any manual cluster snapshots that contain private information that you don't want available to all accounts. If a manual cluster snapshot is encrypted, it can be shared, but only by specifying a list of authorized account IDs for the <code>ValuesToAdd</code> parameter. You can't use <code>all</code> as a value for that parameter in this case.</p> */ public modifyDBClusterSnapshotAttribute( args: ModifyDBClusterSnapshotAttributeCommandInput, options?: __HttpHandlerOptions ): Promise<ModifyDBClusterSnapshotAttributeCommandOutput>; public modifyDBClusterSnapshotAttribute( args: ModifyDBClusterSnapshotAttributeCommandInput, cb: (err: any, data?: ModifyDBClusterSnapshotAttributeCommandOutput) => void ): void; public modifyDBClusterSnapshotAttribute( args: ModifyDBClusterSnapshotAttributeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ModifyDBClusterSnapshotAttributeCommandOutput) => void ): void; public modifyDBClusterSnapshotAttribute( args: ModifyDBClusterSnapshotAttributeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ModifyDBClusterSnapshotAttributeCommandOutput) => void), cb?: (err: any, data?: ModifyDBClusterSnapshotAttributeCommandOutput) => void ): Promise<ModifyDBClusterSnapshotAttributeCommandOutput> | void { const command = new ModifyDBClusterSnapshotAttributeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Modifies settings for an instance. You can change one or more database configuration parameters by specifying these parameters and the new values in the request.</p> */ public modifyDBInstance( args: ModifyDBInstanceCommandInput, options?: __HttpHandlerOptions ): Promise<ModifyDBInstanceCommandOutput>; public modifyDBInstance( args: ModifyDBInstanceCommandInput, cb: (err: any, data?: ModifyDBInstanceCommandOutput) => void ): void; public modifyDBInstance( args: ModifyDBInstanceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ModifyDBInstanceCommandOutput) => void ): void; public modifyDBInstance( args: ModifyDBInstanceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ModifyDBInstanceCommandOutput) => void), cb?: (err: any, data?: ModifyDBInstanceCommandOutput) => void ): Promise<ModifyDBInstanceCommandOutput> | void { const command = new ModifyDBInstanceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Modifies an existing subnet group. subnet groups must contain at least one subnet in at least two Availability Zones in the Region.</p> */ public modifyDBSubnetGroup( args: ModifyDBSubnetGroupCommandInput, options?: __HttpHandlerOptions ): Promise<ModifyDBSubnetGroupCommandOutput>; public modifyDBSubnetGroup( args: ModifyDBSubnetGroupCommandInput, cb: (err: any, data?: ModifyDBSubnetGroupCommandOutput) => void ): void; public modifyDBSubnetGroup( args: ModifyDBSubnetGroupCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ModifyDBSubnetGroupCommandOutput) => void ): void; public modifyDBSubnetGroup( args: ModifyDBSubnetGroupCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ModifyDBSubnetGroupCommandOutput) => void), cb?: (err: any, data?: ModifyDBSubnetGroupCommandOutput) => void ): Promise<ModifyDBSubnetGroupCommandOutput> | void { const command = new ModifyDBSubnetGroupCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Modifies an existing Amazon DocumentDB event notification subscription.</p> */ public modifyEventSubscription( args: ModifyEventSubscriptionCommandInput, options?: __HttpHandlerOptions ): Promise<ModifyEventSubscriptionCommandOutput>; public modifyEventSubscription( args: ModifyEventSubscriptionCommandInput, cb: (err: any, data?: ModifyEventSubscriptionCommandOutput) => void ): void; public modifyEventSubscription( args: ModifyEventSubscriptionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ModifyEventSubscriptionCommandOutput) => void ): void; public modifyEventSubscription( args: ModifyEventSubscriptionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ModifyEventSubscriptionCommandOutput) => void), cb?: (err: any, data?: ModifyEventSubscriptionCommandOutput) => void ): Promise<ModifyEventSubscriptionCommandOutput> | void { const command = new ModifyEventSubscriptionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Modify a setting for an Amazon DocumentDB global cluster. You can change one or more configuration parameters (for example: deletion protection), or the global cluster identifier by specifying these parameters and the new values in the request.</p> * <note> * <p>This action only applies to Amazon DocumentDB clusters.</p> * </note> */ public modifyGlobalCluster( args: ModifyGlobalClusterCommandInput, options?: __HttpHandlerOptions ): Promise<ModifyGlobalClusterCommandOutput>; public modifyGlobalCluster( args: ModifyGlobalClusterCommandInput, cb: (err: any, data?: ModifyGlobalClusterCommandOutput) => void ): void; public modifyGlobalCluster( args: ModifyGlobalClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ModifyGlobalClusterCommandOutput) => void ): void; public modifyGlobalCluster( args: ModifyGlobalClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ModifyGlobalClusterCommandOutput) => void), cb?: (err: any, data?: ModifyGlobalClusterCommandOutput) => void ): Promise<ModifyGlobalClusterCommandOutput> | void { const command = new ModifyGlobalClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>You might need to reboot your instance, usually for maintenance reasons. For * example, if you make certain changes, or if you change the cluster parameter group * that is associated with the instance, you must reboot the instance for the changes to * take effect. </p> * <p>Rebooting an instance restarts the database engine service. Rebooting an instance * results in a momentary outage, during which the instance status is set to * <i>rebooting</i>. </p> */ public rebootDBInstance( args: RebootDBInstanceCommandInput, options?: __HttpHandlerOptions ): Promise<RebootDBInstanceCommandOutput>; public rebootDBInstance( args: RebootDBInstanceCommandInput, cb: (err: any, data?: RebootDBInstanceCommandOutput) => void ): void; public rebootDBInstance( args: RebootDBInstanceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RebootDBInstanceCommandOutput) => void ): void; public rebootDBInstance( args: RebootDBInstanceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RebootDBInstanceCommandOutput) => void), cb?: (err: any, data?: RebootDBInstanceCommandOutput) => void ): Promise<RebootDBInstanceCommandOutput> | void { const command = new RebootDBInstanceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Detaches an Amazon DocumentDB secondary cluster from a global cluster. The cluster becomes a standalone cluster with read-write capability instead of being read-only and receiving data from a primary in a different region. </p> * <note> * <p>This action only applies to Amazon DocumentDB clusters.</p> * </note> */ public removeFromGlobalCluster( args: RemoveFromGlobalClusterCommandInput, options?: __HttpHandlerOptions ): Promise<RemoveFromGlobalClusterCommandOutput>; public removeFromGlobalCluster( args: RemoveFromGlobalClusterCommandInput, cb: (err: any, data?: RemoveFromGlobalClusterCommandOutput) => void ): void; public removeFromGlobalCluster( args: RemoveFromGlobalClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RemoveFromGlobalClusterCommandOutput) => void ): void; public removeFromGlobalCluster( args: RemoveFromGlobalClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RemoveFromGlobalClusterCommandOutput) => void), cb?: (err: any, data?: RemoveFromGlobalClusterCommandOutput) => void ): Promise<RemoveFromGlobalClusterCommandOutput> | void { const command = new RemoveFromGlobalClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes a source identifier from an existing Amazon DocumentDB event notification * subscription.</p> */ public removeSourceIdentifierFromSubscription( args: RemoveSourceIdentifierFromSubscriptionCommandInput, options?: __HttpHandlerOptions ): Promise<RemoveSourceIdentifierFromSubscriptionCommandOutput>; public removeSourceIdentifierFromSubscription( args: RemoveSourceIdentifierFromSubscriptionCommandInput, cb: (err: any, data?: RemoveSourceIdentifierFromSubscriptionCommandOutput) => void ): void; public removeSourceIdentifierFromSubscription( args: RemoveSourceIdentifierFromSubscriptionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RemoveSourceIdentifierFromSubscriptionCommandOutput) => void ): void; public removeSourceIdentifierFromSubscription( args: RemoveSourceIdentifierFromSubscriptionCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: RemoveSourceIdentifierFromSubscriptionCommandOutput) => void), cb?: (err: any, data?: RemoveSourceIdentifierFromSubscriptionCommandOutput) => void ): Promise<RemoveSourceIdentifierFromSubscriptionCommandOutput> | void { const command = new RemoveSourceIdentifierFromSubscriptionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes metadata tags from an Amazon DocumentDB resource.</p> */ public removeTagsFromResource( args: RemoveTagsFromResourceCommandInput, options?: __HttpHandlerOptions ): Promise<RemoveTagsFromResourceCommandOutput>; public removeTagsFromResource( args: RemoveTagsFromResourceCommandInput, cb: (err: any, data?: RemoveTagsFromResourceCommandOutput) => void ): void; public removeTagsFromResource( args: RemoveTagsFromResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RemoveTagsFromResourceCommandOutput) => void ): void; public removeTagsFromResource( args: RemoveTagsFromResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RemoveTagsFromResourceCommandOutput) => void), cb?: (err: any, data?: RemoveTagsFromResourceCommandOutput) => void ): Promise<RemoveTagsFromResourceCommandOutput> | void { const command = new RemoveTagsFromResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> Modifies the parameters of a cluster parameter group to the default value. To * reset specific parameters, submit a list of the following: <code>ParameterName</code> * and <code>ApplyMethod</code>. To reset the entire cluster parameter group, specify * the <code>DBClusterParameterGroupName</code> and <code>ResetAllParameters</code> * parameters. </p> * <p> When you reset the entire group, dynamic parameters are updated immediately and * static parameters are set to <code>pending-reboot</code> to take effect on the next DB * instance reboot.</p> */ public resetDBClusterParameterGroup( args: ResetDBClusterParameterGroupCommandInput, options?: __HttpHandlerOptions ): Promise<ResetDBClusterParameterGroupCommandOutput>; public resetDBClusterParameterGroup( args: ResetDBClusterParameterGroupCommandInput, cb: (err: any, data?: ResetDBClusterParameterGroupCommandOutput) => void ): void; public resetDBClusterParameterGroup( args: ResetDBClusterParameterGroupCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ResetDBClusterParameterGroupCommandOutput) => void ): void; public resetDBClusterParameterGroup( args: ResetDBClusterParameterGroupCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ResetDBClusterParameterGroupCommandOutput) => void), cb?: (err: any, data?: ResetDBClusterParameterGroupCommandOutput) => void ): Promise<ResetDBClusterParameterGroupCommandOutput> | void { const command = new ResetDBClusterParameterGroupCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new cluster from a snapshot or cluster snapshot.</p> * <p>If a snapshot is specified, the target cluster is created from the source DB snapshot with a default configuration and default security group.</p> * <p>If a cluster snapshot is specified, the target cluster is created from the source cluster restore point with the same configuration as the original source DB cluster, except that the new cluster is created with the default security group.</p> */ public restoreDBClusterFromSnapshot( args: RestoreDBClusterFromSnapshotCommandInput, options?: __HttpHandlerOptions ): Promise<RestoreDBClusterFromSnapshotCommandOutput>; public restoreDBClusterFromSnapshot( args: RestoreDBClusterFromSnapshotCommandInput, cb: (err: any, data?: RestoreDBClusterFromSnapshotCommandOutput) => void ): void; public restoreDBClusterFromSnapshot( args: RestoreDBClusterFromSnapshotCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RestoreDBClusterFromSnapshotCommandOutput) => void ): void; public restoreDBClusterFromSnapshot( args: RestoreDBClusterFromSnapshotCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RestoreDBClusterFromSnapshotCommandOutput) => void), cb?: (err: any, data?: RestoreDBClusterFromSnapshotCommandOutput) => void ): Promise<RestoreDBClusterFromSnapshotCommandOutput> | void { const command = new RestoreDBClusterFromSnapshotCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Restores a cluster to an arbitrary point in time. Users can restore to any point in * time before <code>LatestRestorableTime</code> for up to * <code>BackupRetentionPeriod</code> days. The target cluster is created from the * source cluster with the same configuration as the original cluster, except that * the new cluster is created with the default security group. </p> */ public restoreDBClusterToPointInTime( args: RestoreDBClusterToPointInTimeCommandInput, options?: __HttpHandlerOptions ): Promise<RestoreDBClusterToPointInTimeCommandOutput>; public restoreDBClusterToPointInTime( args: RestoreDBClusterToPointInTimeCommandInput, cb: (err: any, data?: RestoreDBClusterToPointInTimeCommandOutput) => void ): void; public restoreDBClusterToPointInTime( args: RestoreDBClusterToPointInTimeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RestoreDBClusterToPointInTimeCommandOutput) => void ): void; public restoreDBClusterToPointInTime( args: RestoreDBClusterToPointInTimeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RestoreDBClusterToPointInTimeCommandOutput) => void), cb?: (err: any, data?: RestoreDBClusterToPointInTimeCommandOutput) => void ): Promise<RestoreDBClusterToPointInTimeCommandOutput> | void { const command = new RestoreDBClusterToPointInTimeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Restarts the stopped cluster that is specified by <code>DBClusterIdentifier</code>. * For more information, see <a href="https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-stop-start.html">Stopping and * Starting an Amazon DocumentDB Cluster</a>.</p> */ public startDBCluster( args: StartDBClusterCommandInput, options?: __HttpHandlerOptions ): Promise<StartDBClusterCommandOutput>; public startDBCluster( args: StartDBClusterCommandInput, cb: (err: any, data?: StartDBClusterCommandOutput) => void ): void; public startDBCluster( args: StartDBClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: StartDBClusterCommandOutput) => void ): void; public startDBCluster( args: StartDBClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StartDBClusterCommandOutput) => void), cb?: (err: any, data?: StartDBClusterCommandOutput) => void ): Promise<StartDBClusterCommandOutput> | void { const command = new StartDBClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Stops the running cluster that is specified by <code>DBClusterIdentifier</code>. The * cluster must be in the <i>available</i> state. For more information, see * <a href="https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-stop-start.html">Stopping and * Starting an Amazon DocumentDB Cluster</a>.</p> */ public stopDBCluster( args: StopDBClusterCommandInput, options?: __HttpHandlerOptions ): Promise<StopDBClusterCommandOutput>; public stopDBCluster( args: StopDBClusterCommandInput, cb: (err: any, data?: StopDBClusterCommandOutput) => void ): void; public stopDBCluster( args: StopDBClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: StopDBClusterCommandOutput) => void ): void; public stopDBCluster( args: StopDBClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StopDBClusterCommandOutput) => void), cb?: (err: any, data?: StopDBClusterCommandOutput) => void ): Promise<StopDBClusterCommandOutput> | void { const command = new StopDBClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import { Opcode, ProtocolNames, ProtocolParams, IStoreService, ProtocolMessage, ProtocolRoles, ILoggerService, SetStateCommitmentJSON, ConditionalTransactionCommitmentJSON, AppInstanceJson, HexString, } from "@connext/types"; import { stringify, logTime, toBN, getSignerAddressFromPublicIdentifier } from "@connext/utils"; import { stateChannelClassFromStoreByMultisig, getPureBytecode, generateProtocolMessageData, parseProtocolMessage, } from "./utils"; import { StateChannel, AppInstance, FreeBalanceClass } from "../models"; import { Context, ProtocolExecutionFlow, PersistStateChannelType } from "../types"; import { SetStateCommitment, ConditionalTransactionCommitment, getSetStateCommitment, } from "../ethereum"; import { getTokenBalanceDecrementForInstall } from "./install"; import { UNASSIGNED_SEQ_NO } from "../constants"; const protocol = ProtocolNames.sync; const { IO_SEND, IO_SEND_AND_WAIT, PERSIST_STATE_CHANNEL, OP_SIGN, OP_VALIDATE } = Opcode; export const SYNC_PROTOCOL: ProtocolExecutionFlow = { 0 /* Initiating */: async function* (context: Context) { const { message, store, networks } = context; const log = context.log.newContext("CF-SyncProtocol"); const start = Date.now(); let substart = start; const { processID, params } = message.data; const loggerId = (params as ProtocolParams.Sync).multisigAddress || processID; log.info(`[${loggerId}] Initiation started: ${stringify(params, false, 0)}`); const { multisigAddress, responderIdentifier, initiatorIdentifier, appIdentityHash, } = params as ProtocolParams.Sync; const myIdentifier = initiatorIdentifier; const counterpartyIdentifier = responderIdentifier; // Send m1 to responder containing all information relevant for them // to: // - begin sync protocol // - determine if they need to sync from message data // - determine information we need to sync from message data const preProtocolStateChannel = await stateChannelClassFromStoreByMultisig( multisigAddress, store, ); if (!preProtocolStateChannel) { throw new Error("No state channel found for sync"); } const { contractAddresses, provider } = networks[preProtocolStateChannel.chainId]; const syncDeterminationData = getSyncDeterminationData(preProtocolStateChannel); const { message: m2 } = (yield [ IO_SEND_AND_WAIT, generateProtocolMessageData(counterpartyIdentifier, protocol, processID, 1, params!, { customData: { ...syncDeterminationData }, prevMessageReceived: substart, }), ] as any)!; logTime( log, substart, `[${loggerId}] Received responder's m2: ${stringify((m2 as any).data.customData, false, 0)}`, ); substart = Date.now(); // Parse responder's m2. This should contain all of the information // we sent in m1 to determine if we should sync, in addition to all // the information they had for us to sync from const counterpartyData = parseProtocolMessage(m2).data.customData as SyncDeterminationData & SyncFromDataJson; // Determine how channel is out of sync, and get the info needed // for counterparty to sync (if any) to send const syncType = makeSyncDetermination( counterpartyData, preProtocolStateChannel, appIdentityHash, log, ); log.info(`Initiator syncing with: ${stringify(syncType, true, 0)}`); const syncInfoForCounterparty = await getInfoForSync(syncType, preProtocolStateChannel, store); // Should already have information from counterparty needed to sync your // channel included in m2 const { commitments, affectedApp, freeBalanceApp } = (m2! as ProtocolMessage).data .customData as SyncDeterminationData & SyncFromDataJson; const validCommitments = commitments && commitments.length > 0; if (syncType && !syncType.counterpartyIsBehind && !validCommitments && !!affectedApp) { throw new Error( `Need to sync from counterparty with ${ syncType.type }, but did not receive any commitments in m2: ${stringify(m2, false, 0)}`, ); } // Perform sync and generate persistType call for channel let postSyncStateChannel: StateChannel; if (!syncType || syncType.counterpartyIsBehind) { // We do not need to sync our channel postSyncStateChannel = StateChannel.fromJson(preProtocolStateChannel.toJson()); } else { // we should update our channel const param = affectedApp ? AppInstance.fromJson(affectedApp) : undefined; const [updatedChannel, persistType, verifiedCommitments, uninstalledApp] = await syncChannel( context, preProtocolStateChannel, syncType.type, commitments.map((c) => !!c["contractAddresses"] ? ConditionalTransactionCommitment.fromJson(c as ConditionalTransactionCommitmentJSON) : SetStateCommitment.fromJson(c as SetStateCommitmentJSON), ), param || syncType.identityHash!, freeBalanceApp ? AppInstance.fromJson(freeBalanceApp) : undefined, log, ); postSyncStateChannel = updatedChannel; const singleSignedCommitments = verifiedCommitments .filter((c) => { return c.signatures.filter((x) => !!x).length === 1; }) .filter((x) => !!x) as SetStateCommitment[]; if (syncType.type !== "takeAction" || singleSignedCommitments.length === 0) { // All other cases can be saved here because they do not require // special middleware access yield [ PERSIST_STATE_CHANNEL, persistType, postSyncStateChannel, verifiedCommitments, // all signed commitments [param || uninstalledApp], // ^^ in the case of uninstall the affectedApp is undefined ]; } else { // NOTE: must update single signed set state commitments here // instead of in the `syncChannel` function to properly access // middlewares if (singleSignedCommitments.length > 1) { throw new Error( `Cannot sync by more than one take action, and detected multiple single signed commitments. Use restore instead.`, ); } const [commitment] = singleSignedCommitments; if (!commitment) { throw new Error(`Cannot find single signed commitment to update`); } const app = postSyncStateChannel.appInstances.get(commitment.appIdentityHash)!; // signature has been validated, add our signature // NOTE: iff commitment is single signed, we were the responder // in the take action commitment, and they initiated it const error = yield [ OP_VALIDATE, ProtocolNames.takeAction, { params: { initiatorIdentifier: counterpartyIdentifier, responderIdentifier: myIdentifier, multisigAddress: postSyncStateChannel.multisigAddress, appIdentityHash: app.identityHash, action: affectedApp!.latestAction, stateTimeout: commitment.stateTimeout, }, appInstance: app.toJson(), role: ProtocolRoles.responder, }, ]; if (!!error) { throw new Error(error); } // update the app postSyncStateChannel = postSyncStateChannel.setState( app, await app.computeStateTransition( getSignerAddressFromPublicIdentifier(initiatorIdentifier), affectedApp!.latestAction, provider, getPureBytecode(app.appDefinition, contractAddresses), ), commitment.stateTimeout, ); // counterparty sig has already been asserted, sign commitment // and update channel const mySig = yield [OP_SIGN, commitment.hashToSign()]; await commitment.addSignatures( mySig, commitment.signatures.find((x) => !!x), ); yield [ PERSIST_STATE_CHANNEL, PersistStateChannelType.SyncAppInstances, postSyncStateChannel, commitment, // all signed commitments [affectedApp], ]; logTime(log, substart, `[${loggerId}] Synced single signed app states with responder`); } } // After syncing channel, create list of proposal ids to send to // counterparty so rejections may be synced const mySyncedProposals = [...postSyncStateChannel.proposedAppInstances.keys()]; const { message: m4 } = (yield [ IO_SEND_AND_WAIT, generateProtocolMessageData(responderIdentifier, protocol, processID, 1, params!, { customData: { ...syncInfoForCounterparty, syncedProposals: mySyncedProposals, }, prevMessageReceived: substart, }), ])!; logTime( log, substart, `[${loggerId}] Received responder's m4: ${stringify((m2 as any).data.customData, false, 0)}`, ); substart = Date.now(); // m4 includes the responders post-sync proposal ids. Handle all // unsynced rejections using these values const { syncedProposals: counterpartySyncedProposals } = parseProtocolMessage(m4).data .customData as { syncedProposals: string[] }; // find any rejected proposals and update your channel const [postRejectChannel, rejected] = syncRejectedApps( postSyncStateChannel, counterpartySyncedProposals, ); yield [ PERSIST_STATE_CHANNEL, PersistStateChannelType.SyncRejectedProposals, postRejectChannel, [], // no commitments effected during proposal rejection rejected, ]; logTime(log, start, `[${loggerId}] Initiation finished`); }, 1 /* Responding */: async function* (context: Context) { const { message: m1, store, networks, preProtocolStateChannel } = context; const { params, processID, customData } = m1.data; const log = context.log.newContext("CF-SyncProtocol"); const start = Date.now(); let substart = start; const loggerId = (params as ProtocolParams.Sync).multisigAddress || processID; if (!preProtocolStateChannel) { throw new Error("No state channel found for sync"); } const { contractAddresses, provider } = networks[preProtocolStateChannel.chainId]; // Determine the sync type needed, and fetch any information the // counterparty would need to sync and send to them log.debug(`[${loggerId}] Response started with m1: ${stringify(customData, false, 0)}`); const { initiatorIdentifier, responderIdentifier, appIdentityHash, } = params as ProtocolParams.Sync; const myIdentifier = responderIdentifier; const counterpartyIdentifier = initiatorIdentifier; const syncType = makeSyncDetermination( customData as SyncDeterminationData, preProtocolStateChannel, appIdentityHash, log, ); log.info(`Responder syncing with: ${stringify(syncType, true, 0)}`); const syncInfoForCounterparty = await getInfoForSync(syncType, preProtocolStateChannel, store); const { message: m3 } = (yield [ IO_SEND_AND_WAIT, generateProtocolMessageData(counterpartyIdentifier, protocol, processID, 0, params!, { customData: { ...getSyncDeterminationData(preProtocolStateChannel), ...syncInfoForCounterparty, }, prevMessageReceived: substart, }), ])!; logTime( log, substart, `[${loggerId}] Received initiator's m3: ${stringify((m3 as any).data.customData, false, 0)}`, ); substart = Date.now(); // Determine how channel is out of sync + sync channel const counterpartyData = parseProtocolMessage(m3).data.customData as { syncedProposals: string[]; } & SyncFromDataJson; const {} = counterpartyData; let postSyncStateChannel: StateChannel; if (!syncType || syncType.counterpartyIsBehind) { // We do not need to sync our channel postSyncStateChannel = StateChannel.fromJson(preProtocolStateChannel.toJson()); } else { const { commitments, affectedApp, freeBalanceApp } = counterpartyData; // we should update our channel const param = affectedApp ? AppInstance.fromJson(affectedApp) : undefined; const [updatedChannel, persistType, verifiedCommitments, uninstalledApp] = await syncChannel( context, preProtocolStateChannel, syncType.type, commitments.map((c) => !!(c as ConditionalTransactionCommitmentJSON).contractAddresses ? ConditionalTransactionCommitment.fromJson(c as ConditionalTransactionCommitmentJSON) : SetStateCommitment.fromJson(c as SetStateCommitmentJSON), ), param || syncType.identityHash!, freeBalanceApp ? AppInstance.fromJson(freeBalanceApp) : undefined, log, ); postSyncStateChannel = updatedChannel; const singleSignedCommitments = verifiedCommitments.filter((c) => { return c.signatures.filter((x) => !!x).length === 1; }) as SetStateCommitment[]; if (syncType.type !== "takeAction" || singleSignedCommitments.length === 0) { // All other cases can be saved here because they do not require // special middleware access yield [ PERSIST_STATE_CHANNEL, persistType, postSyncStateChannel, verifiedCommitments, // all signed commitments [param || uninstalledApp], // ^^ in the case of uninstall the affectedApp is undefined ]; } else { // NOTE: must update single signed set state commitments here // instead of in the `syncChannel` function to properly access // middlewares const singleSignedCommitments = verifiedCommitments.filter((c) => { return c.signatures.filter((x) => !!x).length === 1; }) as SetStateCommitment[]; if (singleSignedCommitments.length > 1) { throw new Error( `Cannot sync by more than one take action, and detected multiple single signed commitments. Use restore instead.`, ); } const [commitment] = singleSignedCommitments; if (!commitment) { throw new Error(`Cannot find single signed commitment to update`); } const app = postSyncStateChannel.appInstances.get(commitment.appIdentityHash)!; // signature has been validated, add our signature // NOTE: iff commitment is single signed, we were the responder // in the take action commitment, and they initiated it const error = yield [ OP_VALIDATE, ProtocolNames.takeAction, { params: { initiatorIdentifier: counterpartyIdentifier, responderIdentifier: myIdentifier, multisigAddress: postSyncStateChannel.multisigAddress, appIdentityHash: app.identityHash, action: affectedApp!.latestAction, stateTimeout: commitment.stateTimeout, }, appInstance: app.toJson(), role: ProtocolRoles.responder, }, ]; if (!!error) { throw new Error(error); } // update the app postSyncStateChannel = postSyncStateChannel.setState( app, await app.computeStateTransition( getSignerAddressFromPublicIdentifier(initiatorIdentifier), affectedApp!.latestAction, provider, getPureBytecode(app.appDefinition, contractAddresses), ), commitment.stateTimeout, ); // counterparty sig has already been asserted, sign commitment // and update channel const mySig = yield [OP_SIGN, commitment.hashToSign()]; await commitment.addSignatures( mySig, commitment.signatures.find((x) => !!x), ); yield [ PERSIST_STATE_CHANNEL, PersistStateChannelType.SyncAppInstances, postSyncStateChannel, commitment, // all signed commitments [affectedApp], ]; logTime(log, substart, `[${loggerId}] Synced single signed app states with responder`); } } // After syncing channel, create list of proposal ids to send to // counterparty so rejections may be synced const [postRejectChannel, rejected] = syncRejectedApps( postSyncStateChannel, counterpartyData.syncedProposals, ); yield [ PERSIST_STATE_CHANNEL, PersistStateChannelType.SyncRejectedProposals, postRejectChannel, [], // no commitments effected during proposal rejection rejected, ]; logTime(log, substart, `[${loggerId}] Synced rejected apps with initiator`); substart = Date.now(); // send counterparty final list of proposal IDs yield [ IO_SEND, generateProtocolMessageData( initiatorIdentifier, protocol, processID, UNASSIGNED_SEQ_NO, params!, { customData: { syncedProposals: [...postRejectChannel.proposedAppInstances.keys()], }, prevMessageReceived: substart, }, ), postSyncStateChannel, ]; logTime(log, start, `[${loggerId}] Response finished`); }, }; // This function should collect all information from our store and // channel necessary for the counterparty to determine if and // how they need to sync. To determine whether or not counterparties // have gotten out of sync, you need the following information: // 1. Free balance nonce (updated on uninstall, install) // 2. Channel num proposed apps (updated on propose) // 3. Channel proposal info inc. id + nonce (updated on propose, // reject, install) // 3. Channel app info inc. id + nonce (updated on install, takeAction, // uninstall) type SyncDeterminationData = { freeBalanceVersionNumber: number; numProposedApps: number; proposals: { identityHash: string; appSeqNo: number }[]; apps: { identityHash: string; latestVersionNumber: number }[]; }; function getSyncDeterminationData(preProtocolStateChannel: StateChannel): SyncDeterminationData { return { freeBalanceVersionNumber: preProtocolStateChannel.freeBalance.latestVersionNumber, numProposedApps: preProtocolStateChannel.numProposedApps, proposals: [...preProtocolStateChannel.proposedAppInstances.values()].map((app) => { return { identityHash: app.identityHash, appSeqNo: app.appSeqNo, }; }), apps: [...preProtocolStateChannel.appInstances.values()].map((app) => { return { identityHash: app.identityHash, latestVersionNumber: app.latestVersionNumber, }; }), }; } // This function should determine if/how the channel is out of sync when // given SyncDeterminationData from your counterparty. It is important // to note that this will NOT handle cases where a channel is out of // sync to do a rejected proposal. Instead, it will verify that the channel // is out of sync by only one other type of state transition, and return // that information. After syncing with this transition, rejected proposals // should *always* be synced between participants. const { sync, setup, ...SyncableProtocols } = ProtocolNames; type SyncDetermination = { type: keyof typeof SyncableProtocols; counterpartyIsBehind: boolean; identityHash?: string; // hash of app or proposal thats out of sync // in the case of free balance sync issues, this is the hash of the // installed or uninstalled app }; function makeSyncDetermination( counterpartyData: SyncDeterminationData | undefined, // just cus types are sketch myChannel: StateChannel, appIdentityHash: HexString | undefined, // from our protocol params log: ILoggerService, ): SyncDetermination | undefined { // Get information from counterparty, and make sure it is defined. const { freeBalanceVersionNumber, numProposedApps, proposals, apps } = counterpartyData || {}; // use helper function in case the numbers are provided and 0 const exists = (val: any) => { return val !== undefined && val !== null; }; if ( !exists(freeBalanceVersionNumber) || !exists(proposals) || !exists(apps) || !exists(numProposedApps) ) { throw new Error( `Cannot make sync determination. Missing information from counterparty, got: ${stringify( counterpartyData, true, 0, )}`, ); } // Important to "prioritize" channel sync issues. The top most priority // is the discrepancy between free balance versions. This happens when // an app is installed or uninstalled *only* if (freeBalanceVersionNumber !== myChannel.freeBalance.latestVersionNumber) { // should only be able to sync from at most one of these transitions if (Math.abs(freeBalanceVersionNumber! - myChannel.freeBalance.latestVersionNumber) !== 1) { throw new Error( `Cannot sync free balance apps by more than one transition. Our nonce: ${myChannel.freeBalance.latestVersionNumber}, theirs: ${freeBalanceVersionNumber}`, ); } let counterpartyIsBehind: boolean; let type: keyof typeof SyncableProtocols; if (myChannel.freeBalance.latestVersionNumber > freeBalanceVersionNumber!) { // we are ahead, our apps are the source of truth counterpartyIsBehind = true; // if we have more apps, counterparty missed install type = myChannel.appInstances.size > apps!.length ? "install" : "uninstall"; } else { // we are behind, their apps are the source of truth counterpartyIsBehind = false; // if we have more apps, we missed install type = apps!.length > myChannel.appInstances.size ? "install" : "uninstall"; } const myApps = [...myChannel.appInstances.values()].map((app) => app.identityHash); const theirApps = apps!.map((app) => app.identityHash); const unsynced = myApps .filter((x) => !(theirApps || []).includes(x)) .concat(theirApps.filter((x) => !(myApps || []).includes(x))); if (!unsynced || unsynced.length !== 1) { throw new Error( `Could not find an unsynced app, or there was more than one. My apps: ${stringify( myApps, true, 0, )}, theirs: ${stringify(theirApps, true, 0)}`, ); } return { type, counterpartyIsBehind, identityHash: unsynced[0], }; } // Free balance apps are now in sync, so we must determine if the // proposals are in sync. Evaluate if a propose protocol was the cause of // the sync issues by using the `numProposedApps`. Both `install` and // `rejectInstall` alter the proposal array within a channel, but only errors // from a propose protocol would result in `numProposedApps` issue if (numProposedApps !== myChannel.numProposedApps) { // should only be able to sync from at most one of these transitions if (Math.abs(numProposedApps! - myChannel.numProposedApps) !== 1) { throw new Error( `Cannot sync proposed apps by more than one transition. Our nonce: ${myChannel.numProposedApps}, theirs: ${numProposedApps}`, ); } if (myChannel.numProposedApps > numProposedApps!) { const myProposals = [...myChannel.proposedAppInstances.values()].map((proposal) => { return { appSeqNo: proposal.appSeqNo, identityHash: proposal.identityHash }; }); const proposal = myProposals.find((p) => p.appSeqNo === myChannel.numProposedApps); if (!proposal) { log.error( `Could not find out of sync proposal (counterparty behind). My proposals: ${stringify( myProposals, true, 0, )}, counterparty proposals: ${stringify(proposals, true, 0)}.`, ); } return { counterpartyIsBehind: true, type: "propose", identityHash: proposal?.identityHash, }; } else if (myChannel.numProposedApps < numProposedApps!) { // we need sync from counterparty const proposal = proposals!.find((p) => p.appSeqNo === numProposedApps); if (!proposal) { log.error( `Could not find out of sync proposal (counterparty ahead). My proposals: ${stringify([ ...myChannel.proposedAppInstances.keys(), true, 0, ])}, counterparty proposals: ${stringify(proposals, true, 0)}`, ); } return { counterpartyIsBehind: false, type: "propose", identityHash: proposal?.identityHash, }; } else { throw new Error("Something is off -- not gt or lt and already checked for eq..."); } } // Now determine if any apps are out of sync from errors in the `takeAction` // protocol. This would come from a discrepancy in app version numbers. // To get to this point in the function, we know that the channel fell out of // sync while taking action on the app. This means that we *know* this app has // to be synced const sameApps = myChannel.appInstances.size === apps!.length; if (!appIdentityHash || sameApps) { // assume that there is no problem with the apps // while this is not technically true, we know that if the appId was not // provided and we are syncing on error, the retry of the fn should work return undefined; } const myApp = myChannel.appInstances.get(appIdentityHash); if (!myApp) { throw new Error( `Counterparty channel has record of app we do not (${appIdentityHash}), despite free balance nonces being in sync. Our apps: ${stringify( [...myChannel.appInstances.keys()], true, 0, )}, their apps: ${stringify(apps, true, 0)}`, ); } const counterpartyInfo = apps!.find((app) => app.identityHash === appIdentityHash); if (!counterpartyInfo) { throw new Error( `Our channel has record of app counterparty does not, despite free balance nonces being in sync. Our apps: ${stringify( [...myChannel.appInstances.keys()], true, 0, )}, their apps: ${stringify(apps, true, 0)}`, ); } if (counterpartyInfo.latestVersionNumber === myApp.latestVersionNumber) { // App + channel are not out of sync, return undefined return undefined; } return { type: "takeAction", counterpartyIsBehind: counterpartyInfo.latestVersionNumber < myApp.latestVersionNumber, identityHash: appIdentityHash, }; // TODO: should eventually allow for syncing of multiple apps, regardless of // what was passed into the sync protocol params } // what gets passed over the wire type SyncFromDataJson = { commitments: (SetStateCommitmentJSON | ConditionalTransactionCommitmentJSON)[]; affectedApp?: AppInstanceJson; // not provided iff syncing from uninstall freeBalanceApp?: AppInstanceJson; // provided iff syncing from uninstall }; async function getInfoForSync( syncType: SyncDetermination | undefined, myChannel: StateChannel, store: IStoreService, ): Promise<SyncFromDataJson> { const emptyObj = { commitments: [], }; // used if no data needed from / available for counterparty if (!syncType) { // Means that channels are not actually out of sync, return empty object return emptyObj; } const { counterpartyIsBehind, identityHash, type } = syncType; if (!counterpartyIsBehind) { // Means that counterparty needs to give us info, return empty obj return emptyObj; } // Get commitments and object for effected app const conditional = await store.getConditionalTransactionCommitment(identityHash!); const [setState] = await store.getSetStateCommitments(identityHash!); // Get data for counterparty dep. on type switch (type) { case "propose": { // send counterparty: // - set state commitment for unsynced proposal // - conditional commitment for unsynced proposal // - unsynced proposal obj const proposal = myChannel.proposedAppInstances.get(identityHash!); if (!setState || !conditional || !proposal) { return { commitments: [], affectedApp: undefined }; } return { commitments: [setState, conditional], affectedApp: proposal, }; } case "install": { // send counterparty: // - set state commitment for free balance // - unsynced app obj const app = myChannel.appInstances.get(identityHash!); const [fbCommitment] = await store.getSetStateCommitments(myChannel.freeBalance.identityHash); if (!fbCommitment) { throw new Error( `Failed to retrieve uninstall sync info for counterparty for: ${identityHash}`, ); } if (!fbCommitment || !app) { // both may be undefined IFF a proposal was rejected throw new Error( `Failed to retrieve install sync info for counterparty for: ${identityHash}. Found app: ${!!app}, found commitment: ${!!fbCommitment}`, ); } return { commitments: [fbCommitment], affectedApp: app.toJson(), }; } case "takeAction": { // send counterparty: // - set state commitment for app // - unsynced app obj const app = myChannel.appInstances.get(identityHash!); if (!setState || !app) { throw new Error( `Failed to retrieve takeAction sync info for counterparty for: ${identityHash}`, ); } return { commitments: [setState], affectedApp: app.toJson(), }; } case "uninstall": { // send counterparty: // - set state commitment for free balance // - latest free balance app (so they dont have to compute with evm) const [fbCommitment] = await store.getSetStateCommitments(myChannel.freeBalance.identityHash); if (!fbCommitment) { throw new Error( `Failed to retrieve uninstall sync info for counterparty for: ${identityHash}`, ); } return { commitments: [fbCommitment], freeBalanceApp: myChannel.freeBalance.toJson(), }; } default: { const c: never = type; throw new Error(`Unrecognized sync type: ${c}`); } } } // Updates the channel with counterparty information // Returns the updated channel, the persist type, and // the signed commitments needed to either save to the store // or validate single signed commitments async function syncChannel( context: Context, myChannel: StateChannel, type: keyof typeof SyncableProtocols, commitments: (SetStateCommitment | ConditionalTransactionCommitment)[], affectedApp: AppInstance | string, freeBalanceApp: AppInstance | undefined, log: ILoggerService, ): Promise< [ StateChannel, PersistStateChannelType, (SetStateCommitment | ConditionalTransactionCommitment)[], AppInstance?, ] // app inc. iff uninstalled > { // Verify signatures on any provided commitments await Promise.all(commitments.map((c) => c.assertSignatures())); // Update channel let updatedChannel: StateChannel; let persistType: PersistStateChannelType; let verifiedCommitments: (SetStateCommitment | ConditionalTransactionCommitment)[]; let uninstalledApp: AppInstance | undefined = undefined; // ^^ commitments in order expected by store middleware // that we have verified are contextually correct and have our sigs on them switch (type) { case "propose": { if (typeof affectedApp === "string") { throw new Error( `Received valid commitments, but no affected app for proposal sync of channel ${myChannel.multisigAddress}`, ); } if (affectedApp) { // should have received a set state and conditional tx as the commitments // and both should correspond to the effected app const setState = commitments.find( (c) => c.appIdentityHash === affectedApp.identityHash && !!c["versionNumber"] && (c as SetStateCommitment).versionNumber.eq(affectedApp.latestVersionNumber), ); const conditional = commitments.find( (c) => c.appIdentityHash === affectedApp.identityHash && !!c["freeBalanceAppIdentityHash"] && (c as ConditionalTransactionCommitment).freeBalanceAppIdentityHash === myChannel.freeBalance.identityHash, ); if (!setState || !conditional) { throw new Error( "Verified commitments are signed, but could not find one that corresponds to the effected app when syncing channel from proposal", ); } // set return values verifiedCommitments = [setState, conditional]; updatedChannel = myChannel.addProposal(affectedApp.toJson()); } else { verifiedCommitments = []; updatedChannel = myChannel.incrementNumProposedApps(); } persistType = PersistStateChannelType.SyncProposal; break; } case "install": { if (typeof affectedApp === "string") { throw new Error( `Received valid commitments, but no effected app for install sync of channel ${myChannel.multisigAddress}`, ); } persistType = PersistStateChannelType.SyncInstall; // calculate the new channel after installation // NOTE: this will NOT fail if we do not have updatedChannel = myChannel.installApp( affectedApp, getTokenBalanceDecrementForInstall(myChannel, affectedApp), ); // verify the expected commitment is included const generatedSetState = getSetStateCommitment( context.networks[myChannel.chainId], updatedChannel.freeBalance, ); const setState = commitments.find((c) => c.hashToSign === generatedSetState.hashToSign); if (!setState) { throw new Error( `Could not find commitment matching expected to sync channel with install of ${affectedApp.identityHash}`, ); } verifiedCommitments = [setState]; break; } case "takeAction": { if (typeof affectedApp === "string") { throw new Error( `Received valid commitments, but no affected app for take action sync of channel ${myChannel.multisigAddress}`, ); } const app = myChannel.appInstances.get(affectedApp.identityHash); if (!app) { throw new Error(`Channel has no record of out of sync app: ${affectedApp.identityHash}`); } const commitment = commitments.find( (c) => c.appIdentityHash === affectedApp.identityHash, ) as SetStateCommitment; // if the commitment is single signed, return only the single signed // commitment without making any updates to the channel if (commitment.signatures.filter((x) => !!x).length === 1) { updatedChannel = myChannel; verifiedCommitments = [commitment]; } else { updatedChannel = myChannel.setState( app, affectedApp.latestState, toBN(affectedApp.stateTimeout), ); const updatedApp = updatedChannel.appInstances.get(affectedApp.identityHash); if (updatedApp?.hashOfLatestState !== commitment.toJson().appStateHash) { throw new Error(`Provided set state commitment for app does not match expected`); } verifiedCommitments = [commitment]; } persistType = PersistStateChannelType.SyncAppInstances; break; } case "uninstall": { if (typeof affectedApp !== "string") { throw new Error( `Expected counterparty to return a string representing the uninstalled appId, got: ${stringify( affectedApp, true, 0, )}`, ); } if (!freeBalanceApp) { throw new Error( `Did not get updated free balance app from counterparty. NOTE: we should re-compute the state-transition here, but overall this is indicative of a different problem`, ); } // verify the expected commitment is included const setState = commitments.find((c) => { const json = c.toJson(); const isSetState = !!json["appStateHash"]; if (!isSetState) { return false; } return ( toBN((json as SetStateCommitmentJSON).versionNumber).eq( freeBalanceApp.latestVersionNumber, ) && json.appIdentityHash === freeBalanceApp.identityHash ); }); if (!setState) { throw new Error( `Could not find commitment matching expected to sync channel with uninstall of ${affectedApp}`, ); } verifiedCommitments = [setState]; updatedChannel = myChannel .removeAppInstance(affectedApp) .setFreeBalance(FreeBalanceClass.fromAppInstance(freeBalanceApp)); persistType = PersistStateChannelType.SyncUninstall; uninstalledApp = myChannel.appInstances.get(affectedApp); break; } default: { const c: never = type; throw new Error(`Could not create updated channel, unrecognized sync type: ${c}`); } } return [updatedChannel, persistType, verifiedCommitments, uninstalledApp]; } function syncRejectedApps( myChannel: StateChannel, counterpartyProposals: string[] = [], ): [StateChannel, AppInstance[]] { const myProposals = [...myChannel.proposedAppInstances.keys()]; // find any rejected proposals and update your channel const rejectedIds = myProposals .filter((x) => !counterpartyProposals.includes(x)) .concat(counterpartyProposals.filter((x) => !myProposals.includes(x))); let postRejectChannel = StateChannel.fromJson(myChannel.toJson()); const rejected: AppInstance[] = []; rejectedIds.forEach((identityHash) => { const proposal = postRejectChannel.proposedAppInstances.get(identityHash); if (!proposal) { return; } rejected.push(AppInstance.fromJson(proposal)); postRejectChannel = postRejectChannel.removeProposal(identityHash); }); return [postRejectChannel, rejected]; }
the_stack
import {Base64} from 'js-base64'; import * as helpers from '../../src/utils/helpers'; import {CategoryType} from '../../src/templates/category'; import {PostType} from '../../src/fragments/post'; // I HAVE NO IDEA WHAT THESE CHINESE WORDS MEAN. NO HATE PLEASE! :) test('[slugify] non-latin characters are not stripped out', () => { expect(helpers.slugify('寻找罪魁祸首')).toBe('寻找罪魁祸首'); }); test('[slugify] multiple repetitive dashes should be replaced with a single one', () => { expect(helpers.slugify('寻-找-罪--魁-祸首')).toBe('寻-找-罪-魁-祸首'); }); test('[slugify] non-word characters should be filtered out', () => { expect(helpers.slugify('寻!-找-$罪--魁-祸首@')).toBe('寻-找-罪-魁-祸首'); }); test('[slugify] dashes should be trimmed from start or finish', () => { expect(helpers.slugify('-寻!-找-$罪--魁-祸首@-')).toBe('寻-找-罪-魁-祸首'); }); test('[slugify] spaces should be trimmed from start or finish', () => { expect(helpers.slugify(' -寻!-找-$罪--魁-祸首@- ')).toBe('寻-找-罪-魁-祸首'); }); test('[Base64] should encode without errors', () => { expect(Base64.encode('寻找罪魁祸首')).toBe('5a+75om+572q6a2B56W46aaW'); expect(Base64.encode( '{"title":"Get a quality microphone","type":"secondary"}')).toBe( 'eyJ0aXRsZSI6IkdldCBhIHF1YWxpdHkgbWljcm9waG9uZSIsInR5cGUiOiJzZWNvbmRhcnkifQ==', ); }); test('[Base64] should decode without errors', () => { expect(Base64.decode('5a+75om+572q6a2B56W46aaW')).toBe('寻找罪魁祸首'); expect(Base64.decode( 'eyJ0aXRsZSI6IkdldCBhIHF1YWxpdHkgbWljcm9waG9uZSIsInR5cGUiOiJzZWNvbmRhcnkifQ==')).toBe( '{"title":"Get a quality microphone","type":"secondary"}', ); }); test('[Base64] encodes and decodes with same result', () => { const input = `寻找罪魁祸首-我一得到任何消息,就立刻给你发短信`; const output = `5a+75om+572q6a2B56W46aaWLeaIkeS4gOW+l+WIsOS7u+S9lea2iOaBr++8jOWwseeri+WIu+e7meS9oOWPkeefreS/oQ==`; expect(Base64.encode(input)).toBe(output); expect(Base64.decode(output)).toBe(input); }); test('[normalizeCfgPath] should return an array if a string is passed', () => { expect(helpers.normalizeCfgPath('a')).toEqual(['a']); }); test('[extractNodesFromEdges] should extract nodes from...yeah...edges', () => { expect(helpers.extractNodesFromEdges([{ node: 'foo', }])).toEqual(['foo']); expect(helpers.extractNodesFromEdges([{ node: { foo: ['bar'], }, }], 'foo')).toEqual(['bar']); }); test('[readingTime] should return proper values', () => { expect(helpers.readingTime('a')).toEqual({ 'minutes': 0.002, 'text' : 'less than a minute read', 'time' : 120, 'words' : 1, }); expect(helpers.readingTime('寻找罪魁祸首')).toEqual({ 'minutes': 0.002, 'text' : 'less than a minute read', 'time' : 120, 'words' : 1, }); let longT = ''; for (let i = 0; i < 900; i++) { longT += `\nIn the last delivery (2.2.1) a correction was made on the index.d.ts which is making the Typescript import`; } expect(helpers.readingTime(longT)).toEqual({ 'minutes': 32.402, 'text' : '32 min. read', 'time' : 1944120.0000000002, 'words' : 16201, }); let utfLongT = ''; for (let i = 0; i < 900; i++) { utfLongT += `\n寻找罪魁祸首 寻找罪魁祸首 寻找罪魁祸首 寻找罪魁祸首 寻找罪魁祸首 寻找罪魁祸首 寻找罪魁祸首 寻找罪魁祸首 寻找罪魁祸首 寻找罪魁祸首`; } expect(helpers.readingTime(utfLongT)).toEqual({ 'minutes': 18, 'text' : '18 min. read', 'time' : 1080000, 'words' : 9000, }); }); test('[lineRepresentsEncodedComponent] should should detect encoded component', () => { const l = `{"widget":"qards-section-heading","config":"eyJ0aXRsZSI6IkF1ZGlvIHBsYXlsaXN0Iiwic3VidGl0bGUiOiJBbiBhdWRpbyBwbGF5bGlzdCBjYW4gY29udGFpbiBvbmUgb3IgbXVsdGlwbGUgYXVkaW8gZmlsZXMiLCJ0eXBlIjoicHJpbWFyeSJ9"}`; expect(helpers.lineRepresentsEncodedComponent(l)).toBe(true); expect(helpers.lineRepresentsEncodedComponent(`-${l}`)).toBe(true); }); test('[getPostPrimaryHeadings] should return primary headings', () => { const md = ` {"widget":"qards-section-heading","config":"eyJ0aXRsZSI6IkF1ZGlvIHBsYXlsaXN0Iiwic3VidGl0bGUiOiJBbiBhdWRpbyBwbGF5bGlzdCBjYW4gY29udGFpbiBvbmUgb3IgbXVsdGlwbGUgYXVkaW8gZmlsZXMiLCJ0eXBlIjoicHJpbWFyeSJ9"} {"widget":"qards-section-heading","config":"eyJ0aXRsZSI6IkF1ZGlvIHBsYXlsaXN0Iiwic3VidGl0bGUiOiJBbiBhdWRpbyBwbGF5bGlzdCBjYW4gY29udGFpbiBvbmUgb3IgbXVsdGlwbGUgYXVkaW8gZmlsZXMiLCJ0eXBlIjoicHJpbWFyeSJ9"} `; expect(helpers.getPostPrimaryHeadings(md).length).toBe(2); }); test('[tokenizePost] should replace specified tokens with provided values', () => { let p: PostType = { id : 'test', frontmatter: { title : 'test', created_at: new Date().toUTCString(), excerpt : 'test', hero : { alt : 'test', image: { thumb: { alt: 'asd', }, sharp: { alt: 'asd', }, }, }, isFeatured: false, isPage : false, meta : { description: '', keywords : '', }, showAuthor: true, tags : ['asd'], }, authors : [], categories : [], fields : { audios : [], galleries: [], images : [], slug : 'asd', }, md : '', html : '', references : [], }; expect(helpers.tokenizePost(p)).toEqual(p); p.frontmatter.title = '{cardsNum} number of cards'; expect(helpers.tokenizePost(p).frontmatter.title).toEqual('0 number of cards'); p.frontmatter.title = '{cardsNum} number of cards'; p.frontmatter.excerpt = '{cardsNum} number of cards'; p.md = ` {"widget":"qards-section-heading","config":"eyJ0aXRsZSI6IkF1ZGlvIHBsYXlsaXN0Iiwic3VidGl0bGUiOiJBbiBhdWRpbyBwbGF5bGlzdCBjYW4gY29udGFpbiBvbmUgb3IgbXVsdGlwbGUgYXVkaW8gZmlsZXMiLCJ0eXBlIjoicHJpbWFyeSJ9"} {"widget":"qards-section-heading","config":"eyJ0aXRsZSI6IkF1ZGlvIHBsYXlsaXN0Iiwic3VidGl0bGUiOiJBbiBhdWRpbyBwbGF5bGlzdCBjYW4gY29udGFpbiBvbmUgb3IgbXVsdGlwbGUgYXVkaW8gZmlsZXMiLCJ0eXBlIjoicHJpbWFyeSJ9"} `; expect(helpers.tokenizePost(p).frontmatter.title).toBe('2 number of cards'); expect(helpers.tokenizePost(p).frontmatter.excerpt).toBe('2 number of cards'); p.frontmatter.title = '{createdAt:yyyy} is the year the article was written'; p.frontmatter.excerpt = '{createdAt:yyyy} is the year the article was written'; expect(helpers.tokenizePost(p).frontmatter.title).toBe('2019 is the year the article was written'); expect(helpers.tokenizePost(p).frontmatter.excerpt).toBe('2019 is the year the article was written'); p.frontmatter.title = '{currentDate:yyyy} is current year'; p.frontmatter.excerpt = '{currentDate:yyyy} is current year'; expect(helpers.tokenizePost(p).frontmatter.title).toBe('2019 is current year'); expect(helpers.tokenizePost(p).frontmatter.excerpt).toBe('2019 is current year'); }); test('[getPopularCategories] should return categories ordered by occurence', () => { const c1 = { id : 'test', fields : { slug: 'test', }, frontmatter: { excerpt: 'test', title : 'test', }, }; const c2 = { id : 'test2', fields : { slug: 'test2', }, frontmatter: { excerpt: 'test2', title : 'test2', }, }; const c3 = { id : 'test3', fields : { slug: 'test3', }, frontmatter: { excerpt: 'test3', title : 'test3', }, }; const categories: CategoryType[] = [c1, c2, c3, c1, c1, c3]; // We expect them to be ordered by occurences descending expect(helpers.getPopularCategories(categories)).toEqual([{ category : c1, occurence: 3, }, { category : c3, occurence: 2, }, { category : c2, occurence: 1, }]); }); // getThemeConfig test('[getThemeConfig] should return the requested value', () => { expect(helpers.getThemeConfig(['colors', 'intents', 'success', 'text'])).toBe('#2fb57d'); expect(helpers.getThemeConfig(['colors', 'intents', 'success', 'background'])).toBe('#B5F3D9'); expect(helpers.getThemeConfig(['colors', 'intents', 'warning', 'text'])).toBe('#ffa000'); expect(helpers.getThemeConfig(['colors', 'intents', 'warning', 'background'])).toBe('#FFECCE'); expect(helpers.getThemeConfig(['colors', 'intents', 'danger', 'text'])).toBe('#f74444'); expect(helpers.getThemeConfig(['colors', 'intents', 'danger', 'background'])).toBe('#FFD9D9'); expect(helpers.getThemeConfig(['colors', 'primary', 'text'])).toBe('#ffffff'); expect(helpers.getThemeConfig(['colors', 'primary', 'background'])).toBe('#192633'); expect(helpers.getThemeConfig(['colors', 'secondary', 'text'])).toBe('#192531'); expect(helpers.getThemeConfig(['colors', 'secondary', 'background'])).toBe('#becbd4'); expect(helpers.getThemeConfig(['colors', 'accent', 'text'])).toBe('#ffffff'); expect(helpers.getThemeConfig(['colors', 'accent', 'background'])).toBe('#3ea38f'); expect(helpers.getThemeConfig(['colors', 'secondaryAccent', 'text'])).toBe('#ffffff'); expect(helpers.getThemeConfig(['colors', 'secondaryAccent', 'background'])).toBe('#F432AC'); expect(helpers.getThemeConfig(['colors', 'faded', 'text'])).toBe('#192533'); expect(helpers.getThemeConfig(['colors', 'faded', 'background'])).toBe('#ecf0f3'); expect(helpers.getThemeConfig(['colors', 'text'])).toBe('#2c2c2c'); expect(helpers.getThemeConfig(['colors', 'lightText'])).toBe('#5a6c7a'); expect(helpers.getThemeConfig(['colors', 'borders'])).toBe('#dde6eb'); expect(helpers.getThemeConfig(['colors']).keySeq().toArray().length).toBe(9); expect(helpers.getThemeConfig(['colors', 'intents']).keySeq().toArray().length).toBe(3); expect(helpers.getThemeConfig(['colors', 'intents', 'success']).keySeq().toArray().length).toBe(2); expect(helpers.getThemeConfig(['colors', 'intents', 'warning']).keySeq().toArray().length).toBe(2); expect(helpers.getThemeConfig(['colors', 'intents', 'danger']).keySeq().toArray().length).toBe(2); expect(helpers.getThemeConfig(['colors', 'primary']).keySeq().toArray().length).toBe(2); expect(helpers.getThemeConfig(['colors', 'secondary']).keySeq().toArray().length).toBe(2); expect(helpers.getThemeConfig(['colors', 'accent']).keySeq().toArray().length).toBe(2); expect(helpers.getThemeConfig(['colors', 'secondaryAccent']).keySeq().toArray().length).toBe(2); expect(helpers.getThemeConfig(['colors', 'secondaryAccent']).keySeq().toArray().length).toBe(2); expect(helpers.getThemeConfig(['colors', 'faded']).keySeq().toArray().length).toBe(2); }); test('[getThemeConfig] should return a provided default if requested not available', () => { expect(helpers.getThemeConfig('foobar', 'bar')).toBe('bar'); }); test('[getThemeConfig] should accept array or string', () => { expect(helpers.getThemeConfig('colors').keySeq().toArray().length).toBe(9); expect(helpers.getThemeConfig(['colors']).keySeq().toArray().length).toBe(9); }); // getPostsConfig test('[getPostsConfig] should return the requested value', () => { expect(helpers.getPostsConfig(['frontLimit'])).toBe(12); expect(helpers.getPostsConfig(['progressShow'])).toBe(true); expect(helpers.getPostsConfig(['tocShow'])).toBe(true); expect(helpers.getPostsConfig(['socialShow'])).toBe(true); expect(helpers.getPostsConfig(['subscribeShow'])).toBe(true); expect(helpers.getPostsConfig(['slugStructure'])).toBe('{{slug}}'); expect(helpers.getPostsConfig(['pathPrefix'])).toBe('/posts'); }); test('[getPostsConfig] should accept array or string', () => { expect(helpers.getPostsConfig('frontLimit')).toBe(12); expect(helpers.getPostsConfig(['frontLimit'])).toBe(12); }); test('[getPostsConfig] should return a provided default if requested not available', () => { expect(helpers.getPostsConfig('foobar', 'bar')).toBe('bar'); }); // getSettingsConfig test('[getSettingsConfig] should return the requested value', () => { expect(helpers.getSettingsConfig(['name'])).toBe('qards'); expect(helpers.getSettingsConfig(['title'])).toBe('Qards - the blogging platform for professionals'); expect(helpers.getSettingsConfig(['excerpt'])).toBe('Qards is a blogging platform for professionals'); expect(helpers.getSettingsConfig(['baseUrl'])).toBe('https://affectionate-hamilton-12254a.netlify.com'); expect(helpers.getSettingsConfig(['performanceMode'])).toBe(false); expect(helpers.getSettingsConfig(['logo'])).toBe('/images/uploads/logo.png'); expect(helpers.getSettingsConfig(['socialShareImg'])).toBe('/images/uploads/andrew-ridley-76547-unsplash.jpg'); expect(helpers.getSettingsConfig(['typography', 'fontSize'])).toBe('15px'); expect(helpers.getSettingsConfig(['typography', 'bodyFontFamily'])).toBe('Roboto'); expect(helpers.getSettingsConfig(['typography', 'baseLineHeight'])).toBe(1); expect(helpers.getSettingsConfig(['typography', 'headerFontFamily'])).toBe('Roboto'); expect(helpers.getSettingsConfig(['typography', 'npmPackage'])).toBe('typeface-roboto'); expect(helpers.getSettingsConfig(['fallbackFont'])).toBe('arial'); }); test('[getSettingsConfig] should accept array or string', () => { expect(helpers.getSettingsConfig('fallbackFont')).toBe('arial'); expect(helpers.getSettingsConfig(['fallbackFont'])).toBe('arial'); }); test('[getSettingsConfig] should return a provided default if requested not available', () => { expect(helpers.getSettingsConfig('foobar', 'bar')).toBe('bar'); }); // getPluginsConfig test('[getPluginsConfig] should return the requested value', () => { expect(helpers.getPluginsConfig(['tracking', 'enable'])).toBe(false); expect(helpers.getPluginsConfig(['tracking', 'analytics', 'trackingId'])).toBe(''); expect(helpers.getPluginsConfig(['emailSubscribers', 'enable'])).toBe(false); expect(helpers.getPluginsConfig(['emailSubscribers', 'mailchimp', 'endpoint'])).toBe(''); expect(helpers.getPluginsConfig(['disqus', 'enable'])).toBe(false); expect(helpers.getPluginsConfig(['disqus', 'shortname'])).toBe(''); expect(helpers.getPluginsConfig(['rssFeed', 'enable'])).toBe(true); expect(helpers.getPluginsConfig(['search', 'enable'])).toBe(false); expect(helpers.getPluginsConfig(['search', 'algolia', 'appId'])).toBe(''); expect(helpers.getPluginsConfig(['search', 'algolia', 'indexName'])).toBe(''); expect(helpers.getPluginsConfig(['search', 'algolia', 'searchKey'])).toBe(''); }); test('[getPluginsConfig] should accept array or string', () => { expect(helpers.getPluginsConfig(['rssFeed']).get('enable')).toBe(true); expect(helpers.getPluginsConfig('rssFeed').get('enable')).toBe(true); }); test('[getPluginsConfig] should return a provided default if requested not available', () => { expect(helpers.getPluginsConfig('foobar', 'bar')).toBe('bar'); });
the_stack
import * as cheerio from "cheerio"; import * as querystring from "querystring"; import {ParsedUrlQuery} from "querystring"; import {BoxingBoutOutcome} from "./boxrec-pages/event/boxrec.event.constants"; /** * Converts fractional symbols into decimals * @param {string} fraction * @returns {number} */ export function convertFractionsToNumber(fraction: string): number { switch (fraction) { case "&#xBC;": case "¼": return .25; case "&#xBD;": case "½": return .5; case "&#xBE;": case "¾": return .75; default: return 0; } } /** * Removes whitespace at the start and end of the string, remove line breaks and removes occurrences where multiple spaces occur * @param {string} str * @returns {string} */ export function trimRemoveLineBreaks(str: string): string { return str.trim().replace(/(?:\r\n|\r|\n)/g, "").replace(/\s{2,}/g, " "); } /** * Changes a string to camelCase * @param {string} str * @example "foo bar" becomes "fooBar" * @returns {string} */ export function changeToCamelCase(str: string): string { const camelCaseStr: string = str.replace(/\s(\w)/g, x => x[1].toUpperCase()); return `${camelCaseStr.charAt(0).toLowerCase()}${camelCaseStr.slice(1)}`; } /** * Takes CheerioStatic and tries to find column data by finding the table header index and then gets that columns data * Nice thing about this is that if the column number changes, the data will not fail and tests will pass * Don't throw errors inside otherwise it blows up when retrieving all data * @param $ the cheerio static item that will have the "mock" fake table row * @param tableColumnsArr contains the name of the table headers * @param columnHeaderText the header text we are searching for, throws error if it cannot find it todo make type * @param returnHTML */ export function getColumnDataByColumnHeader($: CheerioStatic, tableColumnsArr: string[], columnHeaderText: BoxrecCommonTableHeader, returnHTML: boolean = true) : string { const tableEl: Cheerio = $($("<div>").append($("table").clone()).html()); const idx: number = tableColumnsArr.findIndex(item => item === columnHeaderText); /*if (idx === -1) { throw new Error(`Could not find the column header in the array: ${tableColumnsArr}, ${columnHeaderText}`); }*/ if (idx > -1) { const el: Cheerio = tableEl.find(`tr:nth-child(1) td:nth-child(${idx + 1})`); /*if (!el.length) { throw new Error(`Tried to get column data for column that doesn't exist, but existed in array?: ${columnHeaderText}`); }*/ if (returnHTML) { const html: string | null = el.html(); if (html) { return trimRemoveLineBreaks(html); } return ""; } return trimRemoveLineBreaks(el.text()); } return ""; } /** * Common table header text that is used to quickly find data if the column number changes or the header name changes * synthetic headers don't actually exist but are used to classify a column as that type of data */ export enum BoxrecCommonTableHeader { age = "age", career = "career", date = "date", day = "day", debut = "debut", // manager boxers division = "division", fighter = "fighter", // first boxer firstLast6 = "firstLast6", firstFighterWeight = "firstFighterWeight", // synthetic, no actual table header. Is the first occurrence of "lbs" firstRating = "firstRating", // synthetic, is the first fighter rating links = "links", // synthetic, no actual table header location = "location", miles = "miles", name = "name", outcome = "outcome", opponent = "opponent", // second boxer outcomeByWayOf = "outcomeByWayOf", // synthetic, this is the outcome like TKO/KO/SD etc. points = "points", rating = "rating", // synthetic, no actual table header. Is the rating of the bout/event residence = "residence", result = "result", // similar to outcome // todo can they be merged? rounds = "rounds", secondLast6 = "secondLast6", secondFighterWeight = "secondFighterWeight", // synthetic, no actual table header. Is the second occurrence of "lbs" secondRating = "secondRating", // synthetic, is the second fighter rating secondRecord = "secondw-l-d", // on certain pages there are multiple records sport = "sport", stance = "stance", record = "w-l-d", sex = "sex", tick = "tick", // this is purposeless column at this time, it shows whether a fight has occurred or not venue = "venue" } export function getValueForHeadersArr(headersArr: string[], firstValue: BoxrecCommonTableHeader, secondValue: BoxrecCommonTableHeader): any { const hasRecord: boolean = headersArr.some(item => item === firstValue); if (hasRecord) { return secondValue; } return firstValue; } /** * Returns an array of all row data from a specific column * @param tableEl the table element to check from * @param columnNumber the column number to get the data * @param returnHTML optionally return the full HTML of the column */ export function getTableColumnData(tableEl: Cheerio, columnNumber: number = 1, returnHTML: boolean = false): string[] { const arr: string[] = []; tableEl.clone().find(`tbody tr`).each(function(this: CheerioElement, i, elem): void { const $: CheerioStatic = cheerio.load(elem); const tdColumn: Cheerio = $(this).find(`td:nth-child(${columnNumber})`); const data: string | null = returnHTML ? tdColumn.html() : tdColumn.text(); if (data) { arr.push(trimRemoveLineBreaks(stripArrows(data))); } }); return arr; } /** * Takes a table element, clones it and then reads the thead column text and returns an array * @param tableEl * @param theadNumber Some tables have more than 1 thead tag */ // todo complex export function getHeaderColumnText(tableEl: Cheerio, theadNumber: number = 1): BoxrecCommonTableHeader[] { const headersArr: BoxrecCommonTableHeader[] = []; // we clone because it modifies the passed in element when we use map tableEl.clone().find(`thead:nth-child(${theadNumber}) th`) // tslint:disable-next-line .each(function(this: CheerioElement, i, elem): void { const $: CheerioStatic = cheerio.load(elem); // replace all non-alphanumeric characters so we don't include "sort arrows" from dataTables const headerText: string = trimRemoveLineBreaks(stripArrows($(this).text())); // get the "direct" tbody column element for further analysing. Not always necessary /*const tbodyColumnEl: Cheerio = tableEl .find(`> tbody tr:nth-child(1) td:nth-child(${i + 1})`);*/ const tbodyColumnEl: Cheerio = tableEl.clone().find(`> tbody tr:nth-child(1) td:nth-child(${i + 1})`); // take the first rows data and get the text. Some of the columns that don't have headers we can read the // text and proceed to figure out what the column is // todo this is not done right, it brings back too many values as one string const rowDataText: string = trimRemoveLineBreaks(tbodyColumnEl.text()); // some of the columns do not have table header text // therefore try to figure out what the column is if (headerText.length === 0) { // check if rating column if (tbodyColumnEl.find(".starRating").length) { headersArr.push(BoxrecCommonTableHeader.rating); return; } if (tbodyColumnEl.find(".tick").length) { headersArr.push(BoxrecCommonTableHeader.tick); return; } // check if is a column with links if (tbodyColumnEl.find("a[href*='/event/']").length) { headersArr.push(BoxrecCommonTableHeader.links); return; } // check if outcome/results if (tbodyColumnEl.find(".boutResult").length) { headersArr.push(BoxrecCommonTableHeader.outcome); return; } // check if location (on profiles, it doesn't have a location header text) if (tbodyColumnEl.find(".flag").length) { headersArr.push(BoxrecCommonTableHeader.location); return; } if (rowDataText.length > 0 && !isNaN(rowDataText as unknown as number) || /[¼½¾]/.test(rowDataText)) { headersArr.push(getValueForHeadersArr(headersArr, BoxrecCommonTableHeader.firstFighterWeight, BoxrecCommonTableHeader.secondFighterWeight)); return; } if ($(`<div>${tbodyColumnEl.html()}</div>`).find(".personLink").length === 1) { headersArr.push(getValueForHeadersArr(headersArr, BoxrecCommonTableHeader.fighter, BoxrecCommonTableHeader.opponent)); return; } // todo remove this // throw new Error("Should not be here"); } // some headers have "lbs" and "kilos" where the referee page just had "lbs" // todo maybe this should be more strict and check for symbols if (headerText.includes("lbs") || headerText.includes("kilos")) { headersArr.push(getValueForHeadersArr(headersArr, BoxrecCommonTableHeader.firstFighterWeight, BoxrecCommonTableHeader.secondFighterWeight)); return; } if (headerText === "w-l-d") { headersArr.push(getValueForHeadersArr(headersArr, BoxrecCommonTableHeader.record, BoxrecCommonTableHeader.secondRecord)); return; } // some headings occur twice but we're expecting that, to differentiate what the column is // we give it a different label in our array if (headerText === "last 6") { const hasFirstFighterLast6: boolean = headersArr.some(item => item === BoxrecCommonTableHeader.firstLast6); if (hasFirstFighterLast6) { headersArr.push(BoxrecCommonTableHeader.secondLast6); } else { headersArr.push(BoxrecCommonTableHeader.firstLast6); } return; } // so boxer profiles have "3" ratings. The first fighter rating change, the second fighter rating change // and the rating of the bout. The following tries to figure out if it's one of the first two if (headerText === "rating" && rowDataText.includes("➞")) { const hasFirstRating: boolean = headersArr.some(item => item === BoxrecCommonTableHeader.firstRating); if (hasFirstRating) { headersArr.push(BoxrecCommonTableHeader.secondRating); } else { headersArr.push(BoxrecCommonTableHeader.firstRating); } return; } // as a last resort, if the header text is empty, we'll try to parse the row data and // see if we can figure out what column it is // todo what's the difference between this and headerText.length === 0 above? if (headerText === "") { const tableDataRows: string[] = getTableColumnData(tableEl, i + 1); const uniqueVals: string[] = tableDataRows .filter((elemItem: string, pos: number, arr: string[]) => arr.indexOf(elemItem) === pos); // test if is outcome const outcomeKeys: string[] = Object.keys(BoxingBoutOutcome); const numberOfOccurrences: number[] = uniqueVals.map(item => outcomeKeys.findIndex(k => k === item)); if (numberOfOccurrences.length) { const totalOccurrences: number = numberOfOccurrences.reduce((acc, curValue) => acc + curValue); // check the total occurrences if (totalOccurrences > 0) { headersArr.push(BoxrecCommonTableHeader.outcomeByWayOf); return; } } } headersArr.push(headerText as BoxrecCommonTableHeader); return; }); return headersArr; } // the following regex assumes the string is always in the same format // `region` and `town` are wrapped with a conditional statement // in some instances the URL just contains ex. `?country=US` // `region` can be numeric but is often alphanumeric export const townRegionCountryRegex: RegExp = /\?country=([A-Za-z]+)(?:(?:&|&amp;)region=([A-Za-z0-9]*))?(?:(?:&|&amp;)town=(\d+))?/; /** * Strips the commas out of a string. Used for strings that are large numbers * @param {string} str * @returns {string} */ export const stripCommas: (str: string) => string = (str: string): string => str.replace(/,/g, ""); /** * Strips the dataTable arrows from table headers * @param str */ export const stripArrows: (str: string) => string = (str: string): string => str.replace(/[↕↓↑]/g, ""); export const whatTypeOfLink: (href: string) => "town" | "region" | "country" = (href: string): "town" | "region" | "country" => { const matches: RegExpMatchArray | null = href.match(/(\w+)\=(\w+)/g); const locationObj: any = { country: null, region: null, town: null, }; if (matches) { for (const match of matches) { const splitQuery: ParsedUrlQuery = querystring.parse(match); const arr: string[] = Object.keys(splitQuery).map(x => [x, splitQuery[x]])[0] as any; locationObj[arr[0]] = arr[1]; } } if (locationObj.country && locationObj.region && locationObj.town) { return "town"; } else if (locationObj.country && locationObj.region) { return "region"; } return "country"; }; export const getLocationValue: (href: string, type: "town" | "region" | "country") => string | number | null = (href: string, type: "town" | "region" | "country"): string | number | null => { const matches: RegExpMatchArray | null = href.match(/(\w+)=(\w+)/g); if (matches) { for (const match of matches) { const splitQuery: ParsedUrlQuery = querystring.parse(match); const keys: string[] = Object.keys(splitQuery); if (keys[0] === type) { return splitQuery[keys[0]] as any; } } } return null; }; // replaces short division with full ex. Middle Title -> Middleweight Title // ex. World Boxing Council World Middle Title -> World Boxing Council World Middleweight Title export const replaceWithWeight: (str: string) => string = (str: string) => trimRemoveLineBreaks(str).replace(/(\w+)\sTitle$/i, "$1weight Title"); export const parseHeight: (height: string | void) => number[] | null = (height: string | void): number[] | null => { if (height) { // helps simplify the regex // remove `&nbsp;` // height = height.replace(/&#xA0;/g, ""); let regex: RegExp = /^(\d)\′\s(\d+)(½)?\″\s+\/\s+(\d{3})cm$/; if (height.includes("#x2032")) { regex = /^(\d)\&\#x2032\;\s(\d{1,2})(\&\#xB[CDE]\;)?\&\#x2033\;\s\&\#xA0\;\s\/\s\&\#xA0\;\s(\d{3})cm$/; } const heightMatch: RegExpMatchArray | null = height.match(regex); if (heightMatch) { const [, imperialFeet, imperialInches, fractionInches, metric] = heightMatch; let formattedImperialInches: number = parseInt(imperialInches, 10); formattedImperialInches += convertFractionsToNumber(fractionInches); return [ parseInt(imperialFeet, 10), formattedImperialInches, parseInt(metric, 10), ]; } } return null; };
the_stack
import { get, isEmpty } from 'lodash'; import { DOMRectLikeType } from '../utils/dom'; import BaseFoundation, { DefaultAdapter } from '../base/foundation'; import { ArrayElement } from '../utils/type'; import { strings } from './constants'; const REGS = { TOP: /top/i, RIGHT: /right/i, BOTTOM: /bottom/i, LEFT: /left/i, }; const defaultRect = { left: 0, top: 0, height: 0, width: 0, scrollLeft: 0, scrollTop: 0, }; export interface TooltipAdapter<P = Record<string, any>, S = Record<string, any>> extends DefaultAdapter<P, S> { registerPortalEvent(portalEventSet: any): void; unregisterPortalEvent(): void; registerResizeHandler(onResize: () => void): void; unregisterResizeHandler(onResize?: () => void): void; on(arg0: string, arg1: () => void): void; notifyVisibleChange(isVisible: any): void; getPopupContainerRect(): PopupContainerDOMRect; containerIsBody(): boolean; off(arg0: string): void; canMotion(): boolean; registerScrollHandler(arg: () => Record<string, any>): void; unregisterScrollHandler(): void; insertPortal(...args: any[]): void; removePortal(...args: any[]): void; getEventName(): { mouseEnter: string; mouseLeave: string; mouseOut: string; mouseOver: string; click: string; focus: string; blur: string; keydown: string; }; registerTriggerEvent(...args: any[]): void; getTriggerBounding(...args: any[]): DOMRect; getWrapperBounding(...args: any[]): DOMRect; setPosition(...args: any[]): void; togglePortalVisible(...args: any[]): void; registerClickOutsideHandler(...args: any[]): void; unregisterClickOutsideHandler(...args: any[]): void; unregisterTriggerEvent(): void; containerIsRelative(): boolean; containerIsRelativeOrAbsolute(): boolean; getDocumentElementBounding(): DOMRect; updateContainerPosition(): void; updatePlacementAttr(placement: Position): void; getContainerPosition(): string; getFocusableElements(node: any): any[]; getActiveElement(): any; getContainer(): any; setInitialFocus(): void; notifyEscKeydown(event: any): void; getTriggerNode(): any; setId(): void; } export type Position = ArrayElement<typeof strings.POSITION_SET>; export interface PopupContainerDOMRect extends DOMRectLikeType { scrollLeft?: number; scrollTop?: number; } export default class Tooltip<P = Record<string, any>, S = Record<string, any>> extends BaseFoundation<TooltipAdapter<P, S>, P, S> { _timer: ReturnType<typeof setTimeout>; _mounted: boolean; constructor(adapter: TooltipAdapter<P, S>) { super({ ...adapter }); this._timer = null; } init() { const { wrapperId } = this.getProps(); this._mounted = true; this._bindEvent(); this._shouldShow(); this._initContainerPosition(); if (!wrapperId) { this._adapter.setId(); } } destroy() { this._mounted = false; this._unBindEvent(); } _bindEvent() { const trigger = this.getProp('trigger'); // get trigger type const { triggerEventSet, portalEventSet } = this._generateEvent(trigger); this._bindTriggerEvent(triggerEventSet); this._bindPortalEvent(portalEventSet); this._bindResizeEvent(); } _unBindEvent() { this._unBindTriggerEvent(); this._unBindPortalEvent(); this._unBindResizeEvent(); this._unBindScrollEvent(); } _bindTriggerEvent(triggerEventSet: Record<string, any>) { this._adapter.registerTriggerEvent(triggerEventSet); } _unBindTriggerEvent() { this._adapter.unregisterTriggerEvent(); } _bindPortalEvent(portalEventSet: Record<string, any>) { this._adapter.registerPortalEvent(portalEventSet); } _unBindPortalEvent() { this._adapter.unregisterPortalEvent(); } _bindResizeEvent() { this._adapter.registerResizeHandler(this.onResize); } _unBindResizeEvent() { this._adapter.unregisterResizeHandler(this.onResize); } _reversePos(position = '', isVertical = false) { if (isVertical) { if (REGS.TOP.test(position)) { return position.replace('top', 'bottom').replace('Top', 'Bottom'); } else if (REGS.BOTTOM.test(position)) { return position.replace('bottom', 'top').replace('Bottom', 'Top'); } } else if (REGS.LEFT.test(position)) { return position.replace('left', 'right').replace('Left', 'Right'); } else if (REGS.RIGHT.test(position)) { return position.replace('right', 'left').replace('Right', 'Left'); } return position; } clearDelayTimer() { if (this._timer) { clearTimeout(this._timer); this._timer = null; } } _generateEvent(types: ArrayElement<typeof strings.TRIGGER_SET>) { const eventNames = this._adapter.getEventName(); const triggerEventSet = { // bind esc keydown on trigger for a11y [eventNames.keydown]: (event) => { this._handleTriggerKeydown(event); }, }; let portalEventSet = {}; switch (types) { case 'focus': triggerEventSet[eventNames.focus] = () => { this.delayShow(); }; triggerEventSet[eventNames.blur] = () => { this.delayHide(); }; portalEventSet = triggerEventSet; break; case 'click': triggerEventSet[eventNames.click] = () => { // this.delayShow(); this.show(); }; portalEventSet = {}; // Click outside needs special treatment, can not be directly tied to the trigger Element, need to be bound to the document break; case 'hover': triggerEventSet[eventNames.mouseEnter] = () => { // console.log(e); this.setCache('isClickToHide', false); this.delayShow(); // this.show('trigger'); }; triggerEventSet[eventNames.mouseLeave] = () => { // console.log(e); this.delayHide(); // this.hide('trigger'); }; // bind focus to hover trigger for a11y triggerEventSet[eventNames.focus] = () => { this.delayShow(); }; triggerEventSet[eventNames.blur] = () => { this.delayHide(); }; portalEventSet = { ...triggerEventSet }; if (this.getProp('clickToHide')) { portalEventSet[eventNames.click] = () => { this.setCache('isClickToHide', true); this.hide(); }; portalEventSet[eventNames.mouseEnter] = () => { if (this.getCache('isClickToHide')) { return; } this.delayShow(); }; } break; case 'custom': // when trigger type is 'custom', no need to bind eventHandler // show/hide completely depend on props.visible which change by user break; default: break; } return { triggerEventSet, portalEventSet }; } onResize = () => { // this.log('resize'); // rePosition when window resize this.calcPosition(); }; _shouldShow() { const visible = this.getProp('visible'); if (visible) { this.show(); } else { // this.hide(); } } delayShow = () => { const mouseEnterDelay: number = this.getProp('mouseEnterDelay'); this.clearDelayTimer(); if (mouseEnterDelay > 0) { this._timer = setTimeout(() => { this.show(); this.clearDelayTimer(); }, mouseEnterDelay); } else { this.show(); } }; show = () => { const content = this.getProp('content'); const trigger = this.getProp('trigger'); const clickTriggerToHide = this.getProp('clickTriggerToHide'); this.clearDelayTimer(); /** * If you emit an event in setState callback, you need to place the event listener function before setState to execute. * This is to avoid event registration being executed later than setState callback when setState is executed in setTimeout. * internal-issues:1402#note_38969412 */ this._adapter.on('portalInserted', () => { this.calcPosition(); }); this._adapter.on('positionUpdated', () => { this._togglePortalVisible(true); }); const position = this.calcPosition(null, null, null, false); this._adapter.insertPortal(content, position); if (trigger === 'custom') { // eslint-disable-next-line this._adapter.registerClickOutsideHandler(() => {}); } /** * trigger类型是click时,仅当portal被插入显示后,才绑定clickOutsideHandler * 因为handler需要绑定在document上。如果在constructor阶段绑定 * 当一个页面中有多个容器实例时,一次click会触发多个容器的handler * * When the trigger type is click, clickOutsideHandler is bound only after the portal is inserted and displayed * Because the handler needs to be bound to the document. If you bind during the constructor phase * When there are multiple container instances in a page, one click triggers the handler of multiple containers */ if (trigger === 'click' || clickTriggerToHide) { this._adapter.registerClickOutsideHandler(this.hide); } this._bindScrollEvent(); this._bindResizeEvent(); }; _togglePortalVisible(isVisible: boolean) { const nowVisible = this.getState('visible'); if (nowVisible !== isVisible) { this._adapter.togglePortalVisible(isVisible, () => { if (isVisible) { this._adapter.setInitialFocus(); } this._adapter.notifyVisibleChange(isVisible); }); } } _roundPixel(pixel: number) { if (typeof pixel === 'number') { return Math.round(pixel); } return pixel; } calcTransformOrigin(position: Position, triggerRect: DOMRect, translateX: number, translateY: number) { // eslint-disable-next-line if (position && triggerRect && translateX != null && translateY != null) { if (this.getProp('transformFromCenter')) { if (['topLeft', 'bottomLeft'].includes(position)) { return `${this._roundPixel(triggerRect.width / 2)}px ${-translateY * 100}%`; } if (['topRight', 'bottomRight'].includes(position)) { return `calc(100% - ${this._roundPixel(triggerRect.width / 2)}px) ${-translateY * 100}%`; } if (['leftTop', 'rightTop'].includes(position)) { return `${-translateX * 100}% ${this._roundPixel(triggerRect.height / 2)}px`; } if (['leftBottom', 'rightBottom'].includes(position)) { return `${-translateX * 100}% calc(100% - ${this._roundPixel(triggerRect.height / 2)}px)`; } } return `${-translateX * 100}% ${-translateY * 100}%`; } return null; } calcPosStyle(triggerRect: DOMRect, wrapperRect: DOMRect, containerRect: PopupContainerDOMRect, position?: Position, spacing?: number) { triggerRect = (isEmpty(triggerRect) ? triggerRect : this._adapter.getTriggerBounding()) || { ...defaultRect as any }; containerRect = (isEmpty(containerRect) ? containerRect : this._adapter.getPopupContainerRect()) || { ...defaultRect, }; wrapperRect = (isEmpty(wrapperRect) ? wrapperRect : this._adapter.getWrapperBounding()) || { ...defaultRect as any }; // eslint-disable-next-line position = position != null ? position : this.getProp('position'); // eslint-disable-next-line const SPACING = spacing != null ? spacing : this.getProp('spacing'); const { arrowPointAtCenter, showArrow, arrowBounding } = this.getProps(); const pointAtCenter = showArrow && arrowPointAtCenter; const horizontalArrowWidth = get(arrowBounding, 'width', 24); const verticalArrowHeight = get(arrowBounding, 'width', 24); const arrowOffsetY = get(arrowBounding, 'offsetY', 0); const positionOffsetX = 6; const positionOffsetY = 6; // You must use left/top when rendering, using right/bottom does not render the element position correctly // Use left/top + translate to achieve tooltip positioning perfectly without knowing the size of the tooltip expansion layer let left; let top; let translateX = 0; // Container x-direction translation distance let translateY = 0; // Container y-direction translation distance const middleX = triggerRect.left + triggerRect.width / 2; const middleY = triggerRect.top + triggerRect.height / 2; const offsetXWithArrow = positionOffsetX + horizontalArrowWidth / 2; const offsetYWithArrow = positionOffsetY + verticalArrowHeight / 2; switch (position) { case 'top': left = middleX; top = triggerRect.top - SPACING; translateX = -0.5; translateY = -1; break; case 'topLeft': left = pointAtCenter ? middleX - offsetXWithArrow : triggerRect.left; top = triggerRect.top - SPACING; translateY = -1; break; case 'topRight': left = pointAtCenter ? middleX + offsetXWithArrow : triggerRect.right; top = triggerRect.top - SPACING; translateY = -1; translateX = -1; break; case 'left': left = triggerRect.left - SPACING; top = middleY; translateX = -1; translateY = -0.5; break; case 'leftTop': left = triggerRect.left - SPACING; top = pointAtCenter ? middleY - offsetYWithArrow : triggerRect.top; translateX = -1; break; case 'leftBottom': left = triggerRect.left - SPACING; top = pointAtCenter ? middleY + offsetYWithArrow : triggerRect.bottom; translateX = -1; translateY = -1; break; case 'bottom': left = middleX; top = triggerRect.top + triggerRect.height + SPACING; translateX = -0.5; break; case 'bottomLeft': left = pointAtCenter ? middleX - offsetXWithArrow : triggerRect.left; top = triggerRect.bottom + SPACING; break; case 'bottomRight': left = pointAtCenter ? middleX + offsetXWithArrow : triggerRect.right; top = triggerRect.bottom + SPACING; translateX = -1; break; case 'right': left = triggerRect.right + SPACING; top = middleY; translateY = -0.5; break; case 'rightTop': left = triggerRect.right + SPACING; top = pointAtCenter ? middleY - offsetYWithArrow : triggerRect.top; break; case 'rightBottom': left = triggerRect.right + SPACING; top = pointAtCenter ? middleY + offsetYWithArrow : triggerRect.bottom; translateY = -1; break; case 'leftTopOver': left = triggerRect.left - SPACING; top = triggerRect.top - SPACING; break; case 'rightTopOver': left = triggerRect.right + SPACING; top = triggerRect.top - SPACING; translateX = -1; break; case 'leftBottomOver': left = triggerRect.left - SPACING; top = triggerRect.bottom + SPACING; translateY = -1; break; case 'rightBottomOver': left = triggerRect.right + SPACING; top = triggerRect.bottom + SPACING; translateX = -1; translateY = -1; break; default: break; } const transformOrigin = this.calcTransformOrigin(position, triggerRect, translateX, translateY); // Transform origin const _containerIsBody = this._adapter.containerIsBody(); // Calculate container positioning relative to window left = left - containerRect.left; top = top - containerRect.top; /** * container为body时,如果position不为relative或absolute,这时trigger计算出的top/left会根据html定位(initial containing block) * 此时如果body有margin,则计算出的位置相对于body会有问题 fix issue #1368 * * When container is body, if position is not relative or absolute, then the top/left calculated by trigger will be positioned according to html * At this time, if the body has a margin, the calculated position will have a problem relative to the body fix issue #1368 */ if (_containerIsBody && !this._adapter.containerIsRelativeOrAbsolute()) { const documentEleRect = this._adapter.getDocumentElementBounding(); // Represents the left of the body relative to html left += containerRect.left - documentEleRect.left; // Represents the top of the body relative to html top += containerRect.top - documentEleRect.top; } // ContainerRect.scrollLeft to solve the inner scrolling of the container left = _containerIsBody ? left : left + containerRect.scrollLeft; top = _containerIsBody ? top : top + containerRect.scrollTop; const triggerHeight = triggerRect.height; if ( this.getProp('showArrow') && !arrowPointAtCenter && triggerHeight <= (verticalArrowHeight / 2 + arrowOffsetY) * 2 ) { const offsetY = triggerHeight / 2 - (arrowOffsetY + verticalArrowHeight / 2); if ((position.includes('Top') || position.includes('Bottom')) && !position.includes('Over')) { top = position.includes('Top') ? top + offsetY : top - offsetY; } } // The left/top value here must be rounded, otherwise it will cause the small triangle to shake const style: Record<string, string | number> = { left: this._roundPixel(left), top: this._roundPixel(top), }; let transform = ''; // eslint-disable-next-line if (translateX != null) { transform += `translateX(${translateX * 100}%) `; Object.defineProperty(style, 'translateX', { enumerable: false, value: translateX, }); } // eslint-disable-next-line if (translateY != null) { transform += `translateY(${translateY * 100}%) `; Object.defineProperty(style, 'translateY', { enumerable: false, value: translateY, }); } // eslint-disable-next-line if (transformOrigin != null) { style.transformOrigin = transformOrigin; } if (transform) { style.transform = transform; } return style; } /** * 耦合的东西比较多,稍微罗列一下: * * - 根据 trigger 和 wrapper 的 boundingClient 计算当前的 left、top、transform-origin * - 根据当前的 position 和 wrapper 的 boundingClient 决定是否需要自动调整位置 * - 根据当前的 position、trigger 的 boundingClient 以及 motion.handleStyle 调整当前的 style * * There are many coupling things, a little list: * * - calculate the current left, top, and transfer-origin according to the boundingClient of trigger and wrapper * - decide whether to automatically adjust the position according to the current position and the boundingClient of wrapper * - adjust the current style according to the current position, the boundingClient of trigger and motion.handle Style */ calcPosition = (triggerRect?: DOMRect, wrapperRect?: DOMRect, containerRect?: PopupContainerDOMRect, shouldUpdatePos = true) => { triggerRect = (isEmpty(triggerRect) ? this._adapter.getTriggerBounding() : triggerRect) || { ...defaultRect as any }; containerRect = (isEmpty(containerRect) ? this._adapter.getPopupContainerRect() : containerRect) || { ...defaultRect, }; wrapperRect = (isEmpty(wrapperRect) ? this._adapter.getWrapperBounding() : wrapperRect) || { ...defaultRect as any }; // console.log('containerRect: ', containerRect, 'triggerRect: ', triggerRect, 'wrapperRect: ', wrapperRect); let style = this.calcPosStyle(triggerRect, wrapperRect, containerRect); let position = this.getProp('position'); if (this.getProp('autoAdjustOverflow')) { // console.log('style: ', style, '\ntriggerRect: ', triggerRect, '\nwrapperRect: ', wrapperRect); const adjustedPos = this.adjustPosIfNeed(position, style, triggerRect, wrapperRect, containerRect); if (position !== adjustedPos) { position = adjustedPos; style = this.calcPosStyle(triggerRect, wrapperRect, containerRect, position); } } if (shouldUpdatePos && this._mounted) { // this._adapter.updatePlacementAttr(style.position); this._adapter.setPosition({ ...style, position }); } return style; }; isLR(position = '') { return position.indexOf('left') === 0 || position.indexOf('right') === 0; } isTB(position = '') { return position.indexOf('top') === 0 || position.indexOf('bottom') === 0; } // place the dom correctly adjustPosIfNeed(position: Position | string, style: Record<string, any>, triggerRect: DOMRect, wrapperRect: DOMRect, containerRect: PopupContainerDOMRect) { const { innerWidth, innerHeight } = window; const { spacing } = this.getProps(); if (wrapperRect.width > 0 && wrapperRect.height > 0) { // let clientLeft = left + translateX * wrapperRect.width - containerRect.scrollLeft; // let clientTop = top + translateY * wrapperRect.height - containerRect.scrollTop; // if (this._adapter.containerIsBody() || this._adapter.containerIsRelative()) { // clientLeft += containerRect.left; // clientTop += containerRect.top; // } // const clientRight = clientLeft + wrapperRect.width; // const clientBottom = clientTop + wrapperRect.height; // The relative position of the elements on the screen // https://lf3-static.bytednsdoc.com/obj/eden-cn/ptlz_zlp/ljhwZthlaukjlkulzlp/tooltip-pic.svg const clientLeft = triggerRect.left; const clientRight = triggerRect.right; const clientTop = triggerRect.top; const clientBottom = triggerRect.bottom; const restClientLeft = innerWidth - clientLeft; const restClientTop = innerHeight - clientTop; const restClientRight = innerWidth - clientRight; const restClientBottom = innerHeight - clientBottom; const widthIsBigger = wrapperRect.width > triggerRect.width; const heightIsBigger = wrapperRect.height > triggerRect.height; // The wrapperR ect.top|bottom equivalent cannot be directly used here for comparison, which is easy to cause jitter const shouldReverseTop = clientTop < wrapperRect.height + spacing && restClientBottom > wrapperRect.height + spacing; const shouldReverseLeft = clientLeft < wrapperRect.width + spacing && restClientRight > wrapperRect.width + spacing; const shouldReverseBottom = restClientBottom < wrapperRect.height + spacing && clientTop > wrapperRect.height + spacing; const shouldReverseRight = restClientRight < wrapperRect.width + spacing && clientLeft > wrapperRect.width + spacing; const shouldReverseTopOver = restClientTop < wrapperRect.height + spacing && clientBottom > wrapperRect.height + spacing; const shouldReverseBottomOver = clientBottom < wrapperRect.height + spacing && restClientTop > wrapperRect.height + spacing; const shouldReverseTopSide = restClientTop < wrapperRect.height && clientBottom > wrapperRect.height; const shouldReverseBottomSide = clientBottom < wrapperRect.height && restClientTop > wrapperRect.height; const shouldReverseLeftSide = restClientLeft < wrapperRect.width && clientRight > wrapperRect.width; const shouldReverseRightSide = clientRight < wrapperRect.width && restClientLeft > wrapperRect.width; const shouldReverseLeftOver = restClientLeft < wrapperRect.width && clientRight > wrapperRect.width; const shouldReverseRightOver = clientRight < wrapperRect.width && restClientLeft > wrapperRect.width; switch (position) { case 'top': if (shouldReverseTop) { position = this._reversePos(position, true); } break; case 'topLeft': if (shouldReverseTop) { position = this._reversePos(position, true); } if (shouldReverseLeftSide && widthIsBigger) { position = this._reversePos(position); } break; case 'topRight': if (shouldReverseTop) { position = this._reversePos(position, true); } if (shouldReverseRightSide && widthIsBigger) { position = this._reversePos(position); } break; case 'left': if (shouldReverseLeft) { position = this._reversePos(position); } break; case 'leftTop': if (shouldReverseLeft) { position = this._reversePos(position); } if (shouldReverseTopSide && heightIsBigger) { position = this._reversePos(position, true); } break; case 'leftBottom': if (shouldReverseLeft) { position = this._reversePos(position); } if (shouldReverseBottomSide && heightIsBigger) { position = this._reversePos(position, true); } break; case 'bottom': if (shouldReverseBottom) { position = this._reversePos(position, true); } break; case 'bottomLeft': if (shouldReverseBottom) { position = this._reversePos(position, true); } if (shouldReverseLeftSide && widthIsBigger) { position = this._reversePos(position); } break; case 'bottomRight': if (shouldReverseBottom) { position = this._reversePos(position, true); } if (shouldReverseRightSide && widthIsBigger) { position = this._reversePos(position); } break; case 'right': if (shouldReverseRight) { position = this._reversePos(position); } break; case 'rightTop': if (shouldReverseRight) { position = this._reversePos(position); } if (shouldReverseTopSide && heightIsBigger) { position = this._reversePos(position, true); } break; case 'rightBottom': if (shouldReverseRight) { position = this._reversePos(position); } if (shouldReverseBottomSide && heightIsBigger) { position = this._reversePos(position, true); } break; case 'leftTopOver': if (shouldReverseTopOver) { position = this._reversePos(position, true); } if (shouldReverseLeftOver) { position = this._reversePos(position); } break; case 'leftBottomOver': if (shouldReverseBottomOver) { position = this._reversePos(position, true); } if (shouldReverseLeftOver) { position = this._reversePos(position); } break; case 'rightTopOver': if (shouldReverseTopOver) { position = this._reversePos(position, true); } if (shouldReverseRightOver) { position = this._reversePos(position); } break; case 'rightBottomOver': if (shouldReverseBottomOver) { position = this._reversePos(position, true); } if (shouldReverseRightOver) { position = this._reversePos(position); } break; default: break; } } return position; } delayHide = () => { const mouseLeaveDelay = this.getProp('mouseLeaveDelay'); this.clearDelayTimer(); if (mouseLeaveDelay > 0) { this._timer = setTimeout(() => { // console.log('delayHide for ', mouseLeaveDelay, ' ms, ', ...args); this.hide(); this.clearDelayTimer(); }, mouseLeaveDelay); } else { this.hide(); } }; hide = () => { this.clearDelayTimer(); this._togglePortalVisible(false); this._adapter.off('portalInserted'); this._adapter.off('positionUpdated'); if (!this._adapter.canMotion()) { this._adapter.removePortal(); // When the portal is removed, the global click outside event binding is also removed this._adapter.unregisterClickOutsideHandler(); this._unBindScrollEvent(); this._unBindResizeEvent(); } }; _bindScrollEvent() { this._adapter.registerScrollHandler(() => this.calcPosition()); // Capture scroll events on the window to determine whether the current scrolling area (e.target) will affect the positioning of the pop-up layer relative to the viewport when scrolling // (By determining whether the e.target contains the triggerDom of the current tooltip) If so, the pop-up layer will also be affected and needs to be repositioned } _unBindScrollEvent() { this._adapter.unregisterScrollHandler(); } _initContainerPosition() { this._adapter.updateContainerPosition(); } handleContainerKeydown = (event: any) => { const { guardFocus, closeOnEsc } = this.getProps(); switch (event && event.key) { case "Escape": closeOnEsc && this._handleEscKeyDown(event); break; case "Tab": if (guardFocus) { const container = this._adapter.getContainer(); const focusableElements = this._adapter.getFocusableElements(container); const focusableNum = focusableElements.length; if (focusableNum) { // Shift + Tab will move focus backward if (event.shiftKey) { this._handleContainerShiftTabKeyDown(focusableElements, event); } else { this._handleContainerTabKeyDown(focusableElements, event); } } } break; default: break; } } _handleTriggerKeydown(event: any) { const { closeOnEsc } = this.getProps(); const container = this._adapter.getContainer(); const focusableElements = this._adapter.getFocusableElements(container); const focusableNum = focusableElements.length; switch (event && event.key) { case "Escape": closeOnEsc && this._handleEscKeyDown(event); break; case "ArrowUp": focusableNum && this._handleTriggerArrowUpKeydown(focusableElements, event); break; case "ArrowDown": focusableNum && this._handleTriggerArrowDownKeydown(focusableElements, event); break; default: break; } } /** * focus trigger * * when trigger is 'focus' or 'hover', onFocus is bind to show popup * if we focus trigger, popup will show again * * 如果 trigger 是 focus 或者 hover,则它绑定了 onFocus,这里我们如果重新 focus 的话,popup 会再次打开 * 因此 returnFocusOnClose 只支持 click trigger */ _focusTrigger() { const { trigger, returnFocusOnClose } = this.getProps(); if (returnFocusOnClose && trigger === 'click') { const triggerNode = this._adapter.getTriggerNode(); if (triggerNode && 'focus' in triggerNode) { triggerNode.focus(); } } } _handleEscKeyDown(event: any) { const { trigger } = this.getProps(); if (trigger !== 'custom') { this.hide(); this._focusTrigger(); } this._adapter.notifyEscKeydown(event); } _handleContainerTabKeyDown(focusableElements: any[], event: any) { const activeElement = this._adapter.getActiveElement(); const isLastCurrentFocus = focusableElements[focusableElements.length - 1] === activeElement; if (isLastCurrentFocus) { focusableElements[0].focus(); event.preventDefault(); // prevent browser default tab move behavior } } _handleContainerShiftTabKeyDown(focusableElements: any[], event: any) { const activeElement = this._adapter.getActiveElement(); const isFirstCurrentFocus = focusableElements[0] === activeElement; if (isFirstCurrentFocus) { focusableElements[focusableElements.length - 1].focus(); event.preventDefault(); // prevent browser default tab move behavior } } _handleTriggerArrowDownKeydown(focusableElements: any[], event: any) { focusableElements[0].focus(); event.preventDefault(); // prevent browser default scroll behavior } _handleTriggerArrowUpKeydown(focusableElements: any[], event: any) { focusableElements[focusableElements.length - 1].focus(); event.preventDefault(); // prevent browser default scroll behavior } }
the_stack
import { FarceStoreExtension, HistoryEnhancerOptions, Location, LocationDescriptor, LocationDescriptorObject, NavigationListener, NavigationListenerOptions, NavigationListenerResult, Protocol, Query, QueryDescriptor, } from 'farce'; import * as React from 'react'; import { Middleware, Reducer, Store, StoreEnhancer } from 'redux'; export { Query, QueryDescriptor, Location, LocationDescriptor, LocationDescriptorObject, NavigationListenerOptions, NavigationListenerResult, NavigationListener, }; type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>; export const ActionTypes: { UPDATE_MATCH: '@@found/UPDATE_MATCH'; RESOLVE_MATCH: '@@found/RESOLVE_MATCH'; }; export type Params = Record<string, string>; export type ParamsDescriptor = Record< string, string | number | boolean | Record<string, unknown> >; // These need to be interfaces to avoid circular reference issues. /* eslint-disable @typescript-eslint/no-empty-interface */ interface GroupRouteIndices extends Record<string, RouteIndices> {} export interface RouteIndices extends Array<number | GroupRouteIndices> {} /* eslint-enable @typescript-eslint/no-empty-interface */ export interface MatcherResult { routeIndices: RouteIndices; routeParams: Params[]; /** * The union of path parameters for *all* matched routes */ params: Params; } export interface MatchBase extends MatcherResult { /** * The current location */ location: Location; } /** * The shape might be different with a custom matcher or history enhancer, * but the default matcher assumes and provides this shape. As such, this * validator is purely for user convenience and should not be used * internally. */ export interface Match<TContext = any> extends MatchBase { /** * An array of all matched route objects */ routes: RouteObject[]; /** * An object with static router properties. */ router: Router; /** * matchContext from the router */ context: TContext; } export interface Resolver { resolveElements(match: Match): AsyncIterable<ResolvedElement[]>; } export const resolver: Resolver; export interface FoundState { match: MatchBase; resolvedMatch: MatchBase; } export const foundReducer: Reducer<FoundState>; export interface IsActiveOptions { exact?: boolean; } /** * An object implementing the matching algorithm. * * User code generally shouldn't need this, but it doesn't hurt to here, * since we use it for routerShape below. */ export class Matcher { constructor(routeConfig: RouteConfig); match(location: Location): MatcherResult | null; getRoutes: (match: MatchBase) => RouteObject[]; /** * for match as above, returns whether match corresponds to location or a * subpath of location; if exact is set, returns whether match corresponds * exactly to location */ isActive: ( match: Match, location: LocationDescriptorObject, options?: IsActiveOptions, ) => boolean; /** * Returns the path string for a pattern of the same format as a route path * and a object of the corresponding path parameters */ format: (pattern: string, params: ParamsDescriptor) => string; } export interface Router extends FarceStoreExtension, FoundStoreExtension { /** * Navigates to a new location * @see farce */ push: (location: LocationDescriptor) => void; /** * Replace the current history entry * @see farce */ replace: (location: LocationDescriptor) => void; /** * Moves delta steps in the history stack * @see farce */ go: (delta: number) => void; isActive: Matcher['isActive']; } /** * The match for a specific route, including that route and its own params. */ export interface RouteMatch extends Omit<Match, 'routeParams'> { /** * The route object corresponding to this component */ route: RouteObject[]; /** * The path parameters for route */ routeParams: Params; } export interface RenderProps extends RouteMatch { /** * The data for the route, as above; null if the data have not yet been * loaded */ data?: any; } /** * @see https://github.com/4Catalyzer/found/blob/master/README.md#render */ export interface RouteRenderArgs { match: Match; /** * The component for the route, if any; null if the component has not yet * been loaded */ Component?: React.ComponentType<any>; /** * The default props for the route component, specifically match with data * as an additional property; null if data have not yet been loaded */ props?: RenderProps; /** * The data for the route, as above; null if the data have not yet been * loaded */ data?: any; } export type ResolvedElementValue = React.ReactElement | null; export type ResolvedElement = | ResolvedElementValue | ((element: React.ReactElement) => ResolvedElementValue) | ((groups: Record<string, React.ReactElement>) => ResolvedElementValue); export interface RouteRenderMethod { (args: RouteRenderArgs): ResolvedElement | undefined; } /** * Shared properties between JSX and object routes. */ export interface RouteObjectBase { /** * a string defining the pattern for the route */ path?: string; /** * the component for the route */ Component?: React.ComponentType<any>; /** * a method that returns the component for the route */ getComponent?: ( match: RouteMatch, ) => React.ComponentType<any> | Promise<React.ComponentType<any>>; /** * additional data for the route */ data?: any; /** * a method that returns additional data for the route */ getData?: (match: RouteMatch) => any; /** * whether to defer getting data until ancestor data promises are resolved */ defer?: boolean; /** * @throws {HttpError} * @throws {RedirectException} */ render?: RouteRenderMethod; // Provide indexer allowing for other properties. [key: string]: any; } /** * Plain JavaScript route object, possibly from a resolved JSX route. */ export interface RouteObject extends RouteObjectBase { children?: RouteConfig | Record<string, RouteConfig>; } export type RouteConfig = RouteObject[]; export interface RouteProps extends RouteObjectBase { children?: React.ReactNode | Record<string, React.ReactNode>; } /** * JSX Route */ export class Route extends React.Component<RouteProps> { constructor(options: RouteObject | RouteProps); } export function hotRouteConfig(routeConfig: RouteConfig): RouteConfig; export class HttpError { status: number; data: any; constructor(status: number, data?: any); } export interface RedirectOptions { from?: string; to: string | ((match: Match) => LocationDescriptor); status?: number; } // It's more "natural" to call this "props" when used in the context of a // React component. export type RedirectProps = RedirectOptions; export class Redirect extends React.Component<RedirectProps> { constructor(config: RedirectOptions); } export interface LinkPropsCommon { to: LocationDescriptor; // match: Match, provided by withRouter // router: Router, provided by withRouter exact?: boolean; target?: string; onClick?: (event: React.SyntheticEvent<any>) => void; } export interface LinkInjectedProps { href: string; onClick: (event: React.SyntheticEvent<any>) => void; } export interface LinkPropsNodeChild extends LinkPropsCommon { activeClassName?: string; activeStyle?: Record<string, unknown>; children?: React.ReactNode; } type ReplaceLinkProps<TInner extends React.ElementType, TProps> = Omit< React.ComponentProps<TInner>, keyof TProps | keyof LinkInjectedProps > & TProps; export type LinkPropsSimple = ReplaceLinkProps<'a', LinkPropsNodeChild>; export type LinkPropsWithAs< TInner extends React.ElementType<LinkInjectedProps> > = ReplaceLinkProps< TInner, LinkPropsNodeChild & { as: TInner; activePropName?: null; } >; export type LinkPropsWithActivePropName< TInner extends React.ComponentType< LinkInjectedProps & { [activePropName in TActivePropName]: boolean } >, TActivePropName extends string > = ReplaceLinkProps< TInner, LinkPropsNodeChild & { as: TInner; activePropName: TActivePropName; } & { [activePropName in TActivePropName]?: null; } >; export interface LinkPropsWithFunctionChild extends LinkPropsCommon { children: (linkRenderArgs: { href: string; active: boolean; onClick: (event: React.SyntheticEvent<any>) => void; }) => React.ReactNode; } export type LinkProps< TInner extends React.ElementType = never, TInnerWithActivePropName extends React.ComponentType< LinkInjectedProps & { [activePropName in TActivePropName]: boolean } > = never, TActivePropName extends string = never > = | LinkPropsSimple | LinkPropsWithAs<TInner> | LinkPropsWithActivePropName<TInnerWithActivePropName, TActivePropName> | LinkPropsWithFunctionChild; export class Link< TInner extends React.ElementType = never, TInnerWithActivePropName extends React.ComponentType< LinkInjectedProps & { [activePropName in TActivePropName]: boolean } > = never, TActivePropName extends string = never > extends React.Component< LinkProps<TInner, TInnerWithActivePropName, TActivePropName> > { props: LinkProps<TInner, TInnerWithActivePropName, TActivePropName>; } export interface RouterState<TContext = any> { match: Match<TContext>; router: Router; } export type RouterProps<TContext> = RouterState<TContext>; /** * Returns the Router and current route match from context */ export function useRouter<TContext = any>(): RouterState<TContext>; /** Returns the current route Match */ export function useMatch<TContext = any>(): Match<TContext>; /** Returns the current route params */ export function useParams(): Params; /** Returns the current location object */ export function useLocation(): Location; export function withRouter<TProps extends RouterState>( Component: React.ComponentType<TProps>, ): React.ComponentType<Omit<TProps, keyof RouterState>>; export class RedirectException { constructor(location: LocationDescriptor, status?: number); location: LocationDescriptor; status: number; } /** * Create a route configuration from JSX configuration elements. */ export function makeRouteConfig(node: React.ReactNode): RouteConfig; export interface FoundStoreExtension { matcher: Matcher; replaceRouteConfig: (routeConfig: RouteConfig) => void; } export function createMatchEnhancer( matcher: Matcher, ): StoreEnhancer<{ found: FoundStoreExtension }>; export type RenderPendingArgs = Match; // This is the folded resolver output from resolveRenderArgs. export type RenderArgsElements = Array< ResolvedElement | Record<string, ResolvedElement[]> >; export interface RenderReadyArgs extends Match { elements: RenderArgsElements; } export interface RenderErrorArgs extends Match { error: HttpError; } export type RenderArgs = RenderPendingArgs | RenderReadyArgs | RenderErrorArgs; export interface CreateRenderOptions { renderPending?: (args: RenderPendingArgs) => React.ReactElement; renderReady?: (args: RenderReadyArgs) => React.ReactElement; renderError?: (args: RenderErrorArgs) => React.ReactNode; } export function createRender( options: CreateRenderOptions, ): (renderArgs: RenderArgs) => React.ReactElement; export interface ConnectedRouterOptions extends CreateRenderOptions { render?: (args: RenderArgs) => React.ReactElement; getFound?: (store: Store) => FoundState; } export interface ConnectedRouterProps { matchContext?: any; resolver: Resolver; initialRenderArgs?: RenderArgs; } export type ConnectedRouter = React.ComponentType<ConnectedRouterProps>; export function createConnectedRouter( options: ConnectedRouterOptions, ): ConnectedRouter; export interface FarceRouterOptions extends ConnectedRouterOptions { store?: Store; historyProtocol: Protocol; historyMiddlewares?: Middleware[]; historyOptions?: Omit<HistoryEnhancerOptions, 'protocol' | 'middlewares'>; routeConfig: RouteConfig; } export type FarceRouterProps = ConnectedRouterProps; export type FarceRouter = React.ComponentType<FarceRouterProps>; export function createFarceRouter(options: FarceRouterOptions): FarceRouter; export interface BrowserRouterOptions extends Omit<FarceRouterOptions, 'historyProtocol'> { render?: (args: RenderArgs) => React.ReactElement; } export interface BrowserRouterProps extends Omit<FarceRouterProps, 'resolver'> { resolver?: Resolver; } export type BrowserRouter = React.ComponentType<BrowserRouterProps>; export function createBrowserRouter( options: BrowserRouterOptions, ): BrowserRouter; export interface InitialFarceRouterOptions extends Omit<FarceRouterOptions, 'store'> { matchContext?: any; resolver: Resolver; } export function createInitialFarceRouter( options: InitialFarceRouterOptions, ): Promise<FarceRouter>; export type InitialBrowserRouterOptions = Omit< InitialFarceRouterOptions, 'resolver' | 'historyProtocol' >; export function createInitialBrowserRouter( options: InitialBrowserRouterOptions, ): Promise<BrowserRouter>; export interface ElementsRendererProps { elements: RenderArgsElements; } export type ElementsRenderer = React.ComponentType<ElementsRendererProps>; export interface GetStoreRenderArgsOptions { store: Store; getFound?: (store: Store) => FoundState; matchContext: any; resolver: Resolver; } export function getStoreRenderArgs( options: GetStoreRenderArgsOptions, ): Promise<RenderArgs>;
the_stack
import { DocumentEditor } from '../../../src/document-editor/document-editor'; import { DocumentHelper } from '../../../src/document-editor/implementation/viewer/viewer'; import { createElement } from '@syncfusion/ej2-base'; import { TestHelper } from '../../test-helper.spec'; import { ParagraphWidget, LineWidget, BlockWidget, FootnoteElementBox, ShapeElementBox, ShapeBase, ElementBox } from '../../../src/document-editor/implementation/viewer/page'; import { FootnoteType, WSectionFormat, FootnoteRestartIndex, FootEndNoteNumberFormat } from '../../../src'; import { FieldTextElementBox } from '../../../src'; let footendNoteJson: any = { "sections": [ { "blocks": [ { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "styleName": "Normal" }, "inlines": [ { "text": "Hello", "characterFormat": { "fontColor": "empty" } }, { "footnoteType": "Endnote", "markerCharacterFormat": { "fontColor": "empty", "styleName": "Endnote Reference" }, "blocks": [ { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "styleName": "Endnote Text" }, "inlines": [ { "text": "\u0002", "characterFormat": { "fontColor": "empty", "styleName": "Endnote Reference" } }, { "text": " Hello endnote", "characterFormat": { "fontColor": "empty" } } ] } ], "symbolCode": 0, "symbolFontName": "Symbol" }, { "text": " have a nice day", "characterFormat": { "fontColor": "empty" } }, { "footnoteType": "Footnote", "markerCharacterFormat": { "fontColor": "empty", "styleName": "Footnote Reference" }, "blocks": [ { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "styleName": "Footnote Text" }, "inlines": [ { "text": "\u0002", "characterFormat": { "fontColor": "empty", "styleName": "Footnote Reference" } }, { "text": " Nice day endnote", "characterFormat": { "fontColor": "empty" } } ] } ], "symbolCode": 0, "symbolFontName": "Symbol" } ] } ], "headersFooters": {}, "sectionFormat": { "headerDistance": 36.0, "footerDistance": 36.0, "pageWidth": 612.0, "pageHeight": 792.0, "leftMargin": 72.0, "rightMargin": 72.0, "topMargin": 72.0, "bottomMargin": 72.0, "differentFirstPage": false, "differentOddAndEvenPages": false, "bidi": false, "restartPageNumbering": false, "pageStartingNumber": 0, "footnotePosition": "PrintImmediatelyBeneathText", "endnotePosition": "DisplayEndOfDocument", "endnoteNumberFormat": "Arabic", "footNoteNumberFormat": "UpperCaseLetter", "restartIndexForFootnotes": "RestartForEachPage", "restartIndexForEndnotes": "RestartForEachSection" } } ], "characterFormat": { "fontSize": 11.0, "fontFamily": "Calibri", "fontColor": "empty", "fontSizeBidi": 11.0, "fontFamilyBidi": "Arial" }, "paragraphFormat": { "afterSpacing": 8.0, "lineSpacing": 1.0791666507720948, "lineSpacingType": "Multiple" }, "background": { "color": "#FFFFFFFF" }, "styles": [ { "type": "Paragraph", "name": "Normal", "next": "Normal", "characterFormat": { "fontColor": "empty" } }, { "type": "Character", "name": "Default Paragraph Font", "characterFormat": { "fontColor": "empty" } }, { "type": "Paragraph", "name": "Footnote Text", "basedOn": "Normal", "next": "Footnote Text", "link": "Footnote Text Char", "characterFormat": { "fontSize": 10.0, "fontColor": "empty", "fontSizeBidi": 10.0 }, "paragraphFormat": { "afterSpacing": 0.0, "lineSpacing": 1.0, "lineSpacingType": "Multiple" } }, { "type": "Character", "name": "Footnote Text Char", "basedOn": "Default Paragraph Font", "characterFormat": { "fontSize": 10.0, "fontColor": "empty", "fontSizeBidi": 10.0 } }, { "type": "Character", "name": "Footnote Reference", "basedOn": "Default Paragraph Font", "characterFormat": { "baselineAlignment": "Superscript", "fontColor": "empty" } }, { "type": "Paragraph", "name": "Endnote Text", "basedOn": "Normal", "next": "Endnote Text", "link": "Endnote Text Char", "characterFormat": { "fontSize": 10.0, "fontColor": "empty", "fontSizeBidi": 10.0 }, "paragraphFormat": { "afterSpacing": 0.0, "lineSpacing": 1.0, "lineSpacingType": "Multiple" } }, { "type": "Character", "name": "Endnote Text Char", "basedOn": "Default Paragraph Font", "characterFormat": { "fontSize": 10.0, "fontColor": "empty", "fontSizeBidi": 10.0 } }, { "type": "Character", "name": "Endnote Reference", "basedOn": "Default Paragraph Font", "characterFormat": { "baselineAlignment": "Superscript", "fontColor": "empty" } }, { "type": "Paragraph", "name": "Header", "basedOn": "Normal", "next": "Header", "link": "Header Char", "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "afterSpacing": 0.0, "lineSpacing": 1.0, "lineSpacingType": "Multiple", "tabs": [ { "tabJustification": "Center", "position": 234.0, "tabLeader": "None", "deletePosition": 0.0 }, { "tabJustification": "Right", "position": 468.0, "tabLeader": "None", "deletePosition": 0.0 } ] } }, { "type": "Character", "name": "Header Char", "basedOn": "Default Paragraph Font", "characterFormat": { "fontColor": "empty" } }, { "type": "Paragraph", "name": "Footer", "basedOn": "Normal", "next": "Footer", "link": "Footer Char", "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "afterSpacing": 0.0, "lineSpacing": 1.0, "lineSpacingType": "Multiple", "tabs": [ { "tabJustification": "Center", "position": 234.0, "tabLeader": "None", "deletePosition": 0.0 }, { "tabJustification": "Right", "position": 468.0, "tabLeader": "None", "deletePosition": 0.0 } ] } }, { "type": "Character", "name": "Footer Char", "basedOn": "Default Paragraph Font", "characterFormat": { "fontColor": "empty" } } ], "defaultTabWidth": 36.0, "formatting": false, "trackChanges": false, "protectionType": "NoProtection", "enforcement": false, "dontUseHTMLParagraphAutoSpacing": false, "alignTablesRowByRow": false, "formFieldShading": true, "footnotes": { "separator": [ { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "afterSpacing": 0.0, "lineSpacing": 1.0, "lineSpacingType": "Multiple", "styleName": "Normal" }, "inlines": [ { "text": "\u0003", "characterFormat": { "fontColor": "empty" } } ] } ], "continuationSeparator": [ { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "afterSpacing": 0.0, "lineSpacing": 1.0, "lineSpacingType": "Multiple", "styleName": "Normal" }, "inlines": [ { "text": "\u0004", "characterFormat": { "fontColor": "empty" } } ] } ] }, "endnotes": { "separator": [ { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "afterSpacing": 0.0, "lineSpacing": 1.0, "lineSpacingType": "Multiple", "styleName": "Normal" }, "inlines": [ { "text": "\u0003", "characterFormat": { "fontColor": "empty" } } ] } ], "continuationSeparator": [ { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "afterSpacing": 0.0, "lineSpacing": 1.0, "lineSpacingType": "Multiple", "styleName": "Normal" }, "inlines": [ { "text": "\u0004", "characterFormat": { "fontColor": "empty" } } ] } ] } }; let shapeJson: any = { "sections": [ { "blocks": [ { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "styleName": "Normal" }, "inlines": [ { "shapeId": 1, "name": "Text Box 1", "alternativeText": null, "title": null, "visible": true, "width": 60.92307, "height": 33.7846451, "widthScale": 100.0, "heightScale": 100.0, "lineFormat": { "lineFormatType": "Solid", "color": "#000000FF", "weight": 0.5, "lineStyle": "Solid" }, "fillFormat": { "color": "#FFFFFFFF", "fill": true }, "verticalPosition": 2.17, "verticalOrigin": "Paragraph", "verticalAlignment": "None", "horizontalPosition": 36.51, "horizontalOrigin": "Column", "horizontalAlignment": "None", "zOrderPosition": 251659264, "allowOverlap": true, "layoutInCell": true, "lockAnchor": false, "textWrappingStyle": "Square", "textWrappingType": "Both", "distanceBottom": 0.0, "distanceLeft": 9.0, "distanceRight": 9.0, "distanceTop": 0.0, "autoShapeType": "Rectangle", "textFrame": { "textVerticalAlignment": "Top", "leftMargin": 7.2, "rightMargin": 7.2, "topMargin": 3.6, "bottomMargin": 3.6, "blocks": [ { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "styleName": "Normal" }, "inlines": [ { "text": "Square", "characterFormat": { "fontColor": "empty" } } ] } ] } }, { "text": "Test Doc", "characterFormat": { "fontColor": "empty" } } ] }, { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "styleName": "Normal" }, "inlines": [ { "shapeId": 2, "name": "Text Box 2", "alternativeText": null, "title": null, "visible": true, "width": 91.38457, "height": 43.7538567, "widthScale": 100.0, "heightScale": 100.0, "lineFormat": { "lineFormatType": "Solid", "color": "#000000FF", "weight": 0.5, "lineStyle": "Solid" }, "fillFormat": { "color": "#FFFFFFFF", "fill": true }, "verticalPosition": 6.85, "verticalOrigin": "Paragraph", "verticalAlignment": "None", "horizontalPosition": 156.18, "horizontalOrigin": "Column", "horizontalAlignment": "None", "zOrderPosition": 251660288, "allowOverlap": true, "layoutInCell": true, "lockAnchor": false, "textWrappingStyle": "TopAndBottom", "textWrappingType": "Both", "distanceBottom": 0.0, "distanceLeft": 9.0, "distanceRight": 9.0, "distanceTop": 0.0, "autoShapeType": "Rectangle", "textFrame": { "textVerticalAlignment": "Top", "leftMargin": 7.2, "rightMargin": 7.2, "topMargin": 3.6, "bottomMargin": 3.6, "blocks": [ { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "styleName": "Normal" }, "inlines": [ { "text": "Top & bottom", "characterFormat": { "fontColor": "empty" } } ] } ] } }, { "text": "Test Top and Bottom", "characterFormat": { "fontColor": "empty" } } ] }, { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "styleName": "Normal" }, "inlines": [ { "shapeId": 3, "name": "Text Box 3", "alternativeText": null, "title": null, "visible": true, "width": 70.89228, "height": 29.9077168, "widthScale": 100.0, "heightScale": 100.0, "lineFormat": { "lineFormatType": "Solid", "color": "#000000FF", "weight": 0.5, "lineStyle": "Solid" }, "fillFormat": { "color": "#FFFFFFFF", "fill": true }, "verticalPosition": 7.8, "verticalOrigin": "Paragraph", "verticalAlignment": "None", "horizontalPosition": 63.63, "horizontalOrigin": "Column", "horizontalAlignment": "None", "zOrderPosition": 251661312, "allowOverlap": true, "layoutInCell": true, "lockAnchor": false, "textWrappingStyle": "Tight", "textWrappingType": "Both", "distanceBottom": 0.0, "distanceLeft": 9.0, "distanceRight": 9.0, "distanceTop": 0.0, "autoShapeType": "Rectangle", "textFrame": { "textVerticalAlignment": "Top", "leftMargin": 7.2, "rightMargin": 7.2, "topMargin": 3.6, "bottomMargin": 3.6, "blocks": [ { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "styleName": "Normal" }, "inlines": [ { "text": "Tight", "characterFormat": { "fontColor": "empty" } } ] } ] } }, { "text": "Tight", "characterFormat": { "fontColor": "empty" } } ] } ], "headersFooters": {}, "sectionFormat": { "headerDistance": 36.0, "footerDistance": 36.0, "pageWidth": 612.0, "pageHeight": 792.0, "leftMargin": 72.0, "rightMargin": 72.0, "topMargin": 72.0, "bottomMargin": 72.0, "differentFirstPage": false, "differentOddAndEvenPages": false, "bidi": false, "restartPageNumbering": false, "pageStartingNumber": 0, "endnoteNumberFormat": "LowerCaseRoman", "footNoteNumberFormat": "Arabic", "restartIndexForFootnotes": "DoNotRestart", "restartIndexForEndnotes": "DoNotRestart" } } ], "characterFormat": { "fontSize": 11.0, "fontFamily": "Calibri", "fontColor": "empty", "fontSizeBidi": 11.0, "fontFamilyBidi": "Arial" }, "paragraphFormat": { "afterSpacing": 8.0, "lineSpacing": 1.0791666507720947, "lineSpacingType": "Multiple" }, "background": { "color": "#FFFFFFFF" }, "styles": [ { "type": "Paragraph", "name": "Normal", "next": "Normal", "characterFormat": { "fontColor": "empty" } }, { "type": "Character", "name": "Default Paragraph Font", "characterFormat": { "fontColor": "empty" } } ], "defaultTabWidth": 36.0, "formatting": false, "trackChanges": false, "protectionType": "NoProtection", "enforcement": false, "dontUseHTMLParagraphAutoSpacing": false, "alignTablesRowByRow": false, "formFieldShading": true, "footnotes": { "separator": [ { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "styleName": "Normal" }, "inlines": [ { "text": "\u0003", "characterFormat": { "fontColor": "empty" } } ] } ], "continuationSeparator": [ { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "styleName": "Normal" }, "inlines": [ { "text": "\u0004", "characterFormat": { "fontColor": "empty" } } ] } ] }, "endnotes": { "separator": [ { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "styleName": "Normal" }, "inlines": [ { "text": "\u0003", "characterFormat": { "fontColor": "empty" } } ] } ], "continuationSeparator": [ { "characterFormat": { "fontColor": "empty" }, "paragraphFormat": { "styleName": "Normal" }, "inlines": [ { "text": "\u0004", "characterFormat": { "fontColor": "empty" } } ] } ] } }; describe('Content Control Validation', () => { let editor: DocumentEditor; let documentHelper: DocumentHelper; let blocks: BlockWidget[]; beforeAll((): void => { let ele: HTMLElement = createElement('div', { id: 'container' }); document.body.appendChild(ele); editor = new DocumentEditor({}); (editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas; (editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas; (editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas; (editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas; editor.appendTo('#container'); documentHelper = editor.documentHelper; editor.open(footendNoteJson); blocks = editor.documentHelper.pages[0].bodyWidgets[0].childWidgets as ParagraphWidget[]; }); afterAll((done): void => { documentHelper.destroy(); documentHelper = undefined; editor.destroy(); document.body.removeChild(document.getElementById('container')); editor = undefined; document.body.innerHTML = ''; setTimeout(function () { done(); }, 500); }); // it('Inline footnote', () => { // console.log('Inline footnote'); // let footnoteTypes: FootnoteType = 'Endnote'; // let code: any = 0; // expect(((blocks[0].childWidgets[0] as LineWidget).children[1] as FootnoteElementBox).footnoteType).toBe(footnoteTypes); // expect(((blocks[0].childWidgets[0] as LineWidget).children[1] as FootnoteElementBox).symbolFontName).toBe('Symbol'); // expect(((blocks[0].childWidgets[0] as LineWidget).children[1] as FootnoteElementBox).symbolCode).toBe(code); // expect(((blocks[0].childWidgets[0] as LineWidget).children[1] as FootnoteElementBox).customMarker).toBe(undefined); // expect(((blocks[0].childWidgets[0] as LineWidget).children[1] as FootnoteElementBox).blocks.length >= 1).toBe(true) // }); // it('footnote in section format', () => { // console.log('footnote in section format'); // let section: WSectionFormat = editor.documentHelper.pages[0].bodyWidgets[0].sectionFormat; // let endNoteFormat: FootEndNoteNumberFormat = 'Arabic'; // let footNoteFormat: FootEndNoteNumberFormat = 'UpperCaseLetter'; // let endNoteRestartIndex: FootnoteRestartIndex = 'RestartForEachSection'; // let footNoteRestartIndex: FootnoteRestartIndex = 'RestartForEachPage'; // expect(section.endnoteNumberFormat).toBe(endNoteFormat); // expect(section.footNoteNumberFormat).toBe(footNoteFormat); // expect(section.restartIndexForEndnotes).toBe(endNoteRestartIndex); // expect(section.restartIndexForFootnotes).toBe(footNoteRestartIndex); // }); // it('footnote in document', () => { // expect(editor.documentHelper.footnotes.continuationSeparator.length >= 1).toBe(true); // expect(editor.documentHelper.footnotes.separator.length >= 1).toBe(true); // }); // it('endnotes in document', () => { // expect(editor.documentHelper.endnotes.continuationSeparator.length >= 1).toBe(true); // expect(editor.documentHelper.endnotes.separator.length >= 1).toBe(true); // }); }); describe('Shape Validation', () => { let editor: DocumentEditor; let documentHelper: DocumentHelper; let para: ParagraphWidget[]; beforeAll((): void => { let ele: HTMLElement = createElement('div', { id: 'container' }); document.body.appendChild(ele); editor = new DocumentEditor({}); (editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas; (editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas; (editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas; (editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas; editor.appendTo('#container'); documentHelper = editor.documentHelper; editor.open(shapeJson); para = editor.documentHelper.pages[0].bodyWidgets[0].childWidgets as ParagraphWidget[]; }); afterAll((done): void => { documentHelper.destroy(); documentHelper = undefined; editor.destroy(); document.body.removeChild(document.getElementById('container')); editor = undefined; document.body.innerHTML = ''; setTimeout(function () { done(); }, 500); }); it('Square, TopAndBottom, Tight Shape', () => { let shape1: ShapeBase = para[0].floatingElements[0]; let shape2: ShapeBase = para[1].floatingElements[0]; let shape3: ShapeBase = para[2].floatingElements[0]; expect(shape1.textWrappingStyle).toBe('Square'); expect(shape1.textWrappingType).toBe('Both'); expect(shape1.distanceBottom).toBe(0.0); expect(shape1.distanceLeft).toBe(12.0); expect(shape1.distanceRight).toBe(12.0); expect(shape1.distanceTop).toBe(0.0); expect(shape2.textWrappingStyle).toBe('TopAndBottom'); expect(shape2.textWrappingType).toBe('Both'); expect(shape3.textWrappingStyle).toBe('Tight'); expect(shape3.textWrappingType).toBe('Both'); }); }); let footer: any = { "sections": [ { "blocks": [ { "paragraphFormat": { "styleName": "Normal", "listFormat": {} }, "characterFormat": { "fontSize": 11, "fontColor": "empty", "fontSizeBidi": 11 }, "inlines": [] } ], "headersFooters": { "footer": { "blocks": [ { "paragraphFormat": { "textAlignment": "Center", "styleName": "Footer", "listFormat": {} }, "characterFormat": { "fontSize": 8, "fontColor": "empty", "fontSizeBidi": 8 }, "inlines": [ { "characterFormat": { "fontSize": 8, "fontColor": "empty", "styleName": "Page Number", "fontSizeBidi": 8 }, "text": "Page " }, { "characterFormat": { "fontSize": 8, "fontColor": "empty", "styleName": "Page Number", "fontSizeBidi": 8 }, "fieldType": 0, "hasFieldEnd": true }, { "characterFormat": { "fontSize": 8, "fontColor": "empty", "styleName": "Page Number", "fontSizeBidi": 8 }, "text": " PAGE \\* Arabic \\* MERGEFOR" }, { "characterFormat": { "fontSize": 8, "fontColor": "empty", "styleName": "Page Number", "fontSizeBidi": 8 }, "text": "MAT " }, { "characterFormat": {}, "fieldType": 2 }, { "characterFormat": { "fontSize": 8, "fontColor": "empty", "styleName": "Page Number", "fontSizeBidi": 8 }, "text": "1" }, { "characterFormat": {}, "fieldType": 1 }, { "characterFormat": { "fontSize": 8, "fontColor": "empty", "styleName": "Page Number", "fontSizeBidi": 8 }, "text": " of " }, { "characterFormat": { "fontSize": 8, "fontColor": "empty", "styleName": "Page Number", "fontSizeBidi": 8 }, "fieldType": 0, "hasFieldEnd": true }, { "characterFormat": { "fontSize": 8, "fontColor": "empty", "styleName": "Page Number", "fontSizeBidi": 8 }, "text": " NUMP" }, { "characterFormat": { "fontSize": 8, "fontColor": "empty", "styleName": "Page Number", "fontSizeBidi": 8 }, "text": "AG" }, { "characterFormat": { "fontSize": 8, "fontColor": "empty", "styleName": "Page Number", "fontSizeBidi": 8 }, "text": "ES \\* Arabic \\* MERGEFORMAT " }, { "characterFormat": {}, "fieldType": 2 }, { "characterFormat": { "fontSize": 8, "fontColor": "empty", "styleName": "Page Number", "fontSizeBidi": 8 }, "text": "8" }, { "characterFormat": {}, "fieldType": 1 } ] } ] } } } ] }; describe('Page number validation', () => { let editor: DocumentEditor; let documentHelper: DocumentHelper; let para: ParagraphWidget[]; beforeAll((): void => { let ele: HTMLElement = createElement('div', { id: 'container' }); document.body.appendChild(ele); editor = new DocumentEditor({}); (editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas; (editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas; (editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas; (editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas; editor.appendTo('#container'); documentHelper = editor.documentHelper; editor.open(footer); }); afterAll((done): void => { documentHelper.destroy(); documentHelper = undefined; editor.destroy(); document.body.removeChild(document.getElementById('container')); editor = undefined; document.body.innerHTML = ''; setTimeout(function () { done(); }, 500); }); it('Page number validaton', () => { let element: ElementBox = ((editor.documentHelper.pages[0].footerWidget.childWidgets[0] as ParagraphWidget).childWidgets[0] as LineWidget).children[5]; expect((element as any).text).toBe('1'); }); });
the_stack
import * as chai from 'chai'; import { SequenceMultiplicity, SequenceType, ValueType, } from 'fontoxpath/expressions/dataTypes/Value'; import astHelper from 'fontoxpath/parsing/astHelper'; import parseExpression from 'fontoxpath/parsing/parseExpression'; import annotateAst, { countQueryBodyAnnotations } from 'fontoxpath/typeInference/annotateAST'; import { AnnotationContext } from 'fontoxpath/typeInference/AnnotationContext'; /** * * @param expression * @param expectedType * @param staticContext * @param followSpecificPath optional, used to pinpoint the nodes that requires type assertions * as sometimes it is hard to have queries that produce ast that is purely about the item under test. */ function assertValueType( expression: string, expectedType: ValueType, context: AnnotationContext, followSpecificPath?: string[] ) { const ast = parseExpression(expression, {}); if (context) annotateAst(ast, context); else annotateAst(ast, new AnnotationContext(undefined)); const upperNode = astHelper.followPath( ast, followSpecificPath ? followSpecificPath : ['mainModule', 'queryBody', '*'] ); const resultType = astHelper.getAttribute(upperNode, 'type') as SequenceType; if (!resultType) { chai.assert.isTrue(expectedType === null || expectedType === undefined); } else { chai.assert.deepEqual(resultType.type, expectedType); } } describe('Annotating constants', () => { it('annotates an integer constant', () => assertValueType('1', ValueType.XSINTEGER, undefined)); it('annotates a string constant', () => assertValueType("'test'", ValueType.XSSTRING, undefined)); it('annotates decimal constant', () => assertValueType('0.5', ValueType.XSDECIMAL, undefined)); it('annotates double constant', () => assertValueType('1.0e7', ValueType.XSDOUBLE, undefined)); }); describe('Annotating unary expressions', () => { it('annotates unary plus operator', () => assertValueType('+1', ValueType.XSINTEGER, undefined)); it('annotates chained unary plus operator', () => assertValueType('+++1', ValueType.XSINTEGER, undefined)); it('annotates unary minus operator', () => assertValueType('-1', ValueType.XSINTEGER, undefined)); it('annotates chained unary minus operator', () => assertValueType('---1', ValueType.XSINTEGER, undefined)); it('annotates unary plus operator on decimal', () => assertValueType('+0.1', ValueType.XSDECIMAL, undefined)); it('annotates unary minus operator on decimal', () => assertValueType('-0.1', ValueType.XSDECIMAL, undefined)); }); describe('Annotate unary lookup', () => { it('unary look up test', () => { assertValueType('map{"num":1}[?num]', undefined, undefined, [ 'mainModule', 'queryBody', 'pathExpr', 'stepExpr', 'predicates', 'unaryLookup', ]); }); }); describe('Path expression test', () => { it('Path expression test', () => { // The same query also triggers the path expression assertValueType('map{"num":1}[?num]', ValueType.MAP, undefined); }); it('Path expression test get annotate as nodes', () => { assertValueType('ancestor::someParentElement', ValueType.NODE, undefined); }); it('Path expression test annotate nodes with function', () => { assertValueType('self::element()', ValueType.NODE, undefined); }); it('Path expression test annotate as nodes with test', () => { assertValueType('//*[@someAttribute]', ValueType.NODE, undefined); }); it('Path expression test annotate as items with predicate', () => { assertValueType('(array {1,2,3,4,5,6,7})?*[. mod 2 = 1]', ValueType.ARRAY, undefined); }); }); describe('Annotating binary expressions', () => { it('simple add operator', () => assertValueType('1 + 2', ValueType.XSINTEGER, undefined)); it('simple sub operator', () => assertValueType('1 - 2', ValueType.XSINTEGER, undefined)); it('simple mul operator', () => assertValueType('1 * 2', ValueType.XSINTEGER, undefined)); it('simple div operator', () => assertValueType('1 div 2', ValueType.XSDECIMAL, undefined)); it('simple idiv operator', () => assertValueType('1 idiv 2', ValueType.XSINTEGER, undefined)); it('simple mod operator', () => assertValueType('1 mod 2', ValueType.XSINTEGER, undefined)); it('simple chained add operator', () => assertValueType('1 + 2 + 3', ValueType.XSINTEGER, undefined)); it('simple chained sub operator', () => assertValueType('1 - 2 - 3', ValueType.XSINTEGER, undefined)); it('simple chained mul operator', () => assertValueType('1 * 2 * 3', ValueType.XSINTEGER, undefined)); it('simple chained div operator', () => assertValueType('1 div 2 div 3', ValueType.XSDECIMAL, undefined)); it('simple chained idiv operator', () => assertValueType('1 idiv 2 idiv 3', ValueType.XSINTEGER, undefined)); it('simple chained mod operator', () => assertValueType('1 mod 2 mod 3', ValueType.XSINTEGER, undefined)); it('add integer and decimal results in decimal', () => assertValueType('1 + 0.1', ValueType.XSDECIMAL, undefined)); }); describe('Annotating compare expressions', () => { it('eqOp', () => assertValueType('1 = 2', ValueType.XSBOOLEAN, undefined)); it('neOp', () => assertValueType('1 != 2', ValueType.XSBOOLEAN, undefined)); it('leOp', () => assertValueType('1 <= 2', ValueType.XSBOOLEAN, undefined)); it('ltOp', () => assertValueType('1 < 2', ValueType.XSBOOLEAN, undefined)); it('geOp', () => assertValueType('1 >= 2', ValueType.XSBOOLEAN, undefined)); it('gtOp', () => assertValueType('1 > 2', ValueType.XSBOOLEAN, undefined)); }); describe('Annotating cast expressions', () => { it('simple cast expression', () => assertValueType('5 cast as xs:double', ValueType.XSDOUBLE, undefined)); it('unknown child cast expression', () => assertValueType('$x cast as xs:integer', ValueType.XSINTEGER, undefined)); }); describe('Annotate Array', () => { it('annotate simple square array', () => assertValueType('[3, 5, 4]', ValueType.ARRAY, undefined)); it('annotate complex array', () => assertValueType('["hello", (3, 4, 5)]', ValueType.ARRAY, undefined)); }); describe('annotate Sequence', () => { it('annotate simple sequence', () => assertValueType('(4, 3, hello)', undefined, undefined)); it('annotate simple sequence same type integer', () => assertValueType('(4, 3)', ValueType.XSINTEGER, undefined)); it('annotate simple sequence same type string', () => assertValueType('("4", "3")', ValueType.XSSTRING, undefined)); it('annotate complex sequence same type sequences', () => assertValueType('(("4", "he"), ("3", "hello"))', ValueType.XSSTRING, undefined)); it('annotate complex sequence different type sequences', () => assertValueType('(("4", "he"), ("3"))', undefined, undefined)); it('annotate complex sequence', () => assertValueType('(4, 3, hello, (43, (256, "help")))', undefined, undefined)); }); describe('Annotate maps', () => { it('mapConstructor', () => assertValueType('map{a:1, b:2}', ValueType.MAP, undefined)); }); describe('annotateSimpleMapExpr', () => { const context = new AnnotationContext(undefined); insertVariables(context, [ ['numericValues', { type: ValueType.XSINTEGER, mult: SequenceMultiplicity.ZERO_OR_MORE }], ['nodeValues', { type: ValueType.NODE, mult: SequenceMultiplicity.ZERO_OR_MORE }], ]); it('annotate mapExpr of sequence', () => assertValueType('$numericValues ! 4 ! 3', ValueType.XSINTEGER, context)); it('annotate mapExpr of sequence contextItem mult', () => assertValueType('$numericValues!(.*.)', ValueType.XSNUMERIC, undefined)); it('annotate mapExpr contextItem union', () => assertValueType('$nodeValues!(. union //b)', ValueType.NODE, undefined)); it('annotate mapExpr attributes of nodes', () => assertValueType('/ ! (@first, @middle, @last)', ValueType.ATTRIBUTE, undefined)); it('annotate mapExpr of strings', () => assertValueType('(1 to 5)!"*"', ValueType.XSSTRING, undefined)); }); describe('Annotating ifThenElse expressions', () => { it('ifThenElse type is known', () => assertValueType('if (3) then 3 else 5', ValueType.XSINTEGER, undefined)); it('ifThenElse type is not known', () => assertValueType('if (3) then "hello" else 5', undefined, undefined)); }); describe('Annotate quantifiedExpr', () => { it('quantifiedExpr', () => assertValueType('every $x in true() satisfies $x', ValueType.XSBOOLEAN, undefined)); }); describe('Annotate arrowExpr', () => { it('annotate tailFunction', () => assertValueType('array:tail([1]) => array:size()', undefined, undefined)); }); describe('Annotate dynamic function invocation expression test', () => { it('dynamic function invocation', () => { assertValueType('$f()', undefined, undefined, [ 'mainModule', 'queryBody', 'pathExpr', 'stepExpr', 'filterExpr', 'dynamicFunctionInvocationExpr', ]); }); }); describe('Annotating Logical Operator', () => { it('annotate or operator test', () => assertValueType('true() or true()', ValueType.XSBOOLEAN, undefined)); it('annotate and operator test', () => assertValueType('true() and false()', ValueType.XSBOOLEAN, undefined)); it('annotate mixed logical operator test', () => assertValueType('true() (: and false() :) or true()', ValueType.XSBOOLEAN, undefined)); }); describe('Annotating Comparison operator', () => { it('equal operator', () => assertValueType('1 = 1', ValueType.XSBOOLEAN, undefined)); it('not equal operator', () => assertValueType('1 != 1', ValueType.XSBOOLEAN, undefined)); it('greater than operator', () => assertValueType('1 > 1', ValueType.XSBOOLEAN, undefined)); it('greater than or equal operator', () => assertValueType('1 >= 1', ValueType.XSBOOLEAN, undefined)); it('less than operator', () => assertValueType('1 < 1', ValueType.XSBOOLEAN, undefined)); it('less than or equal operator', () => assertValueType('1 <= 1', ValueType.XSBOOLEAN, undefined)); }); // Halted: left and right is node returns undefined describe('Annotating Set operator', () => { it('union of non nodes test', () => { assertValueType('array {a} union array {c}', ValueType.NODE, undefined); }); it('intersect of non nodes test', () => { assertValueType('array {a, b} intersect array {b, c}', ValueType.NODE, undefined); }); it('except of non nodes test', () => { assertValueType('[a] except [a]', ValueType.NODE, undefined); }); // Generating left and right nodes using pathExpr (which returns a node) it('union test', () => { assertValueType('//*[@someAttribute] union //b', ValueType.NODE, undefined); }); it('intersect test', () => { assertValueType('(//*[@someAttribute] intersect //b)', ValueType.NODE, undefined); }); it('except test', () => { assertValueType('//*[@someAttribute] except //b', ValueType.NODE, undefined); }); }); describe('Annotating Node compare operator test', () => { it('Node before', () => { assertValueType('//firstElement << //secondElement', ValueType.XSBOOLEAN, undefined); }); it('Node after', () => { assertValueType('//firstElement >> //secondElement', ValueType.XSBOOLEAN, undefined); }); }); describe('Annotating StringConcatenateOp', () => { it('Concatenate strings', () => { assertValueType('"con" || "cat" || "enate"', ValueType.XSSTRING, undefined); }); }); describe('Annotating RangeSequenceExpr', () => { it('RangeSequenceExpr', () => { assertValueType('(1 to 10)', ValueType.XSINTEGER, undefined); }); }); describe('Annotating Instance of', () => { it('Instance of positive test', () => { assertValueType('true() instance of xs:boolean*', ValueType.XSBOOLEAN, undefined); }); it('Instance of negative test', () => { assertValueType('() instance of xs:boolean*', ValueType.XSBOOLEAN, undefined); }); it('Instance of array', () => { assertValueType( 'array { true(), false()} instance of xs:array*', ValueType.XSBOOLEAN, undefined ); }); }); describe('Annotating contextItemExpr', () => { it('plain contextItemExpr test', () => { // . is the contextItem symbol? Annotation function returns only undefined right now assertValueType('.', undefined, undefined, []); }); }); describe('Annotating castable', () => { it('castable test', () => { assertValueType('"5" castable as xs:integer', ValueType.XSBOOLEAN, undefined); }); }); describe('Annotating function call without context', () => { it('array function call without context', () => { assertValueType('array:size([])', undefined, undefined); }); it('name function call without context', () => { assertValueType('fn:concat#2', undefined, undefined); }); }); describe('Annotating inline functions', () => { it('in line function test', () => { assertValueType('function() {}', ValueType.FUNCTION, undefined); }); }); describe('Annotating typeswitch expression', () => { it('first case matches', () => { assertValueType( 'typeswitch(1) case xs:integer return 2 case xs:string return 42.0 default return a', ValueType.XSINTEGER, undefined ); }); it('not first case matches', () => { assertValueType( 'typeswitch(1) case xs:string return 42.0 case xs:integer return 2 default return a', ValueType.XSINTEGER, undefined ); }); it('typeswitch with an OR in the condition', () => { assertValueType( 'typeswitch(1) case xs:integer | xs:string return 2 default return 42.0', ValueType.XSINTEGER, undefined ); }); it('default case is returned', () => { assertValueType( 'typeswitch(1) case xs:string return 42.0 default return 2', ValueType.XSINTEGER, undefined ); }); }); describe('Annotation counting', () => { const context = new AnnotationContext(undefined); insertVariables(context, [ ['x', { type: ValueType.XSINTEGER, mult: SequenceMultiplicity.EXACTLY_ONE }], ['a', { type: ValueType.XSINTEGER, mult: SequenceMultiplicity.EXACTLY_ONE }], ['b', { type: ValueType.XSINTEGER, mult: SequenceMultiplicity.EXACTLY_ONE }], ]); it('correctly counts add expressions', () => { const ast = parseExpression('2 + 1', {}); annotateAst(ast, new AnnotationContext(undefined)); const [total, annotated] = countQueryBodyAnnotations(ast); chai.assert.equal(total, annotated); }); it('correctly counts unannotated expressions', () => { const ast = parseExpression('$x + 1', {}); annotateAst(ast, context); const [total, annotated] = countQueryBodyAnnotations(ast); chai.assert.equal(annotated, total); chai.assert.equal(total, 3); }); it('correctly counts unannotated expressions 2', () => { const ast = parseExpression('$b + math:sin($a)', {}); annotateAst(ast, context); const [total, annotated] = countQueryBodyAnnotations(ast); chai.assert.equal(annotated, 2); chai.assert.equal(total, 4); }); }); describe('Annotating flwor Expressions', () => { it('annotate simple let expression', () => { assertValueType("let $s := 'Hello' return $s", ValueType.XSSTRING, undefined); }); it('annotate complex let expression', () => { assertValueType( "let $s := 'Hello' return let $v := 3 return $s || $v", ValueType.XSSTRING, undefined ); }); it('annotate simple for expression', () => { assertValueType('for $x in (3, 4, 5) return $x', ValueType.XSINTEGER, undefined); }); it('annotate complex for expression', () => { assertValueType( 'for $x in (3, 4, 5) for $y in (2, 5) return $x + $y', ValueType.XSINTEGER, undefined ); }); it('annotate name shadowing for expression', () => { assertValueType( 'for $x in (3, 25, 5) let $x := "stuff" || $x return $x', ValueType.XSSTRING, undefined ); }); }); describe('annotating varRef', () => { const context = new AnnotationContext(undefined); context.insertVariable('x', { type: ValueType.XSINTEGER, mult: SequenceMultiplicity.EXACTLY_ONE, }); context.insertVariable('y', { type: ValueType.XSINTEGER, mult: SequenceMultiplicity.EXACTLY_ONE, }); context.insertVariable('z', { type: ValueType.XSSTRING, mult: SequenceMultiplicity.EXACTLY_ONE, }); it('annotate simple varRef', () => { assertValueType('$x', ValueType.XSINTEGER, context); }); it('annotate varRef + varRef', () => { assertValueType('$x + $y', ValueType.XSINTEGER, context); }); it('annotate complex varRef', () => { assertValueType('$x + 1', ValueType.XSINTEGER, context); }); it('annotate varRef not in context', () => { assertValueType('$x + $l', undefined, context); }); it('annotate varRef throws when types incorrect', () => { chai.assert.throws(() => assertValueType('$x + $z', undefined, context)); }); }); /** * An easy way to add multiple variables in a context * @param context the context in which the variables are inserted * @param variables */ function insertVariables(context: AnnotationContext, variables: Array<[string, SequenceType]>) { variables.forEach((element) => { context.insertVariable(element[0], element[1]); }); } // Type switch is not tested, type switch is reserved in XPath but not yet used // Annotation of `functionCallExpr` and `namedFunctionRef` with context is not tested // Test case template // describe('Annotating ', () => { // it('', // () => { // // assertValueType('', ValueType. , undefined) // }); // });
the_stack
import { SourceInfo } from "./parser"; import { AutoTypeSignature, TypeSignature } from "./type_signature"; import { InvokeDecl, BuildLevel } from "./assembly"; import { BSQRegex } from "./bsqregex"; class InvokeArgument { readonly value: Expression; readonly ref: "ref" | "out" | "out?" | undefined; constructor(value: Expression, ref: "ref" | "out" | "out?" | undefined) { this.value = value; this.ref = ref; } } class NamedArgument extends InvokeArgument { readonly name: string; constructor(ref: "ref" | "out" | "out?" | undefined, name: string, value: Expression) { super(value, ref); this.name = name; } } class PositionalArgument extends InvokeArgument { readonly isSpread: boolean; constructor(ref: "ref" | "out" | "out?" | undefined, isSpread: boolean, value: Expression) { super(value, ref); this.isSpread = isSpread; } } class Arguments { readonly argList: InvokeArgument[]; constructor(args: InvokeArgument[]) { this.argList = args; } } class TemplateArguments { readonly targs: TypeSignature[]; constructor(targs: TypeSignature[]) { this.targs = targs; } } type RecursiveAnnotation = "yes" | "no" | "cond"; class CondBranchEntry<T> { readonly cond: Expression; readonly action: T; constructor(cond: Expression, action: T) { this.cond = cond; this.action = action; } } class IfElse<T> { readonly conds: CondBranchEntry<T>[]; readonly elseAction: T | undefined; constructor(conds: CondBranchEntry<T>[], elseAction: T | undefined) { this.conds = conds; this.elseAction = elseAction; } } abstract class SwitchGuard { } class WildcardSwitchGuard extends SwitchGuard { } class LiteralSwitchGuard extends SwitchGuard { readonly litmatch: LiteralExpressionValue; constructor(litmatch: LiteralExpressionValue) { super(); this.litmatch = litmatch; } } class SwitchEntry<T> { readonly check: SwitchGuard; readonly action: T; constructor(check: SwitchGuard, action: T) { this.check = check; this.action = action; } } abstract class MatchGuard { } class WildcardMatchGuard extends MatchGuard { } class TypeMatchGuard extends MatchGuard { readonly oftype: TypeSignature; constructor(oftype: TypeSignature) { super(); this.oftype = oftype; } } class StructureMatchGuard extends MatchGuard { readonly match: StructuredAssignment; readonly decls: Set<string>; constructor(match: StructuredAssignment, decls: Set<string>) { super(); this.match = match; this.decls = decls; } } class MatchEntry<T> { readonly check: MatchGuard; readonly action: T; constructor(check: MatchGuard, action: T) { this.check = check; this.action = action; } } enum ExpressionTag { Clear = "[CLEAR]", InvalidExpresion = "[INVALID]", LiteralNoneExpression = "LiteralNoneExpression", LiteralNothingExpression = "LiteralNothingExpression", LiteralBoolExpression = "LiteralBoolExpression", LiteralNumberinoExpression = "LiteralNumberinoExpression", LiteralIntegralExpression = "LiteralIntegralExpression", LiteralRationalExpression = "LiteralRationalExpression", LiteralFloatPointExpression = "LiteralFloatExpression", LiteralStringExpression = "LiteralStringExpression", LiteralRegexExpression = "LiteralRegexExpression", LiteralTypedStringExpression = "LiteralTypedStringExpression", LiteralTypedPrimitiveConstructorExpression = "LiteralTypedPrimitiveConstructorExpression", LiteralTypedStringConstructorExpression = "LiteralTypedStringConstructorExpression", AccessNamespaceConstantExpression = "AccessNamespaceConstantExpression", AccessStaticFieldExpression = " AccessStaticFieldExpression", AccessVariableExpression = "AccessVariableExpression", ConstructorPrimaryExpression = "ConstructorPrimaryExpression", ConstructorPrimaryWithFactoryExpression = "ConstructorPrimaryWithFactoryExpression", ConstructorTupleExpression = "ConstructorTupleExpression", ConstructorRecordExpression = "ConstructorRecordExpression", ConstructorEphemeralValueList = "ConstructorEphemeralValueList", ConstructorPCodeExpression = "ConstructorPCodeExpression", PCodeInvokeExpression = "PCodeInvokeExpression", SpecialConstructorExpression = "SpecialConstructorExpression", CallNamespaceFunctionOrOperatorExpression = "CallNamespaceFunctionOrOperatorExpression", CallStaticFunctionOrOperatorExpression = "CallStaticFunctionOrOperatorExpression", IsTypeExpression = "IsTypeExpression", AsTypeExpression = "AsTypeExpression", PostfixOpExpression = "PostfixOpExpression", PrefixNotOpExpression = "PrefixNotOpExpression", BinKeyExpression = "BinKeyExpression", BinLogicExpression = "BinLogicExpression", MapEntryConstructorExpression = "MapEntryConstructorExpression", SelectExpression = "SelectExpression", ExpOrExpression = "ExpOrExpression", BlockStatementExpression = "BlockStatementExpression", IfExpression = "IfExpression", SwitchExpression = "SwitchExpression", MatchExpression = "MatchExpression" } abstract class Expression { readonly tag: ExpressionTag; readonly sinfo: SourceInfo; constructor(tag: ExpressionTag, sinfo: SourceInfo) { this.tag = tag; this.sinfo = sinfo; } isCompileTimeInlineValue(): boolean { return false; } isLiteralValueExpression(): boolean { return false; } } //This just holds a constant expression that can be evaluated without any arguments but not a subtype of Expression so we can distinguish as types class LiteralExpressionValue { readonly exp: Expression; constructor(exp: Expression) { this.exp = exp; } } //This just holds a constant expression (for use where we expect and constant -- or restricted constant expression) but not a subtype of Expression so we can distinguish as types class ConstantExpressionValue { readonly exp: Expression; readonly captured: Set<string>; constructor(exp: Expression, captured: Set<string>) { this.exp = exp; this.captured = captured; } } class InvalidExpression extends Expression { constructor(sinfo: SourceInfo) { super(ExpressionTag.InvalidExpresion, sinfo); } } class LiteralNoneExpression extends Expression { constructor(sinfo: SourceInfo) { super(ExpressionTag.LiteralNoneExpression, sinfo); } isCompileTimeInlineValue(): boolean { return true; } isLiteralValueExpression(): boolean { return true; } } class LiteralNothingExpression extends Expression { constructor(sinfo: SourceInfo) { super(ExpressionTag.LiteralNothingExpression, sinfo); } isCompileTimeInlineValue(): boolean { return true; } isLiteralValueExpression(): boolean { return true; } } class LiteralBoolExpression extends Expression { readonly value: boolean; constructor(sinfo: SourceInfo, value: boolean) { super(ExpressionTag.LiteralBoolExpression, sinfo); this.value = value; } isCompileTimeInlineValue(): boolean { return true; } isLiteralValueExpression(): boolean { return true; } } class LiteralNumberinoExpression extends Expression { readonly value: string; constructor(sinfo: SourceInfo, value: string) { super(ExpressionTag.LiteralNumberinoExpression, sinfo); this.value = value; } isCompileTimeInlineValue(): boolean { return true; } } class LiteralIntegralExpression extends Expression { readonly value: string; readonly itype: TypeSignature; constructor(sinfo: SourceInfo, value: string, itype: TypeSignature) { super(ExpressionTag.LiteralIntegralExpression, sinfo); this.value = value; this.itype = itype; } isCompileTimeInlineValue(): boolean { return true; } isLiteralValueExpression(): boolean { return true; } } class LiteralRationalExpression extends Expression { readonly value: string; readonly rtype: TypeSignature; constructor(sinfo: SourceInfo, value: string, rtype: TypeSignature) { super(ExpressionTag.LiteralRationalExpression, sinfo); this.value = value; this.rtype = rtype; } isCompileTimeInlineValue(): boolean { return true; } } class LiteralFloatPointExpression extends Expression { readonly value: string; readonly fptype: TypeSignature; constructor(sinfo: SourceInfo, value: string, fptype: TypeSignature) { super(ExpressionTag.LiteralFloatPointExpression, sinfo); this.value = value; this.fptype = fptype; } isCompileTimeInlineValue(): boolean { return true; } } class LiteralStringExpression extends Expression { readonly value: string; constructor(sinfo: SourceInfo, value: string) { super(ExpressionTag.LiteralStringExpression, sinfo); this.value = value; } isCompileTimeInlineValue(): boolean { return true; } isLiteralValueExpression(): boolean { return true; } } class LiteralRegexExpression extends Expression { readonly value: BSQRegex; constructor(sinfo: SourceInfo, value: BSQRegex) { super(ExpressionTag.LiteralRegexExpression, sinfo); this.value = value; } } class LiteralTypedStringExpression extends Expression { readonly value: string; readonly stype: TypeSignature; constructor(sinfo: SourceInfo, value: string, stype: TypeSignature) { super(ExpressionTag.LiteralTypedStringExpression, sinfo); this.value = value; this.stype = stype; } isCompileTimeInlineValue(): boolean { return true; } isLiteralValueExpression(): boolean { return true; } } class LiteralTypedPrimitiveConstructorExpression extends Expression { readonly value: string; readonly oftype: TypeSignature | undefined; readonly vtype: TypeSignature; constructor(sinfo: SourceInfo, value: string, oftype: TypeSignature | undefined, vtype: TypeSignature) { super(ExpressionTag.LiteralTypedPrimitiveConstructorExpression, sinfo); this.value = value; this.oftype = oftype; this.vtype = vtype; } isCompileTimeInlineValue(): boolean { return true; } isLiteralValueExpression(): boolean { return true; } } class LiteralTypedStringConstructorExpression extends Expression { readonly value: string; readonly stype: TypeSignature; constructor(sinfo: SourceInfo, value: string, stype: TypeSignature) { super(ExpressionTag.LiteralTypedStringConstructorExpression, sinfo); this.value = value; this.stype = stype; } } class AccessNamespaceConstantExpression extends Expression { readonly ns: string; readonly name: string; constructor(sinfo: SourceInfo, ns: string, name: string) { super(ExpressionTag.AccessNamespaceConstantExpression, sinfo); this.ns = ns; this.name = name; } } class AccessStaticFieldExpression extends Expression { readonly stype: TypeSignature; readonly name: string; constructor(sinfo: SourceInfo, stype: TypeSignature, name: string) { super(ExpressionTag.AccessStaticFieldExpression, sinfo); this.stype = stype; this.name = name; } } class AccessVariableExpression extends Expression { readonly name: string; constructor(sinfo: SourceInfo, name: string) { super(ExpressionTag.AccessVariableExpression, sinfo); this.name = name; } } class ConstructorPrimaryExpression extends Expression { readonly ctype: TypeSignature; readonly args: Arguments; constructor(sinfo: SourceInfo, ctype: TypeSignature, args: Arguments) { super(ExpressionTag.ConstructorPrimaryExpression, sinfo); this.ctype = ctype; this.args = args; } } class ConstructorPrimaryWithFactoryExpression extends Expression { readonly ctype: TypeSignature; readonly factoryName: string; readonly terms: TemplateArguments; readonly rec: RecursiveAnnotation; readonly args: Arguments; constructor(sinfo: SourceInfo, ctype: TypeSignature, factory: string, rec: RecursiveAnnotation, terms: TemplateArguments, args: Arguments) { super(ExpressionTag.ConstructorPrimaryWithFactoryExpression, sinfo); this.ctype = ctype; this.factoryName = factory; this.rec = rec; this.terms = terms; this.args = args; } } class ConstructorTupleExpression extends Expression { readonly args: Arguments; constructor(sinfo: SourceInfo, args: Arguments) { super(ExpressionTag.ConstructorTupleExpression, sinfo); this.args = args; } } class ConstructorRecordExpression extends Expression { readonly args: Arguments; constructor(sinfo: SourceInfo, args: Arguments) { super(ExpressionTag.ConstructorRecordExpression, sinfo); this.args = args; } } class ConstructorEphemeralValueList extends Expression { readonly args: Arguments; constructor(sinfo: SourceInfo, args: Arguments) { super(ExpressionTag.ConstructorEphemeralValueList, sinfo); this.args = args; } } class ConstructorPCodeExpression extends Expression { readonly isAuto: boolean; readonly invoke: InvokeDecl; constructor(sinfo: SourceInfo, isAuto: boolean, invoke: InvokeDecl) { super(ExpressionTag.ConstructorPCodeExpression, sinfo); this.isAuto = isAuto; this.invoke = invoke; } } class PCodeInvokeExpression extends Expression { readonly pcode: string; readonly rec: RecursiveAnnotation; readonly args: Arguments; constructor(sinfo: SourceInfo, pcode: string, rec: RecursiveAnnotation, args: Arguments) { super(ExpressionTag.PCodeInvokeExpression, sinfo); this.pcode = pcode; this.rec = rec; this.args = args; } } class SpecialConstructorExpression extends Expression { readonly rop: "ok" | "err" | "something"; readonly arg: Expression; constructor(sinfo: SourceInfo, rop: "ok" | "err" | "something", arg: Expression) { super(ExpressionTag.SpecialConstructorExpression, sinfo); this.rop = rop; this.arg = arg; } } class CallNamespaceFunctionOrOperatorExpression extends Expression { readonly ns: string; readonly name: string; readonly rec: RecursiveAnnotation; readonly terms: TemplateArguments; readonly args: Arguments; readonly opkind: "prefix" | "infix" | "std"; constructor(sinfo: SourceInfo, ns: string, name: string, terms: TemplateArguments, rec: RecursiveAnnotation, args: Arguments, opkind: "prefix" | "infix" | "std") { super(ExpressionTag.CallNamespaceFunctionOrOperatorExpression, sinfo); this.ns = ns; this.name = name; this.rec = rec; this.terms = terms; this.args = args; this.opkind = opkind; } } class CallStaticFunctionOrOperatorExpression extends Expression { readonly ttype: TypeSignature; readonly name: string; readonly rec: RecursiveAnnotation; readonly terms: TemplateArguments; readonly args: Arguments; readonly opkind: "prefix" | "infix" | "std"; constructor(sinfo: SourceInfo, ttype: TypeSignature, name: string, terms: TemplateArguments, rec: RecursiveAnnotation, args: Arguments, opkind: "prefix" | "infix" | "std") { super(ExpressionTag.CallStaticFunctionOrOperatorExpression, sinfo); this.ttype = ttype; this.name = name; this.rec = rec; this.terms = terms; this.args = args; this.opkind = opkind; } } class IsTypeExpression extends Expression { readonly arg: Expression; readonly oftype: TypeSignature; constructor(sinfo: SourceInfo, arg: Expression, oftype: TypeSignature) { super(ExpressionTag.IsTypeExpression, sinfo); this.arg = arg; this.oftype = oftype; } } class AsTypeExpression extends Expression { readonly arg: Expression; readonly oftype: TypeSignature; constructor(sinfo: SourceInfo, arg: Expression, oftype: TypeSignature) { super(ExpressionTag.AsTypeExpression, sinfo); this.arg = arg; this.oftype = oftype; } } enum PostfixOpTag { PostfixAccessFromIndex = "PostfixAccessFromIndex", PostfixProjectFromIndecies = "PostfixProjectFromIndecies", PostfixAccessFromName = "PostfixAccessFromName", PostfixProjectFromNames = "PostfixProjectFromNames", PostfixModifyWithIndecies = "PostfixModifyWithIndecies", PostfixModifyWithNames = "PostfixModifyWithNames", PostfixIs = "PostfixIs", PostfixAs = "PostfixAs", PostfixHasIndex = "PostfixHasIndex", PostfixHasProperty = "PostfixHasProperty", PostfixGetIndexOrNone = "PostfixGetIndexOrNone", PostfixGetIndexOption = "PostfixGetIndexOption", PostfixGetIndexTry = "PostfixGetIndexTry", PostfixGetPropertyOrNone = "PostfixGetPropertyOrNone", PostfixGetPropertyOption = "PostfixGetPropertyOption", PostfixGetPropertyTry = "PostfixGetPropertyTry", PostfixInvoke = "PostfixInvoke" } abstract class PostfixOperation { readonly sinfo: SourceInfo; readonly op: PostfixOpTag; constructor(sinfo: SourceInfo, op: PostfixOpTag) { this.sinfo = sinfo; this.op = op; } } class PostfixOp extends Expression { readonly rootExp: Expression; readonly ops: PostfixOperation[]; constructor(sinfo: SourceInfo, root: Expression, ops: PostfixOperation[]) { super(ExpressionTag.PostfixOpExpression, sinfo); this.rootExp = root; this.ops = ops; } } class PostfixAccessFromIndex extends PostfixOperation { readonly index: number; constructor(sinfo: SourceInfo, index: number) { super(sinfo, PostfixOpTag.PostfixAccessFromIndex); this.index = index; } } class PostfixProjectFromIndecies extends PostfixOperation { readonly isEphemeralListResult: boolean; readonly indecies: {index: number, reqtype: TypeSignature | undefined}[]; constructor(sinfo: SourceInfo, isEphemeralListResult: boolean, indecies: {index: number, reqtype: TypeSignature | undefined }[]) { super(sinfo, PostfixOpTag.PostfixProjectFromIndecies); this.isEphemeralListResult = isEphemeralListResult this.indecies = indecies; } } class PostfixAccessFromName extends PostfixOperation { readonly name: string; constructor(sinfo: SourceInfo, name: string) { super(sinfo, PostfixOpTag.PostfixAccessFromName); this.name = name; } } class PostfixProjectFromNames extends PostfixOperation { readonly isEphemeralListResult: boolean; readonly names: { name: string, reqtype: TypeSignature | undefined }[]; constructor(sinfo: SourceInfo, isEphemeralListResult: boolean, names: { name: string, reqtype: TypeSignature | undefined }[]) { super(sinfo, PostfixOpTag.PostfixProjectFromNames); this.isEphemeralListResult = isEphemeralListResult; this.names = names; } } class PostfixModifyWithIndecies extends PostfixOperation { readonly isBinder: boolean; readonly updates: { index: number, value: Expression }[]; constructor(sinfo: SourceInfo, isBinder: boolean, updates: { index: number, value: Expression }[]) { super(sinfo, PostfixOpTag.PostfixModifyWithIndecies); this.isBinder = isBinder; this.updates = updates; } } class PostfixModifyWithNames extends PostfixOperation { readonly isBinder: boolean; readonly updates: { name: string, value: Expression }[]; constructor(sinfo: SourceInfo, isBinder: boolean, updates: { name: string, value: Expression }[]) { super(sinfo, PostfixOpTag.PostfixModifyWithNames); this.isBinder = isBinder; this.updates = updates; } } class PostfixIs extends PostfixOperation { readonly istype: TypeSignature; constructor(sinfo: SourceInfo, istype: TypeSignature) { super(sinfo, PostfixOpTag.PostfixIs); this.istype = istype; } } class PostfixAs extends PostfixOperation { readonly astype: TypeSignature; constructor(sinfo: SourceInfo, astype: TypeSignature) { super(sinfo, PostfixOpTag.PostfixAs); this.astype = astype; } } class PostfixHasIndex extends PostfixOperation { readonly idx: number; constructor(sinfo: SourceInfo, idx: number) { super(sinfo, PostfixOpTag.PostfixHasIndex); this.idx = idx; } } class PostfixHasProperty extends PostfixOperation { readonly pname: string; constructor(sinfo: SourceInfo, pname: string) { super(sinfo, PostfixOpTag.PostfixHasProperty); this.pname = pname; } } class PostfixGetIndexOrNone extends PostfixOperation { readonly idx: number; constructor(sinfo: SourceInfo, idx: number) { super(sinfo, PostfixOpTag.PostfixGetIndexOrNone); this.idx = idx; } } class PostfixGetIndexOption extends PostfixOperation { readonly idx: number; constructor(sinfo: SourceInfo, idx: number) { super(sinfo, PostfixOpTag.PostfixGetIndexOption); this.idx = idx; } } class PostfixGetIndexTry extends PostfixOperation { readonly idx: number; readonly vname: string; constructor(sinfo: SourceInfo, idx: number, vname: string) { super(sinfo, PostfixOpTag.PostfixGetIndexTry); this.idx = idx; this.vname = vname; } } class PostfixGetPropertyOrNone extends PostfixOperation { readonly pname: string; constructor(sinfo: SourceInfo, pname: string) { super(sinfo, PostfixOpTag.PostfixGetPropertyOrNone); this.pname = pname; } } class PostfixGetPropertyOption extends PostfixOperation { readonly pname: string; constructor(sinfo: SourceInfo, pname: string) { super(sinfo, PostfixOpTag.PostfixGetPropertyOption); this.pname = pname; } } class PostfixGetPropertyTry extends PostfixOperation { readonly pname: string; readonly vname: string; constructor(sinfo: SourceInfo, pname: string, vname: string) { super(sinfo, PostfixOpTag.PostfixGetPropertyTry); this.pname = pname; this.vname = vname; } } class PostfixInvoke extends PostfixOperation { readonly isBinder: boolean; readonly specificResolve: TypeSignature | undefined; readonly name: string; readonly rec: RecursiveAnnotation; readonly terms: TemplateArguments; readonly args: Arguments; constructor(sinfo: SourceInfo, isBinder: boolean, specificResolve: TypeSignature | undefined, name: string, terms: TemplateArguments, rec: RecursiveAnnotation, args: Arguments) { super(sinfo, PostfixOpTag.PostfixInvoke); this.isBinder = isBinder; this.specificResolve = specificResolve; this.name = name; this.rec = rec; this.terms = terms; this.args = args; } } class PrefixNotOp extends Expression { readonly exp: Expression; constructor(sinfo: SourceInfo, exp: Expression) { super(ExpressionTag.PrefixNotOpExpression, sinfo); this.exp = exp; } } class BinKeyExpression extends Expression { readonly lhs: Expression; readonly op: string; //===, !== readonly rhs: Expression; constructor(sinfo: SourceInfo, lhs: Expression, op: string, rhs: Expression) { super(ExpressionTag.BinKeyExpression, sinfo); this.lhs = lhs; this.op = op; this.rhs = rhs; } } class BinLogicExpression extends Expression { readonly lhs: Expression; readonly op: string; //==>, &&, || readonly rhs: Expression; constructor(sinfo: SourceInfo, lhs: Expression, op: string, rhs: Expression) { super(ExpressionTag.BinLogicExpression, sinfo); this.lhs = lhs; this.op = op; this.rhs = rhs; } } class MapEntryConstructorExpression extends Expression { readonly kexp: Expression; readonly vexp: Expression; constructor(sinfo: SourceInfo, kexp: Expression, vexp: Expression) { super(ExpressionTag.MapEntryConstructorExpression, sinfo); this.kexp = kexp; this.vexp = vexp; } } class SelectExpression extends Expression { readonly test: Expression; readonly option1: Expression; readonly option2: Expression; constructor(sinfo: SourceInfo, test: Expression, option1: Expression, option2: Expression) { super(ExpressionTag.SelectExpression, sinfo); this.test = test; this.option1 = option1; this.option2 = option2; } } class ExpOrExpression extends Expression { readonly exp: Expression; readonly cond: "none" | "nothing" | "err"; constructor(sinfo: SourceInfo, exp: Expression, cond: "none" | "nothing" | "err") { super(ExpressionTag.ExpOrExpression, sinfo); this.exp = exp; this.cond = cond; } } class BlockStatementExpression extends Expression { readonly ops: Statement[]; constructor(sinfo: SourceInfo, ops: Statement[]) { super(ExpressionTag.BlockStatementExpression, sinfo); this.ops = ops; } } class IfExpression extends Expression { readonly flow: IfElse<Expression>; constructor(sinfo: SourceInfo, flow: IfElse<Expression>) { super(ExpressionTag.IfExpression, sinfo); this.flow = flow; } } class SwitchExpression extends Expression { readonly sval: Expression; readonly flow: SwitchEntry<Expression>[]; constructor(sinfo: SourceInfo, sval: Expression, flow: SwitchEntry<Expression>[]) { super(ExpressionTag.SwitchExpression, sinfo); this.sval = sval; this.flow = flow; } } class MatchExpression extends Expression { readonly sval: Expression; readonly flow: MatchEntry<Expression>[]; constructor(sinfo: SourceInfo, sval: Expression, flow: MatchEntry<Expression>[]) { super(ExpressionTag.MatchExpression, sinfo); this.sval = sval; this.flow = flow; } } enum StatementTag { Clear = "[CLEAR]", InvalidStatement = "[INVALID]", EmptyStatement = "EmptyStatement", VariableDeclarationStatement = "VariableDeclarationStatement", VariablePackDeclarationStatement = "VariablePackDeclarationStatement", VariableAssignmentStatement = "VariableAssignmentStatement", VariablePackAssignmentStatement = "VariablePackAssignmentStatement", StructuredVariableAssignmentStatement = "StructuredVariableAssignmentStatement", ReturnStatement = "ReturnStatement", YieldStatement = "YieldStatement", IfElseStatement = "IfElseStatement", SwitchStatement = "SwitchStatement", MatchStatement = "MatchStatement", AbortStatement = "AbortStatement", AssertStatement = "AssertStatement", //assert(x > 0) CheckStatement = "CheckStatement", //check(x > 0) ValidateStatement = "ValidateStatement", //validate exp else err -> if (!exp) return Result<INVOKE_RESULT>@error(err); DebugStatement = "DebugStatement", //print an arg or if empty attach debugger NakedCallStatement = "NakedCallStatement", BlockStatement = "BlockStatement" } abstract class Statement { readonly tag: StatementTag; readonly sinfo: SourceInfo; constructor(tag: StatementTag, sinfo: SourceInfo) { this.tag = tag; this.sinfo = sinfo; } } class InvalidStatement extends Statement { constructor(sinfo: SourceInfo) { super(StatementTag.InvalidStatement, sinfo); } } class EmptyStatement extends Statement { constructor(sinfo: SourceInfo) { super(StatementTag.EmptyStatement, sinfo); } } class VariableDeclarationStatement extends Statement { readonly name: string; readonly isConst: boolean; readonly vtype: TypeSignature; //may be auto readonly exp: Expression | undefined; //may be undef constructor(sinfo: SourceInfo, name: string, isConst: boolean, vtype: TypeSignature, exp: Expression | undefined) { super(StatementTag.VariableDeclarationStatement, sinfo); this.name = name; this.isConst = isConst; this.vtype = vtype; this.exp = exp; } } class VariablePackDeclarationStatement extends Statement { readonly isConst: boolean; readonly vars: {name: string, vtype: TypeSignature /*may be auto*/}[]; readonly exp: Expression[] | undefined; //may be undef constructor(sinfo: SourceInfo, isConst: boolean, vars: {name: string, vtype: TypeSignature /*may be auto*/}[], exp: Expression[] | undefined) { super(StatementTag.VariablePackDeclarationStatement, sinfo); this.isConst = isConst; this.vars = vars; this.exp = exp; } } class VariableAssignmentStatement extends Statement { readonly name: string; readonly exp: Expression; constructor(sinfo: SourceInfo, name: string, exp: Expression) { super(StatementTag.VariableAssignmentStatement, sinfo); this.name = name; this.exp = exp; } } class VariablePackAssignmentStatement extends Statement { readonly names: string[]; readonly exp: Expression[]; constructor(sinfo: SourceInfo, names: string[], exp: Expression[]) { super(StatementTag.VariablePackAssignmentStatement, sinfo); this.names = names; this.exp = exp; } } class StructuredAssignment { } class StructuredAssignementPrimitive extends StructuredAssignment { readonly assigntype: TypeSignature; constructor(assigntype: TypeSignature) { super(); this.assigntype = assigntype; } } class IgnoreTermStructuredAssignment extends StructuredAssignementPrimitive { constructor(ignoretype: TypeSignature) { super(ignoretype); } } class VariableDeclarationStructuredAssignment extends StructuredAssignementPrimitive { readonly vname: string; constructor(vname: string, vtype: TypeSignature) { super(vtype); this.vname = vname; } } class VariableAssignmentStructuredAssignment extends StructuredAssignementPrimitive { readonly vname: string; constructor(vname: string) { super(new AutoTypeSignature()); this.vname = vname; } } class TupleStructuredAssignment extends StructuredAssignment { readonly assigns: StructuredAssignementPrimitive[]; constructor(assigns: StructuredAssignementPrimitive[]) { super(); this.assigns = assigns; } } class RecordStructuredAssignment extends StructuredAssignment { readonly assigns: [string, StructuredAssignementPrimitive][]; constructor(assigns: [string, StructuredAssignementPrimitive][]) { super(); this.assigns = assigns; } } class NominalStructuredAssignment extends StructuredAssignment { readonly atype: TypeSignature; readonly assigns: [string | undefined, StructuredAssignementPrimitive][]; constructor(atype: TypeSignature, assigns: [string | undefined, StructuredAssignementPrimitive][]) { super(); this.atype = atype; this.assigns = assigns; } } class ValueListStructuredAssignment extends StructuredAssignment { readonly assigns: StructuredAssignementPrimitive[]; constructor(assigns: StructuredAssignementPrimitive[]) { super(); this.assigns = assigns; } } class StructuredVariableAssignmentStatement extends Statement { readonly isConst: boolean; readonly assign: StructuredAssignment; readonly exp: Expression; constructor(sinfo: SourceInfo, isConst: boolean, assign: StructuredAssignment, exp: Expression) { super(StatementTag.StructuredVariableAssignmentStatement, sinfo); this.isConst = isConst; this.assign = assign; this.exp = exp; } } class ReturnStatement extends Statement { readonly values: Expression[]; constructor(sinfo: SourceInfo, values: Expression[]) { super(StatementTag.ReturnStatement, sinfo); this.values = values; } } class YieldStatement extends Statement { readonly values: Expression[]; constructor(sinfo: SourceInfo, values: Expression[]) { super(StatementTag.YieldStatement, sinfo); this.values = values; } } class IfElseStatement extends Statement { readonly flow: IfElse<BlockStatement>; constructor(sinfo: SourceInfo, flow: IfElse<BlockStatement>) { super(StatementTag.IfElseStatement, sinfo); this.flow = flow; } } class SwitchStatement extends Statement { readonly sval: Expression; readonly flow: SwitchEntry<BlockStatement>[]; constructor(sinfo: SourceInfo, sval: Expression, flow: SwitchEntry<BlockStatement>[]) { super(StatementTag.SwitchStatement, sinfo); this.sval = sval; this.flow = flow; } } class MatchStatement extends Statement { readonly sval: Expression; readonly flow: MatchEntry<BlockStatement>[]; constructor(sinfo: SourceInfo, sval: Expression, flow: MatchEntry<BlockStatement>[]) { super(StatementTag.MatchStatement, sinfo); this.sval = sval; this.flow = flow; } } class AbortStatement extends Statement { constructor(sinfo: SourceInfo) { super(StatementTag.AbortStatement, sinfo); } } class AssertStatement extends Statement { readonly cond: Expression; readonly level: BuildLevel; constructor(sinfo: SourceInfo, cond: Expression, level: BuildLevel) { super(StatementTag.AssertStatement, sinfo); this.cond = cond; this.level = level; } } class CheckStatement extends Statement { readonly cond: Expression; constructor(sinfo: SourceInfo, cond: Expression) { super(StatementTag.CheckStatement, sinfo); this.cond = cond; } } class ValidateStatement extends Statement { readonly cond: Expression; readonly err: Expression; constructor(sinfo: SourceInfo, cond: Expression, err: Expression) { super(StatementTag.ValidateStatement, sinfo); this.cond = cond; this.err = err; } } class DebugStatement extends Statement { readonly value: Expression | undefined; constructor(sinfo: SourceInfo, value: Expression | undefined) { super(StatementTag.DebugStatement, sinfo); this.value = value; } } class NakedCallStatement extends Statement { readonly call: CallNamespaceFunctionOrOperatorExpression | CallStaticFunctionOrOperatorExpression; constructor(sinfo: SourceInfo, call: CallNamespaceFunctionOrOperatorExpression | CallStaticFunctionOrOperatorExpression) { super(StatementTag.NakedCallStatement, sinfo); this.call = call; } } class BlockStatement extends Statement { readonly statements: Statement[]; constructor(sinfo: SourceInfo, statements: Statement[]) { super(StatementTag.BlockStatement, sinfo); this.statements = statements; } } class BodyImplementation { readonly id: string; readonly file: string; readonly body: string | BlockStatement | Expression; constructor(bodyid: string, file: string, body: string | BlockStatement | Expression) { this.id = bodyid; this.file = file; this.body = body; } } export { InvokeArgument, NamedArgument, PositionalArgument, Arguments, TemplateArguments, RecursiveAnnotation, CondBranchEntry, IfElse, ExpressionTag, Expression, LiteralExpressionValue, ConstantExpressionValue, InvalidExpression, LiteralNoneExpression, LiteralNothingExpression, LiteralBoolExpression, LiteralNumberinoExpression, LiteralIntegralExpression, LiteralFloatPointExpression, LiteralRationalExpression, LiteralStringExpression, LiteralRegexExpression, LiteralTypedStringExpression, LiteralTypedPrimitiveConstructorExpression, LiteralTypedStringConstructorExpression, AccessNamespaceConstantExpression, AccessStaticFieldExpression, AccessVariableExpression, ConstructorPrimaryExpression, ConstructorPrimaryWithFactoryExpression, ConstructorTupleExpression, ConstructorRecordExpression, ConstructorEphemeralValueList, ConstructorPCodeExpression, SpecialConstructorExpression, CallNamespaceFunctionOrOperatorExpression, CallStaticFunctionOrOperatorExpression, IsTypeExpression, AsTypeExpression, PostfixOpTag, PostfixOperation, PostfixOp, PostfixAccessFromIndex, PostfixProjectFromIndecies, PostfixAccessFromName, PostfixProjectFromNames, PostfixModifyWithIndecies, PostfixModifyWithNames, PostfixIs, PostfixAs, PostfixHasIndex, PostfixHasProperty, PostfixGetIndexOrNone, PostfixGetIndexOption , PostfixGetIndexTry, PostfixGetPropertyOrNone, PostfixGetPropertyOption, PostfixGetPropertyTry, PostfixInvoke, PCodeInvokeExpression, PrefixNotOp, BinKeyExpression, BinLogicExpression, MapEntryConstructorExpression, SelectExpression, ExpOrExpression, BlockStatementExpression, IfExpression, SwitchExpression, MatchExpression, StatementTag, Statement, InvalidStatement, EmptyStatement, VariableDeclarationStatement, VariablePackDeclarationStatement, VariableAssignmentStatement, VariablePackAssignmentStatement, StructuredAssignment, StructuredAssignementPrimitive, IgnoreTermStructuredAssignment, VariableDeclarationStructuredAssignment, VariableAssignmentStructuredAssignment, StructuredVariableAssignmentStatement, TupleStructuredAssignment, RecordStructuredAssignment, NominalStructuredAssignment, ValueListStructuredAssignment, ReturnStatement, YieldStatement, IfElseStatement, AbortStatement, AssertStatement, CheckStatement, ValidateStatement, DebugStatement, NakedCallStatement, SwitchGuard, MatchGuard, WildcardSwitchGuard, LiteralSwitchGuard, WildcardMatchGuard, TypeMatchGuard, StructureMatchGuard, SwitchEntry, MatchEntry, SwitchStatement, MatchStatement, BlockStatement, BodyImplementation };
the_stack
import { Autowired, Injectable, Injector, INJECTOR_TOKEN } from '@opensumi/di'; import { PreferenceChange } from '@opensumi/ide-core-browser'; import { DisposableCollection, PreferenceScope, Uri, URI, Emitter, CommandService, toDisposable, } from '@opensumi/ide-core-common'; import { WorkbenchEditorService, IDocPersistentCacheProvider } from '@opensumi/ide-editor'; import { IEditorFeatureRegistry, IEditorFeatureContribution, EmptyDocCacheImpl, IEditorDocumentModelService, } from '@opensumi/ide-editor/src/browser'; import { IEditorDocumentModel } from '@opensumi/ide-editor/src/browser/'; import { EditorDocumentModel } from '@opensumi/ide-editor/src/browser/doc-model/main'; import { WorkbenchEditorServiceImpl } from '@opensumi/ide-editor/src/browser/workbench-editor.service'; import { monaco as monacoAPI } from '@opensumi/ide-monaco/lib/browser/monaco-api'; import type { ICodeEditor as IMonacoCodeEditor } from '@opensumi/ide-monaco/lib/browser/monaco-api/types'; import * as monaco from '@opensumi/monaco-editor-core/esm/vs/editor/editor.api'; import { createBrowserInjector } from '../../../../../tools/dev-tool/src/injector-helper'; import { MockInjector } from '../../../../../tools/dev-tool/src/mock-injector'; import { IDirtyDiffWorkbenchController } from '../../../src'; import { DirtyDiffWorkbenchController, DirtyDiffItem } from '../../../src/browser/dirty-diff'; import { DirtyDiffDecorator } from '../../../src/browser/dirty-diff/dirty-diff-decorator'; import { DirtyDiffModel } from '../../../src/browser/dirty-diff/dirty-diff-model'; import { DirtyDiffWidget } from '../../../src/browser/dirty-diff/dirty-diff-widget'; import { SCMPreferences } from '../../../src/browser/scm-preference'; jest.useFakeTimers(); @Injectable() class MockEditorDocumentModelService { @Autowired(INJECTOR_TOKEN) private readonly injector: Injector; private readonly instances: Map<string, EditorDocumentModel> = new Map(); async createModelReference(uri: URI): Promise<EditorDocumentModel> { if (!this.instances.has(uri.toString())) { const instance = this.injector.get(EditorDocumentModel, [uri, 'test-content']); this.instances.set(uri.toString(), instance); } return this.instances.get(uri.toString())!; } } @Injectable() class MockPreferenceService { readonly onPreferenceChangedEmitter = new Emitter<PreferenceChange>(); readonly onPreferenceChanged = this.onPreferenceChangedEmitter.event; preferences: Map<string, any> = new Map(); get(k) { return this.preferences.get(k); } set(k, v) { this.preferences.set(k, v); } 'scm.alwaysShowDiffWidget' = true; 'scm.diffDecorations' = 'all'; 'scm.diffDecorationsGutterWidth' = 3; } describe('scm/src/browser/dirty-diff/index.ts', () => { let injector: MockInjector; let dirtyDiffWorkbenchController: DirtyDiffWorkbenchController; let scmPreferences: MockPreferenceService; const editorFeatureContributions = new Set<IEditorFeatureContribution>(); let monacoEditor: IMonacoCodeEditor; let editorModel: IEditorDocumentModel; let commandService: CommandService; let editorService: WorkbenchEditorService; async function createModel(filePath: string): Promise<EditorDocumentModel> { const fileTextModel = injector.get(EditorDocumentModel, [URI.file(filePath), 'test-content']); return fileTextModel; } beforeEach(async () => { injector = createBrowserInjector( [], new Injector([ { token: IDocPersistentCacheProvider, useClass: EmptyDocCacheImpl, }, { token: IEditorDocumentModelService, useClass: MockEditorDocumentModelService, }, { token: SCMPreferences, useClass: MockPreferenceService, }, { token: IEditorFeatureRegistry, useValue: { registerEditorFeatureContribution: (contribution) => { editorFeatureContributions.add(contribution); return toDisposable(() => { editorFeatureContributions.delete(contribution); }); }, runContributions: jest.fn(), runProvideEditorOptionsForUri: jest.fn(), }, }, { token: CommandService, useValue: { executeCommand: jest.fn(), }, }, { token: WorkbenchEditorService, useClass: WorkbenchEditorServiceImpl, }, { token: IDirtyDiffWorkbenchController, useClass: DirtyDiffWorkbenchController, }, ]), ); editorService = injector.get(WorkbenchEditorService); scmPreferences = injector.get(SCMPreferences); commandService = injector.get(CommandService); dirtyDiffWorkbenchController = injector.get(IDirtyDiffWorkbenchController); editorModel = await createModel(`/test/workspace/abc${Math.random()}.ts`); monacoEditor = monacoAPI.editor!.create(document.createElement('div'), { language: 'typescript' }); monacoEditor.setModel(editorModel.getMonacoModel()); }); afterEach(() => { editorFeatureContributions.clear(); monacoEditor.setModel(null); }); it('ok for attachEvents', () => { dirtyDiffWorkbenchController.start(); expect(editorFeatureContributions.size).toBe(1); const mouseDownSpy = jest.spyOn(monacoEditor, 'onMouseDown'); const didChangeModelSpy = jest.spyOn(monacoEditor, 'onDidChangeModel'); // execute editor contribution [...editorFeatureContributions][0].contribute({ monacoEditor } as any); expect(mouseDownSpy).toBeCalledTimes(1); expect(didChangeModelSpy).toBeCalledTimes(1); const $div = document.createElement('div'); $div.classList.add('dirty-diff-glyph'); const toggleWidgetSpy = jest.spyOn(dirtyDiffWorkbenchController, 'toggleDirtyDiffWidget'); monacoEditor['_onMouseDown'].fire({ target: { type: monaco.editor.MouseTargetType.GUTTER_LINE_DECORATIONS, element: $div, position: { lineNumber: 10, column: 5, }, detail: { offsetX: 3, }, }, }); // _doMouseDown // gutterOffsetX < 5 expect(toggleWidgetSpy).toBeCalledTimes(1); monacoEditor['_onMouseDown'].fire({ target: { type: monaco.editor.MouseTargetType.GUTTER_LINE_DECORATIONS, element: $div, position: { lineNumber: 10, column: 5, }, detail: { offsetX: 8, }, }, }); // _doMouseDown // gutterOffsetX >= 5 expect(toggleWidgetSpy).toBeCalledTimes(1); expect(dirtyDiffWorkbenchController['widgets'].get(monacoEditor.getId())).toBeUndefined(); const dirtyDiffModel = injector.get(DirtyDiffModel, [editorModel]); const dirtyDiffWidget = injector.get(DirtyDiffWidget, [monacoEditor, dirtyDiffModel, commandService]); dirtyDiffWorkbenchController['widgets'].set(monacoEditor.getId(), dirtyDiffWidget); expect(dirtyDiffWorkbenchController['widgets'].get(monacoEditor.getId())).not.toBeUndefined(); monacoEditor['_onMouseDown'].fire({ target: { type: monaco.editor.MouseTargetType.GUTTER_LINE_DECORATIONS, element: $div, position: { lineNumber: 10, column: 5, }, detail: { offsetX: 18, }, }, }); // _doMouseDown // gutterOffsetX >= 5 expect(toggleWidgetSpy).toBeCalledTimes(1); expect(dirtyDiffWorkbenchController['widgets'].get(monacoEditor.getId())).toBeUndefined(); monacoEditor['_onDidChangeModel'].fire({ oldModelUrl: null, newModelUrl: Uri.file('def0.ts'), }); // nothing happened monacoEditor['_onDidChangeModel'].fire({ oldModelUrl: Uri.file('abc1.ts'), newModelUrl: Uri.file('def1.ts'), }); // nothing happened dirtyDiffWorkbenchController['widgets'].set(monacoEditor.getId(), dirtyDiffWidget); const disposeSpy = jest.spyOn(dirtyDiffWidget, 'dispose'); monacoEditor['_onDidChangeModel'].fire({ oldModelUrl: Uri.file('abc2.ts'), newModelUrl: Uri.file('def2.ts'), }); // oldWidget.dispose expect(disposeSpy).toBeCalledTimes(1); const disposeSpy1 = jest.spyOn(DisposableCollection.prototype, 'dispose'); monacoEditor['_onDidDispose'].fire(); // disposeCollection.dispose(); expect(disposeSpy).toBeCalledTimes(1); [mouseDownSpy, didChangeModelSpy, toggleWidgetSpy, disposeSpy, disposeSpy1].forEach((spy) => { spy.mockReset(); }); }); it('ok for scm.alwaysShowDiffWidget changes', () => { dirtyDiffWorkbenchController.start(); const dirtyDiffModel = injector.get(DirtyDiffModel, [editorModel]); const dirtyDiffWidget = injector.get(DirtyDiffWidget, [monacoEditor, dirtyDiffModel, commandService]); dirtyDiffWorkbenchController['widgets'].set(monacoEditor.getId(), dirtyDiffWidget); const disposeSpy = jest.spyOn(dirtyDiffWidget, 'dispose'); scmPreferences.onPreferenceChangedEmitter.fire({ preferenceName: 'scm.alwaysShowDiffWidget', scope: PreferenceScope.User, newValue: true, affects: () => false, }); expect(disposeSpy).toBeCalledTimes(0); scmPreferences.onPreferenceChangedEmitter.fire({ preferenceName: 'scm.diffDecorationsGutterWidth', scope: PreferenceScope.User, newValue: false, affects: () => false, }); expect(disposeSpy).toBeCalledTimes(0); scmPreferences.onPreferenceChangedEmitter.fire({ preferenceName: 'scm.alwaysShowDiffWidget', scope: PreferenceScope.User, newValue: false, affects: () => false, }); expect(disposeSpy).toBeCalled(); disposeSpy.mockReset(); }); it('ok for scm.diffDecorations changes', () => { dirtyDiffWorkbenchController.start(); const enableSpy = jest.spyOn<any, any>(dirtyDiffWorkbenchController, 'enable'); const disableSpy = jest.spyOn<any, any>(dirtyDiffWorkbenchController, 'disable'); scmPreferences['scm.diffDecorations'] = 'none'; scmPreferences.onPreferenceChangedEmitter.fire({ preferenceName: 'scm.diffDecorations', scope: PreferenceScope.User, newValue: 'none', affects: () => true, }); // first disabled called when enabled#true expect(disableSpy).toBeCalled(); scmPreferences['scm.diffDecorations'] = 'all'; scmPreferences.onPreferenceChangedEmitter.fire({ preferenceName: 'scm.diffDecorations', scope: PreferenceScope.User, newValue: 'all', affects: () => true, }); expect(enableSpy).toBeCalled(); [enableSpy, disableSpy].forEach((spy) => { spy.mockReset(); }); }); it('ok for enable/disable', () => { dirtyDiffWorkbenchController.start(); const dirtyDiffModel = injector.get(DirtyDiffModel, [editorModel]); const dirtyDiffWidget = injector.get(DirtyDiffWidget, [monacoEditor, dirtyDiffModel, commandService]); dirtyDiffWorkbenchController['widgets'].set(monacoEditor.getId(), dirtyDiffWidget); dirtyDiffWorkbenchController['enabled'] = false; const docModel1 = injector.get(EditorDocumentModel, [URI.file('/test/workspace/abc.ts'), 'test']); editorService.editorGroups.push({ currentOpenType: { type: 'code' }, currentEditor: { currentDocumentModel: docModel1, }, } as any); dirtyDiffWorkbenchController['enable'](); expect(dirtyDiffWorkbenchController['enabled']).toBeTruthy(); expect(dirtyDiffWorkbenchController['models'].length).toBe(1); const textModel1 = docModel1.getMonacoModel(); // dirtyDiff 里使用的 model 是 EditorDocumentModel // 每个 EditorDocumentModel 持有一个 monaco.editor.ITextModel 对象 expect(dirtyDiffWorkbenchController['models'][0]).toEqual(docModel1); expect(dirtyDiffWorkbenchController['models'][0].getMonacoModel()).toEqual(textModel1); expect(dirtyDiffWorkbenchController['items'][docModel1.id]).not.toBeUndefined(); editorService.editorGroups.pop(); // old models dirtyDiffWorkbenchController['models'].push( injector.get(EditorDocumentModel, [URI.file('/test/workspace/def1.ts'), 'test']), ); const docModel2 = injector.get(EditorDocumentModel, [URI.file('/test/workspace/def2.ts'), 'test']); editorService.editorGroups.push({ currentOpenType: { type: 'diff' }, currentEditor: { currentDocumentModel: docModel2, }, } as any); editorService.editorGroups.push({ currentOpenType: { type: 'code' }, currentEditor: { currentDocumentModel: docModel2, }, } as any); editorService.editorGroups.push({ currentOpenType: { type: 'code' }, currentEditor: null, } as any); // eventBus.fire(new EditorGroupChangeEvent({} as any)); dirtyDiffWorkbenchController['enable'](); expect(dirtyDiffWorkbenchController['models'].length).toBe(1); const textModel2 = docModel2.getMonacoModel(); expect(dirtyDiffWorkbenchController['models'][0]).toEqual(docModel2); expect(dirtyDiffWorkbenchController['models'][0].getMonacoModel()).toEqual(textModel2); expect(dirtyDiffWorkbenchController['items'][docModel2.id].model).not.toBeUndefined(); dirtyDiffWorkbenchController['disable'](); expect(dirtyDiffWorkbenchController['enabled']).toBeFalsy(); expect(dirtyDiffWorkbenchController['models']).toEqual([]); expect(dirtyDiffWorkbenchController['items']).toEqual({}); dirtyDiffWorkbenchController['models'].push( injector.get(EditorDocumentModel, [URI.file('/test/workspace/def4.ts'), 'test']), ); dirtyDiffWorkbenchController['disable'](); expect(dirtyDiffWorkbenchController['models'].length).toBe(1); }); it('dispose', () => { dirtyDiffWorkbenchController.start(); const disableSpy = jest.spyOn<any, any>(dirtyDiffWorkbenchController, 'disable'); const dirtyDiffModel = injector.get(DirtyDiffModel, [editorModel]); const dirtyDiffWidget = injector.get(DirtyDiffWidget, [monacoEditor, dirtyDiffModel, commandService]); dirtyDiffWorkbenchController['widgets'].set(monacoEditor.getId(), dirtyDiffWidget); const disposeSpy = jest.spyOn(dirtyDiffWidget, 'dispose'); dirtyDiffWorkbenchController.dispose(); expect(disableSpy).toBeCalledTimes(1); expect(dirtyDiffWorkbenchController['widgets'].size).toBe(0); expect(disposeSpy).toBeCalledTimes(1); }); describe('toggleDirtyDiffWidget', () => { it('ok', () => { const dirtyDiffModel = injector.get(DirtyDiffModel, [editorModel]); const dirtyDiffDecorator = injector.get(DirtyDiffDecorator, [editorModel, dirtyDiffModel]); const dirtyDiffWidget = injector.get(DirtyDiffWidget, [monacoEditor, dirtyDiffModel, commandService]); const change0 = { originalStartLineNumber: 11, originalEndLineNumber: 11, modifiedStartLineNumber: 11, modifiedEndLineNumber: 11, }; const change1 = { originalStartLineNumber: 12, originalEndLineNumber: 12, modifiedStartLineNumber: 12, modifiedEndLineNumber: 12, }; dirtyDiffModel['_changes'] = [change0, change1]; dirtyDiffWidget.updateCurrent(1); dirtyDiffWorkbenchController['items'] = { [editorModel.id]: new DirtyDiffItem(dirtyDiffModel, dirtyDiffDecorator), }; dirtyDiffWorkbenchController['widgets'].set(monacoEditor.getId(), dirtyDiffWidget); const spy = jest.spyOn(dirtyDiffWidget, 'dispose'); // first invoke dirtyDiffWorkbenchController.toggleDirtyDiffWidget(monacoEditor, { lineNumber: 11, column: 5, }); expect(spy).toBeCalledTimes(1); // same: currentIndex === targetIndex expect(dirtyDiffWorkbenchController['widgets'].get(monacoEditor.getId())).toBe(dirtyDiffWidget); dirtyDiffWidget.updateCurrent(2); // second invoke dirtyDiffWorkbenchController.toggleDirtyDiffWidget(monacoEditor, { lineNumber: 11, column: 5, }); expect(spy).toBeCalledTimes(2); // 创建一个新的 widget expect(dirtyDiffWorkbenchController['widgets'].get(monacoEditor.getId())).not.toBe(dirtyDiffWidget); // no widget // 3th invoke const existedWidget = dirtyDiffWorkbenchController['widgets'].get(monacoEditor.getId()); dirtyDiffWorkbenchController['widgets'].delete(monacoEditor.getId()); dirtyDiffWorkbenchController.toggleDirtyDiffWidget(monacoEditor, { lineNumber: 11, column: 5, }); expect(spy).toBeCalledTimes(2); // 创建一个新的 widget const latestWidget = dirtyDiffWorkbenchController['widgets'].get(monacoEditor.getId()); expect(latestWidget).not.toBe(existedWidget); // dirty-diff-widget dispose // latestWidget!.dispose(); // expect(dirtyDiffWorkbenchController['widgets'].get(monacoEditor.getId())).toBeUndefined(); spy.mockReset(); }); it('no dirtyDiffModel', () => { const dirtyDiffModel = injector.get(DirtyDiffModel, [editorModel]); const dirtyDiffWidget = injector.get(DirtyDiffWidget, [monacoEditor, dirtyDiffModel, commandService]); const spy = jest.spyOn(dirtyDiffWidget, 'dispose'); dirtyDiffWorkbenchController['widgets'].set(monacoEditor.getId(), dirtyDiffWidget); dirtyDiffWorkbenchController['items'] = {}; dirtyDiffWorkbenchController.toggleDirtyDiffWidget(monacoEditor, { lineNumber: 11, column: 5, }); expect(spy).not.toBeCalled(); spy.mockReset(); }); it('no position', () => { const spy = jest.spyOn(dirtyDiffWorkbenchController['widgets'], 'get'); dirtyDiffWorkbenchController.toggleDirtyDiffWidget(monacoEditor, undefined as any); expect(spy).not.toBeCalled(); spy.mockReset(); }); it('no model', () => { monacoEditor.setModel(null); const spy = jest.spyOn(dirtyDiffWorkbenchController['widgets'], 'get'); dirtyDiffWorkbenchController.toggleDirtyDiffWidget(monacoEditor, { lineNumber: 10, column: 5, }); expect(spy).not.toBeCalled(); spy.mockReset(); }); }); });
the_stack
import { ENTER, SPACE } from '@angular/cdk/keycodes'; import { HttpErrorResponse } from '@angular/common/http'; import { ChangeDetectorRef, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { MatChipInputEvent, MatDialog } from '@angular/material'; import { Title } from '@angular/platform-browser'; import { ActivatedRoute } from '@angular/router'; import { LoggerService } from '@ngx-engoy/diagnostics-core'; import { FileSaverService } from 'ngx-filesaver'; import { Observable, Subject, Subscription, zip } from 'rxjs'; import { debounceTime } from 'rxjs/operators'; import { BrowseCloudBatchJob, BrowseCloudDocumentWithJobs, BrowseCloudFontSettings, CountingGridModel, JobStatus, jobStatusToString, jobStatusToStringDescription, JobType } from '@browsecloud/models'; import { IDocEntry } from '@browsecloud/models/cg-database'; import { ILexiconWord } from '@browsecloud/models/cg-vocabulary'; import { BrowseCloudService, JobUpdateService } from '@browsecloud/services'; import { AddJobDialogComponent, CloudViewComponent, EditDocumentDialogComponent } from '@browsecloud/shared'; @Component({ selector: 'app-document', templateUrl: './document.component.html', styleUrls: ['./document.component.scss'], }) export class DocumentComponent implements OnInit, OnDestroy { public readonly wordSearchSeparatorKeyCodes: number[] = [ENTER, SPACE]; public readonly defaultFontSettings: BrowseCloudFontSettings = { minimum: 10, quadraticWeight: 45, }; @ViewChild('resultsView', { static: false }) public resultsView: ElementRef<HTMLDivElement>; @ViewChild(CloudViewComponent, { static: false }) public cloudViewComponent: CloudViewComponent; public documentWithJobs: BrowseCloudDocumentWithJobs; public countingGridModel: CountingGridModel; public documentList: IDocEntry[]; public wordsToHighlight: string[]; public highlightPosition: [number, number]; public pinPosition: [number, number]; public documentLoading = true; public documentLoadingFatalErrorText: string; public modelLoading = false; public isDemo = false; public userCanModify = true; public searchWords: ILexiconWord[] = []; public searchWordIds: number[] = []; private updateJobSettingsSubject: Subject<BrowseCloudBatchJob> = new Subject(); private updateJobSettingsSubscription: Subscription; private jobUpdateSubscription: Subscription; constructor( private browseCloudService: BrowseCloudService, private dialog: MatDialog, private loggerService: LoggerService, private route: ActivatedRoute, private titleService: Title, private jobUpdateService: JobUpdateService, private changeDetectorRef: ChangeDetectorRef, private fileSaverService: FileSaverService ) { } public ngOnInit(): void { this.documentLoading = true; const id = this.route.snapshot.paramMap.get('id'); this.titleService.setTitle('BrowseCloud | Document'); // If this is the demo app, this page will be the root url route with length 0. Show the demo data. // Also show the demo data if the id in the route is 'demo'. if (id === 'demo' || this.route.snapshot.url.length === 0) { this.isDemo = true; this.browseCloudService.getDemoData() .subscribe( // No unsubscribe needed. Observable completes. (documentWithJobs) => { this.documentWithJobs = documentWithJobs; this.documentLoading = false; this.getModelFiles(true); }, () => { this.documentLoading = false; } ); return; } this.browseCloudService.getDocumentWithJobs(id) .subscribe( // No unsubscribe needed. Observable completes. (documentWithJobs) => { this.documentWithJobs = documentWithJobs; this.titleService.setTitle(`BrowseCloud | ${this.documentWithJobs.document.displayName}`); this.userCanModify = false; this.browseCloudService.userCanModifyDocument(this.documentWithJobs.document) // No unsubscribe needed. Observable completes. // We don't really care about error handing here. // If the request fails, we just disable the edit button anyway. .subscribe( (userCanModify) => { this.userCanModify = userCanModify; } ); this.documentLoading = false; if (documentWithJobs.jobs != null && documentWithJobs.jobs.length !== 0) { if (documentWithJobs.jobs[0].jobStatus === JobStatus.Success) { this.setupFontSizeSetting(); this.getModelFiles(); } else { this.startJobUpdatesUntilComplete(); } } }, (error: HttpErrorResponse) => { this.documentLoading = false; if (error.status === 401 || error.status === 403) { this.documentLoadingFatalErrorText = 'You do not have permission to access this document. Contact the owner for access.'; } else if (error.status === 400 || error.status === 404) { this.documentLoadingFatalErrorText = 'Document not found.'; } else { this.documentLoadingFatalErrorText = 'Something went wrong.'; } } ); // Debounce job settings updates on font setting change. this.updateJobSettingsSubscription = this.updateJobSettingsSubject .pipe( debounceTime(1000) ) .subscribe((job) => { if (this.userCanModify) { // No unsubscribe needed. Observable completes. this.browseCloudService.putJob(job).subscribe(); } }); this.loggerService.event('DocumentPage.Load', { documentId: id, }); } public ngOnDestroy(): void { if (this.jobUpdateSubscription != null) { this.jobUpdateSubscription.unsubscribe(); } if (this.updateJobSettingsSubscription != null) { this.updateJobSettingsSubscription.unsubscribe(); } } public onEditDocument(): void { const dialogRef = this.dialog.open(EditDocumentDialogComponent); dialogRef.componentInstance.setDocument(this.documentWithJobs.document); this.loggerService.event('DocumentPage.Document.Edit.Start', { documentId: this.documentWithJobs.document.id, }); dialogRef.afterClosed() .subscribe( // No unsubscribe needed. Observable completes. (result) => { if (result != null) { this.documentWithJobs.document = result; this.loggerService.event('DocumentPage.Document.Edit.Complete', { documentId: this.documentWithJobs.document.id, }); } } ); } public onFontSizeChanged(): void { // This forces change detection... Unfortunate, but needed. this.documentWithJobs.jobs[0].settings.fontSettings = { minimum: this.documentWithJobs.jobs[0].settings.fontSettings.minimum, quadraticWeight: this.documentWithJobs.jobs[0].settings.fontSettings.quadraticWeight, }; this.updateJobSettingsSubject.next(this.documentWithJobs.jobs[0]); } public onPinPlaced(gridCoords: [number, number]): void { this.pinPosition = gridCoords; this.updateDocumentList(); } public updateDocumentList(): void { if (this.pinPosition != null) { if (this.resultsView != null) { this.resultsView.nativeElement.scrollTop = 0; } this.documentList = this.countingGridModel.getDocumentEntryList(this.pinPosition[0], this.pinPosition[1], this.searchWordIds); if (this.searchWordIds != null && this.searchWordIds.length !== 0) { this.wordsToHighlight = this.searchWordIds .map((wordId) => this.countingGridModel.vocabulary.getVocabularyWordsById(wordId)) .reduce((a, b) => a.concat(b)); } else { this.wordsToHighlight = null; } } else { this.documentList = []; this.wordsToHighlight = []; } } public onMouseEnterEntryCard(entryId: number): void { const gridMapping = this.countingGridModel.mappings.getPositionOfEntry(entryId); this.highlightPosition = [gridMapping.col, gridMapping.row]; } public onMouseLeaveEntryCard(): void { this.highlightPosition = [null, null]; } public jobStatusToString(jobStatus: JobStatus): string { return jobStatusToString(jobStatus); } public jobStatusToStringDescription(jobStatus: JobStatus): string { return jobStatusToStringDescription(jobStatus, true); } public onAddSearchWord(event: MatChipInputEvent): void { this.loggerService.event('DocumentPage.AddSearchWord', { documentId: this.documentWithJobs.document.id, }); const input = event.input; const value = event.value; if (value != null && value !== '') { const vocabularyWord = this.countingGridModel.vocabulary.getLexiconWordByWord(value); if (vocabularyWord != null) { // Not using push here to trigger change detection. this.searchWords = [...this.searchWords, vocabularyWord]; this.searchWordIds = [...this.searchWordIds, vocabularyWord.wordId]; } else { this.searchWords = [...this.searchWords, { word: value, wordId: null, }]; } } // Reset the input value. if (input != null) { input.value = ''; } this.updateDocumentList(); } public onRemoveSearchWord(word: string): void { this.loggerService.event('DocumentPage.RemoveSearchWord', { documentId: this.documentWithJobs.document.id, }); const indexWord = this.searchWords.findIndex((w) => w.word === word); if (indexWord >= 0) { const vocabWord = this.searchWords[indexWord]; this.searchWords.splice(indexWord, 1); if (vocabWord != null) { const indexId = this.searchWordIds.indexOf(vocabWord.wordId); if (indexId >= 0) { this.searchWordIds.splice(indexId, 1); } } } // Trigger change detection. this.searchWordIds = this.searchWordIds.slice(); this.updateDocumentList(); } public onResetVisualization(): void { // Make pin location null. this.onPinPlaced(null); // Remove all search words. this.searchWordIds = []; this.searchWords = []; // Sent font sizes to default. if (this.documentWithJobs.jobs[0].settings != null) { this.documentWithJobs.jobs[0].settings.fontSettings = this.defaultFontSettings; this.onFontSizeChanged(); } this.cloudViewComponent.resetVisualization(); } public onDownloadResults(): void { this.loggerService.event('DocumentPage.DownloadResults', { documentId: this.documentWithJobs.document.id, }); if (this.documentList == null) { return; } const colDelim = ','; const rowDelim = '\r\n'; let dataForDownload = `Title${colDelim}Text${colDelim}Relevance${colDelim}Link${colDelim}Feature${colDelim}`; this.countingGridModel.database.extraColumns.forEach((key) => dataForDownload += `${key}${colDelim}`); dataForDownload += rowDelim; this.documentList.forEach((result, index) => { const sanitizedTitle = result.title.toLowerCase() !== 'nan' ? result.title.replace(/"/g, '""') : ''; const sanitizedAbstract = result.abstract.toLowerCase() !== 'nan' ? result.abstract.replace(/"/g, '""') : ''; // tslint:disable-next-line:max-line-length dataForDownload += `"${sanitizedTitle}"${colDelim}"${sanitizedAbstract}"${colDelim}${(this.documentList.length - index)}${colDelim}"${result.link}"${colDelim}"${result.feature > 0 ? result.feature : ''}"${colDelim}`; this.countingGridModel.database.extraColumns.forEach((key) => { let value = result.otherFields[key] || ''; value = value.replace(/"/g, '""'); return dataForDownload += `${result.otherFields[key] || ''}${colDelim}`; }); dataForDownload += rowDelim; }); const blob = new Blob([dataForDownload], { type: 'octet/stream' }); this.fileSaverService.save(blob, 'BrowseCloudSearchResults.csv'); } public onAddColor(): void { this.onAddNewJob([JobType.SentimentColoring, JobType.MetadataColoring]); } public onRetrain(): void { this.onAddNewJob([JobType.CountingGridGeneration]); } public onAddNewJob(jobTypeOptions: JobType[]): void { this.loggerService.event('DocumentPage.AddNewJob', { documentId: this.documentWithJobs.document.id, }); const dialogRef = this.dialog.open(AddJobDialogComponent); // target job is defined as the last job that was a counting grids generation. const targetJob = this.documentWithJobs.jobs.find((job) => job.jobType === JobType.CountingGridGeneration); dialogRef.componentInstance.initModal(this.documentWithJobs.document, this.countingGridModel, targetJob, jobTypeOptions); dialogRef.afterClosed() .subscribe( // No unsubscribe needed. Observable completes. (result) => { if (result != null) { this.documentWithJobs.jobs.unshift(result); this.countingGridModel = null; this.onResetVisualization(); this.startJobUpdatesUntilComplete(); } } ); } private startJobUpdatesUntilComplete(): void { this.jobUpdateSubscription = this.jobUpdateService.startConnection() .subscribe( (job) => { if (job != null) { this.browseCloudService.updateJobCache(job); const jobIndex = this.documentWithJobs.jobs.findIndex((j) => j.id === job.id); if (jobIndex !== -1) { this.documentWithJobs.jobs[jobIndex] = job; if (this.documentWithJobs.jobs[0].jobStatus === JobStatus.Success && (this.modelLoading === false || this.countingGridModel == null) ) { this.setupFontSizeSetting(); this.getModelFiles(); // No unsubscribe needed. Observable completes. this.jobUpdateService.stopConnection().subscribe(); } this.changeDetectorRef.detectChanges(); } } } ); } private getModelFiles(isDemo = false): void { this.modelLoading = true; const jobId = this.documentWithJobs.jobs[0].id; const functionToUse: (fileName: string) => Observable<string> = isDemo === false ? (fileName: string) => this.browseCloudService.getJobFile(jobId, fileName) : (fileName: string) => this.browseCloudService.getDemoFile(fileName); zip( functionToUse('top_pi.txt'), functionToUse('colors_browser.txt'), functionToUse('words.txt'), functionToUse('docmap.txt'), functionToUse('database.txt'), functionToUse('legend.txt'), functionToUse('correspondences.txt'), functionToUse('top_pi_layers.txt') ).subscribe( // No unsubscribe needed. Observable completes. // Type declaration below to avoid TS2556. (result: [string, string, string, string, string, string, string, string]) => { this.modelLoading = false; this.documentList = []; try { this.countingGridModel = new CountingGridModel(...result); } catch (ex) { this.loggerService.error(ex, { documentId: this.documentWithJobs.document.id, }); throw ex; } this.changeDetectorRef.detectChanges(); }, () => { this.modelLoading = false; } ); } private setupFontSizeSetting(): void { if (this.documentWithJobs.jobs[0].settings == null) { this.documentWithJobs.jobs[0].settings = {}; } if (this.documentWithJobs.jobs[0].settings.fontSettings == null) { this.documentWithJobs.jobs[0].settings.fontSettings = this.defaultFontSettings; } } }
the_stack
import Util from './Util'; import { getMetadata } from './public'; import Properties from './Properties'; import Timer from './Timer'; import GDriveService from './GDriveService'; import API from './API'; import MimeType from './MimeType'; import Constants from './Constants'; import ErrorMessages from './ErrorMessages'; import FeatureFlag from './FeatureFlag'; import Logging from './Logging'; export default class FileService { gDriveService: GDriveService; timer: Timer; properties: Properties; nativeMimeTypes: string[]; maxNumberOfAttempts: number; constructor( gDriveService: GDriveService, timer: Timer, properties: Properties ) { this.gDriveService = gDriveService; this.timer = timer; this.properties = properties; this.nativeMimeTypes = [ MimeType.DOC, MimeType.DRAWING, MimeType.FOLDER, MimeType.FORM, MimeType.SCRIPT, MimeType.SHEET, MimeType.SLIDES ]; this.maxNumberOfAttempts = 3; // this is arbitrary, could go up or down return this; } /** * Try to copy file to destination parent, or add new folder if it's a folder */ copyFile( file: gapi.client.drive.FileResource ): gapi.client.drive.FileResource { // if folder, use insert, else use copy if (file.mimeType == MimeType.FOLDER) { var r = this.gDriveService.insertFolder( API.copyFileBody( this.properties.map[file.parents[0].id], file.title, MimeType.FOLDER, file.description ) ); // Update list of remaining folders this.properties.remaining.push(file.id); // map source to destination this.properties.map[file.id] = r.id; return r; } else { return this.gDriveService.copyFile( API.copyFileBody(this.properties.map[file.parents[0].id], file.title), file.id ); } } /** * copy permissions from source to destination file/folder */ copyPermissions( srcId: string, owners: { emailAddress: string }[], destId: string ): void { var permissions, destPermissions, i, j; try { permissions = this.gDriveService.getPermissions(srcId).items; } catch (e) { Logging.log({ status: Util.composeErrorMsg(e) }); } // copy editors, viewers, and commenters from src file to dest file if (permissions && permissions.length > 0) { for (i = 0; i < permissions.length; i++) { // if there is no email address, it is only sharable by link. // These permissions will not include an email address, but they will include an ID // Permissions.insert requests must include either value or id, // thus the need to differentiate between permission types try { if (permissions[i].emailAddress) { if (permissions[i].role == 'owner') continue; this.gDriveService.insertPermission( API.permissionBodyValue( permissions[i].role, permissions[i].type, permissions[i].emailAddress ), destId, { sendNotificationEmails: 'false' } ); } else { this.gDriveService.insertPermission( API.permissionBodyId( permissions[i].role, permissions[i].type, permissions[i].id, permissions[i].withLink ), destId, { sendNotificationEmails: 'false' } ); } } catch (e) {} } } // convert old owners to editors if (owners && owners.length > 0) { for (i = 0; i < owners.length; i++) { try { this.gDriveService.insertPermission( API.permissionBodyValue('writer', 'user', owners[i].emailAddress), destId, { sendNotificationEmails: 'false' } ); } catch (e) {} } } // remove permissions that exist in dest but not source // these were most likely inherited from parent try { destPermissions = this.gDriveService.getPermissions(destId).items; } catch (e) { Logging.log({ status: Util.composeErrorMsg(e) }); } if (destPermissions && destPermissions.length > 0) { for (i = 0; i < destPermissions.length; i++) { for (j = 0; j < permissions.length; j++) { if (destPermissions[i].id == permissions[j].id) { break; } // if destPermissions does not exist in permissions, delete it if ( j == permissions.length - 1 && destPermissions[i].role != 'owner' ) { this.gDriveService.removePermission(destId, destPermissions[i].id); } } } } } /** * Process leftover files from prior query results * that weren't processed before script timed out. * Destination folder must be set to the parent of the first leftover item. * The list of leftover items is an equivalent array to fileList returned from the getFiles() query */ handleLeftovers( userProperties: GoogleAppsScript.Properties.UserProperties, ss: GoogleAppsScript.Spreadsheet.Sheet ): void { if (Util.hasSome(this.properties.leftovers, 'items')) { this.properties.currFolderId = this.properties.leftovers.items[0].parents[0].id; this.processFileList(this.properties.leftovers.items, userProperties, ss); } } handleRetries( userProperties: GoogleAppsScript.Properties.UserProperties, ss: GoogleAppsScript.Spreadsheet.Sheet ): void { if (Util.hasSome(this.properties, 'retryQueue')) { this.properties.currFolderId = this.properties.retryQueue[0].parents[0].id; this.processFileList(this.properties.retryQueue, userProperties, ss); } } /** * Loops through array of files.items, * Applies Drive function to each (i.e. copy), * Logs result, * Copies permissions if selected and if file is a Drive document, * Get current runtime and decide if processing needs to stop. */ processFileList( items: gapi.client.drive.FileResource[], userProperties: GoogleAppsScript.Properties.UserProperties, ss: GoogleAppsScript.Spreadsheet.Sheet ): void { while (items.length > 0 && this.timer.canContinue()) { // Get next file from passed file list. var item = items.pop(); if ( item.numberOfAttempts && item.numberOfAttempts > this.maxNumberOfAttempts ) { Logging.logCopyError(ss, item.error, item, this.properties.timeZone); continue; } if (FeatureFlag.SKIP_DUPLICATE_ID) { // if item has already been completed, skip to avoid infinite loop bugs if (this.properties.completed[item.id]) { continue; } } // Copy each (files and folders are both represented the same in Google Drive) try { var newfile = this.copyFile(item); if (FeatureFlag.SKIP_DUPLICATE_ID) { // record that this file has been processed this.properties.completed[item.id] = true; } // log the new file as successful Logging.logCopySuccess(ss, newfile, this.properties.timeZone); } catch (e) { this.properties.retryQueue.unshift({ id: item.id, title: item.title, description: item.description, parents: item.parents, mimeType: item.mimeType, error: e, owners: item.owners, numberOfAttempts: item.numberOfAttempts ? item.numberOfAttempts + 1 : 1 }); } // Copy permissions if selected, and if permissions exist to copy try { if ( this.properties.copyPermissions && this.nativeMimeTypes.indexOf(item.mimeType) !== -1 ) { this.copyPermissions(item.id, item.owners, newfile.id); } } catch (e) { // TODO: logging needed for failed permissions copying? } // Update current runtime and user stop flag this.timer.update(userProperties); } } /** * Create the root folder of the new copy. * Copy permissions from source folder to destination folder if copyPermissions == yes */ initializeDestinationFolder( options: FrontEndOptions, today: string ): gapi.client.drive.FileResource { var destFolder; var destParentID; switch (options.copyTo) { case 'same': destParentID = options.srcParentID; break; case 'custom': destParentID = options.destParentID; break; default: destParentID = this.gDriveService.getRootID(); } if ( options.copyTo === 'custom' && FileService.isDescendant([options.destParentID], options.srcFolderID) ) { throw new Error(ErrorMessages.Descendant); } destFolder = this.gDriveService.insertFolder( API.copyFileBody( destParentID, options.destFolderName, 'application/vnd.google-apps.folder', `Copy of ${options.srcFolderName}, created ${today}` ) ); if (options.copyPermissions) { this.copyPermissions(options.srcFolderID, null, destFolder.id); } return destFolder; } /** * Create the spreadsheet used for logging progress of the copy * @return {File Resource} metadata for logger spreadsheet, or error on fail */ createLoggerSpreadsheet( today: string, destId: string ): gapi.client.drive.FileResource { return this.gDriveService.copyFile( API.copyFileBody(destId, `Copy Folder Log ${today}`), Constants.BaseCopyLogId ); } /** * Create document that is used to store temporary properties information when the app pauses. * Create document as plain text. * This will be deleted upon script completion. */ createPropertiesDocument(destId: string): string { var propertiesDoc = this.gDriveService.insertBlankFile(destId); return propertiesDoc.id; } findPriorCopy( folderId: string ): { spreadsheetId: string; propertiesDocId: string } { // find DO NOT MODIFY OR DELETE file (e.g. propertiesDoc) var query = `'${folderId}' in parents and title contains 'DO NOT DELETE OR MODIFY' and mimeType = '${ MimeType.PLAINTEXT }'`; var p = this.gDriveService.getFiles( query, null, 'modifiedDate,createdDate' ); // find copy log query = `'${folderId}' in parents and title contains 'Copy Folder Log' and mimeType = '${ MimeType.SHEET }'`; var s = this.gDriveService.getFiles(query, null, 'title desc'); try { return { spreadsheetId: s.items[0].id, propertiesDocId: p.items[0].id }; } catch (e) { throw new Error(ErrorMessages.DataFilesNotFound); } } /** * Determines if maybeChildID is a descendant of maybeParentID */ static isDescendant(maybeChildIDs: string[], maybeParentID: string): boolean { // cannot select same folder for (var i = 0; i < maybeChildIDs.length; i++) { if (maybeChildIDs[i] === maybeParentID) { return true; } } var results = []; for (i = 0; i < maybeChildIDs.length; i++) { // get parents of maybeChildID var currentParents = getMetadata(maybeChildIDs[i]).parents; // if at root or no parents, stop if (!currentParents || currentParents.length === 0) { continue; } // check all parents for (i = 0; i < currentParents.length; i++) { if (currentParents[i].id === maybeParentID) { return true; } } // recursively check the parents of the parents results.push( FileService.isDescendant( currentParents.map(function(f) { return f.id; }), maybeParentID ) ); } // check results array for any positives for (i = 0; i < results.length; i++) { if (results[i]) { return true; } } return false; } static getFileLinkForSheet(id: string, title?: string): string { if (id) { return 'https://drive.google.com/open?id=' + id; } return ''; // 2018-12-01: different locales use different delimiters. Simplify link so it works everywhere // return ( // '=HYPERLINK("https://drive.google.com/open?id=' + id + '","' + title + '")' // ); } }
the_stack
'use strict'; // tslint:disable no-unused-expression import * as vscode from 'vscode'; import * as chai from 'chai'; import * as sinon from 'sinon'; import * as sinonChai from 'sinon-chai'; import { TestUtil } from '../TestUtil'; import { PackageRegistryEntry } from '../../extension/registries/PackageRegistryEntry'; import { VSCodeBlockchainOutputAdapter } from '../../extension/logging/VSCodeBlockchainOutputAdapter'; import { ExtensionCommands } from '../../ExtensionCommands'; import { VSCodeBlockchainDockerOutputAdapter } from '../../extension/logging/VSCodeBlockchainDockerOutputAdapter'; import { FabricEnvironmentConnection } from 'ibm-blockchain-platform-environment-v1'; import { Reporter } from '../../extension/util/Reporter'; import { FabricEnvironmentManager, ConnectedState } from '../../extension/fabric/environments/FabricEnvironmentManager'; import { FabricEnvironmentRegistryEntry, FabricRuntimeUtil, LogType, EnvironmentType } from 'ibm-blockchain-platform-common'; import { FabricInstalledSmartContract } from 'ibm-blockchain-platform-common/build/src/fabricModel/FabricInstalledSmartContract'; chai.use(sinonChai); describe('InstantiateCommand', () => { const mySandBox: sinon.SinonSandbox = sinon.createSandbox(); before(async () => { await TestUtil.setupTests(mySandBox); }); describe('InstantiateSmartContract', () => { let fabricRuntimeMock: sinon.SinonStubbedInstance<FabricEnvironmentConnection>; let executeCommandStub: sinon.SinonStub; let logSpy: sinon.SinonSpy; let dockerLogsOutputSpy: sinon.SinonSpy; let sendTelemetryEventStub: sinon.SinonStub; let environmentConnectionStub: sinon.SinonStub; let environmentRegistryStub: sinon.SinonStub; let map: Map<string, Array<string>>; let channelName: string; let peerNames: string[]; let selectedPackage: PackageRegistryEntry; beforeEach(async () => { executeCommandStub = mySandBox.stub(vscode.commands, 'executeCommand'); executeCommandStub.withArgs(ExtensionCommands.CONNECT_TO_GATEWAY).resolves(); executeCommandStub.withArgs(ExtensionCommands.CONNECT_TO_ENVIRONMENT).resolves(); executeCommandStub.callThrough(); fabricRuntimeMock = mySandBox.createStubInstance(FabricEnvironmentConnection); fabricRuntimeMock.connect.resolves(); fabricRuntimeMock.instantiateChaincode.resolves(); fabricRuntimeMock.getInstalledSmartContracts.resolves([]); environmentConnectionStub = mySandBox.stub(FabricEnvironmentManager.instance(), 'getConnection').returns((fabricRuntimeMock)); const environmentRegistryEntry: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry(); environmentRegistryEntry.name = FabricRuntimeUtil.LOCAL_FABRIC; environmentRegistryEntry.managedRuntime = true; environmentRegistryEntry.environmentType = EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT; environmentRegistryStub = mySandBox.stub(FabricEnvironmentManager.instance(), 'getEnvironmentRegistryEntry').returns(environmentRegistryEntry); mySandBox.stub(FabricEnvironmentManager.instance(), 'getState').returns(ConnectedState.CONNECTED); logSpy = mySandBox.spy(VSCodeBlockchainOutputAdapter.instance(), 'log'); dockerLogsOutputSpy = mySandBox.spy(VSCodeBlockchainDockerOutputAdapter.instance(FabricRuntimeUtil.LOCAL_FABRIC), 'show'); sendTelemetryEventStub = mySandBox.stub(Reporter.instance(), 'sendTelemetryEvent'); fabricRuntimeMock.getAllPeerNames.returns(['peerOne']); fabricRuntimeMock.getCommittedSmartContractDefinitions.resolves([]); map = new Map<string, Array<string>>(); map.set('myChannel', ['peerOne']); fabricRuntimeMock.createChannelMap.resolves(map); channelName = 'myChannel'; peerNames = ['peerOne']; selectedPackage = new PackageRegistryEntry({ name: 'myContract', version: '0.0.1', path: undefined, sizeKB: 4 }); }); afterEach(async () => { await vscode.commands.executeCommand(ExtensionCommands.DISCONNECT_GATEWAY); mySandBox.restore(); }); it('should install and instantiate a smart contract', async () => { executeCommandStub.withArgs(ExtensionCommands.INSTALL_SMART_CONTRACT).resolves([undefined, 'none']); const installedContract: FabricInstalledSmartContract = new FabricInstalledSmartContract('myContract@0.0.1', 'myContract'); fabricRuntimeMock.getInstalledSmartContracts.onCall(1).resolves([installedContract]); await vscode.commands.executeCommand(ExtensionCommands.INSTANTIATE_SMART_CONTRACT, channelName, peerNames, selectedPackage, '', [], undefined, undefined); executeCommandStub.should.have.been.calledWithExactly(ExtensionCommands.INSTALL_SMART_CONTRACT, map, selectedPackage); fabricRuntimeMock.instantiateChaincode.should.have.been.calledWith(selectedPackage.name, selectedPackage.version, peerNames, channelName, '', [], undefined, undefined); dockerLogsOutputSpy.should.have.been.called; logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'instantiateSmartContract'); logSpy.getCall(1).should.have.been.calledWith(LogType.SUCCESS, 'Successfully instantiated smart contract'); executeCommandStub.should.have.been.calledWith(ExtensionCommands.REFRESH_GATEWAYS); sendTelemetryEventStub.should.have.been.calledOnceWithExactly('instantiateCommand'); }); it('should instantiate a smart contract that has already been installed', async () => { const installedContract: FabricInstalledSmartContract = new FabricInstalledSmartContract('myContract@0.0.1', 'myContract'); fabricRuntimeMock.getInstalledSmartContracts.resolves([installedContract]); await vscode.commands.executeCommand(ExtensionCommands.INSTANTIATE_SMART_CONTRACT, channelName, peerNames, selectedPackage, '', [], undefined, undefined); executeCommandStub.withArgs(ExtensionCommands.INSTALL_SMART_CONTRACT).should.not.have.been.called; fabricRuntimeMock.instantiateChaincode.should.have.been.calledWith(selectedPackage.name, selectedPackage.version, peerNames, channelName, '', [], undefined, undefined); dockerLogsOutputSpy.should.have.been.called; logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'instantiateSmartContract'); logSpy.getCall(1).should.have.been.calledWith(LogType.SUCCESS, 'Successfully instantiated smart contract'); executeCommandStub.should.have.been.calledWith(ExtensionCommands.REFRESH_GATEWAYS); sendTelemetryEventStub.should.have.been.calledOnceWithExactly('instantiateCommand'); }); it('should instantiate a smart contract on a non-local environment', async () => { const opstoolsEnvironment: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry(); opstoolsEnvironment.name = 'opstoolEnvironment'; opstoolsEnvironment.managedRuntime = true; opstoolsEnvironment.environmentType = EnvironmentType.OPS_TOOLS_ENVIRONMENT; environmentRegistryStub.returns(opstoolsEnvironment); const installedContract: FabricInstalledSmartContract = new FabricInstalledSmartContract('myContract@0.0.1', 'myContract'); fabricRuntimeMock.getInstalledSmartContracts.resolves([installedContract]); await vscode.commands.executeCommand(ExtensionCommands.INSTANTIATE_SMART_CONTRACT, channelName, peerNames, selectedPackage, '', [], undefined, undefined); executeCommandStub.withArgs(ExtensionCommands.INSTALL_SMART_CONTRACT).should.not.have.been.called; fabricRuntimeMock.instantiateChaincode.should.have.been.calledWith(selectedPackage.name, selectedPackage.version, peerNames, channelName, '', [], undefined, undefined); dockerLogsOutputSpy.should.not.have.been.called; logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'instantiateSmartContract'); logSpy.getCall(1).should.have.been.calledWith(LogType.SUCCESS, 'Successfully instantiated smart contract'); executeCommandStub.should.have.been.calledWith(ExtensionCommands.REFRESH_GATEWAYS); sendTelemetryEventStub.should.have.been.calledOnceWithExactly('instantiateCommand'); }); it('should not instantiate if not connected to an environment', async () => { environmentConnectionStub.returns(undefined); await vscode.commands.executeCommand(ExtensionCommands.INSTANTIATE_SMART_CONTRACT, channelName, peerNames, selectedPackage, '', [], undefined, undefined); executeCommandStub.withArgs(ExtensionCommands.INSTALL_SMART_CONTRACT).should.not.have.been.called; fabricRuntimeMock.instantiateChaincode.should.not.have.been.called; logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, 'instantiateSmartContract'); executeCommandStub.withArgs(ExtensionCommands.REFRESH_GATEWAYS).should.not.have.been.called; sendTelemetryEventStub.should.not.have.been.called; }); it('should handle error if smart contract is not installed properly', async () => { executeCommandStub.withArgs(ExtensionCommands.INSTALL_SMART_CONTRACT).resolves([undefined, 'other']); await vscode.commands.executeCommand(ExtensionCommands.INSTANTIATE_SMART_CONTRACT, channelName, peerNames, selectedPackage, '', [], undefined, undefined); executeCommandStub.should.have.been.calledWithExactly(ExtensionCommands.INSTALL_SMART_CONTRACT, map, selectedPackage); fabricRuntimeMock.instantiateChaincode.should.not.have.been.called; dockerLogsOutputSpy.should.not.have.been.called; logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'instantiateSmartContract'); const error: Error = new Error('failed to get contract from peer after install'); logSpy.getCall(1).should.have.been.calledWith(LogType.ERROR, `Error instantiating smart contract: ${error.message}`, `Error instantiating smart contract: ${error.toString()}`); executeCommandStub.withArgs(ExtensionCommands.REFRESH_GATEWAYS).should.not.have.been.called; sendTelemetryEventStub.should.not.have.been.called; }); it('should handle timeout error and contract not installed', async () => { executeCommandStub.withArgs(ExtensionCommands.INSTALL_SMART_CONTRACT).resolves([undefined, 'timeout']); await vscode.commands.executeCommand(ExtensionCommands.INSTANTIATE_SMART_CONTRACT, channelName, peerNames, selectedPackage, '', [], undefined, undefined); executeCommandStub.should.have.been.calledWithExactly(ExtensionCommands.INSTALL_SMART_CONTRACT, map, selectedPackage); fabricRuntimeMock.instantiateChaincode.should.not.have.been.called; dockerLogsOutputSpy.should.not.have.been.called; logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'instantiateSmartContract'); const error: Error = new Error('failed to get contract from peer after install'); logSpy.getCall(1).should.have.been.calledWith(LogType.ERROR, `Error instantiating smart contract: ${error.message}`, `Error instantiating smart contract: ${error.toString()}`); executeCommandStub.withArgs(ExtensionCommands.REFRESH_GATEWAYS).should.not.have.been.called; fabricRuntimeMock.getInstalledSmartContracts.should.have.been.calledTwice; sendTelemetryEventStub.should.not.have.been.called; }); it('should handle timeout error but contract marked as installed (image still building)', async () => { executeCommandStub.withArgs(ExtensionCommands.INSTALL_SMART_CONTRACT).resolves([undefined, 'timeout']); const installedContract: FabricInstalledSmartContract = new FabricInstalledSmartContract('myContract@0.0.1', 'myContract'); fabricRuntimeMock.getInstalledSmartContracts.onCall(1).resolves([installedContract]); await vscode.commands.executeCommand(ExtensionCommands.INSTANTIATE_SMART_CONTRACT, channelName, peerNames, selectedPackage, '', [], undefined, undefined); executeCommandStub.should.have.been.calledWithExactly(ExtensionCommands.INSTALL_SMART_CONTRACT, map, selectedPackage); fabricRuntimeMock.instantiateChaincode.should.not.have.been.called; dockerLogsOutputSpy.should.not.have.been.called; logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'instantiateSmartContract'); const error: Error = new Error('Chaincode installed but timed out waiting for the chaincode image to build. Please redeploy your chaincode package to attempt instantiation'); logSpy.getCall(1).should.have.been.calledWith(LogType.ERROR, `Error instantiating smart contract: ${error.message}`, `Error instantiating smart contract: ${error.toString()}`); executeCommandStub.withArgs(ExtensionCommands.REFRESH_GATEWAYS).should.not.have.been.called; fabricRuntimeMock.getInstalledSmartContracts.should.have.been.calledTwice; sendTelemetryEventStub.should.not.have.been.called; }); it('should handle error', async () => { const error: Error = new Error(`he's dead jim`); executeCommandStub.withArgs(ExtensionCommands.INSTALL_SMART_CONTRACT).rejects(error); await vscode.commands.executeCommand(ExtensionCommands.INSTANTIATE_SMART_CONTRACT, channelName, peerNames, selectedPackage, '', [], undefined, undefined); executeCommandStub.should.have.been.calledWithExactly(ExtensionCommands.INSTALL_SMART_CONTRACT, map, selectedPackage); fabricRuntimeMock.instantiateChaincode.should.not.have.been.called; dockerLogsOutputSpy.should.not.have.been.called; logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'instantiateSmartContract'); logSpy.getCall(1).should.have.been.calledWith(LogType.ERROR, `Error instantiating smart contract: ${error.message}`, `Error instantiating smart contract: ${error.toString()}`); executeCommandStub.withArgs(ExtensionCommands.REFRESH_GATEWAYS).should.not.have.been.called; sendTelemetryEventStub.should.not.have.been.called; }); }); });
the_stack
import { computed, makeObservable, obx, action, runWithGlobalEventOff, wrapWithEventSwitch } from '@alilc/lowcode-editor-core'; import { NodeData, isJSExpression, isDOMText, NodeSchema, isNodeSchema, RootSchema, PageSchema } from '@alilc/lowcode-types'; import { EventEmitter } from 'events'; import { Project } from '../project'; import { ISimulatorHost } from '../simulator'; import { ComponentMeta } from '../component-meta'; import { isDragNodeDataObject, DragNodeObject, DragNodeDataObject, DropLocation, Designer } from '../designer'; import { Node, insertChildren, insertChild, isNode, RootNode, ParentalNode } from './node/node'; import { Selection } from './selection'; import { History } from './history'; import { TransformStage, ModalNodesManager } from './node'; import { uniqueId, isPlainObject, compatStage } from '@alilc/lowcode-utils'; export type GetDataType<T, NodeType> = T extends undefined ? NodeType extends { schema: infer R; } ? R : any : T; export interface ComponentMap { componentName: string; package?: string; version?: string; destructuring?: boolean; exportName?: string; subName?: string; devMode?: 'lowCode' | 'proCode'; } export class DocumentModel { /** * 根节点 类型有:Page/Component/Block */ rootNode: RootNode | null; /** * 文档编号 */ id: string = uniqueId('doc'); /** * 选区控制 */ readonly selection: Selection = new Selection(this); /** * 操作记录控制 */ readonly history: History; /** * 模态节点管理 */ readonly modalNodesManager: ModalNodesManager; private _nodesMap = new Map<string, Node>(); readonly project: Project; readonly designer: Designer; @obx.shallow private nodes = new Set<Node>(); private seqId = 0; private emitter: EventEmitter; private rootNodeVisitorMap: { [visitorName: string]: any } = {}; /** * @deprecated */ private _addons: Array<{ name: string; exportData: any }> = []; /** * 模拟器 */ get simulator(): ISimulatorHost | null { return this.project.simulator; } get nodesMap(): Map<string, Node> { return this._nodesMap; } get fileName(): string { return this.rootNode?.getExtraProp('fileName', false)?.getAsString() || this.id; } set fileName(fileName: string) { this.rootNode?.getExtraProp('fileName', true)?.setValue(fileName); } @computed get focusNode() { if (this._drillDownNode) { return this._drillDownNode; } const selector = this.designer.editor?.get<((rootNode: RootNode) => Node) | null>('focusNodeSelector'); if (selector && typeof selector === 'function') { return selector(this.rootNode!); } return this.rootNode; } @obx.ref private _drillDownNode: Node | null = null; drillDown(node: Node | null) { this._drillDownNode = node; } private _modalNode?: ParentalNode; private _blank?: boolean; private inited = false; constructor(project: Project, schema?: RootSchema) { makeObservable(this); this.project = project; this.designer = this.project?.designer; this.emitter = new EventEmitter(); if (!schema) { this._blank = true; } // 兼容 vision this.id = project.getSchema()?.id || this.id; this.rootNode = this.createNode<RootNode>( schema || { componentName: 'Page', id: 'root', fileName: '', }, ); this.history = new History( () => this.export(TransformStage.Serilize), (schema) => { this.import(schema as RootSchema, true); this.simulator?.rerender(); }, ); this.setupListenActiveNodes(); this.modalNodesManager = new ModalNodesManager(this); this.inited = true; } @obx.shallow private willPurgeSpace: Node[] = []; get modalNode() { return this._modalNode; } get currentRoot() { return this.modalNode || this.focusNode; } addWillPurge(node: Node) { this.willPurgeSpace.push(node); } removeWillPurge(node: Node) { const i = this.willPurgeSpace.indexOf(node); if (i > -1) { this.willPurgeSpace.splice(i, 1); } } isBlank() { return this._blank && !this.isModified(); } /** * 生成唯一id */ nextId(possibleId: string | undefined) { let id = possibleId; while (!id || this.nodesMap.get(id)) { id = `node_${(String(this.id).slice(-10) + (++this.seqId).toString(36)).toLocaleLowerCase()}`; } return id; } /** * 根据 id 获取节点 */ getNode(id: string): Node | null { return this._nodesMap.get(id) || null; } /** * 根据 id 获取节点 */ getNodeCount(): number { return this._nodesMap?.size; } /** * 是否存在节点 */ hasNode(id: string): boolean { const node = this.getNode(id); return node ? !node.isPurged : false; } @obx.shallow private activeNodes?: Node[]; /** * 根据 schema 创建一个节点 */ @action createNode<T extends Node = Node, C = undefined>(data: GetDataType<C, T>, checkId: boolean = true): T { let schema: any; if (isDOMText(data) || isJSExpression(data)) { schema = { componentName: 'Leaf', children: data, }; } else { schema = data; } let node: Node | null = null; if (this.hasNode(schema?.id)) { schema.id = null; } if (schema.id) { node = this.getNode(schema.id); if (node && node.componentName === schema.componentName) { if (node.parent) { node.internalSetParent(null, false); // will move to another position // todo: this.activeNodes?.push(node); } node.import(schema, true); } else if (node) { node = null; } } if (!node) { node = new Node(this, schema, { checkId }); // will add // todo: this.activeNodes?.push(node); } const origin = this._nodesMap.get(node.id); if (origin && origin !== node) { // almost will not go here, ensure the id is unique origin.internalSetWillPurge(); } this._nodesMap.set(node.id, node); this.nodes.add(node); this.emitter.emit('nodecreate', node); return node as any; } public destroyNode(node: Node) { this.emitter.emit('nodedestroy', node); } /** * 插入一个节点 */ insertNode(parent: ParentalNode, thing: Node | NodeData, at?: number | null, copy?: boolean): Node { return insertChild(parent, thing, at, copy); } /** * 插入多个节点 */ insertNodes(parent: ParentalNode, thing: Node[] | NodeData[], at?: number | null, copy?: boolean) { return insertChildren(parent, thing, at, copy); } /** * 移除一个节点 */ removeNode(idOrNode: string | Node) { let id: string; let node: Node | null; if (typeof idOrNode === 'string') { id = idOrNode; node = this.getNode(id); } else { node = idOrNode; id = node.id; } if (!node) { return; } this.internalRemoveAndPurgeNode(node, true); } /** * 内部方法,请勿调用 */ internalRemoveAndPurgeNode(node: Node, useMutator = false) { if (!this.nodes.has(node)) { return; } node.remove(useMutator); } unlinkNode(node: Node) { this.nodes.delete(node); this._nodesMap.delete(node.id); } @obx.ref private _dropLocation: DropLocation | null = null; /** * 内部方法,请勿调用 */ internalSetDropLocation(loc: DropLocation | null) { this._dropLocation = loc; } /** * 投放插入位置标记 */ get dropLocation() { return this._dropLocation; } /** * 包裹当前选区中的节点 */ wrapWith(schema: NodeSchema): Node | null { const nodes = this.selection.getTopNodes(); if (nodes.length < 1) { return null; } const wrapper = this.createNode(schema); if (wrapper.isParental()) { const first = nodes[0]; // TODO: check nesting rules x 2 insertChild(first.parent!, wrapper, first.index); insertChildren(wrapper, nodes); this.selection.select(wrapper.id); return wrapper; } this.removeNode(wrapper); return null; } /** * 导出 schema 数据 */ get schema(): RootSchema { return this.rootNode?.schema as any; } @action import(schema: RootSchema, checkId = false) { const drillDownNodeId = this._drillDownNode?.id; runWithGlobalEventOff(() => { // TODO: 暂时用饱和式删除,原因是 Slot 节点并不是树节点,无法正常递归删除 this.nodes.forEach(node => { if (node.isRoot()) return; this.internalRemoveAndPurgeNode(node, true); }); this.rootNode?.import(schema as any, checkId); this.modalNodesManager = new ModalNodesManager(this); // todo: select added and active track added if (drillDownNodeId) { this.drillDown(this.getNode(drillDownNodeId)); } }); } export(stage: TransformStage = TransformStage.Serilize) { stage = compatStage(stage); // 置顶只作用于 Page 的第一级子节点,目前还用不到里层的置顶;如果后面有需要可以考虑将这段写到 node-children 中的 export const currentSchema = this.rootNode?.export(stage); if (Array.isArray(currentSchema?.children) && currentSchema?.children.length > 0) { const FixedTopNodeIndex = currentSchema.children .filter(i => isPlainObject(i)) .findIndex((i => (i as NodeSchema).props?.__isTopFixed__)); if (FixedTopNodeIndex > 0) { const FixedTopNode = currentSchema.children.splice(FixedTopNodeIndex, 1); currentSchema.children.unshift(FixedTopNode[0]); } } return currentSchema; } /** * 导出节点数据 */ getNodeSchema(id: string): NodeData | null { const node = this.getNode(id); if (node) { return node.schema; } return null; } /** * 是否已修改 */ isModified() { return this.history.isSavePoint(); } // FIXME: does needed? getComponent(componentName: string): any { return this.simulator!.getComponent(componentName); } getComponentMeta(componentName: string): ComponentMeta { return this.designer.getComponentMeta( componentName, () => this.simulator?.generateComponentMetadata(componentName) || null, ); } @obx.ref private _opened = false; @obx.ref private _suspensed = false; /** * 是否为非激活状态 */ get suspensed(): boolean { return this._suspensed || !this._opened; } /** * 与 suspensed 相反,是否为激活状态,这个函数可能用的更多一点 */ get active(): boolean { return !this._suspensed; } /** * @deprecated 兼容 */ get actived(): boolean { return this.active; } /** * 是否打开 */ get opened() { return this._opened; } /** * 切换激活,只有打开的才能激活 * 不激活,打开之后切换到另外一个时发生,比如 tab 视图,切换到另外一个标签页 */ private setSuspense(flag: boolean) { if (!this._opened && !flag) { return; } this._suspensed = flag; this.simulator?.setSuspense(flag); if (!flag) { this.project.checkExclusive(this); } } suspense() { this.setSuspense(true); } activate() { this.setSuspense(false); } /** * 打开,已载入,默认建立时就打开状态,除非手动关闭 */ open(): DocumentModel { const originState = this._opened; this._opened = true; if (originState === false) { this.designer.postEvent('document-open', this); } if (this._suspensed) { this.setSuspense(false); } else { this.project.checkExclusive(this); } return this; } /** * 关闭,相当于 sleep,仍然缓存,停止一切响应,如果有发生的变更没被保存,仍然需要去取数据保存 */ close(): void { this.setSuspense(true); this._opened = false; } /** * 从项目中移除 */ remove() { this.designer.postEvent('document.remove', { id: this.id }); this.purge(); this.project.removeDocument(this); } purge() { this.rootNode?.purge(); this.nodes.clear(); this._nodesMap.clear(); this.rootNode = null; } checkNesting(dropTarget: ParentalNode, dragObject: DragNodeObject | DragNodeDataObject): boolean { let items: Array<Node | NodeSchema>; if (isDragNodeDataObject(dragObject)) { items = Array.isArray(dragObject.data) ? dragObject.data : [dragObject.data]; } else { items = dragObject.nodes; } return items.every((item) => this.checkNestingDown(dropTarget, item)); } checkDropTarget(dropTarget: ParentalNode, dragObject: DragNodeObject | DragNodeDataObject): boolean { let items: Array<Node | NodeSchema>; if (isDragNodeDataObject(dragObject)) { items = Array.isArray(dragObject.data) ? dragObject.data : [dragObject.data]; } else { items = dragObject.nodes; } return items.every((item) => this.checkNestingUp(dropTarget, item)); } /** * 检查对象对父级的要求,涉及配置 parentWhitelist */ checkNestingUp(parent: ParentalNode, obj: NodeSchema | Node): boolean { if (isNode(obj) || isNodeSchema(obj)) { const config = isNode(obj) ? obj.componentMeta : this.getComponentMeta(obj.componentName); if (config) { return config.checkNestingUp(obj, parent); } } return true; } /** * 检查投放位置对子级的要求,涉及配置 childWhitelist */ checkNestingDown(parent: ParentalNode, obj: NodeSchema | Node): boolean { const config = parent.componentMeta; return config.checkNestingDown(parent, obj) && this.checkNestingUp(parent, obj); } // ======= compatibles for vision getRoot() { return this.rootNode; } // add toData toData(extraComps?: string[]) { const node = this.export(TransformStage.Save); const data = { componentsMap: this.getComponentsMap(extraComps), utils: this.getUtilsMap(), componentsTree: [node], }; return data; } getHistory(): History { return this.history; } get root() { return this.rootNode; } /** * @deprecated */ getAddonData(name: string) { const addon = this._addons.find((item) => item.name === name); if (addon) { return addon.exportData(); } } /** * @deprecated */ exportAddonData() { const addons = {}; this._addons.forEach((addon) => { const data = addon.exportData(); if (data === null) { delete addons[addon.name]; } else { addons[addon.name] = data; } }); return addons; } /** * @deprecated */ registerAddon(name: string, exportData: any) { if (['id', 'params', 'layout'].indexOf(name) > -1) { throw new Error('addon name cannot be id, params, layout'); } const i = this._addons.findIndex((item) => item.name === name); if (i > -1) { this._addons.splice(i, 1); } this._addons.push({ exportData, name, }); } acceptRootNodeVisitor( visitorName = 'default', visitorFn: (node: RootNode) => any, ) { let visitorResult = {}; if (!visitorName) { /* eslint-disable-next-line no-console */ console.warn('Invalid or empty RootNodeVisitor name.'); } try { visitorResult = visitorFn.call(this, this.rootNode); this.rootNodeVisitorMap[visitorName] = visitorResult; } catch (e) { console.error('RootNodeVisitor is not valid.'); console.error(e); } return visitorResult; } getRootNodeVisitor(name: string) { return this.rootNodeVisitorMap[name]; } getComponentsMap(extraComps?: string[]) { const componentsMap: ComponentMap[] = []; // 组件去重 const exsitingMap: { [componentName: string]: boolean } = {}; for (const node of this._nodesMap.values()) { const { componentName } = node || {}; if (componentName === 'Slot') continue; if (!exsitingMap[componentName]) { exsitingMap[componentName] = true; if (node.componentMeta?.npm?.package) { componentsMap.push({ ...node.componentMeta.npm, componentName, }); } else { componentsMap.push({ devMode: 'lowCode', componentName, }); } } } // 合并外界传入的自定义渲染的组件 if (Array.isArray(extraComps)) { extraComps.forEach(c => { if (c && !exsitingMap[c]) { const m = this.getComponentMeta(c); if (m && m.npm?.package) { componentsMap.push({ ...m?.npm, componentName: c, }); } } }); } return componentsMap; } /** * 获取 schema 中的 utils 节点,当前版本不判断页面中使用了哪些 utils,直接返回资产包中所有的 utils * @returns */ getUtilsMap() { return this.designer?.editor?.get('assets')?.utils?.map((item: any) => ({ name: item.name, type: item.type || 'npm', // TODO 当前只有 npm 类型,content 直接设置为 item.npm,有 function 类型之后需要处理 content: item.npm, })); } onNodeCreate(func: (node: Node) => void) { const wrappedFunc = wrapWithEventSwitch(func); this.emitter.on('nodecreate', wrappedFunc); return () => { this.emitter.removeListener('nodecreate', wrappedFunc); }; } onNodeDestroy(func: (node: Node) => void) { const wrappedFunc = wrapWithEventSwitch(func); this.emitter.on('nodedestroy', wrappedFunc); return () => { this.emitter.removeListener('nodedestroy', wrappedFunc); }; } /** * @deprecated */ refresh() { console.warn('refresh method is deprecated'); } /** * @deprecated */ onRefresh(/* func: () => void */) { console.warn('onRefresh method is deprecated'); } onReady(fn: Function) { this.designer.editor.on('document-open', fn); return () => { this.designer.editor.removeListener('document-open', fn); }; } private setupListenActiveNodes() { // todo: } } export function isDocumentModel(obj: any): obj is DocumentModel { return obj && obj.rootNode; } export function isPageSchema(obj: any): obj is PageSchema { return obj?.componentName === 'Page'; }
the_stack
import assert from "assert"; import { BigNumber } from "@ethersproject/bignumber"; const getDigits = (numDigits: number) => TEN.pow(numDigits); const MAX_UINT_256 = "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; const PRECISION = 18; const ONE = BigNumber.from(1); const TEN = BigNumber.from(10); const DIGITS = getDigits(PRECISION); const stringRepresentationFormat = /^[0-9]*(\.[0-9]*)?(e[-+]?[0-9]+)?$/; const trailingZeros = /0*$/; const magnitudes = ["", "K", "M", "B", "T"]; const roundedMul = (x: BigNumber, y: BigNumber) => x.mul(y).add(Decimal.HALF.hex).div(DIGITS); /** * Types that can be converted into a Decimal. * * @public */ export type Decimalish = Decimal | number | string; /** * Fixed-point decimal bignumber with 18 digits of precision. * * @remarks * Used by Liquity libraries to precisely represent native currency (e.g. Ether), LUSD and LQTY * amounts, as well as derived metrics like collateral ratios. * * @public */ export class Decimal { static readonly INFINITY = Decimal.fromBigNumberString(MAX_UINT_256); static readonly ZERO = Decimal.from(0); static readonly HALF = Decimal.from(0.5); static readonly ONE = Decimal.from(1); private readonly _bigNumber: BigNumber; /** @internal */ get hex(): string { return this._bigNumber.toHexString(); } /** @internal */ get bigNumber(): string { return this._bigNumber.toString(); } private constructor(bigNumber: BigNumber) { if (bigNumber.isNegative()) { throw new Error("negatives not supported by Decimal"); } this._bigNumber = bigNumber; } static fromBigNumberString(bigNumberString: string): Decimal { return new Decimal(BigNumber.from(bigNumberString)); } private static _fromString(representation: string): Decimal { if (!representation || !representation.match(stringRepresentationFormat)) { throw new Error(`bad decimal format: "${representation}"`); } if (representation.includes("e")) { // eslint-disable-next-line prefer-const let [coefficient, exponent] = representation.split("e"); if (exponent.startsWith("-")) { return new Decimal( Decimal._fromString(coefficient)._bigNumber.div( TEN.pow(BigNumber.from(exponent.substr(1))) ) ); } if (exponent.startsWith("+")) { exponent = exponent.substr(1); } return new Decimal( Decimal._fromString(coefficient)._bigNumber.mul(TEN.pow(BigNumber.from(exponent))) ); } if (!representation.includes(".")) { return new Decimal(BigNumber.from(representation).mul(DIGITS)); } // eslint-disable-next-line prefer-const let [characteristic, mantissa] = representation.split("."); if (mantissa.length < PRECISION) { mantissa += "0".repeat(PRECISION - mantissa.length); } else { mantissa = mantissa.substr(0, PRECISION); } return new Decimal( BigNumber.from(characteristic || 0) .mul(DIGITS) .add(mantissa) ); } static from(decimalish: Decimalish): Decimal { switch (typeof decimalish) { case "object": if (decimalish instanceof Decimal) { return decimalish; } else { throw new Error("invalid Decimalish value"); } case "string": return Decimal._fromString(decimalish); case "number": return Decimal._fromString(decimalish.toString()); default: throw new Error("invalid Decimalish value"); } } private _toStringWithAutomaticPrecision() { const characteristic = this._bigNumber.div(DIGITS); const mantissa = this._bigNumber.mod(DIGITS); if (mantissa.isZero()) { return characteristic.toString(); } else { const paddedMantissa = mantissa.toString().padStart(PRECISION, "0"); const trimmedMantissa = paddedMantissa.replace(trailingZeros, ""); return characteristic.toString() + "." + trimmedMantissa; } } private _roundUp(precision: number) { const halfDigit = getDigits(PRECISION - 1 - precision).mul(5); return this._bigNumber.add(halfDigit); } private _toStringWithPrecision(precision: number) { if (precision < 0) { throw new Error("precision must not be negative"); } const value = precision < PRECISION ? this._roundUp(precision) : this._bigNumber; const characteristic = value.div(DIGITS); const mantissa = value.mod(DIGITS); if (precision === 0) { return characteristic.toString(); } else { const paddedMantissa = mantissa.toString().padStart(PRECISION, "0"); const trimmedMantissa = paddedMantissa.substr(0, precision); return characteristic.toString() + "." + trimmedMantissa; } } toString(precision?: number): string { if (this.infinite) { return "∞"; } else if (precision !== undefined) { return this._toStringWithPrecision(precision); } else { return this._toStringWithAutomaticPrecision(); } } prettify(precision = 2): string { const [characteristic, mantissa] = this.toString(precision).split("."); const prettyCharacteristic = characteristic.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); return mantissa !== undefined ? prettyCharacteristic + "." + mantissa : prettyCharacteristic; } shorten(): string { const characteristicLength = this.toString(0).length; const magnitude = Math.min(Math.floor((characteristicLength - 1) / 3), magnitudes.length - 1); const precision = Math.max(3 * (magnitude + 1) - characteristicLength, 0); const normalized = this.div(new Decimal(getDigits(PRECISION + 3 * magnitude))); return normalized.prettify(precision) + magnitudes[magnitude]; } add(addend: Decimalish): Decimal { return new Decimal(this._bigNumber.add(Decimal.from(addend)._bigNumber)); } sub(subtrahend: Decimalish): Decimal { return new Decimal(this._bigNumber.sub(Decimal.from(subtrahend)._bigNumber)); } mul(multiplier: Decimalish): Decimal { return new Decimal(this._bigNumber.mul(Decimal.from(multiplier)._bigNumber).div(DIGITS)); } div(divider: Decimalish): Decimal { divider = Decimal.from(divider); if (divider.isZero) { return Decimal.INFINITY; } return new Decimal(this._bigNumber.mul(DIGITS).div(divider._bigNumber)); } /** @internal */ _divCeil(divider: Decimalish): Decimal { divider = Decimal.from(divider); if (divider.isZero) { return Decimal.INFINITY; } return new Decimal( this._bigNumber.mul(DIGITS).add(divider._bigNumber.sub(ONE)).div(divider._bigNumber) ); } mulDiv(multiplier: Decimalish, divider: Decimalish): Decimal { multiplier = Decimal.from(multiplier); divider = Decimal.from(divider); if (divider.isZero) { return Decimal.INFINITY; } return new Decimal(this._bigNumber.mul(multiplier._bigNumber).div(divider._bigNumber)); } pow(exponent: number): Decimal { assert(Number.isInteger(exponent)); assert(0 <= exponent && exponent <= 0xffffffff); // Ensure we're safe to use bitwise ops if (exponent === 0) { return Decimal.ONE; } if (exponent === 1) { return this; } let x = this._bigNumber; let y = DIGITS; for (; exponent > 1; exponent >>>= 1) { if (exponent & 1) { y = roundedMul(x, y); } x = roundedMul(x, x); } return new Decimal(roundedMul(x, y)); } get isZero(): boolean { return this._bigNumber.isZero(); } get zero(): this | undefined { if (this.isZero) { return this; } } get nonZero(): this | undefined { if (!this.isZero) { return this; } } get infinite(): this | undefined { if (this.eq(Decimal.INFINITY)) { return this; } } get finite(): this | undefined { if (!this.eq(Decimal.INFINITY)) { return this; } } /** @internal */ get absoluteValue(): this { return this; } lt(that: Decimalish): boolean { return this._bigNumber.lt(Decimal.from(that)._bigNumber); } eq(that: Decimalish): boolean { return this._bigNumber.eq(Decimal.from(that)._bigNumber); } gt(that: Decimalish): boolean { return this._bigNumber.gt(Decimal.from(that)._bigNumber); } gte(that: Decimalish): boolean { return this._bigNumber.gte(Decimal.from(that)._bigNumber); } lte(that: Decimalish): boolean { return this._bigNumber.lte(Decimal.from(that)._bigNumber); } static min(a: Decimalish, b: Decimalish): Decimal { a = Decimal.from(a); b = Decimal.from(b); return a.lt(b) ? a : b; } static max(a: Decimalish, b: Decimalish): Decimal { a = Decimal.from(a); b = Decimal.from(b); return a.gt(b) ? a : b; } } type DifferenceRepresentation = { sign: "" | "+" | "-"; absoluteValue: Decimal }; /** @alpha */ export class Difference { private _number?: DifferenceRepresentation; private constructor(number?: DifferenceRepresentation) { this._number = number; } static between(d1: Decimalish | undefined, d2: Decimalish | undefined): Difference { if (d1 === undefined || d2 === undefined) { return new Difference(undefined); } d1 = Decimal.from(d1); d2 = Decimal.from(d2); if (d1.infinite && d2.infinite) { return new Difference(undefined); } else if (d1.infinite) { return new Difference({ sign: "+", absoluteValue: d1 }); } else if (d2.infinite) { return new Difference({ sign: "-", absoluteValue: d2 }); } else if (d1.gt(d2)) { return new Difference({ sign: "+", absoluteValue: Decimal.from(d1).sub(d2) }); } else if (d2.gt(d1)) { return new Difference({ sign: "-", absoluteValue: Decimal.from(d2).sub(d1) }); } else { return new Difference({ sign: "", absoluteValue: Decimal.ZERO }); } } toString(precision?: number): string { if (!this._number) { return "N/A"; } return this._number.sign + this._number.absoluteValue.toString(precision); } prettify(precision?: number): string { if (!this._number) { return this.toString(); } return this._number.sign + this._number.absoluteValue.prettify(precision); } mul(multiplier: Decimalish): Difference { return new Difference( this._number && { sign: this._number.sign, absoluteValue: this._number.absoluteValue.mul(multiplier) } ); } get nonZero(): this | undefined { return this._number?.absoluteValue.nonZero && this; } get positive(): this | undefined { return this._number?.sign === "+" ? this : undefined; } get negative(): this | undefined { return this._number?.sign === "-" ? this : undefined; } get absoluteValue(): Decimal | undefined { return this._number?.absoluteValue; } get infinite(): this | undefined { return this._number?.absoluteValue.infinite && this; } get finite(): this | undefined { return this._number?.absoluteValue.finite && this; } } /** @alpha */ export class Percent< T extends { infinite?: T | undefined; absoluteValue?: A | undefined; mul?(hundred: 100): T; toString(precision?: number): string; }, A extends { gte(n: string): boolean; } > { private _percent: T; public constructor(ratio: T) { this._percent = ratio.infinite || (ratio.mul && ratio.mul(100)) || ratio; } nonZeroish(precision: number): this | undefined { const zeroish = `0.${"0".repeat(precision)}5`; if (this._percent.absoluteValue?.gte(zeroish)) { return this; } } toString(precision: number): string { return ( this._percent.toString(precision) + (this._percent.absoluteValue && !this._percent.infinite ? "%" : "") ); } prettify(): string { if (this._percent.absoluteValue?.gte("1000")) { return this.toString(0); } else if (this._percent.absoluteValue?.gte("10")) { return this.toString(1); } else { return this.toString(2); } } }
the_stack
import test from 'ava'; import { AuthenticationProgramStateBCH, BytecodeGenerationResult, CompilationEnvironmentBCH, compilerOperationsBCH, createAuthenticationProgramEvaluationCommon, createCompiler, createTransactionContextCommonTesting, dateToLocktime, generateBytecodeMap, hexToBin, instantiateSha256, instantiateVirtualMachineBCH, instructionSetBCHCurrentStrict, OpcodesBCH, TransactionContextBCH, } from '../../lib'; import { expectCompilationResult, privkey, } from './compiler-bch.e2e.spec.helper'; test( '[BCH compiler] built-in variables – current_block_time - error', expectCompilationResult, '<current_block_time>', {}, { errorType: 'resolve', errors: [ { error: 'Cannot resolve "current_block_time" – the "currentBlockTime" property was not provided in the compilation data.', range: { endColumn: 20, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, }, ], success: false, } as BytecodeGenerationResult<AuthenticationProgramStateBCH> ); test( '[BCH compiler] built-in variables – current_block_time', expectCompilationResult, '<current_block_time>', { currentBlockTime: dateToLocktime( new Date('2019-10-13T00:00:00.000Z') ) as number, }, { bytecode: hexToBin('040069a25d'), success: true } ); test( '[BCH compiler] built-in variables – current_block_height - error', expectCompilationResult, '<current_block_height>', {}, { errorType: 'resolve', errors: [ { error: 'Cannot resolve "current_block_height" – the "currentBlockHeight" property was not provided in the compilation data.', range: { endColumn: 22, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, }, ], success: false, } as BytecodeGenerationResult<AuthenticationProgramStateBCH> ); test( '[BCH compiler] built-in variables – current_block_height', expectCompilationResult, '<current_block_height>', { currentBlockHeight: 1 }, { bytecode: hexToBin('51'), success: true } ); test( '[BCH compiler] timeLockType – requires a height-based locktime', expectCompilationResult, '', { transactionContext: { ...createTransactionContextCommonTesting(), locktime: 500000000, }, }, { errorType: 'parse', errors: [ { error: 'The script "test" requires a height-based locktime (less than 500,000,000), but this transaction uses a timestamp-based locktime ("500000000").', range: { endColumn: 0, endLineNumber: 0, startColumn: 0, startLineNumber: 0, }, }, ], success: false, } as BytecodeGenerationResult<AuthenticationProgramStateBCH>, {}, { unlockingScriptTimeLockTypes: { test: 'height' } } ); test( '[BCH compiler] timeLockType – requires a timestamp-based locktime', expectCompilationResult, '', { transactionContext: { ...createTransactionContextCommonTesting(), locktime: 0, }, }, { errorType: 'parse', errors: [ { error: 'The script "test" requires a timestamp-based locktime (greater than or equal to 500,000,000), but this transaction uses a height-based locktime ("0").', range: { endColumn: 0, endLineNumber: 0, startColumn: 0, startLineNumber: 0, }, }, ], success: false, } as BytecodeGenerationResult<AuthenticationProgramStateBCH>, {}, { unlockingScriptTimeLockTypes: { test: 'timestamp' } } ); test( '[BCH compiler] timeLockType – locktime disabled by sequenceNumber', expectCompilationResult, '', { transactionContext: { ...createTransactionContextCommonTesting(), sequenceNumber: 0xffffffff, }, }, { errorType: 'parse', errors: [ { error: 'The script "test" requires a locktime, but this input\'s sequence number is set to disable transaction locktime (0xffffffff). This will cause the OP_CHECKLOCKTIMEVERIFY operation to error when the transaction is verified. To be valid, this input must use a sequence number which does not disable locktime.', range: { endColumn: 0, endLineNumber: 0, startColumn: 0, startLineNumber: 0, }, }, ], success: false, } as BytecodeGenerationResult<AuthenticationProgramStateBCH>, {}, { unlockingScriptTimeLockTypes: { test: 'height' } } ); test( '[BCH compiler] built-in variables – signing_serialization.full_all_outputs - error', expectCompilationResult, '<signing_serialization.full_all_outputs>', { transactionContext: undefined }, { errorType: 'resolve', errors: [ { error: 'Cannot resolve "signing_serialization.full_all_outputs" – the "transactionContext" property was not provided in the compilation data.', range: { endColumn: 40, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, }, ], success: false, } as BytecodeGenerationResult<AuthenticationProgramStateBCH> ); test( '[BCH compiler] built-in variables – signing_serialization - no component or algorithm', expectCompilationResult, '<signing_serialization>', { transactionContext: undefined }, { errorType: 'resolve', errors: [ { error: 'This "signing_serialization" variable could not be resolved because this compiler\'s "signingSerialization" operations require an operation identifier, e.g. \'signing_serialization.version\'.', range: { endColumn: 23, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, }, ], success: false, } as BytecodeGenerationResult<AuthenticationProgramStateBCH> ); /** * While this can't work in a locking or unlocking script (a transaction may * have only one locktime value, and OP_CHECKLOCKTIMEVERIFY must test against * the same type), this must still be supported by the compiler for use cases * such as attestation (for data signatures). */ test( '[BCH compiler] built-in variables – current_block_height and current_block_time', expectCompilationResult, '<current_block_height> <current_block_time>', { currentBlockHeight: 1, currentBlockTime: dateToLocktime( new Date('2019-10-13T00:00:00.000Z') ) as number, }, { bytecode: hexToBin('51040069a25d'), success: true } ); test( '[BCH compiler] errors – multiple reduction errors', expectCompilationResult, '<current_block_height> <current_block_time>', {}, { errorType: 'resolve', errors: [ { error: 'Cannot resolve "current_block_height" – the "currentBlockHeight" property was not provided in the compilation data.', range: { endColumn: 22, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, }, { error: 'Cannot resolve "current_block_time" – the "currentBlockTime" property was not provided in the compilation data.', range: { endColumn: 43, endLineNumber: 1, startColumn: 25, startLineNumber: 1, }, }, ], success: false, } as BytecodeGenerationResult<AuthenticationProgramStateBCH> ); test( '[BCH compiler] built-in variables – signing_serialization - error', expectCompilationResult, '<signing_serialization>', { transactionContext: undefined }, { errorType: 'resolve', errors: [ { error: 'This "signing_serialization" variable could not be resolved because this compiler\'s "signingSerialization" operations require an operation identifier, e.g. \'signing_serialization.version\'.', range: { endColumn: 23, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, }, ], success: false, } as BytecodeGenerationResult<AuthenticationProgramStateBCH> ); test( '[BCH compiler] built-in variables – signing_serialization.full_all_outputs', expectCompilationResult, '<signing_serialization.full_all_outputs>', {}, { bytecode: hexToBin( '4c9d000000001cc3adea40ebfd94433ac004777d68150cce9db4c771bc7de1b297a7b795bbba214e63bf41490e67d34476778f6707aa6c8d2c8dccdf78ae11e40ee9f91e89a705050505050505050505050505050505050505050505050505050505050505050000000000000000000000000000000000c942a06c127c2c18022677e888020afb174208d299354f3ecfedb124a1f3fa450000000041000000' ), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.full_all_outputs_single_input', expectCompilationResult, '<signing_serialization.full_all_outputs_single_input>', {}, { bytecode: hexToBin( '4c9d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005050505050505050505050505050505050505050505050505050505050505050000000000000000000000000000000000c942a06c127c2c18022677e888020afb174208d299354f3ecfedb124a1f3fa4500000000c1000000' ), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.full_corresponding_output', expectCompilationResult, '<signing_serialization.full_corresponding_output>', {}, { bytecode: hexToBin( '4c9d000000001cc3adea40ebfd94433ac004777d68150cce9db4c771bc7de1b297a7b795bbba0000000000000000000000000000000000000000000000000000000000000000050505050505050505050505050505050505050505050505050505050505050500000000000000000000000000000000009c12cfdc04c74584d787ac3d23772132c18524bc7ab28dec4219b8fc5b425f700000000043000000' ), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.full_corresponding_output_single_input', expectCompilationResult, '<signing_serialization.full_corresponding_output_single_input>', {}, { bytecode: hexToBin( '4c9d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000050505050505050505050505050505050505050505050505050505050505050500000000000000000000000000000000009c12cfdc04c74584d787ac3d23772132c18524bc7ab28dec4219b8fc5b425f7000000000c3000000' ), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.full_no_outputs', expectCompilationResult, '<signing_serialization.full_no_outputs>', {}, { bytecode: hexToBin( '4c9d000000001cc3adea40ebfd94433ac004777d68150cce9db4c771bc7de1b297a7b795bbba00000000000000000000000000000000000000000000000000000000000000000505050505050505050505050505050505050505050505050505050505050505000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000042000000' ), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.full_no_outputs_single_input', expectCompilationResult, '<signing_serialization.full_no_outputs_single_input>', {}, { bytecode: hexToBin( '4c9d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005050505050505050505050505050505050505050505050505050505050505050000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c2000000' ), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.corresponding_output', expectCompilationResult, '<signing_serialization.corresponding_output>', {}, { bytecode: hexToBin('51'), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.corresponding_output_hash', expectCompilationResult, '<signing_serialization.corresponding_output_hash>', {}, { bytecode: hexToBin( '209c12cfdc04c74584d787ac3d23772132c18524bc7ab28dec4219b8fc5b425f70' ), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.covered_bytecode_length', expectCompilationResult, '<signing_serialization.covered_bytecode_length>', {}, { bytecode: hexToBin('0100'), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.covered_bytecode', expectCompilationResult, '<signing_serialization.covered_bytecode>', {}, { bytecode: hexToBin('00'), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.locktime', expectCompilationResult, '<signing_serialization.locktime>', {}, { bytecode: hexToBin('0400000000'), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.outpoint_index', expectCompilationResult, '<signing_serialization.outpoint_index>', {}, { bytecode: hexToBin('0400000000'), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.outpoint_transaction_hash', expectCompilationResult, '<signing_serialization.outpoint_transaction_hash>', {}, { bytecode: hexToBin( '200505050505050505050505050505050505050505050505050505050505050505' ), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.output_value', expectCompilationResult, '<signing_serialization.output_value>', {}, { bytecode: hexToBin('080000000000000000'), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.sequence_number', expectCompilationResult, '<signing_serialization.sequence_number>', {}, { bytecode: hexToBin('0400000000'), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.transaction_outpoints', expectCompilationResult, '<signing_serialization.transaction_outpoints>', {}, { bytecode: hexToBin('52'), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.transaction_outpoints_hash', expectCompilationResult, '<signing_serialization.transaction_outpoints_hash>', {}, { bytecode: hexToBin( '201cc3adea40ebfd94433ac004777d68150cce9db4c771bc7de1b297a7b795bbba' ), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.transaction_outputs', expectCompilationResult, '<signing_serialization.transaction_outputs>', {}, { bytecode: hexToBin('53'), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.transaction_outputs_hash', expectCompilationResult, '<signing_serialization.transaction_outputs_hash>', {}, { bytecode: hexToBin( '20c942a06c127c2c18022677e888020afb174208d299354f3ecfedb124a1f3fa45' ), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.transaction_sequence_numbers', expectCompilationResult, '<signing_serialization.transaction_sequence_numbers>', {}, { bytecode: hexToBin('54'), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.transaction_sequence_numbers_hash', expectCompilationResult, '<signing_serialization.transaction_sequence_numbers_hash>', {}, { bytecode: hexToBin( '20214e63bf41490e67d34476778f6707aa6c8d2c8dccdf78ae11e40ee9f91e89a7' ), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.version', expectCompilationResult, '<signing_serialization.version>', {}, { bytecode: hexToBin('0400000000'), success: true, } ); test( '[BCH compiler] built-in variables – signing_serialization.covered_bytecode - unlocking script not in unlockingScripts', expectCompilationResult, '<signing_serialization.covered_bytecode>', {}, { errorType: 'resolve', errors: [ { error: 'Identifier "signing_serialization.covered_bytecode" requires a signing serialization, but "coveredBytecode" cannot be determined because "test" is not present in the compilation environment "unlockingScripts".', range: { endColumn: 40, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, }, ], success: false, } as BytecodeGenerationResult<AuthenticationProgramStateBCH>, {}, { unlockingScripts: {}, } ); test( '[BCH compiler] built-in variables – signing_serialization.covered_bytecode - unknown covered script', expectCompilationResult, '<signing_serialization.covered_bytecode>', {}, { errorType: 'resolve', errors: [ { error: 'Identifier "signing_serialization.covered_bytecode" requires a signing serialization which covers an unknown locking script, "some_unknown_script".', range: { endColumn: 40, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, }, ], success: false, } as BytecodeGenerationResult<AuthenticationProgramStateBCH>, {}, { unlockingScripts: { test: 'some_unknown_script', }, } ); test( '[BCH compiler] built-in variables – signing_serialization.covered_bytecode - error in coveredBytecode compilation', expectCompilationResult, '', {}, { errorType: 'resolve', errors: [ { error: 'Compilation error in resolved script "lock": [1, 1] Unknown identifier "invalid".', range: { endColumn: 40, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, }, ], success: false, } as BytecodeGenerationResult<AuthenticationProgramStateBCH>, {}, { scripts: { lock: 'invalid', test: '<signing_serialization.full_all_outputs>', }, } ); test( '[BCH compiler] built-in variables – signing_serialization.unknown', expectCompilationResult, '<signing_serialization.unknown>', {}, { errorType: 'resolve', errors: [ { error: 'The identifier "signing_serialization.unknown" could not be resolved because the "signing_serialization.unknown" operation is not available to this compiler.', range: { endColumn: 31, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, }, ], success: false, } as BytecodeGenerationResult<AuthenticationProgramStateBCH> ); test( '[BCH compiler] built-in variables – signing_serialization: unrecognized identifier fragment', expectCompilationResult, '<signing_serialization.full_all_outputs.future_operation.with_more_levels>', {}, { errorType: 'resolve', errors: [ { error: 'Unknown component in "signing_serialization.full_all_outputs.future_operation.with_more_levels" – the fragment "future_operation" is not recognized.', range: { endColumn: 74, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, }, ], success: false, } as BytecodeGenerationResult<AuthenticationProgramStateBCH> ); const sha256Promise = instantiateSha256(); const vmPromise = instantiateVirtualMachineBCH(instructionSetBCHCurrentStrict); test('[BCH compiler] signing_serialization.corresponding_output and signing_serialization.corresponding_output_hash – returns empty bytecode if no corresponding output', async (t) => { const sha256 = await sha256Promise; const vm = await vmPromise; const compiler = createCompiler< TransactionContextBCH, CompilationEnvironmentBCH, OpcodesBCH, AuthenticationProgramStateBCH >({ createAuthenticationProgram: createAuthenticationProgramEvaluationCommon, opcodes: generateBytecodeMap(OpcodesBCH), operations: compilerOperationsBCH, scripts: { // eslint-disable-next-line camelcase, @typescript-eslint/naming-convention corresponding_output: '<1> <signing_serialization.corresponding_output> <2>', // eslint-disable-next-line camelcase, @typescript-eslint/naming-convention corresponding_output_hash: '<1> <signing_serialization.corresponding_output_hash> <2>', }, sha256, variables: { a: { type: 'Key', }, }, vm, }); const data = { keys: { privateKeys: { a: privkey } }, transactionContext: { ...createTransactionContextCommonTesting(), ...{ correspondingOutput: undefined, }, }, }; t.deepEqual(compiler.generateBytecode('corresponding_output', data), { bytecode: hexToBin('510052'), success: true, }); t.deepEqual(compiler.generateBytecode('corresponding_output_hash', data), { bytecode: hexToBin('510052'), success: true, }); });
the_stack
import {assert} from '../../platform/chai-web.js'; import {Manifest} from '../manifest.js'; import {Entity, EntityClass} from '../entity.js'; import {IdGenerator, Id} from '../id.js'; import {EntityType, Schema} from '../../types/lib-types.js'; import {SYMBOL_INTERNALS} from '../symbols.js'; import {ConCap} from '../../testing/test-util.js'; import {Ttl} from '../capabilities.js'; import {MockStorageFrontend} from '../storage/testing/test-storage.js'; describe('Entity', () => { let schema: Schema; let entityClass: EntityClass; before(async () => { const manifest = await Manifest.parse(` schema ExternalInline txt: Text schema Foo txt: Text lnk: URL num: Number flg: Boolean buf: Bytes ref: &{z: Text} tuple: (Text, URL, Number, Boolean, Bytes) union: (Text or URL or Number or Boolean or Bytes) kt: Long lst: List<Number> inner: inline { txt: Text, num: Number } inner2: inline ExternalInline `); schema = manifest.findSchemaByName('Foo'); entityClass = Entity.createEntityClass(schema, new MockStorageFrontend()); }); it('behaves like a regular object except writing to any field fails', () => { const e = new entityClass({txt: 'abc', num: 56, lst: [1, 2, 5, 4, 3], inner: {txt: 'def', num: 78}, inner2: {txt: 'ghi'}}); assert.strictEqual(e.txt, 'abc'); assert.strictEqual(e.num, 56); assert.isUndefined(e.flg); assert.isUndefined(e.notInTheSchema); assert.strictEqual(e['txt'], 'abc'); assert.strictEqual(e['num'], 56); assert.isUndefined(e['flg']); assert.isUndefined(e['notInTheSchema']); assert.throws(() => { e.num = 3; }, `Tried to modify entity field 'num'`); assert.throws(() => { e['num'] = 3; }, `Tried to modify entity field 'num'`); assert.throws(() => { e.notInSchema = 3; }, `Tried to modify entity field 'notInSchema'`); assert.throws(() => {e['lst'] = []; }, `Tried to modify entity field 'lst'`); assert.strictEqual(JSON.stringify(e), '{"txt":"abc","num":56,"lst":[1,2,5,4,3],"inner":{"txt":"def","num":78},"inner2":{"txt":"ghi"}}'); assert.strictEqual(e.toString(), 'Foo { txt: "abc", num: 56, lst: [1,2,5,4,3], inner: { txt: "def", num: 78 }, inner2: { txt: "ghi" } }'); assert.strictEqual(`${e}`, 'Foo { txt: "abc", num: 56, lst: [1,2,5,4,3], inner: { txt: "def", num: 78 }, inner2: { txt: "ghi" } }'); assert.deepEqual(Object.entries(e), [['txt', 'abc'], ['num', 56], ['lst', [1, 2, 5, 4, 3]], ['inner', {txt: 'def', num: 78}], ['inner2', {txt: 'ghi'}]]); assert.deepEqual(Object.keys(e), ['txt', 'num', 'lst', 'inner', 'inner2']); assert.deepEqual(Object.values(e), ['abc', 56, [1, 2, 5, 4, 3], {txt: 'def', num: 78}, {txt: 'ghi'}]); }); it('static Entity API maps onto EntityInternals methods', () => { // Mutation APIs are tested below. const e = new entityClass({txt: 'abc', num: 56}); assert.isFalse(Entity.isIdentified(e)); const now = new Date().getTime(); Entity.identify(e, 'id1', null, now); assert.isTrue(Entity.isIdentified(e)); assert.strictEqual(Entity.id(e), 'id1'); assert.strictEqual(Entity.creationTimestamp(e).getTime(), now); const e2 = new entityClass({txt: 'abc'}); assert.isFalse(Entity.isIdentified(e2)); Entity.createIdentity(e2, Id.fromString('id2'), IdGenerator.createWithSessionIdForTesting('s'), null, Ttl.infinite()); assert.isTrue(Entity.isIdentified(e2)); assert.strictEqual(Entity.id(e2), '!s:id2:0'); assert.deepEqual(Entity.dataClone(e), {txt: 'abc', num: 56}); assert.deepEqual(Entity.serialize(e), {id: 'id1', creationTimestamp: now, rawData: {txt: 'abc', num: 56}}); assert.strictEqual(Entity.entityClass(e), entityClass); // Static methods assert.deepEqual(entityClass.type, new EntityType(schema)); assert.deepEqual(entityClass.key, {tag: 'entity', schema}); assert.strictEqual(entityClass.schema, schema); }); it('schema fields can use the same names as internal fields and methods', async () => { const manifest = await Manifest.parse(` schema Shadow // internal fields id: Text mutable: Boolean // static fields schema: URL type: Number // internal methods (exposed via Entity static methods) toLiteral: Number makeImmutable: Text `); const schema = manifest.schemas.Shadow; const entityClass = Entity.createEntityClass(schema, null); const data = {id: 'schema-id', mutable: false, schema: 'url', type: 81, toLiteral: 23, makeImmutable: 'make'}; const e = new entityClass(data); Entity.identify(e, 'arcs-id', null); // Reading the schema fields should match the input data fields. assert.strictEqual(e.id, 'schema-id'); assert.isFalse(e.mutable); assert.strictEqual(e.schema, 'url'); assert.strictEqual(e.type, 81); assert.strictEqual(e.toLiteral, 23); assert.strictEqual(e.makeImmutable, 'make'); // Accessing the internals should be unaffected. assert.strictEqual(Entity.id(e), 'arcs-id'); assert.isTrue(Entity.isMutable(e)); assert.strictEqual(entityClass.schema, schema); assert.deepEqual(entityClass.type, new EntityType(schema)); assert.deepEqual(Entity.toLiteral(e), data); Entity.makeImmutable(e); assert.isFalse(Entity.isMutable(e)); }); it(`Entity.debugLog doesn't affect the original entity`, async () => { const e = new entityClass({ txt: 'abc', lnk: 'http://wut', num: 3.7, flg: true, buf: new Uint8Array([2]), tuple: ['def', '404', 0, true, new Uint8Array()], union: 'str', }); Entity.identify(e, '!test:uid:u0', null); const fields = JSON.stringify(e); const internals = JSON.stringify(e[SYMBOL_INTERNALS]); // debugLog uses a single call to console.dir with the entity copy as the first argument. const cc = ConCap.capture(() => Entity.debugLog(e)); const dirArg = cc.dir[0][0]; // The dir'd object should be an Entity with an Internals object, both different from the original. assert.instanceOf(dirArg, Entity); assert.isDefined(dirArg[SYMBOL_INTERNALS]); assert.notStrictEqual(dirArg, e); assert.notStrictEqual(dirArg[SYMBOL_INTERNALS], e[SYMBOL_INTERNALS]); // Spot check a couple of fields. assert.strictEqual(dirArg.txt, 'abc'); assert.strictEqual(dirArg.num, 3.7); // The original entity should not have been modified. assert.strictEqual(JSON.stringify(e), fields); assert.strictEqual(JSON.stringify(e[SYMBOL_INTERNALS]), internals); }); it('is mutable by default', () => { const e = new entityClass({txt: 'abc'}); assert.isTrue(Entity.isMutable(e)); assert.strictEqual(e.txt, 'abc'); }); it('allows mutations via the mutate method with a callback function', () => { const e = new entityClass({txt: 'abc', num: 56, lst: [1, 2, 5, 4, 3], inner: {txt: 'def', num: 78}}); Entity.mutate(e, e => e.txt = 'xyz'); assert.strictEqual(e.txt, 'xyz'); assert.strictEqual(e.num, 56); assert.deepEqual(e.lst, [1, 2, 5, 4, 3]); Entity.mutate(e, e => e.lst = []); assert.strictEqual(e.num, 56); assert.deepEqual(e.lst, []); Entity.mutate(e, e => e.inner = {txt: 'ghi', num: 90}); assert.deepEqual(e.inner, {txt: 'ghi', num: 90}); }); it('allows mutations via the mutate method with new data', () => { const e = new entityClass({txt: 'abc', num: 56}); Entity.mutate(e, {num: 35, lst: [1, 2, 3], inner: {txt: 'def', num: 78}}); assert.strictEqual(e.txt, 'abc'); assert.strictEqual(e.num, 35); assert.deepEqual(e.lst, [1, 2, 3]); assert.deepEqual(e.inner, {txt: 'def', num: 78}); }); it('prevents mutating a list if contained values are not of the appropriate type', () => { const e = new entityClass({}); assert.throws(() => Entity.mutate(e, {lst: ['foo']}), `Type mismatch setting field lst`); assert.throws(() => Entity.mutate(e, {lst: [1, 2, 'foo']}), `Type mismatch setting field lst`); }); it('prevents mutating a nested schema if values are not of the appropriate type', () => { const e = new entityClass({}); assert.throws(() => Entity.mutate(e, {inner: 77}), 'Cannot set nested schema inner with non-object'); assert.throws(() => Entity.mutate(e, {inner: {txt: 3}}), 'Type mismatch setting field txt'); assert.throws(() => Entity.mutate(e, {inner: {blah: 77}}), 'not in schema undefined'); assert.throws(() => Entity.mutate(e, {inner2: 77}), 'Cannot set nested schema inner2 with non-object'); assert.throws(() => Entity.mutate(e, {inner2: {txt: 3}}), 'Type mismatch setting field txt'); assert.throws(() => Entity.mutate(e, {inner2: {num: 77}}), 'not in schema ExternalInline'); }); it('prevents mutations of Kotlin types', () => { const e = new entityClass({txt: 'abc', num: 56}); assert.throws(() => Entity.mutate(e, {kt: 300}), `Kotlin primitive values can't yet be used`); }); it('prevents construction that sets Kotlin types', () => { assert.throws(() => new entityClass({txt: 'abc', num: 56, kt: 42}), `Kotlin primitive values can't yet be used`); }); it('forbids mutations via setters', () => { const e = new entityClass({txt: 'abc'}); assert.throws(() => e.txt = 'xyz', `Tried to modify entity field 'txt'`); assert.strictEqual(e.txt, 'abc'); }); it('rejects mutations when immutable', () => { const e = new entityClass({txt: 'abc', num: 56}); Entity.makeImmutable(e); assert.throws(() => { Entity.mutate(e, e => e.num = 35); }, 'Entity is immutable'); assert.throws(() => { Entity.mutate(e, {txt: 'xyz'}); }, 'Entity is immutable'); assert.strictEqual(e.txt, 'abc'); assert.strictEqual(e.num, 56); }); it('dataClone supports all field types and performs deep copies', async () => { const creationTimestamp = new Date(); const expirationTimestamp = new Date(creationTimestamp.getTime() + 1000); const storageKey = 'reference-mode://{volatile://!1:test/backing@}{volatile://!2:test/container@}'; const e1 = new entityClass({ txt: 'abc', lnk: 'site', num: 45.8, flg: true, buf: new Uint8Array([25, 73]), ref: {id: 'i1', entityStorageKey: storageKey, creationTimestamp, expirationTimestamp}, tuple: ['def', 'link', -12, true, new Uint8Array([5, 7])], union: new Uint8Array([80]), lst: [1, 2, 5, 4, 3], inner: {txt: 'def', num: 45} }); const e2 = new entityClass(Entity.dataClone(e1)); assert.deepStrictEqual(e1, e2); // Object-based fields should *not* refer to the same instances. assert.isFalse(e1.buf === e2.buf); assert.isFalse(e1.ref === e2.ref); assert.isFalse(e1.tuple === e2.tuple); assert.isFalse(e1.union === e2.union); assert.isFalse(e1.lst === e2.lst); assert.isFalse(e1.inner === e2.inner); // Modify all non-reference object fields on e1 and confirm e2 is not affected. e1.buf.fill(9); e1.tuple[2] = 20; e1.tuple[4].fill(2); e1.union.fill(0); e1.lst[3] = 6; Entity.mutate(e1.inner, {txt: 'bar'}); assert.deepStrictEqual(e2.buf, new Uint8Array([25, 73])); assert.deepStrictEqual(e2.tuple, ['def', 'link', -12, true, new Uint8Array([5, 7])]); assert.deepStrictEqual(e2.union, new Uint8Array([80])); assert.deepStrictEqual(e2.lst, [1, 2, 5, 4, 3]); assert.deepStrictEqual(e2.inner, {txt: 'def', num: 45}); }); // TODO(mmandlis): add tests with TTLs });
the_stack
import { CodeNode, ensureEnvironment, ExpressionNode, ProgramResult, runProgram, } from "literate-elm"; import _ from "lodash"; import { Position } from "unist"; import visit from "unist-util-visit"; import { Cache, CodeBlock, EvaluatedOutputExpression, FailedLitvisContext, LitvisCodeBlock, LitvisNarrative, OutputExpression, ProcessedLitvisContext, SucceededLitvisContext, } from "../types"; interface WrappedCodeBlock { documentIndex: number; subject: LitvisCodeBlock; } interface WrappedOutputExpression { documentIndex: number; subject: OutputExpression; } interface UnprocessedLitvisContext { name: string; wrappedCodeBlocks: WrappedCodeBlock[]; wrappedOutputExpressions: WrappedOutputExpression[]; } const fallbackPosition: Position = { start: { column: 0, line: 0 }, end: { column: 0, line: 0 }, }; export const processElmContexts = async ( narrative: LitvisNarrative, cache: Cache, ): Promise<void> => { // const documentPaths = _.map(narrative.documents, (document) => document.path); // const documentIndexByPath: { [path: string]: number } = _.mapValues( // _.invert(documentPaths), // (v) => parseInt(v, 10), // ); const lastDocument = _.last(narrative.documents); const lastDocumentIndex = narrative.documents.length - 1; if (!lastDocument) { return; } const literateElmJobs: Array<{ contextName: string; codeNodes: CodeNode[]; expressionNodes: ExpressionNode[]; }> = []; try { const wrappedCodeBlocksInAllDocuments: WrappedCodeBlock[] = []; const wrappedCodeBlocksInLastDocument: WrappedCodeBlock[] = []; _.forEach(narrative.documents, (document, documentIndex) => { visit<CodeBlock>(document.data.root, "code", (codeBlock) => { if (codeBlock.data && codeBlock.data.litvisAttributeDerivatives) { const wrappedCodeBlock: WrappedCodeBlock = { subject: codeBlock as LitvisCodeBlock, documentIndex, }; wrappedCodeBlocksInAllDocuments.push(wrappedCodeBlock); if (document === lastDocument) { wrappedCodeBlocksInLastDocument.push(wrappedCodeBlock); } } }); }); const wrappedOutputExpressionsInLastFile: WrappedOutputExpression[] = []; visit( lastDocument.data.root, "outputExpression", (outputExpression: OutputExpression) => { wrappedOutputExpressionsInLastFile.push({ subject: outputExpression, documentIndex: lastDocumentIndex, }); }, ); // build contexts by tracing down chains of code blocks const foundContextsByName: { [name: string]: UnprocessedLitvisContext; } = {}; _.forEachRight( wrappedCodeBlocksInAllDocuments, (wrappedCodeBlock, index) => { const derivatives = wrappedCodeBlock.subject.data.litvisAttributeDerivatives; const contextName = derivatives.contextName; // skip if a code block belongs to a context that is already considered if (foundContextsByName[contextName]) { return; } // ignore contexts where last code blocks do not belong to the last document if (!_.includes(wrappedCodeBlocksInLastDocument, wrappedCodeBlock)) { return; } const context: UnprocessedLitvisContext = { name: contextName, wrappedCodeBlocks: [], wrappedOutputExpressions: [], }; foundContextsByName[contextName] = context; let currentIndex = index; let currentContextName = contextName; do { context.wrappedCodeBlocks.unshift( wrappedCodeBlocksInAllDocuments[currentIndex], ); if (currentIndex === 0) { break; } const follows = wrappedCodeBlocksInAllDocuments[currentIndex].subject.data .litvisAttributeDerivatives.follows; if (follows) { currentIndex = _.findLastIndex( wrappedCodeBlocksInAllDocuments, (b) => b.subject.data.litvisAttributeDerivatives.id === follows || b.subject.data.litvisAttributeDerivatives.contextName === follows, currentIndex - 1, ); if (currentIndex !== -1) { currentContextName = wrappedCodeBlocksInAllDocuments[currentIndex].subject.data .litvisAttributeDerivatives.contextName; } } else { currentIndex = _.findLastIndex( wrappedCodeBlocksInAllDocuments, (b) => b.subject.data.litvisAttributeDerivatives.contextName === currentContextName, currentIndex - 1, ); } } while (currentIndex >= 0); }, ); // add output expressions to contexts _.forEach(wrappedOutputExpressionsInLastFile, (wrappedOutputExpression) => { const contextName = wrappedOutputExpression.subject.data.contextName; if (foundContextsByName[contextName]) { foundContextsByName[contextName].wrappedOutputExpressions.push( wrappedOutputExpression, ); } else { foundContextsByName[contextName] = { name: contextName, wrappedCodeBlocks: [], wrappedOutputExpressions: [wrappedOutputExpression], }; } }); _.forEach( foundContextsByName, ({ wrappedCodeBlocks, wrappedOutputExpressions }, contextName) => { const codeNodes: CodeNode[] = _.map( wrappedCodeBlocks, (wrappedCodeBlock) => ({ text: wrappedCodeBlock.subject.value, position: wrappedCodeBlock.subject.position || fallbackPosition, fileIndex: wrappedCodeBlock.documentIndex, }), ); const expressionNodes: ExpressionNode[] = _.map( wrappedOutputExpressions, (wrappedOutputExpression) => ({ text: wrappedOutputExpression.subject.data.text, position: wrappedOutputExpression.subject.position || fallbackPosition, fileIndex: wrappedOutputExpression.documentIndex, }), ); literateElmJobs.push({ contextName, codeNodes, expressionNodes, }); }, ); if (!literateElmJobs.length) { return; } const literateElmEnvironment = await ensureEnvironment( narrative.elmEnvironmentSpecForLastFile!, cache.literateElmDirectory, ); if (literateElmEnvironment.metadata.status !== "ready") { try { lastDocument.fail( literateElmEnvironment.metadata.errorMessage || "Unknown error", undefined, "litvis:elm-environment", ); } catch (e) { // no need for action - just preventing .fail() from throwing further } return; } const literateElmProgramPromises: Array<Promise<ProgramResult>> = literateElmJobs.map(({ codeNodes, expressionNodes }) => runProgram({ environment: literateElmEnvironment, codeNodes, expressionNodes, }), ); const literateElmProgramResults = await Promise.all( literateElmProgramPromises, ); // map literate-elm messages to vfile messages const allMessages = _.flatten( _.map(literateElmProgramResults, (result) => result.messages), ); const messagesGroupedByPositionAndText = _.groupBy( allMessages, (message) => `${JSON.stringify(message.position)}|${message.text}`, ); _.forEach(messagesGroupedByPositionAndText, (messageGroup) => { const message = messageGroup[0]; const document = narrative.documents[message.fileIndex]; switch (message.severity) { case "info": { document.info(message.text, message.position, "literate-elm:compile"); break; } case "warning": { document.message( message.text, message.position, "literate-elm:compile", ); break; } default: { try { document.fail( message.text, message.position, "literate-elm:compile", ); } catch (e) { // no need for action - just preventing .fail() from throwing further } } } }); const processedContexts: ProcessedLitvisContext[] = _.map( literateElmJobs, ({ contextName }, index) => { const literateElmProgramResult = literateElmProgramResults[index]; const context = foundContextsByName[contextName]; if (literateElmProgramResult.status === "failed") { const processedContext: FailedLitvisContext = { name: contextName, status: "failed", }; return processedContext; } else { if (literateElmProgramResult.debugLog.length) { lastDocument.info( `Debug.log results in context "${contextName}":\n${literateElmProgramResult.debugLog.join( "\n", )}`, undefined, "literate-elm:debug-log", ); } const evaluatedOutputExpressions: EvaluatedOutputExpression[] = _.map( context.wrappedOutputExpressions, (wrappedOutputExpression, i) => { const evaluatedExpressionInProgram = literateElmProgramResult.evaluatedExpressions[i]; const evaluatedExpression = wrappedOutputExpression.subject as EvaluatedOutputExpression; const document = narrative.documents[ evaluatedExpressionInProgram.node.fileIndex || 0 ]; evaluatedExpression.data.value = evaluatedExpressionInProgram.value; evaluatedExpression.data.valueStringRepresentation = evaluatedExpressionInProgram.valueStringRepresentation; if ( evaluatedExpression.data.outputFormat !== "r" && evaluatedExpression.data.value instanceof Error ) { document.message( evaluatedExpression.data.value.message, evaluatedExpression.position, "litvis:expression-value", ); } return evaluatedExpression; }, ); const processedContext: SucceededLitvisContext = { name: contextName, status: literateElmProgramResult.status, evaluatedOutputExpressions, debugLog: literateElmProgramResult.debugLog, }; return processedContext; } }, ); narrative.contexts = processedContexts; } catch (error) { try { lastDocument.fail(error.message); } catch { // no need for action - just preventing .fail() from throwing further } } };
the_stack
export interface ResetDBInstancePasswordResponse { /** * 异步请求Id,用户查询该流程的运行状态 */ AsyncRequestId?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeSpecInfo请求参数结构体 */ export interface DescribeSpecInfoRequest { /** * 待查询可用区 */ Zone?: string; } /** * KillOps请求参数结构体 */ export interface KillOpsRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 */ InstanceId: string; /** * 待终止的操作 */ Operations: Array<Operation>; } /** * CreateDBInstance请求参数结构体 */ export interface CreateDBInstanceRequest { /** * 每个副本集内节点个数,具体参照查询云数据库的售卖规格返回参数 */ NodeNum: number; /** * 实例内存大小,单位:GB */ Memory: number; /** * 实例硬盘大小,单位:GB */ Volume: number; /** * 版本号,具体支持的售卖版本请参照查询云数据库的售卖规格(DescribeSpecInfo)返回结果。参数与版本对应关系是MONGO_3_WT:MongoDB 3.2 WiredTiger存储引擎版本,MONGO_3_ROCKS:MongoDB 3.2 RocksDB存储引擎版本,MONGO_36_WT:MongoDB 3.6 WiredTiger存储引擎版本,MONGO_40_WT:MongoDB 4.0 WiredTiger存储引擎版本,MONGO_42_WT:MongoDB 4.2 WiredTiger存储引擎版本 */ MongoVersion: string; /** * 实例数量, 最小值1,最大值为10 */ GoodsNum: number; /** * 实例所属区域名称,格式如:ap-guangzhou-2。注:此参数填写的是主可用区,如果选择多可用区部署,Zone必须是AvailabilityZoneList中的一个 */ Zone: string; /** * 实例时长,单位:月,可选值包括 [1,2,3,4,5,6,7,8,9,10,11,12,24,36] */ Period: number; /** * 机器类型,HIO:高IO型;HIO10G:高IO万兆型;STDS5:标准型 */ MachineCode: string; /** * 实例类型,REPLSET-副本集,SHARD-分片集群,STANDALONE-单节点 */ ClusterType: string; /** * 副本集个数,创建副本集实例时,该参数必须设置为1;创建分片实例时,具体参照查询云数据库的售卖规格返回参数;若为单节点实例,该参数设置为0 */ ReplicateSetNum: number; /** * 项目ID,不设置为默认项目 */ ProjectId?: number; /** * 私有网络 ID,如果不传则默认选择基础网络,请使用 查询私有网络列表 */ VpcId?: string; /** * 私有网络下的子网 ID,如果设置了 UniqVpcId,则 UniqSubnetId 必填,请使用 查询子网列表 */ SubnetId?: string; /** * 实例密码,不设置该参数则默认密码规则为 实例ID+"@"+主账户uin。举例实例id为cmgo-higv73ed,uin为100000001,则默认密码为"cmgo-higv73ed@100000001"。密码必须是8-16位字符,且至少包含字母、数字和字符 !@#%^*() 中的两种 */ Password?: string; /** * 实例标签信息 */ Tags?: Array<TagInfo>; /** * 自动续费标记,可选值为:0 - 不自动续费;1 - 自动续费。默认为不自动续费 */ AutoRenewFlag?: number; /** * 是否自动选择代金券,可选值为:1 - 是;0 - 否; 默认为0 */ AutoVoucher?: number; /** * 1:正式实例,2:临时实例,3:只读实例,4:灾备实例,5:克隆实例 */ Clone?: number; /** * 若是只读,灾备实例或克隆实例,Father必须填写,即主实例ID */ Father?: string; /** * 安全组 */ SecurityGroup?: Array<string>; /** * 克隆实例回档时间。若是克隆实例,则必须填写,格式:2021-08-13 16:30:00。注:只能回档7天内的时间点 */ RestoreTime?: string; /** * 实例名称。注:名称只支持长度为60个字符的中文、英文、数字、下划线_、分隔符- */ InstanceName?: string; /** * 多可用区部署的节点列表,具体支持的售卖版本请参照查询云数据库的售卖规格(DescribeSpecInfo)返回结果。注:1、多可用区部署节点只能部署在3个不同可用区;2、为了保障跨可用区切换,不支持将集群的大多数节点部署在同一个可用区(如3节点集群不支持2个节点部署在同一个区);3、不支持4.2及以上版本;4、不支持只读灾备实例;5、不能选择基础网络 */ AvailabilityZoneList?: Array<string>; /** * mongos cpu数量,购买MongoDB 4.2 WiredTiger存储引擎版本的分片集群时必须填写,具体支持的售卖版本请参照查询云数据库的售卖规格(DescribeSpecInfo)返回结果 */ MongosCpu?: number; /** * mongos 内存大小,购买MongoDB 4.2 WiredTiger存储引擎版本的分片集群时必须填写,具体支持的售卖版本请参照查询云数据库的售卖规格(DescribeSpecInfo)返回结果 */ MongosMemory?: number; /** * mongos 数量,购买MongoDB 4.2 WiredTiger存储引擎版本的分片集群时必须填写,具体支持的售卖版本请参照查询云数据库的售卖规格(DescribeSpecInfo)返回结果。注:为了保障高可用,最低需要购买3个mongos,上限为32个 */ MongosNodeNum?: number; } /** * DescribeSecurityGroup返回参数结构体 */ export interface DescribeSecurityGroupResponse { /** * 实例绑定的安全组 */ Groups: Array<SecurityGroup>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCurrentOp返回参数结构体 */ export interface DescribeCurrentOpResponse { /** * 符合查询条件的操作总数 */ TotalCount?: number; /** * 当前操作列表 */ CurrentOps?: Array<CurrentOp>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * IsolateDBInstance返回参数结构体 */ export interface IsolateDBInstanceResponse { /** * 异步任务的请求 ID,可使用此 ID 查询异步任务的执行结果。 */ AsyncRequestId?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 创建备份下载任务结果 */ export interface BackupDownloadTaskStatus { /** * 分片名 */ ReplicaSetId: string; /** * 任务当前状态。0-等待执行,1-正在下载,2-下载完成,3-下载失败,4-等待重试 */ Status: number; } /** * CreateBackupDBInstance返回参数结构体 */ export interface CreateBackupDBInstanceResponse { /** * 查询备份流程的状态 */ AsyncRequestId?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 数据库实例价格 */ export interface DBInstancePrice { /** * 单价 注意:此字段可能返回 null,表示取不到有效值。 */ UnitPrice: number; /** * 原价 */ OriginalPrice: number; /** * 折扣加 */ DiscountPrice: number; } /** * DescribeBackupAccess返回参数结构体 */ export interface DescribeBackupAccessResponse { /** * 实例所属地域 */ Region?: string; /** * 备份文件所在存储桶 */ Bucket?: string; /** * 备份文件的存储信息 */ Files?: Array<BackupFile>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * InquirePriceCreateDBInstances请求参数结构体 */ export interface InquirePriceCreateDBInstancesRequest { /** * 实例所属区域名称,格式如:ap-guangzhou-2 */ Zone: string; /** * 每个副本集内节点个数,当前副本集节点数固定为3,分片从节点数可选,具体参照查询云数据库的售卖规格返回参数 */ NodeNum: number; /** * 实例内存大小,单位:GB */ Memory: number; /** * 实例硬盘大小,单位:GB */ Volume: number; /** * 版本号,具体支持的售卖版本请参照查询云数据库的售卖规格(DescribeSpecInfo)返回结果。参数与版本对应关系是MONGO_3_WT:MongoDB 3.2 WiredTiger存储引擎版本,MONGO_3_ROCKS:MongoDB 3.2 RocksDB存储引擎版本,MONGO_36_WT:MongoDB 3.6 WiredTiger存储引擎版本,MONGO_40_WT:MongoDB 4.0 WiredTiger存储引擎版本 */ MongoVersion: string; /** * 机器类型,HIO:高IO型;HIO10G:高IO万兆型;STDS5:标准型 */ MachineCode: string; /** * 实例数量, 最小值1,最大值为10 */ GoodsNum: number; /** * 实例时长,单位:月,可选值包括[1,2,3,4,5,6,7,8,9,10,11,12,24,36] */ Period: number; /** * 实例类型,REPLSET-副本集,SHARD-分片集群,STANDALONE-单节点 */ ClusterType: string; /** * 副本集个数,创建副本集实例时,该参数必须设置为1;创建分片实例时,具体参照查询云数据库的售卖规格返回参数;若为单节点实例,该参数设置为0 */ ReplicateSetNum: number; } /** * IsolateDBInstance请求参数结构体 */ export interface IsolateDBInstanceRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 */ InstanceId: string; } /** * DescribeSlowLogPatterns返回参数结构体 */ export interface DescribeSlowLogPatternsResponse { /** * 慢日志统计信息总数 */ Count: number; /** * 慢日志统计信息 */ SlowLogPatterns: Array<SlowLogPattern>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 分片信息 */ export interface ReplicaSetInfo { /** * 分片名称 */ ReplicaSetId: string; } /** * CreateDBInstanceHour请求参数结构体 */ export interface CreateDBInstanceHourRequest { /** * 实例内存大小,单位:GB */ Memory: number; /** * 实例硬盘大小,单位:GB */ Volume: number; /** * 副本集个数,创建副本集实例时,该参数必须设置为1;创建分片实例时,具体参照查询云数据库的售卖规格返回参数 */ ReplicateSetNum: number; /** * 每个副本集内节点个数,具体参照查询云数据库的售卖规格返回参数 */ NodeNum: number; /** * 版本号,具体支持的售卖版本请参照查询云数据库的售卖规格(DescribeSpecInfo)返回结果。参数与版本对应关系是MONGO_3_WT:MongoDB 3.2 WiredTiger存储引擎版本,MONGO_3_ROCKS:MongoDB 3.2 RocksDB存储引擎版本,MONGO_36_WT:MongoDB 3.6 WiredTiger存储引擎版本,MONGO_40_WT:MongoDB 4.0 WiredTiger存储引擎版本,MONGO_42_WT:MongoDB 4.2 WiredTiger存储引擎版本 */ MongoVersion: string; /** * 机器类型,HIO:高IO型;HIO10G:高IO万兆 */ MachineCode: string; /** * 实例数量,最小值1,最大值为10 */ GoodsNum: number; /** * 可用区信息,格式如:ap-guangzhou-2。注:此参数填写的是主可用区,如果选择多可用区部署,Zone必须是AvailabilityZoneList中的一个 */ Zone: string; /** * 实例类型,REPLSET-副本集,SHARD-分片集群 */ ClusterType: string; /** * 私有网络ID,如果不设置该参数则默认选择基础网络 */ VpcId?: string; /** * 私有网络下的子网ID,如果设置了 VpcId,则 SubnetId必填 */ SubnetId?: string; /** * 实例密码,不设置该参数则默认密码规则为 实例ID+"@"+主账户uin。举例实例id为cmgo-higv73ed,uin为100000001,则默认密码为"cmgo-higv73ed@100000001"。密码必须是8-16位字符,且至少包含字母、数字和字符 !@#%^*() 中的两种 */ Password?: string; /** * 项目ID,不设置为默认项目 */ ProjectId?: number; /** * 实例标签信息 */ Tags?: Array<TagInfo>; /** * 1:正式实例,2:临时实例,3:只读实例,4:灾备实例,5:克隆实例 */ Clone?: number; /** * 父实例Id,当Clone为3或者4时,这个必须填 */ Father?: string; /** * 安全组 */ SecurityGroup?: Array<string>; /** * 克隆实例回档时间。若是克隆实例,则必须填写,示例:2021-08-13 16:30:00。注:只能回档7天内的时间点 */ RestoreTime?: string; /** * 实例名称。注:名称只支持长度为60个字符的中文、英文、数字、下划线_、分隔符- */ InstanceName?: string; /** * 多可用区部署的节点列表,具体支持的售卖版本请参照查询云数据库的售卖规格(DescribeSpecInfo)返回结果。注:1、多可用区部署节点只能部署在3个不同可用区;2、为了保障跨可用区切换,不支持将集群的大多数节点部署在同一个可用区(如3节点集群不支持2个节点部署在同一个区);3、不支持4.2及以上版本;4、不支持只读灾备实例;5、不能选择基础网络 */ AvailabilityZoneList?: Array<string>; /** * mongos cpu数量,购买MongoDB 4.2 WiredTiger存储引擎版本的分片集群时必须填写,具体支持的售卖版本请参照查询云数据库的售卖规格(DescribeSpecInfo)返回结果 */ MongosCpu?: number; /** * mongos 内存大小,购买MongoDB 4.2 WiredTiger存储引擎版本的分片集群时必须填写,具体支持的售卖版本请参照查询云数据库的售卖规格(DescribeSpecInfo)返回结果 */ MongosMemory?: number; /** * mongos 数量,购买MongoDB 4.2 WiredTiger存储引擎版本的分片集群时必须填写,具体支持的售卖版本请参照查询云数据库的售卖规格(DescribeSpecInfo)返回结果。注:为了保障高可用,最低需要购买3个mongos,上限为32个 */ MongosNodeNum?: number; } /** * AssignProject请求参数结构体 */ export interface AssignProjectRequest { /** * 实例ID列表,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 */ InstanceIds: Array<string>; /** * 项目ID */ ProjectId: number; } /** * 安全组规则 */ export interface SecurityGroupBound { /** * 执行规则。ACCEPT或DROP */ Action: string; /** * ip段。 */ CidrIp: string; /** * 端口范围 */ PortRange: string; /** * 传输层协议。tcp,udp或ALL */ IpProtocol: string; /** * 安全组id代表的地址集合 */ Id: string; /** * 地址组id代表的地址集合 */ AddressModule: string; /** * 服务组id代表的协议和端口集合 */ ServiceModule: string; /** * 描述 */ Desc: string; } /** * CreateBackupDownloadTask返回参数结构体 */ export interface CreateBackupDownloadTaskResponse { /** * 下载任务状态 */ Tasks: Array<BackupDownloadTaskStatus>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 客户端连接信息,包括客户端IP和连接数 */ export interface ClientConnection { /** * 连接的客户端IP */ IP: string; /** * 对应客户端IP的连接数 */ Count: number; } /** * InquirePriceModifyDBInstanceSpec请求参数结构体 */ export interface InquirePriceModifyDBInstanceSpecRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同。 */ InstanceId: string; /** * 变更配置后实例内存大小,单位:GB。 */ Memory: number; /** * 变更配置后实例磁盘大小,单位:GB。 */ Volume: number; } /** * 备份信息 */ export interface BackupInfo { /** * 实例ID */ InstanceId: string; /** * 备份方式,0-自动备份,1-手动备份 */ BackupType: number; /** * 备份名称 */ BackupName: string; /** * 备份备注 注意:此字段可能返回 null,表示取不到有效值。 */ BackupDesc: string; /** * 备份文件大小,单位KB 注意:此字段可能返回 null,表示取不到有效值。 */ BackupSize: number; /** * 备份开始时间 注意:此字段可能返回 null,表示取不到有效值。 */ StartTime: string; /** * 备份结束时间 注意:此字段可能返回 null,表示取不到有效值。 */ EndTime: string; /** * 备份状态,1-备份中,2-备份成功 */ Status: number; /** * 备份方法,0-逻辑备份,1-物理备份 */ BackupMethod: number; } /** * InquirePriceRenewDBInstances请求参数结构体 */ export interface InquirePriceRenewDBInstancesRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同,接口单次最多只支持5个实例进行操作。 */ InstanceIds: Array<string>; /** * 预付费模式(即包年包月)相关参数设置。通过该参数可以指定包年包月实例的续费时长、是否设置自动续费等属性。 */ InstanceChargePrepaid: InstanceChargePrepaid; } /** * DescribeAsyncRequestInfo请求参数结构体 */ export interface DescribeAsyncRequestInfoRequest { /** * 异步请求Id,涉及到异步流程的接口返回,如CreateBackupDBInstance */ AsyncRequestId: string; } /** * KillOps返回参数结构体 */ export interface KillOpsResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 实例规格信息 */ export interface SpecificationInfo { /** * 地域信息 */ Region: string; /** * 可用区信息 */ Zone: string; /** * 售卖规格信息 */ SpecItems: Array<SpecItem>; } /** * CreateBackupDownloadTask请求参数结构体 */ export interface CreateBackupDownloadTaskRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 */ InstanceId: string; /** * 要下载的备份文件名,可通过DescribeDBBackups接口获取 */ BackupName: string; /** * 下载备份的分片列表 */ BackupSets: Array<ReplicaSetInfo>; } /** * DescribeSlowLogPatterns请求参数结构体 */ export interface DescribeSlowLogPatternsRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 */ InstanceId: string; /** * 慢日志起始时间,格式:yyyy-mm-dd hh:mm:ss,如:2019-06-01 10:00:00。查询起止时间间隔不能超过24小时,只允许查询最近7天内慢日志。 */ StartTime: string; /** * 慢日志终止时间,格式:yyyy-mm-dd hh:mm:ss,如:2019-06-02 12:00:00。查询起止时间间隔不能超过24小时,只允许查询最近7天内慢日志。 */ EndTime: string; /** * 慢日志执行时间阈值,返回执行时间超过该阈值的慢日志,单位为毫秒(ms),最小为100毫秒。 */ SlowMS: number; /** * 偏移量,最小值为0,最大值为10000,默认值为0。 */ Offset?: number; /** * 分页大小,最小值为1,最大值为100,默认值为20。 */ Limit?: number; /** * 慢日志返回格式,可设置为json,不传默认返回原生慢日志格式。 */ Format?: string; } /** * DescribeSlowLogs返回参数结构体 */ export interface DescribeSlowLogsResponse { /** * 慢日志总数 */ Count: number; /** * 慢日志详情 注意:此字段可能返回 null,表示取不到有效值。 */ SlowLogs: Array<string>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * FlushInstanceRouterConfig返回参数结构体 */ export interface FlushInstanceRouterConfigResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * InquirePriceModifyDBInstanceSpec返回参数结构体 */ export interface InquirePriceModifyDBInstanceSpecResponse { /** * 价格。 */ Price?: DBInstancePrice; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * mongodb售卖规格 */ export interface SpecItem { /** * 规格信息标识 */ SpecCode: string; /** * 规格有效标志,取值:0-停止售卖,1-开放售卖 */ Status: number; /** * 计算资源规格,单位为CPU核心数 */ Cpu: number; /** * 内存规格,单位为MB */ Memory: number; /** * 默认磁盘规格,单位MB */ DefaultStorage: number; /** * 最大磁盘规格,单位MB */ MaxStorage: number; /** * 最小磁盘规格,单位MB */ MinStorage: number; /** * 可承载qps信息 */ Qps: number; /** * 连接数限制 */ Conns: number; /** * 实例mongodb版本信息 */ MongoVersionCode: string; /** * 实例mongodb版本号 */ MongoVersionValue: number; /** * 实例mongodb版本号(短) */ Version: string; /** * 存储引擎 */ EngineName: string; /** * 集群类型,取值:1-分片集群,0-副本集集群 */ ClusterType: number; /** * 最小副本集从节点数 */ MinNodeNum: number; /** * 最大副本集从节点数 */ MaxNodeNum: number; /** * 最小分片数 */ MinReplicateSetNum: number; /** * 最大分片数 */ MaxReplicateSetNum: number; /** * 最小分片从节点数 */ MinReplicateSetNodeNum: number; /** * 最大分片从节点数 */ MaxReplicateSetNodeNum: number; /** * 机器类型,取值:0-HIO,4-HIO10G */ MachineType: string; } /** * DescribeSpecInfo返回参数结构体 */ export interface DescribeSpecInfoResponse { /** * 实例售卖规格信息列表 */ SpecInfoList?: Array<SpecificationInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * InquirePriceRenewDBInstances返回参数结构体 */ export interface InquirePriceRenewDBInstancesResponse { /** * 价格 */ Price?: DBInstancePrice; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ResetDBInstancePassword请求参数结构体 */ export interface ResetDBInstancePasswordRequest { /** * 实例Id */ InstanceId: string; /** * 实例账号名 */ UserName: string; /** * 新密码 */ Password: string; } /** * 实例标签信息 */ export interface TagInfo { /** * 标签键 */ TagKey: string; /** * 标签值 */ TagValue: string; } /** * DescribeDBInstances返回参数结构体 */ export interface DescribeDBInstancesResponse { /** * 符合查询条件的实例总数 */ TotalCount?: number; /** * 实例详细信息列表 */ InstanceDetails?: Array<InstanceDetail>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * OfflineIsolatedDBInstance请求参数结构体 */ export interface OfflineIsolatedDBInstanceRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 */ InstanceId: string; } /** * DescribeCurrentOp请求参数结构体 */ export interface DescribeCurrentOpRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 */ InstanceId: string; /** * 筛选条件,操作所属的命名空间namespace,格式为db.collection */ Ns?: string; /** * 筛选条件,操作已经执行的时间(单位:毫秒),结果将返回超过设置时间的操作,默认值为0,取值范围为[0, 3600000] */ MillisecondRunning?: number; /** * 筛选条件,操作类型,可能的取值:none,update,insert,query,command,getmore,remove和killcursors */ Op?: string; /** * 筛选条件,分片名称 */ ReplicaSetName?: string; /** * 筛选条件,节点状态,可能的取值为:primary secondary */ State?: string; /** * 单次请求返回的数量,默认值为100,取值范围为[0,100] */ Limit?: number; /** * 偏移量,默认值为0,取值范围为[0,10000] */ Offset?: number; /** * 返回结果集排序的字段,目前支持:"MicrosecsRunning"/"microsecsrunning",默认为升序排序 */ OrderBy?: string; /** * 返回结果集排序方式,可能的取值:"ASC"/"asc"或"DESC"/"desc" */ OrderByType?: string; } /** * DescribeDBInstanceDeal请求参数结构体 */ export interface DescribeDBInstanceDealRequest { /** * 订单ID,通过CreateDBInstance等接口返回 */ DealId: string; } /** * DescribeDBInstances请求参数结构体 */ export interface DescribeDBInstancesRequest { /** * 实例ID列表,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 */ InstanceIds?: Array<string>; /** * 实例类型,取值范围:0-所有实例,1-正式实例,2-临时实例, 3-只读实例,-1-正式实例+只读+灾备实例 */ InstanceType?: number; /** * 集群类型,取值范围:0-副本集实例,1-分片实例,-1-所有实例 */ ClusterType?: number; /** * 实例状态,取值范围:0-待初始化,1-流程执行中,2-实例有效,-2-已隔离(包年包月实例),-3-已隔离(按量计费实例) */ Status?: Array<number>; /** * 私有网络的ID,基础网络则不传该参数 */ VpcId?: string; /** * 私有网络的子网ID,基础网络则不传该参数。入参设置该参数的同时,必须设置相应的VpcId */ SubnetId?: string; /** * 付费类型,取值范围:0-按量计费,1-包年包月,-1-按量计费+包年包月 */ PayMode?: number; /** * 单次请求返回的数量,最小值为1,最大值为100,默认值为20 */ Limit?: number; /** * 偏移量,默认值为0 */ Offset?: number; /** * 返回结果集排序的字段,目前支持:"ProjectId", "InstanceName", "CreateTime",默认为升序排序 */ OrderBy?: string; /** * 返回结果集排序方式,目前支持:"ASC"或者"DESC" */ OrderByType?: string; /** * 项目 ID */ ProjectIds?: Array<number>; /** * 搜索关键词,支持实例ID、实例名称、完整IP */ SearchKey?: string; /** * Tag信息 */ Tags?: TagInfo; } /** * DescribeAsyncRequestInfo返回参数结构体 */ export interface DescribeAsyncRequestInfoResponse { /** * 状态。返回参数有:initial-初始化、running-运行中、paused-任务执行失败,已暂停、undoed-任务执行失败,已回滚、failed-任务执行失败, 已终止、success-成功 */ Status: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateDBInstance返回参数结构体 */ export interface CreateDBInstanceResponse { /** * 订单ID */ DealId: string; /** * 创建的实例ID列表 */ InstanceIds: Array<string>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeSlowLogs请求参数结构体 */ export interface DescribeSlowLogsRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 */ InstanceId: string; /** * 慢日志起始时间,格式:yyyy-mm-dd hh:mm:ss,如:2019-06-01 10:00:00。查询起止时间间隔不能超过24小时,只允许查询最近7天内慢日志。 */ StartTime: string; /** * 慢日志终止时间,格式:yyyy-mm-dd hh:mm:ss,如:2019-06-02 12:00:00。查询起止时间间隔不能超过24小时,只允许查询最近7天内慢日志。 */ EndTime: string; /** * 慢日志执行时间阈值,返回执行时间超过该阈值的慢日志,单位为毫秒(ms),最小为100毫秒。 */ SlowMS: number; /** * 偏移量,最小值为0,最大值为10000,默认值为0。 */ Offset?: number; /** * 分页大小,最小值为1,最大值为100,默认值为20。 */ Limit?: number; /** * 慢日志返回格式,可设置为json,不传默认返回原生慢日志格式。 */ Format?: string; } /** * AssignProject返回参数结构体 */ export interface AssignProjectResponse { /** * 返回的异步任务ID列表 */ FlowIds?: Array<number>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 备份下载任务 */ export interface BackupDownloadTask { /** * 任务创建时间 */ CreateTime: string; /** * 备份文件名 */ BackupName: string; /** * 分片名称 */ ReplicaSetId: string; /** * 备份数据大小,单位为字节 */ BackupSize: number; /** * 任务状态。0-等待执行,1-正在下载,2-下载完成,3-下载失败,4-等待重试 */ Status: number; /** * 任务进度百分比 */ Percent: number; /** * 耗时,单位为秒 */ TimeSpend: number; /** * 备份数据下载链接 */ Url: string; } /** * DescribeDBBackups请求参数结构体 */ export interface DescribeDBBackupsRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 */ InstanceId: string; /** * 备份方式,当前支持:0-逻辑备份,1-物理备份,2-所有备份。默认为逻辑备份。 */ BackupMethod?: number; /** * 分页大小,最大值为100,不设置默认查询所有。 */ Limit?: number; /** * 分页偏移量,最小值为0,默认值为0。 */ Offset?: number; } /** * DescribeClientConnections请求参数结构体 */ export interface DescribeClientConnectionsRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 */ InstanceId: string; /** * 查询返回记录条数,默认为10000。 */ Limit?: number; /** * 偏移量,默认值为0。 */ Offset?: number; } /** * DescribeDBInstanceDeal返回参数结构体 */ export interface DescribeDBInstanceDealResponse { /** * 订单状态,1:未支付,2:已支付,3:发货中,4:发货成功,5:发货失败,6:退款,7:订单关闭,8:超时未支付关闭。 */ Status?: number; /** * 订单原价。 */ OriginalPrice?: number; /** * 订单折扣价格。 */ DiscountPrice?: number; /** * 订单行为,purchase:新购,renew:续费,upgrade:升配,downgrade:降配,refund:退货退款。 */ Action?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ModifyDBInstanceSpec返回参数结构体 */ export interface ModifyDBInstanceSpecResponse { /** * 订单ID */ DealId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 安全组信息 */ export interface SecurityGroup { /** * 所属项目id */ ProjectId: number; /** * 创建时间 */ CreateTime: string; /** * 入站规则 */ Inbound: Array<SecurityGroupBound>; /** * 出站规则 */ Outbound: Array<SecurityGroupBound>; /** * 安全组id */ SecurityGroupId: string; /** * 安全组名称 */ SecurityGroupName: string; /** * 安全组备注 */ SecurityGroupRemark: string; } /** * OfflineIsolatedDBInstance返回参数结构体 */ export interface OfflineIsolatedDBInstanceResponse { /** * 异步任务的请求 ID,可使用此 ID 查询异步任务的执行结果。 */ AsyncRequestId?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeBackupDownloadTask请求参数结构体 */ export interface DescribeBackupDownloadTaskRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 */ InstanceId: string; /** * 备份文件名,用来过滤指定文件的下载任务 */ BackupName?: string; /** * 指定要查询任务的时间范围,StartTime指定开始时间,不填默认不限制开始时间 */ StartTime?: string; /** * 指定要查询任务的时间范围,EndTime指定结束时间,不填默认不限制结束时间 */ EndTime?: string; /** * 此次查询返回的条数,取值范围为1-100,默认为20 */ Limit?: number; /** * 指定此次查询返回的页数,默认为0 */ Offset?: number; /** * 排序字段,取值为createTime,finishTime两种,默认为createTime */ OrderBy?: string; /** * 排序方式,取值为asc,desc两种,默认desc */ OrderByType?: string; /** * 根据任务状态过滤。0-等待执行,1-正在下载,2-下载完成,3-下载失败,4-等待重试。不填默认返回所有类型 */ Status?: Array<number>; } /** * DescribeBackupAccess请求参数结构体 */ export interface DescribeBackupAccessRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 */ InstanceId: string; /** * 需要获取下载授权的备份文件名 */ BackupName: string; } /** * RenameInstance请求参数结构体 */ export interface RenameInstanceRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 */ InstanceId: string; /** * 实例名称 */ NewName: string; } /** * DescribeSecurityGroup请求参数结构体 */ export interface DescribeSecurityGroupRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。 */ InstanceId: string; } /** * RenewDBInstances返回参数结构体 */ export interface RenewDBInstancesResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeBackupDownloadTask返回参数结构体 */ export interface DescribeBackupDownloadTaskResponse { /** * 满足查询条件的所有条数 */ TotalCount: number; /** * 下载任务列表 */ Tasks: Array<BackupDownloadTask>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * RenameInstance返回参数结构体 */ export interface RenameInstanceResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeClientConnections返回参数结构体 */ export interface DescribeClientConnectionsResponse { /** * 客户端连接信息,包括客户端IP和对应IP的连接数量。 */ Clients?: Array<ClientConnection>; /** * 满足条件的记录总条数,可用于分页查询。 */ TotalCount?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * FlushInstanceRouterConfig请求参数结构体 */ export interface FlushInstanceRouterConfigRequest { /** * 实例ID */ InstanceId: string; } /** * 实例信息 */ export interface DBInstanceInfo { /** * 实例ID */ InstanceId: string; /** * 地域信息 */ Region: string; } /** * 云数据库实例当前操作 */ export interface CurrentOp { /** * 操作序号 注意:此字段可能返回 null,表示取不到有效值。 */ OpId: number; /** * 操作所在的命名空间,形式如db.collection 注意:此字段可能返回 null,表示取不到有效值。 */ Ns: string; /** * 操作执行语句 注意:此字段可能返回 null,表示取不到有效值。 */ Query: string; /** * 操作类型,可能的取值:aggregate、count、delete、distinct、find、findAndModify、getMore、insert、mapReduce、update和command 注意:此字段可能返回 null,表示取不到有效值。 */ Op: string; /** * 操作所在的分片名称 */ ReplicaSetName: string; /** * 筛选条件,节点状态,可能的取值为:Primary、Secondary 注意:此字段可能返回 null,表示取不到有效值。 */ State: string; /** * 操作详细信息 注意:此字段可能返回 null,表示取不到有效值。 */ Operation: string; /** * 操作所在的节点名称 */ NodeName: string; /** * 操作已执行时间(ms) 注意:此字段可能返回 null,表示取不到有效值。 */ MicrosecsRunning: number; } /** * 备份文件存储信息 */ export interface BackupFile { /** * 备份文件所属的副本集/分片ID */ ReplicateSetId: string; /** * 备份文件保存路径 */ File: string; } /** * DescribeDBBackups返回参数结构体 */ export interface DescribeDBBackupsResponse { /** * 备份列表 */ BackupList?: Array<BackupInfo>; /** * 备份总数 */ TotalCount?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 实例详情 */ export interface InstanceDetail { /** * 实例ID */ InstanceId: string; /** * 实例名称 */ InstanceName: string; /** * 付费类型,可能的返回值:1-包年包月;0-按量计费 */ PayMode: number; /** * 项目ID */ ProjectId: number; /** * 集群类型,可能的返回值:0-副本集实例,1-分片实例, */ ClusterType: number; /** * 地域信息 */ Region: string; /** * 可用区信息 */ Zone: string; /** * 网络类型,可能的返回值:0-基础网络,1-私有网络 */ NetType: number; /** * 私有网络的ID */ VpcId: string; /** * 私有网络的子网ID */ SubnetId: string; /** * 实例状态,可能的返回值:0-待初始化,1-流程处理中,2-运行中,-2-实例已过期 */ Status: number; /** * 实例IP */ Vip: string; /** * 端口号 */ Vport: number; /** * 实例创建时间 */ CreateTime: string; /** * 实例到期时间 */ DeadLine: string; /** * 实例版本信息 */ MongoVersion: string; /** * 实例内存规格,单位为MB */ Memory: number; /** * 实例磁盘规格,单位为MB */ Volume: number; /** * 实例CPU核心数 */ CpuNum: number; /** * 实例机器类型 */ MachineType: string; /** * 实例从节点数 */ SecondaryNum: number; /** * 实例分片数 */ ReplicationSetNum: number; /** * 实例自动续费标志,可能的返回值:0-手动续费,1-自动续费,2-确认不续费 */ AutoRenewFlag: number; /** * 已用容量,单位MB */ UsedVolume: number; /** * 维护窗口起始时间 */ MaintenanceStart: string; /** * 维护窗口结束时间 */ MaintenanceEnd: string; /** * 分片信息 */ ReplicaSets: Array<ShardInfo>; /** * 只读实例信息 */ ReadonlyInstances: Array<DBInstanceInfo>; /** * 灾备实例信息 */ StandbyInstances: Array<DBInstanceInfo>; /** * 临时实例信息 */ CloneInstances: Array<DBInstanceInfo>; /** * 关联实例信息,对于正式实例,该字段表示它的临时实例信息;对于临时实例,则表示它的正式实例信息;如果为只读/灾备实例,则表示他的主实例信息 */ RelatedInstance: DBInstanceInfo; /** * 实例标签信息集合 */ Tags: Array<TagInfo>; /** * 实例版本标记 */ InstanceVer: number; /** * 实例版本标记 */ ClusterVer: number; /** * 协议信息,可能的返回值:1-mongodb,2-dynamodb */ Protocol: number; /** * 实例类型,可能的返回值,1-正式实例,2-临时实例,3-只读实例,4-灾备实例 */ InstanceType: number; /** * 实例状态描述 */ InstanceStatusDesc: string; /** * 实例对应的物理实例id,回档并替换过的实例有不同的InstanceId和RealInstanceId,从barad获取监控数据等场景下需要用物理id获取 */ RealInstanceId: string; } /** * ModifyDBInstanceSpec请求参数结构体 */ export interface ModifyDBInstanceSpecRequest { /** * 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 */ InstanceId: string; /** * 实例配置变更后的内存大小,单位:GB。内存和磁盘必须同时升配或同时降配 */ Memory: number; /** * 实例配置变更后的硬盘大小,单位:GB。内存和磁盘必须同时升配或同时降配。降配时,新的磁盘参数必须大于已用磁盘容量的1.2倍 */ Volume: number; /** * 实例配置变更后oplog的大小,单位:GB,默认为磁盘空间的10%,允许设置的最小值为磁盘的10%,最大值为磁盘的90% */ OplogSize?: number; /** * 实例变更后的节点数,取值范围具体参照查询云数据库的售卖规格返回参数。默认为不变更节点数 */ NodeNum?: number; /** * 实例变更后的分片数,取值范围具体参照查询云数据库的售卖规格返回参数。只能增加不能减少,默认为不变更分片数 */ ReplicateSetNum?: number; /** * 实例配置变更的切换时间,参数为:0(默认)、1。0-调整完成时,1-维护时间内。注:调整节点数和分片数不支持在【维护时间内】变更。 */ InMaintenance?: number; } /** * 用于描述MongoDB数据库慢日志统计信息 */ export interface SlowLogPattern { /** * 慢日志模式 */ Pattern: string; /** * 最大执行时间 */ MaxTime: number; /** * 平均执行时间 */ AverageTime: number; /** * 该模式慢日志条数 */ Total: number; } /** * CreateDBInstanceHour返回参数结构体 */ export interface CreateDBInstanceHourResponse { /** * 订单ID */ DealId: string; /** * 创建的实例ID列表 */ InstanceIds: Array<string>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateBackupDBInstance请求参数结构体 */ export interface CreateBackupDBInstanceRequest { /** * 实例id */ InstanceId: string; /** * 0-逻辑备份,1-物理备份 */ BackupMethod: number; /** * 备份备注 */ BackupRemark?: string; } /** * 需要终止的操作 */ export interface Operation { /** * 操作所在的分片名 */ ReplicaSetName: string; /** * 操作所在的节点名 */ NodeName: string; /** * 操作序号 */ OpId: number; } /** * 描述了实例的计费模式 */ export interface InstanceChargePrepaid { /** * 购买实例的时长,单位:月。取值范围:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 24, 36。默认为1。 (InquirePriceRenewDBInstances,RenewDBInstances调用时必填) */ Period?: number; /** * 自动续费标识。取值范围: NOTIFY_AND_AUTO_RENEW:通知过期且自动续费 NOTIFY_AND_MANUAL_RENEW:通知过期不自动续费 DISABLE_NOTIFY_AND_MANUAL_RENEW:不通知过期不自动续费 默认取值:NOTIFY_AND_MANUAL_RENEW。若该参数指定为NOTIFY_AND_AUTO_RENEW,在账户余额充足的情况下,实例到期后将按月自动续费。 (InquirePriceRenewDBInstances,RenewDBInstances调用时必填) */ RenewFlag?: string; } /** * InquirePriceCreateDBInstances返回参数结构体 */ export interface InquirePriceCreateDBInstancesResponse { /** * 价格 */ Price?: DBInstancePrice; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * RenewDBInstances请求参数结构体 */ export interface RenewDBInstancesRequest { /** * 一个或多个待操作的实例ID。可通过DescribeInstances接口返回值中的InstanceId获取。每次请求批量实例的上限为100。 */ InstanceIds: Array<string>; /** * 预付费模式,即包年包月相关参数设置。通过该参数可以指定包年包月实例的续费时长、是否设置自动续费等属性。包年包月实例该参数为必传参数。 */ InstanceChargePrepaid: InstanceChargePrepaid; } /** * 实例分片详情 */ export interface ShardInfo { /** * 分片已使用容量 */ UsedVolume: number; /** * 分片ID */ ReplicaSetId: string; /** * 分片名 */ ReplicaSetName: string; /** * 分片内存规格,单位为MB */ Memory: number; /** * 分片磁盘规格,单位为MB */ Volume: number; /** * 分片Oplog大小,单位为MB */ OplogSize: number; /** * 分片从节点数 */ SecondaryNum: number; /** * 分片物理id */ RealReplicaSetId: string; }
the_stack
import { assert } from "chai"; import { LinkedList, LinkedListNode } from "../lib/list"; describe("linked-list", () => { describe("node", () => { it("ctor", () => { const node = new LinkedListNode(1); assert.strictEqual(node.value, 1); assert.strictEqual(node.list, undefined); assert.strictEqual(node.previous, undefined); assert.strictEqual(node.next, undefined); }); describe("in list", () => { it("only", () => { const node = new LinkedListNode(1); const list = new LinkedList(); list.pushNode(node); assert.strictEqual(node.list, list); assert.strictEqual(node.previous, undefined); assert.strictEqual(node.next, undefined); }); it("two", () => { const nodeOne = new LinkedListNode(1); const nodeTwo = new LinkedListNode(2); const list = new LinkedList(); list.pushNode(nodeOne); list.pushNode(nodeTwo); assert.strictEqual(nodeOne.list, list); assert.strictEqual(nodeOne.previous, undefined); assert.strictEqual(nodeOne.next, nodeTwo); assert.strictEqual(nodeTwo.list, list); assert.strictEqual(nodeTwo.previous, nodeOne); assert.strictEqual(nodeTwo.next, undefined); }); }); }); describe("list", () => { describe("ctor", () => { it("simple", () => { const list = new LinkedList(); assert.strictEqual(list.size, 0); assert.strictEqual(list.first, undefined); assert.strictEqual(list.last, undefined); }); it("iterable", () => { const list = new LinkedList([1]); assert.strictEqual(list.size, 1); assert.strictEqual(list.first, list.last); assert.strictEqual(list.first.value, 1); }); it("throws if iterable not Iterable", () => { assert.throws(() => new LinkedList(<any>{}), TypeError); }); }); describe("insertBefore", () => { it("correct", () => { const list = new LinkedList([1]); const node = list.insertBefore(list.first, 2); assert.strictEqual(list.size, 2); assert.strictEqual(list.first, node); assert.notStrictEqual(list.first, list.last); assert.strictEqual(node.value, 2); }); it("throws if node not LinkedListNode", () => { const list = new LinkedList(); assert.throws(() => list.insertBefore(<any>{}, 1)); }); it("throws if node from other list", () => { const list1 = new LinkedList([1]); const list2 = new LinkedList(); assert.throws(() => list2.insertBefore(list1.first, 1)); }); }); describe("insertNodeBefore", () => { it("before undefined when empty", () => { const list = new LinkedList(); const node = new LinkedListNode(1); list.insertNodeBefore(undefined, node); assert.strictEqual(list.size, 1); assert.strictEqual(list.first, node); assert.strictEqual(list.last, node); }); it("before undefined when not empty", () => { const list = new LinkedList([2]); const node = new LinkedListNode(1); list.insertNodeBefore(undefined, node); assert.strictEqual(list.size, 2); assert.strictEqual(list.first, node); assert.notStrictEqual(list.last, node); }); it("before first", () => { const list = new LinkedList([1, 2]); const node = new LinkedListNode(3); list.insertNodeBefore(list.first, node); assert.strictEqual(list.size, 3); assert.strictEqual(list.first, node); assert.notStrictEqual(list.last, node); }); it("before last", () => { const list = new LinkedList([1, 2]); const node = new LinkedListNode(3); list.insertNodeBefore(list.last, node); assert.strictEqual(list.size, 3); assert.notStrictEqual(list.first, node); assert.notStrictEqual(list.last, node); assert.strictEqual(list.first.next, node); }); it("throws if node not LinkedListNode", () => { const list = new LinkedList(); const newNode = new LinkedListNode(1); assert.throws(() => list.insertNodeBefore(<any>{}, newNode)); }); it("throws if node from other list", () => { const list1 = new LinkedList([1]); const list2 = new LinkedList(); const newNode = new LinkedListNode(1); assert.throws(() => list2.insertNodeBefore(list1.first, newNode)); }); it("throws if newNode not LinkedListNode", () => { const list = new LinkedList(); assert.throws(() => list.insertNodeBefore(undefined, <any>{})); }); it("throws if newNode from other list", () => { const list1 = new LinkedList([1]); const list2 = new LinkedList(); assert.throws(() => list2.insertNodeBefore(undefined, list1.first)); }); }); describe("insertAfter", () => { it("correct", () => { const list = new LinkedList([1]); const node = list.insertAfter(list.first, 2); assert.strictEqual(list.size, 2); assert.strictEqual(list.last, node); assert.notStrictEqual(list.first, list.last); assert.strictEqual(node.value, 2); }); it("throws if node not LinkedListNode", () => { const list = new LinkedList(); assert.throws(() => list.insertAfter(<any>{}, 1)); }); it("throws if node from other list", () => { const list1 = new LinkedList([1]); const list2 = new LinkedList(); assert.throws(() => list2.insertAfter(list1.first, 1)); }); }); describe("insertNodeAfter", () => { it("after undefined when empty", () => { const list = new LinkedList(); const node = new LinkedListNode(1); list.insertNodeAfter(undefined, node); assert.strictEqual(list.size, 1); assert.strictEqual(list.first, node); assert.strictEqual(list.last, node); }); it("after undefined when not empty", () => { const list = new LinkedList([2]); const node = new LinkedListNode(1); list.insertNodeAfter(undefined, node); assert.strictEqual(list.size, 2); assert.notStrictEqual(list.first, node); assert.strictEqual(list.last, node); }); it("after first", () => { const list = new LinkedList([1, 2]); const node = new LinkedListNode(3); list.insertNodeAfter(list.first, node); assert.strictEqual(list.size, 3); assert.notStrictEqual(list.first, node); assert.notStrictEqual(list.last, node); assert.strictEqual(list.first.next, node); }); it("after last", () => { const list = new LinkedList([1, 2]); const node = new LinkedListNode(3); list.insertNodeAfter(list.last, node); assert.strictEqual(list.size, 3); assert.notStrictEqual(list.first, node); assert.strictEqual(list.last, node); }); it("throws if node not LinkedListNode", () => { const list = new LinkedList(); const newNode = new LinkedListNode(1); assert.throws(() => list.insertNodeAfter(<any>{}, newNode)); }); it("throws if node from other list", () => { const list1 = new LinkedList([1]); const list2 = new LinkedList(); const newNode = new LinkedListNode(1); assert.throws(() => list2.insertNodeAfter(list1.first, newNode)); }); it("throws if newNode not LinkedListNode", () => { const list = new LinkedList(); assert.throws(() => list.insertNodeAfter(undefined, <any>{})); }); it("throws if newNode from other list", () => { const list1 = new LinkedList([1]); const list2 = new LinkedList(); assert.throws(() => list2.insertNodeAfter(undefined, list1.first)); }); }); describe("has", () => { it("normal value", () => { const list = new LinkedList([1, 2, 3]); const hasOne = list.has(1); const hasFour = list.has(4); assert.isTrue(hasOne); assert.isFalse(hasFour); }); it("NaN", () => { const list = new LinkedList([1, NaN, 3]); const hasNaN = list.has(NaN); assert.isTrue(hasNaN); }); it("-0", () => { const list = new LinkedList([1, (0/-1), 3]); const hasMinusZero = list.has((0/-1)); const hasZero = list.has(0); assert.isTrue(hasMinusZero); assert.isFalse(hasZero); }); }); it("find", () => { const list = new LinkedList([2, 1, 2, 3]); const foundTwo = list.find(2); const foundFour = list.find(4); assert.isDefined(foundTwo); assert.strictEqual(foundTwo.value, 2); assert.strictEqual(foundTwo, list.first); assert.isUndefined(foundFour); }); it("findLast", () => { const list = new LinkedList([3, 1, 2, 3]); const foundThree = list.findLast(3); const foundFour = list.findLast(4); assert.isDefined(foundThree); assert.strictEqual(foundThree.value, 3); assert.strictEqual(foundThree, list.last); assert.isUndefined(foundFour); }); it("push", () => { const list = new LinkedList(); const nodeOne = list.push(1); const nodeTwo = list.push(2); assert.strictEqual(list.size, 2); assert.strictEqual(nodeOne, list.first); assert.strictEqual(nodeTwo, list.last); assert.strictEqual(nodeOne.value, 1); assert.strictEqual(nodeTwo.value, 2); }); describe("pushNode", () => { it("correct", () => { const list = new LinkedList(); const first = new LinkedListNode(1); const second = new LinkedListNode(2); list.pushNode(first); list.pushNode(second); assert.strictEqual(list.size, 2); assert.strictEqual(list.first, first); assert.strictEqual(list.last, second); }); it("throws if node not LinkedListNode", () => { const list = new LinkedList(); assert.throws(() => list.pushNode(<any>{})); }); it("throws if node from other list", () => { const list1 = new LinkedList([1]); const list2 = new LinkedList(); assert.throws(() => list2.pushNode(list1.first)); }); }); it("pop", () => { const list = new LinkedList([1, 2]); const first = list.pop(); const second = list.pop(); const third = list.pop(); assert.strictEqual(list.size, 0); assert.strictEqual(first, 2); assert.strictEqual(second, 1); assert.strictEqual(third, undefined); assert.strictEqual(list.first, undefined); assert.strictEqual(list.last, undefined); }); it("popNode", () => { const list = new LinkedList([1, 2]); const first = list.popNode(); const second = list.popNode(); const third = list.popNode(); assert.strictEqual(list.size, 0); assert.strictEqual(first.value, 2); assert.strictEqual(second.value, 1); assert.strictEqual(third, undefined); assert.strictEqual(list.first, undefined); assert.strictEqual(list.last, undefined); }); it("shift", () => { const list = new LinkedList([1, 2]); const first = list.shift(); const second = list.shift(); const third = list.shift(); assert.strictEqual(list.size, 0); assert.strictEqual(first, 1); assert.strictEqual(second, 2); assert.strictEqual(third, undefined); assert.strictEqual(list.first, undefined); assert.strictEqual(list.last, undefined); }); it("shiftNode", () => { const list = new LinkedList([1, 2]); const first = list.shiftNode(); const second = list.shiftNode(); const third = list.shiftNode(); assert.strictEqual(list.size, 0); assert.strictEqual(first.value, 1); assert.strictEqual(second.value, 2); assert.strictEqual(third, undefined); assert.strictEqual(list.first, undefined); assert.strictEqual(list.last, undefined); }); it("unshift", () => { const list = new LinkedList(); const first = list.unshift(1); const second = list.unshift(2); assert.strictEqual(list.size, 2); assert.strictEqual(first, list.last); assert.strictEqual(second, list.first); assert.strictEqual(first.value, 1); assert.strictEqual(second.value, 2); }); describe("unshiftNode", () => { it("correct", () => { const list = new LinkedList(); const first = new LinkedListNode(1); const second = new LinkedListNode(2); list.unshiftNode(first); list.unshiftNode(second); assert.strictEqual(list.size, 2); assert.strictEqual(list.first, second); assert.strictEqual(list.last, first); }); it("throws if node not LinkedListNode", () => { const list = new LinkedList(); assert.throws(() => list.unshiftNode(<any>{})); }); it("throws if node from other list", () => { const list1 = new LinkedList([1]); const list2 = new LinkedList(); assert.throws(() => list2.unshiftNode(list1.first)); }); }); describe("delete", () => { it("when present", () => { const list = new LinkedList([1, 2]); const wasDeleted = list.delete(1); assert.isTrue(wasDeleted); assert.strictEqual(list.size, 1); }); it("when not present", () => { const list = new LinkedList([1, 2]); const wasDeleted = list.delete(4); assert.isFalse(wasDeleted); assert.strictEqual(list.size, 2); }); it("twice", () => { const list = new LinkedList([1, 2]); list.delete(1); const wasDeletedAgain = list.delete(1); assert.isFalse(wasDeletedAgain); assert.strictEqual(list.size, 1); }); }); describe("deleteNode", () => { it("when present", () => { const list = new LinkedList([1, 2]); const node = list.first; const wasDeleted = list.deleteNode(node); assert.isTrue(wasDeleted); assert.strictEqual(list.size, 1); assert.strictEqual(node.list, undefined); assert.strictEqual(node.previous, undefined); assert.strictEqual(node.next, undefined); }); it("when not present", () => { const list = new LinkedList([1, 2]); const node = new LinkedListNode(4); const wasDeleted = list.deleteNode(node); assert.isFalse(wasDeleted); assert.strictEqual(list.size, 2); }); it("when from other list", () => { const other = new LinkedList([1]); const list = new LinkedList([1, 2]); const wasDeleted = list.deleteNode(other.first); assert.isFalse(wasDeleted); assert.strictEqual(list.size, 2); }); it("twice", () => { const list = new LinkedList([1, 2]); const node = list.first; list.deleteNode(node); const wasDeletedAgain = list.deleteNode(node); assert.isFalse(wasDeletedAgain); assert.strictEqual(list.size, 1); }); }); describe("deleteAll", () => { it("when one", () => { const list = new LinkedList([1, 2, 3]); const count = list.deleteAll(value => value === 2); assert.strictEqual(count, 1); assert.strictEqual(list.size, 2); }); it("when many", () => { const list = new LinkedList([1, 2, 3]); const count = list.deleteAll(value => value !== 2); assert.strictEqual(count, 2); assert.strictEqual(list.size, 1); }); it("when none", () => { const list = new LinkedList([1, 2, 3]); const count = list.deleteAll(value => value === 4); assert.strictEqual(count, 0); assert.strictEqual(list.size, 3); }); it("callback arguments", () => { const list = new LinkedList<number>(); const first = list.push(1); const second = list.push(2); const thisArg = {}; const calls: [number, LinkedListNode<number>, LinkedList<number>, {}][] = []; list.deleteAll(function (value, node, list) { calls.push([value, node, list, this]); return false; }, thisArg); assert.deepEqual(calls, [ [1, first, list, thisArg], [2, second, list, thisArg] ]); }); it("throws if predicate not function", () => { const list = new LinkedList([1, 2, 3]); assert.throws(() => list.deleteAll(undefined), TypeError); }); }); it("clear", () => { const list = new LinkedList<number>(); const first = list.push(1); const second = list.push(2); list.clear(); assert.strictEqual(list.size, 0); assert.strictEqual(list.first, undefined); assert.strictEqual(list.last, undefined); assert.strictEqual(first.list, undefined); assert.strictEqual(first.previous, undefined); assert.strictEqual(first.next, undefined); assert.strictEqual(second.list, undefined); assert.strictEqual(second.previous, undefined); assert.strictEqual(second.next, undefined); }); describe("forEach", () => { it("when none", () => { const list = new LinkedList<number>(); const thisArg = {}; const calls: [number, LinkedListNode<number>, LinkedList<number>, {}][] = []; list.forEach(function (value, node, list) { calls.push([value, node, list, this]); }, thisArg); assert.deepEqual(calls, [ ]); }); it("when one", () => { const list = new LinkedList<number>(); const node = list.push(1); const thisArg = {}; const calls: [number, LinkedListNode<number>, LinkedList<number>, {}][] = []; list.forEach(function (value, node, list) { calls.push([value, node, list, this]); }, thisArg); assert.deepEqual(calls, [ [1, node, list, thisArg] ]); }); it("when many", () => { const list = new LinkedList<number>(); const first = list.push(1); const second = list.push(2); const thisArg = {}; const calls: [number, LinkedListNode<number>, LinkedList<number>, {}][] = []; list.forEach(function (value, node, list) { calls.push([value, node, list, this]); }, thisArg); assert.deepEqual(calls, [ [1, first, list, thisArg], [2, second, list, thisArg] ]); }); it("thows if callback not function", () => { const list = new LinkedList([1]); assert.throws(() => list.forEach(undefined), TypeError); }); }); }); });
the_stack
import { debugExports, createWorkspaceNamesResolver, resolveSettings } from './WorkspacePathResolver'; import * as Path from 'path'; import { WorkspaceFolder } from 'vscode-languageserver/node'; import { URI as Uri } from 'vscode-uri'; import { CSpellUserSettings, CustomDictionaries } from '../config/cspellConfig'; import { logError } from 'common-utils/log.js'; jest.mock('vscode-languageserver/node'); jest.mock('./vscode.config'); jest.mock('common-utils/log.js'); const mockLogError = logError as jest.Mock; const cspellConfigInVsCode: CSpellUserSettings = { ignorePaths: ['${workspaceFolder:_server}/**/*.json'], import: [ '${workspaceFolder:_server}/sampleSourceFiles/overrides/cspell.json', '${workspaceFolder:_server}/sampleSourceFiles/cSpell.json', ], enabledLanguageIds: ['typescript', 'javascript', 'php', 'json', 'jsonc'], }; const cspellConfigCustomUserDictionary: CSpellUserSettings = { customUserDictionaries: [ { name: 'Global Dictionary', path: '~/words.txt', addWords: true, }, ], }; const cspellConfigCustomWorkspaceDictionary: CSpellUserSettings = { customWorkspaceDictionaries: [ { name: 'Workspace Dictionary', path: '${workspaceFolder:Server}/sampleSourceFiles/words.txt', addWords: true, }, { name: 'Project Dictionary', addWords: true, }, ], }; const cspellConfigCustomFolderDictionary: CSpellUserSettings = { customFolderDictionaries: [ { name: 'Folder Dictionary', path: './packages/_server/words.txt', addWords: true, }, { name: 'Root Dictionary', path: '${workspaceRoot}/words2.txt', }, { name: 'Workspace Dictionary 2', path: '${workspaceFolder}/words3.txt', }, ], }; describe('Validate WorkspacePathResolver', () => { test('shallowCleanObject', () => { const clean = debugExports.shallowCleanObject; expect(clean('hello')).toBe('hello'); expect(clean(42)).toBe(42); expect([1, 2, 3, 4]).toEqual([1, 2, 3, 4]); expect({}).toEqual({}); expect({ name: 'name' }).toEqual({ name: 'name' }); expect({ name: 'name', age: undefined }).toEqual({ name: 'name' }); }); }); describe('Validate workspace substitution resolver', () => { const rootPath = '/path to root/root'; const clientPath = Path.join(rootPath, 'client'); const serverPath = Path.join(rootPath, '_server'); const clientTestPath = Path.join(clientPath, 'test'); const rootFolderUri = Uri.file(rootPath); const clientUri = Uri.file(clientPath); const serverUri = Uri.file(serverPath); const testUri = Uri.file(clientTestPath); const workspaceFolders = { root: { name: 'Root Folder', uri: rootFolderUri.toString(), }, client: { name: 'Client', uri: clientUri.toString(), }, server: { name: 'Server', uri: serverUri.toString(), }, test: { name: 'client-test', uri: testUri.toString(), }, }; const paths = { root: uriToFsPath(workspaceFolders.root.uri), client: uriToFsPath(workspaceFolders.client.uri), server: uriToFsPath(workspaceFolders.server.uri), test: uriToFsPath(workspaceFolders.test.uri), }; const workspaces: WorkspaceFolder[] = [workspaceFolders.root, workspaceFolders.client, workspaceFolders.server, workspaceFolders.test]; const settingsImports: CSpellUserSettings = Object.freeze({ import: [ 'cspell.json', '${workspaceFolder}/cspell.json', '${workspaceFolder:Client}/cspell.json', '${workspaceFolder:Server}/cspell.json', '${workspaceRoot}/cspell.json', '${workspaceFolder:Failed}/cspell.json', 'path/${workspaceFolder:Client}/cspell.json', ], }); const settingsIgnorePaths: CSpellUserSettings = Object.freeze({ ignorePaths: [ '**/node_modules/**', '${workspaceFolder}/node_modules/**', '${workspaceFolder:Server}/samples/**', '${workspaceFolder:client-test}/**/*.json', { glob: 'dist/**', root: '${workspaceFolder:Server}', }, ], }); const settingsDictionaryDefinitions: CSpellUserSettings = Object.freeze({ dictionaryDefinitions: [ { name: 'My Dictionary', path: '${workspaceFolder:Root Folder}/words.txt', }, { name: 'Company Dictionary', path: '${root}/node_modules/@company/terms/terms.txt', }, { name: 'Project Dictionary', path: `${rootPath}/terms/terms.txt`, }, ].map((f) => Object.freeze(f)), }); const settingsDictionaryDefinitions2: CSpellUserSettings = Object.freeze({ dictionaryDefinitions: (settingsDictionaryDefinitions.dictionaryDefinitions || []) .concat([ { name: 'python-terms', path: '${workspaceFolder:Root Folder}/python-words.txt', }, { name: 'legacy-definition', file: 'legacy-words.txt', path: '${workspaceFolder:Root Folder}', }, { name: 'legacy-definition-file', file: '${workspaceFolder:Root Folder}/legacy-words-2.txt', }, ]) .map((f) => Object.freeze(f)), }); const settingsLanguageSettings: CSpellUserSettings = Object.freeze({ languageSettings: [ { languageId: 'typescript', dictionaryDefinitions: settingsDictionaryDefinitions.dictionaryDefinitions, }, ].map((f) => Object.freeze(f)), }); const overrides: CSpellUserSettings['overrides'] = [ { filename: ['*.md', '**/*.ts', '**/*.js'], languageSettings: settingsLanguageSettings.languageSettings, dictionaryDefinitions: settingsDictionaryDefinitions.dictionaryDefinitions, }, { filename: '${workspaceFolder:Client}/docs/nl_NL/**', language: 'nl', }, { filename: ['${workspaceFolder:Client}/**/*.config.json', { glob: '**/*.config.json', root: '${workspaceFolder:Server}' }], languageId: 'jsonc', }, ]; const customDictionaries: CustomDictionaries = { 'company-terms': { description: 'Company Wide Terms', path: '${root}/node_modules/@company/terms/company-terms.txt', addWords: false, }, 'Project Dictionary': { addWords: true, }, 'python-terms': true, html: false, } as const; const settingsOverride: CSpellUserSettings = { overrides: overrides.map((f) => Object.freeze(f)), }; test('testUri assumptions', () => { const u = Uri.file('relative/to/current/dir/file.txt'); // vscode-uri does not support relative paths. expect(u.path).toBe('/relative/to/current/dir/file.txt'); }); test('resolveSettings Imports', () => { const resolver = createWorkspaceNamesResolver(workspaces[1], workspaces, undefined); const result = resolveSettings(settingsImports, resolver); const imports = Array.isArray(result.import) ? pp(result.import) : result.import; expect(imports).toEqual([ p('cspell.json'), p(`${clientUri.fsPath}/cspell.json`), p(`${clientUri.fsPath}/cspell.json`), p(`${serverUri.fsPath}/cspell.json`), p(`${rootFolderUri.fsPath}/cspell.json`), p('${workspaceFolder:Failed}/cspell.json'), p('path/${workspaceFolder:Client}/cspell.json'), ]); }); test('resolveSettings ignorePaths', () => { const root = '/config root'; const resolver = createWorkspaceNamesResolver(workspaceFolders.client, workspaces, root); const result = resolveSettings(settingsIgnorePaths, resolver); // '**/node_modules/**', // '${workspaceFolder}/node_modules/**', // '${workspaceFolder:Server}/samples/**', // '${workspaceFolder:client-test}/**/*.json', expect(result.ignorePaths).toEqual([ { glob: '**/node_modules/**', root: uriToFsPath(workspaceFolders.client.uri) }, { glob: '/node_modules/**', root: uriToFsPath(workspaceFolders.client.uri) }, { glob: '/samples/**', root: uriToFsPath(workspaceFolders.server.uri) }, { glob: '/**/*.json', root: uriToFsPath(workspaceFolders.test.uri) }, { glob: 'dist/**', root: uriToFsPath(workspaceFolders.server.uri) }, ]); }); test.each` files | globRoot | expected ${undefined} | ${undefined} | ${undefined} ${['**']} | ${undefined} | ${[{ glob: '**', root: paths.client }]} ${['**']} | ${'~/glob-root'} | ${[{ glob: '**', root: '~/glob-root' }]} ${['**']} | ${'${workspaceFolder}/..'} | ${[{ glob: '**', root: paths.root }]} ${['${workspaceFolder}/**']} | ${''} | ${[{ glob: '/**', root: paths.client }]} ${['${workspaceFolder}/**']} | ${undefined} | ${[{ glob: '/**', root: paths.client }]} ${['${workspaceFolder}/**']} | ${'~/glob-root'} | ${[{ glob: '/**', root: paths.client }]} ${['${workspaceFolder:Server}/**']} | ${'~/glob-root'} | ${[{ glob: '/**', root: paths.server }]} `('resolveSettings files $files $globRoot', ({ files, globRoot, expected }) => { const root = '/config root'; const resolver = createWorkspaceNamesResolver(workspaceFolders.client, workspaces, root); const settings: CSpellUserSettings = { globRoot, files }; const result = resolveSettings(settings, resolver); expect(result.files).toEqual(expected); }); test('resolveSettings dictionaryDefinitions', () => { const resolver = createWorkspaceNamesResolver(workspaces[1], workspaces, undefined); const result = resolveSettings(settingsDictionaryDefinitions, resolver); expect(normalizePath(result.dictionaryDefinitions)).toEqual([ expect.objectContaining({ name: 'My Dictionary', path: p(`${rootFolderUri.fsPath}/words.txt`) }), expect.objectContaining({ name: 'Company Dictionary', path: p(`${rootFolderUri.fsPath}/node_modules/@company/terms/terms.txt`), }), expect.objectContaining({ name: 'Project Dictionary', path: p(`${rootFolderUri.fsPath}/terms/terms.txt`) }), ]); }); test('resolveSettings languageSettings', () => { const resolver = createWorkspaceNamesResolver(workspaces[1], workspaces, undefined); const result = resolveSettings(settingsLanguageSettings, resolver); expect(result?.languageSettings?.[0].languageId).toEqual('typescript'); expect(normalizePath(result?.languageSettings?.[0].dictionaryDefinitions)).toEqual([ { name: 'My Dictionary', path: p(`${rootFolderUri.fsPath}/words.txt`) }, { name: 'Company Dictionary', path: p(`${rootFolderUri.fsPath}/node_modules/@company/terms/terms.txt`) }, { name: 'Project Dictionary', path: p(`${rootFolderUri.fsPath}/terms/terms.txt`) }, ]); }); test('resolveSettings overrides', () => { const resolver = createWorkspaceNamesResolver(workspaces[1], workspaces, undefined); const result = resolveSettings(settingsOverride, resolver); expect(result?.overrides?.[0]?.languageSettings?.[0].languageId).toEqual('typescript'); expect(normalizePath(result?.overrides?.[0].dictionaryDefinitions)).toEqual([ { name: 'My Dictionary', path: p(`${rootFolderUri.fsPath}/words.txt`) }, { name: 'Company Dictionary', path: p(`${rootFolderUri.fsPath}/node_modules/@company/terms/terms.txt`) }, { name: 'Project Dictionary', path: p(`${rootFolderUri.fsPath}/terms/terms.txt`) }, ]); expect(normalizePath(result?.overrides?.[0]?.dictionaryDefinitions)).toEqual([ { name: 'My Dictionary', path: p(`${rootFolderUri.fsPath}/words.txt`) }, { name: 'Company Dictionary', path: p(`${rootFolderUri.fsPath}/node_modules/@company/terms/terms.txt`) }, { name: 'Project Dictionary', path: p(`${rootFolderUri.fsPath}/terms/terms.txt`) }, ]); // @todo need to test changes to filename glob patterns. expect(result?.overrides?.map((o) => o.filename)).toEqual([ [ { glob: '*.md', root: uriToFsPath(workspaceFolders.client.uri), }, { glob: '**/*.ts', root: uriToFsPath(workspaceFolders.client.uri), }, { glob: '**/*.js', root: uriToFsPath(workspaceFolders.client.uri), }, ], { glob: '/docs/nl_NL/**', root: uriToFsPath(workspaceFolders.client.uri), }, [ { glob: '/**/*.config.json', root: uriToFsPath(workspaceFolders.client.uri), }, { glob: '**/*.config.json', root: uriToFsPath(workspaceFolders.server.uri), }, ], ]); }); test('resolve custom dictionaries', () => { const settings: CSpellUserSettings = { ...cspellConfigInVsCode, ...settingsDictionaryDefinitions2, ...cspellConfigCustomFolderDictionary, ...cspellConfigCustomUserDictionary, ...cspellConfigCustomWorkspaceDictionary, customDictionaries, dictionaries: ['typescript'], }; const resolver = createWorkspaceNamesResolver(workspaces[1], workspaces, 'custom root'); const result = resolveSettings(settings, resolver); const dictDefs = new Map(result.dictionaryDefinitions?.map((d) => [d.name, d]) || []); expect(new Set(result.dictionaries)).toEqual( new Set([ '!html', 'Global Dictionary', 'Workspace Dictionary', 'Project Dictionary', 'Folder Dictionary', 'Root Dictionary', 'Workspace Dictionary 2', 'company-terms', 'python-terms', 'typescript', ]) ); expect(new Set(dictDefs.keys())).toEqual( new Set([ 'Global Dictionary', 'My Dictionary', 'Company Dictionary', 'Project Dictionary', 'Workspace Dictionary', 'Folder Dictionary', 'Root Dictionary', 'Workspace Dictionary 2', 'company-terms', 'python-terms', 'legacy-definition', 'legacy-definition-file', ]) ); expect(normalizePath(result.dictionaryDefinitions)).toEqual( expect.arrayContaining([ expect.objectContaining({ name: 'Folder Dictionary', path: p(`${clientUri.fsPath}/packages/_server/words.txt`), }), expect.objectContaining({ name: 'Root Dictionary', path: p('custom root/words2.txt'), }), expect.objectContaining({ name: 'Workspace Dictionary 2', path: p(`${clientUri.fsPath}/words3.txt`), }), ]) ); expect(dictDefs.get('legacy-definition-file')?.path).toEqual(expect.stringMatching(/legacy-words-2\.txt$/)); }); test('resolve custom dictionaries by name', () => { const settings: CSpellUserSettings = { ...cspellConfigInVsCode, ...settingsDictionaryDefinitions, customWorkspaceDictionaries: ['Project Dictionary'], customFolderDictionaries: ['Folder Dictionary'], // This dictionary doesn't exist. dictionaries: ['typescript'], }; const resolver = createWorkspaceNamesResolver(workspaces[1], workspaces, 'custom root'); const result = resolveSettings(settings, resolver); expect(new Set(result.dictionaries)).toEqual(new Set(['Project Dictionary', 'Folder Dictionary', 'typescript'])); expect(result.dictionaryDefinitions?.map((d) => d.name)).toEqual(['My Dictionary', 'Company Dictionary', 'Project Dictionary']); expect(normalizePath(result.dictionaryDefinitions)).toEqual( expect.arrayContaining([ expect.objectContaining({ name: 'Project Dictionary', path: p('/path to root/root/terms/terms.txt'), }), ]) ); expect(result.dictionaryDefinitions).not.toEqual( expect.arrayContaining([ expect.objectContaining({ name: 'Folder Dictionary', }), ]) ); }); test('Unresolved workspaceFolder', () => { mockLogError.mockReset(); const settings: CSpellUserSettings = { ...cspellConfigInVsCode, ...settingsDictionaryDefinitions, customWorkspaceDictionaries: [{ name: 'Unknown Dictionary' }], dictionaries: ['typescript'], }; const resolver = createWorkspaceNamesResolver(workspaces[1], workspaces, 'custom root'); const result = resolveSettings(settings, resolver); expect(result.dictionaryDefinitions).not.toEqual( expect.arrayContaining([ expect.objectContaining({ name: 'Unknown Dictionary', }), ]) ); expect(mockLogError).toHaveBeenCalledWith('Failed to resolve ${workspaceFolder:_server}'); }); function uriToFsPath(u: string | Uri): string { if (typeof u === 'string') { u = Uri.parse(u); } return u.fsPath; } function normalizePath<T extends { path?: string }>(values?: T[]): T[] | undefined { function m(v: T): T { const r: T = { ...v }; r.path = p(v.path || ''); return r; } return values?.map(m); } function pp(paths: string[] | undefined): string[] | undefined { return paths?.map(p); } function p(path: string): string { return Uri.file(path).fsPath; } });
the_stack
import type {GeoPackageLoaderOptions} from '../geopackage-loader'; import initSqlJs, {SqlJsStatic, Database, Statement} from 'sql.js'; import {WKBLoader} from '@loaders.gl/wkt'; import { Schema, Field, Geometry, DataType, Bool, Utf8, Float64, Int32, Int8, Int16, Float32, Binary, Tables, ObjectRowTable, Feature } from '@loaders.gl/schema'; import {binaryToGeometry, transformGeoJsonCoords} from '@loaders.gl/gis'; import {Proj4Projection} from '@math.gl/proj4'; import { GeometryColumnsRow, ContentsRow, SpatialRefSysRow, ProjectionMapping, GeometryBitFlags, DataColumnsRow, DataColumnsMapping, PragmaTableInfoRow, SQLiteTypes, GeoPackageGeometryTypes } from './types'; // We pin to the same version as sql.js that we use. // As of March 2022, versions 1.6.0, 1.6.1, and 1.6.2 of sql.js appeared not to work. export const DEFAULT_SQLJS_CDN = 'https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.5.0/'; // https://www.geopackage.org/spec121/#flags_layout const ENVELOPE_BYTE_LENGTHS = { 0: 0, 1: 32, 2: 48, 3: 48, 4: 64, // values 5-7 are invalid and _should_ never show up 5: 0, 6: 0, 7: 0 }; // Documentation: https://www.geopackage.org/spec130/index.html#table_column_data_types const SQL_TYPE_MAPPING: {[type in SQLiteTypes | GeoPackageGeometryTypes]: typeof DataType} = { BOOLEAN: Bool, TINYINT: Int8, SMALLINT: Int16, MEDIUMINT: Int32, INT: Int32, INTEGER: Int32, FLOAT: Float32, DOUBLE: Float64, REAL: Float64, TEXT: Utf8, BLOB: Binary, DATE: Utf8, DATETIME: Utf8, GEOMETRY: Binary, POINT: Binary, LINESTRING: Binary, POLYGON: Binary, MULTIPOINT: Binary, MULTILINESTRING: Binary, MULTIPOLYGON: Binary, GEOMETRYCOLLECTION: Binary }; export default async function parseGeoPackage( arrayBuffer: ArrayBuffer, options?: GeoPackageLoaderOptions ): Promise<Tables<ObjectRowTable> | Record<string, Feature[]>> { const {sqlJsCDN = DEFAULT_SQLJS_CDN} = options?.geopackage || {}; const {reproject = false, _targetCrs = 'WGS84', format = 'tables'} = options?.gis || {}; const db = await loadDatabase(arrayBuffer, sqlJsCDN); const tables = listVectorTables(db); const projections = getProjections(db); // Mapping from tableName to geojson feature collection const outputTables: Tables<ObjectRowTable> = { shape: 'tables', tables: [] }; for (const table of tables) { const {table_name: tableName} = table; outputTables.tables.push({ name: tableName, table: getVectorTable(db, tableName, projections, { reproject, _targetCrs }) }); } if (format === 'geojson') { return formatTablesAsGeojson(outputTables); } return outputTables; } /** * Initialize SQL.js and create database * * @param arrayBuffer input bytes * @return SQL.js database object */ async function loadDatabase(arrayBuffer: ArrayBuffer, sqlJsCDN: string | null): Promise<Database> { // In Node, `locateFile` must not be passed let SQL: SqlJsStatic; if (sqlJsCDN) { SQL = await initSqlJs({ locateFile: (file) => `${sqlJsCDN}${file}` }); } else { SQL = await initSqlJs(); } return new SQL.Database(new Uint8Array(arrayBuffer)); } /** * Find all vector tables in GeoPackage * This queries the `gpkg_contents` table to find a list of vector tables * * @param db GeoPackage to query * @return list of table references */ function listVectorTables(db: Database): ContentsRow[] { // The gpkg_contents table can have at least three categorical values for // data_type. // - 'features' refers to a vector geometry table // (https://www.geopackage.org/spec121/#_contents_2) // - 'tiles' refers to a raster table // (https://www.geopackage.org/spec121/#_contents_3) // - 'attributes' refers to a data table with no geometry // (https://www.geopackage.org/spec121/#_contents_4). // We hard code 'features' because for now we don't support raster data or pure attribute data // eslint-disable-next-line quotes const stmt = db.prepare("SELECT * FROM gpkg_contents WHERE data_type='features';"); const vectorTablesInfo: ContentsRow[] = []; while (stmt.step()) { const vectorTableInfo = stmt.getAsObject() as unknown as ContentsRow; vectorTablesInfo.push(vectorTableInfo); } return vectorTablesInfo; } /** * Load geometries from vector table * * @param db GeoPackage object * @param tableName name of vector table to query * @param projections keys are srs_id values, values are WKT strings * @returns Array of GeoJSON Feature objects */ function getVectorTable( db: Database, tableName: string, projections: ProjectionMapping, {reproject, _targetCrs}: {reproject: boolean; _targetCrs: string} ): ObjectRowTable { const dataColumns = getDataColumns(db, tableName); const geomColumn = getGeometryColumn(db, tableName); const featureIdColumn = getFeatureIdName(db, tableName); // Get vector features from table // Don't think it's possible to parameterize the table name in SQLite? const {columns, values} = db.exec(`SELECT * FROM \`${tableName}\`;`)[0]; let projection; if (reproject) { const geomColumnProjStr = projections[geomColumn.srs_id]; projection = new Proj4Projection({ from: geomColumnProjStr, to: _targetCrs }); } const geojsonFeatures: object[] = []; for (const row of values) { const geojsonFeature = constructGeoJsonFeature( columns, row, geomColumn, // @ts-ignore dataColumns, featureIdColumn ); geojsonFeatures.push(geojsonFeature); } const schema = getArrowSchema(db, tableName); if (projection) { return { data: transformGeoJsonCoords(geojsonFeatures, projection.project), schema, shape: 'object-row-table' }; } return {data: geojsonFeatures, schema, shape: 'object-row-table'}; } /** * Find all projections defined in GeoPackage * This queries the gpkg_spatial_ref_sys table * @param db GeoPackage object * @returns mapping from srid to WKT projection string */ function getProjections(db: Database): ProjectionMapping { // Query gpkg_spatial_ref_sys to get srid: srtext mappings const stmt = db.prepare('SELECT * FROM gpkg_spatial_ref_sys;'); const projectionMapping: ProjectionMapping = {}; while (stmt.step()) { const srsInfo = stmt.getAsObject() as unknown as SpatialRefSysRow; const {srs_id, definition} = srsInfo; projectionMapping[srs_id] = definition; } return projectionMapping; } /** * Construct single GeoJSON feature given row's data * @param columns array of ordered column identifiers * @param row array of ordered values representing row's data * @param geomColumn geometry column metadata * @param dataColumns mapping from table column names to property name * @returns GeoJSON Feature object */ function constructGeoJsonFeature( columns: string[], row: any[], geomColumn: GeometryColumnsRow, dataColumns: DataColumnsMapping, featureIdColumn: string ): Feature<Geometry | null> { // Find feature id const idIdx = columns.indexOf(featureIdColumn); const id = row[idIdx]; // Parse geometry columns to geojson const geomColumnIdx = columns.indexOf(geomColumn.column_name); const geometry = parseGeometry(row[geomColumnIdx].buffer); const properties = {}; if (dataColumns) { for (const [key, value] of Object.entries(dataColumns)) { const idx = columns.indexOf(key); // @ts-ignore TODO - Check what happens if null? properties[value] = row[idx]; } } else { // Put all columns except for the feature id and geometry in properties for (let i = 0; i < columns.length; i++) { if (i === idIdx || i === geomColumnIdx) { // eslint-disable-next-line no-continue continue; } const columnName = columns[i]; properties[columnName] = row[i]; } } return { id, type: 'Feature', geometry, properties }; } /** * Get GeoPackage version from database * @param db database * @returns version string. One of '1.0', '1.1', '1.2' */ // @ts-ignore // eslint-disable-next-line @typescript-eslint/no-unused-vars function getGeopackageVersion(db: Database): string | null { const textDecoder = new TextDecoder(); // Read application id from SQLite metadata const applicationIdQuery = db.exec('PRAGMA application_id;')[0]; const applicationId = applicationIdQuery.values[0][0]; // Convert 4-byte signed int32 application id to text const buffer = new ArrayBuffer(4); const view = new DataView(buffer); view.setInt32(0, Number(applicationId)); const versionString = textDecoder.decode(buffer); if (versionString === 'GP10') { return '1.0'; } if (versionString === 'GP11') { return '1.1'; } // If versionString is GPKG, then read user_version const userVersionQuery = db.exec('PRAGMA user_version;')[0]; const userVersionInt = userVersionQuery.values[0][0]; if (userVersionInt && userVersionInt < 10300) { return '1.2'; } return null; } /** * Find name of feature id column in table * The feature ID is the primary key of the table. * http://www.geopackage.org/spec121/#feature_user_tables * * @param db database * @param tableName name of table * @return name of feature id column */ function getFeatureIdName(db: Database, tableName: string): string | null { // Again, not possible to parameterize table name? const stmt = db.prepare(`PRAGMA table_info(\`${tableName}\`)`); while (stmt.step()) { const pragmaTableInfo = stmt.getAsObject() as unknown as PragmaTableInfoRow; const {name, pk} = pragmaTableInfo; if (pk) { return name; } } // Is it guaranteed for there always to be at least one primary key column in the table? return null; } /** * Parse geometry buffer * GeoPackage vector geometries are slightly extended past the WKB standard * See: https://www.geopackage.org/spec121/#gpb_format * * @param arrayBuffer geometry buffer * @return GeoJSON geometry (in original CRS) */ function parseGeometry(arrayBuffer: ArrayBuffer): Geometry | null { const view = new DataView(arrayBuffer); const {envelopeLength, emptyGeometry} = parseGeometryBitFlags(view.getUint8(3)); // A Feature object has a member with the name "geometry". The value of the // geometry member SHALL be either a Geometry object as defined above or, in // the case that the Feature is unlocated, a JSON null value. /** @see https://tools.ietf.org/html/rfc7946#section-3.2 */ if (emptyGeometry) { return null; } // Do I need to find the srid here? Is it necessarily the same for every // geometry in a table? // const srid = view.getInt32(4, littleEndian); // 2 byte magic, 1 byte version, 1 byte flags, 4 byte int32 srid const wkbOffset = 8 + envelopeLength; // Loaders should not depend on `core` and the context passed to the main loader doesn't include a // `parseSync` option, so instead we call parseSync directly on WKBLoader const binaryGeometry = WKBLoader.parseSync(arrayBuffer.slice(wkbOffset)); return binaryToGeometry(binaryGeometry); } /** * Parse geometry header flags * https://www.geopackage.org/spec121/#flags_layout * * @param byte uint8 number representing flags * @return object representing information from bit flags */ function parseGeometryBitFlags(byte: number): GeometryBitFlags { // Are header values little endian? const envelopeValue = (byte & 0b00001110) / 2; // TODO: Not sure the best way to handle this. Throw an error if envelopeValue outside 0-7? const envelopeLength = ENVELOPE_BYTE_LENGTHS[envelopeValue] as number; return { littleEndian: Boolean(byte & 0b00000001), envelopeLength, emptyGeometry: Boolean(byte & 0b00010000), extendedGeometryType: Boolean(byte & 0b00100000) }; } /** * Find geometry column in given vector table * * @param db GeoPackage object * @param tableName Name of vector table * @returns Array of geometry column definitions */ function getGeometryColumn(db: Database, tableName: string): GeometryColumnsRow { const stmt = db.prepare('SELECT * FROM gpkg_geometry_columns WHERE table_name=:tableName;'); stmt.bind({':tableName': tableName}); // > Requirement 30 // > A feature table SHALL have only one geometry column. // https://www.geopackage.org/spec121/#feature_user_tables // So we should need one and only one step, given that we use the WHERE clause in the SQL query // above stmt.step(); const geometryColumn = stmt.getAsObject() as unknown as GeometryColumnsRow; return geometryColumn; } /** * Find property columns in given vector table * @param db GeoPackage object * @param tableName Name of vector table * @returns Mapping from table column names to property name */ function getDataColumns(db: Database, tableName: string): DataColumnsMapping | null { // gpkg_data_columns is not required to exist // https://www.geopackage.org/spec121/#extension_schema let stmt: Statement; try { stmt = db.prepare('SELECT * FROM gpkg_data_columns WHERE table_name=:tableName;'); } catch (error) { if ((error as Error).message.includes('no such table')) { return null; } throw error; } stmt.bind({':tableName': tableName}); // Convert DataColumnsRow object this to a key-value {column_name: name} const result: DataColumnsMapping = {}; while (stmt.step()) { const column = stmt.getAsObject() as unknown as DataColumnsRow; const {column_name, name} = column; result[column_name] = name || null; } return result; } /** * Get arrow schema * @param db GeoPackage object * @param tableName table name * @returns Arrow-like Schema */ function getArrowSchema(db: Database, tableName: string): Schema { const stmt = db.prepare(`PRAGMA table_info(\`${tableName}\`)`); const fields: Field[] = []; while (stmt.step()) { const pragmaTableInfo = stmt.getAsObject() as unknown as PragmaTableInfoRow; const {name, type, notnull} = pragmaTableInfo; const schemaType = SQL_TYPE_MAPPING[type] && new SQL_TYPE_MAPPING[type](); const field = new Field(name, schemaType, !notnull); fields.push(field); } return new Schema(fields); } function formatTablesAsGeojson(tables: Tables<ObjectRowTable>): Record<string, Feature[]> { const geojsonMap = {}; for (const table of tables.tables) { geojsonMap[table.name] = table.table.data; } return geojsonMap; }
the_stack
import { useComposedRefs } from '@tamagui/compose-refs' import { getButtonSize, getSize, isWeb, styled, withStaticProperties } from '@tamagui/core' import { clamp, composeEventHandlers } from '@tamagui/helpers' import { SizableStackProps, ThemeableStack, YStackProps } from '@tamagui/stacks' import { useControllableState } from '@tamagui/use-controllable-state' import { useDirection } from '@tamagui/use-direction' import * as React from 'react' import { LayoutRectangle, View } from 'react-native' import { ARROW_KEYS, BACK_KEYS, PAGE_KEYS, SLIDER_NAME, SliderOrientationProvider, SliderProvider, useSliderContext, useSliderOrientationContext, } from './constants' import { convertValueToPercentage, getClosestValueIndex, getDecimalCount, getLabel, getNextSortedValues, getThumbInBoundsOffset, hasMinStepsBetweenValues, linearScale, roundValue, } from './helpers' import { SliderFrame, SliderImpl } from './SliderImpl' import { ScopedProps, SliderContextValue, SliderHorizontalProps, SliderImplElement, SliderProps, SliderTrackProps, SliderVerticalProps, } from './types' /* ------------------------------------------------------------------------------------------------- * SliderHorizontal * -----------------------------------------------------------------------------------------------*/ type SliderHorizontalElement = SliderImplElement const SliderHorizontal = React.forwardRef<SliderHorizontalElement, SliderHorizontalProps>( (props: ScopedProps<SliderHorizontalProps>, forwardedRef) => { const { min, max, dir, onSlideStart, onSlideMove, onStepKeyDown, ...sliderProps } = props const direction = useDirection(dir) const isDirectionLTR = direction === 'ltr' const layoutRef = React.useRef<LayoutRectangle | null>(null) const [size, setSize] = React.useState(0) function getValueFromPointer(pointerPosition: number) { const layout = layoutRef.current if (!layout) return const input: [number, number] = [0, layout.width] const output: [number, number] = isDirectionLTR ? [min, max] : [max, min] const value = linearScale(input, output) return value(pointerPosition) } return ( <SliderOrientationProvider scope={props.__scopeSlider} startEdge={isDirectionLTR ? 'left' : 'right'} endEdge={isDirectionLTR ? 'right' : 'left'} direction={isDirectionLTR ? 1 : -1} sizeProp="width" size={size} > <SliderImpl ref={forwardedRef} dir={direction} {...sliderProps} orientation="horizontal" onLayout={(e) => { const layout = e.nativeEvent.layout layoutRef.current = layout setSize(layout.height) }} onSlideStart={(event, target) => { const value = getValueFromPointer(event.nativeEvent.locationX) if (value) { onSlideStart?.(value, target) } }} onSlideMove={(event) => { const value = getValueFromPointer(event.nativeEvent.locationX) if (value) { onSlideMove?.(value) } }} onSlideEnd={() => {}} onStepKeyDown={(event) => { const isBackKey = BACK_KEYS[direction].includes(event.key) onStepKeyDown?.({ event, direction: isBackKey ? -1 : 1 }) }} /> </SliderOrientationProvider> ) } ) /* ------------------------------------------------------------------------------------------------- * SliderVertical * -----------------------------------------------------------------------------------------------*/ type SliderVerticalElement = SliderImplElement const SliderVertical = React.forwardRef<SliderVerticalElement, SliderVerticalProps>( (props: ScopedProps<SliderVerticalProps>, forwardedRef) => { const { min, max, onSlideStart, onSlideMove, onStepKeyDown, ...sliderProps } = props const layoutRef = React.useRef<LayoutRectangle | null>(null) const [size, setSize] = React.useState(0) function getValueFromPointer(pointerPosition: number) { const layout = layoutRef.current if (!layout) return const input: [number, number] = [0, layout.height] const output: [number, number] = [max, min] const value = linearScale(input, output) return value(pointerPosition) } return ( <SliderOrientationProvider scope={props.__scopeSlider} startEdge="bottom" endEdge="top" sizeProp="height" size={size} direction={1} > <SliderImpl ref={forwardedRef} {...sliderProps} orientation="vertical" onLayout={(e) => { const layout = e.nativeEvent.layout layoutRef.current = layout setSize(layout.height) }} onSlideStart={(event, target) => { const value = getValueFromPointer(event.nativeEvent.locationY) if (value) { onSlideStart?.(value, target) } }} onSlideMove={(event) => { const value = getValueFromPointer(event.nativeEvent.locationY) if (value) { onSlideMove?.(value) } }} onSlideEnd={() => {}} onStepKeyDown={(event) => { const isBackKey = BACK_KEYS.ltr.includes(event.key) onStepKeyDown?.({ event, direction: isBackKey ? -1 : 1 }) }} /> </SliderOrientationProvider> ) } ) /* ------------------------------------------------------------------------------------------------- * SliderTrack * -----------------------------------------------------------------------------------------------*/ const TRACK_NAME = 'SliderTrack' type SliderTrackElement = HTMLElement | View const SliderTrackFrame = styled(SliderFrame, { name: 'SliderTrack', height: '100%', width: '100%', backgroundColor: '$background', position: 'relative', borderRadius: 100_000, overflow: 'hidden', }) const SliderTrack = React.forwardRef<SliderTrackElement, SliderTrackProps>( (props: ScopedProps<SliderTrackProps>, forwardedRef) => { const { __scopeSlider, ...trackProps } = props const context = useSliderContext(TRACK_NAME, __scopeSlider) return ( <SliderTrackFrame data-disabled={context.disabled ? '' : undefined} data-orientation={context.orientation} orientation={context.orientation} size={context.size} {...trackProps} ref={forwardedRef} /> ) } ) SliderTrack.displayName = TRACK_NAME /* ------------------------------------------------------------------------------------------------- * SliderTrackActive * -----------------------------------------------------------------------------------------------*/ const RANGE_NAME = 'SliderTrackActive' type SliderTrackActiveElement = HTMLElement | View interface SliderTrackActiveProps extends YStackProps {} const SliderTrackActiveFrame = styled(SliderFrame, { name: 'SliderTrackActive', backgroundColor: '$background', position: 'absolute', }) const SliderTrackActive = React.forwardRef<SliderTrackActiveElement, SliderTrackActiveProps>( (props: ScopedProps<SliderTrackActiveProps>, forwardedRef) => { const { __scopeSlider, ...rangeProps } = props const context = useSliderContext(RANGE_NAME, __scopeSlider) const orientation = useSliderOrientationContext(RANGE_NAME, __scopeSlider) const ref = React.useRef<HTMLSpanElement>(null) const composedRefs = useComposedRefs(forwardedRef, ref) const valuesCount = context.values.length const percentages = context.values.map((value) => convertValueToPercentage(value, context.min, context.max) ) const offsetStart = valuesCount > 1 ? Math.min(...percentages) : 0 const offsetEnd = 100 - Math.max(...percentages) return ( <SliderTrackActiveFrame orientation={context.orientation} data-orientation={context.orientation} data-disabled={context.disabled ? '' : undefined} size={context.size} {...rangeProps} ref={composedRefs} {...{ [orientation.startEdge]: offsetStart + '%', [orientation.endEdge]: offsetEnd + '%', }} {...(orientation.sizeProp === 'width' ? { height: '100%', } : { left: 0, right: 0, })} /> ) } ) SliderTrackActive.displayName = RANGE_NAME /* ------------------------------------------------------------------------------------------------- * SliderThumb * -----------------------------------------------------------------------------------------------*/ const THUMB_NAME = 'SliderThumb' const SliderThumbFrame = styled(ThemeableStack, { name: 'SliderThumb', position: 'absolute', // TODO not taking up 2 bordered: 2, // OR THIS borderWidth: 2, backgrounded: true, pressable: true, focusable: true, hoverable: true, variants: { size: { '...size': (val) => { const size = typeof val === 'number' ? val : getSize(val, -1) return { width: size, height: size, minWidth: size, minHeight: size, } }, }, }, }) type SliderThumbElement = HTMLElement | View interface SliderThumbProps extends SizableStackProps { index: number } const SliderThumb = React.forwardRef<SliderThumbElement, SliderThumbProps>( (props: ScopedProps<SliderThumbProps>, forwardedRef) => { const { __scopeSlider, index, size: sizeProp, ...thumbProps } = props const context = useSliderContext(THUMB_NAME, __scopeSlider) const orientation = useSliderOrientationContext(THUMB_NAME, __scopeSlider) const [thumb, setThumb] = React.useState<View | HTMLElement | null>(null) const composedRefs = useComposedRefs(forwardedRef, (node) => setThumb(node)) // We cast because index could be `-1` which would return undefined const value = context.values[index] as number | undefined const percent = value === undefined ? 0 : convertValueToPercentage(value, context.min, context.max) const label = getLabel(index, context.values.length) const [size, setSize] = React.useState(0) const thumbInBoundsOffset = size ? getThumbInBoundsOffset(size, percent, orientation.direction) : 0 React.useEffect(() => { if (thumb) { context.thumbs.add(thumb) return () => { context.thumbs.delete(thumb) } } }, [thumb, context.thumbs]) return ( <SliderThumbFrame ref={composedRefs} // TODO // @ts-ignore role="slider" aria-label={props['aria-label'] || label} aria-valuemin={context.min} aria-valuenow={value} aria-valuemax={context.max} aria-orientation={context.orientation} data-orientation={context.orientation} data-disabled={context.disabled ? '' : undefined} // TODO // @ts-ignore tabIndex={context.disabled ? undefined : 0} {...thumbProps} {...(context.orientation === 'horizontal' ? { x: thumbInBoundsOffset - size / 2, y: -size / 2, top: '50%', ...(size === 0 && { top: 'auto', bottom: 'auto', }), } : { x: -size / 2, y: size / 2, left: '50%', ...(size === 0 && { left: 'auto', right: 'auto', }), })} size={sizeProp ?? context.size ?? '$4'} onLayout={(e) => { setSize(e.nativeEvent.layout[orientation.sizeProp]) }} {...{ [orientation.startEdge]: `${percent}%`, }} /** * There will be no value on initial render while we work out the index so we hide thumbs * without a value, otherwise SSR will render them in the wrong position before they * snap into the correct position during hydration which would be visually jarring for * slower connections. */ // style={value === undefined ? { display: 'none' } : props.style} onFocus={composeEventHandlers(props.onFocus, () => { context.valueIndexToChangeRef.current = index })} /> ) } ) SliderThumb.displayName = THUMB_NAME /* ------------------------------------------------------------------------------------------------- * Slider * -----------------------------------------------------------------------------------------------*/ type SliderElement = SliderHorizontalElement | SliderVerticalElement const Slider = withStaticProperties( React.forwardRef<SliderElement, SliderProps>((props: ScopedProps<SliderProps>, forwardedRef) => { const { name, min = 0, max = 100, step = 1, orientation = 'horizontal', disabled = false, minStepsBetweenThumbs = 0, defaultValue = [min], value, onValueChange = () => {}, size: sizeProp, ...sliderProps } = props const sliderRef = React.useRef<SliderImplElement>(null) const composedRefs = useComposedRefs(sliderRef, forwardedRef) const thumbRefs = React.useRef<SliderContextValue['thumbs']>(new Set()) const valueIndexToChangeRef = React.useRef<number>(0) const isHorizontal = orientation === 'horizontal' // We set this to true by default so that events bubble to forms without JS (SSR) // TODO // const isFormControl = slider ? Boolean(slider.closest('form')) : true const [values = [], setValues] = useControllableState({ prop: value, defaultProp: defaultValue, onChange: (value) => { if (isWeb) { const thumbs = [...thumbRefs.current] thumbs[valueIndexToChangeRef.current]?.focus() } onValueChange(value) }, }) if (isWeb) { React.useEffect(() => { const node = sliderRef.current as HTMLElement if (!node) return const preventDefault = (e) => { e.preventDefault() } node.addEventListener('touchstart', preventDefault) return () => { node.removeEventListener('touchstart', preventDefault) } }, []) } function handleSlideMove(value: number) { updateValues(value, valueIndexToChangeRef.current) } function updateValues(value: number, atIndex: number) { const decimalCount = getDecimalCount(step) const snapToStep = roundValue(Math.round((value - min) / step) * step + min, decimalCount) const nextValue = clamp(snapToStep, [min, max]) setValues((prevValues = []) => { const nextValues = getNextSortedValues(prevValues, nextValue, atIndex) if (hasMinStepsBetweenValues(nextValues, minStepsBetweenThumbs * step)) { valueIndexToChangeRef.current = nextValues.indexOf(nextValue) return String(nextValues) === String(prevValues) ? prevValues : nextValues } else { return prevValues } }) } const SliderOriented = isHorizontal ? SliderHorizontal : SliderVertical return ( <SliderProvider scope={props.__scopeSlider} disabled={disabled} min={min} max={max} valueIndexToChangeRef={valueIndexToChangeRef} thumbs={thumbRefs.current} values={values} orientation={orientation} size={sizeProp} > <SliderOriented aria-disabled={disabled} data-disabled={disabled ? '' : undefined} {...sliderProps} ref={composedRefs} min={min} max={max} onSlideStart={ disabled ? undefined : (value: number, target) => { // when starting on the track, move it right away // when starting on thumb, dont jump until movemenet as it feels weird if (target !== 'thumb') { const closestIndex = getClosestValueIndex(values, value) updateValues(value, closestIndex) } } } onSlideMove={disabled ? undefined : handleSlideMove} onHomeKeyDown={() => !disabled && updateValues(min, 0)} onEndKeyDown={() => !disabled && updateValues(max, values.length - 1)} onStepKeyDown={({ event, direction: stepDirection }) => { if (!disabled) { const isPageKey = PAGE_KEYS.includes(event.key) const isSkipKey = isPageKey || (event.shiftKey && ARROW_KEYS.includes(event.key)) const multiplier = isSkipKey ? 10 : 1 const atIndex = valueIndexToChangeRef.current const value = values[atIndex] const stepInDirection = step * multiplier * stepDirection updateValues(value + stepInDirection, atIndex) } }} /> {/* {isFormControl && values.map((value, index) => ( <BubbleInput key={index} name={name ? name + (values.length > 1 ? '[]' : '') : undefined} value={value} /> ))} */} </SliderProvider> ) }), { Track: SliderTrack, TrackActive: SliderTrackActive, Thumb: SliderThumb, } ) Slider.displayName = SLIDER_NAME /* -----------------------------------------------------------------------------------------------*/ // TODO // const BubbleInput = (props: any) => { // const { value, ...inputProps } = props // const ref = React.useRef<HTMLInputElement>(null) // const prevValue = usePrevious(value) // // Bubble value change to parents (e.g form change event) // React.useEffect(() => { // const input = ref.current! // const inputProto = window.HTMLInputElement.prototype // const descriptor = Object.getOwnPropertyDescriptor(inputProto, 'value') as PropertyDescriptor // const setValue = descriptor.set // if (prevValue !== value && setValue) { // const event = new Event('input', { bubbles: true }) // setValue.call(input, value) // input.dispatchEvent(event) // } // }, [prevValue, value]) // /** // * We purposefully do not use `type="hidden"` here otherwise forms that // * wrap it will not be able to access its value via the FormData API. // * // * We purposefully do not add the `value` attribute here to allow the value // * to be set programatically and bubble to any parent form `onChange` event. // * Adding the `value` will cause React to consider the programatic // * dispatch a duplicate and it will get swallowed. // */ // return <input style={{ display: 'none' }} {...inputProps} ref={ref} defaultValue={value} /> // } /* -----------------------------------------------------------------------------------------------*/ const Track = SliderTrack const Range = SliderTrackActive const Thumb = SliderThumb export { Slider, SliderTrack, SliderTrackActive, SliderThumb, // Track, Range, Thumb, } export type { SliderProps, SliderTrackProps, SliderTrackActiveProps, SliderThumbProps }
the_stack
import bodyParser from "body-parser"; import express, { Express, NextFunction, Request, Response } from "express"; import path from "path"; import cookieSession from "cookie-session"; import csrf from "csurf"; import * as Sentry from "@sentry/node"; import GithubOAuth from "./github-oauth"; import getGitHubSetup from "./get-github-setup"; import postGitHubSetup from "./post-github-setup"; import getGitHubConfiguration from "./get-github-configuration"; import postGitHubConfiguration from "./post-github-configuration"; import getGitHubSubscriptions from "./get-github-subscriptions"; import deleteGitHubSubscription from "./delete-github-subscription"; import getJiraConfiguration from "./get-jira-configuration"; import deleteJiraConfiguration from "./delete-jira-configuration"; import getGithubClientMiddleware from "./github-client-middleware"; import getJiraConnect, { postInstallUrl } from "../jira/connect"; import postJiraInstall from "../jira/install"; import postJiraUninstall from "../jira/uninstall"; import extractInstallationFromJiraCallback from "../jira/extract-installation-from-jira-callback"; import retrySync from "./retry-sync"; import getMaintenance from "./get-maintenance"; import api from "../api"; import healthcheck from "./healthcheck"; import version from "./version"; import logMiddleware from "../middleware/frontend-log-middleware"; import { App } from "@octokit/app"; import statsd from "../config/statsd"; import envVars from "../config/env"; import { metricError } from "../config/metric-names"; import { authenticateInstallCallback, authenticateUninstallCallback, verifyJiraContextJwtTokenMiddleware, verifyJiraJwtTokenMiddleware } from "./verify-jira-jwt-middleware"; import { booleanFlag, BooleanFlags } from "../config/feature-flags"; import { isNodeProd, isNodeTest } from "../util/isNodeEnv"; import { registerHandlebarsPartials } from "../util/handlebars/partials"; import { registerHandlebarsHelpers } from "../util/handlebars/helpers"; import { Errors } from "../config/errors"; import cookieParser from "cookie-parser"; // Adding session information to request declare global { // eslint-disable-next-line @typescript-eslint/no-namespace namespace Express { interface Request { // eslint-disable-next-line @typescript-eslint/no-explicit-any body?: Record<string, any>; session: { jiraHost?: string; githubToken?: string; }; } } } const throwError = (msg: string) => { throw new Error(msg); }; const oauth = GithubOAuth({ githubClient: process.env.GITHUB_CLIENT_ID || throwError("Missing GITHUB_CLIENT_ID"), githubSecret: process.env.GITHUB_CLIENT_SECRET || throwError("Missing GITHUB_CLIENT_SECRET"), baseURL: process.env.APP_URL || throwError("Missing APP_URL"), loginURI: "/github/login", callbackURI: "/github/callback" }); // setup route middlewares const csrfProtection = csrf( isNodeTest() ? { ignoreMethods: ["GET", "HEAD", "OPTIONS", "POST", "PUT"] } : undefined ); export default (octokitApp: App): Express => { const githubClientMiddleware = getGithubClientMiddleware(octokitApp); const app = express(); const rootPath = path.resolve(__dirname, "..", ".."); // The request handler must be the first middleware on the app app.use(Sentry.Handlers.requestHandler()); // Parse URL-encoded bodies for Jira configuration requests app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(cookieParser()); // We run behind ngrok.io so we need to trust the proxy always // TODO: look into the security of this. Maybe should only be done for local dev? app.set("trust proxy", true); app.use( cookieSession({ keys: [process.env.GITHUB_CLIENT_SECRET || throwError("Missing GITHUB_CLIENT_SECRET")], maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days signed: true, sameSite: "none", secure: true, httpOnly: false }) ); app.use(logMiddleware); app.set("view engine", "hbs"); app.set("views", path.join(rootPath, "views")); registerHandlebarsPartials(rootPath); registerHandlebarsHelpers(); app.use("/public", express.static(path.join(rootPath, "static"))); app.use( "/public/css-reset", express.static( path.join(rootPath, "node_modules/@atlaskit/css-reset/dist") ) ); app.use( "/public/primer", express.static(path.join(rootPath, "node_modules/primer/build")) ); app.use( "/public/atlassian-ui-kit", express.static( path.join(rootPath, "node_modules/@atlaskit/reduced-ui-pack/dist") ) ); app.use( "/public/aui", express.static( path.join(rootPath, "node_modules/@atlassian/aui/dist/aui") ) ); app.get(["/session", "/session/*"], (req: Request, res: Response, next: NextFunction) => { if (!req.params[0]) { return next(new Error("Missing redirect url for session. Needs to be in format `/session/:redirectUrl`")); } return res.render("session.hbs", { title: "Logging you into GitHub", APP_URL: process.env.APP_URL, redirectUrl: new URL(req.params[0], process.env.APP_URL).href, nonce: res.locals.nonce }); }); // Saves the jiraHost cookie to the secure session if available app.use((req: Request, res: Response, next: NextFunction) => { if (req.cookies.jiraHost) { // Save jirahost to secure session req.session.jiraHost = req.cookies.jiraHost; // delete jirahost from cookies. res.clearCookie("jiraHost"); } if (req.path == postInstallUrl && req.method == "GET") { // Only save xdm_e query when on the GET post install url (iframe url) res.locals.jiraHost = req.query.xdm_e as string; } else if ((req.path == postInstallUrl && req.method != "GET") || req.path == "/jira/sync") { // Only save the jiraHost from the body for specific routes that use it res.locals.jiraHost = req.body?.jiraHost; } else { // Save jiraHost from session for any other URLs res.locals.jiraHost = req.session.jiraHost; } next(); }); app.use(githubClientMiddleware); app.use("/", healthcheck); app.use("/api", api); // Add oauth routes app.use("/", oauth.router); // Atlassian Marketplace Connect app.get("/jira/atlassian-connect.json", getJiraConnect); // Maintenance mode view app.use(async (req: Request, res: Response, next: NextFunction) => { if (await booleanFlag(BooleanFlags.MAINTENANCE_MODE, false, res.locals.jiraHost)) { return getMaintenance(req, res); } next(); }); app.get("/version", version); app.get("/maintenance", csrfProtection, getMaintenance); app.get( "/github/setup", csrfProtection, getGitHubSetup ); app.post( "/github/setup", csrfProtection, postGitHubSetup ); app.get( "/github/configuration", csrfProtection, oauth.checkGithubAuth, getGitHubConfiguration ); app.post( "/github/configuration", csrfProtection, oauth.checkGithubAuth, postGitHubConfiguration ); app.get( "/github/subscriptions/:installationId", csrfProtection, getGitHubSubscriptions ); app.post( "/github/subscription", csrfProtection, oauth.checkGithubAuth, deleteGitHubSubscription ); app.get( "/jira/configuration", csrfProtection, verifyJiraJwtTokenMiddleware, getJiraConfiguration ); app.delete( "/jira/configuration", verifyJiraContextJwtTokenMiddleware, deleteJiraConfiguration ); app.post("/jira/sync", verifyJiraContextJwtTokenMiddleware, retrySync); // Set up event handlers // TODO: remove enabled and disabled events once the descriptor is updated in marketplace app.post("/jira/events/disabled", (_: Request, res: Response) => { return res.sendStatus(204); }); app.post("/jira/events/enabled", (_: Request, res: Response) => { return res.sendStatus(204); }); app.post("/jira/events/installed", authenticateInstallCallback, postJiraInstall); app.post("/jira/events/uninstalled", authenticateUninstallCallback, extractInstallationFromJiraCallback, postJiraUninstall); app.get("/", async (_: Request, res: Response) => { const { data: info } = await res.locals.client.apps.getAuthenticated({}); return res.redirect(info.external_url); }); // Add Sentry Context app.use((err: Error, req: Request, res: Response, next: NextFunction) => { Sentry.withScope((scope: Sentry.Scope): void => { const jiraHost = res.locals.jiraHost; if (jiraHost) { scope.setTag("jiraHost", jiraHost); } if (req.body) { Sentry.setExtra("Body", req.body); } next(err); }); }); // Error endpoints to test out different error pages app.get(["/error", "/error/:message", "/error/:message/:name"], (req: Request, res: Response, next: NextFunction) => { res.locals.showError = true; const error = new Error(req.params.message); if(req.params.name) { error.name = req.params.name } next(error); }); // The error handler must come after controllers and before other error middleware app.use(Sentry.Handlers.errorHandler()); // Error catcher - Batter up! app.use(async (err: Error, req: Request, res: Response, next: NextFunction) => { req.log.error({ payload: req.body, err, req, res }, "Error in frontend app."); if (!isNodeProd() && !res.locals.showError) { return next(err); } // Check for IP Allowlist error from Github and set the message explicitly // to be shown to the user in the error page if (err.name == "HttpError" && err.message?.includes("organization has an IP allow list enabled")) { err.message = Errors.IP_ALLOWLIST_MISCONFIGURED; } // TODO: move this somewhere else, enum? const errorCodes = { Unauthorized: 401, Forbidden: 403, "Not Found": 404 }; const messages = { [Errors.MISSING_JIRA_HOST]: "Session information missing - please enable all cookies in your browser settings.", [Errors.IP_ALLOWLIST_MISCONFIGURED]: `The GitHub org you are trying to connect is currently blocking our requests. To configure the GitHub IP Allow List correctly, <a href="${envVars.GITHUB_REPO_URL}/blob/main/docs/ip-allowlist.md">please follow these instructions</a>.` }; const errorStatusCode = errorCodes[err.message] || 500; const message = messages[err.message]; const tags = [`status: ${errorStatusCode}`]; statsd.increment(metricError.githubErrorRendered, tags); return res.status(errorStatusCode).render("error.hbs", { title: "GitHub + Jira integration", message, nonce: res.locals.nonce, githubRepoUrl: envVars.GITHUB_REPO_URL }); }); return app; };
the_stack
import * as ts from 'typescript'; import * as Lint from 'tslint'; import * as tsutils from 'tsutils'; import { AstUtils } from './utils/AstUtils'; import { Scope } from './utils/Scope'; import { Utils } from './utils/Utils'; import { ExtendedMetadata } from './utils/ExtendedMetadata'; import { isObject } from './utils/TypeGuard'; const FAILURE_ANONYMOUS_LISTENER: string = 'A new instance of an anonymous method is passed as a JSX attribute: '; const FAILURE_DOUBLE_BIND: string = "A function is having its 'this' reference bound twice in the constructor: "; const FAILURE_UNBOUND_LISTENER: string = "A class method is passed as a JSX attribute without having the 'this' reference bound: "; interface Options { allowAnonymousListeners: boolean; allowedDecorators: Set<string>; } export class Rule extends Lint.Rules.AbstractRule { public static metadata: ExtendedMetadata = { ruleName: 'react-this-binding-issue', type: 'maintainability', description: 'When using React components you must be careful to correctly bind the `this` reference ' + 'on any methods that you pass off to child components as callbacks.', options: { type: 'object', properties: { 'allow-anonymous-listeners': { type: 'boolean' }, 'bind-decorators': { type: 'list', listType: { anyOf: { type: 'string' } } } } }, optionExamples: [true, [true, { 'bind-decorators': ['autobind'] }]], optionsDescription: '', typescriptOnly: true, issueClass: 'Non-SDL', issueType: 'Error', severity: 'Critical', level: 'Opportunity for Excellence', group: 'Correctness' }; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { if (sourceFile.languageVariant === ts.LanguageVariant.JSX) { return this.applyWithFunction(sourceFile, walk, this.parseOptions(this.getOptions())); } return []; } private parseOptions(options: Lint.IOptions): Options { const parsed: Options = { allowAnonymousListeners: false, allowedDecorators: new Set<string>() }; options.ruleArguments.forEach((opt: unknown) => { if (isObject(opt)) { parsed.allowAnonymousListeners = opt['allow-anonymous-listeners'] === true; if (opt['bind-decorators']) { const allowedDecorators: unknown = opt['bind-decorators']; if (!Array.isArray(allowedDecorators) || allowedDecorators.some(decorator => typeof decorator !== 'string')) { throw new Error('one or more members of bind-decorators is invalid, string required.'); } // tslint:disable-next-line:prefer-type-cast parsed.allowedDecorators = new Set<string>(allowedDecorators); } } }); return parsed; } } function walk(ctx: Lint.WalkContext<Options>) { let boundListeners: Set<string> = new Set<string>(); let declaredMethods: Set<string> = new Set<string>(); let scope: Scope | undefined; function isMethodBoundWithDecorators(node: ts.MethodDeclaration, allowedDecorators: Set<string>): boolean { if (!(allowedDecorators.size > 0 && node.decorators && node.decorators.length > 0)) { return false; } return node.decorators.some(decorator => { if (decorator.kind !== ts.SyntaxKind.Decorator) { return false; } const source = node.getSourceFile(); const text = decorator.expression.getText(source); return ctx.options.allowedDecorators.has(text); }); } function isAttributeAnonymousFunction(attributeLikeElement: ts.JsxAttribute | ts.JsxSpreadAttribute): boolean { if (ctx.options.allowAnonymousListeners) { return false; } if (attributeLikeElement.kind === ts.SyntaxKind.JsxAttribute) { const attribute: ts.JsxAttribute = <ts.JsxAttribute>attributeLikeElement; if (attribute.initializer !== undefined && attribute.initializer.kind === ts.SyntaxKind.JsxExpression) { return isExpressionAnonymousFunction(attribute.initializer.expression); } } return false; } function isExpressionAnonymousFunction(expression: ts.Expression | undefined): boolean { if (expression === undefined) { return false; } // Arrow functions and Function expressions create new anonymous function instances if (expression.kind === ts.SyntaxKind.ArrowFunction || expression.kind === ts.SyntaxKind.FunctionExpression) { return true; } if (expression.kind === ts.SyntaxKind.CallExpression) { const callExpression = <ts.CallExpression>expression; const functionName = AstUtils.getFunctionName(callExpression); if (functionName === 'bind') { return true; // bind functions on Function or _ create a new anonymous instance of a function } } if (expression.kind === ts.SyntaxKind.Identifier && scope !== undefined) { const symbolText: string = expression.getText(); return scope.isFunctionSymbol(symbolText); } return false; } function isUnboundListener(attributeLikeElement: ts.JsxAttribute | ts.JsxSpreadAttribute): boolean { if (attributeLikeElement.kind === ts.SyntaxKind.JsxAttribute) { const attribute: ts.JsxAttribute = <ts.JsxAttribute>attributeLikeElement; if (attribute.initializer !== undefined && attribute.initializer.kind === ts.SyntaxKind.JsxExpression) { const jsxExpression = attribute.initializer; if (jsxExpression.expression !== undefined && jsxExpression.expression.kind === ts.SyntaxKind.PropertyAccessExpression) { const propAccess: ts.PropertyAccessExpression = <ts.PropertyAccessExpression>jsxExpression.expression; if (propAccess.expression.getText() === 'this') { const listenerText: string = propAccess.getText(); // an unbound listener is a class method reference that was not bound to 'this' in the constructor if (declaredMethods.has(listenerText) && !boundListeners.has(listenerText)) { return true; } } } } } return false; } function getSelfBoundListeners(node: ts.ConstructorDeclaration): Set<string> { const result: Set<string> = new Set<string>(); if (node.body !== undefined && node.body.statements !== undefined) { node.body.statements.forEach( (statement: ts.Statement): void => { if (statement.kind === ts.SyntaxKind.ExpressionStatement) { const expressionStatement = <ts.ExpressionStatement>statement; const expression = expressionStatement.expression; if (expression.kind === ts.SyntaxKind.BinaryExpression) { const binaryExpression: ts.BinaryExpression = <ts.BinaryExpression>expression; const operator: ts.Node = binaryExpression.operatorToken; if (operator.kind === ts.SyntaxKind.EqualsToken) { if (binaryExpression.left.kind === ts.SyntaxKind.PropertyAccessExpression) { const leftPropText: string = binaryExpression.left.getText(); if (binaryExpression.right.kind === ts.SyntaxKind.CallExpression) { const callExpression = <ts.CallExpression>binaryExpression.right; if ( AstUtils.getFunctionName(callExpression) === 'bind' && callExpression.arguments !== undefined && callExpression.arguments.length === 1 && callExpression.arguments[0].getText() === 'this' ) { const rightPropText = AstUtils.getFunctionTarget(callExpression); if (leftPropText === rightPropText) { if (result.has(rightPropText)) { const start = binaryExpression.getStart(); const width = binaryExpression.getWidth(); const msg = FAILURE_DOUBLE_BIND + binaryExpression.getText(); ctx.addFailureAt(start, width, msg); } result.add(rightPropText); } } } } } } } } ); } return result; } function visitJsxOpeningElement(node: ts.JsxOpeningLikeElement): void { // create violations if the listener is a reference to a class method that was not bound to 'this' in the constructor node.attributes.properties.forEach( (attributeLikeElement: ts.JsxAttribute | ts.JsxSpreadAttribute): void => { if (isUnboundListener(attributeLikeElement)) { const attribute: ts.JsxAttribute = <ts.JsxAttribute>attributeLikeElement; const jsxExpression = attribute.initializer; if (jsxExpression === undefined || jsxExpression.kind === ts.SyntaxKind.StringLiteral) { return; } const propAccess: ts.PropertyAccessExpression = <ts.PropertyAccessExpression>jsxExpression.expression; const listenerText: string = propAccess.getText(); if (declaredMethods.has(listenerText) && !boundListeners.has(listenerText)) { const start: number = propAccess.getStart(); const widget: number = propAccess.getWidth(); const message: string = FAILURE_UNBOUND_LISTENER + listenerText; ctx.addFailureAt(start, widget, message); } } else if (isAttributeAnonymousFunction(attributeLikeElement)) { const attribute: ts.JsxAttribute = <ts.JsxAttribute>attributeLikeElement; const jsxExpression = attribute.initializer; if (jsxExpression === undefined || jsxExpression.kind === ts.SyntaxKind.StringLiteral) { return; } const expression = jsxExpression.expression; if (expression === undefined) { return; } const start: number = expression.getStart(); const widget: number = expression.getWidth(); const message: string = FAILURE_ANONYMOUS_LISTENER + Utils.trimTo(expression.getText(), 30); ctx.addFailureAt(start, widget, message); } } ); } function visitClassMember(node: ts.Node) { if (tsutils.isConstructorDeclaration(node)) { boundListeners = getSelfBoundListeners(node); } else if (tsutils.isMethodDeclaration(node)) { if (isMethodBoundWithDecorators(node, ctx.options.allowedDecorators)) { boundListeners = boundListeners.add('this.' + node.name.getText()); } } } function cb(node: ts.Node): void { if (tsutils.isMethodDeclaration(node)) { // reset variable scope when we encounter a method. Start tracking variables that are instantiated // in scope so we can make sure new function instances are not passed as JSX attributes scope = new Scope(undefined); ts.forEachChild(node, cb); scope = undefined; return; } if (tsutils.isArrowFunction(node)) { if (scope !== undefined) { scope = new Scope(scope); } ts.forEachChild(node, cb); if (scope !== undefined) { scope = scope.parent; } return; } if (tsutils.isFunctionExpression(node)) { if (scope !== undefined) { scope = new Scope(scope); } ts.forEachChild(node, cb); if (scope !== undefined) { scope = scope.parent; } return; } if (tsutils.isClassDeclaration(node)) { // reset all state when a class declaration is found because a SourceFile can contain multiple classes boundListeners = new Set<string>(); // find all method names and prepend 'this.' to it so we can compare array elements to method names easily declaredMethods = new Set<string>(); AstUtils.getDeclaredMethodNames(node).forEach( (methodName: string): void => { declaredMethods.add('this.' + methodName); } ); node.members.forEach(visitClassMember); } else if (tsutils.isJsxElement(node)) { visitJsxOpeningElement(node.openingElement); // a normal JSX element has-a OpeningElement } else if (tsutils.isJsxSelfClosingElement(node)) { visitJsxOpeningElement(node); // a self closing JSX element is-a OpeningElement } else if (tsutils.isVariableDeclaration(node)) { if (scope !== undefined) { if (node.name.kind === ts.SyntaxKind.Identifier) { const variableName = (<ts.Identifier>node.name).text; if (isExpressionAnonymousFunction(node.initializer)) { scope.addFunctionSymbol(variableName); } } } } return ts.forEachChild(node, cb); } return ts.forEachChild(ctx.sourceFile, cb); }
the_stack
import { ClientWorker, ServerListManager, Snapshot } from '../src'; import * as fs from 'fs'; import * as path from 'path'; import { HttpAgent } from '../src/http_agent'; import { createDefaultConfiguration } from './utils'; import * as mm from 'mm'; import * as assert from 'assert'; const pedding = require('pedding'); const httpclient = require('urllib'); const { rimraf, sleep } = require('mz-modules'); const cacheDir = path.join(__dirname, '.cache'); function getClient(configuration) { return new ClientWorker({ configuration }); } describe('test/client_worker.test.ts', () => { describe('test features in direct mode', () => { const defaultOptions = { serverAddr: '106.14.43.196:8848', namespace: '', cacheDir }; const configuration = createDefaultConfiguration(defaultOptions); const snapshot = new Snapshot({ configuration }); const serverMgr = new ServerListManager({ configuration }); const httpAgent = new HttpAgent({ configuration }); configuration.merge({ snapshot, serverMgr, httpAgent, }); let client: ClientWorker; before(async () => { client = getClient(configuration); await client.publishSingle('com.taobao.hsf.redis', 'DEFAULT_GROUP', '10.123.32.1:8080'); await sleep(1000); await client.ready(); }); afterEach(mm.restore); after(async () => { client.close(); await client.remove('com.taobao.hsf.redis', 'DEFAULT_GROUP'); await client.remove('test-dataId-encoding', 'test-group'); await rimraf(cacheDir); }); it('should subscribe mutli times ok', async () => { const reg = { dataId: 'com.taobao.hsf.redis', group: 'DEFAULT_GROUP', }; client.subscribe(reg, val => { client.emit('redis_address_1', val); }); let val = await client.await('redis_address_1'); assert(val && /^\d+\.\d+\.\d+\.\d+\:\d+$/.test(val)); client.subscribe(reg, val => { client.emit('redis_address_2', val); }); val = await client.await('redis_address_2'); assert(val && /^\d+\.\d+\.\d+\.\d+\:\d+$/.test(val)); client.unSubscribe(reg); }); it('should getConfig from nacos server', async () => { const content = await client.getConfig('com.taobao.hsf.redis', 'DEFAULT_GROUP'); assert(/^\d+\.\d+\.\d+\.\d+\:\d+$/.test(content)); }); it('should not emit duplicate', async () => { let count = 0; const client = getClient(configuration); await client.ready(); client.subscribe({ dataId: 'com.ali.unit.routerule', group: 'DEFAULT_GROUP' }, () => count++); client.subscribe({ dataId: 'com.ali.unit.forbiddenuserrule', group: 'DEFAULT_GROUP' }, () => count++); client.subscribe({ dataId: 'com.ali.unit.apprule', group: 'DEFAULT_GROUP' }, () => count++); client.subscribe({ dataId: 'tangram_page_publish', group: 'tangram' }, () => count++); await sleep(5000); assert(count === 4); client.close(); }); it('should ready', done => { done = pedding(3, done); client.ready(done); client.ready(done); client.ready(() => { client.ready(done); }); }); it('should subscribe a not exists config', done => { client.subscribe({ dataId: 'config-not-exists', group: 'DEFAULT_GROUP', }, content => { assert(!content); client.unSubscribe({ dataId: 'config-not-exists', group: 'DEFAULT_GROUP', }); done(); }); }); it('should getConfig from nacos server before init', async () => { const client = getClient(configuration); await client.publishSingle('com.taobao.hsf.redis', 'testGroup', '10.123.32.1:8080'); await sleep(1000); const content = await client.getConfig('com.taobao.hsf.redis', 'testGroup'); assert(/^\d+\.\d+\.\d+\.\d+\:\d+$/.test(content)); await client.remove('com.taobao.hsf.redis', 'testGroup'); client.close(); }); it('should publishSingle ok', async () => { let isSuccess = await client.publishSingle('test-dataId', 'test-group', 'test-content'); assert(isSuccess); let content = await client.getConfig('test-dataId', 'test-group'); assert(content === 'test-content'); isSuccess = await client.publishSingle('test-dataId-unicode', 'test-group', 'tj'); assert(isSuccess); content = await client.getConfig('test-dataId-unicode', 'test-group'); assert(content === 'tj'); }); it('should test publish encoding content', async () => { await client.publishSingle('test-dataId-encoding', 'test-group', '你好'); let data = ''; client.subscribe({ dataId: 'test-dataId-encoding', group: 'test-group', }, (content) => { data = content; }); await sleep(1000); await client.publishSingle('test-dataId-encoding', 'test-group', '你好啊'); await sleep(30000); assert(data === '你好啊'); }); it('should remove config from nacos server', async () => { const dataId = 'test-dataId2-' + process.pid + '-' + Date.now(); let isSuccess = await client.publishSingle(dataId, 'test-group', 'test-content'); assert(isSuccess === true); await sleep(2000); let content = await client.getConfig(dataId, 'test-group'); assert(content === 'test-content'); isSuccess = await client.remove(dataId, 'test-group'); assert(isSuccess === true); await sleep(1000); content = await client.getConfig('test-dataId2', 'test-group'); assert(content == null); }); }); describe('test features in find address mode', () => { const defaultOptions = { appName: 'test', endpoint: 'acm.aliyun.com', namespace: '81597370-5076-4216-9df5-538a2b55bac3', accessKey: '4c796a4dcd0d4f5895d4ba83a296b489', secretKey: 'UjLemP8inirhjMg1NZyY0faOk1E=', httpclient, ssl: false }; const configuration = createDefaultConfiguration(defaultOptions); const snapshot = new Snapshot({ configuration }); const serverMgr = new ServerListManager({ configuration }); const httpAgent = new HttpAgent({ configuration }); configuration.merge({ snapshot, serverMgr, httpAgent, }); let client: ClientWorker; before(async () => { client = getClient(configuration); await client.publishSingle('com.taobao.hsf.redis', 'DEFAULT_GROUP', '10.123.32.1:8080'); await sleep(1000); await client.ready(); }); afterEach(mm.restore); after(async () => { client.close(); await client.remove('com.taobao.hsf.redis', 'DEFAULT_GROUP'); await rimraf(cacheDir); }); it('should getConfig from nacos server', async () => { const content = await client.getConfig('com.taobao.hsf.redis', 'DEFAULT_GROUP'); assert(/^\d+\.\d+\.\d+\.\d+\:\d+$/.test(content)); }); it('should subscribe a not exists config', done => { client.subscribe({ dataId: 'config-not-exists', group: 'DEFAULT_GROUP', }, content => { assert(!content); client.unSubscribe({ dataId: 'config-not-exists', group: 'DEFAULT_GROUP', }); done(); }); }); it('should getConfig from nacos server before init', async () => { const client = getClient(configuration); await client.publishSingle('com.taobao.hsf.redis', 'testGroup', '10.123.32.1:8080'); await sleep(1000); const content = await client.getConfig('com.taobao.hsf.redis', 'testGroup'); assert(/^\d+\.\d+\.\d+\.\d+\:\d+$/.test(content)); await client.remove('com.taobao.hsf.redis', 'testGroup'); client.close(); }); it('should publishSingle ok', async () => { let isSuccess = await client.publishSingle('test-dataId', 'test-group', 'test-content'); assert(isSuccess); let content = await client.getConfig('test-dataId', 'test-group'); assert(content === 'test-content'); isSuccess = await client.publishSingle('test-dataId-unicode', 'test-group', 'tj'); assert(isSuccess); content = await client.getConfig('test-dataId-unicode', 'test-group'); assert(content === 'tj'); }); it('should remove config from nacos server', async () => { const dataId = 'test-dataId2-' + process.pid + '-' + Date.now(); let isSuccess = await client.publishSingle(dataId, 'test-group', 'test-content'); assert(isSuccess === true); await sleep(2000); let content = await client.getConfig(dataId, 'test-group'); assert(content === 'test-content'); isSuccess = await client.remove(dataId, 'test-group'); assert(isSuccess === true); await sleep(1000); content = await client.getConfig('test-dataId2', 'test-group'); assert(content == null); }); xit('should publishAggr & removeAggr ok', async () => { let isSuccess = await client.publishAggr('NS_DIAMOND_SUBSCRIPTION_TOPIC_chenwztest', 'DEFAULT_GROUP', 'somebody-pub-test', 'xx xx'); assert(isSuccess === true); await sleep(1000); let content = await client.getConfig('NS_DIAMOND_SUBSCRIPTION_TOPIC_chenwztest', 'DEFAULT_GROUP'); assert(content === 'xx xx'); isSuccess = await client.removeAggr('NS_DIAMOND_SUBSCRIPTION_TOPIC_chenwztest', 'DEFAULT_GROUP', 'somebody-pub-test2'); assert(isSuccess === true); isSuccess = await client.publishAggr('NS_DIAMOND_SUBSCRIPTION_TOPIC_unicode', 'DEFAULT_GROUP', 'somebody-pub-test', '宗羽'); assert(isSuccess === true); content = await client.getConfig('NS_DIAMOND_SUBSCRIPTION_TOPIC_unicode', 'DEFAULT_GROUP'); assert(content === '宗羽'); }); xit('should batchGetConfig and save snapshot ok', async () => { let isSuccess = await client.publishSingle('test-dataId3', 'test-group', 'test-content'); assert(isSuccess === true); isSuccess = await client.publishSingle('test-dataId4', 'test-group', 'test-content'); assert(isSuccess === true); const content = await client.batchGetConfig([ 'test-dataId3', 'test-dataId4' ], 'test-group'); assert(content && content.length === 2); assert(content[ 0 ].dataId === 'test-dataId3'); assert(content[ 0 ].content === 'test-content'); assert(content[ 1 ].dataId === 'test-dataId4'); assert(content[ 1 ].content === 'test-content'); const cacheDir = client.snapshot.cacheDir; content.forEach(config => { const file = path.join(cacheDir, 'snapshot', 'config', 'CURRENT_UNIT', defaultOptions.namespace, config.group, config.dataId); assert(fs.readFileSync(file, 'utf8') === config.content); }); }); xit('should batchQuery ok', async () => { const content = await client.batchQuery([ 'test-dataId3', 'test-dataId4' ], 'test-group'); assert(content && content.length === 2); assert(content[ 0 ].dataId === 'test-dataId3'); assert(content[ 0 ].content === 'test-content'); assert(content[ 1 ].dataId === 'test-dataId4'); assert(content[ 1 ].content === 'test-content'); }); describe('mock error', () => { before(async () => { client = getClient(configuration); await client.ready(); }); afterEach(mm.restore); after(async () => { client.close(); await rimraf(cacheDir); }); beforeEach(() => { client.clearSubscriptions(); }); it('should remove failed', async () => { mm.http.requestError(/^\//, null, 'mock res error'); let error; try { await client.remove('intl-alipush-notify-subscribe-info', 'DEFAULT_GROUP'); throw new Error('should never exec'); } catch (err) { error = err; } assert(error); assert(/mock res error/.test(error.message)); }); xit('should get null when batchGetConfig failed', async () => { mm.http.requestError(/^\//, null, 'mock res error'); let error; try { await client.batchGetConfig([ 'test-dataId3', 'test-dataId4' ], 'test-group'); throw new Error('should never exec'); } catch (err) { error = err; } assert(error); assert(/mock res error/.test(error.message)); }); it('should init failed', (done) => { mm.empty(snapshot, 'get'); mm(serverMgr, 'serverListCache', new Map()); mm(serverMgr, 'currentServerAddrMap', new Map()); mm.http.request(/^\//, []); serverMgr.on('error', (error) => { assert(error && error.name === 'NacosServerHostEmptyError'); assert(error.unit === 'CURRENT_UNIT'); done(); }); client.getConfig('com.taobao.hsf.redis', 'HSF'); }); xit('should emit NacosBatchDeserializeError', async () => { mm.data(client, 'request', '{'); let error; try { await client.batchGetConfig([ 'com.taobao.hsf.redis' ], 'HSF'); } catch (err) { error = err; } assert(error && error.name === 'NacosBatchDeserializeError'); assert(error.data === '{'); }); xit('should emit NacosBatchDeserializeError', async () => { mm.data(client, 'request', '{'); let error; try { await client.batchQuery([ 'com.taobao.hsf.redis' ], 'HSF'); } catch (err) { error = err; } assert(error && error.name === 'NacosBatchDeserializeError'); assert(error.data === '{'); }); it('should emit NacosLongPullingError event', done => { mm.error(client, 'checkServerConfigInfo'); mm.empty(client.snapshot, 'get'); client.once('error', err => { assert(err.name === 'NacosLongPullingError'); assert(err.message === 'mm mock error'); client.unSubscribe({ dataId: 'com.taobao.hsf.redis', group: 'HSF', }); client.close(); done(); }); client.subscribe({ dataId: 'com.taobao.hsf.redis', group: 'HSF', }, content => console.log(content)); }); xit('should emit NacosSyncConfigError event', (done) => { // await client.updateCurrentServer(); const _request = httpAgent.request.bind(httpAgent); mm(serverMgr, 'serverListCache', new Map()); mm(serverMgr, 'currentServerAddrMap', new Map()); mm.empty(client.snapshot, 'get'); mm(httpAgent, 'request', async (path, options) => { if (options.method !== 'POST') { throw new Error('mm mock error'); } return await _request(path, options); }); done = pedding(done, 2); client.once('error', function (err) { assert(err.name === 'NacosSyncConfigError'); assert(err.message.indexOf('mm mock error') >= 0); assert(err.dataId === 'com.taobao.hsf.redis'); assert(err.group === 'HSF'); mm.restore(); // 恢复后自动重试 done(); }); client.subscribe({ dataId: 'com.taobao.hsf.redis', group: 'HSF', }, () => { client.unSubscribe({ dataId: 'com.taobao.hsf.redis', group: 'HSF', }); done(); }); }); it('should emit NacosConnectionTimeoutError syncConfigError event', done => { mm(httpAgent, 'requestTimeout', 1); client.once('error', function (err) { assert(err.name === 'NacosSyncConfigError'); assert(err.dataId === 'com.taobao.hsf.redis2'); client.unSubscribe({ dataId: 'com.taobao.hsf.redis2', group: 'HSF', }); assert(err.group === 'HSF'); done(); }); client.subscribe({ dataId: 'com.taobao.hsf.redis2', group: 'HSF', }, () => { throw new Error('should not run here'); }); }); it('should throw error if http status is 409', async () => { mm.data(httpAgent.httpclient, 'request', { status: 409 }); mm.empty(snapshot, 'get'); let error; try { await client.getConfig('com.taobao.hsf.redis', 'HSF'); } catch (err) { error = err; } assert(error && error.name === 'NacosServerConflictError'); }); }); describe('custom decode res data', () => { before(async () => { configuration.merge({ decodeRes(res) { if (/^\d+\.\d+\.\d+\.\d+\:\d+$/.test(res.data)) { return 'customDecode' + res.data } return res.data; }}); client = getClient(configuration); await client.publishSingle('com.taobao.hsf.redis', 'DEFAULT_GROUP', '10.123.32.1:8080'); await sleep(1000); await client.ready(); }); afterEach(mm.restore); after(async () => { client.close(); await client.remove('com.taobao.hsf.redis', 'DEFAULT_GROUP'); await rimraf(cacheDir); }); it('should be handled by decodeRes', async () => { const content = await client.getConfig('com.taobao.hsf.redis', 'DEFAULT_GROUP'); assert(/^customDecode\d+\.\d+\.\d+\.\d+\:\d+$/.test(content)); }); }) }); });
the_stack
import * as path from "path"; import { MessageItem } from "vscode"; import * as nls from "vscode-nls"; // Debugger Server export const SERVER_INFO = { DEFAULT_SERVER_PORT: 5577, ERROR_CODE_INIT_SERVER: "ERROR_INIT_SERVER", SERVER_PORT_CONFIGURATION: "deviceSimulatorExpress.debuggerServerPort", }; const localize: nls.LocalizeFunc = nls.config({ messageFormat: nls.MessageFormat.file, })(); export const CONFIG = { CONFIG_ENV_ON_SWITCH: "deviceSimulatorExpress.configNewEnvironmentUponSwitch", PYTHON_PATH: "python.pythonPath", SHOW_DEPENDENCY_INSTALL: "deviceSimulatorExpress.showDependencyInstall", SHOW_NEW_FILE_POPUP: "deviceSimulatorExpress.showNewFilePopup", }; export const CONSTANTS = { WEBVIEW_TYPE: { SIMULATOR: "simulator", TUTORIAL: "tutorial", }, DEBUG_CONFIGURATION_TYPE: "deviceSimulatorExpress", DEVICE_NAME: { CPX: "CPX", MICROBIT: "micro:bit", CLUE: "CLUE", }, DEVICE_NAME_FORMAL: { CPX: "Circuit Playground Express", MICROBIT: "micro:bit", CLUE: "CLUE", }, SCRIPT_PATH: { SIMULATOR: "out/simulator.js", VSCODE_API: "out/vscode_import.js", }, ERROR: { BAD_PYTHON_PATH: 'Your interpreter is not pointing to a valid Python executable. Please select a different interpreter (CTRL+SHIFT+P and type "python.selectInterpreter") and restart the application', COMPORT_UNKNOWN_ERROR: "Writing to COM port (GetOverlappedResult): Unknown error code 121", CPX_FILE_ERROR: localize( "error.cpxFileFormat", "The cpx.json file format is not correct." ), DEBUGGER_SERVER_INIT_FAILED: (port: number) => { return localize( "error.debuggerServerInitFailed", `Warning : The Debugger Server cannot be opened. Please try to free the port ${port} if it's already in use or select another one in your Settings 'Device Simulator Express: Debugger Server Port' and start another debug session.\n You can still debug your code but you won't be able to use the Simulator.` ); }, DEBUGGING_SESSION_IN_PROGESS: localize( "error.debuggingSessionInProgress", "[ERROR] A debugging session is currently in progress, please stop it before running your code. \n" ), DEPENDENCY_DOWNLOAD_ERROR: "Dependency download could not be completed. Functionality may be limited. Please review the installation docs.", FAILED_TO_OPEN_SERIAL_PORT: (port: string): string => { return localize( "error.failedToOpenSerialPort", `[ERROR] Failed to open serial port ${port}.` ); }, FAILED_TO_OPEN_SERIAL_PORT_DUE_TO: (port: string, error: any) => { return localize( "error.failedToOpenSerialPortDueTo", `[ERROR] Failed to open serial port ${port} due to error: ${error}. \n` ); }, INSTALLATION_ERROR: localize( "error.installationError", "Installation Error" ), INVALID_FILE_EXTENSION_DEBUG: localize( "error.invalidFileExtensionDebug", "The file you tried to run isn't a Python file." ), INVALID_PYTHON_PATH: localize( "error.invalidPythonPath", 'We found that your selected Python interpreter version is too low to run the extension. Please upgrade to version 3.7+ or select a different interpreter (CTRL+SHIFT+P and type "python.selectInterpreter") and restart the application.' ), LOW_PYTHON_VERSION_FOR_MICROBIT_DEPLOYMENT: localize( "error.lowPythonVersionForMicrobitDeployment", "To deploy your code to the micro:bit, you must be using Python 3.3+" ), NO_DEVICE: localize( "error.noDevice", "The device is not detected. Please double check if your board is connected and/or properly formatted" ), NO_FILE_TO_RUN: localize( "error.noFileToRun", '[ERROR] We can\'t find a Python file to run. Please make sure you select or open a new ".py" code file, or use the "New File" command to get started and see useful links.\n' ), NO_FILE_TO_DEPLOY: localize( "error.noFileToDeploy", "[ERROR] We can't find a Python file to deploy to your device.\n" ), NO_FOLDER_OPENED: localize( "error.noFolderCreated", "In order to use the Serial Monitor, you need to open a folder and reload VS Code." ), NO_PROGRAM_FOUND_DEBUG: localize( "error.noProgramFoundDebug", "Cannot find a program to debug." ), NO_PYTHON_PATH: localize( "error.noPythonPath", "We found that you don't have Python 3 installed on your computer, please install the latest version, add it to your PATH and try again." ), RECONNECT_DEVICE: localize( "error.reconnectDevice", "Please disconnect your Circuit Playground Express and try again." ), STDERR: (data: string) => { return localize("error.stderr", `\n[ERROR] ${data} \n`); }, UNEXPECTED_MESSAGE: localize( "error.unexpectedMessage", "Webview sent an unexpected message" ), }, FILESYSTEM: { BASE_CIRCUITPYTHON: "base_circuitpython", CLUE: "clue", PYTHON_VENV_DIR: "venv", MICROPYTHON_DIRECTORY: "micropython", OUTPUT_DIRECTORY: "out", }, INFO: { ALREADY_SUCCESSFUL_INSTALL: localize( "info.successfulInstall", "Your current configuration is already successfully set up for the Device Simulator Expresss." ), ARE_YOU_SURE: localize( "info.areYouSure", "Are you sure you don't want to install the dependencies? The extension can't run without installing them." ), CLOSED_SERIAL_PORT: (port: string) => { return localize( "info.closedSerialPort", `[DONE] Closed the serial port - ${port} \n` ); }, COMPLETED_MESSAGE: "Completed", CPX_JSON_ALREADY_GENERATED: localize( "info.cpxJsonAlreadyGenerated", "cpx.json has already been generated." ), DEPLOY_DEVICE: localize( "info.deployDevice", "\n[INFO] Deploying code to the device...\n" ), DEPLOY_SIMULATOR: localize( "info.deploySimulator", "\n[INFO] Deploying code to the simulator...\n" ), DEPLOY_SUCCESS: localize( "info.deploySuccess", "\n[INFO] Code successfully copied! Your device should be loading and ready to go shortly.\n" ), EXTENSION_ACTIVATED: localize( "info.extensionActivated", "Congratulations, your extension Device Simulator Express is now active!" ), FILE_SELECTED: (filePath: string) => { return localize( "info.fileSelected", `[INFO] File selected : ${filePath} \n` ); }, FIRST_TIME_WEBVIEW: localize( "info.firstTimeWebview", 'To reopen the simulator select the command "Open Simulator" from command palette.' ), INSTALLING_PYTHON_VENV: localize( "info.installingPythonVenv", "A virtual environment is currently being created. The required Python packages will be installed. You will be prompted a message telling you when the installation is done." ), INSTALL_PYTHON_DEPS: localize( "info.installPythonDependencies", "Do you want us to try and install this extension's dependencies on your selected Python interpreter for you?" ), INSTALL_PYTHON_VENV: localize( "info.installPythonVenv", "Do you want us to try and install this extension's dependencies via virtual environment for you?" ), NEW_FILE: localize( "info.newFile", "New to Python or the Circuit Playground Express? We are here to help!" ), NO_DEVICE_CHOSEN_TO_DEPLOY_TO: localize( "info.noDeviceChosenToDeployTo", "\n[INFO] No device was selected to deploy to.\n" ), NO_DEVICE_CHOSEN_TO_SIMULATE_TO: localize( "info.noDeviceChosenToSimulateTo", "\n[INFO] No device was selected to simulate.\n" ), NO_DEVICE_CHOSEN_FOR_NEW_FILE: localize( "info.noDeviceChosenForNewFile", "\n[INFO] No device was selected to open a template file for.\n" ), OPENED_SERIAL_PORT: (port: string) => { return localize( "info.openedSerialPort", `[INFO] Opened the serial port - ${port} \n` ); }, OPENING_SERIAL_PORT: (port: string) => { return localize( "info.openingSerialPort", `[STARTING] Opening the serial port - ${port} \n` ); }, PLEASE_OPEN_FOLDER: localize( "info.pleaseOpenFolder", "Please open a folder first." ), REDIRECT: localize("info.redirect", "You are being redirected."), RUNNING_CODE: localize("info.runningCode", "Running user code"), SUCCESSFUL_INSTALL: localize( "info.successfulInstall", "Successfully set up the Python environment." ), THIRD_PARTY_WEBSITE_ADAFRUIT: localize( "info.thirdPartyWebsiteAdafruit", 'By clicking "Agree and Proceed" you will be redirected to adafruit.com, a third party website not managed by Microsoft. Please note that your activity on adafruit.com is subject to Adafruit\'s privacy policy' ), THIRD_PARTY_WEBSITE_PIP: localize( "info.thirdPartyWebsitePip", 'By clicking "Agree and Proceed" you will be redirected to pip.pypa.io, a third party website not managed by Microsoft. Please note that your activity on pip.pypa.io is subject to PyPA\'s privacy policy' ), THIRD_PARTY_WEBSITE_PYTHON: localize( "info.thirdPartyWebsitePython", 'By clicking "Agree and Proceed" you will be redirected to python.org, a third party website not managed by Microsoft. Please note that your activity on python.org is subject to Python\'s privacy policy' ), UPDATED_TO_EXTENSION_VENV: localize( "info.updatedToExtensionsVenv", "Automatically updated interpreter to point to extension's virtual environment." ), WELCOME_OUTPUT_TAB: localize( "info.welcomeOutputTab", "Welcome to the Device Simulator Express output tab!\n\n" ), }, LABEL: { WEBVIEW_PANEL: localize( "label.webviewPanel", "Device Simulator Express" ), }, LINKS: { DOWNLOAD_PIP: "https://pip.pypa.io/en/stable/installing/", DOWNLOAD_PYTHON: "https://www.python.org/downloads/", EXAMPLE_CODE: "https://github.com/adafruit/Adafruit_CircuitPython_CircuitPlayground/tree/master/examples", CPX_HELP: "https://learn.adafruit.com/adafruit-circuit-playground-express/circuitpython-quickstart", CLUE_HELP: "https://learn.adafruit.com/adafruit-clue/circuitpython", INSTALL: "https://github.com/microsoft/vscode-python-devicesimulator/blob/dev/docs/install.md", PRIVACY: "https://www.adafruit.com/privacy", TUTORIALS: "https://learn.adafruit.com/circuitpython-made-easy-on-circuit-playground-express/circuit-playground-express-library", }, MISC: { SELECT_PORT_PLACEHOLDER: localize( "misc.selectPortPlaceholder", "Select a serial port" ), SERIAL_MONITOR_NAME: localize( "misc.serialMonitorName", "Device Simulator Express Serial Monitor" ), SERIAL_MONITOR_TEST_IF_OPEN: localize( "misc.testIfPortOpen", "Test if serial port is open" ), }, NAME: localize("name", "Device Simulator Express"), TEMPLATE: { CPX: "cpx_template.py", MICROBIT: "microbit_template.py", CLUE: "clue_template.py", }, WARNING: { ACCEPT_AND_RUN: localize( "warning.agreeAndRun", "By selecting ‘Agree and Run’, you understand the extension executes Python code on your local computer, which may be a potential security risk." ), INVALID_BAUD_RATE: localize( "warning.invalidBaudRate", "Invalid baud rate, keep baud rate unchanged." ), NO_RATE_SELECTED: localize( "warning.noRateSelected", "No rate is selected, keep baud rate unchanged." ), NO_SERIAL_PORT_SELECTED: localize( "warning.noSerialPortSelected", "No serial port was selected, please select a serial port first" ), SERIAL_MONITOR_ALREADY_OPENED: (port: string) => { return localize( "warning.serialMonitorAlreadyOpened", `Serial monitor is already opened for ${port} \n` ); }, SERIAL_MONITOR_NOT_STARTED: localize( "warning.serialMonitorNotStarted", "Serial monitor has not been started." ), SERIAL_PORT_NOT_STARTED: localize( "warning.serialPortNotStarted", "Serial port has not been started.\n" ), }, }; export enum CONFIG_KEYS { ENABLE_USB_DETECTION = "deviceSimulatorExpress.enableUSBDetection", } export enum TelemetryEventName { FAILED_TO_OPEN_SIMULATOR = "SIMULATOR.FAILED_TO_OPEN", // Debugger CPX_DEBUGGER_INIT_SUCCESS = "CPX.DEBUGGER.INIT.SUCCESS", CPX_DEBUGGER_INIT_FAIL = "CPX.DEBUGGER.INIT.FAIL", MICROBIT_DEBUGGER_INIT_SUCCESS = "MICROBIT.DEBUGGER.INIT.SUCCESS", MICROBIT_DEBUGGER_INIT_FAIL = "MICROBIT.DEBUGGER.INIT.FAIL", CLUE_DEBUGGER_INIT_SUCCESS = "CLUE.DEBUGGER.INIT.SUCCESS", CLUE_DEBUGGER_INIT_FAIL = "CLUE.DEBUGGER.INIT.FAIL", // Extension commands COMMAND_RUN_SIMULATOR_BUTTON = "COMMAND.RUN.SIMULATOR_BUTTON", COMMAND_RUN_PALETTE = "COMMAND.RUN.PALETTE", COMMAND_INSTALL_EXTENSION_DEPENDENCIES = "COMMAND.INSTALL.EXTENSION.DEPENDENCIES", COMMAND_SERIAL_MONITOR_CHOOSE_PORT = "COMMAND.SERIAL_MONITOR.CHOOSE_PORT", COMMAND_SERIAL_MONITOR_OPEN = "COMMAND.SERIAL_MONITOR.OPEN", COMMAND_SERIAL_MONITOR_BAUD_RATE = "COMMAND.SERIAL_MONITOR.BAUD_RATE", COMMAND_SERIAL_MONITOR_CLOSE = "COMMAND.SERIAL_MONITOR.CLOSE", COMMAND_GETTING_STARTED = "COMMAND.GETTING_STARTED", CPX_COMMAND_DEPLOY_DEVICE = "CPX.COMMAND.DEPLOY.DEVICE", CPX_COMMAND_NEW_FILE = "CPX.COMMAND.NEW.FILE.CPX", CPX_COMMAND_OPEN_SIMULATOR = "CPX.COMMAND.OPEN.SIMULATOR", MICROBIT_COMMAND_DEPLOY_DEVICE = "MICROBIT.COMMAND.DEPLOY.DEVICE", MICROBIT_COMMAND_NEW_FILE = "MICROBIT.COMMAND.NEW.FILE", MICROBIT_COMMAND_OPEN_SIMULATOR = "MICROBIT.COMMAND.OPEN.SIMULATOR", CLUE_COMMAND_DEPLOY_DEVICE = "CLUE.COMMAND.DEPLOY.DEVICE", CLUE_COMMAND_NEW_FILE = "CLUE.COMMAND.NEW.FILE.CPX", CLUE_COMMAND_OPEN_SIMULATOR = "CLUE.COMMAND.OPEN.SIMULATOR", // Simulator interaction CPX_SIMULATOR_BUTTON_A = "CPX.SIMULATOR.BUTTON.A", CPX_SIMULATOR_BUTTON_B = "CPX.SIMULATOR.BUTTON.B", CPX_SIMULATOR_BUTTON_AB = "CPX.SIMULATOR.BUTTON.AB", CPX_SIMULATOR_SWITCH = "CPX.SIMULATOR.SWITCH", MICROBIT_SIMULATOR_BUTTON_A = "MICROBIT.SIMULATOR.BUTTON.A", MICROBIT_SIMULATOR_BUTTON_B = "MICROBIT.SIMULATOR.BUTTON.B", MICROBIT_SIMULATOR_BUTTON_AB = "MICROBIT.SIMULATOR.BUTTON.AB", CLUE_SIMULATOR_BUTTON_A = "CLUE.SIMULATOR.BUTTON.A", CLUE_SIMULATOR_BUTTON_B = "CLUE.SIMULATOR.BUTTON.B", CLUE_SIMULATOR_BUTTON_AB = "CLUE.SIMULATOR.BUTTON.AB", // Sensors CPX_SIMULATOR_TEMPERATURE_SENSOR = "CPX.SIMULATOR.TEMPERATURE", CPX_SIMULATOR_LIGHT_SENSOR = "CPX.SIMULATOR.LIGHT", CPX_SIMULATOR_MOTION_SENSOR = "CPX.SIMULATOR.MOTION", CPX_SIMULATOR_SHAKE = "CPX.SIMULATOR.SHAKE", CPX_SIMULATOR_CAPACITIVE_TOUCH = "CPX.SIMULATOR.CAPACITIVE.TOUCH", MICROBIT_SIMULATOR_TEMPERATURE_SENSOR = "MICROBIT.SIMULATOR.TEMPERATURE", MICROBIT_SIMULATOR_LIGHT_SENSOR = "MICROBIT.SIMULATOR.LIGHT", MICROBIT_SIMULATOR_MOTION_SENSOR = "MICROBIT.SIMULATOR.MOTION", MICROBIT_SIMULATOR_GESTURE_SENSOR = "MICROBIT.SIMULATOR.GESTURE", CLUE_SIMULATOR_TEMPERATURE_SENSOR = "CLUE.SIMULATOR.TEMPERATURE", CLUE_SIMULATOR_LIGHT_SENSOR = "CLUE.SIMULATOR.LIGHT", CLUE_SIMULATOR_MOTION_SENSOR = "CLUE.SIMULATOR.MOTION", CLUE_SIMULATOR_GESTURE_SENSOR = "CLUE.SIMULATOR.GESTURE", CLUE_SIMULATOR_PRESSURE_SENSOR = "CLUE.SIMULATOR.PRESSURE", CLUE_SIMULATOR_PROXIMITY_SENSOR = "CLUE.SIMULATOR.PROXIMITY", CLUE_SIMULATOR_HUMIDITY_SENSOR = "CLUE.SIMULATOR.HUMIDITY", CLUE_SIMULATOR_GYRO_SENSOR = "CLUE.SIMULATOR.GYRO", CLUE_SIMULATOR_MAGNET_SENSOR = "CLUE.SIMULATOR.MAGNET", // Pop-up dialog CPX_CLICK_DIALOG_DONT_SHOW = "CPX.CLICK.DIALOG.DONT.SHOW", CPX_CLICK_DIALOG_EXAMPLE_CODE = "CPX.CLICK.DIALOG.EXAMPLE.CODE", CPX_CLICK_DIALOG_HELP_DEPLOY_TO_DEVICE = "CPX.CLICK.DIALOG.HELP.DEPLOY.TO.DEVICE", CPX_CLICK_DIALOG_TUTORIALS = "CPX.CLICK.DIALOG.TUTORIALS", CLUE_CLICK_DIALOG_HELP_DEPLOY_TO_DEVICE = "CLUE.CLICK.DIALOG.HELP.DEPLOY.TO.DEVICE", ERROR_PYTHON_PROCESS = "ERROR.PYTHON.PROCESS", CPX_ERROR_COMMAND_NEW_FILE = "CPX.ERROR.COMMAND.NEW.FILE", CPX_ERROR_DEPLOY_WITHOUT_DEVICE = "CPX.ERROR.DEPLOY.WITHOUT.DEVICE", CPX_ERROR_PYTHON_DEVICE_PROCESS = "CPX.ERROR.PYTHON.DEVICE.PROCESS", CPX_SUCCESS_COMMAND_DEPLOY_DEVICE = "CPX.SUCCESS.COMMAND.DEPLOY.DEVICE", MICROBIT_ERROR_COMMAND_NEW_FILE = "MICROBIT.ERROR.COMMAND.NEW.FILE", MICROBIT_ERROR_DEPLOY_WITHOUT_DEVICE = "MICROBIT.ERROR.DEPLOY.WITHOUT.DEVICE", MICROBIT_ERROR_PYTHON_DEVICE_PROCESS = "MICROBIT.ERROR.PYTHON.DEVICE.PROCESS", MICROBIT_SUCCESS_COMMAND_DEPLOY_DEVICE = "MICROBIT.SUCCESS.COMMAND.DEPLOY.DEVICE", CLUE_ERROR_COMMAND_NEW_FILE = "CLUE.ERROR.COMMAND.NEW.FILE", CLUE_ERROR_DEPLOY_WITHOUT_DEVICE = "CLUE.ERROR.DEPLOY.WITHOUT.DEVICE", CLUE_ERROR_PYTHON_DEVICE_PROCESS = "CLUE.ERROR.PYTHON.DEVICE.PROCESS", CLUE_SUCCESS_COMMAND_DEPLOY_DEVICE = "CLUE.SUCCESS.COMMAND.DEPLOY.DEVICE", // Performance CPX_PERFORMANCE_DEPLOY_DEVICE = "CPX.PERFORMANCE.DEPLOY.DEVICE", CPX_PERFORMANCE_NEW_FILE = "CPX.PERFORMANCE.NEW.FILE", CPX_PERFORMANCE_OPEN_SIMULATOR = "CPX.PERFORMANCE.OPEN.SIMULATOR", MICROBIT_PERFORMANCE_DEPLOY_DEVICE = "MICROBIT.PERFORMANCE.DEPLOY.DEVICE", MICROBIT_PERFORMANCE_NEW_FILE = "MICROBIT.PERFORMANCE.NEW.FILE", MICROBIT_PERFORMANCE_OPEN_SIMULATOR = "MICROBIT.PERFORMANCE.OPEN.SIMULATOR", CLUE_PERFORMANCE_DEPLOY_DEVICE = "CLUE.PERFORMANCE.DEPLOY.DEVICE", CLUE_PERFORMANCE_NEW_FILE = "CLUE.PERFORMANCE.NEW.FILE", CLUE_PERFORMANCE_OPEN_SIMULATOR = "CLUE.PERFORMANCE.OPEN.SIMULATOR", // Venv options SETUP_VENV_CREATION_ERR = "SETUP.VENV.CREATION.ERR", SETUP_NO_PIP = "SETUP.NO.PIP", SETUP_DEP_INSTALL_FAIL = "SETUP.DEP.INSTALL.FAIL", SETUP_AUTO_RESOLVE_PYTHON_PATH = "SETUP.AUTO.RESOLVE.PYTHON.PATH", SETUP_NO_PYTHON_PATH = "SETUP.NO.PYTHON.PATH", SETUP_DOWNLOAD_PYTHON = "SETUP.DOWNLOAD.PYTHON", SETUP_INVALID_PYTHON_INTERPRETER_PATH = "SETUP.INVALID.PYTHON.INTERPRETER.PATH", SETUP_INVALID_PYTHON_VER = "SETUP.INVALID.PYTHON.VER", SETUP_INSTALL_VENV = "SETUP.INSTALL.VENV", SETUP_ORIGINAL_INTERPRETER_DEP_INSTALL = "SETUP.ORIGINAL.INTERPRETER.DEP.INSTALL", SETUP_HAS_VENV = "SETUP.HAS.VENV", SETUP_NO_DEPS_INSTALLED = "SETUP.NO.DEPS.INSTALLED", } export const DEFAULT_DEVICE = CONSTANTS.DEVICE_NAME.CPX; // tslint:disable-next-line: no-namespace export namespace DialogResponses { export const ACCEPT_AND_RUN: MessageItem = { title: localize("dialogResponses.agreeAndRun", "Agree and Run"), }; export const AGREE_AND_PROCEED: MessageItem = { title: localize("dialogResponses.agreeAndProceed", "Agree and Proceed"), }; export const CANCEL: MessageItem = { title: localize("dialogResponses.cancel", "Cancel"), }; export const SELECT: MessageItem = { title: localize("dialogResponses.select", "Select"), }; export const HELP: MessageItem = { title: localize("dialogResponses.help", "I need help"), }; export const DONT_SHOW: MessageItem = { title: localize("dialogResponses.dontShowAgain", "Don't Show Again"), }; export const NO: MessageItem = { title: localize("dialogResponses.No", "No"), }; export const INSTALL_NOW: MessageItem = { title: localize("dialogResponses.installNow", "Install Now"), }; export const DONT_INSTALL: MessageItem = { title: localize("dialogResponses.dontInstall", "Don't Install"), }; export const PRIVACY_STATEMENT: MessageItem = { title: localize("info.privacyStatement", "Privacy Statement"), }; export const TUTORIALS: MessageItem = { title: localize("dialogResponses.tutorials", "Tutorials on Adafruit"), }; export const EXAMPLE_CODE: MessageItem = { title: localize( "dialogResponses.exampleCode", "Example Code on GitHub" ), }; export const MESSAGE_UNDERSTOOD: MessageItem = { title: localize("dialogResponses.messageUnderstood", "Got It"), }; export const INSTALL_PIP: MessageItem = { title: localize( "dialogResponses.installPip", "Install from Pip's webpage" ), }; export const INSTALL_PYTHON: MessageItem = { title: localize( "dialogResponses.installPython", "Install from python.org" ), }; export const YES: MessageItem = { title: localize("dialogResponses.Yes", "Yes"), }; export const READ_INSTALL_MD: MessageItem = { title: localize( "dialogResponses.readInstall", "Read installation docs" ), }; } export const CPX_CONFIG_FILE = path.join(".vscode", "cpx.json"); export const STATUS_BAR_PRIORITY = { PORT: 20, OPEN_PORT: 30, BAUD_RATE: 40, }; export const VERSIONS = { MIN_PY_VERSION: "Python 3.7.0", }; export const HELPER_FILES = { CHECK_IF_VENV_PY: "check_if_venv.py", CHECK_PYTHON_DEPENDENCIES: "check_python_dependencies.py", DEVICE_PY: "device.py", PROCESS_USER_CODE_PY: "process_user_code.py", PYTHON_EXE: "python.exe", PYTHON: "python", }; export const GLOBAL_ENV_VARS = { PYTHON: "python", PYTHON3: "python3", }; export const LANGUAGE_VARS = { PYTHON: { ID: "python", FILE_ENDS: ".py" }, }; export default CONSTANTS;
the_stack
import fs from 'fs' import fsPath from 'path' import makeDir from 'make-dir' import stream from 'stream' import isStream from 'is-stream' import shellEscape from 'shell-escape' import scanDirectory from 'sb-scandir' import { PromiseQueue } from 'sb-promise-queue' import invariant, { AssertionError } from 'assert' import SSH2, { ConnectConfig, ClientChannel, SFTPWrapper, ExecOptions, PseudoTtyOptions, ShellOptions } from 'ssh2' // eslint-disable-next-line import/no-extraneous-dependencies import { Prompt, Stats, TransferOptions } from 'ssh2-streams' export type Config = ConnectConfig & { password?: string privateKey?: string tryKeyboard?: boolean onKeyboardInteractive?: ( name: string, instructions: string, lang: string, prompts: Prompt[], finish: (responses: string[]) => void, ) => void } export interface SSHExecCommandOptions { cwd?: string stdin?: string | stream.Readable execOptions?: ExecOptions encoding?: BufferEncoding onChannel?: (clientChannel: ClientChannel) => void onStdout?: (chunk: Buffer) => void onStderr?: (chunk: Buffer) => void } export interface SSHExecCommandResponse { stdout: string stderr: string code: number | null signal: string | null } export interface SSHExecOptions extends SSHExecCommandOptions { stream?: 'stdout' | 'stderr' | 'both' } export interface SSHPutFilesOptions { sftp?: SFTPWrapper | null concurrency?: number transferOptions?: TransferOptions } export interface SSHGetPutDirectoryOptions extends SSHPutFilesOptions { tick?: (localFile: string, remoteFile: string, error: Error | null) => void validate?: (path: string) => boolean recursive?: boolean } export type SSHMkdirMethod = 'sftp' | 'exec' const DEFAULT_CONCURRENCY = 1 const DEFAULT_VALIDATE = (path: string) => !fsPath.basename(path).startsWith('.') const DEFAULT_TICK = () => { /* No Op */ } export class SSHError extends Error { constructor(message: string, public code: string | null = null) { super(message) } } function unixifyPath(path: string) { if (path.includes('\\')) { return path.split('\\').join('/') } return path } async function readFile(filePath: string): Promise<string> { return new Promise((resolve, reject) => { fs.readFile(filePath, 'utf8', (err, res) => { if (err) { reject(err) } else { resolve(res) } }) }) } const SFTP_MKDIR_ERR_CODE_REGEXP = /Error: (E[\S]+): / async function makeDirectoryWithSftp(path: string, sftp: SFTPWrapper) { let stats: Stats | null = null try { stats = await new Promise((resolve, reject) => { sftp.stat(path, (err, res) => { if (err) { reject(err) } else { resolve(res) } }) }) } catch (_) { /* No Op */ } if (stats) { if (stats.isDirectory()) { // Already exists, nothing to worry about return } throw new Error('mkdir() failed, target already exists and is not a directory') } try { await new Promise<void>((resolve, reject) => { sftp.mkdir(path, (err) => { if (err) { reject(err) } else { resolve() } }) }) } catch (err) { if (err != null && typeof err.stack === 'string') { const matches = SFTP_MKDIR_ERR_CODE_REGEXP.exec(err.stack) if (matches != null) { throw new SSHError(err.message, matches[1]) } throw err } } } export class NodeSSH { connection: SSH2.Client | null = null private getConnection(): SSH2.Client { const { connection } = this if (connection == null) { throw new Error('Not connected to server') } return connection } public async connect(givenConfig: Config): Promise<this> { invariant(givenConfig != null && typeof givenConfig === 'object', 'config must be a valid object') const config: Config = { ...givenConfig } invariant(config.username != null && typeof config.username === 'string', 'config.username must be a valid string') if (config.host != null) { invariant(typeof config.host === 'string', 'config.host must be a valid string') } else if (config.sock != null) { invariant(typeof config.sock === 'object', 'config.sock must be a valid object') } else { throw new AssertionError({ message: 'Either config.host or config.sock must be provided' }) } if (config.privateKey != null) { invariant(typeof config.privateKey === 'string', 'config.privateKey must be a valid string') invariant( config.passphrase == null || typeof config.passphrase === 'string', 'config.passphrase must be a valid string', ) if ( !( (config.privateKey.includes('BEGIN') && config.privateKey.includes('KEY')) || config.privateKey.includes('PuTTY-User-Key-File-2') ) ) { // Must be an fs path try { config.privateKey = await readFile(config.privateKey) } catch (err) { if (err != null && err.code === 'ENOENT') { throw new AssertionError({ message: 'config.privateKey does not exist at given fs path' }) } throw err } } } else if (config.password != null) { invariant(typeof config.password === 'string', 'config.password must be a valid string') } if (config.tryKeyboard != null) { invariant(typeof config.tryKeyboard === 'boolean', 'config.tryKeyboard must be a valid boolean') } if (config.tryKeyboard) { const { password } = config if (config.onKeyboardInteractive != null) { invariant( typeof config.onKeyboardInteractive === 'function', 'config.onKeyboardInteractive must be a valid function', ) } else if (password != null) { config.onKeyboardInteractive = (name, instructions, instructionsLang, prompts, finish) => { if (prompts.length > 0 && prompts[0].prompt.toLowerCase().includes('password')) { finish([password]) } } } } const connection = new SSH2.Client() this.connection = connection await new Promise<void>((resolve, reject) => { connection.on('error', reject) if (config.onKeyboardInteractive) { connection.on('keyboard-interactive', config.onKeyboardInteractive) } connection.on('ready', () => { connection.removeListener('error', reject) resolve() }) connection.on('end', () => { if (this.connection === connection) { this.connection = null } }) connection.on('close', () => { if (this.connection === connection) { this.connection = null } reject(new SSHError('No response from server', 'ETIMEDOUT')) }) connection.connect(config) }) return this } public isConnected(): boolean { return this.connection != null } async requestShell(options?: PseudoTtyOptions | ShellOptions | false): Promise<ClientChannel> { const connection = this.getConnection() return new Promise((resolve, reject) => { const callback = (err: Error | undefined, res: ClientChannel) => { if (err) { reject(err) } else { resolve(res) } } if (options == null) { connection.shell(callback) } else { connection.shell(options as never, callback) } }) } async withShell( callback: (channel: ClientChannel) => Promise<void>, options?: PseudoTtyOptions | ShellOptions | false, ): Promise<void> { invariant(typeof callback === 'function', 'callback must be a valid function') const shell = await this.requestShell(options) try { await callback(shell) } finally { // Try to close gracefully if (!shell.close()) { // Destroy local socket if it doesn't work shell.destroy() } } } async requestSFTP(): Promise<SFTPWrapper> { const connection = this.getConnection() return new Promise((resolve, reject) => { connection.sftp((err, res) => { if (err) { reject(err) } else { resolve(res) } }) }) } async withSFTP(callback: (sftp: SFTPWrapper) => Promise<void>): Promise<void> { invariant(typeof callback === 'function', 'callback must be a valid function') const sftp = await this.requestSFTP() try { await callback(sftp) } finally { sftp.end() } } async execCommand(givenCommand: string, options: SSHExecCommandOptions = {}): Promise<SSHExecCommandResponse> { invariant(typeof givenCommand === 'string', 'command must be a valid string') invariant(options != null && typeof options === 'object', 'options must be a valid object') invariant(options.cwd == null || typeof options.cwd === 'string', 'options.cwd must be a valid string') invariant( options.stdin == null || typeof options.stdin === 'string' || isStream.readable(options.stdin), 'options.stdin must be a valid string or readable stream', ) invariant( options.execOptions == null || typeof options.execOptions === 'object', 'options.execOptions must be a valid object', ) invariant(options.encoding == null || typeof options.encoding === 'string', 'options.encoding must be a valid string') invariant( options.onChannel == null || typeof options.onChannel === 'function', 'options.onChannel must be a valid function', ) invariant( options.onStdout == null || typeof options.onStdout === 'function', 'options.onStdout must be a valid function', ) invariant( options.onStderr == null || typeof options.onStderr === 'function', 'options.onStderr must be a valid function', ) let command = givenCommand if (options.cwd) { command = `cd ${shellEscape([options.cwd])} ; ${command}` } const connection = this.getConnection() const output: { stdout: string[]; stderr: string[] } = { stdout: [], stderr: [] } return new Promise((resolve, reject) => { connection.exec(command, options.execOptions != null ? options.execOptions : {}, (err, channel) => { if (err) { reject(err) return } if (options.onChannel) { options.onChannel(channel) } channel.on('data', (chunk: Buffer) => { if (options.onStdout) options.onStdout(chunk) output.stdout.push(chunk.toString(options.encoding)) }) channel.stderr.on('data', (chunk: Buffer) => { if (options.onStderr) options.onStderr(chunk) output.stderr.push(chunk.toString(options.encoding)) }) if (options.stdin != null) { if (isStream.readable(options.stdin)) { options.stdin.pipe(channel, { end: true, }) } else { channel.write(options.stdin) channel.end() } } else { channel.end() } let code: number | null = null let signal: string | null = null channel.on('exit', (code_, signal_) => { code = code_ || null signal = signal_ || null }) channel.on('close', () => { resolve({ code: code != null ? code : null, signal: signal != null ? signal : null, stdout: output.stdout.join('').trim(), stderr: output.stderr.join('').trim(), }) }) }) }) } exec(command: string, parameters: string[], options?: SSHExecOptions & { stream?: 'stdout' | 'stderr' }): Promise<string> exec(command: string, parameters: string[], options?: SSHExecOptions & { stream: 'both' }): Promise<SSHExecCommandResponse> async exec(command: string, parameters: string[], options: SSHExecOptions = {}): Promise<SSHExecCommandResponse | string> { invariant(typeof command === 'string', 'command must be a valid string') invariant(Array.isArray(parameters), 'parameters must be a valid array') invariant(options != null && typeof options === 'object', 'options must be a valid object') invariant( options.stream == null || ['both', 'stdout', 'stderr'].includes(options.stream), 'options.stream must be one of both, stdout, stderr', ) for (let i = 0, { length } = parameters; i < length; i += 1) { invariant(typeof parameters[i] === 'string', `parameters[${i}] must be a valid string`) } const completeCommand = `${command} ${shellEscape(parameters)}` const response = await this.execCommand(completeCommand, options) if (options.stream == null || options.stream === 'stdout') { if (response.stderr) { throw new Error(response.stderr) } return response.stdout } if (options.stream === 'stderr') { return response.stderr } return response } async mkdir(path: string, method: SSHMkdirMethod = 'sftp', givenSftp: SFTPWrapper | null = null): Promise<void> { invariant(typeof path === 'string', 'path must be a valid string') invariant(typeof method === 'string' && (method === 'sftp' || method === 'exec'), 'method must be either sftp or exec') invariant(givenSftp == null || typeof givenSftp === 'object', 'sftp must be a valid object') if (method === 'exec') { await this.exec('mkdir', ['-p', unixifyPath(path)]) return } const sftp = givenSftp || (await this.requestSFTP()) const makeSftpDirectory = async (retry: boolean) => makeDirectoryWithSftp(unixifyPath(path), sftp).catch(async (error: SSHError) => { if (!retry || error == null || (error.message !== 'No such file' && error.code !== 'ENOENT')) { throw error } await this.mkdir(fsPath.dirname(path), 'sftp', sftp) await makeSftpDirectory(false) }) try { await makeSftpDirectory(true) } finally { if (!givenSftp) { sftp.end() } } } async getFile( localFile: string, remoteFile: string, givenSftp: SFTPWrapper | null = null, transferOptions: TransferOptions | null = null, ): Promise<void> { invariant(typeof localFile === 'string', 'localFile must be a valid string') invariant(typeof remoteFile === 'string', 'remoteFile must be a valid string') invariant(givenSftp == null || typeof givenSftp === 'object', 'sftp must be a valid object') invariant(transferOptions == null || typeof transferOptions === 'object', 'transferOptions must be a valid object') const sftp = givenSftp || (await this.requestSFTP()) try { await new Promise<void>((resolve, reject) => { sftp.fastGet(unixifyPath(remoteFile), localFile, transferOptions || {}, (err) => { if (err) { reject(err) } else { resolve() } }) }) } finally { if (!givenSftp) { sftp.end() } } } async putFile( localFile: string, remoteFile: string, givenSftp: SFTPWrapper | null = null, transferOptions: TransferOptions | null = null, ): Promise<void> { invariant(typeof localFile === 'string', 'localFile must be a valid string') invariant(typeof remoteFile === 'string', 'remoteFile must be a valid string') invariant(givenSftp == null || typeof givenSftp === 'object', 'sftp must be a valid object') invariant(transferOptions == null || typeof transferOptions === 'object', 'transferOptions must be a valid object') invariant( await new Promise((resolve) => { fs.access(localFile, fs.constants.R_OK, (err) => { resolve(err === null) }) }), `localFile does not exist at ${localFile}`, ) const sftp = givenSftp || (await this.requestSFTP()) const putFile = (retry: boolean) => { return new Promise<void>((resolve, reject) => { sftp.fastPut(localFile, unixifyPath(remoteFile), transferOptions || {}, (err) => { if (err == null) { resolve() return } if (err.message === 'No such file' && retry) { resolve(this.mkdir(fsPath.dirname(remoteFile), 'sftp', sftp).then(() => putFile(false))) } else { reject(err) } }) }) } try { await putFile(true) } finally { if (!givenSftp) { sftp.end() } } } async putFiles( files: { local: string; remote: string }[], { concurrency = DEFAULT_CONCURRENCY, sftp: givenSftp = null, transferOptions = {} }: SSHPutFilesOptions = {}, ): Promise<void> { invariant(Array.isArray(files), 'files must be an array') for (let i = 0, { length } = files; i < length; i += 1) { const file = files[i] invariant(file, 'files items must be valid objects') invariant(file.local && typeof file.local === 'string', `files[${i}].local must be a string`) invariant(file.remote && typeof file.remote === 'string', `files[${i}].remote must be a string`) } const transferred: typeof files = [] const sftp = givenSftp || (await this.requestSFTP()) const queue = new PromiseQueue({ concurrency }) try { await new Promise((resolve, reject) => { files.forEach((file) => { queue .add(async () => { await this.putFile(file.local, file.remote, sftp, transferOptions) transferred.push(file) }) .catch(reject) }) queue.waitTillIdle().then(resolve) }) } catch (error) { if (error != null) { error.transferred = transferred } throw error } finally { if (!givenSftp) { sftp.end() } } } async putDirectory( localDirectory: string, remoteDirectory: string, { concurrency = DEFAULT_CONCURRENCY, sftp: givenSftp = null, transferOptions = {}, recursive = true, tick = DEFAULT_TICK, validate = DEFAULT_VALIDATE, }: SSHGetPutDirectoryOptions = {}, ): Promise<boolean> { invariant(typeof localDirectory === 'string' && localDirectory, 'localDirectory must be a string') invariant(typeof remoteDirectory === 'string' && remoteDirectory, 'remoteDirectory must be a string') const localDirectoryStat: fs.Stats = await new Promise((resolve) => { fs.stat(localDirectory, (err, stat) => { resolve(stat || null) }) }) invariant(localDirectoryStat != null, `localDirectory does not exist at ${localDirectory}`) invariant(localDirectoryStat.isDirectory(), `localDirectory is not a directory at ${localDirectory}`) const sftp = givenSftp || (await this.requestSFTP()) const scanned = await scanDirectory(localDirectory, { recursive, validate, }) const files = scanned.files.map((item) => fsPath.relative(localDirectory, item)) const directories = scanned.directories.map((item) => fsPath.relative(localDirectory, item)) // Sort shortest to longest directories.sort((a, b) => a.length - b.length) let failed = false try { // Do the directories first. await new Promise((resolve, reject) => { const queue = new PromiseQueue({ concurrency }) directories.forEach((directory) => { queue .add(async () => { await this.mkdir(fsPath.join(remoteDirectory, directory), 'sftp', sftp) }) .catch(reject) }) resolve(queue.waitTillIdle()) }) // and now the files await new Promise((resolve, reject) => { const queue = new PromiseQueue({ concurrency }) files.forEach((file) => { queue .add(async () => { const localFile = fsPath.join(localDirectory, file) const remoteFile = fsPath.join(remoteDirectory, file) try { await this.putFile(localFile, remoteFile, sftp, transferOptions) tick(localFile, remoteFile, null) } catch (_) { failed = true tick(localFile, remoteFile, _) } }) .catch(reject) }) resolve(queue.waitTillIdle()) }) } finally { if (!givenSftp) { sftp.end() } } return !failed } async getDirectory( localDirectory: string, remoteDirectory: string, { concurrency = DEFAULT_CONCURRENCY, sftp: givenSftp = null, transferOptions = {}, recursive = true, tick = DEFAULT_TICK, validate = DEFAULT_VALIDATE, }: SSHGetPutDirectoryOptions = {}, ): Promise<boolean> { invariant(typeof localDirectory === 'string' && localDirectory, 'localDirectory must be a string') invariant(typeof remoteDirectory === 'string' && remoteDirectory, 'remoteDirectory must be a string') const localDirectoryStat: fs.Stats = await new Promise((resolve) => { fs.stat(localDirectory, (err, stat) => { resolve(stat || null) }) }) invariant(localDirectoryStat != null, `localDirectory does not exist at ${localDirectory}`) invariant(localDirectoryStat.isDirectory(), `localDirectory is not a directory at ${localDirectory}`) const sftp = givenSftp || (await this.requestSFTP()) const scanned = await scanDirectory(remoteDirectory, { recursive, validate, concurrency, fileSystem: { basename(path) { return fsPath.posix.basename(path) }, join(pathA, pathB) { return fsPath.posix.join(pathA, pathB) }, readdir(path) { return new Promise((resolve, reject) => { sftp.readdir(path, (err, res) => { if (err) { reject(err) } else { resolve(res.map((item) => item.filename)) } }) }) }, stat(path) { return new Promise((resolve, reject) => { sftp.stat(path, (err, res) => { if (err) { reject(err) } else { // eslint-disable-next-line @typescript-eslint/no-explicit-any resolve(res as any) } }) }) }, }, }) const files = scanned.files.map((item) => fsPath.relative(remoteDirectory, item)) const directories = scanned.directories.map((item) => fsPath.relative(remoteDirectory, item)) // Sort shortest to longest directories.sort((a, b) => a.length - b.length) let failed = false try { // Do the directories first. await new Promise((resolve, reject) => { const queue = new PromiseQueue({ concurrency }) directories.forEach((directory) => { queue .add(async () => { await makeDir(fsPath.join(localDirectory, directory)) }) .catch(reject) }) resolve(queue.waitTillIdle()) }) // and now the files await new Promise((resolve, reject) => { const queue = new PromiseQueue({ concurrency }) files.forEach((file) => { queue .add(async () => { const localFile = fsPath.join(localDirectory, file) const remoteFile = fsPath.join(remoteDirectory, file) try { await this.getFile(localFile, remoteFile, sftp, transferOptions) tick(localFile, remoteFile, null) } catch (_) { failed = true tick(localFile, remoteFile, _) } }) .catch(reject) }) resolve(queue.waitTillIdle()) }) } finally { if (!givenSftp) { sftp.end() } } return !failed } dispose(): void { if (this.connection) { this.connection.end() this.connection = null } } }
the_stack
import { JsPsych, JsPsychPlugin, ParameterType, TrialType } from "jspsych"; const info = <const>{ name: "preload", parameters: { /** Whether or not to automatically preload any media files based on the timeline passed to jsPsych.run. */ auto_preload: { type: ParameterType.BOOL, pretty_name: "Auto-preload", default: false, }, /** A timeline of trials to automatically preload. If one or more trial objects is provided in the timeline array, then the plugin will attempt to preload the media files used in the trial(s). */ trials: { type: ParameterType.TIMELINE, pretty_name: "Trials", default: [], }, /** * Array with one or more image files to load. This parameter is often used in cases where media files cannot# * be automatically preloaded based on the timeline, e.g. because the media files are passed into an image plugin/parameter with * timeline variables or dynamic parameters, or because the image is embedded in an HTML string. */ images: { type: ParameterType.STRING, pretty_name: "Images", default: [], array: true, }, /** * Array with one or more audio files to load. This parameter is often used in cases where media files cannot * be automatically preloaded based on the timeline, e.g. because the media files are passed into an audio plugin/parameter with * timeline variables or dynamic parameters, or because the audio is embedded in an HTML string. */ audio: { type: ParameterType.STRING, pretty_name: "Audio", default: [], array: true, }, /** * Array with one or more video files to load. This parameter is often used in cases where media files cannot * be automatically preloaded based on the timeline, e.g. because the media files are passed into a video plugin/parameter with * timeline variables or dynamic parameters, or because the video is embedded in an HTML string. */ video: { type: ParameterType.STRING, pretty_name: "Video", default: [], array: true, }, /** HTML-formatted message to be shown above the progress bar while the files are loading. */ message: { type: ParameterType.HTML_STRING, pretty_name: "Message", default: null, }, /** Whether or not to show the loading progress bar. */ show_progress_bar: { type: ParameterType.BOOL, pretty_name: "Show progress bar", default: true, }, /** * Whether or not to continue with the experiment if a loading error occurs. If false, then if a loading error occurs, * the error_message will be shown on the page and the trial will not end. If true, then if if a loading error occurs, the trial will end * and preloading failure will be logged in the trial data. */ continue_after_error: { type: ParameterType.BOOL, pretty_name: "Continue after error", default: false, }, /** Error message to show on the page in case of any loading errors. This parameter is only relevant when continue_after_error is false. */ error_message: { type: ParameterType.HTML_STRING, pretty_name: "Error message", default: "The experiment failed to load.", }, /** * Whether or not to show a detailed error message on the page. If true, then detailed error messages will be shown on the * page for all files that failed to load, along with the general error_message. This parameter is only relevant when continue_after_error is false. */ show_detailed_errors: { type: ParameterType.BOOL, pretty_name: "Show detailed errors", default: false, }, /** * The maximum amount of time that the plugin should wait before stopping the preload and either ending the trial * (if continue_after_error is true) or stopping the experiment with an error message (if continue_after_error is false). * If null, the plugin will wait indefintely for the files to load. */ max_load_time: { type: ParameterType.INT, pretty_name: "Max load time", default: null, }, /** Function to be called after a file fails to load. The function takes the file name as its only argument. */ on_error: { type: ParameterType.FUNCTION, pretty_name: "On error", default: null, }, /** Function to be called after a file loads successfully. The function takes the file name as its only argument. */ on_success: { type: ParameterType.FUNCTION, pretty_name: "On success", default: null, }, }, }; type Info = typeof info; /** * **preload** * * jsPsych plugin for preloading image, audio, and video files * * @author Becky Gilbert * @see {@link https://www.jspsych.org/plugins/jspsych-preload/ preload plugin documentation on jspsych.org} */ class PreloadPlugin implements JsPsychPlugin<Info> { static info = info; constructor(private jsPsych: JsPsych) {} trial(display_element: HTMLElement, trial: TrialType<Info>) { var success = null; var timeout = false; var failed_images = []; var failed_audio = []; var failed_video = []; var detailed_errors = []; var in_safe_mode = this.jsPsych.getSafeModeStatus(); // create list of media to preload // var images = []; var audio = []; var video = []; if (trial.auto_preload) { var experiment_timeline = this.jsPsych.getTimeline(); var auto_preload = this.jsPsych.pluginAPI.getAutoPreloadList(experiment_timeline); images = images.concat(auto_preload.images); audio = audio.concat(auto_preload.audio); video = video.concat(auto_preload.video); } if (trial.trials.length > 0) { var trial_preloads = this.jsPsych.pluginAPI.getAutoPreloadList(trial.trials); images = images.concat(trial_preloads.images); audio = audio.concat(trial_preloads.audio); video = video.concat(trial_preloads.video); } images = images.concat(trial.images); audio = audio.concat(trial.audio); video = video.concat(trial.video); images = this.jsPsych.utils.unique(images.flat()); audio = this.jsPsych.utils.unique(audio.flat()); video = this.jsPsych.utils.unique(video.flat()); if (in_safe_mode) { // don't preload video if in safe mode (experiment is running via file protocol) video = []; } // render display of message and progress bar var html = ""; if (trial.message !== null) { html += trial.message; } if (trial.show_progress_bar) { html += ` <div id='jspsych-loading-progress-bar-container' style='height: 10px; width: 300px; background-color: #ddd; margin: auto;'> <div id='jspsych-loading-progress-bar' style='height: 10px; width: 0%; background-color: #777;'></div> </div>`; } display_element.innerHTML = html; const update_loading_progress_bar = () => { loaded++; if (trial.show_progress_bar) { var percent_loaded = (loaded / total_n) * 100; var preload_progress_bar = display_element.querySelector<HTMLElement>( "#jspsych-loading-progress-bar" ); if (preload_progress_bar !== null) { preload_progress_bar.style.width = percent_loaded + "%"; } } }; // called if all files load successfully const on_success = () => { if (typeof timeout !== "undefined" && timeout === false) { // clear timeout immediately after finishing, to handle race condition with max_load_time this.jsPsych.pluginAPI.clearAllTimeouts(); // need to call cancel preload function to clear global jsPsych preload_request list, even when they've all succeeded this.jsPsych.pluginAPI.cancelPreloads(); success = true; end_trial(); } }; // called if all_files haven't finished loading when max_load_time is reached const on_timeout = () => { this.jsPsych.pluginAPI.cancelPreloads(); if (typeof success !== "undefined" && (success === false || success === null)) { timeout = true; if (loaded_success < total_n) { success = false; } after_error("timeout"); // call trial's on_error event handler here, in case loading timed out with no file errors detailed_errors.push( "<p><strong>Loading timed out.</strong><br>" + "Consider compressing your stimuli files, loading your files in smaller batches,<br>" + "and/or increasing the <i>max_load_time</i> parameter.</p>" ); if (trial.continue_after_error) { end_trial(); } else { stop_with_error_message(); } } }; const stop_with_error_message = () => { this.jsPsych.pluginAPI.clearAllTimeouts(); this.jsPsych.pluginAPI.cancelPreloads(); // show error message display_element.innerHTML = trial.error_message; // show detailed errors, if necessary if (trial.show_detailed_errors) { display_element.innerHTML += "<p><strong>Error details:</strong></p>"; detailed_errors.forEach((e) => { display_element.innerHTML += e; }); } }; const end_trial = () => { // clear timeout again when end_trial is called, to handle race condition with max_load_time this.jsPsych.pluginAPI.clearAllTimeouts(); var trial_data = { success: success, timeout: timeout, failed_images: failed_images, failed_audio: failed_audio, failed_video: failed_video, }; // clear the display display_element.innerHTML = ""; this.jsPsych.finishTrial(trial_data); }; // do preloading if (trial.max_load_time !== null) { this.jsPsych.pluginAPI.setTimeout(on_timeout, trial.max_load_time); } var total_n = images.length + audio.length + video.length; var loaded = 0; // success or error count var loaded_success = 0; // success count if (total_n == 0) { on_success(); } else { const load_video = (cb) => { this.jsPsych.pluginAPI.preloadVideo(video, cb, file_loading_success, file_loading_error); }; const load_audio = (cb) => { this.jsPsych.pluginAPI.preloadAudio(audio, cb, file_loading_success, file_loading_error); }; const load_images = (cb) => { this.jsPsych.pluginAPI.preloadImages(images, cb, file_loading_success, file_loading_error); }; if (video.length > 0) { load_video(() => {}); } if (audio.length > 0) { load_audio(() => {}); } if (images.length > 0) { load_images(() => {}); } } // helper functions and callbacks // called when a single file loading fails function file_loading_error(e) { // update progress bar even if there's an error update_loading_progress_bar(); // change success flag after first file loading error if (success == null) { success = false; } // add file to failed media list var source = "unknown file"; if (e.source) { source = e.source; } if (e.error && e.error.path && e.error.path.length > 0) { if (e.error.path[0].localName == "img") { failed_images.push(source); } else if (e.error.path[0].localName == "audio") { failed_audio.push(source); } else if (e.error.path[0].localName == "video") { failed_video.push(source); } } // construct detailed error message var err_msg = "<p><strong>Error loading file: " + source + "</strong><br>"; if (e.error.statusText) { err_msg += "File request response status: " + e.error.statusText + "<br>"; } if (e.error == "404") { err_msg += "404 - file not found.<br>"; } if ( typeof e.error.loaded !== "undefined" && e.error.loaded !== null && e.error.loaded !== 0 ) { err_msg += e.error.loaded + " bytes transferred."; } else { err_msg += "File did not begin loading. Check that file path is correct and reachable by the browser,<br>" + "and that loading is not blocked by cross-origin resource sharing (CORS) errors."; } err_msg += "</p>"; detailed_errors.push(err_msg); // call trial's on_error function after_error(source); // if this is the last file if (loaded == total_n) { if (trial.continue_after_error) { // if continue_after_error is false, then stop with an error end_trial(); } else { // otherwise end the trial and continue stop_with_error_message(); } } } // called when a single file loads successfully function file_loading_success(source: string) { update_loading_progress_bar(); // call trial's on_success function after_success(source); loaded_success++; if (loaded_success == total_n) { // if this is the last file and all loaded successfully, call success function on_success(); } else if (loaded == total_n) { // if this is the last file and there was at least one error if (trial.continue_after_error) { // end the trial and continue with experiment end_trial(); } else { // if continue_after_error is false, then stop with an error stop_with_error_message(); } } } function after_error(source: string) { // call on_error function and pass file name if (trial.on_error !== null) { trial.on_error(source); } } function after_success(source: string) { // call on_success function and pass file name if (trial.on_success !== null) { trial.on_success(source); } } } } export default PreloadPlugin;
the_stack
import {Matrix4, Vector3} from '@math.gl/core'; import {Ellipsoid} from '@math.gl/geospatial'; import {Stats} from '@probe.gl/stats'; import { RequestScheduler, assert, path, LoaderWithParser, LoaderOptions } from '@loaders.gl/loader-utils'; import TilesetCache from './tileset-cache'; import {calculateTransformProps} from './helpers/transform-utils'; import {FrameState, getFrameState} from './helpers/frame-state'; import {getZoomFromBoundingVolume} from './helpers/zoom'; import Tile3D from './tile-3d'; import Tileset3DTraverser from './traversers/tileset-3d-traverser'; import TilesetTraverser from './traversers/tileset-traverser'; import I3SetTraverser from './traversers/i3s-tileset-traverser'; import {TILESET_TYPE} from '../constants'; export type Tileset3DProps = { // loading throttleRequests?: boolean; maxRequests?: number; loadOptions?: LoaderOptions; loadTiles?: boolean; basePath?: string; maximumMemoryUsage?: number; // Metadata description?: string; attributions?: string[]; // Transforms ellipsoid?: object; modelMatrix?: Matrix4; // Traversal maximumScreenSpaceError?: number; viewportTraversersMap?: any; updateTransforms?: boolean; viewDistanceScale?: number; // Callbacks onTileLoad?: (tile: Tile3D) => any; onTileUnload?: (tile: Tile3D) => any; onTileError?: (tile: Tile3D, message: string, url: string) => any; contentLoader?: (tile: Tile3D) => Promise<void>; onTraversalComplete?: (selectedTiles: Tile3D[]) => Tile3D[]; }; type Props = { description: string; ellipsoid: object; modelMatrix: Matrix4; throttleRequests: boolean; maximumMemoryUsage: number; onTileLoad: (tile: Tile3D) => any; onTileUnload: (tile: Tile3D) => any; onTileError: (tile: Tile3D, message: string, url: string) => any; onTraversalComplete: (selectedTiles: Tile3D[]) => Tile3D[]; maximumScreenSpaceError: number; viewportTraversersMap: any; attributions: string[]; maxRequests: number; loadTiles: boolean; loadOptions: LoaderOptions; updateTransforms: boolean; viewDistanceScale: number; basePath: string; contentLoader?: (tile: Tile3D) => Promise<void>; i3s: {[key: string]: any}; }; const DEFAULT_PROPS: Props = { description: '', ellipsoid: Ellipsoid.WGS84, // A 4x4 transformation matrix this transforms the entire tileset. modelMatrix: new Matrix4(), // Set to false to disable network request throttling throttleRequests: true, // Number of simultaneous requsts, if throttleRequests is true maxRequests: 64, maximumMemoryUsage: 32, /** * Callback. Indicates this a tile's content was loaded * @param tile {TileHeader} */ onTileLoad: () => {}, /** * Callback. Indicates this a tile's content was unloaded * @param tile {TileHeader} */ onTileUnload: () => {}, onTileError: () => {}, /** * Callback. Allows post-process selectedTiles right after traversal. * @param selectedTiles {TileHeader[]} * @returns TileHeader[] - output array of tiles to return to deck.gl */ onTraversalComplete: (selectedTiles: Tile3D[]) => selectedTiles, // Optional async tile content loader contentLoader: undefined, // View distance scale modifier viewDistanceScale: 1.0, // TODO CESIUM // The maximum screen space error used to drive level of detail refinement. maximumScreenSpaceError: 8, loadTiles: true, updateTransforms: true, viewportTraversersMap: null, loadOptions: {fetch: {}}, attributions: [], basePath: '', i3s: {} }; // Tracked Stats const TILES_TOTAL = 'Tiles In Tileset(s)'; const TILES_IN_MEMORY = 'Tiles In Memory'; const TILES_IN_VIEW = 'Tiles In View'; const TILES_RENDERABLE = 'Tiles To Render'; const TILES_LOADED = 'Tiles Loaded'; const TILES_LOADING = 'Tiles Loading'; const TILES_UNLOADED = 'Tiles Unloaded'; const TILES_LOAD_FAILED = 'Failed Tile Loads'; const POINTS_COUNT = 'Points'; const TILES_GPU_MEMORY = 'Tile Memory Use'; export default class Tileset3D { // props: Tileset3DProps; options: Props; loadOptions: {[key: string]: any}; type: string; tileset: {[key: string]: any}; loader: LoaderWithParser; url: string; basePath: string; modelMatrix: Matrix4; ellipsoid: any; lodMetricType: string; lodMetricValue: number; refine: string; root: Tile3D | null; roots: {[key: string]: Tile3D}; asset: {[key: string]: any}; description: string; properties: any; extras: any; attributions: any; credits: any; stats: Stats; traverseCounter: number; geometricError: number; selectedTiles: Tile3D[]; cartographicCenter: Vector3 | null; cartesianCenter: Vector3 | null; zoom: number; boundingVolume: any; // METRICS // The maximum amount of GPU memory (in MB) that may be used to cache tiles. // Tiles not in view are unloaded to enforce private // The total amount of GPU memory in bytes used by the tileset. gpuMemoryUsageInBytes: any; dynamicScreenSpaceErrorComputedDensity: any; // TRAVERSAL _traverser: TilesetTraverser; private _cache: TilesetCache; _requestScheduler: RequestScheduler; _frameNumber: number; private _queryParamsString: string; private _queryParams: any; private _extensionsUsed: any; private _tiles: {[id: string]: Tile3D}; // counter for tracking tiles requests private _pendingCount: any; // HOLD TRAVERSAL RESULTS private lastUpdatedVieports: any[] | null; private _requestedTiles: any; private _emptyTiles: any; private frameStateData: any; maximumMemoryUsage: number; /** * Create a new Tileset3D * @param json * @param props */ // eslint-disable-next-line max-statements constructor(json: any, options?: Tileset3DProps) { assert(json); // PUBLIC MEMBERS this.options = {...DEFAULT_PROPS, ...options}; // raw data this.tileset = json; this.loader = json.loader; // could be 3d tiles, i3s this.type = json.type; // The url to a tileset JSON file. this.url = json.url; this.basePath = json.basePath || path.dirname(this.url); this.modelMatrix = this.options.modelMatrix; this.ellipsoid = this.options.ellipsoid; // Geometric error when the tree is not rendered at all this.lodMetricType = json.lodMetricType; this.lodMetricValue = json.lodMetricValue; this.refine = json.root.refine; this.loadOptions = this.options.loadOptions || {}; this.root = null; this.roots = {}; // view props this.cartographicCenter = null; this.cartesianCenter = null; this.zoom = 1; this.boundingVolume = null; // TRAVERSAL this.traverseCounter = 0; this.geometricError = 0; this._traverser = this._initializeTraverser(); this._cache = new TilesetCache(); this._requestScheduler = new RequestScheduler({ throttleRequests: this.options.throttleRequests, maxRequests: this.options.maxRequests }); // update tracker // increase in each update cycle this._frameNumber = 0; // counter for tracking tiles requests this._pendingCount = 0; // HOLD TRAVERSAL RESULTS this._tiles = {}; this.selectedTiles = []; this._emptyTiles = []; this._requestedTiles = []; this.frameStateData = {}; this.lastUpdatedVieports = null; this._queryParams = {}; this._queryParamsString = ''; // METRICS // The maximum amount of GPU memory (in MB) that may be used to cache tiles. // Tiles not in view are unloaded to enforce this. this.maximumMemoryUsage = this.options.maximumMemoryUsage || 32; // The total amount of GPU memory in bytes used by the tileset. this.gpuMemoryUsageInBytes = 0; this.stats = new Stats({id: this.url}); this._initializeStats(); // EXTRACTED FROM TILESET this._extensionsUsed = undefined; this.dynamicScreenSpaceErrorComputedDensity = 0.0; // Updated based on the camera position and direction // Metadata for the entire tileset this.extras = null; this.asset = {}; this.credits = {}; this.description = this.options.description || ''; this._initializeTileSet(json); } /** Release resources */ destroy(): void { this._destroy(); } /** Is the tileset loaded (update needs to have been called at least once) */ isLoaded(): boolean { // Check that `_frameNumber !== 0` which means that update was called at least once return this._pendingCount === 0 && this._frameNumber !== 0; } get tiles(): object[] { return Object.values(this._tiles); } get frameNumber(): number { return this._frameNumber; } get queryParams(): string { if (!this._queryParamsString) { this._queryParamsString = getQueryParamString(this._queryParams); } return this._queryParamsString; } setProps(props: Tileset3DProps): void { this.options = {...this.options, ...props}; } /** @deprecated */ setOptions(options: Tileset3DProps): void { this.options = {...this.options, ...options}; } /** * Return a loadable tile url for a specific tile subpath * @param tilePath a tile subpath */ getTileUrl(tilePath: string): string { const isDataUrl = tilePath.startsWith('data:'); if (isDataUrl) { return tilePath; } return `${tilePath}${this.queryParams}`; } // TODO CESIUM specific hasExtension(extensionName: string): boolean { return Boolean(this._extensionsUsed && this._extensionsUsed.indexOf(extensionName) > -1); } /** * Update visible tiles relying on a list of viewports * @param viewports - list of viewports */ // eslint-disable-next-line max-statements, complexity update(viewports: any[]): void { if ('loadTiles' in this.options && !this.options.loadTiles) { return; } if (this.traverseCounter > 0) { return; } if (!viewports && this.lastUpdatedVieports) { viewports = this.lastUpdatedVieports; } else { this.lastUpdatedVieports = viewports; } if (!(viewports instanceof Array)) { viewports = [viewports]; } this._cache.reset(); this._frameNumber++; this.traverseCounter = viewports.length; const viewportsToTraverse: string[] = []; // First loop to decrement traverseCounter for (const viewport of viewports) { const id = viewport.id as string; if (this._needTraverse(id)) { viewportsToTraverse.push(id); } else { this.traverseCounter--; } } // Second loop to traverse for (const viewport of viewports) { const id = viewport.id as string; if (!this.roots[id]) { this.roots[id] = this._initializeTileHeaders(this.tileset, null); } if (!viewportsToTraverse.includes(id)) { continue; // eslint-disable-line no-continue } const frameState = getFrameState(viewport, this._frameNumber); this._traverser.traverse(this.roots[id], frameState, this.options); } } /** * Check if traversal is needed for particular viewport * @param {string} viewportId - id of a viewport * @return {boolean} */ _needTraverse(viewportId: string): boolean { let traverserId = viewportId; if (this.options.viewportTraversersMap) { traverserId = this.options.viewportTraversersMap[viewportId]; } if (traverserId !== viewportId) { return false; } return true; } /** * The callback to post-process tiles after traversal procedure * @param frameState - frame state for tile culling */ _onTraversalEnd(frameState: FrameState): void { const id = frameState.viewport.id; if (!this.frameStateData[id]) { this.frameStateData[id] = {selectedTiles: [], _requestedTiles: [], _emptyTiles: []}; } const currentFrameStateData = this.frameStateData[id]; const selectedTiles = Object.values(this._traverser.selectedTiles); currentFrameStateData.selectedTiles = selectedTiles; currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles); currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles); this.traverseCounter--; if (this.traverseCounter > 0) { return; } this._updateTiles(); } /** * Update tiles relying on data from all traversers */ _updateTiles(): void { this.selectedTiles = []; this._requestedTiles = []; this._emptyTiles = []; for (const frameStateKey in this.frameStateData) { const frameStateDataValue = this.frameStateData[frameStateKey]; this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles); this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles); this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles); } this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles); for (const tile of this.selectedTiles) { this._tiles[tile.id] = tile; } this._loadTiles(); this._unloadTiles(); this._updateStats(); } _tilesChanged(oldSelectedTiles, selectedTiles) { if (oldSelectedTiles.length !== selectedTiles.length) { return true; } const set1 = new Set(oldSelectedTiles.map((t) => t.id)); const set2 = new Set(selectedTiles.map((t) => t.id)); let changed = oldSelectedTiles.filter((x) => !set2.has(x.id)).length > 0; changed = changed || selectedTiles.filter((x) => !set1.has(x.id)).length > 0; return changed; } _loadTiles() { // Sort requests by priority before making any requests. // This makes it less likely this requests will be cancelled after being issued. // requestedTiles.sort((a, b) => a._priority - b._priority); for (const tile of this._requestedTiles) { if (tile.contentUnloaded) { // eslint-disable-next-line @typescript-eslint/no-floating-promises this._loadTile(tile); } } } _unloadTiles() { // unload tiles from cache when hit maximumMemoryUsage this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile)); } _updateStats() { let tilesRenderable = 0; let pointsRenderable = 0; for (const tile of this.selectedTiles) { if (tile.contentAvailable && tile.content) { tilesRenderable++; if (tile.content.pointCount) { pointsRenderable += tile.content.pointCount; } } } this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length; this.stats.get(TILES_RENDERABLE).count = tilesRenderable; this.stats.get(POINTS_COUNT).count = pointsRenderable; } _initializeTileSet(tilesetJson) { this.root = this._initializeTileHeaders(tilesetJson, null); // TODO CESIUM Specific if (this.type === TILESET_TYPE.TILES3D) { this._initializeCesiumTileset(tilesetJson); } if (this.type === TILESET_TYPE.I3S) { this._initializeI3STileset(); } // Calculate cartographicCenter & zoom props to help apps center view on tileset this._calculateViewProps(); } // Called during initialize Tileset to initialize the tileset's cartographic center (longitude, latitude) and zoom. _calculateViewProps() { const root = this.root as Tile3D; assert(root); const {center} = root.boundingVolume; // TODO - handle all cases if (!center) { // eslint-disable-next-line console.warn('center was not pre-calculated for the root tile'); this.cartographicCenter = new Vector3(); this.zoom = 1; return; } this.cartographicCenter = Ellipsoid.WGS84.cartesianToCartographic(center, new Vector3()); this.cartesianCenter = center; this.zoom = getZoomFromBoundingVolume(root.boundingVolume); } _initializeStats() { this.stats.get(TILES_TOTAL); this.stats.get(TILES_LOADING); this.stats.get(TILES_IN_MEMORY); this.stats.get(TILES_IN_VIEW); this.stats.get(TILES_RENDERABLE); this.stats.get(TILES_LOADED); this.stats.get(TILES_UNLOADED); this.stats.get(TILES_LOAD_FAILED); this.stats.get(POINTS_COUNT, 'memory'); this.stats.get(TILES_GPU_MEMORY, 'memory'); } // Installs the main tileset JSON file or a tileset JSON file referenced from a tile. // eslint-disable-next-line max-statements _initializeTileHeaders(tilesetJson, parentTileHeader) { // A tileset JSON file referenced from a tile may exist in a different directory than the root tileset. // Get the basePath relative to the external tileset. const rootTile = new Tile3D(this, tilesetJson.root, parentTileHeader); // resource // If there is a parentTileHeader, add the root of the currently loading tileset // to parentTileHeader's children, and update its depth. if (parentTileHeader) { parentTileHeader.children.push(rootTile); rootTile.depth = parentTileHeader.depth + 1; } // Cesium 3d tiles knows the hierarchy beforehand if (this.type === TILESET_TYPE.TILES3D) { const stack: Tile3D[] = []; stack.push(rootTile); while (stack.length > 0) { const tile = stack.pop() as Tile3D; this.stats.get(TILES_TOTAL).incrementCount(); const children = tile.header.children || []; for (const childHeader of children) { const childTile = new Tile3D(this, childHeader, tile); tile.children.push(childTile); childTile.depth = tile.depth + 1; stack.push(childTile); } } } return rootTile; } _initializeTraverser() { let TraverserClass; const type = this.type; switch (type) { case TILESET_TYPE.TILES3D: TraverserClass = Tileset3DTraverser; break; case TILESET_TYPE.I3S: TraverserClass = I3SetTraverser; break; default: TraverserClass = TilesetTraverser; } return new TraverserClass({ basePath: this.basePath, onTraversalEnd: this._onTraversalEnd.bind(this) }); } _destroyTileHeaders(parentTile) { this._destroySubtree(parentTile); } async _loadTile(tile) { let loaded; try { this._onStartTileLoading(); loaded = await tile.loadContent(); } catch (error) { this._onTileLoadError(tile, error); } finally { this._onEndTileLoading(); this._onTileLoad(tile, loaded); } } _onTileLoadError(tile, error) { this.stats.get(TILES_LOAD_FAILED).incrementCount(); const message = error.message || error.toString(); const url = tile.url; // TODO - Allow for probe log to be injected instead of console? console.error(`A 3D tile failed to load: ${tile.url} ${message}`); // eslint-disable-line this.options.onTileError(tile, message, url); } _onTileLoad(tile, loaded) { if (!loaded) { return; } // add coordinateOrigin and modelMatrix to tile if (tile && tile.content) { calculateTransformProps(tile, tile.content); } this._addTileToCache(tile); this.options.onTileLoad(tile); } _onStartTileLoading() { this._pendingCount++; this.stats.get(TILES_LOADING).incrementCount(); } _onEndTileLoading() { this._pendingCount--; this.stats.get(TILES_LOADING).decrementCount(); } _addTileToCache(tile) { this._cache.add(this, tile, (tileset) => tileset._updateCacheStats(tile)); } _updateCacheStats(tile) { this.stats.get(TILES_LOADED).incrementCount(); this.stats.get(TILES_IN_MEMORY).incrementCount(); // Good enough? Just use the raw binary ArrayBuffer's byte length. this.gpuMemoryUsageInBytes += tile.content.byteLength || 0; this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes; } _unloadTile(tile) { this.gpuMemoryUsageInBytes -= (tile.content && tile.content.byteLength) || 0; this.stats.get(TILES_IN_MEMORY).decrementCount(); this.stats.get(TILES_UNLOADED).incrementCount(); this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes; this.options.onTileUnload(tile); tile.unloadContent(); } // Traverse the tree and destroy all tiles _destroy() { const stack: Tile3D[] = []; if (this.root) { stack.push(this.root); } while (stack.length > 0) { const tile: Tile3D = stack.pop() as Tile3D; for (const child of tile.children) { stack.push(child); } this._destroyTile(tile); } this.root = null; } // Traverse the tree and destroy all sub tiles _destroySubtree(tile) { const root = tile; const stack: Tile3D[] = []; stack.push(root); while (stack.length > 0) { tile = stack.pop(); for (const child of tile.children) { stack.push(child); } if (tile !== root) { this._destroyTile(tile); } } root.children = []; } _destroyTile(tile) { this._cache.unloadTile(this, tile); this._unloadTile(tile); tile.destroy(); } _initializeCesiumTileset(tilesetJson) { this.asset = tilesetJson.asset; if (!this.asset) { throw new Error('Tileset must have an asset property.'); } if (this.asset.version !== '0.0' && this.asset.version !== '1.0') { throw new Error('The tileset must be 3D Tiles version 0.0 or 1.0.'); } // Note: `asset.tilesetVersion` is version of the tileset itself (not the version of the 3D TILES standard) // We add this version as a `v=1.0` query param to fetch the right version and not get an older cached version if ('tilesetVersion' in this.asset) { this._queryParams.v = this.asset.tilesetVersion; } // TODO - ion resources have a credits property we can use for additional attribution. this.credits = { attributions: this.options.attributions || [] }; this.description = this.options.description || ''; // Gets the tileset's properties dictionary object, which contains metadata about per-feature properties. this.properties = tilesetJson.properties; this.geometricError = tilesetJson.geometricError; this._extensionsUsed = tilesetJson.extensionsUsed; // Returns the extras property at the top of the tileset JSON (application specific metadata). this.extras = tilesetJson.extras; } _initializeI3STileset() { if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) { this._queryParams.token = this.loadOptions.i3s.token; } } } function getQueryParamString(queryParams): string { const queryParamStrings: string[] = []; for (const key of Object.keys(queryParams)) { queryParamStrings.push(`${key}=${queryParams[key]}`); } switch (queryParamStrings.length) { case 0: return ''; case 1: return `?${queryParamStrings[0]}`; default: return `?${queryParamStrings.join('&')}`; } }
the_stack
import assign from 'lodash/assign'; import concat from 'lodash/concat'; import deburr from 'lodash/deburr'; import each from 'lodash/each'; import get from 'lodash/get'; import greaterThan from 'lodash/gt'; import greaterOrEqualTo from 'lodash/gte'; import includes from 'lodash/includes'; import isArray from 'lodash/isArray'; import isBoolean from 'lodash/isBoolean'; import isEmpty from 'lodash/isEmpty'; import isEqual from 'lodash/isEqual'; import isFinite from 'lodash/isFinite'; import isFunction from 'lodash/isFunction'; import isInteger from 'lodash/isInteger'; import isNaN from 'lodash/isNaN'; import isNil from 'lodash/isNil'; import isNull from 'lodash/isNull'; import isNumber from 'lodash/isNumber'; import isObject from 'lodash/isObject'; import isString from 'lodash/isString'; import isUndefined from 'lodash/isUndefined'; import lessThan from 'lodash/lt'; import lessOrEqualTo from 'lodash/lte'; import pick from 'lodash/pick'; import set from 'lodash/set'; import size from 'lodash/size'; import split from 'lodash/split'; import stubTrue from 'lodash/stubTrue'; import template from 'lodash/template'; import toLower from 'lodash/toLower'; import toNumber from 'lodash/toNumber'; import * as dates from 'date-fns'; import { format as formatDate, isAfter as isAfterDate, isBefore as isBeforeDate, isValid as isValidDate, } from "date-fns"; // eslint-disable-next-line @typescript-eslint/camelcase import {Bundle, en_us} from './locale'; import isAlpha from 'validator/lib/isAlpha'; import isAlphanumeric from 'validator/lib/isAlphanumeric'; import isBase64 from 'validator/lib/isBase64'; import isCreditCard from 'validator/lib/isCreditCard'; import isEmail from 'validator/lib/isEmail'; import isIP from 'validator/lib/isIP'; import isISO8601 from 'validator/lib/isISO8601'; import isJSON from 'validator/lib/isJSON'; import isURL from 'validator/lib/isURL'; import isUUID from 'validator/lib/isUUID'; import Model from '../Structures/Model'; // Parses any given value as a date. const parseDate = (value: any, format?: string): Date => { if (isString(value)) { return format ? dates.parse(value, format, new Date()) : dates.parseISO(value); } else { return dates.toDate(value); } }; // We want to set the messages a superglobal so that imports across files // reference the same messages object. let _global = typeof window !== 'undefined' ? window : (global || {}); class GlobalMessages { $locale!: string; $fallback!: string; $locales!: Record<string, Bundle>; constructor() { this.reset(); } /** * Resets everything to the default configuration. */ reset(): void { this.$locale = 'en-us'; this.$fallback = 'en-us'; this.$locales = {}; this.register(en_us); } /** * Sets the active locale. * * @param {string} locale */ locale(locale: string): void { this.$locale = toLower(locale); } /** * Registers a language pack. */ register(bundle: Bundle): void { let locale: string = toLower(bundle.locale); each(get(bundle, 'messages', {}), (message, name): void => { set(this.$locales, [locale, name], template(message)); }); } /** * Replaces or adds a new message for a given name and optional locale. * * @param {string} name * @param {string} format * @param {string} locale */ set(name: string, format: string, locale: string): void { let $template: _.TemplateExecutor = isString(format) ? template(format) : format; // Use the given locale. if (locale) { set(this.$locales, [locale, name], $template); // Otherwise use the active locale. } else if (this.$locale) { set(this.$locales, [this.$locale, name], $template); // Otherwise fall back to the default locale. } else { set(this.$locales, [this.$fallback, name], $template); } } /** * Returns a formatted string for a given message name and context data. * * @param {string} name * @param {Object} data * * @returns {string} The formatted message. */ get(name: string, data: Record<string, any> = {}): string { // Attempt to find the name using the active locale, falling back to the // active locale's language, and finally falling back to the default. let template: _.TemplateExecutor = get(this.$locales, [this.$locale, name], get(this.$locales, [split(this.$locale, '-')[0], name], get(this.$locales, [this.$fallback, name]))); // Fall back to a blank string so that we don't potentially // leak message names or context data into the template. if (!template) { return ''; } return template(data); } } /** * Global validation message registry. */ export const messages = // eslint-disable-next-line @typescript-eslint/camelcase _global.__vuemc_validation_messages = _global.__vuemc_validation_messages || new GlobalMessages(); /** * Rule helpers for easy validation. * These can all be used directly in a model's validation configuration. * * @example * * import {ascii, length} from 'vue-mc/validation' * * class User extends Model { * validation() { * return { * password: ascii.and(length(6)), * } * } * } */ /** * Creates a new validation rule. * * Rules returned by this function can be chained with `or` and `and`. * For example: `ruleA.or(ruleB.and(RuleC)).and(RuleD)` * * The error message can be set or replaced using `format(message|template)`. * * @param {Object} config: * - name: Name of the error message. * - data: Context for the error message. * - test: Function accepting (value, model), which should * return `true` if the value is valid. * * @returns {Function} Validation rule. */ export const rule: RuleFunction = function (config: Config): Rule { let name: string = get(config, 'name'); let data: Record<string, any> = get(config, 'data', {}) as Record<string, any>; let test: TestFunction = get(config, 'test', stubTrue); /** * This is the function that is called when using this rule. * It has some extra metadata to allow rule chaining and custom formats. */ // The @ts-ignore is for missing properties which are assigned at the end of this function. // @ts-ignore let $rule: Rule = function (value: any, attribute: string, model: Model): string | true { // `true` if this rule's core acceptance criteria was met. let valid: boolean = test(value, attribute, model); // If valid, check that all rules in the "and" chain also pass. if (valid) { for (let _and of $rule._and) { let result: string | boolean = _and(value, attribute, model); // If any of the chained rules return a string, we know that // that rule has failed, and therefore this chain is invalid. if (isString(result)) { return result; } } // Either there weren't any "and" rules or they all passed. return true; // This rule's acceptance criteria was not met, but there is a chance // that a rule in the "or" chain's might pass. } else { for (let _or of $rule._or) { let result: string | boolean = _or(value, attribute, model); // A rule should either return true in the event of a general // "pass", or nothing at all. A failure would have to be a // string message (usually from another rule). if (result === true || isUndefined(result)) { return true; } } } // At this point we want to report that this rule has failed, because // none of the "and" or "or" chains passed either. // Add the invalid value to the message context, which is made available // to all rules by default. This allows for ${value} interpolation. assign(data, {attribute, value}); // This would be a custom format explicitly set on this rule. let format: string | _.TemplateExecutor | null = get($rule, '_format'); // Use the default message if an explicit format isn't set. if (!format) { return messages.get(name, data); } // Replace the custom format with a template if it's still a string. if (isString(format)) { $rule._format = format = template(format); } return format(data); }; /** * @returns {Function} A copy of this rule, so that appending to a chain or * setting a custom format doesn't modify the base rule. */ $rule.copy = (): Rule => { return assign(rule({name, test, data}), pick($rule, [ '_format', '_and', '_or', ])); }; /** * Sets a custom error message format on this rule. * * @param {string|Function} format */ $rule.format = (format: string | _.TemplateExecutor): Rule => { return assign($rule.copy(), {_format: format}); }; /** * Adds another rule or function to this rule's OR chain. If the given rule * passes when this one fails, this rule will return `true`. * * @param {Function|Function[]} rules One or more functions to add to the chain. */ $rule.or = (rules: Rule | Rule[]): Rule => { return assign($rule.copy(), {_or: concat($rule._or, rules)}); }; /** * Adds another rule or function to this rule's AND chain. If the given rule * fails when this one passes, this rule will return `false`. * * @param {Function|Function[]} rules One or more functions to add to the chain. */ $rule.and = (rules: Rule | Rule[]): Rule => { return assign($rule.copy(), {_and: concat($rule._and, rules)}); }; $rule._and = []; // "and" chain $rule._or = []; // "or" chain $rule._format = null; // Custom format return $rule; }; /** * AVAILABLE RULES */ /** * Checks if the value is after a given date string or `Date` object. */ export const after = function (date: Date): Rule { return rule({ name: 'after', data: {date}, test: (value: string | number | Date): boolean => isAfterDate(parseDate(value), parseDate(date)), }); }; /** * Checks if a value only has letters. */ export const alpha: Rule = rule({ name: 'alpha', test: (value: any): boolean => { return isString(value) && isAlpha(deburr(value)); }, }); /** * Checks if a value only has letters or numbers. */ export const alphanumeric: Rule = rule({ name: 'alphanumeric', test: (value: any): boolean => { return isString(value) && isAlphanumeric(deburr(value)); }, }); /** * Checks if a value is an array. */ export const array: Rule = rule({ name: 'array', test: isArray, }); /** * Checks if a value is a string consisting only of ASCII characters. */ export const ascii: Rule = rule({ name: 'ascii', test: (value: any): boolean => isString(value) && /^[\x00-\x7F]+$/.test(value), }); /** * Checks if a value is a valid Base64 string. */ export const base64: Rule = rule({ name: 'base64', test: (value: any): boolean => isString(value) && isBase64(value), }); /** * Checks if a value is before a given date string or `Date` object. */ export const before = function (date: Date): Rule { return rule({ name: 'before', data: {date}, test: (value: string | number | Date): boolean => isBeforeDate(parseDate(value), parseDate(date)), }); }; /** * Checks if a value is between a given minimum or maximum, inclusive by default. */ export const between: RuleFunction = function (min: string | number | Date, max: string | number | Date, inclusive: boolean = true): Rule { let _min: string | number | Date = +(isString(min) ? parseDate(min) : min); let _max: string | number | Date = +(isString(max) ? parseDate(max) : max); return rule({ data: {min, max}, name: inclusive ? 'between_inclusive' : 'between', test: (value: any): boolean => { let _value: number = +(isString(value) ? parseDate(value) : value); return inclusive ? greaterOrEqualTo(_value, _min) && lessOrEqualTo(_value, _max) : greaterThan(_value, _min) && lessThan(_value, _max); }, }); }; /** * Checks if a value is a boolean (strictly true or false). */ export const boolean: Rule = rule({ name: 'boolean', test: isBoolean, }); /** * Checks if a value is a valid credit card number. */ export const creditcard: Rule = rule({ name: 'creditcard', test: (value: any): boolean => isString(value) && isCreditCard(value), }); /** * Checks if a value is parseable as a date. */ export const date: Rule = rule({ name: 'date', test: (value: string | number | Date): boolean => { return isValidDate(parseDate(value)); }, }); /** * Checks if a value matches the given date format. * * @see https://date-fns.org/v2.0.0-alpha.9/docs/format */ export const dateformat: RuleFunction = function (format): Rule { return rule({ name: 'dateformat', data: {format}, test: (value: string): boolean => { try { return isValidDate(parseDate(value.toString(), format)) && formatDate(parseDate(value.toString(), format), format) === value.toString(); } catch (error) { if (error instanceof RangeError) { return false; } else { throw error; } } }, }); }; /** * Checks if a value is not `undefined` */ export const defined: Rule = rule({ name: 'defined', test: (value: any): boolean => !isUndefined(value), }); /** * Checks if a value is a valid email address. */ export const email: Rule = rule({ name: 'email', test: (value: any): boolean => isString(value) && isEmail(value), }); /** * Checks if value is considered empty. * * @see https://lodash.com/docs/#isEmpty */ export const empty: Rule = rule({ name: 'empty', test: isEmpty, }); /** * Checks if a value equals the given value. */ export const equals: RuleFunction = function (other): Rule { return rule({ name: 'equals', data: {other}, test: (value: any): boolean => isEqual(value, other), }); }; /** * Alias for `equals` */ export const equal: RuleFunction = function (other): Rule { return equals(other); }; /** * Checks if a value is greater than a given minimum. */ export const gt: RuleFunction = function (min): Rule { return rule({ name: 'gt', data: {min}, test: (value: any): boolean => greaterThan(value, min), }); }; /** * Checks if a value is greater than or equal to a given minimum. */ export const gte: RuleFunction = function (min): Rule { return rule({ name: 'gte', data: {min}, test: (value: any): boolean => greaterOrEqualTo(value, min), }); }; /** * Checks if a value is an integer. */ export const integer: Rule = rule({ name: 'integer', test: isInteger, }); /** * Checks if a value is a valid IP address. */ export const ip: Rule = rule({ name: 'ip', test: (value: any): boolean => isString(value) && isIP(value), }); /** * Checks if a value is a zero-length string. */ export const isblank: Rule = rule({ name: 'isblank', test: (value: any): boolean => value === '', }); /** * Checks if a value is `null` or `undefined`. */ export const isnil: Rule = rule({ name: 'isnil', test: isNil, }); /** * Checks if a value is `null`. */ export const isnull: Rule = rule({ name: 'isnull', test: isNull, }); /** * Checks if a value is a valid ISO8601 date string. */ export const iso8601: Rule = rule({ name: 'iso8601', test: (value: any): boolean => isString(value) && isISO8601(value), }); /** * Checks if a value is valid JSON. */ export const json: Rule = rule({ name: 'json', test: (value: any): boolean => isString(value) && isJSON(value), }); /** * Checks if a value's length is at least a given minimum, and no more than an * optional maximum. * * @see https://lodash.com/docs/#toLength */ export const length: RuleFunction = function (min: number, max: number): Rule { // No maximum means the value must be *at least* the minimum. if (isUndefined(max)) { return rule({ name: 'length', data: {min, max}, test: (value?: string | object | null): boolean => size(value) >= min, }); } // Minimum and maximum given, so check that the value is within the range. return rule({ name: 'length_between', data: {min, max}, test: (value?: string | object | null): boolean => { let length: number = size(value); return length >= min && length <= max; }, }); }; /** * Checks if a value is less than a given maximum. */ export const lt: RuleFunction = function (max): Rule { return rule({ name: 'lt', data: {max}, test: (value: any): boolean => lessThan(value, max), }); }; /** * Checks if a value is less than or equal to a given maximum. */ export const lte: RuleFunction = function (max: any): Rule { return rule({ name: 'lte', data: {max}, test: (value: any): boolean => lessOrEqualTo(value, max), }); }; /** * Checks if a value matches a given regular expression string or RegExp. */ export const match: RuleFunction = function (pattern: string | RegExp): Rule { return rule({ name: 'match', data: {pattern}, test: (value: string): boolean => (new RegExp(pattern)).test(value), }); }; /** * Alias for `lte`. */ export const max: RuleFunction = function (max: any): Rule { return lte(max); }; /** * Alias for `gte`. */ export const min: RuleFunction = function (min: any): Rule { return gte(min); }; /** * Checks if a value is negative. */ export const negative: Rule = rule({ name: 'negative', test: (value: any): boolean => toNumber(value) < 0, }); /** * */ export const not: RuleFunction = function (...values: any[]): Rule { return rule({ name: 'not', test: (value: any): boolean => !includes(values, value), }); }; /** * Checks if a value is a number (integer or float), excluding `NaN`. */ export const number: Rule = rule({ name: 'number', test: (value: any): boolean => isFinite(value), }); /** * Checks if a value is a number or numeric string, excluding `NaN`. */ export const numeric: Rule = rule({ name: 'numeric', test: (value: any): boolean => { return (isNumber(value) && !isNaN(value)) || (value && isString(value) && !isNaN(toNumber(value))); }, }); /** * Checks if a value is an object, excluding arrays and functions. */ export const object: Rule = rule({ name: 'object', test: (value: any): boolean => { return isObject(value) && !isArray(value) && !isFunction(value); }, }); /** * Checks if a value is positive. */ export const positive: Rule = rule({ name: 'positive', test: (value: any): boolean => toNumber(value) > 0, }); /** * Checks if a value is present, ie. not `null`, `undefined`, or a blank string. */ export const required: Rule = rule({ name: 'required', test: (value: any): boolean => !(isNil(value) || value === ''), }); /** * Checks if a value equals another attribute's value. */ export const same: RuleFunction = function (other: string): Rule { return rule({ name: 'same', data: {other}, test: (value: any, attribute: string, model: Model): boolean => isEqual(value, model.get(other)), }); }; /** * Checks if a value is a string. */ export const string: Rule = rule({ name: 'string', test: isString, }); /** * Checks if a value is a valid URL string. */ export const url: Rule = rule({ name: 'url', test: (value: any): boolean => isString(value) && isURL(value), }); /** * Checks if a value is a valid UUID. */ export const uuid: Rule = rule({ name: 'uuid', test: (value: any): boolean => isString(value) && isUUID(value), }); declare global { interface Window { __vuemc_validation_messages: GlobalMessages; } // eslint-disable-next-line @typescript-eslint/no-namespace namespace NodeJS { interface Global { __vuemc_validation_messages: GlobalMessages; } } } interface Config { name: string; data?: Record<string, any>; test: TestFunction; } type TestFunction = (value: any, attribute?: string, model?: Model) => boolean; export interface Rule { (value: any, attribute?: string, model?: Model): true | string; _and: Rule[]; _or: Rule[]; _format: string | _.TemplateExecutor | null; copy(): Rule; format(format: string | _.TemplateExecutor): Rule; and(rule: Rule | Rule[]): Rule; or(rule: Rule | Rule[]): Rule; } type RuleFunction = (...params: any[]) => Rule;
the_stack
* This is an autogenerated file created by the Stencil compiler. * It contains typing information for all components that exist in this project. */ import '@stencil/core'; import { SelectOption, TreeItem, } from './shared/interfaces'; import { SelectOption as SelectOption2, } from './draft-components/shared/interfaces'; import { Column, } from './draft-components/grid/grid-helpers'; import { RowSelectionPattern, } from './draft-components/grid/row'; import { Column as Column2, } from './draft-components/gridv2/grid-helpers'; import { RowSelectionPattern as RowSelectionPattern2, } from './draft-components/gridv2/row'; export namespace Components { interface SuiCombobox { /** * Whether the combobox should filter based on user input. Defaults to false. */ 'filter': boolean; /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface SuiComboboxAttributes extends StencilHTMLAttributes { /** * Whether the combobox should filter based on user input. Defaults to false. */ 'filter'?: boolean; /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface SuiDisclosure { /** * Optional override to the button's accessible name (using aria-label) */ 'buttonLabel': string; /** * Optionally set the popup region's accessible name using aria-label (recommended) */ 'popupLabel': string; /** * Set the position of the disclosure, defaults to left */ 'position': 'left' | 'right'; } interface SuiDisclosureAttributes extends StencilHTMLAttributes { /** * Optional override to the button's accessible name (using aria-label) */ 'buttonLabel'?: string; /** * Emit a custom close event when the popup closes */ 'onClose'?: (event: CustomEvent) => void; /** * Emit a custom open event when the popup opens */ 'onOpen'?: (event: CustomEvent) => void; /** * Optionally set the popup region's accessible name using aria-label (recommended) */ 'popupLabel'?: string; /** * Set the position of the disclosure, defaults to left */ 'position'?: 'left' | 'right'; } interface SuiModal { 'customFocusId': string; /** * Optional id to use as descriptive text for the dialog */ 'describedBy': string; /** * Properties for Usability test case behaviors: */ 'focusTarget': 'close' | 'wrapper' | 'custom'; /** * Optionally give the modal a header, also used as the accessible name */ 'heading': string; /** * Whether the modal is open or closed */ 'open': boolean; } interface SuiModalAttributes extends StencilHTMLAttributes { 'customFocusId'?: string; /** * Optional id to use as descriptive text for the dialog */ 'describedBy'?: string; /** * Properties for Usability test case behaviors: */ 'focusTarget'?: 'close' | 'wrapper' | 'custom'; /** * Optionally give the modal a header, also used as the accessible name */ 'heading'?: string; /** * Emit a custom close event when the modal closes */ 'onClose'?: (event: CustomEvent) => void; /** * Whether the modal is open or closed */ 'open'?: boolean; } interface SuiMultiselect { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface SuiMultiselectAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface SuiSelect { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface SuiSelectAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface SuiTabs { /** * Array of ids that point to tab content. These should correspond to the array of tabs. */ 'contentIds': string[]; /** * Optionally control which tab should be displayed on load (defaults to the first tab) */ 'initialTab': number; /** * Array of tabs */ 'tabs': string[]; } interface SuiTabsAttributes extends StencilHTMLAttributes { /** * Array of ids that point to tab content. These should correspond to the array of tabs. */ 'contentIds'?: string[]; /** * Optionally control which tab should be displayed on load (defaults to the first tab) */ 'initialTab'?: number; /** * Emit a custom open event when the popup opens */ 'onTabChange'?: (event: CustomEvent) => void; /** * Array of tabs */ 'tabs'?: string[]; } interface SuiTooltip { /** * Text to show within the tooltip */ 'content': string; /** * Optionally define tooltip position, defaults to "bottom" */ 'position': 'top' | 'bottom'; /** * Give the tooltip an id to reference from elsewhere */ 'tooltipId': string; } interface SuiTooltipAttributes extends StencilHTMLAttributes { /** * Text to show within the tooltip */ 'content'?: string; /** * Optionally define tooltip position, defaults to "bottom" */ 'position'?: 'top' | 'bottom'; /** * Give the tooltip an id to reference from elsewhere */ 'tooltipId'?: string; } interface BatchAnnouncer { /** * Desired announcement */ 'announcement': string; /** * Desired batch time in milliseconds, defaults to 5000ms. If set to 0, it will never announce */ 'batchDelay': number; } interface BatchAnnouncerAttributes extends StencilHTMLAttributes { /** * Desired announcement */ 'announcement'?: string; /** * Desired batch time in milliseconds, defaults to 5000ms. If set to 0, it will never announce */ 'batchDelay'?: number; } interface ComboAutocomplete { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface ComboAutocompleteAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface ComboAutoselect { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface ComboAutoselectAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface ComboEleven { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface ComboElevenAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface ComboFilter { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface ComboFilterAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface ComboNative { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; /** * boolean required */ 'required': boolean; } interface ComboNativeAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; /** * boolean required */ 'required'?: boolean; } interface ComboNofilter { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface ComboNofilterAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface ComboNoinput { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface ComboNoinputAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface ComboReadonly { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface ComboReadonlyAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface ComboTwelve { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface ComboTwelveAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface ModalDisclosure { /** * Optional override to the button's accessible name (using aria-label) */ 'buttonLabel': string; /** * Optionally set the popup region's accessible name using aria-label (recommended) */ 'popupLabel': string; /** * Set the position of the disclosure, defaults to left */ 'position': 'left' | 'right'; } interface ModalDisclosureAttributes extends StencilHTMLAttributes { /** * Optional override to the button's accessible name (using aria-label) */ 'buttonLabel'?: string; /** * Emit a custom close event when the popup closes */ 'onClose'?: (event: CustomEvent) => void; /** * Emit a custom open event when the popup opens */ 'onOpen'?: (event: CustomEvent) => void; /** * Optionally set the popup region's accessible name using aria-label (recommended) */ 'popupLabel'?: string; /** * Set the position of the disclosure, defaults to left */ 'position'?: 'left' | 'right'; } interface FilterList { /** * Data for the filterable items */ 'items': string[]; /** * Label for the filter input */ 'label': string; /** * Optional heading for list of items */ 'listTitle': string; /** * Custom render function for */ 'renderItem': (item: string) => JSX.Element; /** * Control frequency of live region announcements */ 'verbosity': 'high' | 'medium' | 'low'; } interface FilterListAttributes extends StencilHTMLAttributes { /** * Data for the filterable items */ 'items'?: string[]; /** * Label for the filter input */ 'label'?: string; /** * Optional heading for list of items */ 'listTitle'?: string; /** * Emit a custom event when the list updates */ 'onUpdate'?: (event: CustomEvent) => void; /** * Custom render function for */ 'renderItem'?: (item: string) => JSX.Element; /** * Control frequency of live region announcements */ 'verbosity'?: 'high' | 'medium' | 'low'; } interface SuiGrid { /** * Grid data */ 'cells': string[][]; /** * Column definitions */ 'columns': Column[]; /** * Caption/description for the grid */ 'description': string; 'editOnClick': boolean; /** * Properties for Usability test case behaviors: * */ 'editable': boolean; /** * Grid type: grids have controlled focus and fancy behavior, tables are simple static content */ 'gridType': 'grid' | 'table'; 'headerActionsMenu': boolean; /** * String ID of labelling element */ 'labelledBy': string; /** * Number of rows in one "page": used to compute pageUp/pageDown key behavior, and when paging is used */ 'pageLength': number; /** * Custom function to control the render of cell content */ 'renderCustomCell': (content: string, colIndex: number, rowIndex: number) => string | HTMLElement; 'rowSelection': RowSelectionPattern; 'simpleEditable': boolean; /** * Index of the column that best labels a row */ 'titleColumn': number; 'useApplicationRole': boolean; } interface SuiGridAttributes extends StencilHTMLAttributes { /** * Grid data */ 'cells'?: string[][]; /** * Column definitions */ 'columns'?: Column[]; /** * Caption/description for the grid */ 'description'?: string; 'editOnClick'?: boolean; /** * Properties for Usability test case behaviors: * */ 'editable'?: boolean; /** * Grid type: grids have controlled focus and fancy behavior, tables are simple static content */ 'gridType'?: 'grid' | 'table'; 'headerActionsMenu'?: boolean; /** * String ID of labelling element */ 'labelledBy'?: string; /** * Emit a custom edit event when cell content change is submitted */ 'onEditCell'?: (event: CustomEvent<{value: string; column: number; row: number;}>) => void; /** * Emit a custom filter event */ 'onFilter'?: (event: CustomEvent) => void; /** * Emit a custom row selection event */ 'onRowSelect'?: (event: CustomEvent) => void; /** * Number of rows in one "page": used to compute pageUp/pageDown key behavior, and when paging is used */ 'pageLength'?: number; /** * Custom function to control the render of cell content */ 'renderCustomCell'?: (content: string, colIndex: number, rowIndex: number) => string | HTMLElement; 'rowSelection'?: RowSelectionPattern; 'simpleEditable'?: boolean; /** * Index of the column that best labels a row */ 'titleColumn'?: number; 'useApplicationRole'?: boolean; } interface SuiGridNew { /** * Grid data */ 'cells': string[][]; /** * Column definitions */ 'columns': Column[]; /** * Caption/description for the grid */ 'description': string; /** * Properties for Usability test case behaviors: * */ 'editable': boolean; /** * Grid type: grids have controlled focus and fancy behavior, tables are simple static content */ 'gridType': 'grid' | 'table'; 'headerActionsMenu': boolean; /** * String ID of labelling element */ 'labelledBy': string; 'modalCell': boolean; /** * Number of rows in one "page": used to compute pageUp/pageDown key behavior, and when paging is used */ 'pageLength': number; /** * Custom function to control the render of cell content */ 'renderCustomCell': (content: string, colIndex: number, rowIndex: number) => string | HTMLElement; 'rowSelection': RowSelectionPattern; /** * Index of the column that best labels a row */ 'titleColumn': number; } interface SuiGridNewAttributes extends StencilHTMLAttributes { /** * Grid data */ 'cells'?: string[][]; /** * Column definitions */ 'columns'?: Column[]; /** * Caption/description for the grid */ 'description'?: string; /** * Properties for Usability test case behaviors: * */ 'editable'?: boolean; /** * Grid type: grids have controlled focus and fancy behavior, tables are simple static content */ 'gridType'?: 'grid' | 'table'; 'headerActionsMenu'?: boolean; /** * String ID of labelling element */ 'labelledBy'?: string; 'modalCell'?: boolean; /** * Emit a custom edit event when cell content change is submitted */ 'onEditCell'?: (event: CustomEvent<{value: string; column: number; row: number;}>) => void; /** * Emit a custom filter event */ 'onFilter'?: (event: CustomEvent) => void; /** * Emit a custom row selection event */ 'onRowSelect'?: (event: CustomEvent) => void; /** * Emit a custom stepper value change event */ 'onStepperChange'?: (event: CustomEvent<{row: number; value: number}>) => void; /** * Number of rows in one "page": used to compute pageUp/pageDown key behavior, and when paging is used */ 'pageLength'?: number; /** * Custom function to control the render of cell content */ 'renderCustomCell'?: (content: string, colIndex: number, rowIndex: number) => string | HTMLElement; 'rowSelection'?: RowSelectionPattern; /** * Index of the column that best labels a row */ 'titleColumn'?: number; } interface ListboxActions { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; /** * Testing prop: whether or not the "recent searches" items should have secondary actions */ 'removeButton': 'inside' | 'outside' | undefined; } interface ListboxActionsAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; /** * Testing prop: whether or not the "recent searches" items should have secondary actions */ 'removeButton'?: 'inside' | 'outside' | undefined; } interface ListboxButton { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface ListboxButtonAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface ListboxExpand { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface ListboxExpandAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface MultiselectButtons { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface MultiselectButtonsAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface MultiselectButtonsTwo { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface MultiselectButtonsTwoAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface MultiselectCsv { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface MultiselectCsvAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface MultiselectInline { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface MultiselectInlineAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface MultiselectListbox { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; } interface MultiselectListboxAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; } interface MultiselectNative { /** * String label */ 'label': string; /** * Array of name/value options */ 'options': SelectOption[]; /** * boolean required */ 'required': boolean; } interface MultiselectNativeAttributes extends StencilHTMLAttributes { /** * String label */ 'label'?: string; /** * Emit a custom select event on value change */ 'onSelect'?: (event: CustomEvent) => void; /** * Array of name/value options */ 'options'?: SelectOption[]; /** * boolean required */ 'required'?: boolean; } interface SplitButton { /** * (Optional) pass a string to be the primary button id */ 'buttonId': string; /** * Optionally override the component's tabindex */ 'customTabIndex': 0 | 1; /** * Set to true if the button is within a compound widget like a toolbar or menu (changes arrow key behavior) */ 'inCompoundGroup': boolean; /** * Set the keyboard behavior of the splitbutton to be one tab/arrow stop or two (defaults to 2) */ 'isCompoundButton': boolean; /** * Set the accessible name for the button that opens the menu (recommended) */ 'menuButtonLabel': string; /** * Array of menu actions */ 'menuItems': any[]; /** * (Optional) set pressed to make the primary button into a toggle button */ 'pressed': boolean; /** * Optional custom render function for menu items (defaults to the menuItem string) */ 'renderMenuItem': (menItem: any) => string; } interface SplitButtonAttributes extends StencilHTMLAttributes { /** * (Optional) pass a string to be the primary button id */ 'buttonId'?: string; /** * Optionally override the component's tabindex */ 'customTabIndex'?: 0 | 1; /** * Set to true if the button is within a compound widget like a toolbar or menu (changes arrow key behavior) */ 'inCompoundGroup'?: boolean; /** * Set the keyboard behavior of the splitbutton to be one tab/arrow stop or two (defaults to 2) */ 'isCompoundButton'?: boolean; /** * Set the accessible name for the button that opens the menu (recommended) */ 'menuButtonLabel'?: string; /** * Array of menu actions */ 'menuItems'?: any[]; /** * Emit a custom event when a menu item is clicked */ 'onMenuAction'?: (event: CustomEvent) => void; /** * Emit a custom event when a menu item is clicked */ 'onPrimaryAction'?: (event: CustomEvent) => void; /** * (Optional) set pressed to make the primary button into a toggle button */ 'pressed'?: boolean; /** * Optional custom render function for menu items (defaults to the menuItem string) */ 'renderMenuItem'?: (menItem: any) => string; } interface TabActions { /** * Prop for support testing only: whether the tabs should be closeable + location of close button */ 'closeButton': 'inside' | 'outside' | undefined; /** * Array of ids that point to tab content. These should correspond to the array of tabs. */ 'contentIds': string[]; /** * Optionally control which tab should be displayed on load (defaults to the first tab) */ 'initialTab': number; /** * Array of tabs */ 'tabs': string[]; } interface TabActionsAttributes extends StencilHTMLAttributes { /** * Prop for support testing only: whether the tabs should be closeable + location of close button */ 'closeButton'?: 'inside' | 'outside' | undefined; /** * Array of ids that point to tab content. These should correspond to the array of tabs. */ 'contentIds'?: string[]; /** * Optionally control which tab should be displayed on load (defaults to the first tab) */ 'initialTab'?: number; /** * Emit a custom open event when the popup opens */ 'onTabChange'?: (event: CustomEvent) => void; /** * Array of tabs */ 'tabs'?: string[]; } interface TextareaCharcount { /** * Label for the textarea */ 'label': string; /** * Max number of characters */ 'maxLength': number; /** * Verbosity setting for screen reader behavior, defaults to medium */ 'verbosity': 'high' | 'medium' | 'low'; } interface TextareaCharcountAttributes extends StencilHTMLAttributes { /** * Label for the textarea */ 'label'?: string; /** * Max number of characters */ 'maxLength'?: number; /** * Emit a custom event when textarea's value exceeds the max length */ 'onError'?: (event: CustomEvent) => void; /** * Verbosity setting for screen reader behavior, defaults to medium */ 'verbosity'?: 'high' | 'medium' | 'low'; } interface SuiToolbar { /** * Array of CSS selectors for toolbar actions */ 'menuItems': string[]; /** * Set the accessible name for the button that opens the menu (recommended) */ 'toolbarLabel': string; } interface SuiToolbarAttributes extends StencilHTMLAttributes { /** * Array of CSS selectors for toolbar actions */ 'menuItems'?: string[]; /** * Set the accessible name for the button that opens the menu (recommended) */ 'toolbarLabel'?: string; } interface SuiTooltipArrow { /** * Text to show within the tooltip */ 'content': string; /** * Optionally define tooltip position, defaults to "bottom" */ 'position': 'top' | 'bottom'; /** * Give the tooltip an id to reference elsewhere */ 'tooltipId': string; /** * Custom width style, as a string including units */ 'width': string; } interface SuiTooltipArrowAttributes extends StencilHTMLAttributes { /** * Text to show within the tooltip */ 'content'?: string; /** * Optionally define tooltip position, defaults to "bottom" */ 'position'?: 'top' | 'bottom'; /** * Give the tooltip an id to reference elsewhere */ 'tooltipId'?: string; /** * Custom width style, as a string including units */ 'width'?: string; } interface SuiTooltipControl { /** * Text to show within the tooltip */ 'content': string; /** * Optionally define tooltip position, defaults to "bottom" */ 'position': 'top' | 'bottom'; /** * Give the tooltip an id to reference elsewhere */ 'tooltipId': string; /** * Custom width style, as a string including units */ 'width': string; } interface SuiTooltipControlAttributes extends StencilHTMLAttributes { /** * Text to show within the tooltip */ 'content'?: string; /** * Optionally define tooltip position, defaults to "bottom" */ 'position'?: 'top' | 'bottom'; /** * Give the tooltip an id to reference elsewhere */ 'tooltipId'?: string; /** * Custom width style, as a string including units */ 'width'?: string; } interface SuiTooltipCorner { /** * Text to show within the tooltip */ 'content': string; /** * Optionally define tooltip position, defaults to "bottom" */ 'position': 'top' | 'bottom'; /** * Give the tooltip an id to reference elsewhere */ 'tooltipId': string; /** * Custom width style, as a string including units */ 'width': string; } interface SuiTooltipCornerAttributes extends StencilHTMLAttributes { /** * Text to show within the tooltip */ 'content'?: string; /** * Optionally define tooltip position, defaults to "bottom" */ 'position'?: 'top' | 'bottom'; /** * Give the tooltip an id to reference elsewhere */ 'tooltipId'?: string; /** * Custom width style, as a string including units */ 'width'?: string; } interface SuiTooltipEscape { /** * Optional selector to attach parent key events. Defaults to document */ 'containerSelector': string; /** * Text to show within the tooltip */ 'content': string; /** * Optionally define tooltip position, defaults to "bottom" */ 'position': 'top' | 'bottom'; /** * Give the tooltip an id to reference elsewhere */ 'tooltipId': string; /** * Custom width style, as a string including units */ 'width': string; } interface SuiTooltipEscapeAttributes extends StencilHTMLAttributes { /** * Optional selector to attach parent key events. Defaults to document */ 'containerSelector'?: string; /** * Text to show within the tooltip */ 'content'?: string; /** * Optionally define tooltip position, defaults to "bottom" */ 'position'?: 'top' | 'bottom'; /** * Give the tooltip an id to reference elsewhere */ 'tooltipId'?: string; /** * Custom width style, as a string including units */ 'width'?: string; } interface TreeActions { /** * Array of name/value options */ 'items': TreeItem[]; /** * Accessible name for tree */ 'label': string; /** * Include secondary actions inside or outside the treeitem For support testing only */ 'secondaryActions': 'inside' | 'outside' | undefined; } interface TreeActionsAttributes extends StencilHTMLAttributes { /** * Array of name/value options */ 'items'?: TreeItem[]; /** * Accessible name for tree */ 'label'?: string; /** * Include secondary actions inside or outside the treeitem For support testing only */ 'secondaryActions'?: 'inside' | 'outside' | undefined; } } declare global { interface StencilElementInterfaces { 'SuiCombobox': Components.SuiCombobox; 'SuiDisclosure': Components.SuiDisclosure; 'SuiModal': Components.SuiModal; 'SuiMultiselect': Components.SuiMultiselect; 'SuiSelect': Components.SuiSelect; 'SuiTabs': Components.SuiTabs; 'SuiTooltip': Components.SuiTooltip; 'BatchAnnouncer': Components.BatchAnnouncer; 'ComboAutocomplete': Components.ComboAutocomplete; 'ComboAutoselect': Components.ComboAutoselect; 'ComboEleven': Components.ComboEleven; 'ComboFilter': Components.ComboFilter; 'ComboNative': Components.ComboNative; 'ComboNofilter': Components.ComboNofilter; 'ComboNoinput': Components.ComboNoinput; 'ComboReadonly': Components.ComboReadonly; 'ComboTwelve': Components.ComboTwelve; 'ModalDisclosure': Components.ModalDisclosure; 'FilterList': Components.FilterList; 'SuiGrid': Components.SuiGrid; 'SuiGridNew': Components.SuiGridNew; 'ListboxActions': Components.ListboxActions; 'ListboxButton': Components.ListboxButton; 'ListboxExpand': Components.ListboxExpand; 'MultiselectButtons': Components.MultiselectButtons; 'MultiselectButtonsTwo': Components.MultiselectButtonsTwo; 'MultiselectCsv': Components.MultiselectCsv; 'MultiselectInline': Components.MultiselectInline; 'MultiselectListbox': Components.MultiselectListbox; 'MultiselectNative': Components.MultiselectNative; 'SplitButton': Components.SplitButton; 'TabActions': Components.TabActions; 'TextareaCharcount': Components.TextareaCharcount; 'SuiToolbar': Components.SuiToolbar; 'SuiTooltipArrow': Components.SuiTooltipArrow; 'SuiTooltipControl': Components.SuiTooltipControl; 'SuiTooltipCorner': Components.SuiTooltipCorner; 'SuiTooltipEscape': Components.SuiTooltipEscape; 'TreeActions': Components.TreeActions; } interface StencilIntrinsicElements { 'sui-combobox': Components.SuiComboboxAttributes; 'sui-disclosure': Components.SuiDisclosureAttributes; 'sui-modal': Components.SuiModalAttributes; 'sui-multiselect': Components.SuiMultiselectAttributes; 'sui-select': Components.SuiSelectAttributes; 'sui-tabs': Components.SuiTabsAttributes; 'sui-tooltip': Components.SuiTooltipAttributes; 'batch-announcer': Components.BatchAnnouncerAttributes; 'combo-autocomplete': Components.ComboAutocompleteAttributes; 'combo-autoselect': Components.ComboAutoselectAttributes; 'combo-eleven': Components.ComboElevenAttributes; 'combo-filter': Components.ComboFilterAttributes; 'combo-native': Components.ComboNativeAttributes; 'combo-nofilter': Components.ComboNofilterAttributes; 'combo-noinput': Components.ComboNoinputAttributes; 'combo-readonly': Components.ComboReadonlyAttributes; 'combo-twelve': Components.ComboTwelveAttributes; 'modal-disclosure': Components.ModalDisclosureAttributes; 'filter-list': Components.FilterListAttributes; 'sui-grid': Components.SuiGridAttributes; 'sui-grid-new': Components.SuiGridNewAttributes; 'listbox-actions': Components.ListboxActionsAttributes; 'listbox-button': Components.ListboxButtonAttributes; 'listbox-expand': Components.ListboxExpandAttributes; 'multiselect-buttons': Components.MultiselectButtonsAttributes; 'multiselect-buttons-two': Components.MultiselectButtonsTwoAttributes; 'multiselect-csv': Components.MultiselectCsvAttributes; 'multiselect-inline': Components.MultiselectInlineAttributes; 'multiselect-listbox': Components.MultiselectListboxAttributes; 'multiselect-native': Components.MultiselectNativeAttributes; 'split-button': Components.SplitButtonAttributes; 'tab-actions': Components.TabActionsAttributes; 'textarea-charcount': Components.TextareaCharcountAttributes; 'sui-toolbar': Components.SuiToolbarAttributes; 'sui-tooltip-arrow': Components.SuiTooltipArrowAttributes; 'sui-tooltip-control': Components.SuiTooltipControlAttributes; 'sui-tooltip-corner': Components.SuiTooltipCornerAttributes; 'sui-tooltip-escape': Components.SuiTooltipEscapeAttributes; 'tree-actions': Components.TreeActionsAttributes; } interface HTMLSuiComboboxElement extends Components.SuiCombobox, HTMLStencilElement {} var HTMLSuiComboboxElement: { prototype: HTMLSuiComboboxElement; new (): HTMLSuiComboboxElement; }; interface HTMLSuiDisclosureElement extends Components.SuiDisclosure, HTMLStencilElement {} var HTMLSuiDisclosureElement: { prototype: HTMLSuiDisclosureElement; new (): HTMLSuiDisclosureElement; }; interface HTMLSuiModalElement extends Components.SuiModal, HTMLStencilElement {} var HTMLSuiModalElement: { prototype: HTMLSuiModalElement; new (): HTMLSuiModalElement; }; interface HTMLSuiMultiselectElement extends Components.SuiMultiselect, HTMLStencilElement {} var HTMLSuiMultiselectElement: { prototype: HTMLSuiMultiselectElement; new (): HTMLSuiMultiselectElement; }; interface HTMLSuiSelectElement extends Components.SuiSelect, HTMLStencilElement {} var HTMLSuiSelectElement: { prototype: HTMLSuiSelectElement; new (): HTMLSuiSelectElement; }; interface HTMLSuiTabsElement extends Components.SuiTabs, HTMLStencilElement {} var HTMLSuiTabsElement: { prototype: HTMLSuiTabsElement; new (): HTMLSuiTabsElement; }; interface HTMLSuiTooltipElement extends Components.SuiTooltip, HTMLStencilElement {} var HTMLSuiTooltipElement: { prototype: HTMLSuiTooltipElement; new (): HTMLSuiTooltipElement; }; interface HTMLBatchAnnouncerElement extends Components.BatchAnnouncer, HTMLStencilElement {} var HTMLBatchAnnouncerElement: { prototype: HTMLBatchAnnouncerElement; new (): HTMLBatchAnnouncerElement; }; interface HTMLComboAutocompleteElement extends Components.ComboAutocomplete, HTMLStencilElement {} var HTMLComboAutocompleteElement: { prototype: HTMLComboAutocompleteElement; new (): HTMLComboAutocompleteElement; }; interface HTMLComboAutoselectElement extends Components.ComboAutoselect, HTMLStencilElement {} var HTMLComboAutoselectElement: { prototype: HTMLComboAutoselectElement; new (): HTMLComboAutoselectElement; }; interface HTMLComboElevenElement extends Components.ComboEleven, HTMLStencilElement {} var HTMLComboElevenElement: { prototype: HTMLComboElevenElement; new (): HTMLComboElevenElement; }; interface HTMLComboFilterElement extends Components.ComboFilter, HTMLStencilElement {} var HTMLComboFilterElement: { prototype: HTMLComboFilterElement; new (): HTMLComboFilterElement; }; interface HTMLComboNativeElement extends Components.ComboNative, HTMLStencilElement {} var HTMLComboNativeElement: { prototype: HTMLComboNativeElement; new (): HTMLComboNativeElement; }; interface HTMLComboNofilterElement extends Components.ComboNofilter, HTMLStencilElement {} var HTMLComboNofilterElement: { prototype: HTMLComboNofilterElement; new (): HTMLComboNofilterElement; }; interface HTMLComboNoinputElement extends Components.ComboNoinput, HTMLStencilElement {} var HTMLComboNoinputElement: { prototype: HTMLComboNoinputElement; new (): HTMLComboNoinputElement; }; interface HTMLComboReadonlyElement extends Components.ComboReadonly, HTMLStencilElement {} var HTMLComboReadonlyElement: { prototype: HTMLComboReadonlyElement; new (): HTMLComboReadonlyElement; }; interface HTMLComboTwelveElement extends Components.ComboTwelve, HTMLStencilElement {} var HTMLComboTwelveElement: { prototype: HTMLComboTwelveElement; new (): HTMLComboTwelveElement; }; interface HTMLModalDisclosureElement extends Components.ModalDisclosure, HTMLStencilElement {} var HTMLModalDisclosureElement: { prototype: HTMLModalDisclosureElement; new (): HTMLModalDisclosureElement; }; interface HTMLFilterListElement extends Components.FilterList, HTMLStencilElement {} var HTMLFilterListElement: { prototype: HTMLFilterListElement; new (): HTMLFilterListElement; }; interface HTMLSuiGridElement extends Components.SuiGrid, HTMLStencilElement {} var HTMLSuiGridElement: { prototype: HTMLSuiGridElement; new (): HTMLSuiGridElement; }; interface HTMLSuiGridNewElement extends Components.SuiGridNew, HTMLStencilElement {} var HTMLSuiGridNewElement: { prototype: HTMLSuiGridNewElement; new (): HTMLSuiGridNewElement; }; interface HTMLListboxActionsElement extends Components.ListboxActions, HTMLStencilElement {} var HTMLListboxActionsElement: { prototype: HTMLListboxActionsElement; new (): HTMLListboxActionsElement; }; interface HTMLListboxButtonElement extends Components.ListboxButton, HTMLStencilElement {} var HTMLListboxButtonElement: { prototype: HTMLListboxButtonElement; new (): HTMLListboxButtonElement; }; interface HTMLListboxExpandElement extends Components.ListboxExpand, HTMLStencilElement {} var HTMLListboxExpandElement: { prototype: HTMLListboxExpandElement; new (): HTMLListboxExpandElement; }; interface HTMLMultiselectButtonsElement extends Components.MultiselectButtons, HTMLStencilElement {} var HTMLMultiselectButtonsElement: { prototype: HTMLMultiselectButtonsElement; new (): HTMLMultiselectButtonsElement; }; interface HTMLMultiselectButtonsTwoElement extends Components.MultiselectButtonsTwo, HTMLStencilElement {} var HTMLMultiselectButtonsTwoElement: { prototype: HTMLMultiselectButtonsTwoElement; new (): HTMLMultiselectButtonsTwoElement; }; interface HTMLMultiselectCsvElement extends Components.MultiselectCsv, HTMLStencilElement {} var HTMLMultiselectCsvElement: { prototype: HTMLMultiselectCsvElement; new (): HTMLMultiselectCsvElement; }; interface HTMLMultiselectInlineElement extends Components.MultiselectInline, HTMLStencilElement {} var HTMLMultiselectInlineElement: { prototype: HTMLMultiselectInlineElement; new (): HTMLMultiselectInlineElement; }; interface HTMLMultiselectListboxElement extends Components.MultiselectListbox, HTMLStencilElement {} var HTMLMultiselectListboxElement: { prototype: HTMLMultiselectListboxElement; new (): HTMLMultiselectListboxElement; }; interface HTMLMultiselectNativeElement extends Components.MultiselectNative, HTMLStencilElement {} var HTMLMultiselectNativeElement: { prototype: HTMLMultiselectNativeElement; new (): HTMLMultiselectNativeElement; }; interface HTMLSplitButtonElement extends Components.SplitButton, HTMLStencilElement {} var HTMLSplitButtonElement: { prototype: HTMLSplitButtonElement; new (): HTMLSplitButtonElement; }; interface HTMLTabActionsElement extends Components.TabActions, HTMLStencilElement {} var HTMLTabActionsElement: { prototype: HTMLTabActionsElement; new (): HTMLTabActionsElement; }; interface HTMLTextareaCharcountElement extends Components.TextareaCharcount, HTMLStencilElement {} var HTMLTextareaCharcountElement: { prototype: HTMLTextareaCharcountElement; new (): HTMLTextareaCharcountElement; }; interface HTMLSuiToolbarElement extends Components.SuiToolbar, HTMLStencilElement {} var HTMLSuiToolbarElement: { prototype: HTMLSuiToolbarElement; new (): HTMLSuiToolbarElement; }; interface HTMLSuiTooltipArrowElement extends Components.SuiTooltipArrow, HTMLStencilElement {} var HTMLSuiTooltipArrowElement: { prototype: HTMLSuiTooltipArrowElement; new (): HTMLSuiTooltipArrowElement; }; interface HTMLSuiTooltipControlElement extends Components.SuiTooltipControl, HTMLStencilElement {} var HTMLSuiTooltipControlElement: { prototype: HTMLSuiTooltipControlElement; new (): HTMLSuiTooltipControlElement; }; interface HTMLSuiTooltipCornerElement extends Components.SuiTooltipCorner, HTMLStencilElement {} var HTMLSuiTooltipCornerElement: { prototype: HTMLSuiTooltipCornerElement; new (): HTMLSuiTooltipCornerElement; }; interface HTMLSuiTooltipEscapeElement extends Components.SuiTooltipEscape, HTMLStencilElement {} var HTMLSuiTooltipEscapeElement: { prototype: HTMLSuiTooltipEscapeElement; new (): HTMLSuiTooltipEscapeElement; }; interface HTMLTreeActionsElement extends Components.TreeActions, HTMLStencilElement {} var HTMLTreeActionsElement: { prototype: HTMLTreeActionsElement; new (): HTMLTreeActionsElement; }; interface HTMLElementTagNameMap { 'sui-combobox': HTMLSuiComboboxElement 'sui-disclosure': HTMLSuiDisclosureElement 'sui-modal': HTMLSuiModalElement 'sui-multiselect': HTMLSuiMultiselectElement 'sui-select': HTMLSuiSelectElement 'sui-tabs': HTMLSuiTabsElement 'sui-tooltip': HTMLSuiTooltipElement 'batch-announcer': HTMLBatchAnnouncerElement 'combo-autocomplete': HTMLComboAutocompleteElement 'combo-autoselect': HTMLComboAutoselectElement 'combo-eleven': HTMLComboElevenElement 'combo-filter': HTMLComboFilterElement 'combo-native': HTMLComboNativeElement 'combo-nofilter': HTMLComboNofilterElement 'combo-noinput': HTMLComboNoinputElement 'combo-readonly': HTMLComboReadonlyElement 'combo-twelve': HTMLComboTwelveElement 'modal-disclosure': HTMLModalDisclosureElement 'filter-list': HTMLFilterListElement 'sui-grid': HTMLSuiGridElement 'sui-grid-new': HTMLSuiGridNewElement 'listbox-actions': HTMLListboxActionsElement 'listbox-button': HTMLListboxButtonElement 'listbox-expand': HTMLListboxExpandElement 'multiselect-buttons': HTMLMultiselectButtonsElement 'multiselect-buttons-two': HTMLMultiselectButtonsTwoElement 'multiselect-csv': HTMLMultiselectCsvElement 'multiselect-inline': HTMLMultiselectInlineElement 'multiselect-listbox': HTMLMultiselectListboxElement 'multiselect-native': HTMLMultiselectNativeElement 'split-button': HTMLSplitButtonElement 'tab-actions': HTMLTabActionsElement 'textarea-charcount': HTMLTextareaCharcountElement 'sui-toolbar': HTMLSuiToolbarElement 'sui-tooltip-arrow': HTMLSuiTooltipArrowElement 'sui-tooltip-control': HTMLSuiTooltipControlElement 'sui-tooltip-corner': HTMLSuiTooltipCornerElement 'sui-tooltip-escape': HTMLSuiTooltipEscapeElement 'tree-actions': HTMLTreeActionsElement } interface ElementTagNameMap { 'sui-combobox': HTMLSuiComboboxElement; 'sui-disclosure': HTMLSuiDisclosureElement; 'sui-modal': HTMLSuiModalElement; 'sui-multiselect': HTMLSuiMultiselectElement; 'sui-select': HTMLSuiSelectElement; 'sui-tabs': HTMLSuiTabsElement; 'sui-tooltip': HTMLSuiTooltipElement; 'batch-announcer': HTMLBatchAnnouncerElement; 'combo-autocomplete': HTMLComboAutocompleteElement; 'combo-autoselect': HTMLComboAutoselectElement; 'combo-eleven': HTMLComboElevenElement; 'combo-filter': HTMLComboFilterElement; 'combo-native': HTMLComboNativeElement; 'combo-nofilter': HTMLComboNofilterElement; 'combo-noinput': HTMLComboNoinputElement; 'combo-readonly': HTMLComboReadonlyElement; 'combo-twelve': HTMLComboTwelveElement; 'modal-disclosure': HTMLModalDisclosureElement; 'filter-list': HTMLFilterListElement; 'sui-grid': HTMLSuiGridElement; 'sui-grid-new': HTMLSuiGridNewElement; 'listbox-actions': HTMLListboxActionsElement; 'listbox-button': HTMLListboxButtonElement; 'listbox-expand': HTMLListboxExpandElement; 'multiselect-buttons': HTMLMultiselectButtonsElement; 'multiselect-buttons-two': HTMLMultiselectButtonsTwoElement; 'multiselect-csv': HTMLMultiselectCsvElement; 'multiselect-inline': HTMLMultiselectInlineElement; 'multiselect-listbox': HTMLMultiselectListboxElement; 'multiselect-native': HTMLMultiselectNativeElement; 'split-button': HTMLSplitButtonElement; 'tab-actions': HTMLTabActionsElement; 'textarea-charcount': HTMLTextareaCharcountElement; 'sui-toolbar': HTMLSuiToolbarElement; 'sui-tooltip-arrow': HTMLSuiTooltipArrowElement; 'sui-tooltip-control': HTMLSuiTooltipControlElement; 'sui-tooltip-corner': HTMLSuiTooltipCornerElement; 'sui-tooltip-escape': HTMLSuiTooltipEscapeElement; 'tree-actions': HTMLTreeActionsElement; } export namespace JSX { export interface Element {} export interface IntrinsicElements extends StencilIntrinsicElements { [tagName: string]: any; } } export interface HTMLAttributes extends StencilHTMLAttributes {} }
the_stack
import * as tf from '../../index'; import {ALL_ENVS, describeWithFlags} from '../../jasmine_util'; import {expectArraysClose} from '../../test_util'; describeWithFlags('resizeNearestNeighbor', ALL_ENVS, () => { it('simple alignCorners=false', async () => { const input = tf.tensor3d([2, 2, 4, 4], [2, 2, 1]); const output = input.resizeNearestNeighbor([3, 3], false); expectArraysClose(await output.data(), [2, 2, 2, 2, 2, 2, 4, 4, 4]); }); it('simple alignCorners=true', async () => { const input = tf.tensor3d([2, 2, 4, 4], [2, 2, 1]); const output = input.resizeNearestNeighbor([3, 3], true); expectArraysClose(await output.data(), [2, 2, 2, 4, 4, 4, 4, 4, 4]); }); it('5x2To2x2 alignCorners=false halfPixelCenters=true', async () => { const input = tf.tensor4d([1, 2, 3, 4, 5, 1, 2, 3, 4, 5], [1, 2, 5, 1]); const output = input.resizeNearestNeighbor([2, 2], false, true); expectArraysClose(await output.data(), [2, 4, 2, 4]); }); it('2x2To1x1 alignCorners=false halfPixelCenters=true', async () => { const input = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); const output = input.resizeNearestNeighbor([1, 1], false, true); expectArraysClose(await output.data(), [4]); }); it('2x2To3x3 alignCorners=false halfPixelCenters=true', async () => { const input = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); const output = input.resizeNearestNeighbor([3, 3], false, true); expectArraysClose(await output.data(), [1, 2, 2, 3, 4, 4, 3, 4, 4]); }); it('3x3To2x2 alignCorners=false halfPixelCenters=true', async () => { const input = tf.tensor4d([1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 3, 3, 1]); const output = input.resizeNearestNeighbor([2, 2], false, true); expectArraysClose(await output.data(), [1, 3, 7, 9]); }); it('2x2To2x5 alignCorners=false halfPixelCenters=true', async () => { const input = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); const output = input.resizeNearestNeighbor([2, 5], false, true); expectArraysClose(await output.data(), [1, 1, 2, 2, 2, 3, 3, 4, 4, 4]); }); it('4x4To3x3 alignCorners=false halfPixelCenters=true', async () => { const input = tf.tensor4d( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [1, 4, 4, 1]); const output = input.resizeNearestNeighbor([3, 3], false, true); expectArraysClose(await output.data(), [1, 3, 4, 9, 11, 12, 13, 15, 16]); }); it('2x2To5x2 alignCorners=false halfPixelCenters=true', async () => { const input = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); const output = input.resizeNearestNeighbor([5, 2], false, true); expectArraysClose(await output.data(), [1, 2, 1, 2, 3, 4, 3, 4, 3, 4]); }); it('2x2To4x4 alignCorners=false halfPixelCenters=true', async () => { const input = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); const output = input.resizeNearestNeighbor([4, 4], false, true); expectArraysClose( await output.data(), [1, 1, 2, 2, 1, 1, 2, 2, 3, 3, 4, 4, 3, 3, 4, 4]); }); it('matches tensorflow w/ random numbers alignCorners=false', async () => { const input = tf.tensor3d( [ 1.19074044, 0.91373104, 2.01611669, -0.52270832, 0.38725395, 1.30809779, 0.61835143, 3.49600659, 2.09230986, 0.56473997, 0.03823943, 1.19864896 ], [2, 3, 2]); const output = input.resizeNearestNeighbor([4, 5], false); expectArraysClose(await output.data(), [ 1.19074047, 0.913731039, 1.19074047, 0.913731039, 2.01611662, -0.522708297, 2.01611662, -0.522708297, 0.38725394, 1.30809784, 1.19074047, 0.913731039, 1.19074047, 0.913731039, 2.01611662, -0.522708297, 2.01611662, -0.522708297, 0.38725394, 1.30809784, 0.61835146, 3.49600649, 0.61835146, 3.49600649, 2.09230995, 0.564739943, 2.09230995, 0.564739943, 0.0382394306, 1.19864893, 0.61835146, 3.49600649, 0.61835146, 3.49600649, 2.09230995, 0.564739943, 2.09230995, 0.564739943, 0.0382394306, 1.19864893 ]); }); it('matches tensorflow w/ random numbers alignCorners=true', async () => { const input = tf.tensor3d( [ 1.19074044, 0.91373104, 2.01611669, -0.52270832, 0.38725395, 1.30809779, 0.61835143, 3.49600659, 2.09230986, 0.56473997, 0.03823943, 1.19864896 ], [2, 3, 2]); const output = input.resizeNearestNeighbor([4, 5], true); expectArraysClose(await output.data(), [ 1.19074044, 0.91373104, 2.01611669, -0.52270832, 2.01611669, -0.52270832, 0.38725395, 1.30809779, 0.38725395, 1.30809779, 1.19074044, 0.91373104, 2.01611669, -0.52270832, 2.01611669, -0.52270832, 0.38725395, 1.30809779, 0.38725395, 1.30809779, 0.61835143, 3.49600659, 2.09230986, 0.56473997, 2.09230986, 0.56473997, 0.03823943, 1.19864896, 0.03823943, 1.19864896, 0.61835143, 3.49600659, 2.09230986, 0.56473997, 2.09230986, 0.56473997, 0.03823943, 1.19864896, 0.03823943, 1.19864896 ]); }); it('batch of 2, simple, alignCorners=true', async () => { const input = tf.tensor4d([2, 2, 4, 4, 3, 3, 5, 5], [2, 2, 2, 1]); const output = input.resizeNearestNeighbor([3, 3], true /* alignCorners */); expectArraysClose( await output.data(), [2, 2, 2, 4, 4, 4, 4, 4, 4, 3, 3, 3, 5, 5, 5, 5, 5, 5]); }); it('throws when passed a non-tensor', () => { const e = /Argument 'images' passed to 'resizeNearestNeighbor' must be a Tensor/; expect(() => tf.image.resizeNearestNeighbor({} as tf.Tensor3D, [ 1, 1 ])).toThrowError(e); }); it('accepts a tensor-like object', async () => { const input = [[[2], [2]], [[4], [4]]]; // 2x2x1 const output = tf.image.resizeNearestNeighbor(input, [3, 3], false); expectArraysClose(await output.data(), [2, 2, 2, 2, 2, 2, 4, 4, 4]); }); it('does not throw when some output dim is 1 and alignCorners=true', () => { const input = tf.tensor3d([2, 2, 4, 4], [2, 2, 1]); expect(() => input.resizeNearestNeighbor([1, 3], true)).not.toThrow(); }); }); describeWithFlags('resizeNearestNeighbor gradients', ALL_ENVS, () => { it('greyscale: upscale, same aspect ratio', async () => { const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]); const dy = tf.tensor3d([ [[1.0], [2.0], [3.0], [4.0]], [[5.0], [6.0], [7.0], [8.0]], [[9.0], [10.0], [11.0], [12.0]], [[13.0], [14.0], [15.0], [16.0]] ]); const size: [number, number] = [4, 4]; const alignCorners = false; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([[[14.0], [22.0]], [[46.0], [54.0]]]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('with clones, greyscale: upscale, same aspect ratio', async () => { const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]); const dy = tf.tensor3d([ [[1.0], [2.0], [3.0], [4.0]], [[5.0], [6.0], [7.0], [8.0]], [[9.0], [10.0], [11.0], [12.0]], [[13.0], [14.0], [15.0], [16.0]] ]); const size: [number, number] = [4, 4]; const alignCorners = false; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i.clone(), size, alignCorners) .clone()); const output = g(input, dy); const expected = tf.tensor3d([[[14.0], [22.0]], [[46.0], [54.0]]]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('greyscale: upscale, same aspect ratio, align corners', async () => { const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]); const dy = tf.tensor3d([ [[1.0], [2.0], [3.0], [4.0]], [[5.0], [6.0], [7.0], [8.0]], [[9.0], [10.0], [11.0], [12.0]], [[13.0], [14.0], [15.0], [16.0]] ]); const size: [number, number] = [4, 4]; const alignCorners = true; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([[[14.0], [22.0]], [[46.0], [54.0]]]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('greyscale: upscale, taller than wider', async () => { const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]); const dy = tf.tensor3d([ [[1.0], [2.0], [3.0], [4.0]], [[5.0], [6.0], [7.0], [8.0]], [[9.0], [10.0], [11.0], [12.0]], [[13.0], [14.0], [15.0], [16.0]], [[17.0], [18.0], [19.0], [20.0]], [[21.0], [22.0], [23.0], [24.0]], [[25.0], [26.0], [27.0], [28.0]], [[29.0], [30.0], [31.0], [32.0]], [[33.0], [34.0], [35.0], [36.0]] ]); const size: [number, number] = [9, 4]; const alignCorners = false; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([[[95.0], [115.0]], [[220.0], [236.0]]]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('greyscale: upscale, taller than wider, align corners', async () => { const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]); const dy = tf.tensor3d([ [[1.0], [2.0], [3.0], [4.0]], [[5.0], [6.0], [7.0], [8.0]], [[9.0], [10.0], [11.0], [12.0]], [[13.0], [14.0], [15.0], [16.0]], [[17.0], [18.0], [19.0], [20.0]], [[21.0], [22.0], [23.0], [24.0]], [[25.0], [26.0], [27.0], [28.0]], [[29.0], [30.0], [31.0], [32.0]], [[33.0], [34.0], [35.0], [36.0]] ]); const size: [number, number] = [9, 4]; const alignCorners = true; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([[[60.0], [76.0]], [[255.0], [275.0]]]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('greyscale: upscale, wider than taller', async () => { const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]); const dy = tf.tensor3d([ [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0]], [[8.0], [9.0], [10.0], [11.0], [12.0], [13.0], [14.0]], [[15.0], [16.0], [17.0], [18.0], [19.0], [20.0], [21.0]], [[22.0], [23.0], [24.0], [25.0], [26.0], [27.0], [28.0]] ]); const size: [number, number] = [4, 7]; const alignCorners = false; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([[[48.0], [57.0]], [[160.0], [141.0]]]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('greyscale: upscale, wider than taller, align corners', async () => { const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]); const dy = tf.tensor3d([ [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0]], [[8.0], [9.0], [10.0], [11.0], [12.0], [13.0], [14.0]], [[15.0], [16.0], [17.0], [18.0], [19.0], [20.0], [21.0]], [[22.0], [23.0], [24.0], [25.0], [26.0], [27.0], [28.0]] ]); const size: [number, number] = [4, 7]; const alignCorners = true; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([[[33.0], [72.0]], [[117.0], [184.0]]]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); // // Downscaling // it('greyscale: downscale, same aspect ratio', async () => { const input = tf.tensor3d([ [[100.0], [50.0], [25.0], [10.0]], [[60.0], [20.0], [80.0], [20.0]], [[40.0], [15.0], [200.0], [203.0]], [[40.0], [10.0], [230.0], [200.0]] ]); const dy = tf.tensor3d([[[1.0], [2.0]], [[3.0], [4.0]]]); const size: [number, number] = [2, 2]; const alignCorners = false; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([ [[1.0], [0.0], [2.0], [0.0]], [[0.0], [0.0], [0.0], [0.0]], [[3.0], [0.0], [4.0], [0.0]], [[0.0], [0.0], [0.0], [0.0]] ]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('greyscale: downscale, same aspect ratio, align corners', async () => { const input = tf.tensor3d([ [[100.0], [50.0], [25.0], [10.0]], [[60.0], [20.0], [80.0], [20.0]], [[40.0], [15.0], [200.0], [203.0]], [[40.0], [10.0], [230.0], [200.0]] ]); const dy = tf.tensor3d([[[1.0], [2.0]], [[3.0], [4.0]]]); const size: [number, number] = [2, 2]; const alignCorners = true; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([ [[1.0], [0.0], [0.0], [2.0]], [[0.0], [0.0], [0.0], [0.0]], [[0.0], [0.0], [0.0], [0.0]], [[3.0], [0.0], [0.0], [4.0]] ]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('greyscale: downscale, taller than wider', async () => { const input = tf.tensor3d([ [[100.0], [50.0], [25.0], [10.0]], [[60.0], [20.0], [80.0], [20.0]], [[40.0], [15.0], [200.0], [203.0]], [[40.0], [10.0], [230.0], [200.0]] ]); const dy = tf.tensor3d([[[1.0], [2.0]], [[3.0], [4.0]], [[5.0], [6.0]]]); const size: [number, number] = [3, 2]; const alignCorners = false; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([ [[1.0], [0.0], [2.0], [0.0]], [[3.0], [0.0], [4.0], [0.0]], [[5.0], [0.0], [6.0], [0.0]], [[0.0], [0.0], [0.0], [0.0]] ]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('greyscale: downscale, taller than wider, align corners', async () => { const input = tf.tensor3d([ [[100.0], [50.0], [25.0], [10.0]], [[60.0], [20.0], [80.0], [20.0]], [[40.0], [15.0], [200.0], [203.0]], [[40.0], [10.0], [230.0], [200.0]] ]); const dy = tf.tensor3d([[[1.0], [2.0]], [[3.0], [4.0]], [[5.0], [6.0]]]); const size: [number, number] = [3, 2]; const alignCorners = true; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([ [[1.0], [0.0], [0.0], [2.0]], [[0.0], [0.0], [0.0], [0.0]], [[3.0], [0.0], [0.0], [4.0]], [[5.0], [0.0], [0.0], [6.0]] ]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('greyscale: downscale, taller than wider', async () => { const input = tf.tensor3d([ [[100.0], [50.0], [25.0], [10.0]], [[60.0], [20.0], [80.0], [20.0]], [[40.0], [15.0], [200.0], [203.0]], [[40.0], [10.0], [230.0], [200.0]] ]); const dy = tf.tensor3d([[[1.0], [2.0], [3.0]], [[4.0], [5.0], [6.0]]]); const size: [number, number] = [2, 3]; const alignCorners = false; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([ [[1.0], [2.0], [3.0], [0.0]], [[0.0], [0.0], [0.0], [0.0]], [[4.0], [5.0], [6.0], [0.0]], [[0.0], [0.0], [0.0], [0.0]] ]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('greyscale: downscale, taller than wider, align corners', async () => { const input = tf.tensor3d([ [[100.0], [50.0], [25.0], [10.0]], [[60.0], [20.0], [80.0], [20.0]], [[40.0], [15.0], [200.0], [203.0]], [[40.0], [10.0], [230.0], [200.0]] ]); const dy = tf.tensor3d([[[1.0], [2.0], [3.0]], [[4.0], [5.0], [6.0]]]); const size: [number, number] = [2, 3]; const alignCorners = true; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([ [[1.0], [0.0], [2.0], [3.0]], [[0.0], [0.0], [0.0], [0.0]], [[0.0], [0.0], [0.0], [0.0]], [[4.0], [0.0], [5.0], [6.0]] ]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('greyscale: downscale, same size', async () => { const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]); const dy = tf.tensor3d([[[1.0], [2.0]], [[3.0], [4.0]]]); const size: [number, number] = [2, 2]; const alignCorners = false; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([[[1.0], [2.0]], [[3.0], [4.0]]]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('greyscale: downscale, same size, align corners', async () => { const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]); const dy = tf.tensor3d([[[1.0], [2.0]], [[3.0], [4.0]]]); const size: [number, number] = [2, 2]; const alignCorners = true; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([[[1.0], [2.0]], [[3.0], [4.0]]]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); // // 3 channel images // it('color: upscale, wider than taller', async () => { const input = tf.tensor3d([ [ [100.26818084716797, 74.61857604980469, 81.62117767333984], [127.86964416503906, 85.0583267211914, 102.95439147949219] ], [ [104.3798828125, 96.70733642578125, 92.60601043701172], [77.63021850585938, 68.55794525146484, 96.17212677001953] ] ]); const dy = tf.tensor3d([ [ [1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [10.0, 11.0, 12.0], [13.0, 14.0, 15.0] ], [ [16.0, 17.0, 18.0], [19.0, 20.0, 21.0], [22.0, 23.0, 24.0], [25.0, 26.0, 27.0], [28.0, 29.0, 30.0] ], [ [31.0, 32.0, 33.0], [34.0, 35.0, 36.0], [37.0, 38.0, 39.0], [40.0, 41.0, 42.0], [43.0, 44.0, 45.0] ] ]); const size: [number, number] = [3, 5]; const alignCorners = false; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([ [[69.0, 75.0, 81.0], [76.0, 80.0, 84.0]], [[102.0, 105.0, 108.0], [83.0, 85.0, 87.0]] ]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('color: upscale, wider than taller, align corners', async () => { const input = tf.tensor3d([ [ [100.26818084716797, 74.61857604980469, 81.62117767333984], [127.86964416503906, 85.0583267211914, 102.95439147949219] ], [ [104.3798828125, 96.70733642578125, 92.60601043701172], [77.63021850585938, 68.55794525146484, 96.17212677001953] ] ]); const dy = tf.tensor3d([ [ [1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [10.0, 11.0, 12.0], [13.0, 14.0, 15.0] ], [ [16.0, 17.0, 18.0], [19.0, 20.0, 21.0], [22.0, 23.0, 24.0], [25.0, 26.0, 27.0], [28.0, 29.0, 30.0] ], [ [31.0, 32.0, 33.0], [34.0, 35.0, 36.0], [37.0, 38.0, 39.0], [40.0, 41.0, 42.0], [43.0, 44.0, 45.0] ] ]); const size: [number, number] = [3, 5]; const alignCorners = true; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([ [[5.0, 7.0, 9.0], [30.0, 33.0, 36.0]], [[100.0, 104.0, 108.0], [195.0, 201.0, 207.0]] ]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('color: downscale, taller than wider', async () => { const input = tf.tensor3d([ [ [97.98934936523438, 77.24969482421875, 113.70111846923828], [111.34081268310547, 113.15758514404297, 157.90521240234375], [105.77980041503906, 85.75989532470703, 69.62374114990234], [125.94231414794922, 73.11385345458984, 87.03099822998047] ], [ [62.25117111206055, 90.23927307128906, 119.1966552734375], [93.55166625976562, 95.9106674194336, 115.56237030029297], [102.98121643066406, 98.1983413696289, 97.55982971191406], [86.47753143310547, 97.04051208496094, 121.50492095947266] ], [ [92.4140853881836, 118.45619201660156, 108.0341796875], [126.43061065673828, 123.28077697753906, 121.03379821777344], [128.6694793701172, 98.47042846679688, 114.47464752197266], [93.31566619873047, 95.2713623046875, 102.51188659667969] ], [ [101.55884552001953, 83.31947326660156, 119.08016204833984], [128.28546142578125, 92.56212615966797, 74.85054779052734], [88.9786148071289, 119.43685913085938, 73.06110382080078], [98.17908477783203, 105.54570007324219, 93.45832061767578] ] ]); const dy = tf.tensor3d([[[1.0, 2.0, 3.0]], [[4.0, 5.0, 6.0]], [[7.0, 8.0, 9.0]]]); const size: [number, number] = [3, 1]; const alignCorners = false; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([ [[1.0, 2.0, 3.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], [[4.0, 5.0, 6.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], [[7.0, 8.0, 9.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] ]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('color: downscale, taller than wider, align corners', async () => { const input = tf.tensor3d([ [ [97.98934936523438, 77.24969482421875, 113.70111846923828], [111.34081268310547, 113.15758514404297, 157.90521240234375], [105.77980041503906, 85.75989532470703, 69.62374114990234], [125.94231414794922, 73.11385345458984, 87.03099822998047] ], [ [62.25117111206055, 90.23927307128906, 119.1966552734375], [93.55166625976562, 95.9106674194336, 115.56237030029297], [102.98121643066406, 98.1983413696289, 97.55982971191406], [86.47753143310547, 97.04051208496094, 121.50492095947266] ], [ [92.4140853881836, 118.45619201660156, 108.0341796875], [126.43061065673828, 123.28077697753906, 121.03379821777344], [128.6694793701172, 98.47042846679688, 114.47464752197266], [93.31566619873047, 95.2713623046875, 102.51188659667969] ], [ [101.55884552001953, 83.31947326660156, 119.08016204833984], [128.28546142578125, 92.56212615966797, 74.85054779052734], [88.9786148071289, 119.43685913085938, 73.06110382080078], [98.17908477783203, 105.54570007324219, 93.45832061767578] ] ]); const dy = tf.tensor3d([[[1.0, 2.0, 3.0]], [[4.0, 5.0, 6.0]], [[7.0, 8.0, 9.0]]]); const size: [number, number] = [3, 1]; const alignCorners = true; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([ [[1.0, 2.0, 3.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], [[4.0, 5.0, 6.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], [[7.0, 8.0, 9.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] ]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); it('color: same size', async () => { const input = tf.tensor3d([ [ [100.26818084716797, 74.61857604980469, 81.62117767333984], [127.86964416503906, 85.0583267211914, 102.95439147949219] ], [ [104.3798828125, 96.70733642578125, 92.60601043701172], [77.63021850585938, 68.55794525146484, 96.17212677001953] ] ]); const dy = tf.tensor3d([ [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], [[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]] ]); const size: [number, number] = [2, 2]; const alignCorners = false; const g = tf.grad( (i: tf.Tensor3D) => tf.image.resizeNearestNeighbor(i, size, alignCorners)); const output = g(input, dy); const expected = tf.tensor3d([ [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], [[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]] ]); expectArraysClose(await output.data(), await expected.data()); expect(output.shape).toEqual(expected.shape); expect(output.dtype).toBe(expected.dtype); }); });
the_stack
import * as os from "os"; import * as path from "path"; import * as stream from "stream"; import * as fs from "fs"; import * as tl from "azure-pipelines-task-lib/task"; import * as trl from "azure-pipelines-task-lib/toolrunner"; import * as fse from "fs-extra"; import ToolRunner = trl.ToolRunner; import * as uuidv5 from "uuidv5"; function writeBuildTempFile(taskName: string, data: any): string { let tempFile: string; do { // Let's add a random suffix const randomSuffix = Math.random().toFixed(6); tempFile = path.join(os.tmpdir(), `${taskName}-${randomSuffix}.tmp`); } while (tl.exist(tempFile)); tl.debug(`Generating Build temp file: ${tempFile}`); tl.writeFile(tempFile, data); return tempFile; } function deleteBuildTempFile(tempFile: string) { if (tempFile && tl.exist(tempFile)) { tl.debug(`Deleting temp file: ${tempFile}`); fs.unlinkSync(tempFile); } } /** * Set manifest related arguments for "tfx extension" command, such as * the --root or the --manifest-globs switches. * @param {ToolRunner} tfx * @returns {() => void} Cleaner function that the caller should use to cleanup temporary files created to be used as arguments */ export function validateAndSetTfxManifestArguments(tfx: ToolRunner): (() => void) { const rootFolder = tl.getInput("rootFolder", false); tfx.argIf(rootFolder, ["--root", rootFolder]); const globsManifest = tl.getDelimitedInput("patternManifest", "\n", false); tfx.argIf(globsManifest.length, ["--manifest-globs"]); tfx.argIf(globsManifest.length, globsManifest); // Overrides manifest file const publisher = tl.getInput("publisherId", false); const localizationRoot = tl.getInput("localizationRoot", false); tfx.argIf(localizationRoot, ["--loc-root", localizationRoot]); let extensionId = tl.getInput("extensionId", false); const extensionTag = tl.getInput("extensionTag", false); if (extensionId && extensionTag) { extensionId += extensionTag; tl.debug(`Overriding extension id to: ${extensionId}`); } // for backwards compat check both "method" and "fileType" switch (tl.getInput("method", false) || tl.getInput("fileType", false)) { // for backwards compat trigger on both "manifest" and "id" case "manifest": case "id": default: { tfx.argIf(publisher, ["--publisher", publisher]); tfx.argIf(extensionId, ["--extension-id", extensionId]); break; } case "vsix": { const vsixFilePattern = tl.getPathInput("vsixFile", true); let matchingVsixFile: string[]; if (vsixFilePattern.indexOf("*") >= 0 || vsixFilePattern.indexOf("?") >= 0) { tl.debug("Pattern found in vsixFile parameter."); matchingVsixFile = tl.findMatch(process.cwd(), vsixFilePattern); } else { tl.debug("No pattern found in vsixFile parameter."); matchingVsixFile = [vsixFilePattern]; } if (!matchingVsixFile || matchingVsixFile.length === 0) { tl.setResult(tl.TaskResult.Failed, `Found no vsix files matching: ${vsixFilePattern}.`); throw "failed"; } if (matchingVsixFile.length !== 1) { tl.setResult(tl.TaskResult.Failed, `Found multiple vsix files matching: ${vsixFilePattern}.`); throw "failed"; } tfx.arg(["--vsix", matchingVsixFile[0]]); break; } } let jsonOverrides: any; const extensionName = tl.getInput("extensionName", false); if (extensionName) { tl.debug(`Overriding extension name to: ${extensionName}`); jsonOverrides = (jsonOverrides || {}); jsonOverrides.name = extensionName; } const extensionVisibility = tl.getInput("extensionVisibility", false); if (extensionVisibility && extensionVisibility !== "default") { tl.debug(`Overriding extension visibility to: ${extensionVisibility}`); jsonOverrides = (jsonOverrides || {}); const isPublic = extensionVisibility.indexOf("public") >= 0; const isPreview = extensionVisibility.indexOf("preview") >= 0; jsonOverrides.public = isPublic; if (isPreview) { jsonOverrides.galleryFlags = jsonOverrides.galleryFlags || []; jsonOverrides.galleryFlags.push("Preview"); } } const extensionPricing = tl.getInput("extensionPricing", false); if (extensionPricing && extensionPricing !== "default") { tl.debug(`Overriding extension pricing to: ${extensionPricing}`); jsonOverrides = (jsonOverrides || {}); const isPaid = extensionPricing.indexOf("paid") >= 0; if (isPaid) { jsonOverrides.galleryFlags = jsonOverrides.galleryFlags || []; jsonOverrides.galleryFlags.push("Paid"); } } const extensionVersion = getExtensionVersion(); if (extensionVersion) { tl.debug(`Overriding extension version to: ${extensionVersion}`); jsonOverrides = (jsonOverrides || {}); jsonOverrides.version = extensionVersion; } const noWaitValidation = tl.getBoolInput("noWaitValidation", false); if (noWaitValidation) { tl.debug(`Not waiting for validation.`); tfx.arg("--no-wait-validation"); } const bypassLocalValidation = tl.getBoolInput("bypassLocalValidation", false); if (bypassLocalValidation) { tl.debug(`Bypassing local validation.`); tfx.arg("--bypass-validation"); } let overrideFilePath: string; if (jsonOverrides) { // Generate a temp file overrideFilePath = writeBuildTempFile("PackageTask", JSON.stringify(jsonOverrides)); tl.debug(`Generated a JSON temp file to override manifest values Path: ${overrideFilePath}`); tfx.arg(["--overrides-file", overrideFilePath]); } const args = tl.getInput("arguments", false); if (args) { tl.debug(`Adding additional arguments: ${args}.`); tfx.line(args); } return () => deleteBuildTempFile(overrideFilePath); } /** * Run a tfx command by ensuring that "tfx" exists, installing it on the fly if needed. * @param {(tfx:ToolRunner)=>void} cmd */ export async function runTfx(cmd: (tfx: ToolRunner) => void) : Promise<boolean> { let tfx: ToolRunner; let tfxPath: string; const tryRunCmd = async (tfx: ToolRunner) => { try { // Set working folder const cwd = tl.getInput("cwd", false); if (cwd) { tl.cd(cwd); } cmd(tfx); return true; } catch (err) { tl.setResult(tl.TaskResult.Failed, `Error running task: ${err}`); return false; } }; const tfxInstallerPath = tl.getVariable("__tfxpath"); if (tfxInstallerPath) { tfxPath = tl.which(path.join(tfxInstallerPath, "/tfx")); } if (tfxPath) { tl.debug(`using: ${tfxPath}`); tfx = new trl.ToolRunner(tfxPath); await tryRunCmd(tfx); return; } tl.setResult(tl.TaskResult.Failed, "Could not find tfx. To resolve, add the 'Use Node CLI for Azure DevOps' task to your pipeline before this task."); } /** * Reads the extension version from the 'extensionVersion' variable, extracting * just the part that is compatible with the versioning scheme used in the Marketplace. * * @returns string */ export function getExtensionVersion(): string { const extensionVersion = tl.getInput("extensionVersion", false); if (extensionVersion) { const extractedVersions = extensionVersion.match(/[0-9]+\.[0-9]+\.[0-9]+(?:\.[0-9]+)?/); if (extractedVersions && extractedVersions.length === 1) { return extractedVersions[0]; } else { throw new Error(`Supplied ExtensionVersion must contain a string matching '##.##.##(.##)'.`); } } return ""; } /** * Get the Marketplace endpoint details to be used while publishing or installing an extension. * * @param {string="connectedServiceName"} inputFieldName * @returns string */ export function getMarketplaceEndpointDetails(inputFieldName: string): any { const marketplaceEndpoint = tl.getInput(inputFieldName, true); const hostUrl = tl.getEndpointUrl(marketplaceEndpoint, false); const auth = tl.getEndpointAuthorization(marketplaceEndpoint, false); const password = auth.parameters["password"]; const username = auth.parameters["username"]; const apitoken = auth.parameters["apitoken"]; return { "url": hostUrl, "username": username, "password": password, "apitoken": apitoken }; } /** * Sets the marketplace endpoint details (url, credentials) for the toolrunner. * * @param {ToolRunner} tfx * @returns string */ export function setTfxMarketplaceArguments(tfx: ToolRunner, setServiceUrl = true) : void { const connectTo = tl.getInput("connectTo", false) || "VsTeam"; let galleryEndpoint; if (connectTo === "VsTeam") { galleryEndpoint = getMarketplaceEndpointDetails("connectedServiceName"); tfx.argIf(setServiceUrl, ["--service-url", galleryEndpoint.url]); tfx.arg(["--auth-type", "pat"]); tfx.arg(["--token", galleryEndpoint.password]); } else { galleryEndpoint = getMarketplaceEndpointDetails("connectedServiceNameTFS"); tfx.argIf(setServiceUrl, ["--service-url", galleryEndpoint.url]); if (galleryEndpoint.username) { tfx.arg(["--auth-type", "basic"]); tfx.arg(["--username", galleryEndpoint.username]); tfx.arg(["--password", galleryEndpoint.password]); } else { tfx.arg(["--auth-type", "pat"]); tfx.arg(["--token", galleryEndpoint.apitoken]); } } } /** * A writable stream intended to be used with Tfx when using JSON output. * This class overcomes the problem of having tfx warnings being displayed * in stdout as regular messages, even when using --json switch in tfx. * */ export class TfxJsonOutputStream extends stream.Writable { jsonString = ""; messages: string[] = []; constructor(public out: (message: string) => void) { super(); } // eslint-disable-next-line @typescript-eslint/ban-types _write(chunk: any, enc: string, cb: (Function)) : void { const chunkStr: string = chunk.toString(); if (chunkStr.startsWith("[command]")) { this.taskOutput(chunkStr, this.out); } else if (!this.jsonString && (chunkStr.toString()[0] !== "{" && chunkStr.toString()[0] !== "[")) { this.messages.push(chunkStr); this.taskOutput(chunkStr, this.out); } else { this.jsonString += chunkStr; this.taskOutput(chunkStr, tl.debug); } cb(); } private taskOutput(messages: string, lineWriter: (m: string) => void) { if (!messages) { return; } // Split messages to be sure that we are invoking the write lineWriter for each lineWriter // Otherwise we could get messages in console with the wrong prefix used by azure-pipelines-task-lib messages.split("\n").forEach(lineWriter); } } function getTaskPathContributions(manifest: any): string[] { // Check for task contributions if (!manifest.contributions) { return []; } return manifest.contributions .filter((c: any) => c.type === "ms.vss-distributed-task.task" && c.properties && c.properties["name"]) .map((c: any) => c.properties["name"]); } function updateTaskId(manifest: any, publisherId: string, extensionId: string): unknown { tl.debug(`Task manifest ${manifest.name} id before: ${manifest.id}`); const extensionNs = uuidv5("url", "https://marketplace.visualstudio.com/vsts", true); manifest.id = uuidv5(extensionNs, `${publisherId}.${extensionId}.${manifest.name}`, false); tl.debug(`Task manifest ${manifest.name} id after: ${manifest.id}`); return manifest; } function updateExtensionManifestTaskIds(manifest: any, originalTaskId: string, newTaskId: string): unknown { if (!manifest.contributions) { tl.debug(`No contributions found`); return manifest; } manifest.contributions .filter((c: any) => c.type !== "ms.vss-distributed-task.task" && c.properties && c.properties.supportsTasks) .forEach((c: any) => { const supportsTasks = [...c.properties.supportsTasks]; const index = supportsTasks.indexOf(originalTaskId); if(index != -1) { tl.debug(`Extension manifest supportsTasks before: ${c.properties.supportsTasks}`); supportsTasks[index] = newTaskId; c.properties.supportsTasks = supportsTasks; tl.debug(`Extension manifest supportsTasks after: ${c.properties.supportsTasks}`); } else{ tl.debug(`No supportTasks entry found in manifest contribution`); } }); return manifest; } function updateTaskVersion(manifest: any, extensionVersionString: string, extensionVersionType: string): unknown { const versionParts = extensionVersionString.split("."); if (versionParts.length > 3) { tl.warning("Detected a version that consists of more than 3 parts. Build tasks support only 3 parts, ignoring the rest."); } const extensionversion = { major: +versionParts[0], minor: +versionParts[1], patch: +versionParts[2] }; if (!manifest.version && extensionVersionType !== "major") { tl.warning("Detected no version in task manifest. Forcing major."); manifest.version = extensionversion; } else { tl.debug(`Task manifest ${manifest.name} version before: ${JSON.stringify(manifest.version)}`); switch (extensionVersionType) { default: case "major": manifest.version.Major = `${extensionversion.major}`; // eslint-disable-next-line no-fallthrough case "minor": manifest.version.Minor = `${extensionversion.minor}`; // eslint-disable-next-line no-fallthrough case "patch": manifest.version.Patch = `${extensionversion.patch}`; } } tl.debug(`Task manifest ${manifest.name} version after: ${JSON.stringify(manifest.version)}`); return manifest; } /** * * Check whether the version update should be propagated to tasks included * in the extension. * */ export async function updateManifests(manifestPaths: string[]): Promise<void> { const updateTasksVersion = tl.getBoolInput("updateTasksVersion", false); const updateTasksId = tl.getBoolInput("updateTasksId", false); if (updateTasksVersion || updateTasksId) { if (!(manifestPaths && manifestPaths.length)) { manifestPaths = getExtensionManifestPaths(); } tl.debug(`Found manifests: ${manifestPaths.join(", ")}`); const tasksIds = await updateTaskManifests(manifestPaths, updateTasksId, updateTasksVersion); await updateExtensionManifests(manifestPaths, tasksIds); } } async function updateTaskManifests(manifestPaths: string[], updateTasksId: boolean, updateTasksVersion: boolean) : Promise<[string, string][]> { const tasksIds: [string, string][] = []; await Promise.all(manifestPaths.map(async (extensionPath) => { const manifest: any = await getManifest(extensionPath); const taskManifestPaths: string[] = getTaskManifestPaths(extensionPath, manifest); if (taskManifestPaths && taskManifestPaths.length) { await Promise.all(taskManifestPaths.map(async (taskPath) => { tl.debug(`Patching: ${taskPath}.`); let taskManifest: any = await getManifest(taskPath); if (updateTasksId) { tl.debug(`Updating Id...`); const publisherId = tl.getInput("publisherId", false) || manifest.publisher; const extensionTag = tl.getInput("extensionTag", false) || ""; const extensionId = `${(tl.getInput("extensionId", false) || manifest.id)}${extensionTag}`; const originalTaskId: string = taskManifest.id || null; taskManifest = updateTaskId(taskManifest, publisherId, extensionId); const newTaskId: string = taskManifest.id; if(originalTaskId && (originalTaskId !== newTaskId)) { tasksIds.push([originalTaskId, newTaskId]) } } if (updateTasksVersion) { tl.debug(`Updating version...`); const extensionVersion = tl.getInput("extensionVersion", false) || manifest.version; if (!extensionVersion) { throw new Error( "Extension Version was not supplied nor does the extension manifest define one."); } const extensionVersionType = tl.getInput("updateTasksVersionType", false) || "major"; taskManifest = updateTaskVersion(taskManifest, extensionVersion, extensionVersionType); } await writeManifest(taskManifest, taskPath); tl.debug(`Updated: ${taskPath}.`); })); } })); return tasksIds; } async function updateExtensionManifests(manifestPaths: string[], updatedTaskIds: [string, string][]): Promise<void> { await Promise.all(manifestPaths.map(async (path) => { tl.debug(`Patching: ${path}.`); let originalManifest = await getManifest(path); updatedTaskIds.map(([originalTaskId, newTaskId]) => { tl.debug(`Updating: ${originalTaskId} => ${newTaskId}.`) originalManifest = updateExtensionManifestTaskIds(originalManifest, originalTaskId, newTaskId); }); await writeManifest(originalManifest, path); })); } function getExtensionManifestPaths(): string[] { // Search for extension manifests given the rootFolder and patternManifest inputs const rootFolder = tl.getInput("rootFolder", false) || tl.getInput("System.DefaultWorkingDirectory"); const manifestsPatterns = tl.getDelimitedInput("patternManifest", "\n", false) || ["vss-extension.json"]; tl.debug(`Searching for extension manifests: ${manifestsPatterns.join(", ")}`); return tl.findMatch(rootFolder, manifestsPatterns); } function getManifest(path: string): Promise<unknown> { return fse.readFile(path, "utf8").then((data: string) => { try { data = data.replace(/^\uFEFF/, () => { tl.warning(`Removing Unicode BOM from manifest file: ${path}.`); return ""; }); return JSON.parse(data); } catch (jsonError) { throw new Error(`Error parsing task manifest: ${path} - ${jsonError}`); } }); } function getTaskManifestPaths(manifestPath: string, manifest: any): string[] { const tasks = getTaskPathContributions(manifest); const rootFolder = path.dirname(manifestPath); return tasks.reduce((result: string[], task: string) => { tl.debug(`Found task: ${task}`); const taskRoot: string = path.join(rootFolder, task); const rootManifest: string = path.join(taskRoot, "task.json"); let localizationRoot = tl.filePathSupplied("localizationRoot") ? tl.getPathInput("localizationRoot", false) : taskRoot; if (localizationRoot) { localizationRoot = path.resolve(localizationRoot); } if (tl.exist(rootManifest)) { tl.debug(`Found single-task manifest: ${rootManifest}`); const rootManifests: string[] = [rootManifest]; const rootLocManifest: string = path.join(localizationRoot, "task.loc.json"); if (tl.exist(rootLocManifest)) { tl.debug(`Found localized single-task manifest: ${rootLocManifest}`); rootManifests.push(rootLocManifest); } return (result).concat(rootManifests); } else { const versionManifests = tl.findMatch(taskRoot, "*/task.json"); const locVersionManifests = tl.findMatch(localizationRoot, "*/task.loc.json"); tl.debug(`Found multi-task manifests: ${versionManifests.join(", ")}`); tl.debug(`Found multi-task localized manifests: ${locVersionManifests.join(", ")}`); return (result).concat(versionManifests).concat(locVersionManifests); } }, []); } export function writeManifest(manifest: any, path: string): Promise<void> { return fse.writeJSON(path, manifest); } export function checkUpdateTasksManifests(manifestFile?: string): Promise<void> { return updateManifests(manifestFile ? [manifestFile] : []); }
the_stack
import React from 'react' import { Box, Text } from 'ink' import { render } from 'ink-testing-library' import Table, { Header, Skeleton, Cell } from '../src' // Helpers ------------------------------------------------------------------- const skeleton = (v: string) => <Skeleton>{v}</Skeleton> const header = (v: string) => <Header>{v}</Header> const cell = (v: string) => <Cell>{v}</Cell> const Custom = ({ children }: React.PropsWithChildren<{}>) => ( <Text italic color="red"> {children} </Text> ) const custom = (v: string) => <Custom>{v}</Custom> // Tests --------------------------------------------------------------------- test('Renders table.', () => { const data = [{ name: 'Foo' }] const { lastFrame: actual } = render(<Table data={data} />) const { lastFrame: expected } = render( <> <Box> {skeleton('┌')} {skeleton('──────')} {skeleton('┐')} </Box> <Box> {skeleton('│')} {header(' name ')} {skeleton('│')} </Box> <Box> {skeleton('├')} {skeleton('──────')} {skeleton('┤')} </Box> <Box> {skeleton('│')} {cell(' Foo ')} {skeleton('│')} </Box> <Box> {skeleton('└')} {skeleton('──────')} {skeleton('┘')} </Box> </>, ) expect(actual()).toBe(expected()) }) test('Renders table with numbers.', () => { const data = [{ name: 'Foo', age: 12 }] const { lastFrame: actual } = render(<Table data={data} />) const { lastFrame: expected } = render( <> <Box> {skeleton('┌')} {skeleton('──────')} {skeleton('┬')} {skeleton('─────')} {skeleton('┐')} </Box> <Box> {skeleton('│')} {header(' name ')} {skeleton('│')} {header(' age ')} {skeleton('│')} </Box> <Box> {skeleton('├')} {skeleton('──────')} {skeleton('┼')} {skeleton('─────')} {skeleton('┤')} </Box> <Box> {skeleton('│')} {cell(' Foo ')} {skeleton('│')} {cell(' 12 ')} {skeleton('│')} </Box> <Box> {skeleton('└')} {skeleton('──────')} {skeleton('┴')} {skeleton('─────')} {skeleton('┘')} </Box> </>, ) expect(actual()).toBe(expected()) }) test('Renders table with multiple rows.', () => { const data = [ { name: 'Foo', age: 12 }, { name: 'Bar', age: 0 }, ] const { lastFrame: actual } = render(<Table data={data} />) const { lastFrame: expected } = render( <> <Box> {skeleton('┌')} {skeleton('──────')} {skeleton('┬')} {skeleton('─────')} {skeleton('┐')} </Box> <Box> {skeleton('│')} {header(' name ')} {skeleton('│')} {header(' age ')} {skeleton('│')} </Box> <Box> {skeleton('├')} {skeleton('──────')} {skeleton('┼')} {skeleton('─────')} {skeleton('┤')} </Box> <Box> {skeleton('│')} {cell(' Foo ')} {skeleton('│')} {cell(' 12 ')} {skeleton('│')} </Box> <Box> {skeleton('├')} {skeleton('──────')} {skeleton('┼')} {skeleton('─────')} {skeleton('┤')} </Box> <Box> {skeleton('│')} {cell(' Bar ')} {skeleton('│')} {cell(' 0 ')} {skeleton('│')} </Box> <Box> {skeleton('└')} {skeleton('──────')} {skeleton('┴')} {skeleton('─────')} {skeleton('┘')} </Box> </>, ) expect(actual()).toBe(expected()) }) test('Renders table with undefined value.', () => { const data = [{ name: 'Foo' }, { name: 'Bar', age: 15 }] const { lastFrame: actual } = render(<Table data={data} />) const { lastFrame: expected } = render( <> <Box> {skeleton('┌')} {skeleton('──────')} {skeleton('┬')} {skeleton('─────')} {skeleton('┐')} </Box> <Box> {skeleton('│')} {header(' name ')} {skeleton('│')} {header(' age ')} {skeleton('│')} </Box> <Box> {skeleton('├')} {skeleton('──────')} {skeleton('┼')} {skeleton('─────')} {skeleton('┤')} </Box> <Box> {skeleton('│')} {cell(' Foo ')} {skeleton('│')} {cell(' ')} {skeleton('│')} </Box> <Box> {skeleton('├')} {skeleton('──────')} {skeleton('┼')} {skeleton('─────')} {skeleton('┤')} </Box> <Box> {skeleton('│')} {cell(' Bar ')} {skeleton('│')} {cell(' 15 ')} {skeleton('│')} </Box> <Box> {skeleton('└')} {skeleton('──────')} {skeleton('┴')} {skeleton('─────')} {skeleton('┘')} </Box> </>, ) expect(actual()).toBe(expected()) }) test('Renders table with custom padding.', () => { const data = [ { name: 'Foo', age: 12 }, { name: 'Bar', age: 15 }, ] const { lastFrame: actual } = render(<Table data={data} padding={3} />) const { lastFrame: expected } = render( <> <Box> {skeleton('┌')} {skeleton('──────────')} {skeleton('┬')} {skeleton('─────────')} {skeleton('┐')} </Box> <Box> {skeleton('│')} {header(' name ')} {skeleton('│')} {header(' age ')} {skeleton('│')} </Box> <Box> {skeleton('├')} {skeleton('──────────')} {skeleton('┼')} {skeleton('─────────')} {skeleton('┤')} </Box> <Box> {skeleton('│')} {cell(' Foo ')} {skeleton('│')} {cell(' 12 ')} {skeleton('│')} </Box> <Box> {skeleton('├')} {skeleton('──────────')} {skeleton('┼')} {skeleton('─────────')} {skeleton('┤')} </Box> <Box> {skeleton('│')} {cell(' Bar ')} {skeleton('│')} {cell(' 15 ')} {skeleton('│')} </Box> <Box> {skeleton('└')} {skeleton('──────────')} {skeleton('┴')} {skeleton('─────────')} {skeleton('┘')} </Box> </>, ) expect(actual()).toBe(expected()) }) test('Renders table with custom header.', () => { const data = [ { name: 'Foo', age: 12 }, { name: 'Bar', age: 15 }, ] const { lastFrame: actual } = render(<Table data={data} header={Custom} />) const { lastFrame: expected } = render( <> <Box> {skeleton('┌')} {skeleton('──────')} {skeleton('┬')} {skeleton('─────')} {skeleton('┐')} </Box> <Box> {skeleton('│')} {custom(' name ')} {skeleton('│')} {custom(' age ')} {skeleton('│')} </Box> <Box> {skeleton('├')} {skeleton('──────')} {skeleton('┼')} {skeleton('─────')} {skeleton('┤')} </Box> <Box> {skeleton('│')} {cell(' Foo ')} {skeleton('│')} {cell(' 12 ')} {skeleton('│')} </Box> <Box> {skeleton('├')} {skeleton('──────')} {skeleton('┼')} {skeleton('─────')} {skeleton('┤')} </Box> <Box> {skeleton('│')} {cell(' Bar ')} {skeleton('│')} {cell(' 15 ')} {skeleton('│')} </Box> <Box> {skeleton('└')} {skeleton('──────')} {skeleton('┴')} {skeleton('─────')} {skeleton('┘')} </Box> </>, ) expect(actual()).toBe(expected()) }) test('Renders table with custom cell.', () => { const data = [ { name: 'Foo', age: 12 }, { name: 'Bar', age: 15 }, ] const { lastFrame: actual } = render(<Table data={data} cell={Custom} />) const { lastFrame: expected } = render( <> <Box> {skeleton('┌')} {skeleton('──────')} {skeleton('┬')} {skeleton('─────')} {skeleton('┐')} </Box> <Box> {skeleton('│')} {header(' name ')} {skeleton('│')} {header(' age ')} {skeleton('│')} </Box> <Box> {skeleton('├')} {skeleton('──────')} {skeleton('┼')} {skeleton('─────')} {skeleton('┤')} </Box> <Box> {skeleton('│')} {custom(' Foo ')} {skeleton('│')} {custom(' 12 ')} {skeleton('│')} </Box> <Box> {skeleton('├')} {skeleton('──────')} {skeleton('┼')} {skeleton('─────')} {skeleton('┤')} </Box> <Box> {skeleton('│')} {custom(' Bar ')} {skeleton('│')} {custom(' 15 ')} {skeleton('│')} </Box> <Box> {skeleton('└')} {skeleton('──────')} {skeleton('┴')} {skeleton('─────')} {skeleton('┘')} </Box> </>, ) expect(actual()).toBe(expected()) }) test('Renders table with custom skeleton.', () => { const data = [ { name: 'Foo', age: 12 }, { name: 'Bar', age: 15 }, ] const { lastFrame: actual } = render(<Table data={data} skeleton={Custom} />) const { lastFrame: expected } = render( <> <Box> {custom('┌')} {custom('──────')} {custom('┬')} {custom('─────')} {custom('┐')} </Box> <Box> {custom('│')} {header(' name ')} {custom('│')} {header(' age ')} {custom('│')} </Box> <Box> {custom('├')} {custom('──────')} {custom('┼')} {custom('─────')} {custom('┤')} </Box> <Box> {custom('│')} {cell(' Foo ')} {custom('│')} {cell(' 12 ')} {custom('│')} </Box> <Box> {custom('├')} {custom('──────')} {custom('┼')} {custom('─────')} {custom('┤')} </Box> <Box> {custom('│')} {cell(' Bar ')} {custom('│')} {cell(' 15 ')} {custom('│')} </Box> <Box> {custom('└')} {custom('──────')} {custom('┴')} {custom('─────')} {custom('┘')} </Box> </>, ) expect(actual()).toBe(expected()) }) // ---------------------------------------------------------------------------
the_stack
import * as assert from 'assert'; import {describe, it} from 'mocha'; import {Transform} from 'stream'; import {EchoClient} from '../fixtures/google-gax-packaging-test-app/src/v1beta1'; import {GoogleAuth} from 'google-auth-library'; import {GoogleError} from '../../src'; interface Operation { promise(): Function; } describe('Run unit tests of echo client', () => { interface GoogleError extends Error { code: number; } const FAKE_STATUS_CODE = 1; const error = new Error() as GoogleError; error.code = FAKE_STATUS_CODE; const authStub = { getClient: async () => { return { getRequestHeaders: async () => { return { Authorization: 'Bearer zzzz', }; }, }; }, }; describe('echo', () => { it('invokes echo without error', async done => { const client = new EchoClient({ auth: authStub as unknown as GoogleAuth, credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); // Mock request const request = {}; // Mock response const content = 'content951530617'; const expectedResponse = { content, }; // Mock Grpc layer client.innerApiCalls.echo = mockSimpleGrpcMethod( request, expectedResponse ); const [response] = await client.echo(request); assert.deepStrictEqual(response, expectedResponse); done(); }); it('invokes echo with error', async done => { const client = new EchoClient({ auth: authStub as unknown as GoogleAuth, credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); // Mock request const request = {}; // Mock Grpc layer client.innerApiCalls.echo = mockSimpleGrpcMethod(request, null, error); try { await client.echo(request); } catch (err) { assert(err instanceof GoogleError); assert.strictEqual(err.code, FAKE_STATUS_CODE); done(); } }); }); describe('expand', () => { it('invokes expand without error', done => { const client = new EchoClient({ auth: authStub as unknown as GoogleAuth, credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); // Mock request const request = {}; // Mock response const content = 'content951530617'; const expectedResponse = { content, }; // Mock Grpc layer client.innerApiCalls.expand = mockServerStreamingGrpcMethod( request, expectedResponse ); const stream = client.expand(request); stream.on('data', (response: {}) => { assert.deepStrictEqual(response, expectedResponse); done(); }); stream.on('error', (err: Error) => { done(err); }); }); it('invokes expand with error', done => { const client = new EchoClient({ auth: authStub as unknown as GoogleAuth, credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); // Mock request const request = {}; // Mock Grpc layer client.innerApiCalls.expand = mockServerStreamingGrpcMethod( request, null, error ); const stream = client.expand(request); stream.on('data', () => { assert.fail(); }); stream.on('error', (err: {code: number}) => { assert(err instanceof Error); assert.strictEqual(err.code, FAKE_STATUS_CODE); done(); }); }); }); describe('pagedExpand', () => { it('invokes pagedExpand without error', async done => { const client = new EchoClient({ auth: authStub as unknown as GoogleAuth, credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); // Mock request const request = {}; // Mock response const nextPageToken = ''; const responsesElement = {}; const responses = [responsesElement]; const expectedResponse = { nextPageToken, responses, }; // Mock Grpc layer client.innerApiCalls.pagedExpand = ( actualRequest: {}, options: {}, callback: Function ) => { assert.deepStrictEqual(actualRequest, request); callback(null, expectedResponse.responses); }; const [response] = await client.pagedExpand(request); assert.deepStrictEqual(response, expectedResponse.responses); done(); }); it('invokes pagedExpand with error', async done => { const client = new EchoClient({ auth: authStub as unknown as GoogleAuth, credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); // Mock request const request = {}; // Mock Grpc layer client.innerApiCalls.pagedExpand = mockSimpleGrpcMethod( request, null, error ); try { await client.pagedExpand(request); } catch (err) { assert(err instanceof GoogleError); assert.strictEqual(err.code, FAKE_STATUS_CODE); done(); } }); }); describe('chat', () => { it('invokes chat without error', done => { const client = new EchoClient({ auth: authStub as unknown as GoogleAuth, credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); // Mock request const request = {}; // Mock response const content = 'content951530617'; const expectedResponse = { content, }; // Mock Grpc layer client.innerApiCalls.chat = mockBidiStreamingGrpcMethod( request, expectedResponse ); const stream = client .chat() .on('data', (response: {}) => { assert.deepStrictEqual(response, expectedResponse); done(); }) .on('error', (err: {}) => { done(err); }); stream.write(request); }); it('invokes chat with error', done => { const client = new EchoClient({ auth: authStub as unknown as GoogleAuth, credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); // Mock request const request = {}; // Mock Grpc layer client.innerApiCalls.chat = mockBidiStreamingGrpcMethod( request, null, error ); const stream = client .chat() .on('data', () => { assert.fail(); }) .on('error', (err: {code: number}) => { assert(err instanceof Error); assert.strictEqual(err.code, FAKE_STATUS_CODE); done(); }); stream.write(request); }); }); describe('wait', () => { it('invokes wait without error', done => { const client = new EchoClient({ auth: authStub as unknown as GoogleAuth, credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); // Mock request const request = {}; // Mock response const content = 'content951530617'; const expectedResponse = { content, }; // Mock Grpc layer client.innerApiCalls.wait = mockLongRunningGrpcMethod( request, expectedResponse ); client .wait(request) .then(responses => { const operation = responses[0]; return operation.promise(); }) .then(responses => { assert.deepStrictEqual(responses[0], expectedResponse); done(); }) .catch((err: {}) => { done(err); }); }); it('invokes wait with error', done => { const client = new EchoClient({ auth: authStub as unknown as GoogleAuth, credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); // Mock request const request = {}; // Mock Grpc layer client.innerApiCalls.wait = mockLongRunningGrpcMethod( request, null, error ); client .wait(request) .then(responses => { const operation = responses[0]; return operation.promise(); }) .then(() => { assert.fail(); }) .catch((err: {code: number}) => { assert(err instanceof Error); assert.strictEqual(err.code, FAKE_STATUS_CODE); done(); }); }); it('has longrunning decoder functions', () => { const client = new EchoClient({ auth: authStub as unknown as GoogleAuth, credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); assert( client.descriptors.longrunning.wait.responseDecoder instanceof Function ); assert( client.descriptors.longrunning.wait.metadataDecoder instanceof Function ); }); }); }); function mockSimpleGrpcMethod( expectedRequest: {}, response: {} | null, error?: {} ) { return (actualRequest: {}, options: {}, callback: Function) => { assert.deepStrictEqual(actualRequest, expectedRequest); if (error) { callback(error); } else if (response) { callback(null, response); } else { callback(null); } }; } function mockServerStreamingGrpcMethod( expectedRequest: {}, response: {} | null, error?: Error ) { return (actualRequest: Function) => { assert.deepStrictEqual(actualRequest, expectedRequest); const mockStream = new Transform({ objectMode: true, transform: (chunk, enc, callback) => { if (error) { callback(error); } else { callback(undefined, response); } }, }); return mockStream; }; } function mockBidiStreamingGrpcMethod( expectedRequest: {}, response: {} | null, error?: Error ) { return () => { const mockStream = new Transform({ objectMode: true, transform: (chunk, enc, callback) => { assert.deepStrictEqual(chunk, expectedRequest); if (error) { callback(error); } else { callback(undefined, response); } }, }); return mockStream; }; } function mockLongRunningGrpcMethod( expectedRequest: {}, response: {} | null, error?: {} ) { return (request: Function) => { assert.deepStrictEqual(request, expectedRequest); const mockOperation = { promise() { return new Promise((resolve, reject) => { if (error) { reject(error); } else { resolve([response]); } }); }, }; return Promise.resolve([mockOperation]); }; }
the_stack
import { Applicative as ApplicativeHKT, Applicative1 } from 'fp-ts/lib/Applicative' import { Apply1 } from 'fp-ts/lib/Apply' import * as A from 'fp-ts/lib/Array' import * as Eq from 'fp-ts/lib/Eq' import { Foldable1, intercalate } from 'fp-ts/lib/Foldable' import { flow, Predicate, Refinement } from 'fp-ts/lib/function' import { Functor1 } from 'fp-ts/lib/Functor' import { HKT } from 'fp-ts/lib/HKT' import { Monad1 } from 'fp-ts/lib/Monad' import { Monoid, monoidString } from 'fp-ts/lib/Monoid' import * as O from 'fp-ts/lib/Option' import { pipe } from 'fp-ts/lib/pipeable' import { Semigroup } from 'fp-ts/lib/Semigroup' import { Show } from 'fp-ts/lib/Show' import { Traversable1 } from 'fp-ts/lib/Traversable' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 0.1.8 */ export interface Nil { readonly type: 'Nil' readonly length: 0 } /** * @category model * @since 0.1.8 */ export interface Cons<A> { readonly type: 'Cons' readonly head: A readonly tail: List<A> readonly length: number } /** * @category model * @since 0.1.8 */ export type List<A> = Nil | Cons<A> // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 0.1.8 */ export const nil: List<never> = { type: 'Nil', length: 0 } /** * Attaches an element to the front of a list. * * @example * import * as L from 'fp-ts-contrib/List' * * assert.deepStrictEqual(L.cons('a', L.nil), { type: 'Cons', head: 'a', tail: L.nil, length: 1 }) * * @category constructors * @since 0.1.8 */ export const cons: <A>(head: A, tail: List<A>) => List<A> = (head, tail) => ({ type: 'Cons', head, tail, length: 1 + tail.length }) /** * Creates a list from an array * * @example * import * as L from 'fp-ts-contrib/List' * * assert.deepStrictEqual(L.fromArray([]), L.nil) * assert.deepStrictEqual(L.fromArray(['a', 'b']), L.cons('a', L.of('b'))) * * @category constructors * @since 0.1.8 */ export const fromArray = <A>(as: Array<A>): List<A> => A.array.reduceRight<A, List<A>>(as, nil, cons) // ------------------------------------------------------------------------------------- // destructors // ------------------------------------------------------------------------------------- /** * Gets the first element in a list, or `None` if the list is empty. * * @example * import * as O from 'fp-ts/Option' * import * as L from 'fp-ts-contrib/List' * * assert.deepStrictEqual(L.head(L.nil), O.none) * assert.deepStrictEqual(L.head(L.cons('x', L.of('a'))), O.some('x')) * * @category destructors * @since 0.1.8 */ export const head: <A>(fa: List<A>) => O.Option<A> = (fa) => (isCons(fa) ? O.some(fa.head) : O.none) /** * Gets all but the first element of a list, or `None` if the list is empty. * * @example * import * as O from 'fp-ts/Option' * import * as L from 'fp-ts-contrib/List' * * assert.deepStrictEqual(L.tail(L.nil), O.none) * assert.deepStrictEqual(L.tail(L.of('a')), O.some(L.nil)) * assert.deepStrictEqual(L.tail(L.cons('x', L.of('a'))), O.some(L.of('a'))) * * @category destructors * @since 0.1.8 */ export const tail: <A>(fa: List<A>) => O.Option<List<A>> = (fa) => (isCons(fa) ? O.some(fa.tail) : O.none) /** * Breaks a list into its first element and the remaining elements. * * @example * import * as L from 'fp-ts-contrib/List' * * const len: <A>(as: L.List<A>) => number = L.foldLeft( * () => 0, * (_, tail) => 1 + len(tail) * ) * assert.deepStrictEqual(len(L.cons('a', L.of('b'))), 2) * * @category destructors * @since 0.1.8 */ export const foldLeft: <A, B>(onNil: () => B, onCons: (head: A, tail: List<A>) => B) => (fa: List<A>) => B = ( onNil, onCons ) => (fa) => (isNil(fa) ? onNil() : onCons(fa.head, fa.tail)) /** * Gets an array from a list. * * @example * import * as L from 'fp-ts-contrib/List' * * assert.deepStrictEqual(L.toArray(L.cons('a', L.of('b'))), ['a', 'b']) * * @category destructors * @since 0.1.8 */ export const toArray = <A>(fa: List<A>): Array<A> => { const length = fa.length const out: Array<A> = new Array(length) let l: List<A> = fa for (let i = 0; i < length; i++) { out[i] = (l as Cons<A>).head l = (l as Cons<A>).tail } return out } /** * Gets an array from a list in a reversed order. * * @example * import * as L from 'fp-ts-contrib/List' * * assert.deepStrictEqual(L.toReversedArray(L.cons('a', L.of('b'))), ['b', 'a']) * * @category destructors * @since 0.1.8 */ export const toReversedArray = <A>(fa: List<A>): Array<A> => { const length = fa.length const out: Array<A> = new Array(length) let l: List<A> = fa for (let i = 0; i < length; i++) { out[length - i - 1] = (l as Cons<A>).head l = (l as Cons<A>).tail } return out } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * Reverse a list. * * @example * import * as L from 'fp-ts-contrib/List' * * assert.deepStrictEqual(L.reverse(L.cons(1, L.cons(2, L.of(3)))), L.cons(3, L.cons(2, L.of(1)))) * * @category combinators * @since 0.1.8 */ export const reverse = <A>(fa: List<A>): List<A> => { let out: List<A> = nil let l = fa while (isCons(l)) { out = cons(l.head, out) l = l.tail } return out } /** * Drops the specified number of elements from the front of a list. * * @example * import * as L from 'fp-ts-contrib/List' * * assert.deepStrictEqual(L.dropLeft(1)(L.nil), L.nil) * assert.deepStrictEqual(L.dropLeft(1)(L.cons(1, L.of(2))), L.of(2)) * assert.deepStrictEqual(L.dropLeft(3)(L.cons(1, L.of(2))), L.nil) * * @category combinators * @since 0.1.8 */ export const dropLeft = (n: number) => <A>(fa: List<A>): List<A> => { if (isNil(fa)) return nil let i = 0 let l: List<A> = fa while (isCons(l) && i < n) { i++ l = l.tail } return l } /** * Drops those elements from the front of a list which match a predicate. * * @example * import * as L from 'fp-ts-contrib/List' * * const isLTThree = (n: number) => n < 3 * assert.deepStrictEqual(L.dropLeftWhile(isLTThree)(L.nil), L.nil) * assert.deepStrictEqual(L.dropLeftWhile(isLTThree)(L.cons(1, L.cons(2, L.of(3)))), L.of(3)) * assert.deepStrictEqual(L.dropLeftWhile(isLTThree)(L.cons(1, L.of(2))), L.nil) * * @since 0.1.8 */ export function dropLeftWhile<A, B extends A>(refinement: Refinement<A, B>): (fa: List<A>) => List<B> export function dropLeftWhile<A>(predicate: Predicate<A>): (fa: List<A>) => List<A> export function dropLeftWhile<A>(predicate: Predicate<A>): (fa: List<A>) => List<A> { return (fa) => { if (isNil(fa)) return nil let l: List<A> = fa while (isCons(l) && predicate(l.head)) { l = l.tail } return l } } // ------------------------------------------------------------------------------------- // non-pipeables // ------------------------------------------------------------------------------------- const map_: Functor1<URI>['map'] = (fa, f) => pipe(fa, map(f)) const ap_: Apply1<URI>['ap'] = (fab, fa) => pipe(fab, ap(fa)) const chain_: Monad1<URI>['chain'] = (ma, f) => pipe(ma, chain(f)) const reduce_: Foldable1<URI>['reduce'] = (fa, b, f) => pipe(fa, reduce(b, f)) const reduceRight_: Foldable1<URI>['reduceRight'] = (fa, b, f) => pipe(fa, reduceRight(b, f)) const foldMap_: Foldable1<URI>['foldMap'] = (M) => (fa, f) => pipe(fa, foldMap(M)(f)) const traverse_ = <F>(F: ApplicativeHKT<F>): (<A, B>(ta: List<A>, f: (a: A) => HKT<F, B>) => HKT<F, List<B>>) => { return <A, B>(ta: List<A>, f: (a: A) => HKT<F, B>) => list.reduceRight(ta, F.of<List<B>>(nil), (a, fbs) => F.ap( F.map(fbs, (bs) => (b: B) => cons(b, bs)), f(a) ) ) } const sequence_ = <F>(F: ApplicativeHKT<F>) => <A>(ta: List<HKT<F, A>>): HKT<F, List<A>> => { return list.reduceRight(ta, F.of<List<A>>(nil), (a, fas) => F.ap( F.map(fas, (as) => (a: A) => cons(a, as)), a ) ) } // ------------------------------------------------------------------------------------- // pipeables // ------------------------------------------------------------------------------------- /** * @category Functor * @since 0.1.18 */ export const map = <A, B>(f: (a: A) => B) => (fa: List<A>): List<B> => pipe( toArray(fa), A.reduceRight<A, List<B>>(nil, (a, b) => cons(f(a), b)) ) /** * @category Functor * @since 0.1.20 */ export const ap: <A>(fa: List<A>) => <B>(fab: List<(a: A) => B>) => List<B> = (fa) => chain((f) => pipe(fa, map(f))) /** * @category Apply * @since 0.1.20 */ export const apFirst: <B>(fb: List<B>) => <A>(fa: List<A>) => List<A> = (fb) => flow( map((a) => () => a), ap(fb) ) /** * @category Apply * @since 0.1.20 */ export const apSecond = <B>(fb: List<B>): (<A>(fa: List<A>) => List<B>) => flow( map(() => (b: B) => b), ap(fb) ) /** * @category Monad * @since 0.1.20 */ export const chain = <A, B>(f: (a: A) => List<B>) => (ma: List<A>): List<B> => pipe( ma, foldLeft( () => nil, (x, xs) => { const S = getSemigroup<B>() let out = f(x) let l = xs while (isCons(l)) { out = S.concat(out, f(l.head)) l = l.tail } return out } ) ) /** * @category Monad * @since 0.1.20 */ export const chainFirst: <A, B>(f: (a: A) => List<B>) => (fa: List<A>) => List<A> = (f) => chain((a) => pipe( f(a), map(() => a) ) ) /** * @category Foldable * @since 0.1.18 */ export const reduce: <A, B>(b: B, f: (b: B, a: A) => B) => (fa: List<A>) => B = (b, f) => (fa) => { let out = b let l = fa while (isCons(l)) { out = f(out, l.head) l = l.tail } return out } /** * @category Foldable * @since 0.1.18 */ export const reduceRight: <A, B>(b: B, f: (a: A, b: B) => B) => (fa: List<A>) => B = (b, f) => (fa) => pipe(toArray(fa), A.reduceRight(b, f)) /** * @category Foldable * @since 0.1.18 */ export const foldMap: <M>(M: Monoid<M>) => <A>(f: (a: A) => M) => (fa: List<A>) => M = (M) => (f) => (fa) => { let out = M.empty let l = fa while (isCons(l)) { out = M.concat(out, f(l.head)) l = l.tail } return out } // TODO: add pipeable traverse when fp-ts version >= 2.6.3 // /** // * @category Traversable // * @since 0.1.18 // */ // export const traverse: PipeableTraverse1<URI> = <F>( // F: Applicative<F> // ): (<A, B>(f: (a: A) => HKT<F, B>) => (ta: List<A>) => HKT<F, List<B>>) => { // const traverseF = traverse_(F) // return f => ta => traverseF(ta, f) // } /** * @category Traversable * @since 0.1.18 */ export const sequence: Traversable1<URI>['sequence'] = <F>( F: ApplicativeHKT<F> ): (<A>(ta: List<HKT<F, A>>) => HKT<F, List<A>>) => sequence_(F) /** * Creates a list with a single element. * * @example * import * as L from 'fp-ts-contrib/List' * * assert.deepStrictEqual(L.of('a'), L.cons('a', L.nil)) * * @category Applicative * @since 0.1.8 */ export const of: <A>(head: A) => List<A> = (head) => cons(head, nil) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Finds the first index for which a predicate holds. * * @example * import * as O from 'fp-ts/Option' * import * as L from 'fp-ts-contrib/List' * * const f = (a: number): boolean => a % 2 === 0 * const findIndexEven = L.findIndex(f) * assert.deepStrictEqual(findIndexEven(L.nil), O.none) * assert.deepStrictEqual(findIndexEven(L.cons(1, L.of(2))), O.some(1)) * assert.deepStrictEqual(findIndexEven(L.of(1)), O.none) * * @since 0.1.8 */ export const findIndex = <A>(predicate: Predicate<A>) => (fa: List<A>): O.Option<number> => { let l: List<A> = fa let i = 0 while (isCons(l)) { if (predicate(l.head)) return O.some(i) l = l.tail i++ } return O.none } // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- /** * @category instances * @since 0.1.8 */ export const URI = 'List' /** * @category instances * @since 0.1.8 */ export type URI = typeof URI declare module 'fp-ts/lib/HKT' { interface URItoKind<A> { List: List<A> } } /** * Derives an `Eq` over the `List` of a given element type from the `Eq` of that type. * The derived `Eq` defines two lists as equal if all elements of both lists * are compared equal pairwise with the given `E`. In case of lists of different * lengths, the result is non equality. * * @example * import { eqString } from 'fp-ts/Eq' * import * as L from 'fp-ts-contrib/List' * * const E = L.getEq(eqString) * assert.strictEqual(E.equals(L.cons('a', L.of('b')), L.cons('a', L.of('b'))), true) * assert.strictEqual(E.equals(L.of('x'), L.nil), false) * * @category instances * @since 0.1.8 */ export const getEq = <A>(E: Eq.Eq<A>): Eq.Eq<List<A>> => ({ equals: (x, y) => { if (x.length !== y.length) return false let lx = x let ly = y while (isCons(lx) && isCons(ly)) { if (!E.equals(lx.head, ly.head)) return false lx = lx.tail ly = ly.tail } return true } }) /** * @category instances * @since 0.1.20 */ export const getShow = <A>(S: Show<A>): Show<List<A>> => ({ show: (as) => pipe( as, map(S.show), foldLeft( () => 'Nil', (x, xs) => `(${intercalate(monoidString, Foldable)(' : ', cons(x, xs))} : Nil)` ) ) }) /** * @category instances * @since 0.1.20 */ export const getSemigroup = <A>(): Semigroup<List<A>> => ({ concat: (xs, ys) => pipe(xs, reduceRight(ys, cons)) }) /** * @category instances * @since 0.1.20 */ export const getMonoid = <A>(): Monoid<List<A>> => ({ ...getSemigroup(), empty: nil }) /** * @category instances * @since 0.1.18 */ export const Functor: Functor1<URI> = { URI, map: map_ } /** * @category instances * @since 0.1.20 */ export const Apply: Apply1<URI> = { URI, map: map_, ap: ap_ } /** * @category instances * @since 0.1.20 */ export const Applicative: Applicative1<URI> = { URI, map: map_, ap: ap_, of } /** * @category instances * @since 0.1.20 */ export const Monad: Monad1<URI> = { URI, map: map_, ap: ap_, of, chain: chain_ } /** * @category instances * @since 0.1.18 */ export const Foldable: Foldable1<URI> = { URI, foldMap: foldMap_, reduce: reduce_, reduceRight: reduceRight_ } /** * @category instances * @since 0.1.18 */ export const Traversable: Traversable1<URI> = { URI, map: map_, foldMap: foldMap_, reduce: reduce_, reduceRight: reduceRight_, traverse: traverse_, sequence: sequence_ } /** * @category instances * @since 0.1.8 */ export const list: Functor1<URI> & Foldable1<URI> & Traversable1<URI> = { URI, map: map_, reduce: reduce_, foldMap: foldMap_, reduceRight: reduceRight_, traverse: traverse_, sequence: sequence_ } // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @internal */ const bind_ = <A, N extends string, B>( a: A, name: Exclude<N, keyof A>, b: B ): { [K in keyof A | N]: K extends keyof A ? A[K] : B } => Object.assign({}, a, { [name]: b }) as any /** * @since 0.1.20 */ export const bindTo = <N extends string>(name: N) => <A>(fa: List<A>): List<{ [K in N]: A }> => pipe( fa, map((a) => bind_({}, name, a)) ) /** * @since 0.1.20 */ export const bind = <N extends string, A, B>(name: Exclude<N, keyof A>, f: (a: A) => List<B>) => ( fa: List<A> ): List<{ [K in keyof A | N]: K extends keyof A ? A[K] : B }> => pipe( fa, chain((a) => pipe( f(a), map((b) => bind_(a, name, b)) ) ) ) // ------------------------------------------------------------------------------------- // pipeable sequence S // ------------------------------------------------------------------------------------- /** * @since 0.1.20 */ export const apS = <A, N extends string, B>( name: Exclude<N, keyof A>, fb: List<B> ): ((fa: List<A>) => List<{ [K in keyof A | N]: K extends keyof A ? A[K] : B }>) => flow( map((a) => (b: B) => bind_(a, name, b)), ap(fb) ) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * Tests whether a list is an empty list. * * @example * import * as L from 'fp-ts-contrib/List' * * assert.strictEqual(L.isNil(L.nil), true) * assert.strictEqual(L.isNil(L.of(6)), false) * * @since 0.1.8 */ export const isNil = <A>(a: List<A>): a is Nil => a.type === 'Nil' /** * Tests whether a list is a non empty list. * * @example * import * as L from 'fp-ts-contrib/List' * * assert.strictEqual(L.isCons(L.nil), false) * assert.strictEqual(L.isCons(L.of(1)), true) * * @since 0.1.8 */ export const isCons = <A>(a: List<A>): a is Cons<A> => a.type === 'Cons'
the_stack
import React, { useState, useEffect } from "react"; import firebase from "firebase" import "firebase/functions" import { createStyles, makeStyles, Theme } from "@material-ui/core/styles"; import Table from "@material-ui/core/Table"; import TableBody from "@material-ui/core/TableBody"; import TableCell from "@material-ui/core/TableCell"; import TableRow from "@material-ui/core/TableRow"; import Dialog from "@material-ui/core/Dialog"; import DialogActions from "@material-ui/core/DialogActions"; import DialogContent from "@material-ui/core/DialogContent"; import DialogContentText from "@material-ui/core/DialogContentText"; import DialogTitle from "@material-ui/core/DialogTitle"; import CircularProgress from "@material-ui/core/CircularProgress"; import DoneIcon from "@material-ui/icons/Done"; import Button from "@material-ui/core/Button"; import { useAuthUser } from "hooks/auth" import TextField, { useTextField } from "components/TextField" import Select, { useSelect } from "components/Select" import Account from "models/account/Account" import { Create, Individual } from "common/commerce/account" import Grid from "@material-ui/core/Grid"; import { Box } from "@material-ui/core"; import { SupportedCountries, CountryCode } from "common/Country"; import { nullFilter } from "utils" import Loading from "components/Loading" import RegisterableCountries from "config/RegisterableCountries" import { Gender } from "common/Gender" const useStyles = makeStyles((theme: Theme) => createStyles({ box: { padding: theme.spacing(2), backgroundColor: "#fafafa" }, bottomBox: { padding: theme.spacing(2), display: "flex", justifyContent: "flex-end" }, input: { backgroundColor: "#fff" }, cell: { borderBottom: "none", padding: theme.spacing(1), }, cellStatus: { borderBottom: "none", padding: theme.spacing(1), width: "48px", }, cellStatusBox: { display: "flex", justifyContent: "center", alignItems: "center" } }), ); export default ({ individual, onCallback }: { individual: Partial<Individual>, onCallback?: (next: boolean) => void }) => { const classes = useStyles() const [authUser] = useAuthUser() const [open, setOpen] = useState(false) const [error, setError] = useState<string | undefined>() const [first_name_kana] = useTextField(individual.first_name, { inputProps: { pattern: "^[A-Za-zァ-ヴー・]{1,32}" }, required: true }) const [last_name_kana] = useTextField(individual.last_name, { inputProps: { pattern: "^[A-Za-zァ-ヴー・]{1,32}" }, required: true }) const [first_name_kanji] = useTextField(individual.first_name, { inputProps: { pattern: "^.{1,32}" }, required: true }) const [last_name_kanji] = useTextField(individual.last_name, { inputProps: { pattern: "^.{1,32}" }, required: true }) const [year] = useTextField(String(individual.dob?.year), { inputProps: { pattern: "^[12][0-9]{3}$" }, required: true }) const [month] = useTextField(String(individual.dob?.month), { inputProps: { pattern: "^(0?[1-9]|1[012])$" }, required: true }) const [day] = useTextField(String(individual.dob?.day), { inputProps: { pattern: "^(([0]?[1-9])|([1-2][0-9])|(3[01]))$" }, required: true }) const gender = useSelect({ initValue: individual.gender || "male", inputProps: { menu: [ { label: "男性", value: "male" }, { label: "女性", value: "female" } ] }, controlProps: { variant: "outlined" } }) const [postal_code, setPostalCode] = useTextField(individual.address?.postal_code, { required: true }) const state = useSelect({ initValue: individual.address?.country || "US", inputProps: { menu: SupportedCountries.map(country => { return { value: country.alpha2, label: country.name } }) }, controlProps: { variant: "outlined" } }) const [state_kanji, setState] = useTextField(individual.address_kanji?.state, { inputProps: { pattern: "^.{1,32}" }, required: true }) const [city_kanji, setCity] = useTextField(individual.address_kanji?.city, { inputProps: { pattern: "^.{1,32}" }, required: true }) const [town_kanji, setTown] = useTextField(individual.address_kanji?.line1, { inputProps: { pattern: "^.{1,32}" } }) const [line1_kanji] = useTextField(individual.address_kanji?.line1, { inputProps: { pattern: "^.{1,32}" }, required: true }) const [line2_kanji] = useTextField(individual.address_kanji?.line2) const [state_kana, setStateKana] = useTextField(individual.address_kana?.state, { inputProps: { pattern: "^[A-Za-zァ-ヴー・]{1,32}" }, required: true }) const [city_kana, setCityKana] = useTextField(individual.address_kana?.city, { inputProps: { pattern: "^[A-Za-zァ-ヴー・]{1,32}" }, required: true }) const [town_kana, setTownKana] = useTextField(individual.address_kana?.city, { inputProps: { pattern: "^[0-9A-Za-zァ-ヴー・\-]{1,32}" } }) const [line1_kana] = useTextField(individual.address_kana?.line1, { inputProps: { pattern: "^[0-9A-Za-zァ-ヴー・\-]{1,32}" }, required: true }) const [line2_kana] = useTextField(individual.address_kana?.line2, { inputProps: { pattern: "^[0-9A-Za-zァ-ヴー・\-]{1,32}" } }) useEffect(() => { if ((postal_code.value as string).length > 5) { const request = new Request(`https://jp-zipcode-e1b50.web.app/_/v1/address?code=${postal_code.value}`); fetch(request) .then(response => response.json()) .then(addresses => { if (addresses.length) { const address = addresses[0] const { state_kana, city_kana, town_kana, state, city, town } = address setState(state) setCity(city) setTown(town) setStateKana(state_kana) setCityKana(city_kana) setTownKana(town_kana) } }) } }, [postal_code.value]) const addressDisabled = (postal_code.value as string).length < 6 const [email] = useTextField(individual.email, { required: true, type: "email" }) const [phone] = useTextField(individual.phone, { required: true, type: "tel" }) const [front, setFront] = useState<string | undefined>() const [back, setBack] = useState<string | undefined>() const [isFrontLoading, setFrontLoading] = useState(false) const [isBackLoading, setBackLoading] = useState(false) const [isLoading, setLoading] = useState(false) const handleClose = () => setOpen(false) const handleSubmit = async (event) => { event.preventDefault(); const uid = authUser?.uid if (!uid) return let data: Create = { type: "custom", country: "JP", business_type: "individual", requested_capabilities: ["card_payments", "transfers"], individual: { first_name_kanji: first_name_kanji.value as string, last_name_kanji: last_name_kanji.value as string, first_name_kana: first_name_kana.value as string, last_name_kana: last_name_kana.value as string, dob: { year: Number(year.value), month: Number(month.value), day: Number(day.value) }, gender: gender.value as Gender, address_kanji: { country: "JP", state: state_kanji.value as string, city: city_kanji.value as string, town: town_kanji.value as string, line1: line1_kanji.value as string, line2: line2_kanji.value as string, postal_code: postal_code.value as string }, address_kana: { country: "JP", state: state_kana.value as string, city: city_kana.value as string, town: town_kana.value as string, line1: line1_kana.value as string, line2: line2_kana.value as string, postal_code: postal_code.value as string }, email: email.value as string, phone: phone.value as string, verification: { document: { front: front, back: back } } } } data = nullFilter(data) setLoading(true) const accountCreate = firebase.app().functions("us-central1").httpsCallable("account-v1-account-create") try { const response = await accountCreate(data) const { result, error } = response.data if (error) { setError(error.message) setLoading(false) setOpen(true) return } // const account = new Account(uid) // account.accountID = result.id // account.country = result.country // account.businessType = result.business_type // account.email = result.email // account.individual = result.individual // await account.save() setLoading(false) if (onCallback) { onCallback(true) } } catch (error) { setLoading(false) setOpen(true) console.log(error) } } const handleFrontCapture = async ({ target }) => { const uid = authUser?.uid if (!uid) return setFront(undefined) setFrontLoading(true) const file = target.files[0] as File const ref = firebase.storage().ref(new Account(uid).documentReference.path + "/verification/front.jpg") ref.put(file).then(async (snapshot) => { if (snapshot.state === "success") { const metadata = snapshot.metadata const { bucket, fullPath, name, contentType } = metadata const uploadFile = firebase.functions().httpsCallable("stripe-v1-file-upload") try { const result = await uploadFile({ bucket, fullPath, name, contentType, purpose: "identity_document" }) const data = result.data if (data) { setFront(data.id) } } catch (error) { console.error(error) } } setFrontLoading(false) }) } const handleBackCapture = async ({ target }) => { const uid = authUser?.uid if (!uid) return setBack(undefined) setBackLoading(true) const file = target.files[0] as File const ref = firebase.storage().ref(new Account(uid).documentReference.path + "/verification/back.jpg") ref.put(file).then(async (snapshot) => { if (snapshot.state === "success") { const metadata = snapshot.metadata const { bucket, fullPath, name, contentType } = metadata const uploadFile = firebase.functions().httpsCallable("stripe-v1-file-upload") try { const result = await uploadFile({ bucket, fullPath, name, contentType, purpose: "identity_document" }) const data = result.data if (data) { setBack(data.id) } } catch (error) { console.error(error) } } setBackLoading(false) }) } return ( <> <form onSubmit={handleSubmit}> <Box className={classes.box} > <Grid container spacing={2}> <Grid item xs={12} sm={6}> <Table size="small"> <TableBody> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">姓</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="姓" variant="outlined" margin="dense" size="small" {...last_name_kanji} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">名前</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="名前" variant="outlined" margin="dense" size="small" {...first_name_kanji} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">姓(カナ)</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="姓(カナ)" variant="outlined" margin="dense" size="small" {...last_name_kana} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">名前(カナ)</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="名前(カナ)" variant="outlined" margin="dense" size="small" {...first_name_kana} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">email</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="email" variant="outlined" margin="dense" size="small" {...email} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">電話番号</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="電話番号" variant="outlined" margin="dense" size="small" {...phone} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">生年月日</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="年" type="number" variant="outlined" margin="dense" size="small" {...year} style={{ width: "80px", marginRight: "8px" }} /> <TextField className={classes.input} label="月" type="number" variant="outlined" margin="dense" size="small" {...month} style={{ width: "66px", marginRight: "8px" }} /> <TextField className={classes.input} label="日" type="number" variant="outlined" margin="dense" size="small" {...day} style={{ width: "66px" }} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">性別</TableCell> <TableCell className={classes.cell} align="left"> <Select {...gender} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}> <Box className={classes.cellStatusBox}> {isFrontLoading && <CircularProgress size={16} />} {(!isFrontLoading && front) && <DoneIcon color="primary" />} </Box> </TableCell> <TableCell className={classes.cell} align="right">身分証明書 (表)</TableCell> <TableCell className={classes.cell} align="left"> <input accept="image/jpeg,image/png,application/pdf" type="file" onChange={handleFrontCapture} required /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}> <Box className={classes.cellStatusBox}> {isBackLoading && <CircularProgress size={16} />} {(!isBackLoading && back) && <DoneIcon color="primary" />} </Box> </TableCell> <TableCell className={classes.cell} align="right">身分証明書 (裏))</TableCell> <TableCell className={classes.cell} align="left"> <input accept="image/jpeg,image/png,application/pdf" type="file" onChange={handleBackCapture} required /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right"></TableCell> <TableCell className={classes.cell} align="left"> <Box fontSize={10}> 身分証明書はパスポートまたは、免許証、健康保険証を撮影し添付してください。 </Box> </TableCell> </TableRow> </TableBody> </Table> </Grid> <Grid item xs={12} sm={6}> <Table size="small"> <TableBody> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">郵便番号</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="郵便番号" variant="outlined" margin="dense" size="small" {...postal_code} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">都道府県</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="都道府県" variant="outlined" margin="dense" size="small" disabled={addressDisabled} {...state_kanji} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">市区町村</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="市区町村" variant="outlined" margin="dense" size="small" disabled={addressDisabled} {...city_kanji} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">町名(丁目まで)</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="町名(丁目まで)" variant="outlined" margin="dense" size="small" disabled={addressDisabled} {...town_kanji} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">番地など</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="番地など" variant="outlined" margin="dense" size="small" disabled={addressDisabled} {...line1_kanji} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">アパート名など</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="アパート名など" variant="outlined" margin="dense" size="small" disabled={addressDisabled} {...line2_kanji} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">都道府県(カナ)</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="都道府県(カナ)" variant="outlined" margin="dense" size="small" disabled={addressDisabled} {...state_kana} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">市区町村(カナ)</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="市区町村(カナ)" variant="outlined" margin="dense" size="small" disabled={addressDisabled} {...city_kana} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">町名(丁目まで、カナ)</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="町名(丁目まで、カナ)" variant="outlined" margin="dense" size="small" disabled={addressDisabled} {...town_kana} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">番地など(カナ)</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="番地など(カナ)" variant="outlined" margin="dense" size="small" disabled={addressDisabled} {...line1_kana} /> </TableCell> </TableRow> <TableRow> <TableCell className={classes.cellStatus}></TableCell> <TableCell className={classes.cell} align="right">アパート名など(カナ)</TableCell> <TableCell className={classes.cell} align="left"> <TextField className={classes.input} label="アパート名など(カナ)" variant="outlined" margin="dense" size="small" disabled={addressDisabled} {...line2_kana} /> </TableCell> </TableRow> </TableBody> </Table> </Grid> </Grid> </Box> <Box className={classes.bottomBox} > <Button style={{}} size="medium" color="primary" onClick={() => { if (onCallback) { onCallback(false) } }}>Back</Button> <Button style={{}} variant="contained" size="medium" color="primary" type="submit">Save</Button> </Box> </form> {isLoading && <Loading />} <Dialog open={open} onClose={handleClose} > <DialogTitle>Error</DialogTitle> <DialogContent> <DialogContentText> {error ? error : "Account registration failed."} </DialogContentText> </DialogContent> <DialogActions> <Button onClick={handleClose} color="primary" autoFocus> OK </Button> </DialogActions> </Dialog> </> ) }
the_stack
import { PromptValidator, PromptOptions, PromptRecognizerResult } from 'botbuilder-dialogs'; import { DialogTurnResult, Dialog, DialogContext } from 'botbuilder-dialogs'; import { InputHints, TurnContext, Activity, Attachment } from 'botbuilder-core'; /** * Settings to control the behavior of AdaptiveCardPrompt */ export interface AdaptiveCardPromptSettings { /** * An Adaptive Card. Required. * @remarks * Add the card here. Do not pass it in to `Prompt.Attachments` or it will show twice. */ card: Attachment; /** * Array of strings matching IDs of required input fields * * @example * The ID strings must exactly match those used in the Adaptive Card JSON Input IDs * For JSON: * ```json * { * "type": "Input.Text", * "id": "myCustomId", * }, *``` * You would use `"myCustomId"` if you want that to be a required input. */ requiredInputIds?: string[]; /** * ID specific to this prompt. * @requires * If used, you MUST add this promptId to every <submit>.data.promptId in your Adaptive Card. * * @remarks * Card input is only accepted if SubmitAction.data.promptId matches the promptId. * Does not change between reprompts. */ promptId?: string; } /** * Additional items to include on PromptRecognizerResult, as necessary */ export interface AdaptiveCardPromptResult { /** * The value of the user's input from the Adaptive Card. */ data?: object; /** * If not recognized.succeeded, include reason why, if known */ error?: AdaptiveCardPromptErrors; /** * Include which requiredIds were not included with user input */ missingIds?: string[]; } /** * AdaptiveCardPrompt catches certain common errors that are passed to validator, if present * This allows developers to handle these specific errors as they choose * These are given in validator context.recognized.value.error */ export enum AdaptiveCardPromptErrors { /** * No known user errors. */ none, /** * Error presented if developer specifies AdaptiveCardPromptSettings.promptId, * but user submits adaptive card input on a card where the ID does not match. * This error will also be present if developer AdaptiveCardPromptSettings.promptId, * but forgets to add the promptId to every <submit>.data.promptId in your Adaptive Card. */ userInputDoesNotMatchCardId, /** * Error presented if developer specifies AdaptiveCardPromptSettings.requiredIds, * but user does not submit input for all required input id's on the adaptive card */ missingRequiredIds, /** * Error presented if user enters plain text instead of using Adaptive Card's input fields */ userUsedTextInput } /** * Waits for Adaptive Card Input to be received. * * @remarks * This prompt is similar to ActivityPrompt but provides features specific to Adaptive Cards: * * Optionally allow specified input fields to be required * * Optionally ensures input is only valid if it comes from the appropriate card (not one shown previous to prompt) * * Provides ability to handle variety of common user errors related to Adaptive Cards * DO NOT USE WITH CHANNELS THAT DON'T SUPPORT ADAPTIVE CARDS */ export class AdaptiveCardPrompt extends Dialog { private validator: PromptValidator<object>; private requiredInputIds: string[]; private promptId: string; private card: Attachment; /** * Creates a new AdaptiveCardPrompt instance * @param dialogId Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`. * @param settings (optional) Additional options for AdaptiveCardPrompt behavior * @param validator (optional) Validator that will be called each time a new activity is received. Validator should handle error messages on failures. */ public constructor(dialogId: string, settings: AdaptiveCardPromptSettings, validator?: PromptValidator<object>) { super(dialogId); if (!settings || !settings.card) { throw new Error('AdaptiveCardPrompt requires a card in `AdaptiveCardPromptSettings.card`'); } this.validator = validator; this.requiredInputIds = settings.requiredInputIds || []; this.throwIfNotAdaptiveCard(settings.card); this.card = settings.card; // Don't allow promptId to be something falsy if (settings.promptId !== undefined && !settings.promptId) { throw new Error('AdaptiveCardPromptSettings.promptId cannot be a falsy string'); } this.promptId = settings.promptId; } public async beginDialog(dc: DialogContext, options: PromptOptions): Promise<DialogTurnResult> { // Initialize prompt state const state: AdaptiveCardPromptState = dc.activeDialog.state; state.options = options; state.state = {}; // Send initial prompt await this.onPrompt(dc.context, state.state, state.options, false); return Dialog.EndOfTurn; } protected async onPrompt(context: TurnContext, state: object, options: PromptOptions, isRetry: boolean): Promise<void> { // Since card is passed in via AdaptiveCardPromptSettings, PromptOptions may not be used. // Ensure we're working with RetryPrompt, as applicable let prompt: Partial<Activity> | string; if (options) { prompt = isRetry && options.retryPrompt ? options.retryPrompt || {} : options.prompt || {}; } else { prompt = {}; } // Clone the correct prompt so that we don't affect the one saved in state let clonedPrompt = JSON.parse(JSON.stringify(prompt)); // Create a prompt if user didn't pass it in through PromptOptions or if they passed in a string if (!clonedPrompt || typeof(prompt) != 'object' || Object.keys(prompt).length === 0) { clonedPrompt = { text: typeof(prompt) === 'string' ? prompt : undefined, }; } // Depending on how the prompt is called, when compiled to JS, activity attachments may be on prompt or options const existingAttachments = clonedPrompt.attachments || options ? options['attachments'] : []; // Add Adaptive Card as last attachment (user input should go last), keeping any others clonedPrompt.attachments = existingAttachments ? [...existingAttachments, this.card] : [this.card]; await context.sendActivity(clonedPrompt, undefined, InputHints.ExpectingInput); } // Override continueDialog so that we can catch activity.value (which is ignored, by default) public async continueDialog(dc: DialogContext): Promise<DialogTurnResult> { // Perform base recognition const state: AdaptiveCardPromptState = dc.activeDialog.state; const recognized: PromptRecognizerResult<AdaptiveCardPromptResult> = await this.onRecognize(dc.context); if (state.state['attemptCount'] === undefined) { state.state['attemptCount'] = 1; } else { state.state['attemptCount']++; } let isValid = false; if (this.validator) { isValid = await this.validator({ context: dc.context, recognized: recognized, state: state.state, options: state.options, attemptCount: state.state['attemptCount'] }); } else if (recognized.succeeded) { isValid = true; } // Return recognized value or re-prompt if (isValid) { return await dc.endDialog(recognized.value); } else { // Re-prompt if (!dc.context.responded) { await this.onPrompt(dc.context, state.state, state.options, true); } return Dialog.EndOfTurn; } } protected async onRecognize(context: TurnContext): Promise<PromptRecognizerResult<AdaptiveCardPromptResult>> { // Ignore user input that doesn't come from adaptive card if (!context.activity.text && context.activity.value) { const data = context.activity.value; // Validate it comes from the correct card - This is only a worry while the prompt/dialog has not ended if (this.promptId && context.activity.value && context.activity.value['promptId'] != this.promptId) { return { succeeded: false, value: { data, error: AdaptiveCardPromptErrors.userInputDoesNotMatchCardId }}; } // Check for required input data, if specified in AdaptiveCardPromptSettings const missingIds = []; this.requiredInputIds.forEach((id): void => { if (!context.activity.value[id] || !context.activity.value[id].trim()) { missingIds.push(id); } }); // User did not submit inputs that were required if (missingIds.length > 0) { return { succeeded: false, value: { data, missingIds, error: AdaptiveCardPromptErrors.missingRequiredIds}}; } return { succeeded: true, value: { data } }; } else { // User used text input instead of card input return { succeeded: false, value: { error: AdaptiveCardPromptErrors.userUsedTextInput }}; } } private throwIfNotAdaptiveCard(cardAttachment: Attachment): void { const adaptiveCardType = 'application/vnd.microsoft.card.adaptive'; if (!cardAttachment || !cardAttachment.content) { throw new Error('No Adaptive Card provided. Include in the constructor or PromptOptions.prompt.attachments'); } else if (!cardAttachment.contentType || cardAttachment.contentType !== adaptiveCardType) { throw new Error(`Attachment is not a valid Adaptive Card.\n`+ `Ensure card.contentType is '${ adaptiveCardType }'\n`+ `and card.content contains the card json`); } } } /** * @private */ interface AdaptiveCardPromptState { state: object; options: PromptOptions; }
the_stack
import { DOMWidgetModel, DOMWidgetView, ISerializers, } from "@jupyter-widgets/base"; import _ from "lodash"; import Plotly from "plotly.js/dist/plotly"; import { MODULE_NAME, MODULE_VERSION } from "./version"; // @ts-ignore window.PlotlyConfig = { MathJaxConfig: "local" }; const semver_range = "^" + MODULE_VERSION; type InputDeviceState = { alt: any; ctrl: any; meta: any; shift: any; button: any; buttons: any; }; type Js2PyLayoutDeltaMsg = { layout_delta: any; layout_edit_id: any; }; type Js2PyMsg = { source_view_id: string; }; type Js2PyPointsCallbackMsg = { event_type: string; points: Points; device_state: InputDeviceState; selector: Selector; }; type Js2PyRelayoutMsg = Js2PyMsg & { relayout_data: any; }; type Js2PyRestyleMsg = Js2PyMsg & { style_data: any; style_traces?: null | number | number[]; }; type Js2PyTraceDeltasMsg = { trace_deltas: any; trace_edit_id: any; }; type Js2PyUpdateMsg = Js2PyMsg & { style_data: any; layout_data: any; style_traces?: null | number | number[]; }; type Points = { trace_indexes: number[]; point_indexes: number[]; xs: number[]; ys: number[]; zs?: number[]; }; type Py2JsMsg = { trace_edit_id?: any; layout_edit_id?: any; source_view_id?: any; }; type Py2JsAddTracesMsg = Py2JsMsg & { trace_data: any; }; type Py2JsAnimateMsg = Py2JsMsg & { style_data: any; layout_data: any; style_traces?: null | number | number[]; animation_opts?: any; }; type Py2JsDeleteTracesMsg = Py2JsMsg & { delete_inds: number[]; }; type Py2JsMoveTracesMsg = { current_trace_inds: number[]; new_trace_inds: number[]; }; type Py2JsRestyleMsg = Py2JsMsg & { restyle_data: any; restyle_traces?: null | number | number[]; }; type Py2JsRelayoutMsg = Py2JsMsg & { relayout_data: any; }; type Py2JsRemoveLayoutPropsMsg = { remove_props: any; }; type Py2JsRemoveTracePropsMsg = { remove_props: any; remove_trace: any; }; type Py2JsUpdateMsg = Py2JsMsg & { style_data: any; layout_data: any; style_traces?: null | number | number[]; }; type Selector = { type: "box" | "lasso"; selector_state: | { xrange: number[]; yrange: number[] } | { xs: number[]; ys: number[] }; }; // Model // ===== /** * A FigureModel holds a mirror copy of the state of a FigureWidget on * the Python side. There is a one-to-one relationship between JavaScript * FigureModels and Python FigureWidgets. The JavaScript FigureModel is * initialized as soon as a Python FigureWidget initialized, this happens * even before the widget is first displayed in the Notebook * @type {widgets.DOMWidgetModel} */ export class FigureModel extends DOMWidgetModel { defaults() { return { ...super.defaults(), // Model metadata // -------------- _model_name: FigureModel.model_name, _model_module: FigureModel.model_module, _model_module_version: FigureModel.model_module_version, _view_name: FigureModel.view_name, _view_module: FigureModel.view_module, _view_module_version: FigureModel.view_module_version, // Data and Layout // --------------- // The _data and _layout properties are synchronized with the // Python side on initialization only. After initialization, these // properties are kept in sync through the use of the _py2js_* // messages _data: [], _layout: {}, _config: {}, // Python -> JS messages // --------------------- // Messages are implemented using trait properties. This is done so // that we can take advantage of ipywidget's binary serialization // protocol. // // Messages are sent by the Python side by assigning the message // contents to the appropriate _py2js_* property, and then immediately // setting it to None. Messages are received by the JavaScript // side by registering property change callbacks in the initialize // methods for FigureModel and FigureView. e.g. (where this is a // FigureModel): // // this.on('change:_py2js_addTraces', this.do_addTraces, this); // // Message handling methods, do_addTraces, are responsible for // performing the appropriate action if the message contents are // not null /** * @typedef {null|Object} Py2JsAddTracesMsg * @property {Array.<Object>} trace_data * Array of traces to append to the end of the figure's current traces * @property {Number} trace_edit_id * Edit ID to use when returning trace deltas using * the _js2py_traceDeltas message. * @property {Number} layout_edit_id * Edit ID to use when returning layout deltas using * the _js2py_layoutDelta message. */ _py2js_addTraces: null, /** * @typedef {null|Object} Py2JsDeleteTracesMsg * @property {Array.<Number>} delete_inds * Array of indexes of traces to be deleted, in ascending order * @property {Number} trace_edit_id * Edit ID to use when returning trace deltas using * the _js2py_traceDeltas message. * @property {Number} layout_edit_id * Edit ID to use when returning layout deltas using * the _js2py_layoutDelta message. */ _py2js_deleteTraces: null, /** * @typedef {null|Object} Py2JsMoveTracesMsg * @property {Array.<Number>} current_trace_inds * Array of the current indexes of traces to be moved * @property {Array.<Number>} new_trace_inds * Array of the new indexes that traces should be moved to. */ _py2js_moveTraces: null, /** * @typedef {null|Object} Py2JsRestyleMsg * @property {Object} restyle_data * Restyle data as accepted by Plotly.restyle * @property {null|Array.<Number>} restyle_traces * Array of indexes of the traces that the resytle operation applies * to, or null to apply the operation to all traces * @property {Number} trace_edit_id * Edit ID to use when returning trace deltas using * the _js2py_traceDeltas message * @property {Number} layout_edit_id * Edit ID to use when returning layout deltas using * the _js2py_layoutDelta message * @property {null|String} source_view_id * view_id of the FigureView that triggered the original restyle * event (e.g. by clicking the legend), or null if the restyle was * triggered from Python */ _py2js_restyle: null, /** * @typedef {null|Object} Py2JsRelayoutMsg * @property {Object} relayout_data * Relayout data as accepted by Plotly.relayout * @property {Number} layout_edit_id * Edit ID to use when returning layout deltas using * the _js2py_layoutDelta message * @property {null|String} source_view_id * view_id of the FigureView that triggered the original relayout * event (e.g. by clicking the zoom button), or null if the * relayout was triggered from Python */ _py2js_relayout: null, /** * @typedef {null|Object} Py2JsUpdateMsg * @property {Object} style_data * Style data as accepted by Plotly.update * @property {Object} layout_data * Layout data as accepted by Plotly.update * @property {Array.<Number>} style_traces * Array of indexes of the traces that the update operation applies * to, or null to apply the operation to all traces * @property {Number} trace_edit_id * Edit ID to use when returning trace deltas using * the _js2py_traceDeltas message * @property {Number} layout_edit_id * Edit ID to use when returning layout deltas using * the _js2py_layoutDelta message * @property {null|String} source_view_id * view_id of the FigureView that triggered the original update * event (e.g. by clicking a button), or null if the update was * triggered from Python */ _py2js_update: null, /** * @typedef {null|Object} Py2JsAnimateMsg * @property {Object} style_data * Style data as accepted by Plotly.animate * @property {Object} layout_data * Layout data as accepted by Plotly.animate * @property {Array.<Number>} style_traces * Array of indexes of the traces that the animate operation applies * to, or null to apply the operation to all traces * @property {Object} animation_opts * Animation options as accepted by Plotly.animate * @property {Number} trace_edit_id * Edit ID to use when returning trace deltas using * the _js2py_traceDeltas message * @property {Number} layout_edit_id * Edit ID to use when returning layout deltas using * the _js2py_layoutDelta message * @property {null|String} source_view_id * view_id of the FigureView that triggered the original animate * event (e.g. by clicking a button), or null if the update was * triggered from Python */ _py2js_animate: null, /** * @typedef {null|Object} Py2JsRemoveLayoutPropsMsg * @property {Array.<Array.<String|Number>>} remove_props * Array of property paths to remove. Each propery path is an * array of property names or array indexes that locate a property * inside the _layout object */ _py2js_removeLayoutProps: null, /** * @typedef {null|Object} Py2JsRemoveTracePropsMsg * @property {Number} remove_trace * The index of the trace from which to remove properties * @property {Array.<Array.<String|Number>>} remove_props * Array of property paths to remove. Each propery path is an * array of property names or array indexes that locate a property * inside the _data[remove_trace] object */ _py2js_removeTraceProps: null, // JS -> Python messages // --------------------- // Messages are sent by the JavaScript side by assigning the // message contents to the appropriate _js2py_* property and then // calling the `touch` method on the view that triggered the // change. e.g. (where this is a FigureView): // // this.model.set('_js2py_restyle', data); // this.touch(); // // The Python side is responsible for setting the property to None // after receiving the message. // // Message trigger logic is described in the corresponding // handle_plotly_* methods of FigureView /** * @typedef {null|Object} Js2PyRestyleMsg * @property {Object} style_data * Style data that was passed to Plotly.restyle * @property {Array.<Number>} style_traces * Array of indexes of the traces that the restyle operation * was applied to, or null if applied to all traces * @property {String} source_view_id * view_id of the FigureView that triggered the original restyle * event (e.g. by clicking the legend) */ _js2py_restyle: null, /** * @typedef {null|Object} Js2PyRelayoutMsg * @property {Object} relayout_data * Relayout data that was passed to Plotly.relayout * @property {String} source_view_id * view_id of the FigureView that triggered the original relayout * event (e.g. by clicking the zoom button) */ _js2py_relayout: null, /** * @typedef {null|Object} Js2PyUpdateMsg * @property {Object} style_data * Style data that was passed to Plotly.update * @property {Object} layout_data * Layout data that was passed to Plotly.update * @property {Array.<Number>} style_traces * Array of indexes of the traces that the update operation applied * to, or null if applied to all traces * @property {String} source_view_id * view_id of the FigureView that triggered the original relayout * event (e.g. by clicking the zoom button) */ _js2py_update: null, /** * @typedef {null|Object} Js2PyLayoutDeltaMsg * @property {Object} layout_delta * The layout delta object that contains all of the properties of * _fullLayout that are not identical to those in the * FigureModel's _layout property * @property {Number} layout_edit_id * Edit ID of message that triggered the creation of layout delta */ _js2py_layoutDelta: null, /** * @typedef {null|Object} Js2PyTraceDeltasMsg * @property {Array.<Object>} trace_deltas * Array of trace delta objects. Each trace delta contains the * trace's uid along with all of the properties of _fullData that * are not identical to those in the FigureModel's _data property * @property {Number} trace_edit_id * Edit ID of message that triggered the creation of trace deltas */ _js2py_traceDeltas: null, /** * Object representing a collection of points for use in click, hover, * and selection events * @typedef {Object} Points * @property {Array.<Number>} trace_indexes * Array of the trace index for each point * @property {Array.<Number>} point_indexes * Array of the index of each point in its own trace * @property {null|Array.<Number>} xs * Array of the x coordinate of each point (for cartesian trace types) * or null (for non-cartesian trace types) * @property {null|Array.<Number>} ys * Array of the y coordinate of each point (for cartesian trace types) * or null (for non-cartesian trace types * @property {null|Array.<Number>} zs * Array of the z coordinate of each point (for 3D cartesian * trace types) * or null (for non-3D-cartesian trace types) */ /** * Object representing the state of the input devices during a * plotly event * @typedef {Object} InputDeviceState * @property {boolean} alt - true if alt key pressed, * false otherwise * @property {boolean} ctrl - true if ctrl key pressed, * false otherwise * @property {boolean} meta - true if meta key pressed, * false otherwise * @property {boolean} shift - true if shift key pressed, * false otherwise * * @property {boolean} button * Indicates which button was pressed on the mouse to trigger the * event. * 0: Main button pressed, usually the left button or the * un-initialized state * 1: Auxiliary button pressed, usually the wheel button or * the middle button (if present) * 2: Secondary button pressed, usually the right button * 3: Fourth button, typically the Browser Back button * 4: Fifth button, typically the Browser Forward button * * @property {boolean} buttons * Indicates which buttons were pressed on the mouse when the event * is triggered. * 0 : No button or un-initialized * 1 : Primary button (usually left) * 2 : Secondary button (usually right) * 4 : Auxilary button (usually middle or mouse wheel button) * 8 : 4th button (typically the "Browser Back" button) * 16 : 5th button (typically the "Browser Forward" button) * * Combinations of buttons are represented by the sum of the codes * above. e.g. a value of 7 indicates buttons 1 (primary), * 2 (secondary), and 4 (auxilary) were pressed during the event */ /** * @typedef {Object} BoxSelectorState * @property {Array.<Number>} xrange * Two element array containing the x-range of the box selection * @property {Array.<Number>} yrange * Two element array containing the y-range of the box selection */ /** * @typedef {Object} LassoSelectorState * @property {Array.<Number>} xs * Array of the x-coordinates of the lasso selection region * @property {Array.<Number>} ys * Array of the y-coordinates of the lasso selection region */ /** * Object representing the state of the selection tool during a * plotly_select event * @typedef {Object} Selector * @property {String} type * Selection type. One of: 'box', or 'lasso' * @property {BoxSelectorState|LassoSelectorState} selector_state */ /** * @typedef {null|Object} Js2PyPointsCallbackMsg * @property {string} event_type * Name of the triggering event. One of 'plotly_click', * 'plotly_hover', 'plotly_unhover', or 'plotly_selected' * @property {null|Points} points * Points object for event * @property {null|InputDeviceState} device_state * InputDeviceState object for event * @property {null|Selector} selector * State of the selection tool for 'plotly_selected' events, null * for other event types */ _js2py_pointsCallback: null, // Message tracking // ---------------- /** * @type {Number} * layout_edit_id of the last layout modification operation * requested by the Python side */ _last_layout_edit_id: 0, /** * @type {Number} * trace_edit_id of the last trace modification operation * requested by the Python side */ _last_trace_edit_id: 0, }; } /** * Initialize FigureModel. Called when the Python FigureWidget is first * constructed */ initialize() { super.initialize.apply(this, arguments); this.on("change:_data", this.do_data, this); this.on("change:_layout", this.do_layout, this); this.on("change:_py2js_addTraces", this.do_addTraces, this); this.on("change:_py2js_deleteTraces", this.do_deleteTraces, this); this.on("change:_py2js_moveTraces", this.do_moveTraces, this); this.on("change:_py2js_restyle", this.do_restyle, this); this.on("change:_py2js_relayout", this.do_relayout, this); this.on("change:_py2js_update", this.do_update, this); this.on("change:_py2js_animate", this.do_animate, this); this.on("change:_py2js_removeLayoutProps", this.do_removeLayoutProps, this); this.on("change:_py2js_removeTraceProps", this.do_removeTraceProps, this); } /** * Input a trace index specification and return an Array of trace * indexes where: * * - null|undefined -> Array of all traces * - Trace index as Number -> Single element array of input index * - Array of trace indexes -> Input array unchanged * * @param {undefined|null|Number|Array.<Number>} trace_indexes * @returns {Array.<Number>} * Array of trace indexes * @private */ _normalize_trace_indexes(trace_indexes?: null | number | number[]): number[] { if (trace_indexes === null || trace_indexes === undefined) { var numTraces = this.get("_data").length; trace_indexes = _.range(numTraces); } if (!Array.isArray(trace_indexes)) { // Make sure idx is an array trace_indexes = [trace_indexes]; } return trace_indexes; } /** * Log changes to the _data trait * * This should only happed on FigureModel initialization */ do_data() {} /** * Log changes to the _layout trait * * This should only happed on FigureModel initialization */ do_layout() {} /** * Handle addTraces message */ do_addTraces() { // add trace to plot /** @type {Py2JsAddTracesMsg} */ var msgData: Py2JsAddTracesMsg = this.get("_py2js_addTraces"); if (msgData !== null) { var currentTraces = this.get("_data"); var newTraces = msgData.trace_data; _.forEach(newTraces, function (newTrace) { currentTraces.push(newTrace); }); } } /** * Handle deleteTraces message */ do_deleteTraces() { // remove traces from plot /** @type {Py2JsDeleteTracesMsg} */ var msgData: Py2JsDeleteTracesMsg = this.get("_py2js_deleteTraces"); if (msgData !== null) { var delete_inds = msgData.delete_inds; var tracesData = this.get("_data"); // Remove del inds in reverse order so indexes remain valid // throughout loop delete_inds .slice() .reverse() .forEach(function (del_ind) { tracesData.splice(del_ind, 1); }); } } /** * Handle moveTraces message */ do_moveTraces() { /** @type {Py2JsMoveTracesMsg} */ var msgData: Py2JsMoveTracesMsg = this.get("_py2js_moveTraces"); if (msgData !== null) { var tracesData = this.get("_data"); var currentInds = msgData.current_trace_inds; var newInds = msgData.new_trace_inds; performMoveTracesLike(tracesData, currentInds, newInds); } } /** * Handle restyle message */ do_restyle() { /** @type {Py2JsRestyleMsg} */ var msgData: Py2JsRestyleMsg = this.get("_py2js_restyle"); if (msgData !== null) { var restyleData = msgData.restyle_data; var restyleTraces = this._normalize_trace_indexes(msgData.restyle_traces); performRestyleLike(this.get("_data"), restyleData, restyleTraces); } } /** * Handle relayout message */ do_relayout() { /** @type {Py2JsRelayoutMsg} */ var msgData: Py2JsRelayoutMsg = this.get("_py2js_relayout"); if (msgData !== null) { performRelayoutLike(this.get("_layout"), msgData.relayout_data); } } /** * Handle update message */ do_update() { /** @type {Py2JsUpdateMsg} */ var msgData: Py2JsUpdateMsg = this.get("_py2js_update"); if (msgData !== null) { var style = msgData.style_data; var layout = msgData.layout_data; var styleTraces = this._normalize_trace_indexes(msgData.style_traces); performRestyleLike(this.get("_data"), style, styleTraces); performRelayoutLike(this.get("_layout"), layout); } } /** * Handle animate message */ do_animate() { /** @type {Py2JsAnimateMsg} */ var msgData: Py2JsAnimateMsg = this.get("_py2js_animate"); if (msgData !== null) { var styles = msgData.style_data; var layout = msgData.layout_data; var trace_indexes = this._normalize_trace_indexes(msgData.style_traces); for (var i = 0; i < styles.length; i++) { var style = styles[i]; var trace_index = trace_indexes[i]; var trace = this.get("_data")[trace_index]; performRelayoutLike(trace, style); } performRelayoutLike(this.get("_layout"), layout); } } /** * Handle removeLayoutProps message */ do_removeLayoutProps() { /** @type {Py2JsRemoveLayoutPropsMsg} */ var msgData: Py2JsRemoveLayoutPropsMsg = this.get( "_py2js_removeLayoutProps" ); if (msgData !== null) { var keyPaths = msgData.remove_props; var layout = this.get("_layout"); performRemoveProps(layout, keyPaths); } } /** * Handle removeTraceProps message */ do_removeTraceProps() { /** @type {Py2JsRemoveTracePropsMsg} */ var msgData: Py2JsRemoveTracePropsMsg = this.get("_py2js_removeTraceProps"); if (msgData !== null) { var keyPaths = msgData.remove_props; var traceIndex = msgData.remove_trace; var trace = this.get("_data")[traceIndex]; performRemoveProps(trace, keyPaths); } } static serializers: ISerializers = { ...DOMWidgetModel.serializers, _data: { deserialize: py2js_deserializer, serialize: js2py_serializer }, _layout: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, _py2js_addTraces: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, _py2js_deleteTraces: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, _py2js_moveTraces: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, _py2js_restyle: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, _py2js_relayout: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, _py2js_update: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, _py2js_animate: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, _py2js_removeLayoutProps: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, _py2js_removeTraceProps: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, _js2py_restyle: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, _js2py_relayout: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, _js2py_update: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, _js2py_layoutDelta: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, _js2py_traceDeltas: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, _js2py_pointsCallback: { deserialize: py2js_deserializer, serialize: js2py_serializer, }, }; static model_name = "FigureModel"; static model_module = MODULE_NAME; static model_module_version = semver_range; static view_name = "FigureView"; static view_module = MODULE_NAME; static view_module_version = semver_range; } // View // ==== /** * A FigureView manages the visual presentation of a single Plotly.js * figure for a single notebook output cell. Each FigureView has a * reference to FigureModel. Multiple views may share a single model * instance, as is the case when a Python FigureWidget is displayed in * multiple notebook output cells. * * @type {widgets.DOMWidgetView} */ export class FigureView extends DOMWidgetView { viewID: string; /** * The perform_render method is called by processPhosphorMessage * after the widget's DOM element has been attached to the notebook * output cell. This happens after the initialize of the * FigureModel, and it won't happen at all if the Python FigureWidget * is never displayed in a notebook output cell */ perform_render() { var that = this; // Wire up message property callbacks // ---------------------------------- // Python -> JS event properties this.model.on("change:_py2js_addTraces", this.do_addTraces, this); this.model.on("change:_py2js_deleteTraces", this.do_deleteTraces, this); this.model.on("change:_py2js_moveTraces", this.do_moveTraces, this); this.model.on("change:_py2js_restyle", this.do_restyle, this); this.model.on("change:_py2js_relayout", this.do_relayout, this); this.model.on("change:_py2js_update", this.do_update, this); this.model.on("change:_py2js_animate", this.do_animate, this); // MathJax configuration // --------------------- if ((window as any).MathJax) { (window as any).MathJax.Hub.Config({ SVG: { font: "STIX-Web" } }); } // Get message ids // --------------------- var layout_edit_id = this.model.get("_last_layout_edit_id"); var trace_edit_id = this.model.get("_last_trace_edit_id"); // Set view UID // ------------ this.viewID = randstr(); // Initialize Plotly.js figure // --------------------------- // We must clone the model's data and layout properties so that // the model is not directly mutated by the Plotly.js library. var initialTraces = _.cloneDeep(this.model.get("_data")); var initialLayout = _.cloneDeep(this.model.get("_layout")); var config = this.model.get("_config"); Plotly.newPlot(that.el, initialTraces, initialLayout, config).then( function () { // ### Send trace deltas ### // We create an array of deltas corresponding to the new // traces. that._sendTraceDeltas(trace_edit_id); // ### Send layout delta ### that._sendLayoutDelta(layout_edit_id); // Wire up plotly event callbacks (<Plotly.PlotlyHTMLElement>that.el).on("plotly_restyle", function (update: any) { that.handle_plotly_restyle(update); }); (<Plotly.PlotlyHTMLElement>that.el).on("plotly_relayout", function (update: any) { that.handle_plotly_relayout(update); }); (<Plotly.PlotlyHTMLElement>that.el).on("plotly_update", function (update: any) { that.handle_plotly_update(update); }); (<Plotly.PlotlyHTMLElement>that.el).on("plotly_click", function (update: any) { that.handle_plotly_click(update); }); (<Plotly.PlotlyHTMLElement>that.el).on("plotly_hover", function (update: any) { that.handle_plotly_hover(update); }); (<Plotly.PlotlyHTMLElement>that.el).on("plotly_unhover", function (update: any) { that.handle_plotly_unhover(update); }); (<Plotly.PlotlyHTMLElement>that.el).on("plotly_selected", function (update: any) { that.handle_plotly_selected(update); }); (<Plotly.PlotlyHTMLElement>that.el).on("plotly_deselect", function (update: any) { that.handle_plotly_deselect(update); }); (<Plotly.PlotlyHTMLElement>that.el).on("plotly_doubleclick", function (update: any) { that.handle_plotly_doubleclick(update); }); // Emit event indicating that the widget has finished // rendering var event = new CustomEvent("plotlywidget-after-render", { detail: { element: that.el, viewID: that.viewID }, }); // Dispatch/Trigger/Fire the event document.dispatchEvent(event); } ); } /** * Respond to phosphorjs events */ processPhosphorMessage(msg: any) { super.processPhosphorMessage.apply(this, arguments); var that = this; switch (msg.type) { case "before-attach": // Render an initial empty figure. This establishes with // the page that the element will not be empty, avoiding // some occasions where the dynamic sizing behavior leads // to collapsed figure dimensions. var axisHidden = { showgrid: false, showline: false, tickvals: [] as any[], }; Plotly.newPlot(that.el, [], { xaxis: axisHidden, yaxis: axisHidden, }); window.addEventListener("resize", function () { that.autosizeFigure(); }); break; case "after-attach": // Rendering actual figure in the after-attach event allows // Plotly.js to size the figure to fill the available element this.perform_render(); break; case "resize": this.autosizeFigure(); break; } } autosizeFigure() { var that = this; var layout = that.model.get("_layout"); if (_.isNil(layout) || _.isNil(layout.width)) { // @ts-ignore Plotly.Plots.resize(that.el).then(function () { var layout_edit_id = that.model.get("_last_layout_edit_id"); that._sendLayoutDelta(layout_edit_id); }); } } /** * Purge Plotly.js data structures from the notebook output display * element when the view is destroyed */ destroy() { Plotly.purge(this.el); } /** * Return the figure's _fullData array merged with its data array * * The merge ensures that for any properties that el._fullData and * el.data have in common, we return the version from el.data * * Named colorscales are one example of why this is needed. The el.data * array will hold named colorscale strings (e.g. 'Viridis'), while the * el._fullData array will hold the actual colorscale array. e.g. * * el.data[0].marker.colorscale == 'Viridis' but * el._fullData[0].marker.colorscale = [[..., ...], ...] * * Performing the merge allows our FigureModel to retain the 'Viridis' * string, rather than having it overridded by the colorscale array. * */ getFullData() { return _.mergeWith( {}, (<Plotly.PlotlyHTMLElement>this.el)._fullData, (<Plotly.PlotlyHTMLElement>this.el).data, fullMergeCustomizer ); } /** * Return the figure's _fullLayout object merged with its layout object * * See getFullData documentation for discussion of why the merge is * necessary */ getFullLayout() { return _.mergeWith( {}, (<Plotly.PlotlyHTMLElement>this.el)._fullLayout, (<Plotly.PlotlyHTMLElement>this.el).layout, fullMergeCustomizer ); } /** * Build Points data structure from data supplied by the plotly_click, * plotly_hover, or plotly_select events * @param {Object} data * @returns {null|Points} */ buildPointsObject(data: any): null | Points { var pointsObject: Points; if (data.hasOwnProperty("points")) { // Most cartesian plots var pointObjects = data["points"]; var numPoints = pointObjects.length; var hasNestedPointObjects = true; for (let i = 0; i < numPoints; i++) { hasNestedPointObjects = hasNestedPointObjects && pointObjects[i].hasOwnProperty("pointNumbers"); if (!hasNestedPointObjects) break; } var numPointNumbers = numPoints; if (hasNestedPointObjects) { numPointNumbers = 0; for (let i = 0; i < numPoints; i++) { numPointNumbers += pointObjects[i]["pointNumbers"].length; } } pointsObject = { trace_indexes: new Array(numPointNumbers), point_indexes: new Array(numPointNumbers), xs: new Array(numPointNumbers), ys: new Array(numPointNumbers), }; if (hasNestedPointObjects) { var flatPointIndex = 0; for (var p = 0; p < numPoints; p++) { for ( let i = 0; i < pointObjects[p]["pointNumbers"].length; i++, flatPointIndex++ ) { pointsObject["point_indexes"][flatPointIndex] = pointObjects[p]["pointNumbers"][i]; // also add xs, ys and traces so that the array doesn't get truncated later pointsObject["xs"][flatPointIndex] = pointObjects[p]["x"]; pointsObject["ys"][flatPointIndex] = pointObjects[p]["y"]; pointsObject["trace_indexes"][flatPointIndex] = pointObjects[p]["curveNumber"]; } } let single_trace = true; for (let i = 1; i < numPointNumbers; i++) { single_trace = single_trace && (pointsObject["trace_indexes"][i - 1] === pointsObject["trace_indexes"][i]) if (!single_trace) break; } if (single_trace) { pointsObject["point_indexes"].sort((function (a, b) { return a - b })) } } else { for (var p = 0; p < numPoints; p++) { pointsObject["trace_indexes"][p] = pointObjects[p]["curveNumber"]; pointsObject["point_indexes"][p] = pointObjects[p]["pointNumber"]; pointsObject["xs"][p] = pointObjects[p]["x"]; pointsObject["ys"][p] = pointObjects[p]["y"]; } } // Add z if present var hasZ = pointObjects[0] !== undefined && pointObjects[0].hasOwnProperty("z"); if (hasZ) { pointsObject["zs"] = new Array(numPoints); for (p = 0; p < numPoints; p++) { pointsObject["zs"][p] = pointObjects[p]["z"]; } } return pointsObject; } else { return null; } } /** * Build InputDeviceState data structure from data supplied by the * plotly_click, plotly_hover, or plotly_select events * @param {Object} data * @returns {null|InputDeviceState} */ buildInputDeviceStateObject(data: any): null | InputDeviceState { var event = data["event"]; if (event === undefined) { return null; } else { /** @type {InputDeviceState} */ var inputDeviceState: InputDeviceState = { // Keyboard modifiers alt: event["altKey"], ctrl: event["ctrlKey"], meta: event["metaKey"], shift: event["shiftKey"], // Mouse buttons button: event["button"], buttons: event["buttons"], }; return inputDeviceState; } } /** * Build Selector data structure from data supplied by the * plotly_select event * @param data * @returns {null|Selector} */ buildSelectorObject(data: any): null | Selector { var selectorObject: Selector; if (data.hasOwnProperty("range")) { // Box selection selectorObject = { type: "box", selector_state: { xrange: data["range"]["x"], yrange: data["range"]["y"], }, }; } else if (data.hasOwnProperty("lassoPoints")) { // Lasso selection selectorObject = { type: "lasso", selector_state: { xs: data["lassoPoints"]["x"], ys: data["lassoPoints"]["y"], }, }; } else { selectorObject = null; } return selectorObject; } /** * Handle ploty_restyle events emitted by the Plotly.js library * @param data */ handle_plotly_restyle(data: any) { if (data === null || data === undefined) { // No data to report to the Python side return; } if (data[0] && data[0].hasOwnProperty("_doNotReportToPy")) { // Restyle originated on the Python side return; } // Unpack data var styleData = data[0]; var styleTraces = data[1]; // Construct restyle message to send to the Python side /** @type {Js2PyRestyleMsg} */ var restyleMsg: Js2PyRestyleMsg = { style_data: styleData, style_traces: styleTraces, source_view_id: this.viewID, }; this.model.set("_js2py_restyle", restyleMsg); this.touch(); } /** * Handle plotly_relayout events emitted by the Plotly.js library * @param data */ handle_plotly_relayout(data: any) { if (data === null || data === undefined) { // No data to report to the Python side return; } if (data.hasOwnProperty("_doNotReportToPy")) { // Relayout originated on the Python side return; } /** @type {Js2PyRelayoutMsg} */ var relayoutMsg: Js2PyRelayoutMsg = { relayout_data: data, source_view_id: this.viewID, }; this.model.set("_js2py_relayout", relayoutMsg); this.touch(); } /** * Handle plotly_update events emitted by the Plotly.js library * @param data */ handle_plotly_update(data: any) { if (data === null || data === undefined) { // No data to report to the Python side return; } if (data["data"] && data["data"][0].hasOwnProperty("_doNotReportToPy")) { // Update originated on the Python side return; } /** @type {Js2PyUpdateMsg} */ var updateMsg: Js2PyUpdateMsg = { style_data: data["data"][0], style_traces: data["data"][1], layout_data: data["layout"], source_view_id: this.viewID, }; // Log message this.model.set("_js2py_update", updateMsg); this.touch(); } /** * Handle plotly_click events emitted by the Plotly.js library * @param data */ handle_plotly_click(data: any) { this._send_points_callback_message(data, "plotly_click"); } /** * Handle plotly_hover events emitted by the Plotly.js library * @param data */ handle_plotly_hover(data: any) { this._send_points_callback_message(data, "plotly_hover"); } /** * Handle plotly_unhover events emitted by the Plotly.js library * @param data */ handle_plotly_unhover(data: any) { this._send_points_callback_message(data, "plotly_unhover"); } /** * Handle plotly_selected events emitted by the Plotly.js library * @param data */ handle_plotly_selected(data: any) { this._send_points_callback_message(data, "plotly_selected"); } /** * Handle plotly_deselect events emitted by the Plotly.js library * @param data */ handle_plotly_deselect(data: any) { data = { points: [], }; this._send_points_callback_message(data, "plotly_deselect"); } /** * Build and send a points callback message to the Python side * * @param {Object} data * data object as provided by the plotly_click, plotly_hover, * plotly_unhover, or plotly_selected events * @param {String} event_type * Name of the triggering event. One of 'plotly_click', * 'plotly_hover', 'plotly_unhover', or 'plotly_selected' * @private */ _send_points_callback_message(data: any, event_type: string) { if (data === null || data === undefined) { // No data to report to the Python side return; } /** @type {Js2PyPointsCallbackMsg} */ var pointsMsg: Js2PyPointsCallbackMsg = { event_type: event_type, points: this.buildPointsObject(data), device_state: this.buildInputDeviceStateObject(data), selector: this.buildSelectorObject(data), }; if (pointsMsg["points"] !== null && pointsMsg["points"] !== undefined) { this.model.set("_js2py_pointsCallback", pointsMsg); this.touch(); } } /** * Stub for future handling of plotly_doubleclick * @param data */ handle_plotly_doubleclick(data: any) {} /** * Handle Plotly.addTraces request */ do_addTraces() { /** @type {Py2JsAddTracesMsg} */ var msgData: Py2JsAddTracesMsg = this.model.get("_py2js_addTraces"); if (msgData !== null) { var that = this; Plotly.addTraces(this.el, msgData.trace_data).then(function () { // ### Send trace deltas ### that._sendTraceDeltas(msgData.trace_edit_id); // ### Send layout delta ### var layout_edit_id = msgData.layout_edit_id; that._sendLayoutDelta(layout_edit_id); }); } } /** * Handle Plotly.deleteTraces request */ do_deleteTraces() { /** @type {Py2JsDeleteTracesMsg} */ var msgData: Py2JsDeleteTracesMsg = this.model.get("_py2js_deleteTraces"); if (msgData !== null) { var delete_inds = msgData.delete_inds; var that = this; Plotly.deleteTraces(this.el, delete_inds).then(function () { // ### Send trace deltas ### var trace_edit_id = msgData.trace_edit_id; that._sendTraceDeltas(trace_edit_id); // ### Send layout delta ### var layout_edit_id = msgData.layout_edit_id; that._sendLayoutDelta(layout_edit_id); }); } } /** * Handle Plotly.moveTraces request */ do_moveTraces() { /** @type {Py2JsMoveTracesMsg} */ var msgData: Py2JsMoveTracesMsg = this.model.get("_py2js_moveTraces"); if (msgData !== null) { // Unpack message var currentInds = msgData.current_trace_inds; var newInds = msgData.new_trace_inds; // Check if the new trace indexes are actually different than // the current indexes var inds_equal = _.isEqual(currentInds, newInds); if (!inds_equal) { Plotly.moveTraces(this.el, currentInds, newInds); } } } /** * Handle Plotly.restyle request */ do_restyle() { /** @type {Py2JsRestyleMsg} */ var msgData: Py2JsRestyleMsg = this.model.get("_py2js_restyle"); if (msgData !== null) { var restyleData = msgData.restyle_data; var traceIndexes = (this.model as FigureModel)._normalize_trace_indexes( msgData.restyle_traces ); restyleData["_doNotReportToPy"] = true; Plotly.restyle(this.el, restyleData, traceIndexes); // ### Send trace deltas ### // We create an array of deltas corresponding to the restyled // traces. this._sendTraceDeltas(msgData.trace_edit_id); // ### Send layout delta ### var layout_edit_id = msgData.layout_edit_id; this._sendLayoutDelta(layout_edit_id); } } /** * Handle Plotly.relayout request */ do_relayout() { /** @type {Py2JsRelayoutMsg} */ var msgData: Py2JsRelayoutMsg = this.model.get("_py2js_relayout"); if (msgData !== null) { if (msgData.source_view_id !== this.viewID) { var relayoutData = msgData.relayout_data; relayoutData["_doNotReportToPy"] = true; Plotly.relayout(this.el, msgData.relayout_data); } // ### Send layout delta ### var layout_edit_id = msgData.layout_edit_id; this._sendLayoutDelta(layout_edit_id); } } /** * Handle Plotly.update request */ do_update() { /** @type {Py2JsUpdateMsg} */ var msgData: Py2JsUpdateMsg = this.model.get("_py2js_update"); if (msgData !== null) { var style = msgData.style_data || {}; var layout = msgData.layout_data || {}; var traceIndexes = (this.model as FigureModel)._normalize_trace_indexes( msgData.style_traces ); style["_doNotReportToPy"] = true; Plotly.update(this.el, style, layout, traceIndexes); // ### Send trace deltas ### // We create an array of deltas corresponding to the updated // traces. this._sendTraceDeltas(msgData.trace_edit_id); // ### Send layout delta ### var layout_edit_id = msgData.layout_edit_id; this._sendLayoutDelta(layout_edit_id); } } /** * Handle Plotly.animate request */ do_animate() { /** @type {Py2JsAnimateMsg} */ var msgData: Py2JsAnimateMsg = this.model.get("_py2js_animate"); if (msgData !== null) { // Unpack params // var animationData = msgData[0]; var animationOpts = msgData.animation_opts; var styles = msgData.style_data; var layout = msgData.layout_data; var traceIndexes = (this.model as FigureModel)._normalize_trace_indexes( msgData.style_traces ); var animationData: any = { data: styles, layout: layout, traces: traceIndexes, }; animationData["_doNotReportToPy"] = true; var that = this; // @ts-ignore Plotly.animate(this.el, animationData, animationOpts).then(function () { // ### Send trace deltas ### // We create an array of deltas corresponding to the // animated traces. that._sendTraceDeltas(msgData.trace_edit_id); // ### Send layout delta ### var layout_edit_id = msgData.layout_edit_id; that._sendLayoutDelta(layout_edit_id); }); } } /** * Construct layout delta object and send layoutDelta message to the * Python side * * @param layout_edit_id * Edit ID of message that triggered the creation of the layout delta * @private */ _sendLayoutDelta(layout_edit_id: any) { // ### Handle layout delta ### var layout_delta = createDeltaObject( this.getFullLayout(), this.model.get("_layout") ); /** @type{Js2PyLayoutDeltaMsg} */ var layoutDeltaMsg: Js2PyLayoutDeltaMsg = { layout_delta: layout_delta, layout_edit_id: layout_edit_id, }; this.model.set("_js2py_layoutDelta", layoutDeltaMsg); this.touch(); } /** * Construct trace deltas array for the requested trace indexes and * send traceDeltas message to the Python side * Array of indexes of traces for which to compute deltas * @param trace_edit_id * Edit ID of message that triggered the creation of trace deltas * @private */ _sendTraceDeltas(trace_edit_id: any) { var trace_data = this.model.get("_data"); var traceIndexes = _.range(trace_data.length); var trace_deltas = new Array(traceIndexes.length); var fullData = this.getFullData(); for (var i = 0; i < traceIndexes.length; i++) { var traceInd = traceIndexes[i]; trace_deltas[i] = createDeltaObject( fullData[traceInd], trace_data[traceInd] ); } /** @type{Js2PyTraceDeltasMsg} */ var traceDeltasMsg: Js2PyTraceDeltasMsg = { trace_deltas: trace_deltas, trace_edit_id: trace_edit_id, }; this.model.set("_js2py_traceDeltas", traceDeltasMsg); this.touch(); } } // Serialization /** * Create a mapping from numpy dtype strings to corresponding typed array * constructors */ const numpy_dtype_to_typedarray_type = { int8: Int8Array, int16: Int16Array, int32: Int32Array, uint8: Uint8Array, uint16: Uint16Array, uint32: Uint32Array, float32: Float32Array, float64: Float64Array, }; function serializeTypedArray(v: ArrayConstructor) { var numpyType; if (v instanceof Int8Array) { numpyType = "int8"; } else if (v instanceof Int16Array) { numpyType = "int16"; } else if (v instanceof Int32Array) { numpyType = "int32"; } else if (v instanceof Uint8Array) { numpyType = "uint8"; } else if (v instanceof Uint16Array) { numpyType = "uint16"; } else if (v instanceof Uint32Array) { numpyType = "uint32"; } else if (v instanceof Float32Array) { numpyType = "float32"; } else if (v instanceof Float64Array) { numpyType = "float64"; } else { // Don't understand it, return as is return v; } var res = { dtype: numpyType, shape: [v.length], value: v.buffer, }; return res; } /** * ipywidget JavaScript -> Python serializer */ function js2py_serializer(v: any, widgetManager?: any) { var res: any; if (_.isTypedArray(v)) { res = serializeTypedArray(v); } else if (Array.isArray(v)) { // Serialize array elements recursively res = new Array(v.length); for (var i = 0; i < v.length; i++) { res[i] = js2py_serializer(v[i]); } } else if (_.isPlainObject(v)) { // Serialize object properties recursively res = {}; for (var p in v) { if (v.hasOwnProperty(p)) { res[p] = js2py_serializer(v[p]); } } } else if (v === undefined) { // Translate undefined into '_undefined_' sentinal string. The // Python _js_to_py deserializer will convert this into an // Undefined object res = "_undefined_"; } else { // Primitive value to transfer directly res = v; } return res; } /** * ipywidget Python -> Javascript deserializer */ function py2js_deserializer(v: any, widgetManager?: any) { var res: any; if (Array.isArray(v)) { // Deserialize array elements recursively res = new Array(v.length); for (var i = 0; i < v.length; i++) { res[i] = py2js_deserializer(v[i]); } } else if (_.isPlainObject(v)) { if ( (_.has(v, "value") || _.has(v, "buffer")) && _.has(v, "dtype") && _.has(v, "shape") ) { // Deserialize special buffer/dtype/shape objects into typed arrays // These objects correspond to numpy arrays on the Python side // // Note plotly.py<=3.1.1 called the buffer object `buffer` // This was renamed `value` in 3.2 to work around a naming conflict // when saving widget state to a notebook. // @ts-ignore var typedarray_type = numpy_dtype_to_typedarray_type[v.dtype]; var buffer = _.has(v, "value") ? v.value.buffer : v.buffer.buffer; res = new typedarray_type(buffer); } else { // Deserialize object properties recursively res = {}; for (var p in v) { if (v.hasOwnProperty(p)) { res[p] = py2js_deserializer(v[p]); } } } } else if (v === "_undefined_") { // Convert the _undefined_ sentinal into undefined res = undefined; } else { // Accept primitive value directly res = v; } return res; } /** * Return whether the input value is a typed array * @param potentialTypedArray * Value to examine * @returns {boolean} */ function isTypedArray(potentialTypedArray: any): boolean { return ( ArrayBuffer.isView(potentialTypedArray) && !(potentialTypedArray instanceof DataView) ); } /** * Customizer for use with lodash's mergeWith function * * The customizer ensures that typed arrays are not converted into standard * arrays during the recursive merge * * See: https://lodash.com/docs/latest#mergeWith */ function fullMergeCustomizer(objValue: any, srcValue: any, key: string) { if (key[0] === "_") { // Don't recurse into private properties return null; } else if (isTypedArray(srcValue)) { // Return typed arrays directly, don't recurse inside return srcValue; } } /** * Reform a Plotly.relayout like operation on an input object * * @param {Object} parentObj * The object that the relayout operation should be applied to * @param {Object} relayoutData * An relayout object as accepted by Plotly.relayout * * Examples: * var d = {foo {bar [5, 10]}}; * performRelayoutLike(d, {'foo.bar': [0, 1]}); * d -> {foo: {bar: [0, 1]}} * * var d = {foo {bar [5, 10]}}; * performRelayoutLike(d, {'baz': 34}); * d -> {foo: {bar: [5, 10]}, baz: 34} * * var d = {foo: {bar: [5, 10]}; * performRelayoutLike(d, {'foo.baz[1]': 17}); * d -> {foo: {bar: [5, 17]}} * */ function performRelayoutLike(parentObj: any, relayoutData: any) { // Perform a relayout style operation on a given parent object for (var rawKey in relayoutData) { if (!relayoutData.hasOwnProperty(rawKey)) { continue; } // Extract value for this key var relayoutVal = relayoutData[rawKey]; // Set property value if (relayoutVal === null) { _.unset(parentObj, rawKey); } else { _.set(parentObj, rawKey, relayoutVal); } } } /** * Perform a Plotly.restyle like operation on an input object array * * @param {Array.<Object>} parentArray * The object that the restyle operation should be applied to * @param {Object} restyleData * A restyle object as accepted by Plotly.restyle * @param {Array.<Number>} restyleTraces * Array of indexes of the traces that the resytle operation applies to * * Examples: * var d = [{foo: {bar: 1}}, {}, {}] * performRestyleLike(d, {'foo.bar': 2}, [0]) * d -> [{foo: {bar: 2}}, {}, {}] * * var d = [{foo: {bar: 1}}, {}, {}] * performRestyleLike(d, {'foo.bar': 2}, [0, 1, 2]) * d -> [{foo: {bar: 2}}, {foo: {bar: 2}}, {foo: {bar: 2}}] * * var d = [{foo: {bar: 1}}, {}, {}] * performRestyleLike(d, {'foo.bar': [2, 3, 4]}, [0, 1, 2]) * d -> [{foo: {bar: 2}}, {foo: {bar: 3}}, {foo: {bar: 4}}] * */ function performRestyleLike( parentArray: any[], restyleData: any, restyleTraces: number[] ) { // Loop over the properties of restyleData for (var rawKey in restyleData) { if (!restyleData.hasOwnProperty(rawKey)) { continue; } // Extract value for property and normalize into a value list var valArray = restyleData[rawKey]; if (!Array.isArray(valArray)) { valArray = [valArray]; } // Loop over the indexes of the traces being restyled for (var i = 0; i < restyleTraces.length; i++) { // Get trace object var traceInd = restyleTraces[i]; var trace = parentArray[traceInd]; // Extract value for this trace var singleVal = valArray[i % valArray.length]; // Set property value if (singleVal === null) { _.unset(trace, rawKey); } else if (singleVal !== undefined) { _.set(trace, rawKey, singleVal); } } } } /** * Perform a Plotly.moveTraces like operation on an input object array * @param parentArray * The object that the moveTraces operation should be applied to * @param currentInds * Array of the current indexes of traces to be moved * @param newInds * Array of the new indexes that traces selected by currentInds should be * moved to. * * Examples: * var d = [{foo: 0}, {foo: 1}, {foo: 2}] * performMoveTracesLike(d, [0, 1], [2, 0]) * d -> [{foo: 1}, {foo: 2}, {foo: 0}] * * var d = [{foo: 0}, {foo: 1}, {foo: 2}] * performMoveTracesLike(d, [0, 2], [1, 2]) * d -> [{foo: 1}, {foo: 0}, {foo: 2}] */ function performMoveTracesLike( parentArray: any[], currentInds: number[], newInds: number[] ) { // ### Remove by currentInds in reverse order ### var movingTracesData: any[] = []; for (var ci = currentInds.length - 1; ci >= 0; ci--) { // Insert moving parentArray at beginning of the list movingTracesData.splice(0, 0, parentArray[currentInds[ci]]); parentArray.splice(currentInds[ci], 1); } // ### Sort newInds and movingTracesData by newInds ### var newIndexSortedArrays = _(newInds) .zip(movingTracesData) .sortBy(0) .unzip() .value(); newInds = newIndexSortedArrays[0]; movingTracesData = newIndexSortedArrays[1]; // ### Insert by newInds in forward order ### for (var ni = 0; ni < newInds.length; ni++) { parentArray.splice(newInds[ni], 0, movingTracesData[ni]); } } /** * Remove nested properties from a parent object * @param {Object} parentObj * Parent object from which properties or nested properties should be removed * @param {Array.<Array.<Number|String>>} keyPaths * Array of key paths for properties that should be removed. Each key path * is an array of properties names or array indexes that reference a * property to be removed * * Examples: * var d = {foo: [{bar: 0}, {bar: 1}], baz: 32} * performRemoveProps(d, ['baz']) * d -> {foo: [{bar: 0}, {bar: 1}]} * * var d = {foo: [{bar: 0}, {bar: 1}], baz: 32} * performRemoveProps(d, ['foo[1].bar', 'baz']) * d -> {foo: [{bar: 0}, {}]} * */ function performRemoveProps( parentObj: object, keyPaths: Array<Array<number | string>> ) { for (var i = 0; i < keyPaths.length; i++) { var keyPath = keyPaths[i]; _.unset(parentObj, keyPath); } } /** * Return object that contains all properties in fullObj that are not * identical to the corresponding properties in removeObj * * Properties of fullObj and removeObj may be objects or arrays of objects * * Returned object is a deep clone of the properties of the input objects * * @param {Object} fullObj * @param {Object} removeObj * * Examples: * var fullD = {foo: [{bar: 0}, {bar: 1}], baz: 32} * var removeD = {baz: 32} * createDeltaObject(fullD, removeD) * -> {foo: [{bar: 0}, {bar: 1}]} * * var fullD = {foo: [{bar: 0}, {bar: 1}], baz: 32} * var removeD = {baz: 45} * createDeltaObject(fullD, removeD) * -> {foo: [{bar: 0}, {bar: 1}], baz: 32} * * var fullD = {foo: [{bar: 0}, {bar: 1}], baz: 32} * var removeD = {foo: [{bar: 0}, {bar: 1}]} * createDeltaObject(fullD, removeD) * -> {baz: 32} * */ function createDeltaObject(fullObj: any, removeObj: any) { // Initialize result as object or array var res: any; if (Array.isArray(fullObj)) { res = new Array(fullObj.length); } else { res = {}; } // Initialize removeObj to empty object if not specified if (removeObj === null || removeObj === undefined) { removeObj = {}; } // Iterate over object properties or array indices for (var p in fullObj) { if ( p[0] !== "_" && // Don't consider private properties fullObj.hasOwnProperty(p) && // Exclude parent properties fullObj[p] !== null // Exclude cases where fullObj doesn't // have the property ) { // Compute object equality var props_equal; props_equal = _.isEqual(fullObj[p], removeObj[p]); // Perform recursive comparison if props are not equal if (!props_equal || p === "uid") { // Let uids through // property has non-null value in fullObj that doesn't // match the value in removeObj var fullVal = fullObj[p]; if (removeObj.hasOwnProperty(p) && typeof fullVal === "object") { // Recurse over object properties if (Array.isArray(fullVal)) { if (fullVal.length > 0 && typeof fullVal[0] === "object") { // We have an object array res[p] = new Array(fullVal.length); for (var i = 0; i < fullVal.length; i++) { if (!Array.isArray(removeObj[p]) || removeObj[p].length <= i) { res[p][i] = fullVal[i]; } else { res[p][i] = createDeltaObject(fullVal[i], removeObj[p][i]); } } } else { // We have a primitive array or typed array res[p] = fullVal; } } else { // object var full_obj = createDeltaObject(fullVal, removeObj[p]); if (Object.keys(full_obj).length > 0) { // new object is not empty res[p] = full_obj; } } } else if (typeof fullVal === "object" && !Array.isArray(fullVal)) { // Return 'clone' of fullVal // We don't use a standard clone method so that we keep // the special case handling of this method res[p] = createDeltaObject(fullVal, {}); } else if (fullVal !== undefined && typeof fullVal !== "function") { // No recursion necessary, Just keep value from fullObj. // But skip values with function type res[p] = fullVal; } } } } return res; } function randstr( existing?: { [k: string]: any }, bits?: number, base?: number, _recursion?: number ): string { if (!base) base = 16; if (bits === undefined) bits = 24; if (bits <= 0) return "0"; var digits = Math.log(Math.pow(2, bits)) / Math.log(base); var res = ""; var i, b, x; for (i = 2; digits === Infinity; i *= 2) { digits = (Math.log(Math.pow(2, bits / i)) / Math.log(base)) * i; } var rem = digits - Math.floor(digits); for (i = 0; i < Math.floor(digits); i++) { x = Math.floor(Math.random() * base).toString(base); res = x + res; } if (rem) { b = Math.pow(base, rem); x = Math.floor(Math.random() * b).toString(base); res = x + res; } var parsed = parseInt(res, base); if ( (existing && existing[res]) || (parsed !== Infinity && parsed >= Math.pow(2, bits)) ) { if (_recursion > 10) { console.warn("randstr failed uniqueness"); return res; } return randstr(existing, bits, base, (_recursion || 0) + 1); } else return res; }
the_stack
import { fail } from 'assert'; import { expect } from 'chai'; import { stub } from 'sinon'; import { nls } from '../../../src/messages'; import { BrowserNode, ComponentUtils, MetadataOutlineProvider, NodeType, parseErrors, TypeUtils } from '../../../src/orgBrowser'; /* tslint:disable:no-unused-expression */ describe('load org browser tree outline', () => { const username = 'test-username@test1234.com'; let metadataProvider: MetadataOutlineProvider; beforeEach(() => { metadataProvider = new MetadataOutlineProvider(username); }); it('should load the root node with default org', async () => { const expectedNode = new BrowserNode(username, NodeType.Org); const orgNode = await metadataProvider.getChildren(); expect(orgNode).to.deep.equal([expectedNode]); }); it('should display emptyNode with error message if default org is not set', async () => { metadataProvider = new MetadataOutlineProvider(undefined); const expectedNode = new BrowserNode( nls.localize('missing_default_org'), NodeType.EmptyNode ); const orgNode = await metadataProvider.getChildren(); expect(orgNode).to.deep.equal([expectedNode]); }); it('should load metadata type nodes when tree is created', async () => { const metadataInfo = [ { label: 'typeNode1', type: NodeType.MetadataType, xmlName: 'typeNode1' }, { label: 'typeNode2', type: NodeType.MetadataType, xmlName: 'typeNode2' } ]; const expected = [ { label: 'typeNode1', type: NodeType.MetadataType, fullName: 'typeNode1' }, { label: 'typeNode2', type: NodeType.MetadataType, fullName: 'typeNode2' } ]; const orgNode = new BrowserNode(username, NodeType.Org); const getTypesStub = stub( MetadataOutlineProvider.prototype, 'getTypes' ).returns(metadataInfo); const typesNodes = await metadataProvider.getChildren(orgNode); compareNodes(typesNodes, expected); getTypesStub.restore(); }); it('should throw error if trouble fetching types', async () => { const orgNode = new BrowserNode(username, NodeType.Org); const loadTypesStub = stub(TypeUtils.prototype, 'loadTypes').returns( Promise.reject( JSON.stringify({ name: 'Should throw an error' }) ) ); try { await metadataProvider.getChildren(orgNode); fail('Should have thrown an error getting the children'); } catch (e) { expect(e.message).to.equal( `${nls.localize('error_fetching_metadata')} ${nls.localize( 'error_org_browser_text' )}` ); } loadTypesStub.restore(); }); it('should throw error if trouble fetching components', async () => { const metadataObject = { xmlName: 'typeNode1', directoryName: 'testDirectory', suffix: 'cls', inFolder: false, metaFile: false, label: 'Type Node 1' }; const typeNode = new BrowserNode( 'ApexClass', NodeType.MetadataType, undefined, metadataObject ); const loadCmpsStub = stub( ComponentUtils.prototype, 'loadComponents' ).returns( Promise.reject( JSON.stringify({ name: 'Should throw an error' }) ) ); try { await metadataProvider.getChildren(typeNode); fail('Should have thrown an error getting the children'); } catch (e) { expect(e.message).to.equal( `${nls.localize('error_fetching_metadata')} ${nls.localize( 'error_org_browser_text' )}` ); } loadCmpsStub.restore(); }); it('should load metadata component nodes when a type node is selected', async () => { const expected = [ { label: 'cmpNode1', fullName: 'cmpNode1', type: NodeType.MetadataComponent }, { label: 'cmpNode2', fullName: 'cmpNode2', type: NodeType.MetadataComponent } ]; const getCmpsStub = stub( MetadataOutlineProvider.prototype, 'getComponents' ).returns(expected.map(n => n.fullName)); const metadataObject = { xmlName: 'typeNode1', directoryName: 'testDirectory', suffix: 'cls', inFolder: false, metaFile: false, label: 'Type Node 1' }; const typeNode = new BrowserNode( 'ApexClass', NodeType.MetadataType, undefined, metadataObject ); const cmpsNodes = await metadataProvider.getChildren(typeNode); compareNodes(cmpsNodes, expected); getCmpsStub.restore(); }); it('should display emptyNode with error message if no components are present for a given type', async () => { const metadataObject = { xmlName: 'typeNode1', directoryName: 'classes', suffix: 'cls', inFolder: false, metaFile: false, label: 'Type Node 1' }; const typeNode = new BrowserNode( 'ApexClass', NodeType.MetadataType, undefined, metadataObject ); const emptyNode = new BrowserNode( nls.localize('empty_components'), NodeType.EmptyNode ); const loadCmpsStub = stub( ComponentUtils.prototype, 'loadComponents' ).returns([]); const cmpsNodes = await metadataProvider.getChildren(typeNode); expect(cmpsNodes).to.deep.equal([emptyNode]); loadCmpsStub.restore(); }); it('should display folders and components that live in them when a folder type node is selected', async () => { const folder1 = [ { fullName: 'SampleFolder/Sample_Template', label: 'Sample_Template', type: NodeType.MetadataField }, { fullName: 'SampleFolder/Sample_Template2', label: 'Sample_Template2', type: NodeType.MetadataField } ]; const folder2 = [ { fullName: 'SampleFolder2/Main', label: 'Main', type: NodeType.MetadataField } ]; const folders = [ { fullName: 'SampleFolder', label: 'SampleFolder', type: NodeType.Folder }, { fullName: 'SampleFolder2', label: 'SampleFolder2', type: NodeType.Folder } ]; const loadCmpStub = stub(ComponentUtils.prototype, 'loadComponents'); loadCmpStub .withArgs(username, 'EmailFolder') .returns(folders.map(n => n.fullName)); loadCmpStub .withArgs(username, 'EmailTemplate', folders[0].fullName) .returns(folder1.map(n => n.fullName)); loadCmpStub .withArgs(username, 'EmailTemplate', folders[1].fullName) .returns(folder2.map(n => n.fullName)); const metadataObject = { xmlName: 'typeNode1', directoryName: 'testDirectory', suffix: 'cls', inFolder: true, metaFile: false, label: 'Type Node 1' }; const testNode = new BrowserNode( 'EmailTemplate', NodeType.MetadataType, undefined, metadataObject ); const f = await metadataProvider.getChildren(testNode); compareNodes(f, folders); const f1 = await metadataProvider.getChildren(f[0]); compareNodes(f1, folder1); const f2 = await metadataProvider.getChildren(f[1]); compareNodes(f2, folder2); loadCmpStub.restore(); }); it('should display fields when a custom object node is selected', async () => { const loadComponentsStub = stub(ComponentUtils.prototype, 'loadComponents'); const customObjectBrowserNodes = [ new BrowserNode('Account', NodeType.Folder, 'Account', undefined), new BrowserNode('Asset', NodeType.Folder, 'Asset', undefined), new BrowserNode('Book__c', NodeType.Folder, 'Book__c', undefined), new BrowserNode('Campaign', NodeType.Folder, 'Campaign', undefined), new BrowserNode('Customer Case', NodeType.Folder, 'Customer Case', undefined) ]; const customObjectNames = [ 'Account', 'Asset', 'Book__c', 'Campaign', 'Customer Case' ]; loadComponentsStub .withArgs(username, 'CustomObject', undefined, false) .returns(Promise.resolve(customObjectNames)); const bookFieldBrowserNodes = [ new BrowserNode('Id (id)', NodeType.MetadataField, 'Id (id)', undefined), new BrowserNode('Owner (reference)', NodeType.MetadataField, 'Owner (reference)', undefined), new BrowserNode('IsDeleted (boolean)', NodeType.MetadataField, 'IsDeleted (boolean)', undefined), new BrowserNode('Name (string(80))', NodeType.MetadataField, 'Name (string(80))', undefined), new BrowserNode('CreatedDate (datetime)', NodeType.MetadataField, 'CreatedDate (datetime)', undefined), new BrowserNode('CreatedBy (reference)', NodeType.MetadataField, 'CreatedBy (reference)', undefined), new BrowserNode('LastModifiedDate (datetime)', NodeType.MetadataField, 'LastModifiedDate (datetime)', undefined), new BrowserNode('LastModifiedBy (reference)', NodeType.MetadataField, 'LastModifiedBy (reference)', undefined), new BrowserNode('SystemModstamp (datetime)', NodeType.MetadataField, 'SystemModstamp (datetime)', undefined), new BrowserNode('Price__c (currency)', NodeType.MetadataField, 'Price__c (currency)', undefined) ]; const bookFieldNames = [ 'Id (id)', 'Owner (reference)', 'IsDeleted (boolean)', 'Name (string(80))', 'CreatedDate (datetime)', 'CreatedBy (reference)', 'LastModifiedDate (datetime)', 'LastModifiedBy (reference)', 'SystemModstamp (datetime)', 'Price__c (currency)' ]; loadComponentsStub .withArgs(username, 'CustomObject', 'Book__c', false) .returns(Promise.resolve(bookFieldNames)); const customObjectMetadataObject = { directoryName: 'objects', inFolder: false, label: 'Custom Objects', metaFile: false, suffix: 'object', xmlName: 'CustomObject' }; const customObjectNode = new BrowserNode( 'Custom Objects', NodeType.MetadataType, 'CustomObject', customObjectMetadataObject ); const customObjects = await metadataProvider.getChildren(customObjectNode); compareNodes(customObjects, customObjectBrowserNodes); const fields = await metadataProvider.getChildren(customObjects[2]); compareNodes(fields, bookFieldBrowserNodes); loadComponentsStub.restore(); }); it('should call loadComponents with force refresh', async () => { const loadCmpStub = stub( ComponentUtils.prototype, 'loadComponents' ).returns([]); const metadataObject = { xmlName: 'typeNode1', directoryName: 'testDirectory', suffix: 'cls', inFolder: false, metaFile: false, label: 'Type Node 1' }; const node = new BrowserNode( 'ApexClass', NodeType.MetadataType, undefined, metadataObject ); await metadataProvider.getChildren(node); expect(loadCmpStub.getCall(0).args[3]).to.be.false; await metadataProvider.refresh(node); await metadataProvider.getChildren(node); expect(loadCmpStub.getCall(1).args[3]).to.be.true; await metadataProvider.getChildren(node); expect(loadCmpStub.getCall(2).args[3]).to.be.false; loadCmpStub.restore(); }); it('should call loadTypes with force refresh', async () => { const loadTypesStub = stub(TypeUtils.prototype, 'loadTypes').returns([]); const usernameStub = stub( MetadataOutlineProvider.prototype, 'getDefaultUsernameOrAlias' ).returns(username); const node = new BrowserNode(username, NodeType.Org); await metadataProvider.getChildren(node); expect(loadTypesStub.getCall(0).args[1]).to.be.false; await metadataProvider.refresh(); await metadataProvider.getChildren(node); expect(loadTypesStub.getCall(1).args[1]).to.be.true; await metadataProvider.getChildren(node); expect(loadTypesStub.getCall(2).args[1]).to.be.false; loadTypesStub.restore(); usernameStub.restore(); }); }); // Can't compare nodes w/ deep.equal because of circular parent node reference function compareNodes(actual: BrowserNode[], expected: any[]) { expected.forEach((node, index) => { Object.keys(node).forEach(key => { expect((actual[index] as any)[key]).to.equal((node as any)[key]); }); }); } describe('parse errors and throw with appropriate message', () => { it('should return default message when given a dirty json', async () => { const error = `< Warning: sfdx-cli update available + ${JSON.stringify({ status: 1, name: 'RetrievingError' })}`; const errorResponse = parseErrors(error); expect(errorResponse.message).to.equal( `${nls.localize('error_fetching_metadata')} ${nls.localize( 'error_org_browser_text' )}` ); }); it('should return authorization token message when throwing RefreshTokenAuthError', async () => { const error = JSON.stringify({ status: 1, name: 'RefreshTokenAuthError' }); const errorResponse = parseErrors(error); expect(errorResponse.message).to.equal( `${nls.localize('error_auth_token')} ${nls.localize( 'error_org_browser_text' )}` ); }); it('should return no org found message when throwing NoOrgFound error', async () => { const error = JSON.stringify({ status: 1, name: 'NoOrgFound' }); const errorResponse = parseErrors(error); expect(errorResponse.message).to.equal( `${nls.localize('error_no_org_found')} ${nls.localize( 'error_org_browser_text' )}` ); }); });
the_stack
import { GenesisBlock, Chain, Block, Transaction } from '@liskhq/lisk-chain'; import { jobHandlers } from '@liskhq/lisk-utils'; import { ForkStatus, BFT } from '@liskhq/lisk-bft'; import { validator } from '@liskhq/lisk-validator'; import { CustomModule0, CustomModule1 } from './custom_modules'; import { Processor } from '../../../../src/node/processor'; describe('processor', () => { const defaultLastBlock = { header: { id: Buffer.from('lastId'), version: 1, height: 98, }, payload: [], }; let processor: Processor; let channelStub: any; let loggerStub: any; let chainModuleStub: Chain; let bftModuleStub: BFT; let stateStoreStub: any; let customModule0: CustomModule0; let customModule1: CustomModule1; beforeEach(() => { customModule0 = new CustomModule0({} as any); customModule1 = new CustomModule1({} as any); channelStub = { publish: jest.fn(), }; loggerStub = { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(), trace: jest.fn(), }; stateStoreStub = { chain: { cache: jest.fn(), }, }; chainModuleStub = ({ init: jest.fn(), genesisBlockExist: jest.fn(), validateGenesisBlockHeader: jest.fn(), applyGenesisBlock: jest.fn(), validateBlockHeader: jest.fn(), validateTransaction: jest.fn(), verifyBlockHeader: jest.fn(), saveBlock: jest.fn(), removeBlock: jest.fn(), newStateStore: jest.fn().mockResolvedValue(stateStoreStub), dataAccess: { encode: jest.fn(), decode: jest.fn(), }, } as unknown) as Chain; bftModuleStub = ({ init: jest.fn(), forkChoice: jest.fn(), verifyBlockHeader: jest.fn(), applyBlockHeader: jest.fn(), finalizedHeight: 5, } as unknown) as BFT; Object.defineProperty(chainModuleStub, 'lastBlock', { get: jest.fn().mockReturnValue(defaultLastBlock), }); processor = new Processor({ channel: channelStub, logger: loggerStub, chainModule: chainModuleStub, bftModule: bftModuleStub, }); }); describe('constructor', () => { describe('when the instance is created', () => { it('should initialize the sequence', () => { expect(processor['_mutex']).toBeInstanceOf(jobHandlers.Mutex); }); it('should assign channel to its context', () => { expect(processor['_channel']).toBe(channelStub); }); it('should assign blocks module to its context', () => { expect(processor['_chain']).toBe(chainModuleStub); }); it('should assign logger to its context', () => { expect(processor['_logger']).toBe(loggerStub); }); }); }); describe('register', () => { describe('when module is registered', () => { it('should store the module', () => { processor.register(customModule0); processor.register(customModule1); expect(processor['_modules']).toHaveLength(2); }); }); }); describe('init', () => { const genesisBlock = ({ header: { id: Buffer.from('fakeGenesisBlock'), version: 0, }, payload: [], } as unknown) as GenesisBlock; beforeEach(() => { processor.register(customModule0); processor.register(customModule1); }); it('should process genesis block if genesis block does not exist', async () => { // Arrange jest.spyOn(chainModuleStub, 'genesisBlockExist').mockResolvedValue(false); // Act await processor.init(genesisBlock); // Assert expect(customModule0.afterGenesisBlockApply).toHaveBeenCalledTimes(1); expect(chainModuleStub.init).toHaveBeenCalledTimes(1); expect(chainModuleStub.saveBlock).toHaveBeenCalledTimes(1); expect(bftModuleStub.init).toHaveBeenCalledTimes(1); }); it('should not apply genesis block if it exists in chain', async () => { // Arrange jest.spyOn(chainModuleStub, 'genesisBlockExist').mockResolvedValue(true); // Act await processor.init(genesisBlock); // Assert expect(customModule0.afterGenesisBlockApply).not.toHaveBeenCalled(); expect(chainModuleStub.init).toHaveBeenCalledTimes(1); expect(bftModuleStub.init).toHaveBeenCalledTimes(1); }); }); describe('process', () => { const blockV2 = ({ header: { id: Buffer.from('fakelock1'), version: 2, height: 99, }, payload: [ new Transaction({ asset: Buffer.alloc(0), moduleID: 3, assetID: 0, fee: BigInt(10000000), nonce: BigInt(3), senderPublicKey: Buffer.from('0a08736f6d6520737472', 'hex'), signatures: [], }), ], } as unknown) as Block; const encodedBlock = Buffer.from('encoded block'); beforeEach(() => { processor.register(customModule0); processor.register(customModule1); (chainModuleStub.dataAccess.encode as jest.Mock).mockReturnValue(encodedBlock); }); describe('when the fork step returns unknown fork status', () => { beforeEach(() => { (bftModuleStub.forkChoice as jest.Mock).mockReturnValue(undefined); }); it('should throw an error', async () => { await expect(processor.process(blockV2)).rejects.toThrow('Unknown fork status'); }); }); describe('when the fork step returns ForkStatus.IDENTICAL_BLOCK', () => { beforeEach(async () => { (bftModuleStub.forkChoice as jest.Mock).mockReturnValue(ForkStatus.IDENTICAL_BLOCK); await processor.process(blockV2); }); it('should not validate block', () => { expect(chainModuleStub.validateBlockHeader).not.toHaveBeenCalled(); }); it('should not verify block', () => { expect(chainModuleStub.verifyBlockHeader).not.toHaveBeenCalled(); expect(bftModuleStub.verifyBlockHeader).not.toHaveBeenCalled(); }); it('should not call hooks', () => { expect(customModule0.beforeBlockApply).not.toHaveBeenCalled(); expect(customModule0.afterBlockApply).not.toHaveBeenCalled(); expect(customModule0.beforeTransactionApply).not.toHaveBeenCalled(); expect(customModule0.afterTransactionApply).not.toHaveBeenCalled(); }); it('should not save block', () => { expect(chainModuleStub.saveBlock).not.toHaveBeenCalled(); }); it('should not publish any event', () => { expect(channelStub.publish).not.toHaveBeenCalled(); }); }); describe('when the fork step returns ForkStatus.DOUBLE_FORGING', () => { beforeEach(async () => { (bftModuleStub.forkChoice as jest.Mock).mockReturnValue(ForkStatus.DOUBLE_FORGING); await processor.process(blockV2); }); it('should not validate block', () => { expect(chainModuleStub.validateBlockHeader).not.toHaveBeenCalled(); }); it('should not verify block', () => { expect(chainModuleStub.verifyBlockHeader).not.toHaveBeenCalled(); expect(bftModuleStub.verifyBlockHeader).not.toHaveBeenCalled(); }); it('should not call hooks', () => { expect(customModule0.beforeBlockApply).not.toHaveBeenCalled(); expect(customModule0.afterBlockApply).not.toHaveBeenCalled(); expect(customModule0.beforeTransactionApply).not.toHaveBeenCalled(); expect(customModule0.afterTransactionApply).not.toHaveBeenCalled(); }); it('should not save block', () => { expect(chainModuleStub.saveBlock).not.toHaveBeenCalled(); }); it('should publish fork event', () => { expect(channelStub.publish).toHaveBeenCalledWith('app:chain:fork', { block: encodedBlock.toString('hex'), }); }); }); describe('when the fork step returns ForkStatus.TIE_BREAK and success to process', () => { beforeEach(async () => { (bftModuleStub.forkChoice as jest.Mock).mockReturnValue(ForkStatus.TIE_BREAK); jest.spyOn(processor.events, 'emit'); await processor.process(blockV2); }); it('should publish fork event', () => { expect(channelStub.publish).toHaveBeenCalledWith('app:chain:fork', { block: encodedBlock.toString('hex'), }); }); it('should validate block', () => { expect(chainModuleStub.validateBlockHeader).toHaveBeenCalledTimes(1); }); it('should revert the last block', () => { expect(chainModuleStub.removeBlock).toHaveBeenCalledWith(defaultLastBlock, stateStoreStub, { saveTempBlock: false, }); }); it('should verify the block', () => { expect(chainModuleStub.verifyBlockHeader).toHaveBeenCalledTimes(1); expect(bftModuleStub.verifyBlockHeader).toHaveBeenCalledTimes(1); }); it('should apply the block', () => { expect(bftModuleStub.applyBlockHeader).toHaveBeenCalledTimes(1); expect(customModule0.beforeBlockApply).toHaveBeenCalledTimes(1); expect(customModule0.afterBlockApply).toHaveBeenCalledTimes(1); expect(customModule0.beforeTransactionApply).toHaveBeenCalledTimes(1); expect(customModule0.afterTransactionApply).toHaveBeenCalledTimes(1); }); it('should save the block', () => { expect(chainModuleStub.saveBlock).toHaveBeenCalledWith( blockV2, stateStoreStub, bftModuleStub.finalizedHeight, { removeFromTempTable: false, }, ); }); it('should emit broadcast event for the block', () => { expect(processor.events.emit).toHaveBeenCalledWith('EVENT_PROCESSOR_BROADCAST_BLOCK', { block: blockV2, }); }); }); describe('when the fork step returns ForkStatus.TIE_BREAK and fail to process', () => { beforeEach(async () => { (chainModuleStub.verifyBlockHeader as jest.Mock).mockRejectedValueOnce( new Error('invalid block'), ); (bftModuleStub.forkChoice as jest.Mock).mockReturnValue(ForkStatus.TIE_BREAK); try { await processor.process(blockV2); } catch (err) { // Expected error } }); it('should publish fork event', () => { expect(channelStub.publish).toHaveBeenCalledWith('app:chain:fork', { block: encodedBlock.toString('hex'), }); }); it('should validate block', () => { expect(chainModuleStub.validateBlockHeader).toHaveBeenCalledTimes(1); }); it('should revert the last block', () => { expect(chainModuleStub.removeBlock).toHaveBeenCalledWith(defaultLastBlock, stateStoreStub, { saveTempBlock: false, }); }); it('should not emit broadcast event for the block', () => { expect(channelStub.publish).not.toHaveBeenCalledWith( 'app:block:broadcast', expect.anything(), ); }); it('should verify the last block', () => { expect(chainModuleStub.verifyBlockHeader).toHaveBeenCalledTimes(2); expect(bftModuleStub.verifyBlockHeader).toHaveBeenCalledTimes(1); }); it('should apply the last block', () => { expect(bftModuleStub.applyBlockHeader).toHaveBeenCalledTimes(1); expect(customModule0.beforeBlockApply).toHaveBeenCalledTimes(1); expect(customModule0.afterBlockApply).toHaveBeenCalledTimes(1); expect(customModule0.beforeTransactionApply).toHaveBeenCalledTimes(0); expect(customModule0.afterTransactionApply).toHaveBeenCalledTimes(0); }); it('should save the last block', () => { expect(chainModuleStub.saveBlock).toHaveBeenCalledWith( defaultLastBlock, stateStoreStub, bftModuleStub.finalizedHeight, { removeFromTempTable: false }, ); }); }); describe('when the fork step returns ForkStatus.DIFFERENT_CHAIN', () => { beforeEach(async () => { (bftModuleStub.forkChoice as jest.Mock).mockReturnValue(ForkStatus.DIFFERENT_CHAIN); jest.spyOn(processor.events, 'emit'); await processor.process(blockV2); }); it('should not validate block', () => { expect(chainModuleStub.validateBlockHeader).not.toHaveBeenCalled(); }); it('should not verify block', () => { expect(chainModuleStub.verifyBlockHeader).not.toHaveBeenCalled(); expect(bftModuleStub.verifyBlockHeader).not.toHaveBeenCalled(); }); it('should not call hooks', () => { expect(customModule0.beforeBlockApply).not.toHaveBeenCalled(); expect(customModule0.afterBlockApply).not.toHaveBeenCalled(); expect(customModule0.beforeTransactionApply).not.toHaveBeenCalled(); expect(customModule0.afterTransactionApply).not.toHaveBeenCalled(); }); it('should not save block', () => { expect(chainModuleStub.saveBlock).not.toHaveBeenCalled(); }); it('should publish sync', () => { expect(processor.events.emit).toHaveBeenCalledWith('EVENT_PROCESSOR_SYNC_REQUIRED', { block: blockV2, }); }); it('should publish fork event', () => { expect(channelStub.publish).toHaveBeenCalledWith('app:chain:fork', { block: encodedBlock.toString('hex'), }); }); }); describe('when the fork step returns ForkStatus.DISCARD', () => { beforeEach(async () => { (bftModuleStub.forkChoice as jest.Mock).mockReturnValue(ForkStatus.DISCARD); await processor.process(blockV2); }); it('should not validate block', () => { expect(chainModuleStub.validateBlockHeader).not.toHaveBeenCalled(); }); it('should not verify block', () => { expect(chainModuleStub.verifyBlockHeader).not.toHaveBeenCalled(); expect(bftModuleStub.verifyBlockHeader).not.toHaveBeenCalled(); }); it('should not call hooks', () => { expect(customModule0.beforeBlockApply).not.toHaveBeenCalled(); expect(customModule0.afterBlockApply).not.toHaveBeenCalled(); expect(customModule0.beforeTransactionApply).not.toHaveBeenCalled(); expect(customModule0.afterTransactionApply).not.toHaveBeenCalled(); }); it('should not save block', () => { expect(chainModuleStub.saveBlock).not.toHaveBeenCalled(); }); it('should publish fork event', () => { expect(channelStub.publish).toHaveBeenCalledWith('app:chain:fork', { block: encodedBlock.toString('hex'), }); }); }); describe('when the fork step returns ForkStatus.VALID_BLOCK', () => { beforeEach(async () => { (bftModuleStub.forkChoice as jest.Mock).mockReturnValue(ForkStatus.VALID_BLOCK); jest.spyOn(processor.events, 'emit'); await processor.process(blockV2); }); it('should validate block', () => { expect(chainModuleStub.validateBlockHeader).toHaveBeenCalledTimes(1); }); it('should not emit broadcast event for the block', () => { expect(channelStub.publish).not.toHaveBeenCalledWith( 'app:block:broadcast', expect.anything(), ); }); it('should verify the last block', () => { expect(chainModuleStub.verifyBlockHeader).toHaveBeenCalledTimes(1); expect(bftModuleStub.verifyBlockHeader).toHaveBeenCalledTimes(1); }); it('should apply the block', () => { expect(bftModuleStub.applyBlockHeader).toHaveBeenCalledTimes(1); expect(customModule0.beforeBlockApply).toHaveBeenCalledTimes(1); expect(customModule0.afterBlockApply).toHaveBeenCalledTimes(1); expect(customModule0.beforeTransactionApply).toHaveBeenCalledTimes(1); expect(customModule0.afterTransactionApply).toHaveBeenCalledTimes(1); }); it('should save the block', () => { expect(chainModuleStub.saveBlock).toHaveBeenCalledWith( blockV2, stateStoreStub, bftModuleStub.finalizedHeight, { removeFromTempTable: false }, ); }); it('should broadcast with the block', () => { expect(processor.events.emit).toHaveBeenCalledWith('EVENT_PROCESSOR_BROADCAST_BLOCK', { block: blockV2, }); }); }); }); describe('validate', () => { const tx = new Transaction({ asset: Buffer.alloc(0), moduleID: 3, assetID: 0, fee: BigInt(10000000), nonce: BigInt(3), senderPublicKey: Buffer.from('0a08736f6d6520737472', 'hex'), signatures: [], }); const blockV2 = ({ header: { id: Buffer.from('fakelock2'), version: 2, height: 100, }, payload: [tx], } as unknown) as Block; beforeEach(() => { processor.register(customModule0); processor.register(customModule1); }); it('should throw error if version is not 2', async () => { const blockV3 = { ...blockV2, header: { ...blockV2.header, version: 3, }, }; await expect(processor.validate(blockV3)).rejects.toThrow('Block version must be 2'); }); it('should validate basic properties of block header', async () => { await processor.validate(blockV2); expect(chainModuleStub.validateBlockHeader).toHaveBeenCalledTimes(1); }); it('should validate payload', async () => { await processor.validate(blockV2); expect(chainModuleStub.validateTransaction).toHaveBeenCalledTimes(1); }); it('should validate payload asset', async () => { jest.spyOn(validator, 'validate'); await processor.validate(blockV2); expect(validator.validate).toHaveBeenCalledTimes(1); expect(validator.validate).toHaveBeenCalledWith( customModule0.transactionAssets[0].schema, expect.any(Object), ); }); it('should fail when module id does not exist', async () => { const block = ({ header: { id: Buffer.from('fakelock2'), version: 2, height: 100, }, payload: [ new Transaction({ asset: Buffer.alloc(0), moduleID: 20, assetID: 5, fee: BigInt(10000000), nonce: BigInt(3), senderPublicKey: Buffer.from('0a08736f6d6520737472', 'hex'), signatures: [], }), ], } as unknown) as Block; await expect(processor.validate(block)).rejects.toThrow('Module id 20 does not exist'); }); it('should fail when asset id does not exist', async () => { const block = ({ header: { id: Buffer.from('fakelock2'), version: 2, height: 100, }, payload: [ new Transaction({ asset: Buffer.alloc(0), moduleID: 3, assetID: 5, fee: BigInt(10000000), nonce: BigInt(3), senderPublicKey: Buffer.from('0a08736f6d6520737472', 'hex'), signatures: [], }), ], } as unknown) as Block; await expect(processor.validate(block)).rejects.toThrow( 'Asset id 5 does not exist in module id 3.', ); }); }); describe('processValidated', () => { const blockV1 = ({ header: { id: Buffer.from('fakelock1'), version: 1, height: 99, }, payload: [ new Transaction({ asset: Buffer.alloc(0), moduleID: 3, assetID: 0, fee: BigInt(10000000), nonce: BigInt(3), senderPublicKey: Buffer.from('0a08736f6d6520737472', 'hex'), signatures: [], }), ], } as unknown) as Block; beforeEach(() => { processor.register(customModule0); processor.register(customModule1); }); describe('when block is not verifiable', () => { beforeEach(async () => { (chainModuleStub.verifyBlockHeader as jest.Mock).mockRejectedValueOnce( new Error('invalid block header'), ); try { await processor.processValidated(blockV1); } catch (error) { // expected error } }); it('should not apply the block', () => { expect(bftModuleStub.applyBlockHeader).not.toHaveBeenCalled(); expect(customModule0.beforeBlockApply).not.toHaveBeenCalled(); expect(customModule0.afterBlockApply).not.toHaveBeenCalled(); expect(customModule0.beforeTransactionApply).not.toHaveBeenCalled(); expect(customModule0.afterTransactionApply).not.toHaveBeenCalled(); }); it('should not save the block', () => { expect(chainModuleStub.saveBlock).not.toHaveBeenCalled(); }); it('should not broadcast the block', () => { expect(channelStub.publish).not.toHaveBeenCalledWith( 'app:block:broadcast', expect.anything(), ); }); it('should not emit newBlock event', () => { expect(channelStub.publish).not.toHaveBeenCalledWith('app:block:new', expect.anything()); }); }); describe('when block is not applicable', () => { beforeEach(async () => { customModule0.beforeBlockApply.mockRejectedValue(new Error('Invalid block')); try { await processor.processValidated(blockV1); } catch (err) { // expected error } }); it('should call subsequent hooks', () => { expect(customModule0.afterBlockApply).not.toHaveBeenCalled(); expect(customModule0.beforeTransactionApply).not.toHaveBeenCalled(); expect(customModule0.afterTransactionApply).not.toHaveBeenCalled(); }); it('should not broadcast the block', () => { expect(channelStub.publish).not.toHaveBeenCalledWith( 'app:block:broadcast', expect.anything(), ); }); it('should not emit newBlock event', () => { expect(channelStub.publish).not.toHaveBeenCalledWith('app:block:new', expect.anything()); }); }); describe('when block cannot be saved', () => { beforeEach(async () => { (chainModuleStub.saveBlock as jest.Mock).mockRejectedValue(new Error('Invalid block')); try { await processor.processValidated(blockV1); } catch (error) { // expected error } }); it('should verify the block', () => { expect(chainModuleStub.verifyBlockHeader).toHaveBeenCalledTimes(1); expect(bftModuleStub.verifyBlockHeader).toHaveBeenCalledTimes(1); }); it('should apply the block', () => { expect(bftModuleStub.applyBlockHeader).toHaveBeenCalledTimes(1); expect(customModule0.beforeBlockApply).toHaveBeenCalledTimes(1); expect(customModule0.afterBlockApply).toHaveBeenCalledTimes(1); expect(customModule0.beforeTransactionApply).toHaveBeenCalledTimes(1); expect(customModule0.afterTransactionApply).toHaveBeenCalledTimes(1); }); it('should not broadcast the block', () => { expect(channelStub.publish).not.toHaveBeenCalledWith( 'app:block:broadcast', expect.anything(), ); }); it('should not emit newBlock event', () => { expect(channelStub.publish).not.toHaveBeenCalledWith('app:block:new', expect.anything()); }); }); describe('when block successfully processed with flag removeFromTempTable = true', () => { beforeEach(async () => { await processor.processValidated(blockV1, { removeFromTempTable: true, }); }); it('should remove block from temp_blocks table', () => { expect(chainModuleStub.saveBlock).toHaveBeenCalledWith( blockV1, stateStoreStub, bftModuleStub.finalizedHeight, { removeFromTempTable: true, }, ); }); }); describe('when block successfully processed', () => { beforeEach(async () => { await processor.processValidated(blockV1); }); it('should verify the block', () => { expect(chainModuleStub.verifyBlockHeader).toHaveBeenCalledTimes(1); expect(bftModuleStub.verifyBlockHeader).toHaveBeenCalledTimes(1); }); it('should apply the block', () => { expect(bftModuleStub.applyBlockHeader).toHaveBeenCalledTimes(1); expect(customModule0.beforeBlockApply).toHaveBeenCalledTimes(1); expect(customModule0.afterBlockApply).toHaveBeenCalledTimes(1); expect(customModule0.beforeTransactionApply).toHaveBeenCalledTimes(1); expect(customModule0.afterTransactionApply).toHaveBeenCalledTimes(1); }); it('should save the block', () => { expect(chainModuleStub.saveBlock).toHaveBeenCalledWith( blockV1, stateStoreStub, bftModuleStub.finalizedHeight, { removeFromTempTable: false, }, ); }); it('should not broadcast the block', () => { expect(channelStub.publish).not.toHaveBeenCalledWith( 'app:block:broadcast', expect.anything(), ); }); }); }); describe('deleteLastBlock', () => { describe('when everything is successful', () => { beforeEach(async () => { await processor.deleteLastBlock(); }); it('should call remove from chainModule', () => { expect(chainModuleStub.removeBlock).toHaveBeenCalledWith(defaultLastBlock, stateStoreStub, { saveTempBlock: false, }); }); }); }); describe('validateTransaction', () => { const tx = new Transaction({ asset: Buffer.alloc(0), moduleID: 3, assetID: 0, fee: BigInt(10000000), nonce: BigInt(3), senderPublicKey: Buffer.from('0a08736f6d6520737472', 'hex'), signatures: [], }); beforeEach(() => { processor.register(customModule0); processor.register(customModule1); }); it('should throw if module is not registered', () => { expect(() => processor.validateTransaction( new Transaction({ asset: Buffer.from('0a0873d34d3420737472', 'hex'), moduleID: 99, assetID: 0, fee: BigInt(10000000), nonce: BigInt(3), senderPublicKey: Buffer.alloc(0), signatures: [], }), ), ).toThrow('Module id 99 does not exist'); }); it('should throw if asset is not registered', () => { expect(() => processor.validateTransaction( new Transaction({ asset: Buffer.from('0a0873d34d3420737472', 'hex'), moduleID: 3, assetID: 99, fee: BigInt(10000000), nonce: BigInt(3), senderPublicKey: Buffer.alloc(0), signatures: [], }), ), ).toThrow('Asset id 99 does not exist in module id 3'); }); it('should throw if root schema is invalid', () => { (chainModuleStub.validateTransaction as jest.Mock).mockImplementation(() => { throw new Error('Lisk validator found 1 error'); }); expect(() => processor.validateTransaction( new Transaction({ asset: Buffer.from('0a0873d34d3420737472', 'hex'), moduleID: 3, assetID: 0, fee: BigInt(10000000), nonce: BigInt(-3), senderPublicKey: Buffer.alloc(0), signatures: [], }), ), ).toThrow('Lisk validator found 1 error'); }); it('should throw if asset validation fails', () => { customModule0.transactionAssets[0].validate.mockImplementation(() => { throw new Error('invalid tx'); }); expect(() => processor.validateTransaction(tx)).toThrow('invalid tx'); }); it('should not throw transaction is valid', () => { expect(() => processor.validateTransaction(tx)).not.toThrow(); }); }); describe('verifyTransaction', () => { const tx = new Transaction({ asset: Buffer.alloc(0), moduleID: 3, assetID: 0, fee: BigInt(10000000), nonce: BigInt(3), senderPublicKey: Buffer.from('0a08736f6d6520737472', 'hex'), signatures: [], }); const tx2 = new Transaction({ asset: Buffer.from('0a08736f6d6520737472', 'hex'), moduleID: 3, assetID: 0, fee: BigInt(10100000), nonce: BigInt(4), senderPublicKey: Buffer.from('0a08736f6d6520737472', 'hex'), signatures: [], }); beforeEach(() => { processor.register(customModule0); processor.register(customModule1); }); it('should not verify if transaction input is empty', async () => { await processor.verifyTransactions([], stateStoreStub); expect(customModule0.beforeTransactionApply).not.toHaveBeenCalled(); expect(customModule0.afterTransactionApply).not.toHaveBeenCalled(); }); it('should call all hooks for transaction', async () => { await processor.verifyTransactions([tx, tx2], stateStoreStub); expect(customModule0.beforeTransactionApply).toHaveBeenCalledTimes(2); expect(customModule0.transactionAssets[0].apply).toHaveBeenCalledTimes(2); expect(customModule0.afterTransactionApply).toHaveBeenCalledTimes(2); expect(customModule1.afterTransactionApply).toHaveBeenCalledTimes(2); }); it('should reject if module id does not exist', async () => { await expect( processor.verifyTransactions( [ new Transaction({ asset: Buffer.alloc(0), moduleID: 99, assetID: 0, fee: BigInt(10000000), nonce: BigInt(3), senderPublicKey: Buffer.from('0a08736f6d6520737472', 'hex'), signatures: [], }), ], stateStoreStub, ), ).rejects.toThrow('Module id 99 does not exist'); }); it('should reject if asset id does not exist', async () => { await expect( processor.verifyTransactions( [ new Transaction({ asset: Buffer.alloc(0), moduleID: 4, assetID: 0, fee: BigInt(10000000), nonce: BigInt(3), senderPublicKey: Buffer.from('0a08736f6d6520737472', 'hex'), signatures: [], }), ], stateStoreStub, ), ).rejects.toThrow('Asset id 0 does not exist in module id 4'); }); it('should resolve transaction is valid', async () => { await expect( processor.verifyTransactions([tx, tx2], stateStoreStub), ).resolves.toBeUndefined(); }); }); // TODO: this is private function, so there should be better way to test it from outside describe('_createReducerHandler', () => { beforeEach(() => { processor.register(customModule0); processor.register(customModule1); }); it('should reject if format name is invalid', async () => { const handler = processor['_createReducerHandler'](stateStoreStub); await expect(handler.invoke('customModule0:testing:input', { input: 0 })).rejects.toThrow( 'Invalid format to call reducer', ); }); it('should reject if function is not registered', async () => { const handler = processor['_createReducerHandler'](stateStoreStub); await expect(handler.invoke('customModule0:notFound', { input: 0 })).rejects.toThrow( 'notFound does not exist in module customModule0', ); }); it('should resolve to the response of the reducer', async () => { customModule0.reducers.testing.mockResolvedValue(BigInt(200)); const handler = processor['_createReducerHandler'](stateStoreStub); const res = await handler.invoke('customModule0:testing', { input: 0 }); expect(res).toEqual(BigInt(200)); expect(customModule0.reducers.testing).toHaveBeenCalledWith({ input: 0 }, expect.anything()); }); }); });
the_stack
const { path } = require('@vuepress/utils') module.exports = { // 注入到当前页面的 HTML <head> 中的标签 head: [ [ 'link', { rel: 'icon', href: '/logo-s.png', }, ], // 增加一个自定义的 favicon(网页标签的图标) [ 'script', { src: 'https://cdn.jsdelivr.net/npm/react/umd/react.production.min.js' }, ], [ 'script', { src: 'https://cdn.jsdelivr.net/npm/react-dom/umd/react-dom.production.min.js', }, ], ['script', { src: 'https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js' }], [ 'script', { src: 'https://cdn.jsdelivr.net/npm/@babel/standalone/babel.min.js' }, ], ], // 这是部署到github相关的配置 base: '/Different-UI/', markdown: { lineNumbers: true, // 代码块显示行号 }, // directiveTransforms: { // // v-magnifier -> magnifier // magnifier: () => ({ // props: [], // needRuntime: true, // <- remember this // }), // }, locales: { // 键名是该语言所属的子路径 // 作为特例,默认语言可以使用 '/' 作为其路径。 '/': { lang: 'zh-CN', // 将会被设置为 <html> 的 lang 属性 title: 'Different', description: '一个Vue 3 UI组件库', }, '/en/': { lang: 'eh-US', title: 'Different', description: 'A Vue.js 3 UI library', }, }, themeConfig: { // sidebarDepth: 2, // 将同时提取markdown中h2 和 h3 标题,显示在侧边栏上,默认为1(只会显示h2标题),若 sidebar 下也配置该属性,则以 sidebar 的为准 activeHeaderLinks: true, // 当用户通过滚动查看页面的不同部分时,嵌套的标题链接和 URL 中的 Hash 值会实时更新, 默认为 true nextLinks: true, // 显示下一篇链接, 默认为 true prevLinks: true, // 显示上一篇链接, 默认为 true search: true, searchMaxSuggestions: 10, locales: { '/': { selectLanguageText: '多语言', selectLanguageName: '简体中文', // ariaLabel: '', lastUpdated: '上次更新', editLinkText: '在Github上编辑此页', contributors: true, contributorsText: '贡献者列表', serviceWorker: { updatePopup: { message: '有新的内容被推送', buttonText: '刷新', }, }, navbar: [ { text: '版本', children: [ { text: 'v0.1.1-beta.11', link: 'https://github.com/yesmore/different-ui', }, ], }, { text: '指南', link: '/guide/', }, // 内部链接 { text: '组件', link: '/component/', }, { text: '帮助', link: '/help/', }, { text: '快乐码原', link: 'https://yesmore.cc', target: '_blank', }, // 外部链接 { text: 'Github', link: 'https://github.com/yesmore/different-ui', }, ], sidebar: { '/guide/': [ { text: '指南', // collapsable: false, // 是否侧边菜单折叠,默认值是 true children: ['/guide/README.md', '/guide/start.md'], }, { text: '深入', // collapsable: false, // sidebarDepth: 3, children: ['/guide/link.md'], }, ], '/component/': [ // 设置侧边栏分组, 通过设置 children 将页面划分到分组里 { text: 'Basic 基础组件', // sidebarDepth: 4, // collapsable: false, // 是否侧边菜单折叠,默认值是 true children: [ '/component/', '/component/button.md', '/component/magnifier.md', '/component/icon.md', '/component/toolClass.md', ], }, { text: 'Form 表单组件', children: ['/component/starsrate.md', '/component/switch.md'], }, { text: 'Data 数据展示', children: ['/component/card.md'], }, { text: 'Navigation 导航', children: ['/component/more.md'], }, { text: 'Feedback 反馈组件', children: ['/component/message.md', '/component/modal.md'], }, { text: 'Business 业务', children: ['/component/more.md'], }, { text: 'Others 其他', children: ['/component/animation.md'], }, ], '/help/': [ { text: '帮助', children: ['/component/'], }, ], // 配置 auto 适合单文件 README.md 的场景, 自动生成侧边栏 }, }, '/en/': { selectLanguageText: 'Languages', // 多语言下拉菜单的标题 selectLanguageName: 'English', lastUpdatedText: 'Last Updated', lastUpdated: 'Last Updated', editLinkText: 'Edit this page on GitHub', contributors: true, contributorsText: 'Contributors', // 该语言在下拉菜单中的标签 // Service Worker 的配置 serviceWorker: { updatePopup: { message: 'New content is available.', buttonText: 'Refresh', }, }, navbar: [ { text: 'Version', children: [ { text: 'v0.1.1-beta.3', link: 'https://github.com/yesmore/different-ui', }, ], }, { text: 'Guide', link: '/en/guide/', }, // 内部链接 { text: 'Component', link: '/en/component/', }, { text: 'Help', link: '/en/help/', }, { text: 'Blog', link: 'https://yesmore.cc', target: '_blank', }, // 外部链接 { text: 'Github', link: 'https://github.com/yesmore/different-ui', }, ], sidebar: { '/en/guide/': [ { text: 'Guide', // collapsable: false, // 是否侧边菜单折叠,默认值是 true children: ['/en/guide/README.md', '/en/guide/start.md'], }, { text: 'More', // collapsable: false, // sidebarDepth: 3, children: ['/en/guide/link.md'], }, ], '/en/component/': [ // 设置侧边栏分组, 通过设置 children 将页面划分到分组里 { text: 'Basic', // sidebarDepth: 4, // collapsable: false, // 是否侧边菜单折叠,默认值是 true children: [ '/en/component/', '/en/component/button.md', '/en/component/magnifier.md', '/en/component/icon.md', '/en/component/toolClass.md', ], }, { text: 'Form', children: [ '/en/component/starsrate.md', '/en/component/switch.md', ], }, { text: 'Data', children: ['/en/component/card.md'], }, { text: 'Navigation', children: ['/component/more.md'], }, { text: 'Feedback', children: ['/en/component/message.md'], }, { text: 'Business', children: ['/en/component/more.md'], }, { text: 'Others', children: ['/en/component/animation.md'], }, ], '/en/help/': [ { text: 'Help', children: ['/en/component/'], }, ], // 配置 auto 适合单文件 README.md 的场景, 自动生成侧边栏 }, }, }, }, plugins: [ [ '@vuepress/plugin-search', { locales: { '/': { placeholder: '搜索', }, '/en/': { placeholder: 'Search', }, }, }, ], [ '@vuepress/register-components', { components: { DfTemplate: path.resolve(__dirname, './components/DfTemplate.vue'), DfIcon: path.resolve(__dirname, './components/DfIcon.vue'), DfAnimation: path.resolve(__dirname, './components/DfAnimation.vue'), DfButton: path.resolve(__dirname, './components/button/DfButton.vue'), DfMagnifier: path.resolve( __dirname, './components/magnifier/DfMagnifier.vue', ), DfMessage: path.resolve( __dirname, './components/message/DfMessage.vue', ), DfMessageTemplate: path.resolve( __dirname, './components/message/DfMessageTemplate.vue', ), DfModal: path.resolve(__dirname, './components/modal/DfModal.vue'), DfModalTemplate: path.resolve( __dirname, './components/modal/DfModalTemplate.vue', ), DfStarsrate: path.resolve( __dirname, './components/starsRate/DfStarsrate.vue', ), DfCard: path.resolve(__dirname, './components/card/DfCard.vue'), DfSwitch: path.resolve(__dirname, './components/switch/DfSwitch.vue'), }, }, ], [ '@vuepress/container', { type: 'tip', locales: { '/': { defaultInfo: '提示', }, '/en/': { defaultInfo: 'TIP', }, }, }, { type: 'warning', locales: { '/': { defaultInfo: '警告', }, '/en/': { defaultInfo: 'Warning', }, }, }, ], ], }
the_stack
import { expect, test } from '@jest/globals'; import { typeOf } from '../src/reflection/reflection'; import { assertType, ReflectionKind, stringifyResolvedType, Type } from '../src/reflection/type'; import { serialize } from '../src/serializer-facade'; import { expectEqualType } from './utils'; test('array stack', () => { type Pop<T extends unknown[]> = T extends [...infer U, unknown] ? U : never type Push<T extends unknown[], U> = [...T, U] type Shift<T extends unknown[]> = T extends [unknown, ...infer U] ? U : never type Unshift<T extends unknown[], U> = [U, ...T] }); test('union to intersection', () => { { type UnionToIntersection<U> = (U extends any ? { k: U } : never) extends { k: infer I } ? I : never; type t1 = UnionToIntersection<{ a: string } | { b: number }>; const type = typeOf<t1>(); expect(stringifyResolvedType(type)).toBe('{a: string} | {b: number}'); // console.log('result', stringifyResolvedType(type), type); } { type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; type t1 = UnionToIntersection<{ a: string } | { b: number }>; const type = typeOf<t1>(); expect(stringifyResolvedType(type)).toBe('{a: string} & {b: number}'); // console.log('result', stringifyType(type, {showNames: false})); } }); test('StringToNum', () => { type test<A extends 0[] = []> = `${A['length']}`; expectEqualType(typeOf<test>(), { kind: ReflectionKind.literal, literal: '0', typeName: 'test' } as Type); type StringToNum<T extends string, A extends 0[] = []> = `${A['length']}` extends T ? A['length'] : StringToNum<T, [...A, 0]>; const type = typeOf<StringToNum<'100'>>(); expectEqualType(type, { kind: ReflectionKind.literal, literal: 100 } as Type as any); }); test('circular generic 1', () => { type QuerySelector<T> = { // Comparison $eq?: T; $gt?: T; $gte?: T; $in?: T[]; $lt?: T; $lte?: T; $ne?: T; $nin?: T[]; // Logical $not?: T extends string ? (QuerySelector<T> | RegExp) : QuerySelector<T>; $regex?: T extends string ? (RegExp | string) : never; //special deepkit/type type $parameter?: string; }; type RootQuerySelector<T> = { $and?: Array<FilterQuery<T>>; $nor?: Array<FilterQuery<T>>; $or?: Array<FilterQuery<T>>; }; type RegExpForString<T> = T extends string ? (RegExp | T) : T; type MongoAltQuery<T> = T extends Array<infer U> ? (T | RegExpForString<U>) : RegExpForString<T>; type Condition<T> = MongoAltQuery<T> | QuerySelector<MongoAltQuery<T>>; type FilterQuery<T> = { [P in keyof T & string]?: Condition<T[P]>; } & RootQuerySelector<T>; interface Product { id: number; title: string; } type t = FilterQuery<Product>; const type = typeOf<t>(); expect(serialize<t>({ id: 5 })).toEqual({ id: 5 }); expect(serialize<t>({ id: { $lt: 5 } })).toEqual({ id: { $lt: 5 } }); }); test('circular generic 1', () => { type QuerySelector<T> = { // Comparison $eq?: T; $gt?: T; $gte?: T; $in?: T[]; $lt?: T; $lte?: T; $ne?: T; $nin?: T[]; // Logical $not?: T extends string ? (QuerySelector<T> | RegExp) : QuerySelector<T>; $regex?: T extends string ? (RegExp | string) : never; //special deepkit/type type $parameter?: string; }; type RootQuerySelector<T> = { $and?: Array<FilterQuery<T>>; $nor?: Array<FilterQuery<T>>; $or?: Array<FilterQuery<T>>; // we could not find a proper TypeScript generic to support nested queries e.g. 'user.friends.name' // this will mark all unrecognized properties as any (including nested queries) [key: string]: any; }; type RegExpForString<T> = T extends string ? (RegExp | T) : T; type MongoAltQuery<T> = T extends Array<infer U> ? (T | RegExpForString<U>) : RegExpForString<T>; type Condition<T> = MongoAltQuery<T> | QuerySelector<MongoAltQuery<T>>; type FilterQuery<T> = { [P in keyof T & string]?: Condition<T[P]>; } & RootQuerySelector<T>; interface Product { id: number; title: string; } type t = FilterQuery<Product>; const type = typeOf<t>(); expect(serialize<t>({ id: 5 })).toEqual({ id: 5 }); expect(serialize<t>({ id: { $lt: 5 } })).toEqual({ id: { $lt: 5 } }); type t2 = FilterQuery<any>; const type2 = typeOf<t2>(); expect(serialize<t2>({ id: 5 })).toEqual({ id: 5 }); expect(serialize<t2>({ id: { $lt: 5 } })).toEqual({ id: { $lt: 5 } }); console.log('type2', type2); }); test('circular generic 3', () => { //this tests if FilterQuery<> is correctly instantiated in a circular type interface Product { id: number; title: string; } type RootQuerySelector<T> = { /** https://docs.mongodb.com/manual/reference/operator/query/and/#op._S_and */ $and?: Array<FilterQuery<T>>; $another?: Array<FilterQuery<Product>>; } type FilterQuery<T> = { [P in keyof T]?: string; } & RootQuerySelector<T>; interface User { id: number; username: string; } type t = FilterQuery<User>; const type = typeOf<t>(); assertType(type, ReflectionKind.objectLiteral); //$and assertType(type.types[2], ReflectionKind.propertySignature); assertType(type.types[2].type, ReflectionKind.array); assertType(type.types[2].type.type, ReflectionKind.objectLiteral); //$and.username assertType(type.types[2].type.type.types[1], ReflectionKind.propertySignature); expect(type.types[2].type.type.types[1].name).toBe('username'); //$another assertType(type.types[3], ReflectionKind.propertySignature); expect(type.types[3].name).toBe('$another'); assertType(type.types[3].type, ReflectionKind.array); assertType(type.types[3].type.type, ReflectionKind.objectLiteral); //$another.title assertType(type.types[3].type.type.types[1], ReflectionKind.propertySignature); expect(type.types[3].type.type.types[1].name).toBe('title'); }); test('nested template literal', () => { type t0 = `yes-${string}` | `no-${string}`; type t1 = `${number}.title:${t0}` | `${number}.size:${t0}`; type t2 = `items.${t1}`; const type = typeOf<t2>(); expect(stringifyResolvedType(type)).toBe('`items.${number}.title:yes-${string}` | `items.${number}.title:no-${string}` | `items.${number}.size:yes-${string}` | `items.${number}.size:no-${string}`'); type SubKeys<T, K extends string> = K extends keyof T ? `${K}.${Keys<T[K]>}` : never; type Keys<T> = T extends (infer A)[] ? `${number}.${Keys<A>}` : T extends object ? Extract<keyof T, string> | SubKeys<T, Extract<keyof T, string>> : never; type t10 = Keys<{ id: number, items: { title: string, size: number }[] }>; const type2 = typeOf<t10>(); expect(stringifyResolvedType(type2)).toBe('\'id\' | \'items\' | `items.${number}.title` | `items.${number}.size`'); }); test('union to intersection', () => { //functions are contra-variant type UnionToIntersection<T> = (T extends any ? (x: T) => any : never) extends (x: infer R) => any ? R : never }); test('dotted path', () => { interface Product { id: number; title: string; } interface User { id: number; username: string; products: Product[]; mainProduct: Product; } type PathKeys<T> = object extends T ? string : T extends (infer A)[] ? `${number}.${PathKeys<A>}` : T extends object ? Extract<keyof T, string> | SubKeys<T, Extract<keyof T, string>> : never; type SubKeys<T, K extends string> = K extends keyof T ? `${K}.${PathKeys<T[K]>}` : never; type t1 = PathKeys<User>; const type = typeOf<t1>(); expect(stringifyResolvedType(type)).toBe('\'id\' | \'username\' | \'products\' | \'mainProduct\' | `products.${number}.id` | `products.${number}.title` | \'mainProduct.id\' | \'mainProduct.title\''); }); test('dotted object', () => { interface Admin { firstName: string; lastName: string; } interface Product { id: number; title: string; title2: string; owner: User; } interface User { id: number; username: string; products: Product[]; mainProduct: Product; } type O<T, K extends string, Prefix extends string, Depth extends number[]> = K extends keyof T ? { [_ in `${Prefix}.${K}`]?: T[K] } | (T[K] extends object ? SubObjects<T[K], Extract<keyof T[K], string>, `${Prefix}.${K}`, [...Depth, 1]> : {}) : {}; type SubObjects<T, K extends string, Prefix extends string, Depth extends number[]> = Depth['length'] extends 10 ? {} : //bail out when too deep K extends keyof T ? T[K] extends Array<infer A> ? SubObjects<A, Extract<keyof A, string>, `${Prefix}.${K}.${number}`, [...Depth, 1]> : T[K] extends object ? O<T[K], Extract<keyof T[K], string>, Prefix extends '' ? K : `${Prefix}.${K}`, Depth> : { [P in `${Prefix}.${K}`]?: T[K] } : {}; type FilterQuery<T> = SubObjects<T, Extract<keyof T, string>, 'root', []>; // for (let i = 0; i < 100; i++) { // type t1 = FilterQuery<User>; // const start = Date.now(); // const type = typeOf<t1>(); // console.log('took', Date.now() - start); // } type t1 = FilterQuery<User>; const o: t1 = {}; const type = typeOf<t1>(); // console.log(stringifyResolvedType(type)); // expect(stringifyResolvedType(type)).toBe("'id' | 'username' | 'products' | 'mainProduct' | `products.${number}.id` | `products.${number}.title` | 'mainProduct.id' | 'mainProduct.title'") });
the_stack
import { AfterViewInit, Component, ElementRef, Inject, ViewChild, } from '@angular/core' import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog' import { DataStore, DataStoreAutoCompleter, InvalidItemError, } from '../data/data-store' import Color from 'color' import { DayID, Item, ItemDraft, ItemID, ItemStatus, REPEAT_TYPE_FACTORY_BY_TYPE, WeeklyRepeatType, } from '../data/common' import {BehaviorSubject} from 'rxjs' import {MatDatepickerInputEvent} from '@angular/material/datepicker' import { dateAddDay, dayIDToDate, parseMatDatePicker, startOfWeek, } from '../util/time-util' export interface ItemDetailsConfig { item?: Item /** * When item is present, this field is ignored. */ initialColor?: Color /** * When item is present, this field is ignored. */ initialParent?: ItemID /** * When item is present, this field is ignored. */ initialPriorityPredecessor?: ItemID /** * When item is present, this field is ignored. */ initialDueDate?: DayID } const REPEAT_TYPE_OPTIONS = [ { type: 'day', displayName: 'Day', }, { type: 'week', displayName: 'Week', }, { type: 'month', displayName: 'Month', }, { type: 'year', displayName: 'Year', }, ] const REPEAT_DAY_OF_WEEK_OPTIONS = (() => { const result: { value: number, dowDate: Date }[] = [] const start = startOfWeek(new Date()) for (let i = 0; i < 7; ++i) { result.push({value: i, dowDate: dateAddDay(start, i)}) } return result })() @Component({ selector: 'app-item-details', templateUrl: './item-details.component.html', styleUrls: ['./item-details.component.scss'], }) export class ItemDetailsComponent implements AfterViewInit { static readonly DIALOG_WIDTH = '500px' // @ts-ignore @ViewChild('nameInput') nameInput: ElementRef draft: ItemDraft isAddingNewItem = false parentAutoCompleter: DataStoreAutoCompleter originalParentItemKey?: string originalParentItemID?: ItemID private _parentItemKey: string = '' filteredParentKeys = new BehaviorSubject<string[]>([]) priorityPredecessorAutoCompleter: DataStoreAutoCompleter private _priorityPredecessorItemKey: string = '' filteredPriorityPredecessorKeys = new BehaviorSubject<string[]>([]) deferDate: Date | null = null dueDate: Date | null = null repeatEndDate: Date | null = null repeatTypeOptions = REPEAT_TYPE_OPTIONS repeatDayOfWeekOptions = REPEAT_DAY_OF_WEEK_OPTIONS cost?: number hasChildren: boolean constructor( public dialogRef: MatDialogRef<ItemDetailsComponent>, private readonly dataStore: DataStore, @Inject(MAT_DIALOG_DATA) public data: ItemDetailsConfig) { const item = data.item if (item === undefined) { this.draft = new ItemDraft() if (data.initialColor !== undefined) { this.draft.color = data.initialColor } else { this.draft.color = dataStore.generateColor() } this.draft.parentID = data.initialParent this.draft.dueDate = data.initialDueDate this.isAddingNewItem = true this.hasChildren = false } else { this.draft = item.toDraft() this.cost = item.cost === 0 ? undefined : item.cost this.isAddingNewItem = false this.hasChildren = item.childrenIDs.length > 0 } this.parentAutoCompleter = dataStore.createAutoCompleter() if (this.draft.parentID !== undefined) { this.originalParentItemID = this.draft.parentID this.originalParentItemKey = this.parentAutoCompleter.idToKey(this.draft.parentID) if (this.originalParentItemKey === undefined) { throw new Error('Parent item key not found') } this._parentItemKey = this.originalParentItemKey } // Setting up dates this.deferDate = this.draft.deferDate ? dayIDToDate(this.draft.deferDate) : null this.dueDate = this.draft.dueDate ? dayIDToDate(this.draft.dueDate) : null this.repeatEndDate = this.draft.repeatEndDate ? dayIDToDate(this.draft.repeatEndDate) : null // Setting up priority predecessor // TODO deal with things that have the same key, just like how parent is // done const queueSet = new Set(dataStore.state.queue) this.priorityPredecessorAutoCompleter = dataStore.createAutoCompleter(item => queueSet.has(item.id)) let predecessorID: ItemID | undefined = undefined if (this.isAddingNewItem) { if (data.initialPriorityPredecessor !== undefined) { this.draft.autoAdjustPriority = false predecessorID = data.initialPriorityPredecessor } } else { predecessorID = this.dataStore.getQueuePredecessor(this.draft.id) } if (predecessorID !== undefined) { this._priorityPredecessorItemKey = this.priorityPredecessorAutoCompleter.idToKey(predecessorID) || '' } else { this._priorityPredecessorItemKey = '' } } get colorString() { return this.draft.color.hex() } set colorString(value: string) { this.draft.color = Color(value) } get completed() { return this.draft.status === ItemStatus.COMPLETED } set completed(value: boolean) { this.draft.status = value ? ItemStatus.COMPLETED : ItemStatus.ACTIVE } get costString() { if (this.cost === undefined) { return '' } return this.cost.toString() } set costString(value: string) { if (value === '') { this.cost = undefined return } let v = Number(value) if (isNaN(v) || v < 0) { v = 0 } this.cost = v } get parentItemKey() { return this._parentItemKey } set parentItemKey(value: string) { this._parentItemKey = value this.filteredParentKeys.next(this.parentAutoCompleter.queryKeys(value, 10)) } get priorityPredecessorItemKey() { return this._priorityPredecessorItemKey } set priorityPredecessorItemKey(value: string) { this._priorityPredecessorItemKey = value this.filteredPriorityPredecessorKeys.next( this.priorityPredecessorAutoCompleter.queryKeys(value, 10)) } get repeatEnabled() { return this.dueDate !== null && this.draft.repeat !== undefined } set repeatEnabled(value: boolean) { if (value) { if (this.draft.repeat === undefined) { this.draft.repeat = REPEAT_TYPE_FACTORY_BY_TYPE.get(REPEAT_TYPE_OPTIONS[0].type)?.create() } } else { this.draft.repeat = undefined } } get repeatDeferOffsetEnabled() { return this.draft.repeatDeferOffset !== undefined } set repeatDeferOffsetEnabled(value: boolean) { if (value) { if (this.draft.repeatDeferOffset !== undefined) return this.draft.repeatDeferOffset = 0 } else { this.draft.repeatDeferOffset = undefined } } get repeatDeferOffsetString() { return this.draft.repeatDeferOffset === undefined ? '' : this.draft.repeatDeferOffset.toString() } set repeatDeferOffsetString(value: string) { let v = Number(value) if (isNaN(v) || v < 0) { v = 0 } this.draft.repeatDeferOffset = v } get repeatType() { const repeatType = this.draft.repeat if (repeatType === undefined) return undefined return repeatType.type } set repeatType(value: string | undefined) { if (value === undefined) { this.draft.repeat = undefined } else { if (this.draft.repeat === undefined || this.draft.repeat.type !== value) { this.draft.repeat = REPEAT_TYPE_FACTORY_BY_TYPE.get(value)?.create() } } } get repeatIntervalString() { return this.draft.repeatInterval.toString() } set repeatIntervalString(value: string) { let v = Number(value) if (isNaN(v) || v <= 0) { v = 1 } this.draft.repeatInterval = v } get repeatDayOfWeek() { return (this.draft.repeat as WeeklyRepeatType).dayOfWeek } set repeatDayOfWeek(value: number[]) { if (this.draft.repeat === undefined) return (this.draft.repeat as WeeklyRepeatType).dayOfWeek = value } close(): void { this.dialogRef.close() } ngAfterViewInit(): void { setTimeout(() => { this.nameInput?.nativeElement?.focus() this.nameInput?.nativeElement?.select() }) } save() { // Validation // TODO refactor: move this this.draft.cost = this.cost === undefined ? 0 : this.cost let parentID: ItemID | undefined = undefined if (this.parentItemKey !== '') { parentID = (this.originalParentItemKey !== undefined && this.parentItemKey === this.originalParentItemKey) ? this.originalParentItemID : this.parentAutoCompleter.keyToID(this._parentItemKey) if (parentID === undefined) { this.errorParentNotFound() return } } this.draft.parentID = parentID const priorityPredecessorID = this.priorityPredecessorAutoCompleter.keyToID( this._priorityPredecessorItemKey) const autoAdjustPriority = this.draft.autoAdjustPriority let itemID = this.draft.id // Finalize try { this.dataStore.validateItemDraft(this.draft, this.isAddingNewItem) } catch (e) { this.errorInvalidItem(e) return } this.dataStore.batchEdit(it => { if (this.isAddingNewItem) { itemID = it.addItem(this.draft) } else { it.updateItem(this.draft) } if (!autoAdjustPriority) { if (priorityPredecessorID) { it.queueMoveToAfter(itemID, priorityPredecessorID) } else { it.queueMoveToIndex(itemID, 0) } } }) this.close() } private errorParentNotFound() { alert('Error: parent not found') } private errorInvalidCost() { alert('Error: invalid cost') } private errorInvalidParent() { alert('Error: parent is invalid') } onFormKeyDown(event: KeyboardEvent) { if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') { this.save() } } private errorInvalidName() { alert('Error: invalid name') } setRandomColor() { this.draft.color = this.dataStore.generateColor() } onDeferDateChanged(event: MatDatepickerInputEvent<unknown, unknown>) { let dayID = parseMatDatePicker(event, this.dataStore.getCurrentDayID()) if (dayID === undefined) { this.clearDeferDate() } else { this.draft.deferDate = dayID this.deferDate = dayIDToDate(this.draft.deferDate) } } onDueDateChanged(event: MatDatepickerInputEvent<unknown, unknown>) { let dayID = parseMatDatePicker(event, this.dataStore.getCurrentDayID()) if (dayID === undefined) { this.clearDueDate() } else { this.draft.dueDate = dayID this.dueDate = dayIDToDate(this.draft.dueDate) } } onRepeatEndDateChanged(event: MatDatepickerInputEvent<unknown, unknown>) { let dayID = parseMatDatePicker(event, this.dataStore.getCurrentDayID()) if (dayID === undefined) { this.clearRepeatEndDate() } else { this.draft.repeatEndDate = dayID this.repeatEndDate = dayIDToDate(this.draft.repeatEndDate) } } clearDeferDate() { this.draft.deferDate = undefined this.deferDate = null } clearDueDate() { this.draft.dueDate = undefined this.dueDate = null } clearRepeatEndDate() { this.draft.repeatEndDate = undefined this.repeatEndDate = null } private errorInvalidRepeatInterval() { alert('Error: Invalid repeat interval') } private errorInvalidItem(error: any) { alert((error as InvalidItemError).message) } get shouldShowCostWarning() { return this.hasChildren } delete() { if (this.isAddingNewItem) return this.dataStore.removeItem(this.draft.id) this.close() } }
the_stack
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { AbstractClient } from "../../../common/abstract_client" import { ClientConfig } from "../../../common/interface" import { DescribeClusterPersonArrivedMallResponse, DescribeShopTrafficInfoRequest, GenderAgeTrafficDetail, DescribeZoneFlowAndStayTimeResponse, DescribePersonArrivedMallResponse, ModifyPersonTypeResponse, HourTrafficInfoDetail, DescribeZoneFlowDailyByZoneIdResponse, DescribeZoneFlowAgeInfoByZoneIdResponse, DescribeClusterPersonTraceResponse, DescribePersonInfoRequest, DescribePersonInfoByFacePictureResponse, DescribePersonTraceDetailRequest, CreateAccountRequest, NetworkLastInfo, DescribeZoneFlowGenderAvrStayTimeByZoneIdResponse, DeletePersonFeatureResponse, DescribeCameraPersonResponse, ModifyPersonTagInfoResponse, DescribeShopHourTrafficInfoResponse, RegisterCallbackResponse, NetworkInfo, DescribeClusterPersonArrivedMallRequest, DescribeZoneFlowGenderInfoByZoneIdResponse, DescribeHistoryNetworkInfoRequest, DescribePersonTraceDetailResponse, DescribePersonInfoByFacePictureRequest, DescribePersonVisitInfoRequest, DescribeZoneTrafficInfoResponse, DeletePersonFeatureRequest, DescribeFaceIdByTempIdRequest, PersonProfile, DescribePersonResponse, DescribeTrajectoryDataRequest, DescribeZoneTrafficInfoRequest, ModifyPersonFeatureInfoResponse, ZoneTrafficInfoDetail, DescribeZoneFlowGenderAvrStayTimeByZoneIdRequest, ZoneFlowAndAvrStayTime, SceneInfo, CameraPersonInfo, DescribePersonVisitInfoResponse, DescribeNetworkInfoRequest, DescribeZoneFlowAndStayTimeRequest, DescribeZoneFlowHourlyByZoneIdRequest, DescribeFaceIdByTempIdResponse, TrajectorySunData, ModifyPersonTagInfoRequest, ShopDayTrafficInfo, DescribePersonRequest, DescribePersonTraceResponse, PersonTraceRoute, PersonTracePoint, ZoneTrafficInfo, DescribeNetworkInfoResponse, NetworkAndShopInfo, DescribeZoneFlowGenderInfoByZoneIdRequest, DescribeShopHourTrafficInfoRequest, RegisterCallbackRequest, DescribeShopInfoRequest, NetworkHistoryInfo, PersonInfo, PersonTagInfo, ZoneHourFlow, ShopHourTrafficInfo, DescribeClusterPersonTraceRequest, PersonCoordinate, ModifyPersonFeatureInfoRequest, ZoneDayFlow, DescribePersonTraceRequest, DescribeZoneFlowHourlyByZoneIdResponse, DescribeZoneFlowDailyByZoneIdRequest, DescribePersonInfoResponse, DailyTracePoint, CreateAccountResponse, DescribeHistoryNetworkInfoResponse, CreateFacePictureResponse, DescribeShopInfoResponse, PersonVisitInfo, CreateFacePictureRequest, DescribeZoneFlowAgeInfoByZoneIdRequest, ShopInfo, ModifyPersonTypeRequest, ArrivedMallInfo, ZoneAgeGroupAvrStayTime, DescribePersonArrivedMallRequest, DescribeCameraPersonRequest, DescribeShopTrafficInfoResponse, DescribeTrajectoryDataResponse, } from "./youmall_models" /** * youmall client * @class */ export class Client extends AbstractClient { constructor(clientConfig: ClientConfig) { super("youmall.tencentcloudapi.com", "2018-02-28", clientConfig) } /** * 通过指定设备ID和指定时段,获取该时段内中收银台摄像设备抓取到顾客头像及身份ID */ async DescribeCameraPerson( req: DescribeCameraPersonRequest, cb?: (error: string, rep: DescribeCameraPersonResponse) => void ): Promise<DescribeCameraPersonResponse> { return this.request("DescribeCameraPerson", req, cb) } /** * 指定门店获取所有顾客详情列表,包含客户ID、图片、年龄、性别 */ async DescribePersonInfo( req: DescribePersonInfoRequest, cb?: (error: string, rep: DescribePersonInfoResponse) => void ): Promise<DescribePersonInfoResponse> { return this.request("DescribePersonInfo", req, cb) } /** * 按天提供查询日期范围内,客户指定门店下的所有区域(优Mall部署时已配置区域)的累计客流人次和平均停留时间。支持的时间范围:过去365天,含当天。 */ async DescribeZoneTrafficInfo( req: DescribeZoneTrafficInfoRequest, cb?: (error: string, rep: DescribeZoneTrafficInfoResponse) => void ): Promise<DescribeZoneTrafficInfoResponse> { return this.request("DescribeZoneTrafficInfo", req, cb) } /** * 获取指定区域人流各年龄占比 */ async DescribeZoneFlowAgeInfoByZoneId( req: DescribeZoneFlowAgeInfoByZoneIdRequest, cb?: (error: string, rep: DescribeZoneFlowAgeInfoByZoneIdResponse) => void ): Promise<DescribeZoneFlowAgeInfoByZoneIdResponse> { return this.request("DescribeZoneFlowAgeInfoByZoneId", req, cb) } /** * 调用本接口在优Mall中注册自己集团的到店通知回调接口地址,接口协议为HTTP或HTTPS。注册后,若集团有特殊身份(例如老客)到店通知,优Mall后台将主动将到店信息push给该接口 */ async RegisterCallback( req: RegisterCallbackRequest, cb?: (error: string, rep: RegisterCallbackResponse) => void ): Promise<RegisterCallbackResponse> { return this.request("RegisterCallback", req, cb) } /** * 获取指定区域不同年龄段男女平均停留时间 */ async DescribeZoneFlowGenderAvrStayTimeByZoneId( req: DescribeZoneFlowGenderAvrStayTimeByZoneIdRequest, cb?: (error: string, rep: DescribeZoneFlowGenderAvrStayTimeByZoneIdResponse) => void ): Promise<DescribeZoneFlowGenderAvrStayTimeByZoneIdResponse> { return this.request("DescribeZoneFlowGenderAvrStayTimeByZoneId", req, cb) } /** * 获取区域人流和停留时间 */ async DescribeZoneFlowAndStayTime( req: DescribeZoneFlowAndStayTimeRequest, cb?: (error: string, rep: DescribeZoneFlowAndStayTimeResponse) => void ): Promise<DescribeZoneFlowAndStayTimeResponse> { return this.request("DescribeZoneFlowAndStayTime", req, cb) } /** * 获取门店指定时间范围内的所有用户到访信息记录,支持的时间范围:过去365天,含当天。 */ async DescribePersonVisitInfo( req: DescribePersonVisitInfoRequest, cb?: (error: string, rep: DescribePersonVisitInfoResponse) => void ): Promise<DescribePersonVisitInfoResponse> { return this.request("DescribePersonVisitInfo", req, cb) } /** * 获取指定区域分时客流量 */ async DescribeZoneFlowHourlyByZoneId( req: DescribeZoneFlowHourlyByZoneIdRequest, cb?: (error: string, rep: DescribeZoneFlowHourlyByZoneIdResponse) => void ): Promise<DescribeZoneFlowHourlyByZoneIdResponse> { return this.request("DescribeZoneFlowHourlyByZoneId", req, cb) } /** * 根据客户身份标识获取客户下所有的门店信息列表 */ async DescribeShopInfo( req: DescribeShopInfoRequest, cb?: (error: string, rep: DescribeShopInfoResponse) => void ): Promise<DescribeShopInfoResponse> { return this.request("DescribeShopInfo", req, cb) } /** * 通过DescribeCameraPerson接口上报的收银台身份ID查询顾客的FaceID。查询最佳时间为收银台上报的次日1点后。 */ async DescribeFaceIdByTempId( req: DescribeFaceIdByTempIdRequest, cb?: (error: string, rep: DescribeFaceIdByTempIdResponse) => void ): Promise<DescribeFaceIdByTempIdResponse> { return this.request("DescribeFaceIdByTempId", req, cb) } /** * 获取指定区域性别占比 */ async DescribeZoneFlowGenderInfoByZoneId( req: DescribeZoneFlowGenderInfoByZoneIdRequest, cb?: (error: string, rep: DescribeZoneFlowGenderInfoByZoneIdResponse) => void ): Promise<DescribeZoneFlowGenderInfoByZoneIdResponse> { return this.request("DescribeZoneFlowGenderInfoByZoneId", req, cb) } /** * 按天提供查询日期范围内门店的单日累计客流人数,支持的时间范围:过去365天,含当天。 */ async DescribeShopTrafficInfo( req: DescribeShopTrafficInfoRequest, cb?: (error: string, rep: DescribeShopTrafficInfoResponse) => void ): Promise<DescribeShopTrafficInfoResponse> { return this.request("DescribeShopTrafficInfo", req, cb) } /** * 通过上传人脸图片检索系统face id、顾客身份信息及底图 */ async DescribePersonInfoByFacePicture( req: DescribePersonInfoByFacePictureRequest, cb?: (error: string, rep: DescribePersonInfoByFacePictureResponse) => void ): Promise<DescribePersonInfoByFacePictureResponse> { return this.request("DescribePersonInfoByFacePicture", req, cb) } /** * 通过上传指定规格的人脸图片,创建黑名单用户或者白名单用户。 */ async CreateFacePicture( req: CreateFacePictureRequest, cb?: (error: string, rep: CreateFacePictureResponse) => void ): Promise<CreateFacePictureResponse> { return this.request("CreateFacePicture", req, cb) } /** * 创建集团门店管理员账号 */ async CreateAccount( req: CreateAccountRequest, cb?: (error: string, rep: CreateAccountResponse) => void ): Promise<CreateAccountResponse> { return this.request("CreateAccount", req, cb) } /** * 按小时提供查询日期范围内门店的每天每小时累计客流人数数据,支持的时间范围:过去365天,含当天。 */ async DescribeShopHourTrafficInfo( req: DescribeShopHourTrafficInfoRequest, cb?: (error: string, rep: DescribeShopHourTrafficInfoResponse) => void ): Promise<DescribeShopHourTrafficInfoResponse> { return this.request("DescribeShopHourTrafficInfo", req, cb) } /** * 输出开始时间到结束时间段内的进出场数据。 */ async DescribePersonTrace( req: DescribePersonTraceRequest, cb?: (error: string, rep: DescribePersonTraceResponse) => void ): Promise<DescribePersonTraceResponse> { return this.request("DescribePersonTrace", req, cb) } /** * 获取指定区域每日客流量 */ async DescribeZoneFlowDailyByZoneId( req: DescribeZoneFlowDailyByZoneIdRequest, cb?: (error: string, rep: DescribeZoneFlowDailyByZoneIdResponse) => void ): Promise<DescribeZoneFlowDailyByZoneIdResponse> { return this.request("DescribeZoneFlowDailyByZoneId", req, cb) } /** * 输出开始时间到结束时间段内的进出场数据。不做按天聚合的情况下,每次进出场,产生一条进出场数据。 */ async DescribePersonArrivedMall( req: DescribePersonArrivedMallRequest, cb?: (error: string, rep: DescribePersonArrivedMallResponse) => void ): Promise<DescribePersonArrivedMallResponse> { return this.request("DescribePersonArrivedMall", req, cb) } /** * 输出开始时间到结束时间段内的进出场数据。按天聚合的情况下,每天多次进出场算一次,以最初进场时间为进场时间,最后离场时间为离场时间。停留时间为多次进出场的停留时间之和。 */ async DescribeClusterPersonArrivedMall( req: DescribeClusterPersonArrivedMallRequest, cb?: (error: string, rep: DescribeClusterPersonArrivedMallResponse) => void ): Promise<DescribeClusterPersonArrivedMallResponse> { return this.request("DescribeClusterPersonArrivedMall", req, cb) } /** * 查询客户单次到场轨迹明细 */ async DescribePersonTraceDetail( req: DescribePersonTraceDetailRequest, cb?: (error: string, rep: DescribePersonTraceDetailResponse) => void ): Promise<DescribePersonTraceDetailResponse> { return this.request("DescribePersonTraceDetail", req, cb) } /** * 修改顾客身份类型接口 */ async ModifyPersonType( req: ModifyPersonTypeRequest, cb?: (error: string, rep: ModifyPersonTypeResponse) => void ): Promise<ModifyPersonTypeResponse> { return this.request("ModifyPersonType", req, cb) } /** * 支持修改黑白名单类型的顾客特征 */ async ModifyPersonFeatureInfo( req: ModifyPersonFeatureInfoRequest, cb?: (error: string, rep: ModifyPersonFeatureInfoResponse) => void ): Promise<ModifyPersonFeatureInfoResponse> { return this.request("ModifyPersonFeatureInfo", req, cb) } /** * 返回当前门店历史网络状态数据 */ async DescribeHistoryNetworkInfo( req: DescribeHistoryNetworkInfoRequest, cb?: (error: string, rep: DescribeHistoryNetworkInfoResponse) => void ): Promise<DescribeHistoryNetworkInfoResponse> { return this.request("DescribeHistoryNetworkInfo", req, cb) } /** * 返回当前门店最新网络状态数据 */ async DescribeNetworkInfo( req: DescribeNetworkInfoRequest, cb?: (error: string, rep: DescribeNetworkInfoResponse) => void ): Promise<DescribeNetworkInfoResponse> { return this.request("DescribeNetworkInfo", req, cb) } /** * 删除顾客特征,仅支持删除黑名单或者白名单用户特征。 */ async DeletePersonFeature( req: DeletePersonFeatureRequest, cb?: (error: string, rep: DeletePersonFeatureResponse) => void ): Promise<DeletePersonFeatureResponse> { return this.request("DeletePersonFeature", req, cb) } /** * 标记到店顾客的身份类型,例如黑名单、白名单等 */ async ModifyPersonTagInfo( req: ModifyPersonTagInfoRequest, cb?: (error: string, rep: ModifyPersonTagInfoResponse) => void ): Promise<ModifyPersonTagInfoResponse> { return this.request("ModifyPersonTagInfo", req, cb) } /** * 查询指定某一卖场的用户信息 */ async DescribePerson( req: DescribePersonRequest, cb?: (error: string, rep: DescribePersonResponse) => void ): Promise<DescribePersonResponse> { return this.request("DescribePerson", req, cb) } /** * 输出开始时间到结束时间段内的进出场数据。按天聚合的情况下,每天多次进出场算一次,以最初进场时间为进场时间,最后离场时间为离场时间。 */ async DescribeClusterPersonTrace( req: DescribeClusterPersonTraceRequest, cb?: (error: string, rep: DescribeClusterPersonTraceResponse) => void ): Promise<DescribeClusterPersonTraceResponse> { return this.request("DescribeClusterPersonTrace", req, cb) } /** * 获取动线轨迹信息 */ async DescribeTrajectoryData( req: DescribeTrajectoryDataRequest, cb?: (error: string, rep: DescribeTrajectoryDataResponse) => void ): Promise<DescribeTrajectoryDataResponse> { return this.request("DescribeTrajectoryData", req, cb) } }
the_stack
import { addSeconds } from 'date-fns'; import mongoose from 'mongoose'; import { PageActionStage, PageActionType } from '../../../src/server/models/page-operation'; import { getInstance } from '../setup-crowi'; describe('Test page service methods', () => { let crowi; let Page; let Revision; let User; let UserGroup; let UserGroupRelation; let Tag; let PageTagRelation; let Bookmark; let Comment; let ShareLink; let PageRedirect; let PageOperation; let xssSpy; let rootPage; let dummyUser1; let dummyUser2; let globalGroupUser1; let globalGroupUser2; let globalGroupUser3; let globalGroupIsolate; let globalGroupA; let globalGroupB; let globalGroupC; let pageOpId1; let pageOpId2; let pageOpId3; let pageOpId4; let pageOpId5; let pageOpId6; beforeAll(async() => { crowi = await getInstance(); await crowi.configManager.updateConfigsInTheSameNamespace('crowi', { 'app:isV5Compatible': true }); User = mongoose.model('User'); UserGroup = mongoose.model('UserGroup'); UserGroupRelation = mongoose.model('UserGroupRelation'); Page = mongoose.model('Page'); Revision = mongoose.model('Revision'); Tag = mongoose.model('Tag'); PageTagRelation = mongoose.model('PageTagRelation'); Bookmark = mongoose.model('Bookmark'); Comment = mongoose.model('Comment'); ShareLink = mongoose.model('ShareLink'); PageRedirect = mongoose.model('PageRedirect'); UserGroup = mongoose.model('UserGroup'); UserGroupRelation = mongoose.model('UserGroupRelation'); PageOperation = mongoose.model('PageOperation'); /* * Common */ xssSpy = jest.spyOn(crowi.xss, 'process').mockImplementation(path => path); // *********************************************************************************************************** // * Do NOT change properties of globally used documents. Otherwise, it might cause some errors in other tests // *********************************************************************************************************** // users dummyUser1 = await User.findOne({ username: 'v5DummyUser1' }); dummyUser2 = await User.findOne({ username: 'v5DummyUser2' }); globalGroupUser1 = await User.findOne({ username: 'gGroupUser1' }); globalGroupUser2 = await User.findOne({ username: 'gGroupUser2' }); globalGroupUser3 = await User.findOne({ username: 'gGroupUser3' }); // groups globalGroupIsolate = await UserGroup.findOne({ name: 'globalGroupIsolate' }); globalGroupA = await UserGroup.findOne({ name: 'globalGroupA' }); globalGroupB = await UserGroup.findOne({ name: 'globalGroupB' }); globalGroupC = await UserGroup.findOne({ name: 'globalGroupC' }); // page rootPage = await Page.findOne({ path: '/' }); /** * pages */ const pageId0 = new mongoose.Types.ObjectId(); const pageId1 = new mongoose.Types.ObjectId(); const pageId2 = new mongoose.Types.ObjectId(); const pageId3 = new mongoose.Types.ObjectId(); const pageId4 = new mongoose.Types.ObjectId(); const pageId5 = new mongoose.Types.ObjectId(); const pageId6 = new mongoose.Types.ObjectId(); const pageId7 = new mongoose.Types.ObjectId(); const pageId8 = new mongoose.Types.ObjectId(); const pageId9 = new mongoose.Types.ObjectId(); const pageId10 = new mongoose.Types.ObjectId(); const pageId11 = new mongoose.Types.ObjectId(); const pageId12 = new mongoose.Types.ObjectId(); const pageId13 = new mongoose.Types.ObjectId(); const pageId14 = new mongoose.Types.ObjectId(); const pageId15 = new mongoose.Types.ObjectId(); const pageId16 = new mongoose.Types.ObjectId(); const pageId17 = new mongoose.Types.ObjectId(); await Page.insertMany([ { _id: pageId0, path: '/resume_rename_0', parent: rootPage._id, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 1, isEmpty: false, }, { _id: pageId1, path: '/resume_rename_0/resume_rename_1', parent: pageId0, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 2, isEmpty: false, }, { _id: pageId2, path: '/resume_rename_1/resume_rename_2', parent: pageId1, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 1, isEmpty: false, }, { _id: pageId3, path: '/resume_rename_1/resume_rename_2/resume_rename_3', parent: pageId2, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 0, isEmpty: false, }, { _id: pageId4, path: '/resume_rename_4', parent: rootPage._id, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 0, isEmpty: false, }, { _id: pageId5, path: '/resume_rename_4/resume_rename_5', parent: pageId0, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 1, isEmpty: false, }, { _id: pageId6, path: '/resume_rename_5/resume_rename_6', parent: pageId5, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 0, isEmpty: false, }, { _id: pageId7, path: '/resume_rename_7', parent: rootPage._id, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 0, isEmpty: false, }, { _id: pageId8, path: '/resume_rename_8', parent: rootPage._id, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 1, isEmpty: false, }, { _id: pageId9, path: '/resume_rename_8/resume_rename_9', parent: pageId8, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 1, isEmpty: false, }, { path: '/resume_rename_9/resume_rename_10', parent: pageId9, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 0, isEmpty: false, }, { _id: pageId10, path: '/resume_rename_11', parent: rootPage._id, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 3, isEmpty: false, }, { _id: pageId11, path: '/resume_rename_11/resume_rename_12', parent: pageId10, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 2, isEmpty: false, }, { _id: pageId12, path: '/resume_rename_11/resume_rename_12/resume_rename_13', parent: pageId11, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 1, isEmpty: false, }, { path: '/resume_rename_11/resume_rename_12/resume_rename_13/resume_rename_14', parent: pageId12, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 0, isEmpty: false, }, { _id: pageId13, path: '/resume_rename_15', parent: rootPage._id, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 2, isEmpty: false, }, { _id: pageId14, path: '/resume_rename_15/resume_rename_16', parent: pageId13, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 0, isEmpty: false, }, { _id: pageId15, path: '/resume_rename_15/resume_rename_17', parent: pageId13, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 1, isEmpty: false, }, { _id: pageId16, path: '/resume_rename_15/resume_rename_17/resume_rename_18', parent: pageId15, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 1, isEmpty: false, }, { _id: pageId17, path: '/resume_rename_15/resume_rename_17/resume_rename_18/resume_rename_19', parent: pageId16, grant: Page.GRANT_PUBLIC, creator: dummyUser1, lastUpdateUser: dummyUser1._id, descendantCount: 0, isEmpty: false, }, ]); /** * PageOperation */ pageOpId1 = new mongoose.Types.ObjectId(); pageOpId2 = new mongoose.Types.ObjectId(); pageOpId3 = new mongoose.Types.ObjectId(); pageOpId4 = new mongoose.Types.ObjectId(); pageOpId5 = new mongoose.Types.ObjectId(); pageOpId6 = new mongoose.Types.ObjectId(); const pageOpRevisionId1 = new mongoose.Types.ObjectId(); const pageOpRevisionId2 = new mongoose.Types.ObjectId(); const pageOpRevisionId3 = new mongoose.Types.ObjectId(); const pageOpRevisionId4 = new mongoose.Types.ObjectId(); const pageOpRevisionId5 = new mongoose.Types.ObjectId(); const pageOpRevisionId6 = new mongoose.Types.ObjectId(); await PageOperation.insertMany([ { _id: pageOpId1, actionType: 'Rename', actionStage: 'Sub', fromPath: '/resume_rename_1', toPath: '/resume_rename_0/resume_rename_1', page: { _id: pageId1, parent: rootPage._id, descendantCount: 2, isEmpty: false, path: '/resume_rename_1', revision: pageOpRevisionId1, status: 'published', grant: 1, grantedUsers: [], grantedGroup: null, creator: dummyUser1._id, lastUpdateUser: dummyUser1._id, }, user: { _id: dummyUser1._id, }, options: { createRedirectPage: false, updateMetadata: true, }, unprocessableExpiryDate: null, }, { _id: pageOpId2, actionType: 'Rename', actionStage: 'Sub', fromPath: '/resume_rename_5', toPath: '/resume_rename_4/resume_rename_5', page: { _id: pageId5, parent: rootPage._id, descendantCount: 2, isEmpty: false, path: '/resume_rename_5', revision: pageOpRevisionId2, status: 'published', grant: 1, grantedUsers: [], grantedGroup: null, creator: dummyUser1._id, lastUpdateUser: dummyUser1._id, }, user: { _id: dummyUser1._id, }, options: { createRedirectPage: false, updateMetadata: true, }, unprocessableExpiryDate: new Date(), }, { _id: pageOpId3, actionType: 'Rename', actionStage: 'Sub', fromPath: '/resume_rename_7', // toPath NOT exist page: { _id: pageId7, parent: rootPage._id, descendantCount: 2, isEmpty: false, path: '/resume_rename_7', revision: pageOpRevisionId3, status: 'published', grant: 1, grantedUsers: [], grantedGroup: null, creator: dummyUser1._id, lastUpdateUser: dummyUser1._id, }, user: { _id: dummyUser1._id, }, options: { createRedirectPage: false, updateMetadata: true, }, unprocessableExpiryDate: new Date(), }, { _id: pageOpId4, actionType: 'Rename', actionStage: 'Sub', fromPath: '/resume_rename_9', toPath: '/resume_rename_8/resume_rename_9', page: { _id: pageId9, parent: rootPage._id, descendantCount: 1, isEmpty: false, path: '/resume_rename_9', revision: pageOpRevisionId4, status: 'published', grant: Page.GRANT_PUBLIC, grantedUsers: [], grantedGroup: null, creator: dummyUser1._id, lastUpdateUser: dummyUser1._id, }, user: { _id: dummyUser1._id, }, options: { createRedirectPage: false, updateMetadata: true, }, unprocessableExpiryDate: null, }, { _id: pageOpId5, actionType: 'Rename', actionStage: 'Sub', fromPath: '/resume_rename_11/resume_rename_13', toPath: '/resume_rename_11/resume_rename_12/resume_rename_13', page: { _id: pageId12, parent: pageId10, descendantCount: 1, isEmpty: false, path: '/resume_rename_11/resume_rename_13', revision: pageOpRevisionId5, status: 'published', grant: Page.GRANT_PUBLIC, grantedUsers: [], grantedGroup: null, creator: dummyUser1._id, lastUpdateUser: dummyUser1._id, }, user: { _id: dummyUser1._id, }, options: { createRedirectPage: false, updateMetadata: true, }, unprocessableExpiryDate: new Date(), }, { _id: pageOpId6, actionType: 'Rename', actionStage: 'Sub', fromPath: '/resume_rename_15/resume_rename_16/resume_rename_18', toPath: '/resume_rename_15/resume_rename_17/resume_rename_18', page: { _id: pageId16, parent: pageId14, descendantCount: 1, isEmpty: false, path: '/resume_rename_15/resume_rename_16/resume_rename_18', revision: pageOpRevisionId6, status: 'published', grant: Page.GRANT_PUBLIC, grantedUsers: [], grantedGroup: null, creator: dummyUser1._id, lastUpdateUser: dummyUser1._id, }, user: { _id: dummyUser1._id, }, options: { createRedirectPage: false, updateMetadata: true, }, unprocessableExpiryDate: new Date(), }, ]); }); describe('restart renameOperation', () => { const resumeRenameSubOperation = async(page) => { const mockedRenameSubOperation = jest.spyOn(crowi.pageService, 'renameSubOperation').mockReturnValue(null); await crowi.pageService.resumeRenameSubOperation(page); const argsForRenameSubOperation = mockedRenameSubOperation.mock.calls[0]; mockedRenameSubOperation.mockRestore(); await crowi.pageService.renameSubOperation(...argsForRenameSubOperation); }; test('it should successfully restart rename operation', async() => { // paths before renaming const _path0 = '/resume_rename_0'; // out of renaming scope const _path1 = '/resume_rename_0/resume_rename_1'; // renamed already const _path2 = '/resume_rename_1/resume_rename_2'; // not renamed yet const _path3 = '/resume_rename_1/resume_rename_2/resume_rename_3'; // not renamed yet // paths after renaming const path0 = '/resume_rename_0'; const path1 = '/resume_rename_0/resume_rename_1'; const path2 = '/resume_rename_0/resume_rename_1/resume_rename_2'; const path3 = '/resume_rename_0/resume_rename_1/resume_rename_2/resume_rename_3'; // page const _page0 = await Page.findOne({ path: _path0 }); const _page1 = await Page.findOne({ path: _path1 }); const _page2 = await Page.findOne({ path: _path2 }); const _page3 = await Page.findOne({ path: _path3 }); expect(_page0).toBeTruthy(); expect(_page1).toBeTruthy(); expect(_page2).toBeTruthy(); expect(_page3).toBeTruthy(); expect(_page0.descendantCount).toBe(1); expect(_page1.descendantCount).toBe(2); expect(_page2.descendantCount).toBe(1); expect(_page3.descendantCount).toBe(0); // page operation const fromPath = '/resume_rename_1'; const toPath = '/resume_rename_0/resume_rename_1'; const _pageOperation = await PageOperation.findOne({ _id: pageOpId1, fromPath, toPath, 'page._id': _page1._id, actionType: PageActionType.Rename, actionStage: PageActionStage.Sub, }); expect(_pageOperation).toBeTruthy(); // rename await resumeRenameSubOperation(_page1); // page const page0 = await Page.findById(_page0._id); const page1 = await Page.findById(_page1._id); const page2 = await Page.findById(_page2._id); const page3 = await Page.findById(_page3._id); expect(page0).toBeTruthy(); expect(page1).toBeTruthy(); expect(page2).toBeTruthy(); expect(page3).toBeTruthy(); // check paths after renaming expect(page0.path).toBe(path0); expect(page1.path).toBe(path1); expect(page2.path).toBe(path2); expect(page3.path).toBe(path3); // page operation const pageOperation = await PageOperation.findById(_pageOperation._id); expect(pageOperation).toBeNull(); // should not exist expect(page0.descendantCount).toBe(3); expect(page1.descendantCount).toBe(2); expect(page2.descendantCount).toBe(1); expect(page3.descendantCount).toBe(0); }); test('it should successfully restart rename operation when unprocessableExpiryDate is null', async() => { // paths before renaming const _path0 = '/resume_rename_8'; // out of renaming scope const _path1 = '/resume_rename_8/resume_rename_9'; // renamed already const _path2 = '/resume_rename_9/resume_rename_10'; // not renamed yet // paths after renaming const path0 = '/resume_rename_8'; const path1 = '/resume_rename_8/resume_rename_9'; const path2 = '/resume_rename_8/resume_rename_9/resume_rename_10'; // page const _page0 = await Page.findOne({ path: _path0 }); const _page1 = await Page.findOne({ path: _path1 }); const _page2 = await Page.findOne({ path: _path2 }); expect(_page0).toBeTruthy(); expect(_page1).toBeTruthy(); expect(_page2).toBeTruthy(); expect(_page0.descendantCount).toBe(1); expect(_page1.descendantCount).toBe(1); expect(_page2.descendantCount).toBe(0); // page operation const fromPath = '/resume_rename_9'; const toPath = '/resume_rename_8/resume_rename_9'; const _pageOperation = await PageOperation.findOne({ _id: pageOpId4, fromPath, toPath, 'page._id': _page1._id, actionType: PageActionType.Rename, actionStage: PageActionStage.Sub, }); expect(_pageOperation).toBeTruthy(); // rename await resumeRenameSubOperation(_page1); // page const page0 = await Page.findById(_page0._id); const page1 = await Page.findById(_page1._id); const page2 = await Page.findById(_page2._id); expect(page0).toBeTruthy(); expect(page1).toBeTruthy(); expect(page2).toBeTruthy(); // check paths after renaming expect(page0.path).toBe(path0); expect(page1.path).toBe(path1); expect(page2.path).toBe(path2); // page operation const pageOperation = await PageOperation.findById(_pageOperation._id); expect(pageOperation).toBeNull(); // should not exist // others expect(page1.parent).toStrictEqual(page0._id); expect(page2.parent).toStrictEqual(page1._id); expect(page0.descendantCount).toBe(2); expect(page1.descendantCount).toBe(1); expect(page2.descendantCount).toBe(0); }); test('it should fail and throw error if PageOperation is not found', async() => { // create dummy page operation data not stored in DB const notExistPageOp = { _id: new mongoose.Types.ObjectId(), actionType: 'Rename', actionStage: 'Sub', fromPath: '/FROM_NOT_EXIST', toPath: 'TO_NOT_EXIST', page: { _id: new mongoose.Types.ObjectId(), parent: rootPage._id, descendantCount: 2, isEmpty: false, path: '/NOT_EXIST_PAGE', revision: new mongoose.Types.ObjectId(), status: 'published', grant: 1, grantedUsers: [], grantedGroup: null, creator: dummyUser1._id, lastUpdateUser: dummyUser1._id, }, user: { _id: dummyUser1._id, }, options: { createRedirectPage: false, updateMetadata: false, }, unprocessableExpiryDate: new Date(), }; await expect(resumeRenameSubOperation(notExistPageOp)) .rejects.toThrow(new Error('There is nothing to be processed right now')); }); test('it should fail and throw error if the current time is behind unprocessableExpiryDate', async() => { // path before renaming const _path0 = '/resume_rename_4'; // out of renaming scope const _path1 = '/resume_rename_4/resume_rename_5'; // renamed already const _path2 = '/resume_rename_5/resume_rename_6'; // not renamed yet // page const _page0 = await Page.findOne({ path: _path0 }); const _page1 = await Page.findOne({ path: _path1 }); const _page2 = await Page.findOne({ path: _path2 }); expect(_page0).toBeTruthy(); expect(_page1).toBeTruthy(); expect(_page2).toBeTruthy(); // page operation const fromPath = '/resume_rename_5'; const toPath = '/resume_rename_4/resume_rename_5'; const pageOperation = await PageOperation.findOne({ _id: pageOpId2, fromPath, toPath, 'page._id': _page1._id, actionType: PageActionType.Rename, actionStage: PageActionStage.Sub, }); expect(pageOperation).toBeTruthy(); // Make `unprocessableExpiryDate` 15 seconds ahead of current time. // The number 15 seconds has no meaning other than placing time in the furue. await PageOperation.findByIdAndUpdate(pageOperation._id, { unprocessableExpiryDate: addSeconds(new Date(), 15) }); await expect(resumeRenameSubOperation(_page1)).rejects.toThrow(new Error('This page operation is currently being processed')); // cleanup await PageOperation.findByIdAndDelete(pageOperation._id); }); test('Missing property(toPath) for PageOperation should throw error', async() => { // page const _path1 = '/resume_rename_7'; const _page1 = await Page.findOne({ path: _path1 }); expect(_page1).toBeTruthy(); // page operation const pageOperation = await PageOperation.findOne({ _id: pageOpId3, 'page._id': _page1._id, actionType: PageActionType.Rename, actionStage: PageActionStage.Sub, }); expect(pageOperation).toBeTruthy(); const promise = resumeRenameSubOperation(_page1); await expect(promise).rejects.toThrow(new Error(`Property toPath is missing which is needed to resume page operation(${pageOperation._id})`)); // cleanup await PageOperation.findByIdAndDelete(pageOperation._id); }); test(`it should succeed but 2 extra descendantCount should be added if the page operation was interrupted right after increasing ancestor's descendantCount in renameSubOperation`, async() => { // paths before renaming const _path0 = '/resume_rename_11'; // out of renaming scope const _path1 = '/resume_rename_11/resume_rename_12'; // out of renaming scope const _path2 = '/resume_rename_11/resume_rename_12/resume_rename_13'; // renamed already const _path3 = '/resume_rename_11/resume_rename_12/resume_rename_13/resume_rename_14'; // renamed already // paths after renaming const path0 = '/resume_rename_11'; const path1 = '/resume_rename_11/resume_rename_12'; const path2 = '/resume_rename_11/resume_rename_12/resume_rename_13'; const path3 = '/resume_rename_11/resume_rename_12/resume_rename_13/resume_rename_14'; // page const _page0 = await Page.findOne({ path: _path0 }); const _page1 = await Page.findOne({ path: _path1 }); const _page2 = await Page.findOne({ path: _path2 }); const _page3 = await Page.findOne({ path: _path3 }); expect(_page0).toBeTruthy(); expect(_page1).toBeTruthy(); expect(_page2).toBeTruthy(); expect(_page3).toBeTruthy(); // descendantCount expect(_page0.descendantCount).toBe(3); expect(_page1.descendantCount).toBe(2); expect(_page2.descendantCount).toBe(1); expect(_page3.descendantCount).toBe(0); // page operation const fromPath = '/resume_rename_11/resume_rename_13'; const toPath = '/resume_rename_11/resume_rename_12/resume_rename_13'; const _pageOperation = await PageOperation.findOne({ _id: pageOpId5, fromPath, toPath, 'page._id': _page2._id, actionType: PageActionType.Rename, actionStage: PageActionStage.Sub, }); expect(_pageOperation).toBeTruthy(); // rename await resumeRenameSubOperation(_page2); // page const page0 = await Page.findById(_page0._id); const page1 = await Page.findById(_page1._id); const page2 = await Page.findById(_page2._id); const page3 = await Page.findById(_page3._id); expect(page0).toBeTruthy(); expect(page1).toBeTruthy(); expect(page2).toBeTruthy(); expect(page3).toBeTruthy(); expect(page0.path).toBe(path0); expect(page1.path).toBe(path1); expect(page2.path).toBe(path2); expect(page3.path).toBe(path3); // page operation const pageOperation = await PageOperation.findById(_pageOperation._id); expect(pageOperation).toBeNull(); // should not exist // 2 extra descendants should be added to page1 expect(page0.descendantCount).toBe(3); expect(page1.descendantCount).toBe(3); // originally 2, +1 in Main, -1 in Sub, +2 for new descendants expect(page2.descendantCount).toBe(1); expect(page3.descendantCount).toBe(0); }); test(`it should succeed but 2 extra descendantCount should be subtracted from ex parent page if the page operation was interrupted right after reducing ancestor's descendantCount in renameSubOperation`, async() => { // paths before renaming const _path0 = '/resume_rename_15'; // out of renaming scope const _path1 = '/resume_rename_15/resume_rename_16'; // out of renaming scope const _path2 = '/resume_rename_15/resume_rename_17'; // out of renaming scope const _path3 = '/resume_rename_15/resume_rename_17/resume_rename_18'; // renamed already const _path4 = '/resume_rename_15/resume_rename_17/resume_rename_18/resume_rename_19'; // renamed already // paths after renaming const path0 = '/resume_rename_15'; const path1 = '/resume_rename_15/resume_rename_16'; const path2 = '/resume_rename_15/resume_rename_17'; const path3 = '/resume_rename_15/resume_rename_17/resume_rename_18'; const path4 = '/resume_rename_15/resume_rename_17/resume_rename_18/resume_rename_19'; // page const _page0 = await Page.findOne({ path: _path0 }); const _page1 = await Page.findOne({ path: _path1 }); const _page2 = await Page.findOne({ path: _path2 }); const _page3 = await Page.findOne({ path: _path3 }); const _page4 = await Page.findOne({ path: _path4 }); expect(_page0).toBeTruthy(); expect(_page1).toBeTruthy(); expect(_page2).toBeTruthy(); expect(_page3).toBeTruthy(); expect(_page4).toBeTruthy(); // descendantCount expect(_page0.descendantCount).toBe(2); expect(_page1.descendantCount).toBe(0); expect(_page2.descendantCount).toBe(1); expect(_page3.descendantCount).toBe(1); expect(_page4.descendantCount).toBe(0); // page operation const fromPath = '/resume_rename_15/resume_rename_16/resume_rename_18'; const toPath = '/resume_rename_15/resume_rename_17/resume_rename_18'; const _pageOperation = await PageOperation.findOne({ _id: pageOpId6, fromPath, toPath, 'page._id': _page3._id, actionType: PageActionType.Rename, actionStage: PageActionStage.Sub, }); expect(_pageOperation).toBeTruthy(); // rename await resumeRenameSubOperation(_page3); // page const page0 = await Page.findById(_page0._id); const page1 = await Page.findById(_page1._id); const page2 = await Page.findById(_page2._id); const page3 = await Page.findById(_page3._id); const page4 = await Page.findById(_page4._id); expect(page0).toBeTruthy(); expect(page1).toBeTruthy(); expect(page2).toBeTruthy(); expect(page3).toBeTruthy(); expect(page3).toBeTruthy(); expect(page0.path).toBe(path0); expect(page1.path).toBe(path1); expect(page2.path).toBe(path2); expect(page3.path).toBe(path3); expect(page4.path).toBe(path4); // page operation const pageOperation = await PageOperation.findById(_pageOperation._id); expect(pageOperation).toBeNull(); // should not exist // 2 extra descendants should be subtracted from page1 expect(page0.descendantCount).toBe(2); expect(page1.descendantCount).toBe(-2); // originally 0, -2 for old descendants expect(page2.descendantCount).toBe(2); // originally 1, -1 in Sub, +2 for new descendants expect(page3.descendantCount).toBe(1); expect(page4.descendantCount).toBe(0); }); }); });
the_stack
import * as store from '../store'; // TODO: refactor for Redux Hooks import * as actions from './../features/business/businessSlice'; import * as uiactions from './../features/ui/uiSlice'; import graphQLController from './graphQLController'; import { ReqRes, WindowAPI, WindowExt } from '../../types'; const { api }: { api: WindowAPI} = window as unknown as WindowExt; const connectionController = { openConnectionArray: [] as number[] | number[], // toggles checked in state for entire reqResArray toggleSelectAll(): void { const { reqResArray }: { reqResArray: ReqRes[] } = store.default.getState().business; if (reqResArray.every((obj: ReqRes): boolean => obj.checked === true)) { reqResArray.forEach((obj: ReqRes): boolean => obj.checked = false); } else { reqResArray.forEach((obj: ReqRes): boolean => obj.checked = true); } store.default.dispatch(actions.setChecksAndMinis(reqResArray)); }, // listens for reqResUpdate event from main process telling it to update reqResObj REST EVENTS openReqRes(id: number): void { // remove all previous listeners for 'reqResUpdate' before starting to listen for 'reqResUpdate' again api.removeAllListeners('reqResUpdate'); api.receive('reqResUpdate', (reqResObj: ReqRes) => { if ( (reqResObj.connection === 'closed' || reqResObj.connection === 'error') && reqResObj.timeSent && reqResObj.timeReceived && reqResObj.response.events.length > 0 ) { store.default.dispatch(actions.updateGraph(reqResObj)); } store.default.dispatch(actions.reqResUpdate(reqResObj)); // If current selected response equals reqResObj received, update current response const currentID = store.default.getState().business.currentResponse.id; if (currentID === reqResObj.id) { store.default.dispatch( actions.saveCurrentResponseData(reqResObj, 'currentID===reqResObj.id') ); } }); // Since only obj ID is passed in, next two lines get the current array of request objects and finds the one with matching ID const reqResArr: ReqRes[] = store.default.getState().business.reqResArray; const reqResObj: ReqRes = reqResArr.find((el: ReqRes) => el.id === id); // console.log('this is the reqResArr!!!!!!!', reqResArr); //console.log('this is the openConnectionArray!!!!!!!', this.openConnectionArray); if (reqResObj.request.method === 'SUBSCRIPTION') graphQLController.openSubscription(reqResObj); else if (reqResObj.graphQL) { graphQLController.openGraphQLConnection(reqResObj); } else if (/wss?:\/\//.test(reqResObj.protocol) && !reqResObj.webRtc) { // create context bridge to wsController in node process to open connection, send the reqResObj and connection array api.send('open-ws', reqResObj, this.openConnectionArray); // pretty sure this is not needed anymore... -Prince // update the connectionArray when connection is open from ws // api.receive('update-connectionArray', (connectionArray: any) => { // // @ts-expect-error ts-migrate(2345) FIXME: Argument of type 'any' is not assignable to parame... Remove this comment to see the full error message // this.openConnectionArray.push(...connectionArray); // }); } // gRPC connection else if (reqResObj.gRPC) { api.send('open-grpc', reqResObj); // Standard HTTP? } else if (reqResObj.openapi) { console.log('got an open api request to fill'); //console.log(reqResObj); } else { api.send('open-http', reqResObj, this.openConnectionArray); } }, openScheduledReqRes(id: string | number): void { // listens for reqResUpdate event from main process telling it to update reqResObj // REST EVENTS api.removeAllListeners('reqResUpdate'); api.receive('reqResUpdate', (reqResObj: ReqRes) => { if ( (reqResObj.connection === 'closed' || reqResObj.connection === 'error') && reqResObj.timeSent && reqResObj.timeReceived && reqResObj.response.events.length > 0 ) { store.default.dispatch(actions.updateGraph(reqResObj)); } store.default.dispatch(actions.scheduledReqResUpdate(reqResObj)); }); // Since only obj ID is passed in, next two lines get the current array of request objects and finds the one with matching ID const reqResArr: ReqRes[] = store.default.getState().business.reqResArray; const reqResObj: ReqRes = reqResArr.find((el: ReqRes) => el.id === id); if (reqResObj.request.method === 'SUBSCRIPTION') graphQLController.openSubscription(reqResObj); else if (reqResObj.graphQL) { graphQLController.openGraphQLConnection(reqResObj); } else if (/wss?:\/\//.test(reqResObj.protocol)) { // create context bridge to wsController in node process to open connection, send the reqResObj and connection array api.send('open-ws', reqResObj, this.openConnectionArray); // pretty sure that this is not needed... -Prince // update the connectionArray when connection is open from ws // api.receive('update-connectionArray', (connectionArray: any) => { // // @ts-expect-error ts-migrate(2345) FIXME: Argument of type 'any' is not assignable to parame... Remove this comment to see the full error message // this.openConnectionArray.push(...connectionArray); // }); } // gRPC connection else if (reqResObj.gRPC) { api.send('open-grpc', reqResObj); // Standard HTTP? } else { api.send('open-http', reqResObj, this.openConnectionArray); } }, runCollectionTest(reqResArray: ReqRes[]): void { api.removeAllListeners('reqResUpdate'); let index = 0; api.receive('reqResUpdate', (reqResObj: ReqRes) => { if ( (reqResObj.connection === 'closed' || reqResObj.connection === 'error') && reqResObj.timeSent && reqResObj.timeReceived && reqResObj.response.events.length > 0 ) { store.default.dispatch(actions.updateGraph(reqResObj)); } store.default.dispatch(actions.reqResUpdate(reqResObj)); store.default.dispatch( actions.saveCurrentResponseData(reqResObj, 'api.receive reqresupdate') ); if (index < reqResArray.length) { runSingletest(reqResArray[index]); index += 1; } }); const reqResObj = reqResArray[index]; function runSingletest(reqResObj: ReqRes) { if (reqResObj.request.method === 'SUBSCRIPTION') graphQLController.openSubscription(reqResObj); else if (reqResObj.graphQL) { graphQLController.openGraphQLConnectionAndRunCollection(reqResArray); } else if (/wss?:\/\//.test(reqResObj.protocol)) { // create context bridge to wsController in node process to open connection, send the reqResObj and connection array api.send('open-ws', reqResObj); // update the connectionArray when connection is open from ws api.receive('update-connectionArray', (connectionArray: number[]) => { // is this the correct type??? connectionController.openConnectionArray.push(...connectionArray); }); } // gRPC connection else if (reqResObj.gRPC) { api.send('open-grpc', reqResObj); // Standard HTTP? } else { api.send('open-http', reqResObj); } } runSingletest(reqResObj); index += 1; }, openAllSelectedReqRes(): void { connectionController.closeAllReqRes(); const { reqResArray }: { reqResArray: ReqRes[] } = store.default.getState().business; reqResArray.forEach((reqRes: ReqRes) => connectionController.openReqRes(reqRes.id)); }, // We are pretty sure that this is not used anymore... -Prince // getConnectionObject(id: number): any { // // @ts-expect-error ts-migrate(2339) FIXME: Property 'id' does not exist on type 'never'. // console.log('getConnectionObject has been invoked'); // return this.openConnectionArray.find((obj) => (obj.id = id)); // }, setReqResConnectionToClosed(id: number): void { const reqResArr = store.default.getState().business.reqResArray; const foundReqRes: ReqRes = JSON.parse( JSON.stringify(reqResArr.find((reqRes: ReqRes) => reqRes.id === id)) ); foundReqRes.connection = 'closed'; store.default.dispatch(actions.reqResUpdate(foundReqRes)); store.default.dispatch( actions.saveCurrentResponseData( foundReqRes, 'foundreqres.connection closed' ) ); }, closeReqRes(reqResObj: ReqRes): void { if (reqResObj.protocol.includes('http')) { api.send('close-http', reqResObj); } const { id } = reqResObj; this.setReqResConnectionToClosed(id); // We are pretty sure that this code block is never executed... -Prince // // WS is the only protocol using openConnectionArray // const foundAbortController = this.openConnectionArray.find( // // @ts-expect-error ts-migrate(2339) FIXME: Property 'id' does not exist on type 'never'. // (obj) => obj.id === id // ); // // @ts-expect-error ts-migrate(2339) FIXME: Property 'protocol' does not exist on type 'never'... Remove this comment to see the full error message // if (foundAbortController && foundAbortController.protocol === 'WS') { // console.log('you dummy, you thought you didnt need this'); // api.send('close-ws'); // } // this.openConnectionArray = this.openConnectionArray.filter( // // @ts-expect-error ts-migrate(2339) FIXME: Property 'id' does not exist on type 'never'. // (obj) => obj.id !== id // ); }, /* Closes all open endpoint */ closeAllReqRes(): void { const { reqResArray }: { reqResArray: ReqRes[] } = store.default.getState().business; reqResArray.forEach((reqRes: ReqRes) => connectionController.closeReqRes(reqRes)); }, clearAllReqRes(): void { connectionController.closeAllReqRes(); store.default.dispatch(actions.reqResClear()); }, // toggles minimized in ReqRes array in state toggleMinimizeAll(): void { const { reqResArray }: { reqResArray: ReqRes[] } = store.default.getState().business; if (reqResArray.every((obj: ReqRes) => obj.minimized === true)) { reqResArray.forEach((obj: ReqRes) => obj.minimized = false); } else { reqResArray.forEach((obj: ReqRes) => obj.minimized = true); } store.default.dispatch(actions.setChecksAndMinis(reqResArray)); }, // clears a dataPoint from state clearGraph(): void { store.default.dispatch(actions.clearGraph()); }, // clears ALL data points from state clearAllGraph(): void { store.default.dispatch(actions.clearAllGraph()); }, }; export default connectionController;
the_stack
import * as assert from 'assert'; import { basename } from 'path'; import { Uri } from 'vscode'; import { isLinux } from '../../../env/node/platform'; import { normalizeRepoUri } from '../../../repositories'; import { PathEntryTrie, UriEntry, UriEntryTrie, UriTrie } from '../../../system/trie'; // eslint-disable-next-line import/extensions import paths from './paths.json'; describe('PathEntryTrie Test Suite', () => { type Repo = { type: 'repo'; name: string; path: string; fsPath: string }; type File = { type: 'file'; name: string; path: string }; const repoGL: Repo = { type: 'repo', name: 'vscode-gitlens', path: 'c:/Users/Name/code/gitkraken/vscode-gitlens', fsPath: 'C:\\Users\\Name\\code\\gitkraken\\vscode-gitlens', }; const repoNested: Repo = { type: 'repo', name: 'repo', path: 'c:/Users/Name/code/gitkraken/vscode-gitlens/nested/repo', fsPath: 'C:\\Users\\Name\\code\\gitkraken\\vscode-gitlens\\nested\\repo', }; const repoVSC: Repo = { type: 'repo', name: 'vscode', path: 'c:/Users/Name/code/microsoft/vscode', fsPath: 'C:\\Users\\Name\\code\\microsoft\\vscode', }; const trie = new PathEntryTrie<Repo | File>(); before(() => { trie.set(repoGL.fsPath, repoGL); trie.set(repoNested.fsPath, repoNested); trie.set(repoVSC.fsPath, repoVSC); let file: File = { type: 'file', name: 'index.ts', path: `${repoNested.fsPath}\\src\\index.ts` }; trie.set(file.path, file); file = { type: 'file', name: 'main.ts', path: `${repoVSC.fsPath}\\src\\main.ts` }; trie.set(file.path, file); for (const path of paths) { file = { type: 'file', name: basename(path), path: `C:\\Users\\Name\\code${path}` }; trie.set(file.path, file); } }); it('has: repo', () => { assert.strictEqual(trie.has(repoGL.fsPath), true); assert.strictEqual(trie.has(repoNested.fsPath), true); assert.strictEqual(trie.has(repoVSC.fsPath), true); assert.strictEqual(trie.has('C:\\Users\\Name\\code\\company\\repo'), false); assert.strictEqual(trie.has('D:\\Users\\Name\\code\\gitkraken\\vscode-gitlens'), false); }); it('has: repo (ignore case)', () => { assert.strictEqual(trie.has(repoGL.fsPath.toUpperCase()), true); assert.strictEqual(trie.has(repoNested.fsPath.toUpperCase()), true); assert.strictEqual(trie.has(repoVSC.fsPath.toUpperCase()), true); }); it('has: file', () => { assert.strictEqual(trie.has(`${repoGL.fsPath}\\src\\extension.ts`), true); assert.strictEqual(trie.has(`${repoGL.fsPath}\\foo\\bar\\baz.ts`), false); assert.strictEqual(trie.has(`${repoNested.fsPath}\\src\\index.ts`), true); assert.strictEqual(trie.has(`${repoVSC.fsPath}\\src\\main.ts`), true); }); it('has: file (ignore case)', () => { assert.strictEqual(trie.has(`${repoGL.fsPath}\\src\\extension.ts`.toUpperCase()), true); assert.strictEqual(trie.has(`${repoGL.fsPath}\\foo\\bar\\baz.ts`.toUpperCase()), false); assert.strictEqual(trie.has(`${repoNested.fsPath}\\src\\index.ts`.toUpperCase()), true); assert.strictEqual(trie.has(`${repoVSC.fsPath}\\src\\main.ts`.toUpperCase()), true); }); it('has: folder (failure case)', () => { assert.strictEqual(trie.has(`${repoGL.fsPath}\\src`), false); assert.strictEqual(trie.has(`${repoNested.fsPath}\\src`), false); assert.strictEqual(trie.has(`${repoVSC.fsPath}\\src`), false); }); it('get: repo', () => { let entry = trie.get(repoGL.fsPath); assert.strictEqual(entry?.path, basename(repoGL.path)); assert.strictEqual(entry?.fullPath, repoGL.path); assert.strictEqual(entry?.value?.type, 'repo'); assert.strictEqual(entry?.value?.path, repoGL.path); entry = trie.get(repoNested.fsPath); assert.strictEqual(entry?.path, basename(repoNested.path)); assert.strictEqual(entry?.fullPath, repoNested.path); assert.strictEqual(entry?.value?.type, 'repo'); assert.strictEqual(entry?.value?.path, repoNested.path); entry = trie.get(repoVSC.fsPath); assert.strictEqual(entry?.path, basename(repoVSC.path)); assert.strictEqual(entry?.fullPath, repoVSC.path); assert.strictEqual(entry?.value?.type, 'repo'); assert.strictEqual(entry?.value?.path, repoVSC.path); assert.strictEqual(trie.get('C:\\Users\\Name\\code\\company\\repo'), undefined); assert.strictEqual(trie.get('D:\\Users\\Name\\code\\gitkraken\\vscode-gitlens'), undefined); }); it('get: repo (ignore case)', () => { let entry = trie.get(repoGL.fsPath.toUpperCase()); assert.strictEqual(entry?.path, basename(repoGL.path)); assert.strictEqual(entry?.fullPath, repoGL.path); assert.strictEqual(entry?.value?.type, 'repo'); assert.strictEqual(entry?.value?.path, repoGL.path); entry = trie.get(repoNested.fsPath.toUpperCase()); assert.strictEqual(entry?.path, basename(repoNested.path)); assert.strictEqual(entry?.fullPath, repoNested.path); assert.strictEqual(entry?.value?.type, 'repo'); assert.strictEqual(entry?.value?.path, repoNested.path); entry = trie.get(repoVSC.fsPath.toUpperCase()); assert.strictEqual(entry?.path, basename(repoVSC.path)); assert.strictEqual(entry?.fullPath, repoVSC.path); assert.strictEqual(entry?.value?.type, 'repo'); assert.strictEqual(entry?.value?.path, repoVSC.path); }); it('get: file', () => { let entry = trie.get(`${repoGL.fsPath}\\src\\extension.ts`); assert.strictEqual(entry?.path, 'extension.ts'); assert.strictEqual(entry?.fullPath, `${repoGL.path}/src/extension.ts`); assert.strictEqual(entry?.value?.path, `${repoGL.fsPath}\\src\\extension.ts`); assert.strictEqual(trie.get(`${repoGL.fsPath}\\foo\\bar\\baz.ts`), undefined); entry = trie.get(`${repoNested.fsPath}\\src\\index.ts`); assert.strictEqual(entry?.path, 'index.ts'); assert.strictEqual(entry?.fullPath, `${repoNested.path}/src/index.ts`); assert.strictEqual(entry?.value?.path, `${repoNested.fsPath}\\src\\index.ts`); entry = trie.get(`${repoVSC.fsPath}\\src\\main.ts`); assert.strictEqual(entry?.path, 'main.ts'); assert.strictEqual(entry?.fullPath, `${repoVSC.path}/src/main.ts`); assert.strictEqual(entry?.value?.path, `${repoVSC.fsPath}\\src\\main.ts`); }); it('get: file (ignore case)', () => { let entry = trie.get(`${repoGL.fsPath}\\src\\extension.ts`.toLocaleUpperCase()); assert.strictEqual(entry?.path, 'extension.ts'); assert.strictEqual(entry?.fullPath, `${repoGL.path}/src/extension.ts`); assert.strictEqual(entry?.value?.path, `${repoGL.fsPath}\\src\\extension.ts`); entry = trie.get(`${repoNested.fsPath}\\src\\index.ts`.toLocaleUpperCase()); assert.strictEqual(entry?.path, 'index.ts'); assert.strictEqual(entry?.fullPath, `${repoNested.path}/src/index.ts`); assert.strictEqual(entry?.value?.path, `${repoNested.fsPath}\\src\\index.ts`); entry = trie.get(`${repoVSC.fsPath}\\src\\main.ts`.toLocaleUpperCase()); assert.strictEqual(entry?.path, 'main.ts'); assert.strictEqual(entry?.fullPath, `${repoVSC.path}/src/main.ts`); assert.strictEqual(entry?.value?.path, `${repoVSC.fsPath}\\src\\main.ts`); }); it('get: folder (failure case)', () => { assert.strictEqual(trie.get(`${repoGL.fsPath}\\src`), undefined); assert.strictEqual(trie.get(`${repoNested.fsPath}\\src`), undefined); assert.strictEqual(trie.get(`${repoVSC.fsPath}\\src`), undefined); }); it('getClosest: repo file', () => { let entry = trie.getClosest(`${repoGL.fsPath}\\src\\extension.ts`, true); assert.strictEqual(entry?.path, repoGL.name); assert.strictEqual(entry?.fullPath, repoGL.path); assert.strictEqual(entry?.value?.path, repoGL.path); entry = trie.getClosest(`${repoNested.fsPath}\\src\\index.ts`, true); assert.strictEqual(entry?.path, repoNested.name); assert.strictEqual(entry?.fullPath, repoNested.path); assert.strictEqual(entry?.value?.path, repoNested.path); entry = trie.getClosest(`${repoVSC.fsPath}\\src\\main.ts`, true); assert.strictEqual(entry?.path, repoVSC.name); assert.strictEqual(entry?.fullPath, repoVSC.path); assert.strictEqual(entry?.value?.path, repoVSC.path); }); it('getClosest: repo file (ignore case)', () => { let entry = trie.getClosest(`${repoGL.fsPath}\\src\\extension.ts`.toUpperCase(), true); assert.strictEqual(entry?.path, repoGL.name); assert.strictEqual(entry?.fullPath, repoGL.path); assert.strictEqual(entry?.value?.path, repoGL.path); entry = trie.getClosest(`${repoNested.fsPath}\\src\\index.ts`.toUpperCase(), true); assert.strictEqual(entry?.path, repoNested.name); assert.strictEqual(entry?.fullPath, repoNested.path); assert.strictEqual(entry?.value?.path, repoNested.path); entry = trie.getClosest(`${repoVSC.fsPath}\\src\\main.ts`.toUpperCase(), true); assert.strictEqual(entry?.path, repoVSC.name); assert.strictEqual(entry?.fullPath, repoVSC.path); assert.strictEqual(entry?.value?.path, repoVSC.path); }); it('getClosest: missing path but inside repo', () => { let entry = trie.getClosest(`${repoGL.fsPath}\\src\\foo\\bar\\baz.ts`.toUpperCase()); assert.strictEqual(entry?.path, repoGL.name); assert.strictEqual(entry?.fullPath, repoGL.path); assert.strictEqual(entry?.value?.path, repoGL.path); entry = trie.getClosest(`${repoNested.fsPath}\\foo\\bar\\baz.ts`.toUpperCase()); assert.strictEqual(entry?.path, repoNested.name); assert.strictEqual(entry?.fullPath, repoNested.path); assert.strictEqual(entry?.value?.path, repoNested.path); entry = trie.getClosest(`${repoVSC.fsPath}\\src\\foo\\bar\\baz.ts`.toUpperCase()); assert.strictEqual(entry?.path, repoVSC.name); assert.strictEqual(entry?.fullPath, repoVSC.path); assert.strictEqual(entry?.value?.path, repoVSC.path); }); it('getClosest: missing path', () => { const entry = trie.getClosest('C:\\Users\\Name\\code\\company\\repo\\foo\\bar\\baz.ts'); assert.strictEqual(entry, undefined); }); it('getClosest: repo', () => { let entry = trie.getClosest(repoGL.fsPath); assert.strictEqual(entry?.path, repoGL.name); assert.strictEqual(entry?.fullPath, repoGL.path); assert.strictEqual(entry?.value?.path, repoGL.path); entry = trie.getClosest(repoNested.fsPath); assert.strictEqual(entry?.path, repoNested.name); assert.strictEqual(entry?.fullPath, repoNested.path); assert.strictEqual(entry?.value?.path, repoNested.path); entry = trie.getClosest(repoVSC.fsPath); assert.strictEqual(entry?.path, repoVSC.name); assert.strictEqual(entry?.fullPath, repoVSC.path); assert.strictEqual(entry?.value?.path, repoVSC.path); }); it('delete file', () => { const file = `${repoVSC.fsPath}\\src\\main.ts`; assert.strictEqual(trie.has(file), true); assert.strictEqual(trie.delete(file), true); assert.strictEqual(trie.has(file), false); }); it('delete repo', () => { const repo = repoGL.fsPath; assert.strictEqual(trie.has(repo), true); assert.strictEqual(trie.delete(repo), true); assert.strictEqual(trie.has(repo), false); assert.strictEqual(trie.has(repoNested.fsPath), true); }); it('delete missing', () => { const file = `${repoGL.fsPath}\\src\\foo\\bar\\baz.ts`; assert.strictEqual(trie.has(file), false); assert.strictEqual(trie.delete(file), false); assert.strictEqual(trie.has(file), false); }); it('clear', () => { assert.strictEqual(trie.has(repoVSC.fsPath), true); trie.clear(); assert.strictEqual(trie.has(repoGL.fsPath), false); assert.strictEqual(trie.has(repoNested.fsPath), false); assert.strictEqual(trie.has(repoVSC.fsPath), false); assert.strictEqual(trie.get(repoGL.fsPath), undefined); assert.strictEqual(trie.get(repoNested.fsPath), undefined); assert.strictEqual(trie.get(repoVSC.fsPath), undefined); assert.strictEqual(trie.getClosest(repoGL.fsPath), undefined); assert.strictEqual(trie.getClosest(repoNested.fsPath), undefined); assert.strictEqual(trie.getClosest(repoVSC.fsPath), undefined); }); }); describe('UriEntryTrie Test Suite', () => { type Repo = { type: 'repo'; name: string; uri: Uri; fsPath: string }; type File = { type: 'file'; name: string; uri: Uri }; const repoGL: Repo = { type: 'repo', name: 'vscode-gitlens', uri: Uri.file('c:/Users/Name/code/gitkraken/vscode-gitlens'), fsPath: 'c:/Users/Name/code/gitkraken/vscode-gitlens', }; const repoNested: Repo = { type: 'repo', name: 'repo', uri: Uri.file('c:/Users/Name/code/gitkraken/vscode-gitlens/nested/repo'), fsPath: 'c:/Users/Name/code/gitkraken/vscode-gitlens/nested/repo', }; const repoGLvfs: Repo = { type: 'repo', name: 'vscode-gitlens', uri: Uri.parse('vscode-vfs://github/gitkraken/vscode-gitlens'), fsPath: 'github/gitkraken/vscode-gitlens', }; const repoVSCvfs: Repo = { type: 'repo', name: 'vscode', uri: Uri.parse('vscode-vfs://github/microsoft/vscode'), fsPath: 'github/microsoft/vscode', }; const trie = new UriEntryTrie<Repo | File>(); function assertRepoEntry(actual: UriEntry<Repo | File> | undefined, expected: Repo): void { assert.strictEqual(actual?.path, expected.name); assert.strictEqual(actual?.fullPath, expected.fsPath); assert.strictEqual(actual?.value?.type, 'repo'); assert.strictEqual(actual?.value?.uri.toString(), expected.uri.toString()); } function assertRepoEntryIgnoreCase(actual: UriEntry<Repo | File> | undefined, expected: Repo): void { if (isLinux) { assert.strictEqual(actual, undefined); } else { assert.strictEqual(actual?.path, expected.name); assert.strictEqual(actual?.fullPath, expected.fsPath); assert.strictEqual(actual?.value?.type, 'repo'); assert.strictEqual(actual?.value?.uri.toString(), expected.uri.toString()); } } function assertFileEntry(actual: UriEntry<Repo | File> | undefined, expected: Uri): void { assert.strictEqual(actual?.path, basename(expected.path)); if (expected.scheme === 'file' || expected.scheme === 'git' || expected.scheme === 'gitlens') { assert.strictEqual(actual?.fullPath, expected.path.slice(1)); } else { assert.strictEqual(actual?.fullPath, `${expected.authority}${expected.path}`); } assert.strictEqual(actual?.value?.type, 'file'); assert.strictEqual(actual?.value?.uri.toString(), expected.toString()); } before(() => { trie.set(repoGL.uri, repoGL); trie.set(repoNested.uri, repoNested); trie.set(repoGLvfs.uri, repoGLvfs); trie.set(repoVSCvfs.uri, repoVSCvfs); let file: File = { type: 'file', name: 'index.ts', uri: Uri.joinPath(repoNested.uri, 'src\\index.ts') }; trie.set(file.uri, file); file = { type: 'file', name: 'main.ts', uri: Uri.joinPath(repoVSCvfs.uri, 'src/main.ts') }; trie.set(file.uri, file); for (const path of paths) { file = { type: 'file', name: basename(path), uri: Uri.file(`C:\\Users\\Name\\code${path}`) }; trie.set(file.uri, file); file = { type: 'file', name: basename(path), uri: repoGLvfs.uri.with({ path: path.replace(/\\/g, '/') }) }; trie.set(file.uri, file); } }); it('has(file://): repo', () => { assert.strictEqual(trie.has(repoGL.uri), true); assert.strictEqual(trie.has(repoGL.uri.with({ path: repoGL.uri.path.toUpperCase() })), !isLinux); assert.strictEqual(trie.has(repoNested.uri), true); assert.strictEqual(trie.has(repoNested.uri.with({ path: repoGL.uri.path.toUpperCase() })), !isLinux); assert.strictEqual(trie.has(Uri.file('C:\\Users\\Name\\code\\company\\repo')), false); assert.strictEqual(trie.has(Uri.file('D:\\Users\\Name\\code\\gitkraken\\vscode-gitlens')), false); }); it('has(file://): file', () => { assert.strictEqual(trie.has(Uri.file(`${repoGL.fsPath}/src/extension.ts`)), true); assert.strictEqual(trie.has(Uri.file(`${repoGL.fsPath}/foo/bar/baz.ts`)), false); assert.strictEqual(trie.has(Uri.file(`${repoNested.fsPath}/src/index.ts`)), true); }); it('has(vscode-vfs://): repo', () => { assert.strictEqual(trie.has(repoGLvfs.uri), true); assert.strictEqual(trie.has(repoGLvfs.uri.with({ path: repoGLvfs.uri.path.toUpperCase() })), false); assert.strictEqual(trie.has(repoVSCvfs.uri), true); assert.strictEqual(trie.has(repoVSCvfs.uri.with({ path: repoVSCvfs.uri.path.toUpperCase() })), false); assert.strictEqual(trie.has(Uri.parse('vscode-vfs://github/company/repo')), false); assert.strictEqual(trie.has(repoGLvfs.uri.with({ authority: 'azdo' })), false); }); it('has(vscode-vfs://): file', () => { assert.strictEqual(trie.has(Uri.joinPath(repoGLvfs.uri, 'src/extension.ts')), true); assert.strictEqual(trie.has(Uri.joinPath(repoGLvfs.uri, 'foo/bar/baz.ts')), false); assert.strictEqual(trie.has(Uri.joinPath(repoVSCvfs.uri, 'src/main.ts')), true); assert.strictEqual(trie.has(Uri.parse('vscode-vfs://github/company/repo/foo/bar/baz.ts')), false); assert.strictEqual( trie.has( repoGLvfs.uri.with({ authority: 'azdo', path: Uri.joinPath(repoGLvfs.uri, 'src/extension.ts').path }), ), false, ); }); it('has(github://): repo', () => { assert.strictEqual(trie.has(repoGLvfs.uri.with({ scheme: 'github' })), true); assert.strictEqual( trie.has(repoGLvfs.uri.with({ scheme: 'github', path: repoGLvfs.uri.path.toUpperCase() })), false, ); assert.strictEqual(trie.has(repoVSCvfs.uri.with({ scheme: 'github' })), true); assert.strictEqual( trie.has(repoVSCvfs.uri.with({ scheme: 'github', path: repoVSCvfs.uri.path.toUpperCase() })), false, ); assert.strictEqual(trie.has(Uri.parse('github://github/company/repo')), false); assert.strictEqual(trie.has(repoGLvfs.uri.with({ scheme: 'github', authority: 'azdo' })), false); }); it('has(github://): file', () => { assert.strictEqual(trie.has(Uri.joinPath(repoGLvfs.uri, 'src/extension.ts').with({ scheme: 'github' })), true); assert.strictEqual(trie.has(Uri.joinPath(repoGLvfs.uri, 'foo/bar/baz.ts').with({ scheme: 'github' })), false); assert.strictEqual(trie.has(Uri.joinPath(repoVSCvfs.uri, 'src/main.ts').with({ scheme: 'github' })), true); assert.strictEqual( trie.has(Uri.parse('vscode-vfs://github/company/repo/foo/bar/baz.ts').with({ scheme: 'github' })), false, ); assert.strictEqual( trie.has( repoGLvfs.uri.with({ scheme: 'github', authority: 'azdo', path: Uri.joinPath(repoGLvfs.uri, 'src/extension.ts').path, }), ), false, ); }); // it('has(gitlens://): repo', () => { // assert.strictEqual( // trie.has( // repoGL.uri.with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }), // ), // true, // ); // assert.strictEqual( // trie.has( // Uri.parse( // repoGL.uri // .with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }) // .toString() // .toUpperCase(), // ), // ), // !isLinux, // ); // assert.strictEqual( // trie.has( // repoNested.uri.with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }), // ), // true, // ); // assert.strictEqual( // trie.has( // Uri.parse( // repoNested.uri // .with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }) // .toString() // .toUpperCase(), // ), // ), // !isLinux, // ); // assert.strictEqual( // trie.has( // Uri.file('C:\\Users\\Name\\code\\company\\repo').with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }), // ), // false, // ); // }); // it('has(gitlens://): file', () => { // assert.strictEqual( // trie.has( // Uri.joinPath(repoGL.uri, 'src/extension.ts').with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }), // ), // true, // ); // assert.strictEqual( // trie.has( // Uri.joinPath(repoGL.uri, 'foo/bar/baz.ts').with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }), // ), // false, // ); // assert.strictEqual( // trie.has( // Uri.joinPath(repoNested.uri, 'src/index.ts').with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }), // ), // true, // ); // }); it('get(file://): repo', () => { assertRepoEntry(trie.get(repoGL.uri), repoGL); assertRepoEntry(trie.get(repoNested.uri), repoNested); assert.strictEqual(trie.get(Uri.file('C:\\Users\\Name\\code\\company\\repo')), undefined); assert.strictEqual(trie.get(Uri.file('D:\\Users\\Name\\code\\gitkraken\\vscode-gitlens')), undefined); }); it('get(vscode-vfs://): repo', () => { assertRepoEntry(trie.get(repoGLvfs.uri), repoGLvfs); assertRepoEntry(trie.get(repoVSCvfs.uri), repoVSCvfs); assert.strictEqual(trie.get(Uri.file('C:\\Users\\Name\\code\\company\\repo')), undefined); assert.strictEqual(trie.get(Uri.file('D:\\Users\\Name\\code\\gitkraken\\vscode-gitlens')), undefined); }); it('get(github://): repo', () => { assertRepoEntry(trie.get(repoGLvfs.uri.with({ scheme: 'github' })), repoGLvfs); assertRepoEntry(trie.get(repoVSCvfs.uri.with({ scheme: 'github' })), repoVSCvfs); }); // it('get(gitlens://): repo', () => { // assertRepoEntry( // trie.get( // repoGL.uri.with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }), // ), // repoGL, // ); // assertRepoEntry( // trie.get( // repoNested.uri.with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }), // ), // repoNested, // ); // }); it('get(file://): repo (ignore case)', () => { assertRepoEntryIgnoreCase(trie.get(repoGL.uri.with({ path: repoGL.uri.path.toUpperCase() })), repoGL); assertRepoEntryIgnoreCase( trie.get(repoNested.uri.with({ path: repoNested.uri.path.toUpperCase() })), repoNested, ); }); it('get(vscode://): repo (ignore case)', () => { assertRepoEntry(trie.get(repoGLvfs.uri.with({ scheme: 'VSCODE-VFS' })), repoGLvfs); assert.strictEqual( trie.get(repoGLvfs.uri.with({ authority: repoGLvfs.uri.authority.toUpperCase() })), undefined, ); assert.strictEqual(trie.get(repoGLvfs.uri.with({ path: repoGLvfs.uri.path.toUpperCase() })), undefined); }); it('get(github://): repo (ignore case)', () => { assertRepoEntry(trie.get(repoGLvfs.uri.with({ scheme: 'GITHUB' })), repoGLvfs); assert.strictEqual( trie.get(repoGLvfs.uri.with({ scheme: 'github', authority: repoGLvfs.uri.authority.toUpperCase() })), undefined, ); assert.strictEqual( trie.get(repoGLvfs.uri.with({ scheme: 'github', path: repoGLvfs.uri.path.toUpperCase() })), undefined, ); }); // it('get(gitlens://): repo (ignore case)', () => { // assertRepoEntry( // trie.get( // repoGL.uri.with({ // scheme: 'GITLENS', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }), // ), // repoGL, // ); // assertRepoEntryIgnoreCase( // trie.get( // Uri.parse( // repoGL.uri // .with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }) // .toString() // .toUpperCase(), // ), // ), // repoGL, // ); // }); it('get(file://): file', () => { let uri = Uri.joinPath(repoGL.uri, 'src/extension.ts'); assertFileEntry(trie.get(uri), uri); assert.strictEqual(trie.get(Uri.joinPath(repoGL.uri, 'foo/bar/baz.ts')), undefined); uri = Uri.joinPath(repoNested.uri, 'src/index.ts'); assertFileEntry(trie.get(uri), uri); }); it('get(vscode-vfs://): file', () => { const uri = Uri.joinPath(repoGLvfs.uri, 'src/extension.ts'); assertFileEntry(trie.get(uri), uri); }); it('get(github://): file', () => { const uri = Uri.joinPath(repoGLvfs.uri, 'src/extension.ts'); assertFileEntry(trie.get(uri.with({ scheme: 'github' })), uri); }); // it('get(gitlens://): file', () => { // const uri = Uri.joinPath(repoGL.uri, 'src/extension.ts'); // assertFileEntry( // trie.get( // uri.with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }), // ), // uri, // ); // }); it('get: missing file', () => { assert.strictEqual(trie.get(Uri.joinPath(repoGL.uri, 'foo/bar/baz.ts')), undefined); }); it('getClosest(file://): repo', () => { assertRepoEntry(trie.getClosest(repoGL.uri), repoGL); assertRepoEntry(trie.getClosest(repoNested.uri), repoNested); }); it('getClosest(vscode-vfs://): repo', () => { assertRepoEntry(trie.getClosest(repoGLvfs.uri), repoGLvfs); assertRepoEntry(trie.getClosest(repoVSCvfs.uri), repoVSCvfs); }); it('getClosest(file://): file', () => { assertRepoEntry(trie.getClosest(Uri.joinPath(repoGL.uri, 'src/extension.ts'), true), repoGL); }); it('getClosest(vscode-vfs://): file', () => { assertRepoEntry(trie.getClosest(Uri.joinPath(repoGLvfs.uri, 'src/extension.ts'), true), repoGLvfs); }); it('getClosest(github://): file', () => { assertRepoEntry( trie.getClosest(Uri.joinPath(repoGLvfs.uri, 'src/extension.ts').with({ scheme: 'github' }), true), repoGLvfs, ); }); // it('getClosest(gitlens://): file', () => { // assertRepoEntry( // trie.getClosest( // Uri.joinPath(repoGL.uri, 'src/extension.ts').with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }), // true, // ), // repoGL, // ); // }); it('getClosest(file://): missing repo file', () => { assertRepoEntry(trie.getClosest(Uri.joinPath(repoGL.uri, 'foo/bar/baz.ts'), true), repoGL); }); it('getClosest(vscode-vfs://): missing repo file', () => { assertRepoEntry(trie.getClosest(Uri.joinPath(repoGLvfs.uri, 'foo/bar/baz.ts'), true), repoGLvfs); }); it('getClosest(github://): missing repo file', () => { assertRepoEntry( trie.getClosest(Uri.joinPath(repoGLvfs.uri, 'foo/bar/baz.ts').with({ scheme: 'github' }), true), repoGLvfs, ); }); // it('getClosest(gitlens://): missing repo file', () => { // assertRepoEntry( // trie.getClosest( // Uri.joinPath(repoGL.uri, 'src/extension.ts').with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }), // true, // ), // repoGL, // ); // assertRepoEntry( // trie.getClosest( // Uri.joinPath(repoGL.uri, 'foo/bar/baz.ts').with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }), // ), // repoGL, // ); // assertRepoEntry( // trie.getClosest( // Uri.joinPath(repoNested.uri, 'foo/bar/baz.ts').with({ // scheme: 'gitlens', // authority: 'abcd', // query: JSON.stringify({ ref: '1234567890' }), // }), // ), // repoNested, // ); // }); it("getClosest: path doesn't exists anywhere", () => { assert.strictEqual( trie.getClosest(Uri.file('C:\\Users\\Name\\code\\company\\repo\\foo\\bar\\baz.ts')), undefined, ); }); }); describe('UriTrie(Repositories) Test Suite', () => { type Repo = { type: 'repo'; name: string; uri: Uri; fsPath: string }; const repoGL: Repo = { type: 'repo', name: 'vscode-gitlens', uri: Uri.file('c:/Users/Name/code/gitkraken/vscode-gitlens'), fsPath: 'c:/Users/Name/code/gitkraken/vscode-gitlens', }; const repoNested: Repo = { type: 'repo', name: 'repo', uri: Uri.file('c:/Users/Name/code/gitkraken/vscode-gitlens/nested/repo'), fsPath: 'c:/Users/Name/code/gitkraken/vscode-gitlens/nested/repo', }; const repoGLvfs: Repo = { type: 'repo', name: 'vscode-gitlens', uri: Uri.parse('vscode-vfs://github/gitkraken/vscode-gitlens'), fsPath: 'github/gitkraken/vscode-gitlens', }; const repoVSCvfs: Repo = { type: 'repo', name: 'vscode', uri: Uri.parse('vscode-vfs://github/microsoft/vscode'), fsPath: 'github/microsoft/vscode', }; const trie = new UriTrie<Repo>(normalizeRepoUri); function assertRepoEntry(actual: Repo | undefined, expected: Repo): void { // assert.strictEqual(actual?.path, expected.name); // assert.strictEqual(actual?.fullPath, expected.fsPath); assert.strictEqual(actual?.type, 'repo'); assert.strictEqual(actual?.uri.toString(), expected.uri.toString()); } function assertRepoEntryIgnoreCase(actual: Repo | undefined, expected: Repo): void { if (isLinux) { assert.strictEqual(actual, undefined); } else { // assert.strictEqual(actual?.path, expected.name); // assert.strictEqual(actual?.fullPath, expected.fsPath); assert.strictEqual(actual?.type, 'repo'); assert.strictEqual(actual?.uri.toString(), expected.uri.toString()); } } before(() => { trie.set(repoGL.uri, repoGL); trie.set(repoNested.uri, repoNested); trie.set(repoGLvfs.uri, repoGLvfs); trie.set(repoVSCvfs.uri, repoVSCvfs); }); it('has(file://)', () => { assert.strictEqual(trie.has(repoGL.uri), true); assert.strictEqual(trie.has(repoGL.uri.with({ path: repoGL.uri.path.toUpperCase() })), !isLinux); assert.strictEqual(trie.has(repoNested.uri), true); assert.strictEqual(trie.has(repoNested.uri.with({ path: repoGL.uri.path.toUpperCase() })), !isLinux); assert.strictEqual(trie.has(Uri.file('C:\\Users\\Name\\code\\company\\repo')), false); assert.strictEqual(trie.has(Uri.file('D:\\Users\\Name\\code\\gitkraken\\vscode-gitlens')), false); }); it('has(vscode-vfs://)', () => { assert.strictEqual(trie.has(repoGLvfs.uri), true); assert.strictEqual(trie.has(repoGLvfs.uri.with({ path: repoGLvfs.uri.path.toUpperCase() })), false); assert.strictEqual(trie.has(repoVSCvfs.uri), true); assert.strictEqual(trie.has(repoVSCvfs.uri.with({ path: repoVSCvfs.uri.path.toUpperCase() })), false); assert.strictEqual(trie.has(Uri.parse('vscode-vfs://github/company/repo')), false); assert.strictEqual(trie.has(repoGLvfs.uri.with({ authority: 'azdo' })), false); }); it('has(github://)', () => { assert.strictEqual(trie.has(repoGLvfs.uri.with({ scheme: 'github' })), true); assert.strictEqual( trie.has(repoGLvfs.uri.with({ scheme: 'github', path: repoGLvfs.uri.path.toUpperCase() })), false, ); assert.strictEqual(trie.has(repoVSCvfs.uri.with({ scheme: 'github' })), true); assert.strictEqual( trie.has(repoVSCvfs.uri.with({ scheme: 'github', path: repoVSCvfs.uri.path.toUpperCase() })), false, ); assert.strictEqual(trie.has(Uri.parse('github://github/company/repo')), false); assert.strictEqual(trie.has(repoGLvfs.uri.with({ scheme: 'github', authority: 'azdo' })), false); }); it('has(gitlens://)', () => { assert.strictEqual( trie.has( repoGL.uri.with({ scheme: 'gitlens', authority: 'abcd', query: JSON.stringify({ ref: '1234567890' }), }), ), true, ); assert.strictEqual( trie.has( Uri.parse( repoGL.uri .with({ scheme: 'gitlens', authority: 'abcd', query: JSON.stringify({ ref: '1234567890' }), }) .toString() .toUpperCase(), ), ), !isLinux, ); assert.strictEqual( trie.has( repoNested.uri.with({ scheme: 'gitlens', authority: 'abcd', query: JSON.stringify({ ref: '1234567890' }), }), ), true, ); assert.strictEqual( trie.has( Uri.parse( repoNested.uri .with({ scheme: 'gitlens', authority: 'abcd', query: JSON.stringify({ ref: '1234567890' }), }) .toString() .toUpperCase(), ), ), !isLinux, ); assert.strictEqual( trie.has( Uri.file('C:\\Users\\Name\\code\\company\\repo').with({ scheme: 'gitlens', authority: 'abcd', query: JSON.stringify({ ref: '1234567890' }), }), ), false, ); }); it('get(file://)', () => { assertRepoEntry(trie.get(repoGL.uri), repoGL); assertRepoEntry(trie.get(repoNested.uri), repoNested); assert.strictEqual(trie.get(Uri.file('C:\\Users\\Name\\code\\company\\repo')), undefined); assert.strictEqual(trie.get(Uri.file('D:\\Users\\Name\\code\\gitkraken\\vscode-gitlens')), undefined); }); it('get(vscode-vfs://)', () => { assertRepoEntry(trie.get(repoGLvfs.uri), repoGLvfs); assertRepoEntry(trie.get(repoVSCvfs.uri), repoVSCvfs); assert.strictEqual(trie.get(Uri.file('C:\\Users\\Name\\code\\company\\repo')), undefined); assert.strictEqual(trie.get(Uri.file('D:\\Users\\Name\\code\\gitkraken\\vscode-gitlens')), undefined); }); it('get(github://)', () => { assertRepoEntry(trie.get(repoGLvfs.uri.with({ scheme: 'github' })), repoGLvfs); assertRepoEntry(trie.get(repoVSCvfs.uri.with({ scheme: 'github' })), repoVSCvfs); }); it('get(gitlens://)', () => { assertRepoEntry( trie.get( repoGL.uri.with({ scheme: 'gitlens', authority: 'abcd', query: JSON.stringify({ ref: '1234567890' }), }), ), repoGL, ); assertRepoEntry( trie.get( repoNested.uri.with({ scheme: 'gitlens', authority: 'abcd', query: JSON.stringify({ ref: '1234567890' }), }), ), repoNested, ); }); it('get(file://) (ignore case)', () => { assertRepoEntryIgnoreCase(trie.get(repoGL.uri.with({ path: repoGL.uri.path.toUpperCase() })), repoGL); assertRepoEntryIgnoreCase( trie.get(repoNested.uri.with({ path: repoNested.uri.path.toUpperCase() })), repoNested, ); }); it('get(vscode://) (ignore case)', () => { assertRepoEntry(trie.get(repoGLvfs.uri.with({ scheme: 'VSCODE-VFS' })), repoGLvfs); assert.strictEqual( trie.get(repoGLvfs.uri.with({ authority: repoGLvfs.uri.authority.toUpperCase() })), undefined, ); assert.strictEqual(trie.get(repoGLvfs.uri.with({ path: repoGLvfs.uri.path.toUpperCase() })), undefined); }); it('get(github://) (ignore case)', () => { assertRepoEntry(trie.get(repoGLvfs.uri.with({ scheme: 'GITHUB' })), repoGLvfs); assert.strictEqual( trie.get(repoGLvfs.uri.with({ scheme: 'github', authority: repoGLvfs.uri.authority.toUpperCase() })), undefined, ); assert.strictEqual( trie.get(repoGLvfs.uri.with({ scheme: 'github', path: repoGLvfs.uri.path.toUpperCase() })), undefined, ); }); it('get(gitlens://) (ignore case)', () => { assertRepoEntry( trie.get( repoGL.uri.with({ scheme: 'GITLENS', authority: 'abcd', query: JSON.stringify({ ref: '1234567890' }), }), ), repoGL, ); assertRepoEntryIgnoreCase( trie.get( Uri.parse( repoGL.uri .with({ scheme: 'gitlens', authority: 'abcd', query: JSON.stringify({ ref: '1234567890' }), }) .toString() .toUpperCase(), ), ), repoGL, ); }); it('getClosest(file://)', () => { assertRepoEntry(trie.getClosest(repoGL.uri), repoGL); assert.strictEqual(trie.getClosest(repoGL.uri, true), undefined); assertRepoEntry(trie.getClosest(repoNested.uri), repoNested); assertRepoEntry(trie.getClosest(repoNested.uri, true), repoGL); assertRepoEntry(trie.getClosest(Uri.joinPath(repoGL.uri, 'src/extension.ts')), repoGL); assertRepoEntry(trie.getClosest(Uri.joinPath(repoNested.uri, 'src/index.ts')), repoNested); }); it('getClosest(vscode-vfs://)', () => { assertRepoEntry(trie.getClosest(repoGLvfs.uri), repoGLvfs); assert.strictEqual(trie.getClosest(repoGLvfs.uri, true), undefined); assertRepoEntry(trie.getClosest(repoVSCvfs.uri), repoVSCvfs); assert.strictEqual(trie.getClosest(repoVSCvfs.uri, true), undefined); assertRepoEntry(trie.getClosest(Uri.joinPath(repoGLvfs.uri, 'src/extension.ts'), true), repoGLvfs); assertRepoEntry(trie.getClosest(Uri.joinPath(repoVSCvfs.uri, 'src/main.ts'), true), repoVSCvfs); }); it('getClosest(github://)', () => { const repoGLvfsUri = repoGLvfs.uri.with({ scheme: 'github' }); const repoVSCvfsUri = repoVSCvfs.uri.with({ scheme: 'github' }); assertRepoEntry(trie.getClosest(repoGLvfsUri), repoGLvfs); assert.strictEqual(trie.getClosest(repoGLvfsUri, true), undefined); assertRepoEntry(trie.getClosest(repoVSCvfsUri), repoVSCvfs); assert.strictEqual(trie.getClosest(repoVSCvfsUri, true), undefined); assertRepoEntry(trie.getClosest(Uri.joinPath(repoGLvfsUri, 'src/extension.ts'), true), repoGLvfs); assertRepoEntry(trie.getClosest(Uri.joinPath(repoVSCvfsUri, 'src/main.ts'), true), repoVSCvfs); }); it('getClosest(gitlens://)', () => { const repoGLUri = Uri.joinPath(repoGL.uri, 'src/extension.ts').with({ scheme: 'gitlens', authority: 'abcd', query: JSON.stringify({ ref: '1234567890' }), }); const repoNestedUri = Uri.joinPath(repoNested.uri, 'src/index.ts').with({ scheme: 'gitlens', authority: 'abcd', query: JSON.stringify({ ref: '1234567890' }), }); assertRepoEntry(trie.getClosest(repoGLUri), repoGL); assertRepoEntry(trie.getClosest(repoNestedUri), repoNested); }); it('getClosest: missing', () => { assert.strictEqual( trie.getClosest(Uri.file('C:\\Users\\Name\\code\\company\\repo\\foo\\bar\\baz.ts')), undefined, ); }); it('getDescendants', () => { const descendants = [...trie.getDescendants()]; assert.strictEqual(descendants.length, 4); }); });
the_stack
import { expect } from "chai"; import { UnexpectedErrors } from "@itwin/core-bentley"; import { Point2d } from "@itwin/core-geometry"; import { AnalysisStyle, ColorDef, ImageBuffer, ImageBufferFormat } from "@itwin/core-common"; import { ViewRect } from "../ViewRect"; import { ScreenViewport } from "../Viewport"; import { DisplayStyle3dState } from "../DisplayStyleState"; import { IModelApp } from "../IModelApp"; import { openBlankViewport, testBlankViewport } from "./openBlankViewport"; import { DecorateContext } from "../ViewContext"; import { GraphicType } from "../render/GraphicBuilder"; import { Pixel } from "../render/Pixel"; describe("Viewport", () => { before(async () => IModelApp.startup()); after(async () => IModelApp.shutdown()); describe("flashedId", () => { type ChangedEvent = [string | undefined, string | undefined]; function expectFlashedId(viewport: ScreenViewport, expectedId: string | undefined, expectedEvent: ChangedEvent | undefined, func: () => void): void { let event: ChangedEvent | undefined; const removeListener = viewport.onFlashedIdChanged.addListener((vp, arg) => { expect(vp).to.equal(viewport); expect(event).to.be.undefined; event = [arg.previous, arg.current]; }); func(); removeListener(); expect(viewport.flashedId).to.equal(expectedId); expect(event).to.deep.equal(expectedEvent); } it("dispatches events when flashed Id changes", () => { testBlankViewport((viewport) => { expectFlashedId(viewport, "0x123", [undefined, "0x123"], () => viewport.flashedId = "0x123"); expectFlashedId(viewport, "0x456", ["0x123", "0x456"], () => viewport.flashedId = "0x456"); expectFlashedId(viewport, "0x456", undefined, () => viewport.flashedId = "0x456"); expectFlashedId(viewport, undefined, ["0x456", undefined], () => viewport.flashedId = undefined); expectFlashedId(viewport, undefined, undefined, () => viewport.flashedId = undefined); }); }); it("treats invalid Id as undefined", () => { testBlankViewport((viewport) => { viewport.flashedId = "0x123"; expectFlashedId(viewport, undefined, ["0x123", undefined], () => viewport.flashedId = "0"); viewport.flashedId = "0x123"; expectFlashedId(viewport, undefined, ["0x123", undefined], () => viewport.flashedId = undefined); }); }); it("rejects malformed Ids", () => { testBlankViewport((viewport) => { expectFlashedId(viewport, undefined, undefined, () => viewport.flashedId = "not an id"); viewport.flashedId = "0x123"; expectFlashedId(viewport, "0x123", undefined, () => viewport.flashedId = "not an id"); }); }); it("prohibits assignment from within event callback", () => { testBlankViewport((viewport) => { const oldHandler = UnexpectedErrors.setHandler(UnexpectedErrors.reThrowImmediate); viewport.onFlashedIdChanged.addOnce(() => viewport.flashedId = "0x12345"); expect(() => viewport.flashedId = "0x12345").to.throw(Error, "Cannot assign to Viewport.flashedId from within an onFlashedIdChanged event callback"); UnexpectedErrors.setHandler(oldHandler); }); }); }); describe("analysis style changed events", () => { it("registers and unregisters for multiple events", () => { testBlankViewport((viewport) => { function expectListeners(expected: boolean): void { const expectedNum = expected ? 1 : 0; expect(viewport.onChangeView.numberOfListeners).to.equal(expectedNum); // The viewport registers its own listener for each of these. expect(viewport.view.onDisplayStyleChanged.numberOfListeners).to.equal(expectedNum + 1); expect(viewport.displayStyle.settings.onAnalysisStyleChanged.numberOfListeners).to.equal(expectedNum + 1); } expectListeners(false); const removeListener = viewport.addOnAnalysisStyleChangedListener(() => undefined); expectListeners(true); removeListener(); expectListeners(false); }); }); it("emits events when analysis style changes", () => { testBlankViewport((viewport) => { type EventPayload = AnalysisStyle | "undefined" | "none"; function expectChangedEvent(expectedPayload: EventPayload, func: () => void): void { let payload: EventPayload = "none"; const removeListener = viewport.addOnAnalysisStyleChangedListener((style) => { expect(payload).to.equal("none"); payload = style ?? "undefined"; }); func(); removeListener(); expect(payload).to.equal(expectedPayload); } const a = AnalysisStyle.fromJSON({ normalChannelName: "a" }); expectChangedEvent(a, () => viewport.displayStyle.settings.analysisStyle = a); expectChangedEvent("none", () => viewport.displayStyle.settings.analysisStyle = a); const b = AnalysisStyle.fromJSON({ normalChannelName: "b" }); expectChangedEvent(b, () => { const style = viewport.displayStyle.clone(); style.settings.analysisStyle = b; viewport.displayStyle = style; }); const c = AnalysisStyle.fromJSON({ normalChannelName: "c" }); expectChangedEvent(c, () => { const view = viewport.view.clone(); expect(view.displayStyle).not.to.equal(viewport.view.displayStyle); view.displayStyle.settings.analysisStyle = c; viewport.changeView(view); }); expectChangedEvent("undefined", () => viewport.displayStyle.settings.analysisStyle = undefined); expectChangedEvent("none", () => viewport.displayStyle.settings.analysisStyle = undefined); }); }); }); describe("background map", () => { let viewport: ScreenViewport; function expectBackgroundMap(expected: boolean) { expect(viewport.viewFlags.backgroundMap).to.equal(expected); } function expectTerrain(expected: boolean) { expect(viewport.backgroundMap).not.to.be.undefined; // this is *never* undefined despite type annotation... expect(viewport.backgroundMap!.settings.applyTerrain).to.equal(expected); } beforeEach(() => { viewport = openBlankViewport(); expectBackgroundMap(false); expectTerrain(false); viewport.viewFlags = viewport.viewFlags.with("backgroundMap", true); expectBackgroundMap(true); expectTerrain(false); }); afterEach(() => { viewport.view.displayStyle = new DisplayStyle3dState({} as any, viewport.iModel); expectBackgroundMap(false); expectTerrain(false); viewport.dispose(); }); it("updates when display style is assigned to", () => { let style = viewport.displayStyle.clone(); style.viewFlags = style.viewFlags.with("backgroundMap", false); viewport.displayStyle = style; expectBackgroundMap(false); expectTerrain(false); style = style.clone(); style.viewFlags = style.viewFlags.with("backgroundMap", true); style.settings.applyOverrides({ backgroundMap: { applyTerrain: true } }); viewport.displayStyle = style; expectBackgroundMap(true); expectTerrain(true); style = style.clone(); style.settings.applyOverrides({ backgroundMap: { applyTerrain: false } }); viewport.displayStyle = style; expectBackgroundMap(true); expectTerrain(false); }); it("updates when settings are modified", () => { const style = viewport.displayStyle; style.viewFlags = style.viewFlags.with("backgroundMap", false); expectBackgroundMap(false); expectTerrain(false); style.viewFlags = style.viewFlags.with("backgroundMap", true); style.settings.applyOverrides({ backgroundMap: { applyTerrain: true } }); expectBackgroundMap(true); expectTerrain(true); style.settings.applyOverrides({ backgroundMap: { applyTerrain: false } }); expectBackgroundMap(true); expectTerrain(false); }); }); describe("read images", () => { interface TestCase { width: number; height?: number; image: ColorDef[]; bgColor?: ColorDef; } class Decorator { public constructor(public readonly image: ColorDef[], public readonly width: number, public readonly height: number) { IModelApp.viewManager.addDecorator(this); } public decorate(context: DecorateContext): void { const builder = context.createGraphicBuilder(GraphicType.ViewOverlay); for (let x = 0; x < this.width; x++) { for (let y = 0; y < this.height; y++) { const color = this.image[x + y * this.width]; builder.setSymbology(color, color, 1); builder.addPointString2d([new Point2d(x + 0.5, y + 0.5)], 0); } } context.addDecorationFromBuilder(builder); } } function test(testCase: TestCase, func: (viewport: ScreenViewport) => void): void { const decHeight = testCase.image.length / testCase.width; const rectHeight = testCase.height ?? decHeight; expect(rectHeight).to.equal(Math.floor(rectHeight)); expect(decHeight).to.equal(Math.floor(decHeight)); testBlankViewport({ width: testCase.width, height: rectHeight, position: "absolute", test: (viewport) => { expect(viewport.viewRect.width).to.equal(testCase.width); expect(viewport.viewRect.height).to.equal(rectHeight); if (testCase.bgColor) viewport.displayStyle.backgroundColor = testCase.bgColor; const decorator = new Decorator(testCase.image, testCase.width, decHeight); try { viewport.renderFrame(); func(viewport); } finally { IModelApp.viewManager.dropDecorator(decorator); } }, }); } function expectColors(image: ImageBuffer, expectedColors: ColorDef[]): void { expect(image.width * image.height).to.equal(expectedColors.length); expect(image.format).to.equal(ImageBufferFormat.Rgba); const expected = expectedColors.map((x) => x.tbgr.toString(16)); const actual: string[] = []; for (let i = 0; i < expected.length; i++) { const offset = i * 4; actual.push(ColorDef.from(image.data[offset], image.data[offset + 1], image.data[offset + 2], 0xff - image.data[offset + 3]).tbgr.toString(16)); } expect(actual).to.deep.equal(expected); } const rgbw2: TestCase = { width: 2, image: [ ColorDef.red, ColorDef.green, ColorDef.blue, ColorDef.white, ], }; const purple = ColorDef.from(255, 0, 255); const cyan = ColorDef.from(0, 255, 255); const yellow = ColorDef.from(255, 255, 0); const grey = ColorDef.from(127, 127, 127); const transpBlack = ColorDef.black.withTransparency(0xff); const halfRed = ColorDef.from(0x80, 0, 0); const rgbwp1: TestCase = { width: 1, image: [ ColorDef.red, ColorDef.green, ColorDef.blue, ColorDef.white, purple ], }; const rTransp50pct: TestCase = { width: 1, height: 2, image: [ ColorDef.red.withTransparency(0x7f) ], bgColor: transpBlack, }; const rTransp100pct: TestCase = { ...rTransp50pct, image: [ ColorDef.red.withTransparency(0xff) ], }; const square3: TestCase = { width: 3, image: [ ColorDef.red, ColorDef.green, ColorDef.blue, ColorDef.white, ColorDef.black, grey, cyan, purple, yellow, ], }; describe("readImage", () => { it("reads image upside down by default (BUG)", () => { test(rgbw2, (viewport) => { // eslint-disable-next-line deprecation/deprecation const image = viewport.readImage()!; expect(image).not.to.be.undefined; expectColors(image, [ ColorDef.blue, ColorDef.white, ColorDef.red, ColorDef.green ]); }); }); it("flips image vertically if specified", () => { test(rgbw2, (viewport) => { // eslint-disable-next-line deprecation/deprecation const image = viewport.readImage(undefined, undefined, true)!; expect(image).not.to.be.undefined; expectColors(image, rgbw2.image); }); }); it("inverts view rect y (BUG)", () => { test(rgbwp1, (viewport) => { // eslint-disable-next-line deprecation/deprecation const image = viewport.readImage(new ViewRect(0, 1, 1, 3), undefined, true)!; expect(image).not.to.be.undefined; expectColors(image, [ ColorDef.blue, ColorDef.white ]); }); }); }); describe("readImageBuffer", () => { it("reads image right-side up by default", () => { test(rgbw2, (viewport) => { const image = viewport.readImageBuffer()!; expect(image).not.to.be.undefined; expectColors(image, rgbw2.image); }); }); it("produces upside-down image if specified", () => { test(rgbw2, (viewport) => { const image = viewport.readImageBuffer({ upsideDown: true })!; expect(image).not.to.be.undefined; expectColors(image, [ ColorDef.blue, ColorDef.white, ColorDef.red, ColorDef.green ]); }); }); it("does not invert view rect", () => { test(rgbwp1, (viewport) => { const image = viewport.readImageBuffer({ rect: new ViewRect(0, 1, 1, 3) })!; expect(image).not.to.be.undefined; expectColors(image, [ ColorDef.green, ColorDef.blue ]); }); }); it("captures specified region", () => { test(square3, (viewport) => { const capture = (left: number, top: number, width: number, height: number, expected: ColorDef[]) => { const rect = new ViewRect(left, top, left + width, top + height); const image = viewport.readImageBuffer({ rect })!; expect(image).not.to.be.undefined; expectColors(image, expected); }; capture(0, 0, 3, 3, square3.image); capture(0, 0, 2, 2, [ ColorDef.red, ColorDef.green, ColorDef.white, ColorDef.black ]); capture(1, 1, 2, 2, [ ColorDef.black, grey, purple, yellow ]); capture(2, 0, 1, 3, [ ColorDef.blue, grey, yellow ]); capture(0, 2, 3, 1, [ cyan, purple, yellow ]); capture(1, 2, 1, 1, [ purple ]); }); }); it("rejects invalid capture rects", () => { test(rgbw2, (viewport) => { const expectNoImage = (left: number, top: number, right: number, bottom: number) => { expect(viewport.readImageBuffer({ rect: new ViewRect(left, top, right, bottom) })).to.be.undefined; }; expectNoImage(0, 0, -1, -1); expectNoImage(0, 0, 100, 1); expectNoImage(0, 0, 1, 100); expectNoImage(100, 100, 1, 1); expectNoImage(1, 1, 1, 1); }); }); it("resizes", () => { test({ ...rgbw2, bgColor: grey }, (viewport) => { const resize = (w: number, h: number, expectedBarPixels?: { top?: number, bottom?: number, left?: number, right?: number }, expectedColors?: ColorDef[]) => { const image = viewport.readImageBuffer({ size: { x: w, y: h } })!; expect(image).not.to.be.undefined; expect(image.width).to.equal(w); expect(image.height).to.equal(h); if (expectedColors) expectColors(image, expectedColors); const top = expectedBarPixels?.top ?? 0; const left = expectedBarPixels?.left ?? 0; const right = w - (expectedBarPixels?.right ?? 0); const bottom = h - (expectedBarPixels?.bottom ?? 0); for (let x = 0; x < w; x++) { for (let y = 0; y < h; y++) { const i = 4 * (x + y * w); const color = ColorDef.from(image.data[i], image.data[i + 1], image.data[i + 2], 0xff - image.data[i + 3]); expect(color.equals(grey)).to.equal(x < left || y < top || x >= right || y >= bottom); } } }; resize(4, 4); resize(1, 1); resize(4, 2, { left: 1, right: 1 }, [ grey, ColorDef.red, ColorDef.green, grey, grey, ColorDef.blue, ColorDef.white, grey, ]); resize(2, 4, { top: 1, bottom: 1 }, [ grey, grey, ColorDef.red, ColorDef.green, ColorDef.blue, ColorDef.white, grey, grey, ]); resize(8, 4, { left: 2, right: 2 }); resize(4, 8, { top: 2, bottom: 2 }); resize(3, 2, { left: 1 }); resize(2, 5, { top: 1, bottom: 2 }, [ grey, grey, ColorDef.red, ColorDef.green, ColorDef.blue, ColorDef.white, grey, grey, grey, grey, ]); }); }); it("rejects invalid sizes", () => { test(rgbw2, (viewport) => { const expectNoImage = (width: number, height: number) => { expect(viewport.readImageBuffer({ size: { x: width, y: height } })).to.be.undefined; }; expectNoImage(0, 1); expectNoImage(1, 0); expectNoImage(-1, 1); expectNoImage(1, -1); }); }); it("discards alpha by default", () => { test({ ...rTransp50pct, bgColor: undefined }, (viewport) => { const image = viewport.readImageBuffer()!; expect(image).not.to.be.undefined; expectColors(image, [ halfRed, ColorDef.black ]); }); test({ ...rTransp100pct, bgColor: undefined }, (viewport) => { const image = viewport.readImageBuffer()!; expect(image).not.to.be.undefined; expectColors(image, [ ColorDef.black, ColorDef.black ]); }); }); it("preserves background alpha if background color is fully transparent", () => { test(rTransp50pct, (viewport) => { const image = viewport.readImageBuffer()!; expect(image).not.to.be.undefined; expectColors(image, [ halfRed, transpBlack ]); }); }); it("doesn't preserve background alpha when resizing (canvas limitation)", () => { // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/putImageData#data_loss_due_to_browser_optimization test(rTransp50pct, (viewport) => { const image = viewport.readImageBuffer({ size: { x: 2, y: 4 } })!; expect(image).not.to.be.undefined; for (let i = 3; i < 2 * 4 * 4; i += 4) expect(image.data[i]).to.equal(0xff); }); }); it("produces undefined if image is entirely transparent background pixels", () => { test(rTransp100pct, (viewport) => { expect(viewport.readImageBuffer()).to.be.undefined; }); }); }); }); describe("readPixels", () => { it("returns undefined if viewport is disposed", async () => { testBlankViewport((vp) => { vp.readPixels(vp.viewRect, Pixel.Selector.All, (pixels) => expect(pixels).not.to.be.undefined); // BlankViewport.dispose also closes the iModel and removes the viewport's div from the DOM. // We don't want that until the test completes. const dispose = vp.dispose; // eslint-disable-line @typescript-eslint/unbound-method vp.dispose = ScreenViewport.prototype.dispose; // eslint-disable-line @typescript-eslint/unbound-method vp.dispose(); vp.readPixels(vp.viewRect, Pixel.Selector.All, (pixels) => expect(pixels).to.be.undefined); vp.dispose = dispose; }); }); }); });
the_stack
import { Test, TestingModule } from '@nestjs/testing' import { NotImplementedException } from '@nestjs/common' import { getRepositoryToken } from '@nestjs/typeorm' import { Repository } from 'typeorm' import { TypeOrmQueryService } from '@nestjs-query/query-typeorm' import { PaymentEntity /* PaymentStatus */ } from '../entities/payment.entity' import { PaymentsService } from './payments.service' import { StripeService } from './stripe.service' import { KillBillService } from './killbill.service' import { ConfigService } from '@nestjs/config' import { SettingsService } from '../../settings/settings.service' import { ValidationService } from '../../validator/validation.service' import { PlansService } from './plans.service' import { AccountEntity } from '../../accounts/entities/account.entity' import { ProvidersService } from './providers.service' const deletedSubscription = new PaymentEntity() const existingSubscription = new PaymentEntity() const otherAccountSubscription = new PaymentEntity() deletedSubscription.id = 1 deletedSubscription.account_id = 101 deletedSubscription.status = 'active' deletedSubscription.stripe_id = 'sub_1' deletedSubscription.data = { id: 'sub_1', status: 'active', active: 'true' } existingSubscription.id = 2 existingSubscription.account_id = 101 existingSubscription.status = 'active' existingSubscription.stripe_id = 'sub_2' existingSubscription.data = { id: 'sub_2', status: 'active', active: 'true' } otherAccountSubscription.id = 3 otherAccountSubscription.account_id = 109 otherAccountSubscription.status = 'active' otherAccountSubscription.stripe_id = 'sub_4' otherAccountSubscription.data = { id: 'sub_4', status: 'active', active: 'true' } const paymentsArray = [ deletedSubscription, existingSubscription ] // This depends on Stripe. We need to update this when we support more payment processors const subscriptionsArray = [ { id: 'sub_2', status: 'active', active: 'false' }, { id: 'sub_3', status: 'active', active: 'true' } ] describe('Payments Service - enrollOrUpdateAccount', () => { let service // Removed type paymentsService because we must overwrite the paymentsRepository property let stripeService let providersService let repo: Repository<PaymentEntity> let account let planHandle let paymentMethod let mockPlan let mockSettings let mockStripeCustomer let mockStripeCustomerWithDefaultPayment let mockStripeSub let mockedStripePaymentMethod const mockedRepo = { query: jest.fn( query => { if (query?.filter?.account_id?.eq === 101) { return paymentsArray } if (query?.filter?.status?.in != null) { return paymentsArray } return [ deletedSubscription, existingSubscription, otherAccountSubscription ] }), find: jest.fn(() => paymentsArray), createOne: jest.fn((payment) => { return payment }), updateOne: jest.fn((id, payment) => { return payment }), deleteOne: jest.fn(id => { return 0 }) } // This depends on Stripe. We need to update this when we support more payment processors const mockedStripe = { customers: { retrieve: jest.fn(_ => ({ subscriptions: { data: subscriptionsArray } })), update: jest.fn(_ => (mockStripeCustomerWithDefaultPayment)), create: jest.fn(_ => (mockStripeCustomer)) }, paymentMethods: { attach: jest.fn(_ => (mockedStripePaymentMethod)) }, subscriptions: { create: jest.fn(_ => (mockStripeSub)) } } const mockedKillBill = { } const mockedSettingsService = { getWebsiteRenderingVariables: jest.fn(_ => (mockSettings)), getTrialLength: jest.fn(_ => (7)) } const mockedPlanService = { getPlanFromHandle: jest.fn(_ => (mockPlan)) } beforeEach(async () => { jest.clearAllMocks() const module: TestingModule = await Test.createTestingModule({ providers: [ PaymentsService, { provide: getRepositoryToken(PaymentEntity), useValue: mockedRepo }, StripeService, { provide: KillBillService, useValue: mockedKillBill }, { provide: SettingsService, useValue: mockedSettingsService }, { provide: PlansService, useValue: mockedPlanService }, ValidationService, { provide: ConfigService, useValue: { get: () => {} } }, ProvidersService, // We must also pass TypeOrmQueryService TypeOrmQueryService ] }).compile() service = await module.get(PaymentsService) stripeService = await module.get(StripeService) providersService = await module.get(ProvidersService) repo = await module.get<Repository<PaymentEntity>>( getRepositoryToken(PaymentEntity) ) // this is not really unit test, we're going 1 level deep and testing also StripeService stripeService.client = mockedStripe stripeService.enabled = true // We must manually set the following because extending TypeOrmQueryService seems to break it Object.keys(mockedRepo).forEach(f => (service[f] = mockedRepo[f])) service.paymentsRepository = repo service.providersService = providersService service.providersService.stripeService = stripeService service.providersService.killbillService = { accountApi: mockedKillBill } service.providersService.settingsService = mockedSettingsService service.settingsService = mockedSettingsService service.plansService = mockedPlanService service.validationService = await module.get(ValidationService) service.providersService.paymentIntegration = 'stripe' service.providersService.paymentProcessor = stripeService // Object.keys(mockedStripe).forEach( // f => (service.stripeClient[f] = mockedStripe[f]), // ); account = new AccountEntity() planHandle = '' paymentMethod = null mockSettings = {} mockPlan = {} mockStripeCustomer = { object: 'customer', id: 'cus_123' } mockStripeCustomerWithDefaultPayment = { object: 'customer', id: 'cus_123', default_payment_method: 'met_123' } mockStripeSub = { object: 'subscription', id: 'sub_123' } mockedStripePaymentMethod = { object: 'method', id: 'met_123' } }) it('should be defined', () => { expect(service).toBeDefined() expect(service.paymentsRepository).toEqual(repo) }) describe('getPaymentsConfig', () => { it('default = stripe', async () => { const config = await service.getPaymentsConfig() expect(config).toEqual({ payment_processor: 'stripe', payment_processor_enabled: true, signup_force_payment: false }) }) it('signup_force_payment: true', async () => { mockSettings = { signup_force_payment: true } const config = await service.getPaymentsConfig() expect(config).toEqual({ payment_processor: 'stripe', payment_processor_enabled: true, signup_force_payment: true }) }) it('Stripe disabled', async () => { stripeService.enabled = false const config = await service.getPaymentsConfig() expect(config).toEqual({ payment_processor: 'stripe', payment_processor_enabled: false, signup_force_payment: false }) }) }) describe('enrollOrUpdateAccount - subscription succeed', () => { /* #golden test = stripe + free trial + add payment method used as a basis for other corner cases */ it('should create an external subscription [create account via admin dashboard]', async () => { mockPlan = { provider: 'external' } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: 'stripe', plan: mockPlan, sub: { status: 'external' } } expect(payment).toEqual(expectedPayment) }) it('should create a free tier [signup]', async () => { mockPlan = { price: 0 } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: 'stripe', plan: mockPlan, sub: { status: 'active' } } expect(payment).toEqual(expectedPayment) }) it('should create a free trial [signup]', async () => { mockPlan = { price: 10, freeTrial: 14 } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: 'stripe', plan: mockPlan, customer: mockStripeCustomer, sub: mockStripeSub } expect(payment).toEqual(expectedPayment) }) it('should update a free trial when a payment method is passed [add payment method] #golden', async () => { paymentMethod = { id: 123 } mockPlan = { price: 10, freeTrial: 14 } const payment0 = await service.enrollOrUpdateAccount(account, planHandle, null) expect(payment0).toEqual({ provider: 'stripe', plan: mockPlan, customer: mockStripeCustomer, sub: mockStripeSub }) account.data.payment = payment0 const payment = await service.enrollOrUpdateAccount(account, null, paymentMethod) const expectedPayment = { provider: 'stripe', plan: mockPlan, customer: mockStripeCustomerWithDefaultPayment, sub: mockStripeSub, methods: [mockedStripePaymentMethod] } expect(payment).toEqual(expectedPayment) }) it('should not create a full subscription if no payment method is set [signup]', async () => { mockPlan = { price: 10, freeTrial: 0 } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: 'stripe', plan: mockPlan, customer: mockStripeCustomer } expect(payment).toEqual(expectedPayment) }) it('should create a full subscription when a payment method is passed [add payment method]', async () => { paymentMethod = { id: 123 } mockPlan = { price: 10, freeTrial: 0 } const payment0 = await service.enrollOrUpdateAccount(account, planHandle, null) expect(payment0).toEqual({ provider: 'stripe', plan: mockPlan, customer: mockStripeCustomer }) account.data.payment = payment0 const payment = await service.enrollOrUpdateAccount(account, null, paymentMethod) const expectedPayment = { provider: 'stripe', plan: mockPlan, customer: mockStripeCustomerWithDefaultPayment, sub: mockStripeSub, methods: [mockedStripePaymentMethod] } expect(payment).toEqual(expectedPayment) }) }) describe('enrollOrUpdateAccount - subscription not created', () => { it('should not create a subscription if already set', async () => { mockPlan = { price: 10, freeTrial: 14 } const existingPlan = { id: 4567 } const existingCustomer = { id: 4568 } const existingSub = { id: 4569 } account.data.payment = { provider: 'stripe', plan: existingPlan, customer: existingCustomer, sub: existingSub } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: 'stripe', plan: existingPlan, customer: existingCustomer, sub: existingSub } expect(payment).toEqual(expectedPayment) }) /* DUPE it('should not create a subscription if payment provider is not set', async () => { stripeService.enabled = false // if stripe is disabled, customer will return null. In theory also subscriptions etc. but they are unnecessary mockStripeCustomer = null mockPlan = { price: 10, freeTrial: 14 } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: null, plan: mockPlan, } expect(payment).toEqual(expectedPayment) }) */ }) describe('enrollOrUpdateAccount - customer not set', () => { it('should create an external subscription if customer is not set', async () => { mockStripeCustomer = null // simulate one Stripe call failure mockPlan = { provider: 'external' } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: 'stripe', plan: mockPlan, sub: { status: 'external' } } expect(payment).toEqual(expectedPayment) }) it('should create a free tier if customer is not set', async () => { mockStripeCustomer = null // simulate one Stripe call failure mockPlan = { price: 0 } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: 'stripe', plan: mockPlan, sub: { status: 'active' } } expect(payment).toEqual(expectedPayment) }) it('should not create a free trial if customer is not set', async () => { mockStripeCustomer = null // simulate one Stripe call failure mockPlan = { price: 10, freeTrial: 14 } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: 'stripe', plan: mockPlan } expect(payment).toEqual(expectedPayment) }) it('should not create a full subscription if customer is not set', async () => { mockStripeCustomer = null // simulate one Stripe call failure mockPlan = { price: 10, freeTrial: 0 } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: 'stripe', plan: mockPlan } expect(payment).toEqual(expectedPayment) }) }) describe('enrollOrUpdateAccount - no provider', () => { it('should not create an external subscription when provider is null', async () => { stripeService.enabled = false // if stripe is disabled, customer will return null. In theory also subscriptions etc. but they are unnecessary mockStripeCustomer = null mockPlan = { provider: 'external' } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: null, plan: mockPlan } expect(payment).toEqual(expectedPayment) }) it('should not create a free tier when provider is null', async () => { stripeService.enabled = false // if stripe is disabled, customer will return null. In theory also subscriptions etc. but they are unnecessary mockStripeCustomer = null mockPlan = { price: 0 } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: null, plan: mockPlan } expect(payment).toEqual(expectedPayment) }) it('should not create a free trial when provider is null', async () => { stripeService.enabled = false // if stripe is disabled, customer will return null. In theory also subscriptions etc. but they are unnecessary mockStripeCustomer = null mockPlan = { price: 10, freeTrial: 14 } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: null, plan: mockPlan } expect(payment).toEqual(expectedPayment) }) it('should not create a full subscription when provider is null', async () => { stripeService.enabled = false // if stripe is disabled, customer will return null. In theory also subscriptions etc. but they are unnecessary mockStripeCustomer = null mockPlan = { price: 10, freeTrial: 0 } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: null, plan: mockPlan } expect(payment).toEqual(expectedPayment) }) }) describe('enrollOrUpdateAccount - payment processor', () => { it('should set the payment processor after it gets enabled', async () => { stripeService.enabled = false // if stripe is disabled, customer will return null. In theory also subscriptions etc. but they are unnecessary const customer = { ...mockStripeCustomer } mockStripeCustomer = null paymentMethod = { id: 123 } mockPlan = { price: 10, freeTrial: 14 } const payment0 = await service.enrollOrUpdateAccount(account, planHandle, null) expect(payment0).toEqual({ provider: null, plan: mockPlan }) stripeService.enabled = true mockStripeCustomer = customer account.data.payment = payment0 const payment = await service.enrollOrUpdateAccount(account, null, paymentMethod) const expectedPayment = { provider: 'stripe', plan: mockPlan, customer: mockStripeCustomerWithDefaultPayment, sub: mockStripeSub, methods: [mockedStripePaymentMethod] } expect(payment).toEqual(expectedPayment) }) it('should fail if there is a payment processor mismatch', async () => { paymentMethod = { id: 123 } mockPlan = { price: 10, freeTrial: 14 } const payment0 = await service.enrollOrUpdateAccount(account, planHandle, null) expect(payment0).toEqual({ provider: 'stripe', plan: mockPlan, customer: mockStripeCustomer, sub: mockStripeSub }) service.providersService.paymentIntegration = 'killbill' account.data.payment = payment0 let error try { await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) } catch (e) { error = e } expect(error).toStrictEqual(new NotImplementedException('Payment provider mismatch')) }) }) describe('enrollOrUpdateAccount - plan', () => { it('should add a plan if not set', async () => { paymentMethod = { id: 123 } const plan0 = { name: 'plan0', price: 10, freeTrial: 14 } mockPlan = null const payment0 = await service.enrollOrUpdateAccount(account, planHandle, null) expect(payment0).toEqual({ provider: 'stripe', customer: mockStripeCustomer }) mockPlan = plan0 account.data.payment = payment0 const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: 'stripe', plan: plan0, customer: mockStripeCustomerWithDefaultPayment, sub: mockStripeSub, methods: [mockedStripePaymentMethod] } expect(payment).toEqual(expectedPayment) }) it('should not overwrite a plan if already set', async () => { paymentMethod = { id: 123 } const plan0 = { name: 'plan0', price: 10, freeTrial: 14 } const plan1 = { name: 'plan1', price: 20, freeTrial: 7 } mockPlan = plan0 const payment0 = await service.enrollOrUpdateAccount(account, planHandle, null) expect(payment0).toEqual({ provider: 'stripe', plan: plan0, customer: mockStripeCustomer, sub: mockStripeSub }) mockPlan = plan1 account.data.payment = payment0 const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: 'stripe', plan: plan0, customer: mockStripeCustomerWithDefaultPayment, sub: mockStripeSub, methods: [mockedStripePaymentMethod] } expect(payment).toEqual(expectedPayment) }) }) describe('enrollOrUpdateAccount - customer', () => { it('should not overwrite a customer if already set', async () => { }) // same as subscription succeed, external // it('should not create a customer for external if payment method is not passed', async () => { }) // same as subscription succeed, free tier // it('should not create a customer for free tier if payment method is not passed', async () => { }) it('should create a customer for external if payment method is passed', async () => { paymentMethod = { id: 123 } mockPlan = { provider: 'external' } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: 'stripe', plan: mockPlan, sub: { status: 'external' }, customer: mockStripeCustomerWithDefaultPayment, methods: [mockedStripePaymentMethod] } expect(payment).toEqual(expectedPayment) }) it('should create a customer for free tier if payment method is passed', async () => { paymentMethod = { id: 123 } mockPlan = { price: 0 } const payment = await service.enrollOrUpdateAccount(account, planHandle, paymentMethod) const expectedPayment = { provider: 'stripe', plan: mockPlan, sub: { status: 'active' }, customer: mockStripeCustomerWithDefaultPayment, methods: [mockedStripePaymentMethod] } expect(payment).toEqual(expectedPayment) }) // same as subscription succeed, free trial #golden // it('should create a customer for free trial', async () => { }) // same as subscription succeed, full // it('should create a customer for full subscription', async () => { }) }) describe('enrollOrUpdateAccount - payment method', () => { // same as subscription succeed, free trial #golden // it('should add the first payment method', async () => { }) it('should add the second payment method', async () => { paymentMethod = { id: 123 } mockPlan = { price: 10, freeTrial: 14 } const stripePaymentMethod0 = { object: 'method', id: 'met_123' } const stripePaymentMethod1 = { object: 'method', id: 'met_456' } const payment0 = await service.enrollOrUpdateAccount(account, planHandle, null) expect(payment0).toEqual({ provider: 'stripe', plan: mockPlan, customer: mockStripeCustomer, sub: mockStripeSub }) mockedStripePaymentMethod = stripePaymentMethod0 account.data.payment = payment0 const payment1 = await service.enrollOrUpdateAccount(account, null, paymentMethod) expect(payment1).toEqual({ provider: 'stripe', plan: mockPlan, customer: mockStripeCustomerWithDefaultPayment, sub: mockStripeSub, methods: [stripePaymentMethod0] }) mockedStripePaymentMethod = stripePaymentMethod1 account.data.payment = payment1 const payment = await service.enrollOrUpdateAccount(account, null, paymentMethod) const expectedPayment = { provider: 'stripe', plan: mockPlan, customer: mockStripeCustomerWithDefaultPayment, sub: mockStripeSub, methods: [stripePaymentMethod0, stripePaymentMethod1] } expect(payment).toEqual(expectedPayment) }) it('should update the customer when adding a payment method', async () => { paymentMethod = { id: 123 } mockPlan = { price: 10, freeTrial: 14 } const payment0 = await service.enrollOrUpdateAccount(account, planHandle, null) expect(payment0).toEqual({ provider: 'stripe', plan: mockPlan, customer: mockStripeCustomer, sub: mockStripeSub }) account.data.payment = payment0 const payment = await service.enrollOrUpdateAccount(account, null, paymentMethod) const expectedPayment = { provider: 'stripe', plan: mockPlan, customer: mockStripeCustomerWithDefaultPayment, sub: mockStripeSub, methods: [mockedStripePaymentMethod] } expect(payment).toEqual(expectedPayment) }) }) describe('enrollOrUpdateAccount - inputs', () => { it('should not fail on all null', async () => { mockPlan = { price: 10, freeTrial: 14 } const payment = await service.enrollOrUpdateAccount(null, null, null) expect(payment).toEqual({ provider: 'stripe', plan: mockPlan }) }) it('should not fail on all null (stripe disabled)', async () => { stripeService.enabled = false mockPlan = null const payment = await service.enrollOrUpdateAccount(null, null, null) expect(payment).toEqual({ provider: null }) }) it('should create a subscription when everything but account is null', async () => { mockPlan = { price: 10, freeTrial: 14 } const payment = await service.enrollOrUpdateAccount(account, null, null) expect(payment).toEqual({ provider: 'stripe', plan: mockPlan, customer: mockStripeCustomer, sub: mockStripeSub }) }) }) })
the_stack
import * as C from "csstype" import * as T from "../types" import { PX_SCALE } from "../constants" import { addPx } from "../utils" import { compose } from "../compose" import { extend, style } from "../style" import { display, DisplayProps, DisplayStyle } from "./display" import { alignContent, AlignContentProps, AlignContentStyle, alignItems, AlignItemsProps, AlignItemsStyle, alignSelf, AlignSelfProps, AlignSelfStyle, justifyContent, JustifyContentProps, JustifyContentStyle, justifyItems, JustifyItemsProps, JustifyItemsStyle, justifySelf, JustifySelfProps, JustifySelfStyle, placeContent, PlaceContentProps, PlaceContentStyle, placeItems, PlaceItemsProps, PlaceItemsStyle, placeSelf, PlaceSelfProps, PlaceSelfStyle } from "./align" const ex = extend({ themeKeys: ["spaces"], transform: addPx, defaults: PX_SCALE }) // Grid export type GridValue = C.GridProperty export type GridProp = T.Prop<GridValue> export interface GridProps extends T.ThemeProps { grid?: GridProp g?: GridProp } export interface GridStyle extends T.Style { grid?: GridValue } export const grid = style<GridProps, GridStyle>({ propsKeys: ["grid", "g"] }) // Grid Template export type GridTemplateValue = C.GridTemplateProperty export type GridTemplateProp = T.Prop<GridTemplateValue> export interface GridTemplateProps extends T.ThemeProps { gridTemplate?: GridTemplateProp gt?: GridTemplateProp } export interface GridTemplateStyle extends T.Style { gridTemplate?: GridTemplateValue } export const gridTemplate = style<GridTemplateProps, GridTemplateStyle>({ propsKeys: ["gridTemplate", "gt"] }) // Grid Template Rows export type GridTemplateRowsValue = C.GridTemplateRowsProperty<T.Length> export type GridTemplateRowsProp = T.Prop<GridTemplateRowsValue> export interface GridTemplateRowsProps extends T.ThemeProps { gridTemplateRows?: GridTemplateRowsProp gtr?: GridTemplateRowsProp } export interface GridTemplateRowsStyle extends T.Style { gridTemplateRows?: GridTemplateRowsValue } export const gridTemplateRows = style< GridTemplateRowsProps, GridTemplateRowsStyle >({ propsKeys: ["gridTemplateRows", "gtr"] }) // Grid Template Columns export type GridTemplateColumnsValue = C.GridTemplateColumnsProperty<T.Length> export type GridTemplateColumnsProp = T.Prop<GridTemplateColumnsValue> export interface GridTemplateColumnsProps extends T.ThemeProps { gridTemplateColumns?: GridTemplateColumnsProp gtc?: GridTemplateColumnsProp } export interface GridTemplateColumnsStyle extends T.Style { gridTemplateColumns?: GridTemplateColumnsValue } export const gridTemplateColumns = style< GridTemplateColumnsProps, GridTemplateColumnsStyle >({ propsKeys: ["gridTemplateColumns", "gtc"] }) // Grid Template Areas export type GridTemplateAreasValue = C.GridTemplateAreasProperty export type GridTemplateAreasProp = T.Prop<GridTemplateAreasValue> export interface GridTemplateAreasProps extends T.ThemeProps { gridTemplateAreas?: GridTemplateAreasProp gta?: GridTemplateAreasProp } export interface GridTemplateAreasStyle extends T.Style { gridTemplateAreas?: GridTemplateAreasValue } export const gridTemplateAreas = style< GridTemplateAreasProps, GridTemplateAreasStyle >({ propsKeys: ["gridTemplateAreas", "gta"] }) // Grid Gap export type GridGapValue = C.GridGapProperty<T.Length> export type GridGapProp = T.Prop<GridGapValue> export interface GridGapProps extends T.ThemeProps { gridGap?: GridGapProp gg?: GridGapProp } export interface GridGapStyle extends T.Style { gridGap?: GridGapValue } export const gridGap = ex<GridGapProps, GridGapStyle>({ propsKeys: ["gridGap", "gg"] }) // Grid Row Gap export type GridRowGapValue = C.GridRowGapProperty<T.Length> export type GridRowGapProp = T.Prop<GridRowGapValue> export interface GridRowGapProps extends T.ThemeProps { gridRowGap?: GridRowGapProp grg?: GridRowGapProp } export interface GridRowGapStyle extends T.Style { gridRowGap?: GridRowGapValue } export const gridRowGap = ex<GridRowGapProps, GridRowGapStyle>({ propsKeys: ["gridRowGap", "grg"] }) // Grid Column Gap export type GridColumnGapValue = C.GridColumnGapProperty<T.Length> export type GridColumnGapProp = T.Prop<GridColumnGapValue> export interface GridColumnGapProps extends T.ThemeProps { gridColumnGap?: GridColumnGapProp gcg?: GridColumnGapProp } export interface GridColumnGapStyle extends T.Style { gridColumnGap?: GridColumnGapValue } export const gridColumnGap = ex<GridColumnGapProps, GridColumnGapStyle>({ propsKeys: ["gridColumnGap", "gcg"] }) // Grid Auto Rows export type GridAutoRowsValue = C.GridAutoRowsProperty<T.Length> export type GridAutoRowsProp = T.Prop<GridAutoRowsValue> export interface GridAutoRowsProps extends T.ThemeProps { gridAutoRows?: GridAutoRowsProp gar?: GridAutoRowsProp } export interface GridAutoRowsStyle extends T.Style { gridAutoRows?: GridAutoRowsValue } export const gridAutoRows = style<GridAutoRowsProps, GridAutoRowsStyle>({ propsKeys: ["gridAutoRows", "gar"] }) // Grid Auto Columns export type GridAutoColumnsValue = C.GridAutoColumnsProperty<T.Length> export type GridAutoColumnsProp = T.Prop<GridAutoColumnsValue> export interface GridAutoColumnsProps extends T.ThemeProps { gridAutoColumns?: GridAutoColumnsProp gac?: GridAutoColumnsProp } export interface GridAutoColumnsStyle extends T.Style { gridAutoColumns?: GridAutoColumnsValue } export const gridAutoColumns = style< GridAutoColumnsProps, GridAutoColumnsStyle >({ propsKeys: ["gridAutoColumns", "gac"] }) // Grid Auto Flow export type GridAutoFlowValue = C.GridAutoFlowProperty export type GridAutoFlowProp = T.Prop<GridAutoFlowValue> export interface GridAutoFlowProps extends T.ThemeProps { gridAutoFlow?: GridAutoFlowProp gaf?: GridAutoFlowProp } export interface GridAutoFlowStyle extends T.Style { gridAutoFlow?: GridAutoFlowValue } export const gridAutoFlow = style<GridAutoFlowProps, GridAutoFlowStyle>({ propsKeys: ["gridAutoFlow", "gaf"] }) // Grid Area export type GridAreaValue = C.GridAreaProperty export type GridAreaProp = T.Prop<GridAreaValue> export interface GridAreaProps extends T.ThemeProps { gridArea?: GridAreaProp ga?: GridAreaProp } export interface GridAreaStyle extends T.Style { gridArea?: GridAreaValue } export const gridArea = style<GridAreaProps, GridAreaStyle>({ propsKeys: ["gridArea", "ga"] }) // Grid Row export type GridRowValue = C.GridRowProperty export type GridRowProp = T.Prop<GridRowValue> export interface GridRowProps extends T.ThemeProps { gridRow?: GridRowProp gr?: GridRowProp } export interface GridRowStyle extends T.Style { gridRow?: GridRowValue } export const gridRow = style<GridRowProps, GridRowStyle>({ propsKeys: ["gridRow", "gr"] }) // Grid Row Start export type GridRowStartValue = C.GridRowStartProperty export type GridRowStartProp = T.Prop<GridRowStartValue> export interface GridRowStartProps extends T.ThemeProps { gridRowStart?: GridRowStartProp grs?: GridRowStartProp } export interface GridRowStartStyle extends T.Style { gridRowStart?: GridRowStartValue } export const gridRowStart = style<GridRowStartProps, GridRowStartStyle>({ propsKeys: ["gridRowStart", "grs"] }) // Grid Row End export type GridRowEndValue = C.GridRowEndProperty export type GridRowEndProp = T.Prop<GridRowEndValue> export interface GridRowEndProps extends T.ThemeProps { gridRowEnd?: GridRowEndProp gre?: GridRowEndProp } export interface GridRowEndStyle extends T.Style { gridRowEnd?: GridRowEndValue } export const gridRowEnd = style<GridRowEndProps, GridRowEndStyle>({ propsKeys: ["gridRowEnd", "gre"] }) // Grid Column export type GridColumnValue = C.GridColumnProperty export type GridColumnProp = T.Prop<GridColumnValue> export interface GridColumnProps extends T.ThemeProps { gridColumn?: GridColumnProp gc?: GridColumnProp } export interface GridColumnStyle extends T.Style { gridColumn?: GridColumnValue } export const gridColumn = style<GridColumnProps, GridColumnStyle>({ propsKeys: ["gridColumn", "gc"] }) // Grid Column Start export type GridColumnStartValue = C.GridColumnStartProperty export type GridColumnStartProp = T.Prop<GridColumnStartValue> export interface GridColumnStartProps extends T.ThemeProps { gridColumnStart?: GridColumnStartProp gcs?: GridColumnStartProp } export interface GridColumnStartStyle extends T.Style { gridColumnStart?: GridColumnStartValue } export const gridColumnStart = style< GridColumnStartProps, GridColumnStartStyle >({ propsKeys: ["gridColumnStart", "gcs"] }) // Grid Column End export type GridColumnEndValue = C.GridColumnEndProperty export type GridColumnEndProp = T.Prop<GridColumnEndValue> export interface GridColumnEndProps extends T.ThemeProps { gridColumnEnd?: GridColumnEndProp gce?: GridColumnEndProp } export interface GridColumnEndStyle extends T.Style { gridColumnEnd?: GridColumnEndValue } export const gridColumnEnd = style<GridColumnEndProps, GridColumnEndStyle>({ propsKeys: ["gridColumnEnd", "gce"] }) // Grid Parent Set export type GridParentSetProps = DisplayProps & PlaceItemsProps & PlaceContentProps & AlignItemsProps & AlignContentProps & JustifyItemsProps & JustifyContentProps & GridProps & GridTemplateProps & GridTemplateRowsProps & GridTemplateColumnsProps & GridTemplateAreasProps & GridGapProps & GridRowGapProps & GridColumnGapProps & GridAutoRowsProps & GridAutoColumnsProps & GridAutoFlowProps export type GridParentSetStyle = DisplayStyle & PlaceItemsStyle & PlaceContentStyle & AlignItemsStyle & AlignContentStyle & JustifyItemsStyle & JustifyContentStyle & GridStyle & GridTemplateStyle & GridTemplateRowsStyle & GridTemplateColumnsStyle & GridTemplateAreasStyle & GridGapStyle & GridRowGapStyle & GridColumnGapStyle & GridAutoRowsStyle & GridAutoColumnsStyle & GridAutoFlowStyle export const gridParentSet = compose<GridParentSetProps, GridParentSetStyle>({ name: "gridParent", renderers: [ display, placeItems, placeContent, alignItems, alignContent, justifyItems, justifyContent, grid, gridTemplate, gridTemplateRows, gridTemplateColumns, gridTemplateAreas, gridGap, gridRowGap, gridColumnGap, gridAutoRows, gridAutoColumns, gridAutoFlow ] }) // Grid Child Set export type GridChildSetProps = PlaceSelfProps & AlignSelfProps & JustifySelfProps & GridAreaProps & GridRowProps & GridRowStartProps & GridRowEndProps & GridColumnProps & GridColumnStartProps & GridColumnEndProps export type GridChildSetStyle = PlaceSelfStyle & AlignSelfStyle & JustifySelfStyle & GridAreaStyle & GridRowStyle & GridRowStartStyle & GridRowEndStyle & GridColumnStyle & GridColumnStartStyle & GridColumnEndStyle export const gridChildSet = compose<GridChildSetProps, GridChildSetStyle>({ name: "gridChild", renderers: [ placeSelf, alignSelf, justifySelf, gridArea, gridRow, gridRowStart, gridRowEnd, gridColumn, gridColumnStart, gridColumnEnd ] }) // Grid Set export type GridSetProps = GridParentSetProps & GridChildSetProps export type GridSetStyle = GridParentSetStyle & GridChildSetStyle export const gridSet = compose<GridSetProps, GridSetStyle>({ name: "grid", renderers: [gridParentSet, gridChildSet] })
the_stack
import {dirname, basename, extname} from 'path'; import camelCase from 'camelcase'; import * as t from '@babel/types'; import traverse, {NodePath} from '@babel/traverse'; import MigrationReporter from './migration_reporter'; import shouldMigrateFilePath from './should_migrate_file_path'; import * as allowlists from './allowlists'; import isBabelInteropDefaultImportTheSame from './babel_interop_default_import'; export default function migrateToEsModules( reporter: MigrationReporter, filePath: string, file: t.File, ) { traverse(file, { Program: { exit(path) { // Check to see if any side-effects will be broken by hoisted ES Modules. if (shouldMigrateFilePath(filePath)) { doesProgramHaveSideEffectsBeforeImports({ reporter, filePath, program: path.node, }); } }, }, DirectiveLiteral(path) { // ES Modules are implicitly in strict mode so we don’t need the directive anymore. if (shouldMigrateFilePath(filePath)) { if (path.node.value === 'use strict') { path.parentPath.remove(); } } }, Identifier(path) { // Don’t visit the same node twice. Fixes an infinite recursion error. if ((path.node as any)[visited]) return; (path.node as any)[visited] = true; // Handle any reference to the Node.js `require` identifier: if (path.node.name === 'require') { if (path.parent.type !== 'CallExpression') { reporter.requireNotCalled(filePath, path.node.loc!); } else { if (path.parent.arguments.length !== 1) { throw new Error(`Expected require() calls to only have one argument.`); } const moduleId = path.parent.arguments[0]; if (moduleId.type !== 'StringLiteral') { reporter.requireOtherThanString(filePath, moduleId.loc!); } else { // Resolve the full path to a module using the Node.js // resolution algorithm. let modulePath; try { modulePath = require.resolve( moduleId.value, {paths: [dirname(filePath)]}, ); } catch (error) { reporter.cannotFindModule(moduleId.value, filePath, moduleId.loc!); modulePath = null; } // If we were able to resolve the module path... if (modulePath !== null) { const callPath = path.parentPath; if (callPath.node.type !== 'CallExpression') { throw new Error('Expected above conditions to prove this is a call expression.'); } if (shouldMigrateFilePath(filePath)) { migrateRequireToImport({ reporter, path, callPath: callPath as NodePath<t.CallExpression>, moduleId, modulePath, }); } else { // Modules with custom handling should not be used outside of // migrated modules. if (allowlists.modulesWithNamedExports.has(moduleId.value)) { throw new Error( 'Did not expect a named exports module to be used in a ' + 'file that is not migrated.' ); } // If we are not a module which will be transpiled by Babel, but we // are importing a transpiled module then we need to add `.default` // to the require. if (shouldMigrateFilePath(modulePath)) { replaceWith(callPath, t.memberExpression( callPath.node, t.identifier('default'), )); } } } } } } // Handle any reference to the Node.js `module` identifier: if (path.node.name === 'module') { const {node, parent} = path; if ( // If someone has locally declared a module variable, that’s fine. path.scope.hasBinding('module') || // Object property access is fine. (parent.type === 'ObjectProperty' && parent.key === node) || (parent.type === 'MemberExpression' && parent.computed === false && parent.property === node) || (parent.type === 'ObjectTypeProperty' && parent.key === node) ) { // Use of `module` that is not dangerous to our migration script. We can // ignore it. } else if (!( isModuleExports(parent) && path.parentPath.parent.type === 'AssignmentExpression' && path.parentPath.parent.left === parent && path.parentPath.parentPath.parent.type === 'ExpressionStatement' && path.parentPath.parentPath.parentPath.parent.type === 'Program' )) { reporter.moduleNotExportAssignment(filePath, node.loc!); } else { if (shouldMigrateFilePath(filePath)) { const assignmentPath = path // `Identifier` .parentPath // `MemberExpression` .parentPath; // `AssignmentExpression` if (assignmentPath.node.type !== 'AssignmentExpression') { throw new Error(`Expected above conditions to prove this is an assignment expression.`); } const statementPath = assignmentPath // `AssignmentExpresison` .parentPath; // `ExpressionStatement` // Workaround a bug in Recast that drops parentheses around type // cast expressions by rebuilding the AST node. let exportExpression = assignmentPath.node.right; if (exportExpression.type === 'TypeCastExpression') { exportExpression = t.typeCastExpression( exportExpression.expression, exportExpression.typeAnnotation, ); } // Actually replace `module.exports` with `export default`! replaceWith( statementPath, t.exportDefaultDeclaration(exportExpression), ); } } } // Handle any reference to the Node.js `exports` identifier: if (path.node.name === 'exports') { const {node, parent} = path; if (!isModuleExports(parent)) { reporter.moduleNotExportAssignment(filePath, node.loc!); } } }, }); } const visited = Symbol('visited'); function isModuleExports(node: t.Node): boolean { return ( node.type === 'MemberExpression' && node.computed === false && node.object.type === 'Identifier' && node.object.name === 'module' && node.property.type === 'Identifier' && node.property.name === 'exports' ); } function migrateRequireToImport({ reporter, path, callPath, moduleId, modulePath, }: { path: NodePath<t.Identifier>, reporter: MigrationReporter, callPath: NodePath<t.CallExpression>, moduleId: t.StringLiteral, modulePath: string, }) { // Determine if we should use a default or namespace import. We always use a default import for // migrated files. We load the module in our worker process to determine whether we should use // a default or namespace import. let defaultImport: boolean; if (shouldMigrateFilePath(modulePath)) { defaultImport = true; } else { const sameBabelInteropDefaultImport = isBabelInteropDefaultImportTheSame(modulePath); // If we were not able to load this module then don’t migrate this require! if (sameBabelInteropDefaultImport === null) { reporter.unableToLoadExternalModule(modulePath); return; } defaultImport = sameBabelInteropDefaultImport; } const moduleWithNamedExport = allowlists.modulesWithNamedExports.get(moduleId.value); // A common pattern is `const foo = require('bar').foo`. To make this pattern work better with // our migration tooling we convert it to `const {foo} = require('bar')` before processing // the require. if ( callPath.parent.type === 'MemberExpression' && callPath.parent.computed === false && callPath.parentPath.parent.type === 'VariableDeclarator' && callPath.parentPath.parent.id.type === 'Identifier' ) { const key = callPath.parent.property; const value = callPath.parentPath.parent.id; replaceWith(callPath.parentPath.parentPath, t.variableDeclarator( t.objectPattern([t.objectProperty(key, value, false, key.name === value.name)]), callPath.node, )); // Make sure to re-visit this node now that we’ve transformed it! (callPath.node.callee as any)[visited] = false; return; } // If we are in a file which should be migrated, and we have a top level require then change it // to an import declaration. if ( callPath.parent.type === 'VariableDeclarator' && callPath.parentPath.parent.type === 'VariableDeclaration' && callPath.parentPath.parentPath.parent.type === 'Program' ) { if (callPath.parentPath.parent.declarations.length !== 1) { throw new Error('Expected there to only be one variable declarator.'); } const importPattern = callPath.parent.id; if (moduleWithNamedExport === undefined) { // If we are importing to an identifier we can replace the require with an // import statement. // // Otherwise we create a temporary variable that we destructure. if (importPattern.type === 'Identifier' && !importPattern.typeAnnotation) { replaceWith(callPath.parentPath.parentPath, t.importDeclaration( [defaultImport ? t.importDefaultSpecifier(importPattern) : t.importNamespaceSpecifier(importPattern)], moduleId, )); } else if (importPattern.type === 'ObjectPattern' && defaultImport === false) { // If this is not a default import module and we have an object destructure then // trust that each key is a valid named import! const importSpecifiers = importPattern.properties.map(property => { if (property.type !== 'ObjectProperty') throw new Error(`Unexpected AST node: '${property.type}'`); if (property.computed !== false) throw new Error(`Expected object property key to not be computed.`); if (property.value.type !== 'Identifier') throw new Error(`Unexpected AST node: '${property.value.type}'`); if (property.key.name === 'default') { return t.importDefaultSpecifier(property.value); } else { return t.importSpecifier(property.value, property.key); } }); replaceWith(callPath.parentPath.parentPath, t.importDeclaration( importSpecifiers, moduleId, )); } else { reporter.requireWasDestructed(modulePath); // If we are destructuring the import then we need to add a level of indirection. const moduleName = camelCase(basename(moduleId.value, extname(moduleId.value))); const tmpIdentifier = path.scope.generateUidIdentifier(moduleName); const destructVariableDeclaration = t.variableDeclaration('const', [ t.variableDeclarator(importPattern, tmpIdentifier), ]); // Special flag for our Recast fork... (destructVariableDeclaration as any).recastDisableMultilineSpacing = true; replaceWithMultipleCopyingComments(callPath.parentPath.parentPath, [ t.importDeclaration( [defaultImport ? t.importDefaultSpecifier(tmpIdentifier) : t.importNamespaceSpecifier(tmpIdentifier)], moduleId, ), destructVariableDeclaration, ]); } } else { if (importPattern.type === 'Identifier') { // Default imports for a module we give named exports has various // special behaviors... switch (moduleWithNamedExport.defaultImport) { case 'defaultExport': { replaceWith(callPath.parentPath.parentPath, t.importDeclaration( [t.importDefaultSpecifier(importPattern)], moduleId, )); break; } case 'namespaceImport': { replaceWith(callPath.parentPath.parentPath, t.importDeclaration( [t.importNamespaceSpecifier(importPattern)], moduleId, )); break; } case 'none': throw new Error(`Did not expect '${moduleId.value}' to have a default import.`); default: { const never: never = moduleWithNamedExport.defaultImport; throw new Error(`Unexpected: '${never}'`); } } } else if (importPattern.type === 'ObjectPattern') { // Transform a simple object destructuring into a named import. const importSpecifiers = importPattern.properties.map(property => { if (property.type !== 'ObjectProperty') throw new Error(`Unexpected AST node: '${property.type}'`); if (property.computed !== false) throw new Error(`Expected object property key to not be computed.`); if (property.value.type !== 'Identifier') throw new Error(`Unexpected AST node: '${property.value.type}'`); if (!moduleWithNamedExport.exports.has(property.key.name)) throw new Error(`Unexpected import '${property.key.name}' from '${moduleId.value}'`); return t.importSpecifier(property.value, property.key); }); replaceWith(callPath.parentPath.parentPath, t.importDeclaration( importSpecifiers, moduleId, )); } else { throw new Error(`Unexpected AST node: '${importPattern.type}'`); } } } else if ( callPath.parent.type === 'ExpressionStatement' && callPath.parentPath.parent.type === 'Program' ) { // Imports only for side effects are also converted into import declarations. replaceWith(callPath.parentPath, t.importDeclaration([], moduleId)); } else { if (moduleWithNamedExport === undefined) { // If we are not requiring at the top level, but we are importing a transpiled module then // we need to add `.default` to the require. // // TODO: Report these for manual fixes! if (shouldMigrateFilePath(modulePath)) { replaceWith<t.Expression>(callPath, t.memberExpression( callPath.node, t.identifier('default'), )); } } else { switch (moduleWithNamedExport.defaultImport) { case 'defaultExport': { // They still have a default export... replaceWith<t.Expression>(callPath, t.memberExpression( callPath.node, t.identifier('default'), )); break; } case 'namespaceImport': { // We can leave these alone... break; } case 'none': throw new Error(`Did not expect '${moduleId.value}' to have a default import.`); default: { const never: never = moduleWithNamedExport.defaultImport; throw new Error(`Unexpected: '${never}'`); } } } } } /** * Checks to see if the program does some side effects before imports that the imported module might * depend on. Babel hoists imports to the top so these side effects will break. */ function doesProgramHaveSideEffectsBeforeImports({ reporter, filePath, program, }: { reporter: MigrationReporter, filePath: string, program: t.Program, }) { let importZone = true; for (const statement of program.body) { if ( statement.type === 'ImportDeclaration' && (!statement.importKind || statement.importKind === 'value') ) { if (importZone === false && statement.loc) { reporter.importAfterSideEffects(filePath, statement.loc); break; } } if (statementHasSideEffects(statement)) { importZone = false; } } } /** * Conservative check for whether a statement has any side-effects that should be executed before * an import. */ function statementHasSideEffects(statement: t.Statement): boolean { if (statement.type === 'ImportDeclaration') { return false; } if (statement.type === 'ExpressionStatement') { return expressionHasSideEffects(statement.expression); } if (statement.type === 'VariableDeclaration') { for (const declarator of statement.declarations) { if (declarator.init && expressionHasSideEffects(declarator.init)) { return true; } } return false; } return true; } /** * Conservative check for whether an expression has any side-effects that should be executed before * an import. */ function expressionHasSideEffects(expression: t.Expression): boolean { if (t.isLiteral(expression)) { return false; } if (expression.type === 'Identifier') { return false; } if (expression.type === 'MemberExpression') { // Technically a getter could have a side-effect, but it’s pretty uncommon that we’d have // a getter with a signfificant side-effect. return ( expressionHasSideEffects(expression.object) || expressionHasSideEffects(expression.property) ); } return true; } /** * Recast uses a different format for comments. We need to manually copy them over to the new node. * We also attach the old location so that Recast prints it at the same place. * * https://github.com/benjamn/recast/issues/572 */ function replaceWith<T extends t.Node>(path: NodePath<T>, node: T) { node.loc = path.node.loc; if ((path.node as any).comments) { (node as any).comments = (path.node as any).comments; delete (path.node as any).comments; } path.replaceWith(node); } /** * Recast uses a different format for comments. We need to manually copy them over to the new node. * We also attach the old location so that Recast prints it at the same place. * * https://github.com/benjamn/recast/issues/572 */ function replaceWithMultipleCopyingComments<T extends t.Node>(path: NodePath<T>, nodes: Array<T>) { if (nodes.length === 0) throw new Error('Unsupported'); if ((path.node as any).comments) { (nodes as any)[0].comments = (path.node as any).comments; delete (path.node as any).comments; } path.replaceWithMultiple(nodes); }
the_stack
import { Inject, Injectable, InjectionToken } from '@angular/core'; import * as LocalForage from 'localforage'; import 'localforage'; import IdleQueue from 'custom-idle-queue'; import { PoLokiDriver } from '../drivers/lokijs/po-loki-driver'; import { PoStorageConfig } from './po-storage-config.interface'; export const PO_STORAGE_CONFIG_TOKEN = new InjectionToken('PO_STORAGE_CONFIG_TOKEN'); /** * @description * * O PO Storage é uma biblioteca que fornece um serviço para armazenamento de dados no dispositivo local, sendo semelhante * ao funcionamento do [IonicStorage](https://ionicframework.com/docs/storage/). * É possível utilizar os drivers [Websql](https://dev.w3.org/html5/webdatabase/), [Indexeddb](https://www.w3.org/TR/IndexedDB/), * [LocalStorage](https://html.spec.whatwg.org/multipage/webstorage.html) e também [LokiJS](https://github.com/techfort/LokiJS/wiki). * * Para um melhor ganho de performance ao buscar e salvar dados, recomendamos a utilização do `LokiJS`, um *database* * orientado a documento semelhante ao MongoDB, que além de permitir a persistência dos dados no dispositivo possibilita * também o armazenamento dos dados em memória. Outra vantagem, é o aumento do limite de armazenamento para * aproximadamente `300mb`. * * A estrutura utilizada para armazenar os dados é a de chave/valor, onde uma chave funciona como um identificador exclusivo. * * #### Instalando o PO Storage * * Para instalar o `po-storage` em sua aplicação execute o seguinte comando: * * ```shell * ng add @po-ui/ng-storage * ``` * Será instalado o pacote `@po-ui/ng-storage` e também já importará `PoStorageModule` no módulo principal da sua aplicação, conforme abaixo: * * ```typescript * import { PoStorageModule } from '@po-ui/ng-storage'; * * @NgModule({ * declarations: [...], * imports: [ * // Importação do módulo PoStorageModule * PoStorageModule.forRoot(), * ], * bootstrap: [IonicApp], * providers: [...] * }) * export class AppModule {} * ``` * * Com a declaração do módulo, é criada uma base de dados no armazenamento local e o serviço `PoStorageService` estará * pronto para ser utilizada na sua aplicação. * * #### Configurando as opções de armazenamento * * Na importação do módulo, o método `PoStorageModule.forRoot()` pode receber como parâmetro um objeto do tipo * [`PoStorageConfig`](documentation/po-storage#po-storage-config), * que serve para configurar as opções personalizadas do armazenamento, como por exemplo: o tipo de armazenamento * preferêncial. * * Caso não seja passada nenhuma configuração a ordem padrão será: ['websql', 'indexeddb', 'localstorage', 'lokijs']. * * Abaixo segue um exemplo de configuração onde o storage preferencial passa a ser o `lokijs`: * * ```typescript * import { PoStorageModule } from '@po-ui/ng-storage'; * * @NgModule({ * declarations: [...], * imports: [ * // Importação do módulo PoStorageModule com a configuração personalizada * PoStorageModule.forRoot({ * name: 'mystorage', * storeName: '_mystore', * driverOrder: ['lokijs', 'websql', 'indexeddb', 'localstorage'] * }), * ], * bootstrap: [IonicApp], * providers: [...] * }) * export class AppModule {} * ``` */ @Injectable() export class PoStorageService { private driver: string = null; private idleQueue = new IdleQueue(); private storagePromise: Promise<LocalForage>; private lokijsDriver: PoLokiDriver; constructor(@Inject(PO_STORAGE_CONFIG_TOKEN) config?: PoStorageConfig) { this.lokijsDriver = new PoLokiDriver(); this.setStoragePromise(config); } /** * Retorna a configuração padrão para o armazenamento. Caso nenhuma configuração seja inserida, * essa configuração será utilizada. * * @returns {PoStorageConfig} Objeto com a configuração padrão do armazenamento. */ static getDefaultConfig(): PoStorageConfig { return { name: '_postorage', storeName: '_pokv', driverOrder: ['websql', 'indexeddb', 'localstorage', 'lokijs'] }; } /** * Cria uma instância do `PoStorageService` com a configuração de armazenamento passada como parâmetro. * * @param {PoStorageConfig} storageConfig Configuração para o armazenamento. * @returns {PoStorageService} Instância do `PoStorageService`. */ static providePoStorage(storageConfig?: PoStorageConfig): PoStorageService { return new PoStorageService(PoStorageService.getConfig(storageConfig)); } private static getConfig(storageConfig?: PoStorageConfig) { return storageConfig || PoStorageService.getDefaultConfig(); } /** * Busca uma lista armazenada pela chave e concatena com a lista passada por parâmetro. * * Por exemplo: * * ``` typescript * const clients = [ { name: 'Marie', age: 23 }, { name: 'Pether', age: 39 }]; * * this.poStorageService.set('clientKey', clients).then(() => {}); * * ... * * const newClients = [ { name: 'Lisa', age: 36 }, { name: 'Bruce', age: 18 } ]; * * this.poStorageService.appendArrayToArray('clientKey', newClients).then(() => { * // A lista agora será: * // [ { name: 'Marie', age: 23 }, { name: 'Pether', age: 39 }, { name: 'Lisa', age: 36 }, { name: 'Bruce', age: 18 }]; * }); * ``` * * @param {string} key Chave da lista armazenada. * @param {Array} value Lista que será concatenada. * * @returns {Promise<any>} Promessa que é resolvida após as duas listas serem concatenadas e armazenadas localmente. */ async appendArrayToArray(key: string, value: Array<any>): Promise<any> { const data = await this.getArrayOfStorage(key); const newData = [...data, ...value]; return this.set(key, newData); } /** * Acrescenta um item em uma lista armazenada pela chave. * * @param {string} key Chave da lista armazenada. * @param {Array} value Item que será acrescentado na lista. * * @returns {Promise<any>} Promessa que é resolvida após o item ser acrescentado na lista armazenada. */ async appendItemToArray(key: string, value: any): Promise<any> { const data = await this.getArrayOfStorage(key); data.push(value); return this.set(key, data); } /** * Remove todos os itens da base de dados local configurada na declaração do módulo `PoStorageModule`. * * > Utilize este método com cautela, para evitar a perda indesejada de dados. * * @returns {Promise<void>} Promessa que é resolvida após todos os itens da base de dados local serem removidos. */ clear(): Promise<void> { return this.storagePromise.then(store => store.clear()); } /** * Verifica se existe um valor dentro de uma determinada chave. * * @param {string} key Chave que será verificada. * * @returns {Promise<boolean>} Promessa que é resolvida quando a verificação da existência do valor na chave é concluída. */ exists(key: string): Promise<boolean> { return this.get(key).then(data => Promise.resolve(data !== null)); } /** * Itera sobre todas as chaves armazenadas. * * @param {any} iteratorCallback Função de `callback` que é chamada a cada iteração, com os seguintes parâmetros: * valor, chave e número da iteração. * * Exemplo de utilização: * * ``` typescript * this.poStorageService.forEach((value: any, key: string, iterationNumber: number) => { * // Iteração sobre cada chave armazenada. * }); * ``` * * @returns {Promise<void>} Promessa que é resolvida após a iteração sobre todas as chaves armazenadas. */ forEach(iteratorCallback: (value: any, key: string, iterationNumber: number) => any): Promise<void> { return this.storagePromise.then(store => store.iterate(iteratorCallback)); } /** * Retorna o valor armazenado em uma determinada chave. * * @param {string} key Chave que identifica o item. * @param {boolean} lock Define se irá travar a leitura e a escrita da base de dados para não ser acessada de forma paralela. * Caso outra leitura/escrita já tenha sido iniciada, este método irá esperar o outro terminar para então começar. * * Padrão: `false`. * * > Esta definição só será válida se o outro acesso paralelo a este método também estiver com o parâmetro *lock* ativado. * @returns {Promise<any>} Promessa que é resolvida após o item ser buscado. */ async get(key: string, lock: boolean = false): Promise<any> { if (lock) { await this.requestIdlePromise(); return await this.idleQueue.wrapCall(async () => { await this.getImmutableItem(key); }); } return await this.getImmutableItem(key); } /** * Retorna o nome do *driver* que está sendo usado para armazenar os dados, por exemplo: localStorage. * * @returns {string | null} Nome do *driver*. */ getDriver(): string { return this.driver; } /** * Retorna o primeiro item de uma lista para uma determinada chave. * * @param {string} key Chave da lista. * @returns {Promise<any>} Promessa que é resolvida após o primeiro item ser encontrado. */ getFirstItem(key: string): Promise<any> { return this.get(key).then((data: Array<any>) => Promise.resolve(data ? data[0] : null)); } /** * Remove o primeiro item de uma lista a partir da chave. * * @param {string} key Chave da lista que será removido o primeiro item. * @returns {Promise<any>} Promessa que é resolvida após o primeiro item da lista ser removido. */ getItemAndRemove(key: string): Promise<any> { return this.get(key).then((data: Array<any>) => { if (data === null) { return null; } const item = data.shift(); return this.set(key, data).then(() => Promise.resolve(item)); }); } /** * Busca o primeiro objeto encontrado dentro de uma lista pelo do valor de um campo. * * Por exemplo: * * ``` typescript * const clients = [ { name: 'Marie', age: 23 }, { name: 'Pether', age: 39 }]; * * this.poStorageService.set('clientKey', clients).then(() => {}); * * ... * * this.poStorageService.getItemByField('clientKey', 'name', 'Marie').then(client => { * // Resultado do console.log: { name: 'Marie', age: 23 } * console.log(client); * }); * ``` * * @param {string} key Chave da lista. * @param {string} fieldName O campo a ser filtrado. * @param {any} fieldValue O valor do campo. * @returns {Promise<any>} Promessa que é resolvida com o item que foi encontrado. */ getItemByField(key: string, fieldName: string, fieldValue: any): Promise<any> { return this.get(key).then((storageRecords: Array<any>) => { let storageRecordsFiltered = storageRecords.find(storageRecord => storageRecord[fieldName] === fieldValue); storageRecordsFiltered = storageRecordsFiltered || null; return Promise.resolve(storageRecordsFiltered); }); } /** * Lista com todas as chaves armazenadas. * * @returns {Promise<Array<string>>} Promessa que é resolvida com todas as chaves armazenadas. */ keys(): Promise<Array<string>> { return this.storagePromise.then(store => store.keys()); } /** * Quantidade de chaves armazenadas. * * @returns {Promise<number>} Promessa que é resolvida com o número de chaves armazenadas. */ length(): Promise<number> { return this.storagePromise.then(store => store.length()); } /** * Utilizado para gerenciar o bloqueio e desbloqueio de recursos no `PoStorageService`. * Aguardando a liberação da utilização dos recursos que participam deste comportamento e posteriormente envolve o recurso * passado como parâmetro em um comportamento de bloqueio e desbloqueio. * * Este método se comporta igual a utilização em conjunta dos métodos: `PoStorageService.requestIdlePromise()`, * `PoStorageService.lock()` e `PoStorageService.unlook()`. * * Veja mais no método: [`PoStorage.requestIdlePromise()`](documentation/po-storage#request-idle-promise). * * @param {Function} limitedResource Função que será envolvida no comportamento de bloqueio e desbloqueio. */ async limitedCallWrap(limitedResource: Function): Promise<any> { await this.requestIdlePromise(); return this.idleQueue.wrapCall(limitedResource); } /** * Incrementa um valor na fila de bloqueio do `PoStorageService`. Utilizado juntamente com o método `unlock` para poder * controlar a execução de uma determinada tarefa com o `PoStorage.requestIdlePromise()`. * * Veja mais no método: [`PoStorage.requestIdlePromise()`](documentation/po-storage#request-idle-promise). */ lock() { this.idleQueue.lock(); } /** * Determina se o processo de inicialização do *driver* assíncrono foi concluído. * * @returns {Promise<LocalForage>} Promessa que é resolvida quando o processo de inicialização do *driver* assíncrono * for concluído. */ ready(): Promise<LocalForage> { return this.storagePromise; } /** * Remove um valor associado a uma chave. * * @param {key} key Chave do valor que será removido. * @returns {Promise<any>} Promessa que é resolvida após o valor ser removido. */ remove(key: string): Promise<any> { return this.storagePromise.then(store => store.removeItem(key)); } /** * Remove uma propriedade de um objeto armazenado. * * @param {string} key Chave do objeto armazenado. * @param {string} property Propriedade que será removida. * * @returns {Promise<any>} Promessa que é resolvida após a propriedade ser removida. */ async removeIndexFromObject(key: string, property: string): Promise<any> { const data = await this.getObjectOfStorage(key); delete data[property]; return this.set(key, data); } /** * Remove um objeto de uma lista armazenada pelo valor de uma propriedade. * * Por exemplo: * * ``` typescript * const clients = [ { name: 'Marie', age: 23 }, { name: 'Pether', age: 39 }]; * * this.poStorageService.set('clientKey', clients).then(() => {}); * * ... * * this.poStorageService.removeItemFromArray('clientKey', 'name', 'Marie').then(() => { * // O objeto { name: 'Marie', age: 23 } foi removido da lista que está na chave 'clientKey' * }); * ``` * * @param {string} key Chave da lista que contém o item que será removido. * @param {string} field O campo a ser filtrado no item. * @param {string} value O valor do filtro. * @returns {Promise<any>} Promessa que é resolvida quando o objeto for removido da lista. */ async removeItemFromArray(key: string, field: string, value: any): Promise<any> { let data = await this.getArrayOfStorage(key); data = data.filter(item => item[field] !== value); return this.set(key, data); } /** * <a id="request-idle-promise"></a> * Método que verifica se o acesso a base de dados configurada está liberado. * * Utilizado em conjunto com os métodos `lock()` e `unlock()` entre tarefas que não podem ser executadas de forma * paralela, para não causar inconsistências nos dados. * * Exemplo de utilização: * * ``` * // Aguarda a liberação para continuar * await this.poStorage.requestIdlePromise(); * * this.poStorage.lock(); * * // Executa uma tarefa que irá ler e/ou escrever na base de dados configurada. * * this.poStorage.unlock(); * ``` * * > É importante sempre utilizá-lo antes de executar os métodos `lock()` e `unlock()` para garantir que a tarefa só * será executada caso o acesso esteja livre. * * @returns {Promise<any>} Promessa que é resolvida quando o acesso a base de dados configurada estiver liberado. */ requestIdlePromise(): Promise<any> { return this.idleQueue.requestIdlePromise(); } /** * Grava um valor em uma determinada chave. * * @param {string} key Chave para o valor que será gravado. * @param {any} value Valor que será gravado. * @param {boolean} lock Define se irá travar a leitura e a escrita da base de dados para não ser acessada de forma paralela. * Caso outra leitura/escrita já tenha sido iniciada, este método irá esperar o outro terminar para então começar. * * Padrão: `false`. * * > Esta definição só será válida se o outro acesso paralelo a este método também estiver com o parâmetro *lock* ativado. * @returns {Promise<any>} Promessa que é resolvida após o valor ter sido gravado. */ async set(key: string, value: any, lock: boolean = false): Promise<any> { const store = await this.storagePromise; const newValue = typeof value === 'object' ? JSON.parse(JSON.stringify(value)) : value; if (lock) { await this.requestIdlePromise(); return this.idleQueue.wrapCall(() => store.setItem(key, newValue)); } return store.setItem(key, newValue); } /** * Atribui um valor a uma propriedade de um objeto armazenado pela chave. * * Por exemplo: * * ``` typescript * const clients = [ { name: 'Marie', age: 23 }, { name: 'Pether', age: 39 }]; * * this.poStorageService.set('clientKey', clients).then(() => {}); * * ... * * this.poStorageService.setIndexToObject('clientKey', 'name', 'Clare').then(() => { * // O objeto { name: 'Marie', age: 23 } passa a ser { name: 'Clare', age: 23 } * }); * ``` * * @param {string} key Chave do objeto. * @param {string} property Nome da propriedade do objeto. * @param {any} value Valor que será gravado na propriedade do objeto. */ async setIndexToObject(key: string, property: string, value: any): Promise<any> { const data = await this.getObjectOfStorage(key); data[property] = value; return this.set(key, data); } /** * Decrementa um valor na fila de bloqueio. Utilizado juntamente com o método `lock` para poder * controlar a execução de uma determinada tarefa com o `PoStorage.requestIdlePromise()`. * * Veja mais no método: [`PoStorage.requestIdlePromise()`](documentation/po-storage#request-idle-promise). */ unlock() { this.idleQueue.unlock(); } private async getArrayOfStorage(key: string) { const data = await this.get(key); return data || []; } private async getImmutableItem(key: string) { const store = await this.storagePromise; const items = await store.getItem(key); return items ? JSON.parse(JSON.stringify(items)) : null; } private async defineLocalForageDriver(localForageInstance: any, driverOrder) { await localForageInstance.defineDriver(this.lokijsDriver.getDriver()); await this.setDriver(localForageInstance, driverOrder); return localForageInstance; } private getDriverOrder(driverOrder: Array<string>): Array<string> { return driverOrder.map(driver => { switch (driver) { case 'indexeddb': return LocalForage.INDEXEDDB; case 'websql': return LocalForage.WEBSQL; case 'localstorage': return LocalForage.LOCALSTORAGE; default: return driver; } }); } private async getObjectOfStorage(key: string) { const data = await this.get(key); return data || {}; } private async setDriver(localForageInstance: LocalForage, driverOrder) { await localForageInstance.setDriver(this.getDriverOrder(driverOrder)); this.driver = localForageInstance.driver(); } private setStoragePromise(config: PoStorageConfig) { this.storagePromise = this.getStorageInstance(config); } private async getStorageInstance(config: PoStorageConfig) { const defaultConfig = PoStorageService.getDefaultConfig(); const actualConfig = Object.assign(defaultConfig, config || {}); const localForageInstance = LocalForage.createInstance(actualConfig); try { return await this.defineLocalForageDriver(localForageInstance, actualConfig.driverOrder); } catch { throw new Error(`Cannot use this drivers: ${actualConfig.driverOrder.join(', ')}.`); } } }
the_stack
import {get as getBrowserGlobals} from 'app/client/lib/browserGlobals'; import {guessTimezone} from 'app/client/lib/guessTimezone'; import {getWorker} from 'app/client/models/gristConfigCache'; import * as gutil from 'app/common/gutil'; import {addOrgToPath, docUrl, getGristConfig} from 'app/common/urlUtils'; import {UserAPI, UserAPIImpl} from 'app/common/UserAPI'; import {Events as BackboneEvents} from 'backbone'; import {Disposable} from 'grainjs'; const G = getBrowserGlobals('window'); const reconnectInterval = [1000, 1000, 2000, 5000, 10000]; // Time that may elapse prior to triggering a heartbeat message. This is a message // sent in order to keep the websocket from being closed by an intermediate load // balancer. const HEARTBEAT_PERIOD_IN_SECONDS = 45; // Find the correct worker to connect to for the currently viewed doc, // returning a base url for endpoints served by that worker. The url // may need to change again in future. async function getDocWorkerUrl(assignmentId: string|null): Promise<string|null> { // Currently, a null assignmentId happens only in classic Grist, where the server // never changes. if (assignmentId === null) { return docUrl(null); } const api: UserAPI = new UserAPIImpl(getGristConfig().homeUrl!); return getWorker(api, assignmentId); } /** * Settings for the Grist websocket connection. Includes timezone, urls, and client id, * and various services needed for the connection. */ export interface GristWSSettings { // A factory function for creating the WebSocket so that we can use from node // or browser. makeWebSocket(url: string): WebSocket; // A function for getting the timezone, so the code can be used outside webpack - // currently a timezone library is lazy loaded in a way that doesn't quite work // with ts-node. getTimezone(): Promise<string>; // Get the page url - this is how the organization is currently determined. getPageUrl(): string; // Get the URL for the worker serving the given assignmentId (which is usually a docId). getDocWorkerUrl(assignmentId: string|null): Promise<string|null>; // Get an id associated with the client, null for "no id set yet". getClientId(assignmentId: string|null): string|null; // Get selector for user, so if cookie auth allows multiple the correct one will be picked. // Selector is currently just the email address. getUserSelector(): string; // Update the id associated with the client. Future calls to getClientId should return this. updateClientId(assignmentId: string|null, clentId: string): void; // Returns the next identifier for a new GristWSConnection object, and advance the counter. advanceCounter(): string; // Called with messages to log. log(...args: any[]): void; warn(...args: any[]): void; } /** * An implementation of Grist websocket connection settings for the browser. */ export class GristWSSettingsBrowser implements GristWSSettings { public makeWebSocket(url: string) { return new WebSocket(url); } public getTimezone() { return guessTimezone(); } public getPageUrl() { return G.window.location.href; } public async getDocWorkerUrl(assignmentId: string|null) { return getDocWorkerUrl(assignmentId); } public getClientId(assignmentId: string|null) { return window.sessionStorage.getItem(`clientId_${assignmentId}`) || null; } public getUserSelector(): string { // TODO: find/create a more official way to get the user. return (window as any).gristDocPageModel?.appModel.currentUser?.email || ''; } public updateClientId(assignmentId: string|null, id: string) { window.sessionStorage.setItem(`clientId_${assignmentId}`, id); } public advanceCounter(): string { const value = parseInt(window.sessionStorage.getItem('clientCounter')!, 10) || 0; window.sessionStorage.setItem('clientCounter', String(value + 1)); return String(value); } public log(...args: any[]): void { console.log(...args); // tslint:disable-line:no-console } public warn(...args: any[]): void { console.warn(...args); // tslint:disable-line:no-console } } /** * GristWSConnection establishes a connection to the server and keep reconnecting * in the event that it loses the connection. */ export class GristWSConnection extends Disposable { public useCount: number = 0; public on: BackboneEvents['on']; // set by Backbone protected trigger: BackboneEvents['trigger']; // set by Backbone private _clientId: string|null; private _clientCounter: string; // Identifier of this GristWSConnection object in this browser tab session private _assignmentId: string|null; private _docWorkerUrl: string|null = null; private _initialConnection: Promise<void>; private _established: boolean = false; // This is set once the server sends us a 'clientConnect' message. private _firstConnect: boolean = true; private _heartbeatTimeout: ReturnType<typeof setTimeout> | null = null; private _reconnectTimeout: ReturnType<typeof setTimeout> | null = null; private _reconnectAttempts: number = 0; private _wantReconnect: boolean = true; private _ws: WebSocket|null = null; constructor(private _settings: GristWSSettings = new GristWSSettingsBrowser()) { super(); this._clientCounter = _settings.advanceCounter(); this.onDispose(() => this.disconnect()); } public initialize(assignmentId: string|null) { // For reconnections, squirrel away the id of the resource we are committed to (if any). this._assignmentId = assignmentId; // clientId is associated with a session. We try to persist it within a tab across navigation // and reloads, but the server may reset it if it doesn't recognize it. this._clientId = this._settings.getClientId(assignmentId); // For the DocMenu, identified as a page served with a homeUrl but no getWorker cache, we will // simply not hook up the websocket. The client is not ready to use it, and the server is not // ready to serve it. And the errors in the logs of both are distracting. However, it // doesn't really make sense to rip out the websocket code entirely, since the plan is // to eventually bring it back for smoother serving. Hence this compromise of simply // not trying to make the connection. // TODO: serve and use websockets for the DocMenu. if (getGristConfig().getWorker) { this.trigger('connectState', false); this._initialConnection = this.connect(); } else { this._log("GristWSConnection not activating for hosted grist page with no document present"); } } /** * Method that opens a websocket connection and continuously tries to reconnect if the connection * is closed. * @param isReconnecting - Flag set when attempting to reconnect */ public async connect(isReconnecting: boolean = false): Promise<void> { await this._updateDocWorkerUrl(); this._wantReconnect = true; this._connectImpl(isReconnecting, await this._settings.getTimezone()); } // Disconnect websocket if currently connected, and reset to initial state. public disconnect() { this._log('GristWSConnection: disconnect'); this._wantReconnect = false; this._established = false; if (this._ws) { this._ws.close(); this._ws = null; this._clientId = null; } this._clearHeartbeat(); if (this._reconnectTimeout) { clearTimeout(this._reconnectTimeout); } this._firstConnect = true; this._reconnectAttempts = 0; } public get established(): boolean { return this._established; } public get clientId(): string|null { return this._clientId; } /** * Returns the URL of the doc worker, or throws if we don't have one. */ public get docWorkerUrl(): string { if (!this._docWorkerUrl) { throw new Error('server for document not known'); } return this._docWorkerUrl; } /** * Returns the URL of the doc worker, or null if we don't have one. */ public getDocWorkerUrlOrNull(): string | null { return this._docWorkerUrl; } /** * @event serverMessage Triggered when a message arrives from the server. Callbacks receive * the raw message data as an additional argument. */ public onmessage(ev: any) { this._log('GristWSConnection: onmessage (%d bytes)', ev.data.length); this._scheduleHeartbeat(); const message = JSON.parse(ev.data); // clientConnect is the first message from the server that sets the clientId. We only consider // the connection established once we receive it. if (message.type === 'clientConnect') { if (this._established) { this._log("GristWSConnection skipping duplicate 'clientConnect' message"); return; } this._established = true; // Add a flag to the message to indicate if the active session changed, and warrants a reload. message.resetClientId = (message.clientId !== this._clientId && !this._firstConnect); this._log(`GristWSConnection established: clientId ${message.clientId} counter ${this._clientCounter}` + ` resetClientId ${message.resetClientId}`); if (message.dup) { this._warn("GristWSConnection missed initial 'clientConnect', processing its duplicate"); } if (message.clientId !== this._clientId) { this._clientId = message.clientId; if (this._settings) { this._settings.updateClientId(this._assignmentId, message.clientId); } } this._firstConnect = false; this.trigger('connectState', true); // Process any missed messages. (Should only have any if resetClientId is false.) for (const msg of message.missedMessages) { this.trigger('serverMessage', JSON.parse(msg)); } } if (!this._established) { this._log("GristWSConnection not yet established; ignoring message", message); return; } this.trigger('serverMessage', message); } public send(message: any) { this._log(`GristWSConnection.send[${this.established}]`, message); if (!this._established) { return false; } this._ws!.send(message); this._scheduleHeartbeat(); return true; } // unschedule any pending heartbeat message private _clearHeartbeat() { if (this._heartbeatTimeout) { clearTimeout(this._heartbeatTimeout); this._heartbeatTimeout = null; } } // schedule a heartbeat message for HEARTBEAT_PERIOD_IN_SECONDS seconds from now private _scheduleHeartbeat() { this._clearHeartbeat(); this._heartbeatTimeout = setTimeout(this._sendHeartbeat.bind(this), Math.round(HEARTBEAT_PERIOD_IN_SECONDS * 1000)); } // send a heartbeat message, including the document url for server-side logs private _sendHeartbeat() { this.send(JSON.stringify({ beat: 'alive', url: G.window.location.href, docId: this._assignmentId, })); } private _connectImpl(isReconnecting: boolean, timezone: any) { if (!this._wantReconnect) { return; } if (isReconnecting) { this._reconnectAttempts++; } // Note that if a WebSocket can't establish a connection it will trigger onclose() // As per http://dev.w3.org/html5/websockets/ // "If the establish a WebSocket connection algorithm fails, // it triggers the fail the WebSocket connection algorithm, // which then invokes the close the WebSocket connection algorithm, // which then establishes that the WebSocket connection is closed, // which fires the close event." const url = this._buildWebsocketUrl(isReconnecting, timezone); this._log("GristWSConnection connecting to: " + url); this._ws = this._settings.makeWebSocket(url); this._ws.onopen = () => { const connectMessage = isReconnecting ? 'Reconnected' : 'Connected'; this._log('GristWSConnection: onopen: ' + connectMessage); this.trigger('connectionStatus', connectMessage, 'OK'); this._reconnectAttempts = 0; // reset reconnection information this._scheduleHeartbeat(); }; this._ws.onmessage = this.onmessage.bind(this); this._ws.onerror = (ev: Event) => { this._log('GristWSConnection: onerror', ev); }; this._ws.onclose = () => { if (this._settings) { this._log('GristWSConnection: onclose'); } if (this.isDisposed()) { return; } this._established = false; this._ws = null; this.trigger('connectState', false); if (!this._wantReconnect) { return; } const reconnectTimeout = gutil.getReconnectTimeout(this._reconnectAttempts, reconnectInterval); this._log("Trying to reconnect in", reconnectTimeout, "ms"); this.trigger('connectionStatus', 'Trying to reconnect...', 'WARNING'); this._reconnectTimeout = setTimeout(async () => { this._reconnectTimeout = null; // Make sure we've gotten through all lazy-loading. await this._initialConnection; await this.connect(true); }, reconnectTimeout); }; } private _buildWebsocketUrl(isReconnecting: boolean, timezone: any): string { const url = new URL(this.docWorkerUrl); url.protocol = (url.protocol === 'https:') ? 'wss:' : 'ws:'; url.searchParams.append('clientId', this._clientId || '0'); url.searchParams.append('counter', this._clientCounter); url.searchParams.append('newClient', String(isReconnecting ? 0 : 1)); url.searchParams.append('browserSettings', JSON.stringify({timezone})); url.searchParams.append('user', this._settings.getUserSelector()); return url.href; } private async _updateDocWorkerUrl() { try { const url: string|null = await this._settings.getDocWorkerUrl(this._assignmentId); // Doc worker urls in general will need to have org information in them, since // the doc worker will check for that. The home service doesn't currently do // that for us, although it could. TODO: update home server to produce // standalone doc worker urls. this._docWorkerUrl = url ? addOrgToPath(url, this._settings.getPageUrl()) : url; } catch (e) { this._warn('Failed to connect to server for document'); } } // Log a message using the configured logger, or send it to console if no // logger available. private _log(...args: any[]): void { if (!this._settings) { // tslint:disable-next-line:no-console console.warn('log called without settings in GristWSConnection'); console.log(...args); // tslint:disable-line:no-console } else { this._settings.log(...args); } } // Log a warning using the configured logger, or send it to console if no // logger available. private _warn(...args: any[]): void { if (!this._settings) { // tslint:disable-next-line:no-console console.warn('warn called without settings in GristWSConnection'); console.warn(...args); // tslint:disable-line:no-console } else { this._settings.warn(...args); } } } Object.assign(GristWSConnection.prototype, BackboneEvents);
the_stack
import { EventEmitter } from 'events'; import SDKDriver from '../../../lib/sdkdriver/src'; import LocalParticipantDriver from './localparticipant'; import { ParticipantSID } from './participant'; import RemoteParticipantDriver from './remoteparticipant'; const { difference } = require('../../../../lib/util'); /** * A {@link RoomSID} is a 34-character string starting with "RM" * that uniquely identifies a {@link Room}. * @type string * @typedef RoomSID */ type RoomSID = string; /** * {@link Room} driver. * @classdesc A {@link RoomDriver} manages the execution of the * corresponding {@link Room}'s methods in the browser and * re-emits itsevents. * @extends EventEmitter * @property {LocalParticipantDriver} localParticipant * @property {string} name * @property {Map<ParticipantSID, RemoteParticipantDriver>} participants * @property {RoomSID} sid * @property {string} state * @fires RoomDriver#disconnected * @fires RoomDriver#participantConnected * @fires RoomDriver#participantDisconnected * @fires RoomDriver#recordingStarted * @fires RoomDriver#recordingStopped * @fires RoomDriver#trackDisabled * @fires RoomDriver#trackEnabled * @fires RoomDriver#trackMessage * @fires RoomDriver#trackStarted * @fires RoomDriver#trackSubscribed * @fires RoomDriver#trackUnsubscribed */ export default class RoomDriver extends EventEmitter { private readonly _resourceId: string; private readonly _sdkDriver: SDKDriver; readonly localParticipant: LocalParticipantDriver; readonly name: string; readonly participants: Map<ParticipantSID, RemoteParticipantDriver>; readonly sid: RoomSID; state: string; /** * Constructor. * @param {SDKDriver} sdkDriver * @param {object} serializedRoom */ constructor(sdkDriver: SDKDriver, serializedRoom: any) { super(); this.localParticipant = new LocalParticipantDriver(sdkDriver, serializedRoom.localParticipant); this.name = serializedRoom.name; this.participants = new Map(); this.sid = serializedRoom.sid; this._resourceId = serializedRoom._resourceId; this._sdkDriver = sdkDriver; this._update(serializedRoom); sdkDriver.on('event', (data: any) => { const { type, source, args } = data; if (source._resourceId !== this._resourceId) { return; } switch (type) { case 'disconnected': this._reemitDisconnected(source, args); break; case 'participantConnected': this._reemitParticipantConnected(source, args); break; case 'participantDisconnected': this._reemitParticipantDisconnected(source, args); break; case 'recordingStarted': this._reemitRecordingStarted(source); break; case 'recordingStopped': this._reemitRecordingStopped(source); break; case 'trackAdded': this._reemitTrackAdded(source, args); break; case 'trackDisabled': this._reemitTrackDisabled(source, args); break; case 'trackEnabled': this._reemitTrackEnabled(source, args); break; case 'trackMessage': this._reemitTrackMessage(source, args); break; case 'trackRemoved': this._reemitTrackRemoved(source, args); break; case 'trackStarted': this._reemitTrackStarted(source, args); break; case 'trackSubscribed': this._reemitTrackSubscribed(source, args); break; case 'trackUnsubscribed': this._reemitTrackUnsubscribed(source, args); break; } }); } /** * Re-emit the "disconnected" event from the browser. * @private * @param {object} source * @param {Array<*>} args * @returns {void} */ private _reemitDisconnected(source: any, args: any): void { this._update(source); const [, serializedError] = args; let error: any = null; if (serializedError) { error = new Error(serializedError.message); error.code = serializedError.code; } this.emit('disconnected', this, error); } /** * Re-emit the "participantConnected" event from the browser. * @private * @param {object} source * @param {Array<*>} args * @returns {void} */ private _reemitParticipantConnected(source: any, args: any): void { this._update(source); const serializedParticipant: any = args[0]; this.emit('participantConnected', this.participants.get(serializedParticipant.sid)); } /** * Re-emit the "participantConnected" event from the browser. * @private * @param {object} source * @param {Array<*>} args * @returns {void} */ private _reemitParticipantDisconnected(source: any, args: any): void { const serializedParticipant: any = args[0]; const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid); this._update(source); this.emit('participantDisconnected', participant); } /** * Re-emit the "recordingStarted" event from the browser. * @private * @param {object} source * @returns {void} */ private _reemitRecordingStarted(source: any): void { this._update(source); this.emit('recordingStarted'); } /** * Re-emit the "recordingStopped" event from the browser. * @private * @param {object} source * @returns {void} */ private _reemitRecordingStopped(source: any): void { this._update(source); this.emit('recordingStopped'); } /** * Re-emit the "trackAdded" event from the browser. * @private * @param {object} source * @param {Array<*>} args * @returns {void} */ private _reemitTrackAdded(source: any, args: any): void { this._update(source); const [ serializedTrack, serializedParticipant ] = args; const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid); if (participant) { this.emit('trackAdded', participant.tracks.get(serializedTrack.id), participant); } } /** * Re-emit the "trackDisabled" event from the browser. * @private * @param {object} source * @param {Array<*>} args * @returns {void} */ private _reemitTrackDisabled(source: any, args: any): void { this._update(source); const [ serializedTrack, serializedParticipant ] = args; const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid); if (participant) { this.emit('trackDisabled', participant.tracks.get(serializedTrack.id), participant); } } /** * Re-emit the "trackEnabled" event from the browser. * @private * @param {object} source * @param {Array<*>} args * @returns {void} */ private _reemitTrackEnabled(source: any, args: any): void { this._update(source); const [ serializedTrack, serializedParticipant ] = args; const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid); if (participant) { this.emit('trackEnabled', participant.tracks.get(serializedTrack.id), participant); } } /** * Re-emit the "trackMessage" event from the browser. * @private * @param {object} source * @param {Array<*>} args * @returns {void} */ private _reemitTrackMessage(source: any, args: any): void { this._update(source); const [ data, serializedTrack, serializedParticipant ] = args; const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid); if (participant) { this.emit('trackMessage', data, participant.tracks.get(serializedTrack.id), participant); } } /** * Re-emit the "trackRemoved" event from the browser. * @private * @param {object} source * @param {Array<*>} args * @returns {void} */ private _reemitTrackRemoved(source: any, args: any): void { this._update(source); const [ serializedTrack, serializedParticipant ] = args; const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid); if (participant) { this.emit('trackRemoved', participant.getRemovedTrack(serializedTrack.id), participant); } } /** * Re-emit the "trackStarted" event from the browser. * @private * @param {object} source * @param {Array<*>} args * @returns {void} */ private _reemitTrackStarted(source: any, args: any): void { this._update(source); const [ serializedTrack, serializedParticipant ] = args; const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid); if (participant) { this.emit('trackStarted', participant.tracks.get(serializedTrack.id), participant); } } /** * Re-emit the "trackSubscribed" event from the browser. * @private * @param {object} source * @param {Array<*>} args * @returns {void} */ private _reemitTrackSubscribed(source: any, args: any): void { this._update(source); const [ serializedTrack, serializedParticipant ] = args; const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid); if (participant) { this.emit('trackSubscribed', participant.tracks.get(serializedTrack.id), participant); } } /** * Re-emit the "trackUnsubscribed" event from the browser. * @private * @param {object} source * @param {Array<*>} args * @returns {void} */ private _reemitTrackUnsubscribed(source: any, args: any): void { this._update(source); const [ serializedTrack, serializedParticipant ] = args; const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid); if (participant) { this.emit('trackUnsubscribed', participant.getRemovedTrack(serializedTrack.id), participant); } } /** * Update the {@link RoomDriver}'s properties. * @param {object} serializedRoom * @returns {void} */ private _update(serializedRoom: any): void { const { participants, state } = serializedRoom; this.state = state; const serializedParticipants: Map<ParticipantSID, any> = new Map(participants.map((serializedParticipant: any) => [ serializedParticipant.sid, serializedParticipant ])); const participantsToAdd: Set<ParticipantSID> = difference( Array.from(serializedParticipants.keys()), Array.from(this.participants.keys())); const participantsToRemove: Set<ParticipantSID> = difference( Array.from(this.participants.keys()), Array.from(serializedParticipants.keys())); participantsToAdd.forEach((sid: ParticipantSID) => { this.participants.set(sid, new RemoteParticipantDriver(this._sdkDriver, serializedParticipants.get(sid))); }); participantsToRemove.forEach((sid: ParticipantSID) => { this.participants.delete(sid); }); } /** * Disconnect from the {@link Room} in the browser. * @returns {void} */ disconnect(): void { this._sdkDriver.sendRequest({ api: 'disconnect', target: this._resourceId }).then(() => { // Do nothing. }, () => { // Do nothing. }); } /** * Get WebRTC stats for the {@link Room} from the browser. * @returns {Promise<Array<object>>} */ async getStats(): Promise<Array<any>> { const { error, result } = await this._sdkDriver.sendRequest({ api: 'getStats', target: this._resourceId }); if (error) { throw new Error(error.message); } return result; } } /** * @param {RoomDriver} room * @param {?TwilioError} error * @event RoomDriver#disconnected */ /** * @param {RemoteParticipantDriver} participant * @event RoomDriver#participantConnected */ /** * @param {RemoteParticipantDriver} participant * @event RoomDriver#participantDisconnected */ /** * @event RoomDriver#recordingStarted */ /** * @event RoomDriver#recordingStopped */ /** * @param {RemoteMediaTrackDriver} track * @param {RemoteParticipantDriver} participant * @event RoomDriver#trackDisabled */ /** * @param {RemoteMediaTrackDriver} track * @param {RemoteParticipantDriver} participant * @event RoomDriver#trackEnabled */ /** * @param {string} data * @param {RemoteDataTrackDriver} track * @param {RemotreParticipantDriver} participant * @event RoomDriver#trackMessage */ /** * @param {RemoteMediaTrackDriver} track * @param {RemoteParticipantDriver} participant * @event RoomDriver#trackStarted */ /** * @param {RemoteDataTrackDriver | RemoteMediaTrackDriver} track * @param {RemoteParticipantDriver} participant * @event RoomDriver#trackAdded */ /** * @param {RemoteDataTrackDriver | RemoteMediaTrackDriver} track * @param {RemoteParticipantDriver} participant * @event RoomDriver#trackRemoved */ /** * @param {RemoteDataTrackDriver | RemoteMediaTrackDriver} track * @param {RemoteParticipantDriver} participant * @event RoomDriver#trackSubscribed */ /** * @param {RemoteDataTrackDriver | RemoteMediaTrackDriver} track * @param {RemoteParticipantDriver} participant * @event RoomDriver#trackUnsubscribed */
the_stack
declare module net { export module lingala { export module zip4j { export class ZipFile { public static class: java.lang.Class<net.lingala.zip4j.ZipFile>; public addFiles(param0: java.util.List<java.io.File>, param1: net.lingala.zip4j.model.ZipParameters): void; public getSplitZipFiles(): java.util.List<java.io.File>; public isRunInThread(): boolean; public addFolder(param0: java.io.File, param1: net.lingala.zip4j.model.ZipParameters): void; public getFileHeaders(): java.util.List<net.lingala.zip4j.model.FileHeader>; public addFile(param0: java.io.File, param1: net.lingala.zip4j.model.ZipParameters): void; public createSplitZipFileFromFolder(param0: java.io.File, param1: net.lingala.zip4j.model.ZipParameters, param2: boolean, param3: number): void; public addStream(param0: java.io.InputStream, param1: net.lingala.zip4j.model.ZipParameters): void; public addFile(param0: java.io.File): void; public getFileHeader(param0: string): net.lingala.zip4j.model.FileHeader; public constructor(param0: string); public extractFile(param0: net.lingala.zip4j.model.FileHeader, param1: string, param2: string): void; public getInputStream(param0: net.lingala.zip4j.model.FileHeader): net.lingala.zip4j.io.inputstream.ZipInputStream; public removeFile(param0: net.lingala.zip4j.model.FileHeader): void; public mergeSplitFiles(param0: java.io.File): void; public setPassword(param0: native.Array<string>): void; public addFiles(param0: java.util.List<java.io.File>): void; public getCharset(): java.nio.charset.Charset; public getComment(): string; public setComment(param0: string): void; public isSplitArchive(): boolean; public extractFile(param0: string, param1: string): void; public constructor(param0: java.io.File); public isValidZipFile(): boolean; public addFile(param0: string): void; public addFolder(param0: java.io.File): void; public extractFile(param0: string, param1: string, param2: string): void; public getProgressMonitor(): net.lingala.zip4j.progress.ProgressMonitor; public setRunInThread(param0: boolean): void; public toString(): string; public extractFile(param0: net.lingala.zip4j.model.FileHeader, param1: string): void; public constructor(param0: string, param1: native.Array<string>); public createSplitZipFile(param0: java.util.List<java.io.File>, param1: net.lingala.zip4j.model.ZipParameters, param2: boolean, param3: number): void; public addFile(param0: string, param1: net.lingala.zip4j.model.ZipParameters): void; public extractAll(param0: string): void; public constructor(param0: java.io.File, param1: native.Array<string>); public removeFile(param0: string): void; public getFile(): java.io.File; public setCharset(param0: java.nio.charset.Charset): void; public isEncrypted(): boolean; } } } } declare module net { export module lingala { export module zip4j { export module crypto { export class AESDecrypter extends net.lingala.zip4j.crypto.Decrypter { public static class: java.lang.Class<net.lingala.zip4j.crypto.AESDecrypter>; public static PASSWORD_VERIFIER_LENGTH: number; public constructor(param0: net.lingala.zip4j.model.AESExtraDataRecord, param1: native.Array<string>, param2: native.Array<number>, param3: native.Array<number>); public decryptData(param0: native.Array<number>, param1: number, param2: number): number; public getCalculatedAuthenticationBytes(): native.Array<number>; } } } } } declare module net { export module lingala { export module zip4j { export module crypto { export class AESEncrpyter extends net.lingala.zip4j.crypto.Encrypter { public static class: java.lang.Class<net.lingala.zip4j.crypto.AESEncrpyter>; public getSaltBytes(): native.Array<number>; public getFinalMac(): native.Array<number>; public encryptData(param0: native.Array<number>, param1: number, param2: number): number; public encryptData(param0: native.Array<number>): number; public constructor(param0: native.Array<string>, param1: net.lingala.zip4j.model.enums.AesKeyStrength); public getDerivedPasswordVerifier(): native.Array<number>; } } } } } declare module net { export module lingala { export module zip4j { export module crypto { export class AesCipherUtil { public static class: java.lang.Class<net.lingala.zip4j.crypto.AesCipherUtil>; public constructor(); public static prepareBuffAESIVBytes(param0: native.Array<number>, param1: number): void; } } } } } declare module net { export module lingala { export module zip4j { export module crypto { export class Decrypter { public static class: java.lang.Class<net.lingala.zip4j.crypto.Decrypter>; /** * Constructs a new instance of the net.lingala.zip4j.crypto.Decrypter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { decryptData(param0: native.Array<number>, param1: number, param2: number): number; }); public constructor(); public decryptData(param0: native.Array<number>, param1: number, param2: number): number; } } } } } declare module net { export module lingala { export module zip4j { export module crypto { export class Encrypter { public static class: java.lang.Class<net.lingala.zip4j.crypto.Encrypter>; /** * Constructs a new instance of the net.lingala.zip4j.crypto.Encrypter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { encryptData(param0: native.Array<number>): number; encryptData(param0: native.Array<number>, param1: number, param2: number): number; }); public constructor(); public encryptData(param0: native.Array<number>, param1: number, param2: number): number; public encryptData(param0: native.Array<number>): number; } } } } } declare module net { export module lingala { export module zip4j { export module crypto { export module PBKDF2 { export class BinTools { public static class: java.lang.Class<net.lingala.zip4j.crypto.PBKDF2.BinTools>; public static hex: string; public static hex2bin(param0: string): native.Array<number>; public static bin2hex(param0: native.Array<number>): string; public static hex2bin(param0: string): number; } } } } } } declare module net { export module lingala { export module zip4j { export module crypto { export module PBKDF2 { export class MacBasedPRF extends net.lingala.zip4j.crypto.PBKDF2.PRF { public static class: java.lang.Class<net.lingala.zip4j.crypto.PBKDF2.MacBasedPRF>; public init(param0: native.Array<number>): void; public update(param0: native.Array<number>): void; public doFinal(): native.Array<number>; public update(param0: native.Array<number>, param1: number, param2: number): void; public doFinal(param0: native.Array<number>): native.Array<number>; public constructor(param0: string); public getHLen(): number; } } } } } } declare module net { export module lingala { export module zip4j { export module crypto { export module PBKDF2 { export class PBKDF2Engine { public static class: java.lang.Class<net.lingala.zip4j.crypto.PBKDF2.PBKDF2Engine>; public getPseudoRandomFunction(): net.lingala.zip4j.crypto.PBKDF2.PRF; public INT(param0: native.Array<number>, param1: number, param2: number): void; public getParameters(): net.lingala.zip4j.crypto.PBKDF2.PBKDF2Parameters; public setParameters(param0: net.lingala.zip4j.crypto.PBKDF2.PBKDF2Parameters): void; public verifyKey(param0: native.Array<string>): boolean; public constructor(param0: net.lingala.zip4j.crypto.PBKDF2.PBKDF2Parameters, param1: net.lingala.zip4j.crypto.PBKDF2.PRF); public deriveKey(param0: native.Array<string>): native.Array<number>; public deriveKey(param0: native.Array<string>, param1: number): native.Array<number>; public constructor(param0: net.lingala.zip4j.crypto.PBKDF2.PBKDF2Parameters); public setPseudoRandomFunction(param0: net.lingala.zip4j.crypto.PBKDF2.PRF): void; } } } } } } declare module net { export module lingala { export module zip4j { export module crypto { export module PBKDF2 { export class PBKDF2HexFormatter { public static class: java.lang.Class<net.lingala.zip4j.crypto.PBKDF2.PBKDF2HexFormatter>; public toString(param0: net.lingala.zip4j.crypto.PBKDF2.PBKDF2Parameters): string; public fromString(param0: net.lingala.zip4j.crypto.PBKDF2.PBKDF2Parameters, param1: string): boolean; } } } } } } declare module net { export module lingala { export module zip4j { export module crypto { export module PBKDF2 { export class PBKDF2Parameters { public static class: java.lang.Class<net.lingala.zip4j.crypto.PBKDF2.PBKDF2Parameters>; public salt: native.Array<number>; public iterationCount: number; public hashAlgorithm: string; public hashCharset: string; public derivedKey: native.Array<number>; public constructor(); public getIterationCount(): number; public constructor(param0: string, param1: string, param2: native.Array<number>, param3: number); public setIterationCount(param0: number): void; public getHashCharset(): string; public constructor(param0: string, param1: string, param2: native.Array<number>, param3: number, param4: native.Array<number>); public setSalt(param0: native.Array<number>): void; public setDerivedKey(param0: native.Array<number>): void; public getHashAlgorithm(): string; public setHashAlgorithm(param0: string): void; public setHashCharset(param0: string): void; public getDerivedKey(): native.Array<number>; public getSalt(): native.Array<number>; } } } } } } declare module net { export module lingala { export module zip4j { export module crypto { export module PBKDF2 { export class PRF { public static class: java.lang.Class<net.lingala.zip4j.crypto.PBKDF2.PRF>; /** * Constructs a new instance of the net.lingala.zip4j.crypto.PBKDF2.PRF interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { init(param0: native.Array<number>): void; doFinal(param0: native.Array<number>): native.Array<number>; getHLen(): number; }); public constructor(); public init(param0: native.Array<number>): void; public doFinal(param0: native.Array<number>): native.Array<number>; public getHLen(): number; } } } } } } declare module net { export module lingala { export module zip4j { export module crypto { export class StandardDecrypter extends net.lingala.zip4j.crypto.Decrypter { public static class: java.lang.Class<net.lingala.zip4j.crypto.StandardDecrypter>; public decryptData(param0: native.Array<number>, param1: number, param2: number): number; public constructor(param0: native.Array<string>, param1: native.Array<number>, param2: native.Array<number>); } } } } } declare module net { export module lingala { export module zip4j { export module crypto { export class StandardEncrypter extends net.lingala.zip4j.crypto.Encrypter { public static class: java.lang.Class<net.lingala.zip4j.crypto.StandardEncrypter>; public encryptByte(param0: number): number; public constructor(param0: native.Array<string>, param1: number); public getHeaderBytes(): native.Array<number>; public encryptData(param0: native.Array<number>, param1: number, param2: number): number; public encryptData(param0: native.Array<number>): number; public generateRandomBytes(param0: number): native.Array<number>; } } } } } declare module net { export module lingala { export module zip4j { export module crypto { export module engine { export class AESEngine { public static class: java.lang.Class<net.lingala.zip4j.crypto.engine.AESEngine>; public constructor(param0: native.Array<number>); public processBlock(param0: native.Array<number>, param1: native.Array<number>): number; public processBlock(param0: native.Array<number>, param1: number, param2: native.Array<number>, param3: number): number; } } } } } } declare module net { export module lingala { export module zip4j { export module crypto { export module engine { export class ZipCryptoEngine { public static class: java.lang.Class<net.lingala.zip4j.crypto.engine.ZipCryptoEngine>; public constructor(); public initKeys(param0: native.Array<string>): void; public updateKeys(param0: number): void; public decryptByte(): number; } } } } } } declare module net { export module lingala { export module zip4j { export module exception { export class ZipException { public static class: java.lang.Class<net.lingala.zip4j.exception.ZipException>; public constructor(param0: string); public constructor(param0: string, param1: java.lang.Throwable, param2: net.lingala.zip4j.exception.ZipException.Type); public constructor(param0: string, param1: java.lang.Exception); public getType(): net.lingala.zip4j.exception.ZipException.Type; public constructor(param0: java.lang.Exception); public constructor(param0: string, param1: net.lingala.zip4j.exception.ZipException.Type); } export module ZipException { export class Type { public static class: java.lang.Class<net.lingala.zip4j.exception.ZipException.Type>; public static WRONG_PASSWORD: net.lingala.zip4j.exception.ZipException.Type; public static TASK_CANCELLED_EXCEPTION: net.lingala.zip4j.exception.ZipException.Type; public static CHECKSUM_MISMATCH: net.lingala.zip4j.exception.ZipException.Type; public static UNKNOWN_COMPRESSION_METHOD: net.lingala.zip4j.exception.ZipException.Type; public static UNKNOWN: net.lingala.zip4j.exception.ZipException.Type; public static valueOf(param0: string): net.lingala.zip4j.exception.ZipException.Type; public static values(): native.Array<net.lingala.zip4j.exception.ZipException.Type>; } } } } } } declare module net { export module lingala { export module zip4j { export module headers { export class FileHeaderFactory { public static class: java.lang.Class<net.lingala.zip4j.headers.FileHeaderFactory>; public generateLocalFileHeader(param0: net.lingala.zip4j.model.FileHeader): net.lingala.zip4j.model.LocalFileHeader; public constructor(); public generateFileHeader(param0: net.lingala.zip4j.model.ZipParameters, param1: boolean, param2: number, param3: java.nio.charset.Charset): net.lingala.zip4j.model.FileHeader; } } } } } declare module net { export module lingala { export module zip4j { export module headers { export class HeaderReader { public static class: java.lang.Class<net.lingala.zip4j.headers.HeaderReader>; public readDataDescriptor(param0: java.io.InputStream, param1: boolean): net.lingala.zip4j.model.DataDescriptor; public constructor(); public readLocalFileHeader(param0: java.io.InputStream, param1: java.nio.charset.Charset): net.lingala.zip4j.model.LocalFileHeader; public readAllHeaders(param0: java.io.RandomAccessFile, param1: java.nio.charset.Charset): net.lingala.zip4j.model.ZipModel; } } } } } declare module net { export module lingala { export module zip4j { export module headers { export class HeaderSignature { public static class: java.lang.Class<net.lingala.zip4j.headers.HeaderSignature>; public static LOCAL_FILE_HEADER: net.lingala.zip4j.headers.HeaderSignature; public static EXTRA_DATA_RECORD: net.lingala.zip4j.headers.HeaderSignature; public static CENTRAL_DIRECTORY: net.lingala.zip4j.headers.HeaderSignature; public static END_OF_CENTRAL_DIRECTORY: net.lingala.zip4j.headers.HeaderSignature; public static DIGITAL_SIGNATURE: net.lingala.zip4j.headers.HeaderSignature; public static ARCEXTDATREC: net.lingala.zip4j.headers.HeaderSignature; public static SPLIT_ZIP: net.lingala.zip4j.headers.HeaderSignature; public static ZIP64_END_CENTRAL_DIRECTORY_LOCATOR: net.lingala.zip4j.headers.HeaderSignature; public static ZIP64_END_CENTRAL_DIRECTORY_RECORD: net.lingala.zip4j.headers.HeaderSignature; public static ZIP64_EXTRA_FIELD_SIGNATURE: net.lingala.zip4j.headers.HeaderSignature; public static AES_EXTRA_DATA_RECORD: net.lingala.zip4j.headers.HeaderSignature; public static values(): native.Array<net.lingala.zip4j.headers.HeaderSignature>; public getValue(): number; public static valueOf(param0: string): net.lingala.zip4j.headers.HeaderSignature; } } } } } declare module net { export module lingala { export module zip4j { export module headers { export class HeaderUtil { public static class: java.lang.Class<net.lingala.zip4j.headers.HeaderUtil>; public constructor(); public static decodeStringWithCharset(param0: native.Array<number>, param1: boolean, param2: java.nio.charset.Charset): string; public static getIndexOfFileHeader(param0: net.lingala.zip4j.model.ZipModel, param1: net.lingala.zip4j.model.FileHeader): number; public static getFileHeader(param0: net.lingala.zip4j.model.ZipModel, param1: string): net.lingala.zip4j.model.FileHeader; } } } } } declare module net { export module lingala { export module zip4j { export module headers { export class HeaderWriter { public static class: java.lang.Class<net.lingala.zip4j.headers.HeaderWriter>; public writeLocalFileHeader(param0: net.lingala.zip4j.model.ZipModel, param1: net.lingala.zip4j.model.LocalFileHeader, param2: java.io.OutputStream, param3: java.nio.charset.Charset): void; public constructor(); public finalizeZipFileWithoutValidations(param0: net.lingala.zip4j.model.ZipModel, param1: java.io.OutputStream, param2: java.nio.charset.Charset): void; public updateLocalFileHeader(param0: net.lingala.zip4j.model.FileHeader, param1: net.lingala.zip4j.model.ZipModel, param2: net.lingala.zip4j.io.outputstream.SplitOutputStream): void; public finalizeZipFile(param0: net.lingala.zip4j.model.ZipModel, param1: java.io.OutputStream, param2: java.nio.charset.Charset): void; public writeExtendedLocalHeader(param0: net.lingala.zip4j.model.LocalFileHeader, param1: java.io.OutputStream): void; } } } } } declare module net { export module lingala { export module zip4j { export module io { export module inputstream { export class AesCipherInputStream extends net.lingala.zip4j.io.inputstream.CipherInputStream<net.lingala.zip4j.crypto.AESDecrypter> { public static class: java.lang.Class<net.lingala.zip4j.io.inputstream.AesCipherInputStream>; public read(): number; public constructor(param0: net.lingala.zip4j.io.inputstream.ZipEntryInputStream, param1: net.lingala.zip4j.model.LocalFileHeader, param2: native.Array<string>); public read(param0: native.Array<number>): number; public initializeDecrypter(param0: net.lingala.zip4j.model.LocalFileHeader, param1: native.Array<string>): any; public readStoredMac(param0: java.io.InputStream): native.Array<number>; public initializeDecrypter(param0: net.lingala.zip4j.model.LocalFileHeader, param1: native.Array<string>): net.lingala.zip4j.crypto.AESDecrypter; public read(param0: native.Array<number>, param1: number, param2: number): number; public endOfEntryReached(param0: java.io.InputStream): void; } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module inputstream { export abstract class CipherInputStream<T> extends java.io.InputStream { public static class: java.lang.Class<net.lingala.zip4j.io.inputstream.CipherInputStream<any>>; public read(): number; public constructor(param0: net.lingala.zip4j.io.inputstream.ZipEntryInputStream, param1: net.lingala.zip4j.model.LocalFileHeader, param2: native.Array<string>); public read(param0: native.Array<number>): number; public close(): void; public getNumberOfBytesReadForThisEntry(): number; public readRaw(param0: native.Array<number>): number; public initializeDecrypter(param0: net.lingala.zip4j.model.LocalFileHeader, param1: native.Array<string>): any; public getLocalFileHeader(): net.lingala.zip4j.model.LocalFileHeader; public getDecrypter(): any; public getLastReadRawDataCache(): native.Array<number>; public read(param0: native.Array<number>, param1: number, param2: number): number; public endOfEntryReached(param0: java.io.InputStream): void; } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module inputstream { export abstract class DecompressedInputStream { public static class: java.lang.Class<net.lingala.zip4j.io.inputstream.DecompressedInputStream>; public oneByteBuffer: native.Array<number>; public read(): number; public read(param0: native.Array<number>): number; public close(): void; public constructor(param0: net.lingala.zip4j.io.inputstream.CipherInputStream<any>); public getLastReadRawDataCache(): native.Array<number>; public read(param0: native.Array<number>, param1: number, param2: number): number; public endOfEntryReached(param0: java.io.InputStream): void; public pushBackInputStreamIfNecessary(param0: java.io.PushbackInputStream): void; } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module inputstream { export class InflaterInputStream extends net.lingala.zip4j.io.inputstream.DecompressedInputStream { public static class: java.lang.Class<net.lingala.zip4j.io.inputstream.InflaterInputStream>; public read(): number; public read(param0: native.Array<number>): number; public constructor(param0: net.lingala.zip4j.io.inputstream.CipherInputStream<any>); public read(param0: native.Array<number>, param1: number, param2: number): number; public pushBackInputStreamIfNecessary(param0: java.io.PushbackInputStream): void; } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module inputstream { export class NoCipherInputStream extends net.lingala.zip4j.io.inputstream.CipherInputStream<any> { public static class: java.lang.Class<net.lingala.zip4j.io.inputstream.NoCipherInputStream>; public constructor(param0: net.lingala.zip4j.io.inputstream.ZipEntryInputStream, param1: net.lingala.zip4j.model.LocalFileHeader, param2: native.Array<string>); public initializeDecrypter(param0: net.lingala.zip4j.model.LocalFileHeader, param1: native.Array<string>): any; public initializeDecrypter(param0: net.lingala.zip4j.model.LocalFileHeader, param1: native.Array<string>): net.lingala.zip4j.crypto.Decrypter; } export module NoCipherInputStream { export class NoDecrypter extends net.lingala.zip4j.crypto.Decrypter { public static class: java.lang.Class<net.lingala.zip4j.io.inputstream.NoCipherInputStream.NoDecrypter>; public decryptData(param0: native.Array<number>, param1: number, param2: number): number; } } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module inputstream { export class SplitInputStream { public static class: java.lang.Class<net.lingala.zip4j.io.inputstream.SplitInputStream>; public read(): number; public prepareExtractionForFileHeader(param0: net.lingala.zip4j.model.FileHeader): void; public constructor(param0: java.io.File, param1: boolean, param2: number); public read(param0: native.Array<number>): number; public close(): void; public read(param0: native.Array<number>, param1: number, param2: number): number; } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module inputstream { export class StoreInputStream extends net.lingala.zip4j.io.inputstream.DecompressedInputStream { public static class: java.lang.Class<net.lingala.zip4j.io.inputstream.StoreInputStream>; public constructor(param0: net.lingala.zip4j.io.inputstream.CipherInputStream<any>); } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module inputstream { export class ZipEntryInputStream { public static class: java.lang.Class<net.lingala.zip4j.io.inputstream.ZipEntryInputStream>; public read(): number; public read(param0: native.Array<number>): number; public close(): void; public constructor(param0: java.io.InputStream, param1: number); public readRawFully(param0: native.Array<number>): number; public read(param0: native.Array<number>, param1: number, param2: number): number; public getNumberOfBytesRead(): number; } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module inputstream { export class ZipInputStream { public static class: java.lang.Class<net.lingala.zip4j.io.inputstream.ZipInputStream>; public read(): number; public getAvailableBytesInPushBackInputStream(): number; public getNextEntry(): net.lingala.zip4j.model.LocalFileHeader; public constructor(param0: java.io.InputStream); public constructor(param0: java.io.InputStream, param1: java.nio.charset.Charset); public getNextEntry(param0: net.lingala.zip4j.model.FileHeader): net.lingala.zip4j.model.LocalFileHeader; public read(param0: native.Array<number>): number; public close(): void; public constructor(param0: java.io.InputStream, param1: native.Array<string>); public constructor(param0: java.io.InputStream, param1: native.Array<string>, param2: java.nio.charset.Charset); public read(param0: native.Array<number>, param1: number, param2: number): number; } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module inputstream { export class ZipStandardCipherInputStream extends net.lingala.zip4j.io.inputstream.CipherInputStream<net.lingala.zip4j.crypto.StandardDecrypter> { public static class: java.lang.Class<net.lingala.zip4j.io.inputstream.ZipStandardCipherInputStream>; public constructor(param0: net.lingala.zip4j.io.inputstream.ZipEntryInputStream, param1: net.lingala.zip4j.model.LocalFileHeader, param2: native.Array<string>); public initializeDecrypter(param0: net.lingala.zip4j.model.LocalFileHeader, param1: native.Array<string>): any; public initializeDecrypter(param0: net.lingala.zip4j.model.LocalFileHeader, param1: native.Array<string>): net.lingala.zip4j.crypto.StandardDecrypter; } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module outputstream { export class AesCipherOutputStream extends net.lingala.zip4j.io.outputstream.CipherOutputStream<net.lingala.zip4j.crypto.AESEncrpyter> { public static class: java.lang.Class<net.lingala.zip4j.io.outputstream.AesCipherOutputStream>; public initializeEncrypter(param0: java.io.OutputStream, param1: net.lingala.zip4j.model.ZipParameters, param2: native.Array<string>): net.lingala.zip4j.crypto.AESEncrpyter; public write(param0: number): void; public write(param0: native.Array<number>, param1: number, param2: number): void; public closeEntry(): void; public constructor(param0: net.lingala.zip4j.io.outputstream.ZipEntryOutputStream, param1: net.lingala.zip4j.model.ZipParameters, param2: native.Array<string>); public write(param0: native.Array<number>): void; public initializeEncrypter(param0: java.io.OutputStream, param1: net.lingala.zip4j.model.ZipParameters, param2: native.Array<string>): any; } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module outputstream { export abstract class CipherOutputStream<T> extends java.io.OutputStream { public static class: java.lang.Class<net.lingala.zip4j.io.outputstream.CipherOutputStream<any>>; public writeHeaders(param0: native.Array<number>): void; public close(): void; public write(param0: number): void; public write(param0: native.Array<number>, param1: number, param2: number): void; public closeEntry(): void; public constructor(param0: net.lingala.zip4j.io.outputstream.ZipEntryOutputStream, param1: net.lingala.zip4j.model.ZipParameters, param2: native.Array<string>); public write(param0: native.Array<number>): void; public initializeEncrypter(param0: java.io.OutputStream, param1: net.lingala.zip4j.model.ZipParameters, param2: native.Array<string>): any; public getNumberOfBytesWrittenForThisEntry(): number; public getEncrypter(): any; } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module outputstream { export abstract class CompressedOutputStream { public static class: java.lang.Class<net.lingala.zip4j.io.outputstream.CompressedOutputStream>; public getCompressedSize(): number; public constructor(param0: net.lingala.zip4j.io.outputstream.CipherOutputStream<any>); public close(): void; public write(param0: number): void; public write(param0: native.Array<number>, param1: number, param2: number): void; public closeEntry(): void; public write(param0: native.Array<number>): void; } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module outputstream { export class CountingOutputStream { public static class: java.lang.Class<net.lingala.zip4j.io.outputstream.CountingOutputStream>; public constructor(param0: java.io.OutputStream); public getNumberOfBytesWritten(): number; public checkBuffSizeAndStartNextSplitFile(param0: number): boolean; public isSplitZipFile(): boolean; public close(): void; public write(param0: number): void; public write(param0: native.Array<number>, param1: number, param2: number): void; public getOffsetForNextEntry(): number; public write(param0: native.Array<number>): void; public getCurrentSplitFileCounter(): number; public getSplitLength(): number; public getFilePointer(): number; } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module outputstream { export class DeflaterOutputStream extends net.lingala.zip4j.io.outputstream.CompressedOutputStream { public static class: java.lang.Class<net.lingala.zip4j.io.outputstream.DeflaterOutputStream>; public deflater: java.util.zip.Deflater; public constructor(param0: net.lingala.zip4j.io.outputstream.CipherOutputStream<any>); public constructor(param0: net.lingala.zip4j.io.outputstream.CipherOutputStream<any>, param1: net.lingala.zip4j.model.enums.CompressionLevel); public write(param0: number): void; public write(param0: native.Array<number>, param1: number, param2: number): void; public closeEntry(): void; public write(param0: native.Array<number>): void; } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module outputstream { export class NoCipherOutputStream extends net.lingala.zip4j.io.outputstream.CipherOutputStream<net.lingala.zip4j.io.outputstream.NoCipherOutputStream.NoEncrypter> { public static class: java.lang.Class<net.lingala.zip4j.io.outputstream.NoCipherOutputStream>; public constructor(param0: net.lingala.zip4j.io.outputstream.ZipEntryOutputStream, param1: net.lingala.zip4j.model.ZipParameters, param2: native.Array<string>); public initializeEncrypter(param0: java.io.OutputStream, param1: net.lingala.zip4j.model.ZipParameters, param2: native.Array<string>): any; public initializeEncrypter(param0: java.io.OutputStream, param1: net.lingala.zip4j.model.ZipParameters, param2: native.Array<string>): net.lingala.zip4j.io.outputstream.NoCipherOutputStream.NoEncrypter; } export module NoCipherOutputStream { export class NoEncrypter extends net.lingala.zip4j.crypto.Encrypter { public static class: java.lang.Class<net.lingala.zip4j.io.outputstream.NoCipherOutputStream.NoEncrypter>; public encryptData(param0: native.Array<number>, param1: number, param2: number): number; public encryptData(param0: native.Array<number>): number; } } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module outputstream { export class SplitOutputStream { public static class: java.lang.Class<net.lingala.zip4j.io.outputstream.SplitOutputStream>; public constructor(param0: java.io.File, param1: number); public skipBytes(param0: number): number; public constructor(param0: java.io.File); public close(): void; public write(param0: number): void; public checkBufferSizeAndStartNextSplitFile(param0: number): boolean; public getCurrentSplitFileCounter(): number; public getSplitLength(): number; public getFilePointer(): number; public isSplitZipFile(): boolean; public write(param0: native.Array<number>, param1: number, param2: number): void; public write(param0: native.Array<number>): void; public seek(param0: number): void; } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module outputstream { export class StoreOutputStream extends net.lingala.zip4j.io.outputstream.CompressedOutputStream { public static class: java.lang.Class<net.lingala.zip4j.io.outputstream.StoreOutputStream>; public constructor(param0: net.lingala.zip4j.io.outputstream.CipherOutputStream<any>); } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module outputstream { export class ZipEntryOutputStream { public static class: java.lang.Class<net.lingala.zip4j.io.outputstream.ZipEntryOutputStream>; public constructor(param0: java.io.OutputStream); public close(): void; public write(param0: number): void; public write(param0: native.Array<number>, param1: number, param2: number): void; public closeEntry(): void; public write(param0: native.Array<number>): void; public getNumberOfBytesWrittenForThisEntry(): number; } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module outputstream { export class ZipOutputStream { public static class: java.lang.Class<net.lingala.zip4j.io.outputstream.ZipOutputStream>; public constructor(param0: java.io.OutputStream); public close(): void; public putNextEntry(param0: net.lingala.zip4j.model.ZipParameters): void; public write(param0: number): void; public constructor(param0: java.io.OutputStream, param1: native.Array<string>, param2: java.nio.charset.Charset); public write(param0: native.Array<number>, param1: number, param2: number): void; public closeEntry(): net.lingala.zip4j.model.FileHeader; public constructor(param0: java.io.OutputStream, param1: java.nio.charset.Charset); public write(param0: native.Array<number>): void; public constructor(param0: java.io.OutputStream, param1: native.Array<string>, param2: java.nio.charset.Charset, param3: net.lingala.zip4j.model.ZipModel); public constructor(param0: java.io.OutputStream, param1: native.Array<string>); } } } } } } declare module net { export module lingala { export module zip4j { export module io { export module outputstream { export class ZipStandardCipherOutputStream extends net.lingala.zip4j.io.outputstream.CipherOutputStream<net.lingala.zip4j.crypto.StandardEncrypter> { public static class: java.lang.Class<net.lingala.zip4j.io.outputstream.ZipStandardCipherOutputStream>; public initializeEncrypter(param0: java.io.OutputStream, param1: net.lingala.zip4j.model.ZipParameters, param2: native.Array<string>): net.lingala.zip4j.crypto.StandardEncrypter; public write(param0: number): void; public write(param0: native.Array<number>, param1: number, param2: number): void; public constructor(param0: net.lingala.zip4j.io.outputstream.ZipEntryOutputStream, param1: net.lingala.zip4j.model.ZipParameters, param2: native.Array<string>); public write(param0: native.Array<number>): void; public initializeEncrypter(param0: java.io.OutputStream, param1: net.lingala.zip4j.model.ZipParameters, param2: native.Array<string>): any; } } } } } } declare module net { export module lingala { export module zip4j { export module model { export class AESExtraDataRecord extends net.lingala.zip4j.model.ZipHeader { public static class: java.lang.Class<net.lingala.zip4j.model.AESExtraDataRecord>; public getAesVersion(): net.lingala.zip4j.model.enums.AesVersion; public getAesKeyStrength(): net.lingala.zip4j.model.enums.AesKeyStrength; public setCompressionMethod(param0: net.lingala.zip4j.model.enums.CompressionMethod): void; public constructor(); public setVendorID(param0: string): void; public setAesKeyStrength(param0: net.lingala.zip4j.model.enums.AesKeyStrength): void; public getCompressionMethod(): net.lingala.zip4j.model.enums.CompressionMethod; public setDataSize(param0: number): void; public setAesVersion(param0: net.lingala.zip4j.model.enums.AesVersion): void; public getDataSize(): number; public getVendorID(): string; } } } } } declare module net { export module lingala { export module zip4j { export module model { export abstract class AbstractFileHeader extends net.lingala.zip4j.model.ZipHeader { public static class: java.lang.Class<net.lingala.zip4j.model.AbstractFileHeader>; public setGeneralPurposeFlag(param0: native.Array<number>): void; public getAesExtraDataRecord(): net.lingala.zip4j.model.AESExtraDataRecord; public getCrc(): number; public setFileNameLength(param0: number): void; public getFileNameLength(): number; public getUncompressedSize(): number; public getCrcRawData(): native.Array<number>; public getExtraDataRecords(): java.util.List<net.lingala.zip4j.model.ExtraDataRecord>; public setUncompressedSize(param0: number): void; public isDataDescriptorExists(): boolean; public getExtraFieldLength(): number; public constructor(); public setDirectory(param0: boolean): void; public setCrc(param0: number): void; public getCompressedSize(): number; public setDataDescriptorExists(param0: boolean): void; public setCompressionMethod(param0: net.lingala.zip4j.model.enums.CompressionMethod): void; public getVersionNeededToExtract(): number; public setExtraFieldLength(param0: number): void; public getFileName(): string; public setLastModifiedTime(param0: number): void; public isEncrypted(): boolean; public setEncrypted(param0: boolean): void; public isFileNameUTF8Encoded(): boolean; public setFileNameUTF8Encoded(param0: boolean): void; public setCrcRawData(param0: native.Array<number>): void; public setFileName(param0: string): void; public getEncryptionMethod(): net.lingala.zip4j.model.enums.EncryptionMethod; public isDirectory(): boolean; public getLastModifiedTime(): number; public getZip64ExtendedInfo(): net.lingala.zip4j.model.Zip64ExtendedInfo; public setCompressedSize(param0: number): void; public setAesExtraDataRecord(param0: net.lingala.zip4j.model.AESExtraDataRecord): void; public setEncryptionMethod(param0: net.lingala.zip4j.model.enums.EncryptionMethod): void; public setVersionNeededToExtract(param0: number): void; public getCompressionMethod(): net.lingala.zip4j.model.enums.CompressionMethod; public getGeneralPurposeFlag(): native.Array<number>; public setZip64ExtendedInfo(param0: net.lingala.zip4j.model.Zip64ExtendedInfo): void; public setExtraDataRecords(param0: java.util.List<net.lingala.zip4j.model.ExtraDataRecord>): void; } } } } } declare module net { export module lingala { export module zip4j { export module model { export class ArchiveExtraDataRecord extends net.lingala.zip4j.model.ZipHeader { public static class: java.lang.Class<net.lingala.zip4j.model.ArchiveExtraDataRecord>; public setExtraFieldLength(param0: number): void; public getExtraFieldLength(): number; public constructor(); public setExtraFieldData(param0: string): void; public getExtraFieldData(): string; } } } } } declare module net { export module lingala { export module zip4j { export module model { export class CentralDirectory { public static class: java.lang.Class<net.lingala.zip4j.model.CentralDirectory>; public constructor(); public setFileHeaders(param0: java.util.List<net.lingala.zip4j.model.FileHeader>): void; public getFileHeaders(): java.util.List<net.lingala.zip4j.model.FileHeader>; public setDigitalSignature(param0: net.lingala.zip4j.model.DigitalSignature): void; public getDigitalSignature(): net.lingala.zip4j.model.DigitalSignature; } } } } } declare module net { export module lingala { export module zip4j { export module model { export class DataDescriptor extends net.lingala.zip4j.model.ZipHeader { public static class: java.lang.Class<net.lingala.zip4j.model.DataDescriptor>; public getCrc(): number; public constructor(); public getUncompressedSize(): number; public setCrc(param0: number): void; public getCompressedSize(): number; public setCompressedSize(param0: number): void; public setUncompressedSize(param0: number): void; } } } } } declare module net { export module lingala { export module zip4j { export module model { export class DigitalSignature extends net.lingala.zip4j.model.ZipHeader { public static class: java.lang.Class<net.lingala.zip4j.model.DigitalSignature>; public constructor(); public setSignatureData(param0: string): void; public getSignatureData(): string; public setSizeOfData(param0: number): void; public getSizeOfData(): number; } } } } } declare module net { export module lingala { export module zip4j { export module model { export class EndOfCentralDirectoryRecord extends net.lingala.zip4j.model.ZipHeader { public static class: java.lang.Class<net.lingala.zip4j.model.EndOfCentralDirectoryRecord>; public getNumberOfThisDiskStartOfCentralDir(): number; public setComment(param0: string): void; public getSizeOfCentralDirectory(): number; public setSizeOfCentralDirectory(param0: number): void; public setTotalNumberOfEntriesInCentralDirectory(param0: number): void; public setNumberOfThisDisk(param0: number): void; public getTotalNumberOfEntriesInCentralDirectoryOnThisDisk(): number; public constructor(); public setTotalNumberOfEntriesInCentralDirectoryOnThisDisk(param0: number): void; public setNumberOfThisDiskStartOfCentralDir(param0: number): void; public getNumberOfThisDisk(): number; public getTotalNumberOfEntriesInCentralDirectory(): number; public getOffsetOfStartOfCentralDirectory(): number; public setOffsetOfStartOfCentralDirectory(param0: number): void; public getComment(): string; } } } } } declare module net { export module lingala { export module zip4j { export module model { export class ExtraDataRecord extends net.lingala.zip4j.model.ZipHeader { public static class: java.lang.Class<net.lingala.zip4j.model.ExtraDataRecord>; public constructor(); public getData(): native.Array<number>; public setHeader(param0: number): void; public setSizeOfData(param0: number): void; public getHeader(): number; public getSizeOfData(): number; public setData(param0: native.Array<number>): void; } } } } } declare module net { export module lingala { export module zip4j { export module model { export class FileHeader extends net.lingala.zip4j.model.AbstractFileHeader { public static class: java.lang.Class<net.lingala.zip4j.model.FileHeader>; public getFileCommentLength(): number; public setFileCommentLength(param0: number): void; public getExternalFileAttributes(): native.Array<number>; public getDiskNumberStart(): number; public setDiskNumberStart(param0: number): void; public setOffsetLocalHeader(param0: number): void; public setFileComment(param0: string): void; public getOffsetLocalHeader(): number; public setVersionMadeBy(param0: number): void; public constructor(); public getInternalFileAttributes(): native.Array<number>; public getVersionMadeBy(): number; public setExternalFileAttributes(param0: native.Array<number>): void; public setInternalFileAttributes(param0: native.Array<number>): void; public getFileComment(): string; } } } } } declare module net { export module lingala { export module zip4j { export module model { export class LocalFileHeader extends net.lingala.zip4j.model.AbstractFileHeader { public static class: java.lang.Class<net.lingala.zip4j.model.LocalFileHeader>; public isWriteCompressedSizeInZip64ExtraRecord(): boolean; public setExtraField(param0: native.Array<number>): void; public getOffsetStartOfData(): number; public setWriteCompressedSizeInZip64ExtraRecord(param0: boolean): void; public constructor(); public getExtraField(): native.Array<number>; public setOffsetStartOfData(param0: number): void; } } } } } declare module net { export module lingala { export module zip4j { export module model { export class Zip64EndOfCentralDirectoryLocator extends net.lingala.zip4j.model.ZipHeader { public static class: java.lang.Class<net.lingala.zip4j.model.Zip64EndOfCentralDirectoryLocator>; public setNumberOfDiskStartOfZip64EndOfCentralDirectoryRecord(param0: number): void; public getOffsetZip64EndOfCentralDirectoryRecord(): number; public constructor(); public setOffsetZip64EndOfCentralDirectoryRecord(param0: number): void; public getNumberOfDiskStartOfZip64EndOfCentralDirectoryRecord(): number; public setTotalNumberOfDiscs(param0: number): void; public getTotalNumberOfDiscs(): number; } } } } } declare module net { export module lingala { export module zip4j { export module model { export class Zip64EndOfCentralDirectoryRecord extends net.lingala.zip4j.model.ZipHeader { public static class: java.lang.Class<net.lingala.zip4j.model.Zip64EndOfCentralDirectoryRecord>; public getVersionNeededToExtract(): number; public getSizeOfCentralDirectory(): number; public setExtensibleDataSector(param0: native.Array<number>): void; public setSizeOfZip64EndCentralDirectoryRecord(param0: number): void; public setSizeOfCentralDirectory(param0: number): void; public getExtensibleDataSector(): native.Array<number>; public setTotalNumberOfEntriesInCentralDirectory(param0: number): void; public setNumberOfThisDisk(param0: number): void; public getTotalNumberOfEntriesInCentralDirectoryOnThisDisk(): number; public setVersionMadeBy(param0: number): void; public constructor(); public getNumberOfThisDiskStartOfCentralDirectory(): number; public setTotalNumberOfEntriesInCentralDirectoryOnThisDisk(param0: number): void; public getOffsetStartCentralDirectoryWRTStartDiskNumber(): number; public getVersionMadeBy(): number; public setVersionNeededToExtract(param0: number): void; public getNumberOfThisDisk(): number; public getTotalNumberOfEntriesInCentralDirectory(): number; public setOffsetStartCentralDirectoryWRTStartDiskNumber(param0: number): void; public getSizeOfZip64EndCentralDirectoryRecord(): number; public setNumberOfThisDiskStartOfCentralDirectory(param0: number): void; } } } } } declare module net { export module lingala { export module zip4j { export module model { export class Zip64ExtendedInfo extends net.lingala.zip4j.model.ZipHeader { public static class: java.lang.Class<net.lingala.zip4j.model.Zip64ExtendedInfo>; public getOffsetLocalHeader(): number; public setSize(param0: number): void; public constructor(); public getUncompressedSize(): number; public getCompressedSize(): number; public setCompressedSize(param0: number): void; public getDiskNumberStart(): number; public getSize(): number; public setUncompressedSize(param0: number): void; public setDiskNumberStart(param0: number): void; public setOffsetLocalHeader(param0: number): void; } } } } } declare module net { export module lingala { export module zip4j { export module model { export abstract class ZipHeader { public static class: java.lang.Class<net.lingala.zip4j.model.ZipHeader>; public getSignature(): net.lingala.zip4j.headers.HeaderSignature; public constructor(); public setSignature(param0: net.lingala.zip4j.headers.HeaderSignature): void; } } } } } declare module net { export module lingala { export module zip4j { export module model { export class ZipModel { public static class: java.lang.Class<net.lingala.zip4j.model.ZipModel>; public getZip64EndOfCentralDirectoryRecord(): net.lingala.zip4j.model.Zip64EndOfCentralDirectoryRecord; public getEnd(): number; public isZip64Format(): boolean; public setCentralDirectory(param0: net.lingala.zip4j.model.CentralDirectory): void; public getSplitLength(): number; public getStart(): number; public setNestedZipFile(param0: boolean): void; public getCentralDirectory(): net.lingala.zip4j.model.CentralDirectory; public isSplitArchive(): boolean; public clone(): any; public constructor(); public getEndOfCentralDirectoryRecord(): net.lingala.zip4j.model.EndOfCentralDirectoryRecord; public getArchiveExtraDataRecord(): net.lingala.zip4j.model.ArchiveExtraDataRecord; public setZip64EndOfCentralDirectoryLocator(param0: net.lingala.zip4j.model.Zip64EndOfCentralDirectoryLocator): void; public setLocalFileHeaders(param0: java.util.List<net.lingala.zip4j.model.LocalFileHeader>): void; public setDataDescriptors(param0: java.util.List<net.lingala.zip4j.model.DataDescriptor>): void; public getLocalFileHeaders(): java.util.List<net.lingala.zip4j.model.LocalFileHeader>; public setEnd(param0: number): void; public getZip64EndOfCentralDirectoryLocator(): net.lingala.zip4j.model.Zip64EndOfCentralDirectoryLocator; public setSplitLength(param0: number): void; public setArchiveExtraDataRecord(param0: net.lingala.zip4j.model.ArchiveExtraDataRecord): void; public getZipFile(): java.io.File; public setZipFile(param0: java.io.File): void; public isNestedZipFile(): boolean; public setStart(param0: number): void; public setEndOfCentralDirectoryRecord(param0: net.lingala.zip4j.model.EndOfCentralDirectoryRecord): void; public setZip64Format(param0: boolean): void; public setSplitArchive(param0: boolean): void; public setZip64EndOfCentralDirectoryRecord(param0: net.lingala.zip4j.model.Zip64EndOfCentralDirectoryRecord): void; public getDataDescriptors(): java.util.List<net.lingala.zip4j.model.DataDescriptor>; } } } } } declare module net { export module lingala { export module zip4j { export module model { export class ZipParameters { public static class: java.lang.Class<net.lingala.zip4j.model.ZipParameters>; public isWriteExtendedLocalFileHeader(): boolean; public isEncryptFiles(): boolean; public setDefaultFolderPath(param0: string): void; public setWriteExtendedLocalFileHeader(param0: boolean): void; public isReadHiddenFolders(): boolean; public constructor(param0: net.lingala.zip4j.model.ZipParameters); public setAesVersion(param0: net.lingala.zip4j.model.enums.AesVersion): void; public getLastModifiedFileTime(): number; public getCompressionLevel(): net.lingala.zip4j.model.enums.CompressionLevel; public clone(): any; public getFileNameInZip(): string; public setLastModifiedFileTime(param0: number): void; public constructor(); public setCompressionLevel(param0: net.lingala.zip4j.model.enums.CompressionLevel): void; public getDefaultFolderPath(): string; public getEntryCRC(): number; public getRootFolderNameInZip(): string; public getAesVersion(): net.lingala.zip4j.model.enums.AesVersion; public setRootFolderNameInZip(param0: string): void; public setCompressionMethod(param0: net.lingala.zip4j.model.enums.CompressionMethod): void; public isReadHiddenFiles(): boolean; public setIncludeRootFolder(param0: boolean): void; public setOverrideExistingFilesInZip(param0: boolean): void; public setEncryptFiles(param0: boolean): void; public setEntryCRC(param0: number): void; public getAesKeyStrength(): net.lingala.zip4j.model.enums.AesKeyStrength; public getEncryptionMethod(): net.lingala.zip4j.model.enums.EncryptionMethod; public setFileNameInZip(param0: string): void; public getEntrySize(): number; public setEntrySize(param0: number): void; public setReadHiddenFiles(param0: boolean): void; public isIncludeRootFolder(): boolean; public setEncryptionMethod(param0: net.lingala.zip4j.model.enums.EncryptionMethod): void; public setAesKeyStrength(param0: net.lingala.zip4j.model.enums.AesKeyStrength): void; public getCompressionMethod(): net.lingala.zip4j.model.enums.CompressionMethod; public setReadHiddenFolders(param0: boolean): void; public isOverrideExistingFilesInZip(): boolean; } } } } } declare module net { export module lingala { export module zip4j { export module model { export module enums { export class AesKeyStrength { public static class: java.lang.Class<net.lingala.zip4j.model.enums.AesKeyStrength>; public static KEY_STRENGTH_128: net.lingala.zip4j.model.enums.AesKeyStrength; public static KEY_STRENGTH_192: net.lingala.zip4j.model.enums.AesKeyStrength; public static KEY_STRENGTH_256: net.lingala.zip4j.model.enums.AesKeyStrength; public static getAesKeyStrengthFromRawCode(param0: number): net.lingala.zip4j.model.enums.AesKeyStrength; public static values(): native.Array<net.lingala.zip4j.model.enums.AesKeyStrength>; public getRawCode(): number; public getMacLength(): number; public getKeyLength(): number; public static valueOf(param0: string): net.lingala.zip4j.model.enums.AesKeyStrength; public getSaltLength(): number; } } } } } } declare module net { export module lingala { export module zip4j { export module model { export module enums { export class AesVersion { public static class: java.lang.Class<net.lingala.zip4j.model.enums.AesVersion>; public static ONE: net.lingala.zip4j.model.enums.AesVersion; public static TWO: net.lingala.zip4j.model.enums.AesVersion; public static values(): native.Array<net.lingala.zip4j.model.enums.AesVersion>; public static valueOf(param0: string): net.lingala.zip4j.model.enums.AesVersion; public static getFromVersionNumber(param0: number): net.lingala.zip4j.model.enums.AesVersion; public getVersionNumber(): number; } } } } } } declare module net { export module lingala { export module zip4j { export module model { export module enums { export class CompressionLevel { public static class: java.lang.Class<net.lingala.zip4j.model.enums.CompressionLevel>; public static FASTEST: net.lingala.zip4j.model.enums.CompressionLevel; public static FAST: net.lingala.zip4j.model.enums.CompressionLevel; public static NORMAL: net.lingala.zip4j.model.enums.CompressionLevel; public static MAXIMUM: net.lingala.zip4j.model.enums.CompressionLevel; public getLevel(): number; public static values(): native.Array<net.lingala.zip4j.model.enums.CompressionLevel>; public static valueOf(param0: string): net.lingala.zip4j.model.enums.CompressionLevel; } } } } } } declare module net { export module lingala { export module zip4j { export module model { export module enums { export class CompressionMethod { public static class: java.lang.Class<net.lingala.zip4j.model.enums.CompressionMethod>; public static STORE: net.lingala.zip4j.model.enums.CompressionMethod; public static DEFLATE: net.lingala.zip4j.model.enums.CompressionMethod; public static AES_INTERNAL_ONLY: net.lingala.zip4j.model.enums.CompressionMethod; public static valueOf(param0: string): net.lingala.zip4j.model.enums.CompressionMethod; public getCode(): number; public static getCompressionMethodFromCode(param0: number): net.lingala.zip4j.model.enums.CompressionMethod; public static values(): native.Array<net.lingala.zip4j.model.enums.CompressionMethod>; } } } } } } declare module net { export module lingala { export module zip4j { export module model { export module enums { export class EncryptionMethod { public static class: java.lang.Class<net.lingala.zip4j.model.enums.EncryptionMethod>; public static NONE: net.lingala.zip4j.model.enums.EncryptionMethod; public static ZIP_STANDARD: net.lingala.zip4j.model.enums.EncryptionMethod; public static ZIP_STANDARD_VARIANT_STRONG: net.lingala.zip4j.model.enums.EncryptionMethod; public static AES: net.lingala.zip4j.model.enums.EncryptionMethod; public static valueOf(param0: string): net.lingala.zip4j.model.enums.EncryptionMethod; public static values(): native.Array<net.lingala.zip4j.model.enums.EncryptionMethod>; } } } } } } declare module net { export module lingala { export module zip4j { export module model { export module enums { export class RandomAccessFileMode { public static class: java.lang.Class<net.lingala.zip4j.model.enums.RandomAccessFileMode>; public static READ: net.lingala.zip4j.model.enums.RandomAccessFileMode; public static WRITE: net.lingala.zip4j.model.enums.RandomAccessFileMode; public static values(): native.Array<net.lingala.zip4j.model.enums.RandomAccessFileMode>; public static valueOf(param0: string): net.lingala.zip4j.model.enums.RandomAccessFileMode; public getValue(): string; } } } } } } declare module net { export module lingala { export module zip4j { export module progress { export class ProgressMonitor { public static class: java.lang.Class<net.lingala.zip4j.progress.ProgressMonitor>; public setCancelAllTasks(param0: boolean): void; public getWorkCompleted(): number; public getTotalWork(): number; public getFileName(): string; public setException(param0: java.lang.Exception): void; public setPause(param0: boolean): void; public isPause(): boolean; public setTotalWork(param0: number): void; public endProgressMonitor(): void; public setCurrentTask(param0: net.lingala.zip4j.progress.ProgressMonitor.Task): void; public setFileName(param0: string): void; public getPercentDone(): number; public constructor(); public getCurrentTask(): net.lingala.zip4j.progress.ProgressMonitor.Task; public getException(): java.lang.Exception; public fullReset(): void; public updateWorkCompleted(param0: number): void; public setState(param0: net.lingala.zip4j.progress.ProgressMonitor.State): void; public endProgressMonitor(param0: java.lang.Exception): void; public setPercentDone(param0: number): void; public setResult(param0: net.lingala.zip4j.progress.ProgressMonitor.Result): void; public getResult(): net.lingala.zip4j.progress.ProgressMonitor.Result; public isCancelAllTasks(): boolean; public getState(): net.lingala.zip4j.progress.ProgressMonitor.State; } export module ProgressMonitor { export class Result { public static class: java.lang.Class<net.lingala.zip4j.progress.ProgressMonitor.Result>; public static SUCCESS: net.lingala.zip4j.progress.ProgressMonitor.Result; public static WORK_IN_PROGRESS: net.lingala.zip4j.progress.ProgressMonitor.Result; public static ERROR: net.lingala.zip4j.progress.ProgressMonitor.Result; public static CANCELLED: net.lingala.zip4j.progress.ProgressMonitor.Result; public static values(): native.Array<net.lingala.zip4j.progress.ProgressMonitor.Result>; public static valueOf(param0: string): net.lingala.zip4j.progress.ProgressMonitor.Result; } export class State { public static class: java.lang.Class<net.lingala.zip4j.progress.ProgressMonitor.State>; public static READY: net.lingala.zip4j.progress.ProgressMonitor.State; public static BUSY: net.lingala.zip4j.progress.ProgressMonitor.State; public static values(): native.Array<net.lingala.zip4j.progress.ProgressMonitor.State>; public static valueOf(param0: string): net.lingala.zip4j.progress.ProgressMonitor.State; } export class Task { public static class: java.lang.Class<net.lingala.zip4j.progress.ProgressMonitor.Task>; public static NONE: net.lingala.zip4j.progress.ProgressMonitor.Task; public static ADD_ENTRY: net.lingala.zip4j.progress.ProgressMonitor.Task; public static REMOVE_ENTRY: net.lingala.zip4j.progress.ProgressMonitor.Task; public static CALCULATE_CRC: net.lingala.zip4j.progress.ProgressMonitor.Task; public static EXTRACT_ENTRY: net.lingala.zip4j.progress.ProgressMonitor.Task; public static MERGE_ZIP_FILES: net.lingala.zip4j.progress.ProgressMonitor.Task; public static SET_COMMENT: net.lingala.zip4j.progress.ProgressMonitor.Task; public static valueOf(param0: string): net.lingala.zip4j.progress.ProgressMonitor.Task; public static values(): native.Array<net.lingala.zip4j.progress.ProgressMonitor.Task>; } } } } } } declare module net { export module lingala { export module zip4j { export module tasks { export abstract class AbstractAddFileToZipTask<T> extends net.lingala.zip4j.tasks.AsyncZipTask<any> { public static class: java.lang.Class<net.lingala.zip4j.tasks.AbstractAddFileToZipTask<any>>; public getZipModel(): net.lingala.zip4j.model.ZipModel; public getTask(): net.lingala.zip4j.progress.ProgressMonitor.Task; } } } } } declare module net { export module lingala { export module zip4j { export module tasks { export abstract class AbstractExtractFileTask<T> extends net.lingala.zip4j.tasks.AsyncZipTask<any> { public static class: java.lang.Class<net.lingala.zip4j.tasks.AbstractExtractFileTask<any>>; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean); public extractFile(param0: net.lingala.zip4j.io.inputstream.ZipInputStream, param1: net.lingala.zip4j.model.FileHeader, param2: string, param3: string, param4: net.lingala.zip4j.progress.ProgressMonitor): void; public getZipModel(): net.lingala.zip4j.model.ZipModel; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean, param2: net.lingala.zip4j.model.ZipModel); public getTask(): net.lingala.zip4j.progress.ProgressMonitor.Task; } } } } } declare module net { export module lingala { export module zip4j { export module tasks { export abstract class AbstractZipTaskParameters { public static class: java.lang.Class<net.lingala.zip4j.tasks.AbstractZipTaskParameters>; public charset: java.nio.charset.Charset; public constructor(param0: java.nio.charset.Charset); } } } } } declare module net { export module lingala { export module zip4j { export module tasks { export class AddFilesToZipTask extends net.lingala.zip4j.tasks.AbstractAddFileToZipTask<net.lingala.zip4j.tasks.AddFilesToZipTask.AddFilesToZipTaskParameters> { public static class: java.lang.Class<net.lingala.zip4j.tasks.AddFilesToZipTask>; public executeTask(param0: net.lingala.zip4j.tasks.AddFilesToZipTask.AddFilesToZipTaskParameters, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public executeTask(param0: any, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean, param2: net.lingala.zip4j.model.ZipModel, param3: native.Array<string>, param4: net.lingala.zip4j.headers.HeaderWriter); public calculateTotalWork(param0: any): number; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean); public calculateTotalWork(param0: net.lingala.zip4j.tasks.AddFilesToZipTask.AddFilesToZipTaskParameters): number; public getTask(): net.lingala.zip4j.progress.ProgressMonitor.Task; } export module AddFilesToZipTask { export class AddFilesToZipTaskParameters extends net.lingala.zip4j.tasks.AbstractZipTaskParameters { public static class: java.lang.Class<net.lingala.zip4j.tasks.AddFilesToZipTask.AddFilesToZipTaskParameters>; public constructor(param0: java.util.List<java.io.File>, param1: net.lingala.zip4j.model.ZipParameters, param2: java.nio.charset.Charset); public constructor(param0: java.nio.charset.Charset); } } } } } } declare module net { export module lingala { export module zip4j { export module tasks { export class AddFolderToZipTask extends net.lingala.zip4j.tasks.AbstractAddFileToZipTask<net.lingala.zip4j.tasks.AddFolderToZipTask.AddFolderToZipTaskParameters> { public static class: java.lang.Class<net.lingala.zip4j.tasks.AddFolderToZipTask>; public executeTask(param0: any, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean, param2: net.lingala.zip4j.model.ZipModel, param3: native.Array<string>, param4: net.lingala.zip4j.headers.HeaderWriter); public calculateTotalWork(param0: any): number; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean); public executeTask(param0: net.lingala.zip4j.tasks.AddFolderToZipTask.AddFolderToZipTaskParameters, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public calculateTotalWork(param0: net.lingala.zip4j.tasks.AddFolderToZipTask.AddFolderToZipTaskParameters): number; } export module AddFolderToZipTask { export class AddFolderToZipTaskParameters extends net.lingala.zip4j.tasks.AbstractZipTaskParameters { public static class: java.lang.Class<net.lingala.zip4j.tasks.AddFolderToZipTask.AddFolderToZipTaskParameters>; public constructor(param0: java.io.File, param1: net.lingala.zip4j.model.ZipParameters, param2: java.nio.charset.Charset); public constructor(param0: java.nio.charset.Charset); } } } } } } declare module net { export module lingala { export module zip4j { export module tasks { export class AddStreamToZipTask extends net.lingala.zip4j.tasks.AbstractAddFileToZipTask<net.lingala.zip4j.tasks.AddStreamToZipTask.AddStreamToZipTaskParameters> { public static class: java.lang.Class<net.lingala.zip4j.tasks.AddStreamToZipTask>; public executeTask(param0: net.lingala.zip4j.tasks.AddStreamToZipTask.AddStreamToZipTaskParameters, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public executeTask(param0: any, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean, param2: net.lingala.zip4j.model.ZipModel, param3: native.Array<string>, param4: net.lingala.zip4j.headers.HeaderWriter); public calculateTotalWork(param0: any): number; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean); public calculateTotalWork(param0: net.lingala.zip4j.tasks.AddStreamToZipTask.AddStreamToZipTaskParameters): number; } export module AddStreamToZipTask { export class AddStreamToZipTaskParameters extends net.lingala.zip4j.tasks.AbstractZipTaskParameters { public static class: java.lang.Class<net.lingala.zip4j.tasks.AddStreamToZipTask.AddStreamToZipTaskParameters>; public constructor(param0: java.io.InputStream, param1: net.lingala.zip4j.model.ZipParameters, param2: java.nio.charset.Charset); public constructor(param0: java.nio.charset.Charset); } } } } } } declare module net { export module lingala { export module zip4j { export module tasks { export abstract class AsyncZipTask<T> extends java.lang.Object { public static class: java.lang.Class<net.lingala.zip4j.tasks.AsyncZipTask<any>>; public executeTask(param0: T, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public calculateTotalWork(param0: T): number; public verifyIfTaskIsCancelled(): void; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean); public execute(param0: T): void; public getTask(): net.lingala.zip4j.progress.ProgressMonitor.Task; } } } } } declare module net { export module lingala { export module zip4j { export module tasks { export class ExtractAllFilesTask extends net.lingala.zip4j.tasks.AbstractExtractFileTask<net.lingala.zip4j.tasks.ExtractAllFilesTask.ExtractAllFilesTaskParameters> { public static class: java.lang.Class<net.lingala.zip4j.tasks.ExtractAllFilesTask>; public calculateTotalWork(param0: net.lingala.zip4j.tasks.ExtractAllFilesTask.ExtractAllFilesTaskParameters): number; public executeTask(param0: net.lingala.zip4j.tasks.ExtractAllFilesTask.ExtractAllFilesTaskParameters, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public executeTask(param0: any, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean, param2: net.lingala.zip4j.model.ZipModel, param3: native.Array<string>); public calculateTotalWork(param0: any): number; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean); public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean, param2: net.lingala.zip4j.model.ZipModel); } export module ExtractAllFilesTask { export class ExtractAllFilesTaskParameters extends net.lingala.zip4j.tasks.AbstractZipTaskParameters { public static class: java.lang.Class<net.lingala.zip4j.tasks.ExtractAllFilesTask.ExtractAllFilesTaskParameters>; public constructor(param0: string, param1: java.nio.charset.Charset); public constructor(param0: java.nio.charset.Charset); } } } } } } declare module net { export module lingala { export module zip4j { export module tasks { export class ExtractFileTask extends net.lingala.zip4j.tasks.AbstractExtractFileTask<net.lingala.zip4j.tasks.ExtractFileTask.ExtractFileTaskParameters> { public static class: java.lang.Class<net.lingala.zip4j.tasks.ExtractFileTask>; public executeTask(param0: net.lingala.zip4j.tasks.ExtractFileTask.ExtractFileTaskParameters, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public calculateTotalWork(param0: net.lingala.zip4j.tasks.ExtractFileTask.ExtractFileTaskParameters): number; public executeTask(param0: any, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean, param2: net.lingala.zip4j.model.ZipModel, param3: native.Array<string>); public calculateTotalWork(param0: any): number; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean); public createZipInputStream(param0: net.lingala.zip4j.model.FileHeader, param1: java.nio.charset.Charset): net.lingala.zip4j.io.inputstream.ZipInputStream; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean, param2: net.lingala.zip4j.model.ZipModel); } export module ExtractFileTask { export class ExtractFileTaskParameters extends net.lingala.zip4j.tasks.AbstractZipTaskParameters { public static class: java.lang.Class<net.lingala.zip4j.tasks.ExtractFileTask.ExtractFileTaskParameters>; public constructor(param0: string, param1: net.lingala.zip4j.model.FileHeader, param2: string, param3: java.nio.charset.Charset); public constructor(param0: java.nio.charset.Charset); } } } } } } declare module net { export module lingala { export module zip4j { export module tasks { export class MergeSplitZipFileTask extends net.lingala.zip4j.tasks.AsyncZipTask<net.lingala.zip4j.tasks.MergeSplitZipFileTask.MergeSplitZipFileTaskParameters> { public static class: java.lang.Class<net.lingala.zip4j.tasks.MergeSplitZipFileTask>; public executeTask(param0: net.lingala.zip4j.tasks.MergeSplitZipFileTask.MergeSplitZipFileTaskParameters, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public executeTask(param0: any, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public calculateTotalWork(param0: any): number; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean); public calculateTotalWork(param0: net.lingala.zip4j.tasks.MergeSplitZipFileTask.MergeSplitZipFileTaskParameters): number; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean, param2: net.lingala.zip4j.model.ZipModel); public getTask(): net.lingala.zip4j.progress.ProgressMonitor.Task; } export module MergeSplitZipFileTask { export class MergeSplitZipFileTaskParameters extends net.lingala.zip4j.tasks.AbstractZipTaskParameters { public static class: java.lang.Class<net.lingala.zip4j.tasks.MergeSplitZipFileTask.MergeSplitZipFileTaskParameters>; public constructor(param0: java.io.File, param1: java.nio.charset.Charset); public constructor(param0: java.nio.charset.Charset); } } } } } } declare module net { export module lingala { export module zip4j { export module tasks { export class RemoveEntryFromZipFileTask extends net.lingala.zip4j.tasks.AsyncZipTask<net.lingala.zip4j.tasks.RemoveEntryFromZipFileTask.RemoveEntryFromZipFileTaskParameters> { public static class: java.lang.Class<net.lingala.zip4j.tasks.RemoveEntryFromZipFileTask>; public executeTask(param0: any, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public calculateTotalWork(param0: any): number; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean); public executeTask(param0: net.lingala.zip4j.tasks.RemoveEntryFromZipFileTask.RemoveEntryFromZipFileTaskParameters, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public calculateTotalWork(param0: net.lingala.zip4j.tasks.RemoveEntryFromZipFileTask.RemoveEntryFromZipFileTaskParameters): number; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean, param2: net.lingala.zip4j.model.ZipModel); public getTask(): net.lingala.zip4j.progress.ProgressMonitor.Task; } export module RemoveEntryFromZipFileTask { export class RemoveEntryFromZipFileTaskParameters extends net.lingala.zip4j.tasks.AbstractZipTaskParameters { public static class: java.lang.Class<net.lingala.zip4j.tasks.RemoveEntryFromZipFileTask.RemoveEntryFromZipFileTaskParameters>; public constructor(param0: net.lingala.zip4j.model.FileHeader, param1: java.nio.charset.Charset); public constructor(param0: java.nio.charset.Charset); } } } } } } declare module net { export module lingala { export module zip4j { export module tasks { export class SetCommentTask extends net.lingala.zip4j.tasks.AsyncZipTask<net.lingala.zip4j.tasks.SetCommentTask.SetCommentTaskTaskParameters> { public static class: java.lang.Class<net.lingala.zip4j.tasks.SetCommentTask>; public executeTask(param0: any, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public calculateTotalWork(param0: any): number; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean); public executeTask(param0: net.lingala.zip4j.tasks.SetCommentTask.SetCommentTaskTaskParameters, param1: net.lingala.zip4j.progress.ProgressMonitor): void; public constructor(param0: net.lingala.zip4j.progress.ProgressMonitor, param1: boolean, param2: net.lingala.zip4j.model.ZipModel); public calculateTotalWork(param0: net.lingala.zip4j.tasks.SetCommentTask.SetCommentTaskTaskParameters): number; public getTask(): net.lingala.zip4j.progress.ProgressMonitor.Task; } export module SetCommentTask { export class SetCommentTaskTaskParameters extends net.lingala.zip4j.tasks.AbstractZipTaskParameters { public static class: java.lang.Class<net.lingala.zip4j.tasks.SetCommentTask.SetCommentTaskTaskParameters>; public constructor(param0: string, param1: java.nio.charset.Charset); public constructor(param0: java.nio.charset.Charset); } } } } } } declare module net { export module lingala { export module zip4j { export module util { export class BitUtils { public static class: java.lang.Class<net.lingala.zip4j.util.BitUtils>; public static unsetBit(param0: number, param1: number): number; public constructor(); public static isBitSet(param0: number, param1: number): boolean; public static setBit(param0: number, param1: number): number; } } } } } declare module net { export module lingala { export module zip4j { export module util { export class CrcUtil { public static class: java.lang.Class<net.lingala.zip4j.util.CrcUtil>; public static computeFileCrc(param0: java.io.File, param1: net.lingala.zip4j.progress.ProgressMonitor): number; public constructor(); } } } } } declare module net { export module lingala { export module zip4j { export module util { export class FileUtils { public static class: java.lang.Class<net.lingala.zip4j.util.FileUtils>; public static getFilesInDirectoryRecursive(param0: java.io.File, param1: boolean, param2: boolean): java.util.List<java.io.File>; public static isZipEntryDirectory(param0: string): boolean; public constructor(); public static setFileLastModifiedTime(param0: any /*java.nio.file.Path*/, param1: number): void; public static getZipFileNameWithoutExtension(param0: string): string; public static getSplitZipFiles(param0: net.lingala.zip4j.model.ZipModel): java.util.List<java.io.File>; public static getFileAttributes(param0: java.io.File): native.Array<number>; public static assertFilesExist(param0: java.util.List<java.io.File>): void; public static setFileLastModifiedTimeWithoutNio(param0: java.io.File, param1: number): void; public static getRelativeFileName(param0: string, param1: string, param2: string): string; public static setFileAttributes(param0: any /*java.nio.file.Path*/, param1: native.Array<number>): void; public static copyFile(param0: java.io.RandomAccessFile, param1: java.io.OutputStream, param2: number, param3: number, param4: net.lingala.zip4j.progress.ProgressMonitor): void; } } } } } declare module net { export module lingala { export module zip4j { export module util { export class InternalZipConstants { public static class: java.lang.Class<net.lingala.zip4j.util.InternalZipConstants>; public static ENDHDR: number; public static STD_DEC_HDR_SIZE: number; public static AES_AUTH_LENGTH: number; public static AES_BLOCK_SIZE: number; public static MIN_SPLIT_LENGTH: number; public static ZIP_64_SIZE_LIMIT: number; public static ZIP_64_NUMBER_OF_ENTRIES_LIMIT: number; public static BUFF_SIZE: number; public static UPDATE_LFH_CRC: number; public static UPDATE_LFH_COMP_SIZE: number; public static UPDATE_LFH_UNCOMP_SIZE: number; public static ZIP_STANDARD_CHARSET: string; public static FILE_SEPARATOR: string; public static ZIP_FILE_SEPARATOR: string; public static MAX_ALLOWED_ZIP_COMMENT_LENGTH: number; public static CHARSET_UTF_8: java.nio.charset.Charset; } } } } } declare module net { export module lingala { export module zip4j { export module util { export class RawIO { public static class: java.lang.Class<net.lingala.zip4j.util.RawIO>; public writeLongLittleEndian(param0: native.Array<number>, param1: number, param2: number): void; public writeLongLittleEndian(param0: java.io.OutputStream, param1: number): void; public writeShortLittleEndian(param0: java.io.OutputStream, param1: number): void; public readLongLittleEndian(param0: java.io.RandomAccessFile): number; public readLongLittleEndian(param0: java.io.RandomAccessFile, param1: number): number; public readIntLittleEndian(param0: java.io.InputStream): number; public writeShortLittleEndian(param0: native.Array<number>, param1: number, param2: number): void; public readLongLittleEndian(param0: native.Array<number>, param1: number): number; public readShortLittleEndian(param0: native.Array<number>, param1: number): number; public readShortLittleEndian(param0: java.io.InputStream): number; public readIntLittleEndian(param0: native.Array<number>, param1: number): number; public constructor(); public readLongLittleEndian(param0: java.io.InputStream, param1: number): number; public readLongLittleEndian(param0: java.io.InputStream): number; public writeIntLittleEndian(param0: native.Array<number>, param1: number, param2: number): void; public readShortLittleEndian(param0: java.io.RandomAccessFile): number; public readIntLittleEndian(param0: java.io.RandomAccessFile): number; public readIntLittleEndian(param0: native.Array<number>): number; public writeIntLittleEndian(param0: java.io.OutputStream, param1: number): void; } } } } } declare module net { export module lingala { export module zip4j { export module util { export class UnzipUtil { public static class: java.lang.Class<net.lingala.zip4j.util.UnzipUtil>; public static createZipInputStream(param0: net.lingala.zip4j.model.ZipModel, param1: net.lingala.zip4j.model.FileHeader, param2: native.Array<string>): net.lingala.zip4j.io.inputstream.ZipInputStream; public constructor(); public static applyFileAttributes(param0: net.lingala.zip4j.model.FileHeader, param1: java.io.File): void; } } } } } declare module net { export module lingala { export module zip4j { export module util { export class Zip4jUtil { public static class: java.lang.Class<net.lingala.zip4j.util.Zip4jUtil>; public constructor(); public static createDirectoryIfNotExists(param0: java.io.File): boolean; public static javaToDosTime(param0: number): number; public static getCompressionMethod(param0: net.lingala.zip4j.model.LocalFileHeader): net.lingala.zip4j.model.enums.CompressionMethod; public static convertCharArrayToByteArray(param0: native.Array<string>): native.Array<number>; public static readFully(param0: java.io.InputStream, param1: native.Array<number>, param2: number, param3: number): number; public static isStringNotNullAndNotEmpty(param0: string): boolean; public static readFully(param0: java.io.InputStream, param1: native.Array<number>): number; public static dosToJavaTme(param0: number): number; } } } } } //Generics information: //net.lingala.zip4j.io.inputstream.CipherInputStream:1 //net.lingala.zip4j.io.outputstream.CipherOutputStream:1 //net.lingala.zip4j.tasks.AbstractAddFileToZipTask:1 //net.lingala.zip4j.tasks.AbstractExtractFileTask:1 //net.lingala.zip4j.tasks.AsyncZipTask:1
the_stack
// @ts-nocheck // o object_name | g group_name const OBJECT_RE = /^[og]\s*(.+)?/; // mtllib file_reference const MATERIAL_RE = /^mtllib /; // usemtl material_name const MATERIAL_USE_RE = /^usemtl /; class MeshMaterial { constructor({index, name = '', mtllib, smooth, groupStart}) { this.index = index; this.name = name; this.mtllib = mtllib; this.smooth = smooth; this.groupStart = groupStart; this.groupEnd = -1; this.groupCount = -1; this.inherited = false; } clone(index = this.index) { return new MeshMaterial({ index, name: this.name, mtllib: this.mtllib, smooth: this.smooth, groupStart: 0 }); } } class MeshObject { constructor(name = '') { this.name = name; this.geometry = { vertices: [], normals: [], colors: [], uvs: [] }; this.materials = []; this.smooth = true; this.fromDeclaration = null; } startMaterial(name, libraries) { const previous = this._finalize(false); // New usemtl declaration overwrites an inherited material, except if faces were declared // after the material, then it must be preserved for proper MultiMaterial continuation. if (previous && (previous.inherited || previous.groupCount <= 0)) { this.materials.splice(previous.index, 1); } const material = new MeshMaterial({ index: this.materials.length, name, mtllib: Array.isArray(libraries) && libraries.length > 0 ? libraries[libraries.length - 1] : '', smooth: previous !== undefined ? previous.smooth : this.smooth, groupStart: previous !== undefined ? previous.groupEnd : 0 }); this.materials.push(material); return material; } currentMaterial() { if (this.materials.length > 0) { return this.materials[this.materials.length - 1]; } return undefined; } _finalize(end) { const lastMultiMaterial = this.currentMaterial(); if (lastMultiMaterial && lastMultiMaterial.groupEnd === -1) { lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3; lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart; lastMultiMaterial.inherited = false; } // Ignore objects tail materials if no face declarations followed them before a new o/g started. if (end && this.materials.length > 1) { for (let mi = this.materials.length - 1; mi >= 0; mi--) { if (this.materials[mi].groupCount <= 0) { this.materials.splice(mi, 1); } } } // Guarantee at least one empty material, this makes the creation later more straight forward. if (end && this.materials.length === 0) { this.materials.push({ name: '', smooth: this.smooth }); } return lastMultiMaterial; } } class ParserState { constructor() { this.objects = []; this.object = null; this.vertices = []; this.normals = []; this.colors = []; this.uvs = []; this.materialLibraries = []; this.startObject('', false); } startObject(name, fromDeclaration = true) { // If the current object (initial from reset) is not from a g/o declaration in the parsed // file. We need to use it for the first parsed g/o to keep things in sync. if (this.object && !this.object.fromDeclaration) { this.object.name = name; this.object.fromDeclaration = fromDeclaration; return; } const previousMaterial = this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined; if (this.object && typeof this.object._finalize === 'function') { this.object._finalize(true); } this.object = new MeshObject(name); this.object.fromDeclaration = fromDeclaration; // Inherit previous objects material. // Spec tells us that a declared material must be set to all objects until a new material is declared. // If a usemtl declaration is encountered while this new object is being parsed, it will // overwrite the inherited material. Exception being that there was already face declarations // to the inherited material, then it will be preserved for proper MultiMaterial continuation. if (previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function') { const declared = previousMaterial.clone(0); declared.inherited = true; this.object.materials.push(declared); } this.objects.push(this.object); } finalize() { if (this.object && typeof this.object._finalize === 'function') { this.object._finalize(true); } } parseVertexIndex(value, len) { const index = parseInt(value); return (index >= 0 ? index - 1 : index + len / 3) * 3; } parseNormalIndex(value, len) { const index = parseInt(value); return (index >= 0 ? index - 1 : index + len / 3) * 3; } parseUVIndex(value, len) { const index = parseInt(value); return (index >= 0 ? index - 1 : index + len / 2) * 2; } addVertex(a, b, c) { const src = this.vertices; const dst = this.object.geometry.vertices; dst.push(src[a + 0], src[a + 1], src[a + 2]); dst.push(src[b + 0], src[b + 1], src[b + 2]); dst.push(src[c + 0], src[c + 1], src[c + 2]); } addVertexPoint(a) { const src = this.vertices; const dst = this.object.geometry.vertices; dst.push(src[a + 0], src[a + 1], src[a + 2]); } addVertexLine(a) { const src = this.vertices; const dst = this.object.geometry.vertices; dst.push(src[a + 0], src[a + 1], src[a + 2]); } addNormal(a, b, c) { const src = this.normals; const dst = this.object.geometry.normals; dst.push(src[a + 0], src[a + 1], src[a + 2]); dst.push(src[b + 0], src[b + 1], src[b + 2]); dst.push(src[c + 0], src[c + 1], src[c + 2]); } addColor(a, b, c) { const src = this.colors; const dst = this.object.geometry.colors; dst.push(src[a + 0], src[a + 1], src[a + 2]); dst.push(src[b + 0], src[b + 1], src[b + 2]); dst.push(src[c + 0], src[c + 1], src[c + 2]); } addUV(a, b, c) { const src = this.uvs; const dst = this.object.geometry.uvs; dst.push(src[a + 0], src[a + 1]); dst.push(src[b + 0], src[b + 1]); dst.push(src[c + 0], src[c + 1]); } addUVLine(a) { const src = this.uvs; const dst = this.object.geometry.uvs; dst.push(src[a + 0], src[a + 1]); } // eslint-disable-next-line max-params addFace(a, b, c, ua, ub, uc, na, nb, nc) { const vLen = this.vertices.length; let ia = this.parseVertexIndex(a, vLen); let ib = this.parseVertexIndex(b, vLen); let ic = this.parseVertexIndex(c, vLen); this.addVertex(ia, ib, ic); if (ua !== undefined && ua !== '') { const uvLen = this.uvs.length; ia = this.parseUVIndex(ua, uvLen); ib = this.parseUVIndex(ub, uvLen); ic = this.parseUVIndex(uc, uvLen); this.addUV(ia, ib, ic); } if (na !== undefined && na !== '') { // Normals are many times the same. If so, skip function call and parseInt. const nLen = this.normals.length; ia = this.parseNormalIndex(na, nLen); ib = na === nb ? ia : this.parseNormalIndex(nb, nLen); ic = na === nc ? ia : this.parseNormalIndex(nc, nLen); this.addNormal(ia, ib, ic); } if (this.colors.length > 0) { this.addColor(ia, ib, ic); } } addPointGeometry(vertices) { this.object.geometry.type = 'Points'; const vLen = this.vertices.length; for (const vertex of vertices) { this.addVertexPoint(this.parseVertexIndex(vertex, vLen)); } } addLineGeometry(vertices, uvs) { this.object.geometry.type = 'Line'; const vLen = this.vertices.length; const uvLen = this.uvs.length; for (const vertex of vertices) { this.addVertexLine(this.parseVertexIndex(vertex, vLen)); } for (const uv of uvs) { this.addUVLine(this.parseUVIndex(uv, uvLen)); } } } // eslint-disable-next-line max-statements, complexity export default (text) => { const state = new ParserState(); if (text.indexOf('\r\n') !== -1) { // This is faster than String.split with regex that splits on both text = text.replace(/\r\n/g, '\n'); } if (text.indexOf('\\\n') !== -1) { // join lines separated by a line continuation character (\) text = text.replace(/\\\n/g, ''); } const lines = text.split('\n'); let line = ''; let lineFirstChar = ''; let lineLength = 0; let result = []; // Faster to just trim left side of the line. Use if available. const trimLeft = typeof ''.trimLeft === 'function'; /* eslint-disable no-continue, max-depth */ for (let i = 0, l = lines.length; i < l; i++) { line = lines[i]; line = trimLeft ? line.trimLeft() : line.trim(); lineLength = line.length; if (lineLength === 0) continue; lineFirstChar = line.charAt(0); // @todo invoke passed in handler if any if (lineFirstChar === '#') continue; if (lineFirstChar === 'v') { const data = line.split(/\s+/); switch (data[0]) { case 'v': state.vertices.push(parseFloat(data[1]), parseFloat(data[2]), parseFloat(data[3])); if (data.length === 8) { state.colors.push(parseFloat(data[4]), parseFloat(data[5]), parseFloat(data[6])); } break; case 'vn': state.normals.push(parseFloat(data[1]), parseFloat(data[2]), parseFloat(data[3])); break; case 'vt': state.uvs.push(parseFloat(data[1]), parseFloat(data[2])); break; default: } } else if (lineFirstChar === 'f') { const lineData = line.substr(1).trim(); const vertexData = lineData.split(/\s+/); const faceVertices = []; // Parse the face vertex data into an easy to work with format for (let j = 0, jl = vertexData.length; j < jl; j++) { const vertex = vertexData[j]; if (vertex.length > 0) { const vertexParts = vertex.split('/'); faceVertices.push(vertexParts); } } // Draw an edge between the first vertex and all subsequent vertices to form an n-gon const v1 = faceVertices[0]; for (let j = 1, jl = faceVertices.length - 1; j < jl; j++) { const v2 = faceVertices[j]; const v3 = faceVertices[j + 1]; state.addFace(v1[0], v2[0], v3[0], v1[1], v2[1], v3[1], v1[2], v2[2], v3[2]); } } else if (lineFirstChar === 'l') { const lineParts = line.substring(1).trim().split(' '); let lineVertices; const lineUVs = []; if (line.indexOf('/') === -1) { lineVertices = lineParts; } else { lineVertices = []; for (let li = 0, llen = lineParts.length; li < llen; li++) { const parts = lineParts[li].split('/'); if (parts[0] !== '') lineVertices.push(parts[0]); if (parts[1] !== '') lineUVs.push(parts[1]); } } state.addLineGeometry(lineVertices, lineUVs); } else if (lineFirstChar === 'p') { const lineData = line.substr(1).trim(); const pointData = lineData.split(' '); state.addPointGeometry(pointData); } else if ((result = OBJECT_RE.exec(line)) !== null) { // o object_name // or // g group_name // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869 // var name = result[ 0 ].substr( 1 ).trim(); const name = (' ' + result[0].substr(1).trim()).substr(1); // eslint-disable-line state.startObject(name); } else if (MATERIAL_USE_RE.test(line)) { // material state.object.startMaterial(line.substring(7).trim(), state.materialLibraries); } else if (MATERIAL_RE.test(line)) { // mtl file state.materialLibraries.push(line.substring(7).trim()); } else if (lineFirstChar === 's') { result = line.split(' '); // smooth shading // @todo Handle files that have varying smooth values for a set of faces inside one geometry, // but does not define a usemtl for each face set. // This should be detected and a dummy material created (later MultiMaterial and geometry groups). // This requires some care to not create extra material on each smooth value for "normal" obj files. // where explicit usemtl defines geometry groups. // Example asset: examples/models/obj/cerberus/Cerberus.obj /* * http://paulbourke.net/dataformats/obj/ * or * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf * * From chapter "Grouping" Syntax explanation "s group_number": * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form * surfaces, smoothing groups are either turned on or off; there is no difference between values greater * than 0." */ if (result.length > 1) { const value = result[1].trim().toLowerCase(); state.object.smooth = value !== '0' && value !== 'off'; } else { // ZBrush can produce "s" lines #11707 state.object.smooth = true; } const material = state.object.currentMaterial(); if (material) material.smooth = state.object.smooth; } else { // Handle null terminated files without exception if (line === '\0') continue; throw new Error(`Unexpected line: "${line}"`); } } state.finalize(); const meshes = []; const materials = []; for (const object of state.objects) { const {geometry} = object; // Skip o/g line declarations that did not follow with any faces if (geometry.vertices.length === 0) continue; const mesh = { header: { vertexCount: geometry.vertices.length / 3 }, attributes: {} }; switch (geometry.type) { case 'Points': mesh.mode = 0; // GL.POINTS break; case 'Line': mesh.mode = 1; // GL.LINES break; default: mesh.mode = 4; // GL.TRIANGLES break; } mesh.attributes.POSITION = {value: new Float32Array(geometry.vertices), size: 3}; if (geometry.normals.length > 0) { mesh.attributes.NORMAL = {value: new Float32Array(geometry.normals), size: 3}; } if (geometry.colors.length > 0) { mesh.attributes.COLOR_0 = {value: new Float32Array(geometry.colors), size: 3}; } if (geometry.uvs.length > 0) { mesh.attributes.TEXCOORD_0 = {value: new Float32Array(geometry.uvs), size: 2}; } // Create materials mesh.materials = []; for (const sourceMaterial of object.materials) { // TODO - support full spec const _material = { name: sourceMaterial.name, flatShading: !sourceMaterial.smooth }; mesh.materials.push(_material); materials.push(_material); } mesh.name = object.name; meshes.push(mesh); } return {meshes, materials}; };
the_stack
import { Component, State, Element, h } from '@stencil/core'; import Utils from '@visa/visa-charts-utils'; // import 'core-js/features/symbol'; import '@visa/scatter-plot'; const { autoTextColor } = Utils; @Component({ tag: 'app-bivariate-mapbox-map', styleUrl: 'app-bivariate-mapbox-map.scss' }) export class AppBivariateMapboxMap { @State() data: any = []; @State() mapboxToken: string = ''; @State() pinnedIDs: any = ['94404']; @State() clickElements: any = [0, 1, 2, 3, 4, 5, 6, 7, 8]; @State() value: any = 0; // this is for handling value changes for button to control which dataset to send @State() hoveringElement: string = ''; @State() pinStyle: any = { size: 20, overrideColor: '#F2B602' }; @State() zoomThreshold: number = 10; @State() title: string = 'Mapbox Map'; @State() subtitle: string = 'This is a custom mapbox component'; @State() palette: string = 'bluePurple'; @State() defaultColor: string = '#F7F7F7'; // '#FAF7FA'; // '#CCCCCC' @State() height: number = 500; @State() width: number = 1100; @State() stateTrigger: boolean = false; @State() lassos: any = {}; @State() selection: any = []; @State() zipSelection: any = []; @State() bounds: any = []; @State() moveToToggle: boolean = false; @State() showMissingData: boolean = true; @State() showEmptyData: boolean = false; // @Event() updateComponent: EventEmitter; @State() msaMapData: any = []; @State() zipMapData: any = []; @State() zipDataPrepped: any = []; @State() decimatedZipData: any = []; @State() currentLassos: any = {}; @State() randomPin: string = '39820'; @State() savedLassos: any = {}; @State() selected: number = 0; @State() showMe: boolean = false; @State() extents: any = { zip: { 'Metric 2': { min: Infinity, max: 0 }, 'Metric 1': { min: Infinity, max: 0 } }, msa: { 'Metric 2': { min: Infinity, max: 0 }, 'Metric 1': { min: Infinity, max: 0 } } }; @State() boundsHash: any = { msa: {}, zip: {} }; @State() currentCounts: any = { msa: 0, zip: 0 }; @State() bivariateTitles: any = { msa: [ { colorKey: 6, color: '#be64ac', count: 0, metric1: 'High Metric 1', metric2: 'Low Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 7, color: '#8c62aa', count: 0, metric1: 'High Metric 1', metric2: 'Med Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 8, color: '#3b4994', count: 0, metric1: 'High Metric 1', metric2: 'High Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 3, color: '#dfb0d6', count: 0, metric1: 'Med Metric 1', metric2: 'Low Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 4, color: '#a5add3', count: 0, metric1: 'Med Metric 1', metric2: 'Med Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 5, color: '#5698b9', count: 0, metric1: 'Med Metric 1', metric2: 'High Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 0, color: '#e8e8e8', count: 0, metric1: 'Low Metric 1', metric2: 'Low Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 1, color: '#ace4e4', count: 0, metric1: 'Low Metric 1', metric2: 'Med Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 2, color: '#5ac8c8', count: 0, metric1: 'Low Metric 1', metric2: 'High Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } } ], zip: [ { colorKey: 6, color: '#be64ac', count: 0, metric1: 'High Metric 1', metric2: 'Low Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 7, color: '#8c62aa', count: 0, metric1: 'High Metric 1', metric2: 'Med Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 8, color: '#3b4994', count: 0, metric1: 'High Metric 1', metric2: 'High Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 3, color: '#dfb0d6', count: 0, metric1: 'Med Metric 1', metric2: 'Low Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 4, color: '#a5add3', count: 0, metric1: 'Med Metric 1', metric2: 'Med Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 5, color: '#5698b9', count: 0, metric1: 'Med Metric 1', metric2: 'High Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 0, color: '#e8e8e8', count: 0, metric1: 'Low Metric 1', metric2: 'Low Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 1, color: '#ace4e4', count: 0, metric1: 'Low Metric 1', metric2: 'Med Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } }, { colorKey: 2, color: '#5ac8c8', count: 0, metric1: 'Low Metric 1', metric2: 'High Metric 2', 'Metric 1': { min: 0, max: 0 }, 'Metric 2': { min: 0, max: 0 } } ] }; msaCustomers: string = 'http://localhost:3333/data/msaData.json'; zipCustomers: string = 'http://localhost:3333/data/zipData.json'; msaBoundaries: string = 'http://localhost:3333/data/msaBoundaries.json'; zipBoundaries: string = 'http://localhost:3333/data/zipBoundaries.json'; msaToZipBaseHref: string = 'http://localhost:3333/data/'; msaDataPrepped: any = []; valueAccessors: any = ['Metric 1', 'Metric 2']; @Element() appEl: HTMLElement; componentWillLoad() { const msaPromise = this.get(this.msaCustomers).then( (response: string) => { return response; }, error => { console.log('MSA Request Error', error); } ); const zipPromise = this.get(this.zipCustomers).then( (response: string) => { return response; }, error => { console.log('ZIP Request Error', error); } ); const msaHashPromise = this.get(this.msaBoundaries).then( (response: string) => { return response; }, error => { console.log('MSA Bounds Request Error', error); } ); const zipHashPromise = this.get(this.zipBoundaries).then( (response: string) => { return response; }, error => { console.log('ZIP Bounds Request Error', error); } ); return Promise.all([msaPromise, zipPromise, msaHashPromise, zipHashPromise]).then(responses => { const msaResponse = responses[0] || '[]'; const zipResponse = responses[1] || '[]'; const msaHash = responses[2] || '[]'; const zipHash = responses[3] || '[]'; this.msaDataPrepped = JSON.parse(msaResponse); this.zipDataPrepped = JSON.parse(zipResponse); this.boundsHash.msa = JSON.parse(msaHash)[0]; this.boundsHash.zip = JSON.parse(zipHash)[0]; let msaI = 0; this.msaDataPrepped.forEach(msa => { msa.MapID = msa['MSA Id']; msa.Name = msa['MSA Name']; if (msaI % 13 === 0) { msa.cannotShow = true; msa['Metric 1'] = null; msa['Metric 2'] = null; } msaI++; }); this.msaMapData = this.msaDataPrepped; let i = 0; const zipDecimation = []; this.zipDataPrepped.forEach(zip => { zip.MapID = zip.Zip; zip.Name = 'Belongs to MSA: ' + zip['MSA Name']; if (i % 13 === 0) { zip.cannotShow = true; zip['Metric 1'] = null; zip['Metric 2'] = null; zipDecimation.push(zip); } i++; }); zipDecimation.push({ 'Metric 1': 0, 'Metric 2': 0 }); this.zipMapData = this.zipDataPrepped; this.decimatedZipData = zipDecimation; }); } // Demo Interactivity changeBivariate = e => { let tempState = [...this.clickElements]; const value = parseInt(e.target.getAttribute('data-colorKey'), 10); const index = tempState.indexOf(value); if (tempState.length === 9) { tempState = [value]; } else if (index > -1) { if (tempState.length === 1) { tempState = [0, 1, 2, 3, 4, 5, 6, 7, 8]; } else { tempState.splice(index, 1); } } else { tempState.push(value); } this.clickElements = tempState; this.showMissingData = tempState.length === 9 ? true : false; }; onHoverFunction = e => { const d = e.detail; // console.log('we made it to hover function!', e, d); this.hoveringElement = d[0] && d[0]['Name'] ? d[0]['Name'] : d[0] && d[0].MapID ? d[0].MapID : ''; }; onBivariateChangeFunction = e => { const d = e.detail; let i = 0; d.zip.forEach(cellData => { this.bivariateTitles.zip[i].count = cellData.count; this.bivariateTitles.zip[i]['Metric 1'] = cellData['Metric 1']; this.bivariateTitles.zip[i]['Metric 2'] = cellData['Metric 2']; i++; }); i = 0; d.msa.forEach(cellData => { this.bivariateTitles.msa[i].count = cellData.count; this.bivariateTitles.msa[i]['Metric 1'] = cellData['Metric 1']; this.bivariateTitles.msa[i]['Metric 2'] = cellData['Metric 2']; i++; }); this.extents.zip['Metric 2'].min = d.zip[6]['Metric 2'].min; this.extents.zip['Metric 1'].min = d.zip[6]['Metric 1'].min; this.extents.msa['Metric 2'].min = d.msa[6]['Metric 2'].min; this.extents.msa['Metric 1'].min = d.msa[6]['Metric 1'].min; this.extents.zip['Metric 2'].max = d.zip[2]['Metric 2'].max; this.extents.zip['Metric 1'].max = d.zip[2]['Metric 1'].max; this.extents.msa['Metric 2'].max = d.msa[2]['Metric 2'].max; this.extents.msa['Metric 1'].max = d.msa[2]['Metric 1'].max; }; onClickFunction = e => { const d = e.detail; if (this.selection.length && d.msa.length && d.msa[0].MapID === this.selection[0].MapID) { if (this.bounds.length && this.moveToToggle) { this.bounds = []; } this.selection = []; this.selected = 0; } else if (d.msa[0]) { if (this.moveToToggle) { this.bounds = [this.boundsHash.msa[d.msa[0].MapID]]; } this.selection = [d.msa[0]]; this.selected = 1; } if (this.zipSelection.length && d.zip.length && d.zip[0].MapID === this.zipSelection[0].MapID) { if (this.bounds.length && this.moveToToggle) { this.bounds = []; } this.zipSelection = []; this.selected = 0; } else if (d.zip[0]) { if (this.moveToToggle) { this.bounds = [this.boundsHash.zip[d.zip[0].MapID]]; } this.zipSelection = [d.zip[0]]; this.selected = 1; } }; get = url => { return new Promise((resolve, reject) => { const request = new XMLHttpRequest(); request.open('GET', url); request.onload = () => { if (request.status === 200) { resolve(request.response); } else { reject(Error(request.statusText)); } }; request.onerror = () => { reject(Error('Request Failed')); }; request.send(); }); }; onMoveEndFunction = _ => { // log('we are in on move end function', d); }; setToken = e => { const inputDOMObject = document.querySelector('#' + e.target.name); if (inputDOMObject && inputDOMObject['value']) { this.mapboxToken = inputDOMObject['value']; } }; onSelectionFunction = e => { const d = e.detail; this.currentCounts[d.layer] = d.data.length; this.currentLassos = { ...d.lassoFilter }; console.log('checking what is in selection', d); }; changePins = _e => { const tempState = [...this.pinnedIDs]; tempState.push(this.randomPin); this.randomPin = this.msaMapData[Math.floor(Math.random() * this.msaMapData.length)].MapID; this.pinnedIDs = tempState; }; changeLayer = () => { this.stateTrigger = !this.stateTrigger; this.zoomThreshold = this.zoomThreshold ? 0 : 10; }; loadLasso = () => { this.lassos = { ...this.savedLassos }; }; emptyLasso = () => { this.lassos = {}; }; saveLasso = () => { if (Object.keys(this.currentLassos).length) { this.savedLassos = { ...this.currentLassos }; } else { alert('There must be a lasso visible in order to save one!'); } }; prepareTitle = cell => { const layer = this.zoomThreshold ? 'msa' : 'zip'; let title = 'Count of ' + layer + 's: '; title += cell.count; title += '\n' + cell.metric1 + (cell['Metric 1'].min !== cell['Metric 1'].max ? ' (' + Math.round(1000 * cell['Metric 1'].min) / 10 + '% - ' + Math.round(1000 * cell['Metric 1'].max) / 10 + '%)' : ''); title += '\n' + cell.metric2 + (cell['Metric 2'].min !== cell['Metric 2'].max ? ' (' + Math.round(1000 * cell['Metric 2'].min) / 10 + '% - ' + Math.round(1000 * cell['Metric 2'].max) / 10 + '%)' : ''); return title; }; resolveSearch = (bounds, apiData) => { this.zoomThreshold = 0; this.moveToToggle = true; this.bounds = [bounds]; this.zipSelection = apiData; this.selected = this.zipSelection.length; }; search = clickedResult => { if (clickedResult.layer === 'msa') { // we must do an api request for the zips this.get(this.msaToZipBaseHref + 'searchZips.json').then( (response: string) => { const zipResponse = JSON.parse(response || '[]'); const zipsArray = []; zipResponse[0].results.forEach(zip => { zipsArray.push({ MapID: zip }); }); this.resolveSearch(this.boundsHash[clickedResult.layer][clickedResult.MapID], zipsArray); // return response; }, error => { console.log('MSA Zips Array Request Error', error); } ); } else { this.resolveSearch(this.boundsHash[clickedResult.layer][clickedResult.MapID], [clickedResult]); } }; clearSelections = () => { this.selected = 0; this.zipSelection = []; this.selection = []; }; generateCanvas = () => { (async () => { await customElements.whenDefined('bivariate-mapbox-map'); const mapElement = document.querySelector('bivariate-mapbox-map'); mapElement.generateCanvas().then(this.drawCanvas); })(); // .then(object => { // }); }; generatePNG = () => { (async () => { await customElements.whenDefined('bivariate-mapbox-map'); const mapElement = document.querySelector('bivariate-mapbox-map'); mapElement.generateCanvas().then(this.drawPNG); })(); }; drawCanvas = canvas => { console.log('canvas data is ', canvas); document.body.appendChild(canvas); console.log('your application may safely print now'); }; drawPNG = canvas => { console.log('canvas data is ', canvas); const png = new Image(); png.src = canvas.toDataURL(); png.width = this.width; png.height = this.height; png.onload = () => { console.log('your application may safely print now'); }; document.body.appendChild(png); }; render() { const layer = this.zoomThreshold ? 'msa' : 'zip'; return ( <div class="app-bivariate-mapbox-map"> <div class="button-group"> <br /> <div class="row"> <div class="col col-1"> <span class="button-summary">Enter Mapbox Token:&nbsp;</span> <input id="mtoken" type="text" name="mtoken" /> <button onClick={this.setToken} name="mtoken" style={{ cursor: 'pointer', backgroundColor: '#ECF6F7', color: 'steelBlue' }} > Submit </button> </div> </div> <br /> <div class="col col-1"> <div> <span class="button-summary">Currently Viewing:&nbsp;</span> <button onClick={this.changeLayer} style={{ cursor: 'pointer', backgroundColor: '#ECF6F7', color: 'steelBlue' }} > {this.zoomThreshold ? 'MSAs' : 'Zips'} </button> </div> <div> <span class="button-summary">Click-to-Move Feature is: </span> <button onClick={() => { this.moveToToggle = !this.moveToToggle; }} style={{ cursor: 'pointer', backgroundColor: `${this.moveToToggle ? 'steelBlue' : '#ECF6F7'}`, color: `${this.moveToToggle ? 'white' : 'black'}` }} > {this.moveToToggle ? 'Enabled' : 'Disabled'} </button> </div> <div> <span class="button-summary">Show Missing Data?: </span> <button onClick={() => { this.showMissingData = !this.showMissingData; }} style={{ cursor: 'pointer', backgroundColor: `${this.showMissingData ? 'steelBlue' : '#ECF6F7'}`, color: `${this.showMissingData ? 'white' : 'black'}` }} > {this.showMissingData ? 'Yes' : 'No'} </button> </div> <div> <span class="button-summary">Show Empty Polygons?: </span> <button onClick={() => { this.showEmptyData = !this.showEmptyData; }} style={{ cursor: 'pointer', backgroundColor: `${this.showEmptyData ? 'steelBlue' : '#ECF6F7'}`, color: `${this.showEmptyData ? 'white' : 'black'}` }} > {this.showEmptyData ? 'Yes' : 'No'} </button> </div> <div> <span class="button-summary"> {Object.keys(this.currentLassos).length + ' Lassos Shown on the Map.'}&nbsp; </span> <button onClick={this.saveLasso} disabled={!Object.keys(this.currentLassos).length} style={{ backgroundColor: Object.keys(this.currentLassos).length ? '#ECF6F7' : '#757575', color: Object.keys(this.currentLassos).length ? 'steelBlue' : 'black' }} > {!Object.keys(this.currentLassos).length ? '(Create lassos to save them)' : Object.keys(this.currentLassos).length === 1 ? 'Save shown lasso' : 'Save all ' + Object.keys(this.currentLassos).length + ' lassos'} </button> </div> <div style={{ display: Object.keys(this.savedLassos).length ? 'block' : 'none' }}> <span class="button-summary"> {Object.keys(this.savedLassos).length + ' Lasso' + (Object.keys(this.savedLassos).length === 1 ? '' : 's') + ' Saved.'} &nbsp; </span> <button onClick={this.loadLasso} style={{ cursor: 'pointer', backgroundColor: '#ECF6F7', color: Object.keys(this.savedLassos).length ? 'steelBlue' : 'black' }} > {!Object.keys(this.savedLassos).length ? 'Load nothing (delete unsaved lassos)' : Object.keys(this.savedLassos).length === 1 ? 'Load saved lasso' : 'Load ' + Object.keys(this.savedLassos).length + ' saved lassos'} </button> </div> <div style={{ display: Object.keys(this.currentLassos).length ? 'block' : 'none' }}> <span class="button-summary">&nbsp;</span> <button onClick={this.emptyLasso} style={{ cursor: 'pointer', backgroundColor: '#ECF6F7', color: 'steelBlue' }} > Delete lassos on map </button> </div> <div style={{ display: this.zoomThreshold ? 'block' : 'none' }}> <span class="button-summary">Pin this random MSA:</span> <button onClick={this.changePins} style={{ cursor: 'pointer', backgroundColor: '#ECF6F7', color: 'steelBlue' }} > {this.randomPin} </button> </div> </div> <div class="col col-2"> <div> <button onClick={() => { this.showMe = !this.showMe; }} style={{ width: '160px', cursor: 'pointer', backgroundColor: '#ECF6F7', color: 'steelBlue' }} > {this.showMe ? 'Hide the Data' : 'Show me the Data'} </button> </div> <div class="bivariate-key"> {this.bivariateTitles[layer].map(cell => { return ( <button onClick={this.changeBivariate} data-colorKey={cell.colorKey} title={this.prepareTitle(cell)} style={{ margin: '0px', cursor: 'pointer', backgroundColor: `${this.clickElements.includes(cell.colorKey) ? cell.color : '#757575'}`, color: `${this.clickElements.includes(cell.colorKey) ? autoTextColor(cell.color) : 'black'}` }} > {' '} {''}{' '} </button> ); })} </div> {this.showMe ? ( <scatter-plot data={this.zoomThreshold ? this.msaMapData : this.zipMapData} mainTitle={''} subTitle={''} height={105} width={105} xMinValueOverride={this.extents[layer]['Metric 2'].min} xMaxValueOverride={this.extents[layer]['Metric 2'].max} yMinValueOverride={this.extents[layer]['Metric 1'].min} yMaxValueOverride={this.extents[layer]['Metric 1'].max} xAxis={{ visible: false, gridVisible: false, label: '', format: '0' }} yAxis={{ visible: false, gridVisible: false, label: '', format: '$0[a]' }} showTooltip={false} dotRadius={0.5} dotOpacity={0.7} colors={['black']} padding={{ top: 0, left: 0, right: 0, bottom: 0 }} margin={{ top: 0, left: 0, right: 0, bottom: 0 }} hoverOpacity={0.2} xAccessor={'Metric 2'} yAccessor={'Metric 1'} groupAccessor={'group'} legend={{ visible: false }} dataLabel={{ visible: false, placement: 'top', labelAccessor: 'value', format: '0.0[a]' }} accessibility={{ disableValidation: true, hideDataTableButton: true }} /> ) : null} </div> <div class="col col-3"> <button onClick={this.generateCanvas} style={{ cursor: 'pointer', backgroundColor: '#ECF6F7', color: 'steelBlue' }} > Generate Canvas </button> <button onClick={this.generatePNG} style={{ cursor: 'pointer', backgroundColor: '#ECF6F7', color: 'steelBlue' }} > Generate PNG </button> <div style={{ fontSize: '14px', padding: '10px', paddingBottom: '0px' }}> <u>San Franci|_____________________</u> </div> <div style={{ boxShadow: '0 4px 6px 0 rgba(32,33,36,0.28)', borderRadius: '0 0 12px 12px', padding: '10px', paddingTop: '0px' }} > <i>Results:</i> <div class="search-results"> MSA: <b>San Franci</b>sco-Oakland-Hayward <span> <button onClick={() => { this.search({ layer: 'msa', Name: 'San Francisco-Oakland-Hayward', MapID: '41860' }); }} style={{ marginLeft: '15px', cursor: 'pointer', backgroundColor: '#ECF6F7', color: 'steelBlue', padding: '5px' }} > Go Here </button> </span> </div> <div class="search-results"> Zip: 94114 (in <b>San Franci</b>sco-Oaklan...) <span> <button onClick={() => { this.search({ layer: 'zip', Name: '94114', MapID: '94114' }); }} style={{ marginLeft: '16px', cursor: 'pointer', backgroundColor: '#ECF6F7', color: 'steelBlue', padding: '5px' }} > Go Here </button> </span> </div> </div> <div style={{ display: this.selected ? 'block' : 'none', paddingTop: '10px' }}> <span class="button-summary"> {this.selected + (this.zoomThreshold ? ' Msa' : ' Zip') + (this.selected === 1 ? '' : 's') + ' Selected'} </span> <button onClick={this.clearSelections} style={{ cursor: 'pointer', backgroundColor: '#ECF6F7', color: 'steelBlue' }} > Clear </button> </div> </div> </div> {this.mapboxToken && this.mapboxToken.length > 10 && this.mapboxToken.substr(0, 3) === 'pk.' ? ( <bivariate-mapbox-map mainTitle={this.title} subTitle={ 'Currently showing ' + this.currentCounts[layer] + ' out of ' + (this.zoomThreshold ? this.msaMapData.length : this.zipMapData.length) + (' ' + layer + ' (') + Math.round( 1000 * (this.currentCounts[layer] / (this.zoomThreshold ? this.msaMapData.length : this.zipMapData.length)) ) / 10 + '%)' } selectMSAs={this.selection} selectZips={this.zipSelection} token={this.mapboxToken} width={this.width} height={this.height} colorPalette={this.palette} onHoverFunc={this.onHoverFunction} onClickFunc={this.onClickFunction} onMoveEndFunc={this.onMoveEndFunction} onSelectionFunc={this.onSelectionFunction} onBinUpdateFunc={this.onBivariateChangeFunction} ordinalAccessor={'MapID'} ordinalNameAccessor={'Name'} valueAccessors={this.valueAccessors} bivariateFilter={this.clickElements} pinIDs={this.pinnedIDs} msaData={this.msaMapData} pinStyle={this.pinStyle} zipData={this.zipMapData} zoomThreshold={this.zoomThreshold} fitBounds={this.bounds} lassoData={this.lassos} preserveDrawingBuffer={true} noDataAccessor={'cannotShow'} noDataMessage={ 'Your filter combination is too restrictive. Please make some adjustments to selected filters.' } hideNoData={!this.showMissingData} showEmpty={this.showEmptyData} // showTooltip={false} defaultColor={this.defaultColor} tooltipLabel={{ format: ['', '', '0.0', '0.0'], labelTitle: ['', 'Code', 'Metric 1', 'Metric 2'], labelAccessor: ['Name', 'MapID', 'Metric 1', 'Metric 2'] }} /> ) : null} <div>{this.hoveringElement ? 'Currently hovering on ' + this.hoveringElement : ''}</div> </div> ); } }
the_stack
export type Maybe<T> = T | null; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; /** A date, expressed as an ISO8601 string */ Date: any; /** An ISO 8601-encoded date */ ISO8601Date: any; /** An ISO 8601-encoded datetime */ ISO8601DateTime: any; /** A loose key-value map in GraphQL */ Map: any; Upload: any; }; /** A user account on Kitsu */ export type Account = WithTimestamps & { readonly __typename?: 'Account'; /** The country this user resides in */ readonly country?: Maybe<Scalars['String']>; readonly createdAt: Scalars['ISO8601DateTime']; /** The email addresses associated with this account */ readonly email: ReadonlyArray<Scalars['String']>; /** Facebook account linked to the account */ readonly facebookId?: Maybe<Scalars['String']>; readonly id: Scalars['ID']; /** Primary language for the account */ readonly language?: Maybe<Scalars['String']>; /** Longest period an account has had a PRO subscription for in seconds */ readonly maxProStreak?: Maybe<Scalars['Int']>; /** The PRO subscription for this account */ readonly proSubscription?: Maybe<ProSubscription>; /** The profile for this account */ readonly profile: Profile; /** Media rating system used for the account */ readonly ratingSystem: RatingSystemEnum; /** Whether Not Safe For Work content is accessible */ readonly sfwFilter?: Maybe<Scalars['Boolean']>; /** The site-wide permissions this user has access to */ readonly sitePermissions: ReadonlyArray<SitePermissionEnum>; /** Time zone of the account */ readonly timeZone?: Maybe<Scalars['String']>; /** Preferred language for media titles */ readonly titleLanguagePreference?: Maybe<TitleLanguagePreferenceEnum>; /** Twitter account linked to the account */ readonly twitterId?: Maybe<Scalars['String']>; readonly updatedAt: Scalars['ISO8601DateTime']; }; export enum AgeRatingEnum { /** Acceptable for all ages */ G = 'G', /** Parental guidance suggested; should be safe for preteens and older */ Pg = 'PG', /** Possible lewd or intense themes; should be safe for teens and older */ R = 'R', /** Contains adult content or themes; should only be viewed by adults */ R18 = 'R18' } /** Generic Amount Consumed based on Media */ export type AmountConsumed = { /** Total media completed atleast once. */ readonly completed: Scalars['Int']; readonly id: Scalars['ID']; /** Total amount of media. */ readonly media: Scalars['Int']; /** The profile related to the user for this stat. */ readonly profile: Profile; /** Last time we fully recalculated this stat. */ readonly recalculatedAt: Scalars['ISO8601Date']; /** Total progress of library including reconsuming. */ readonly units: Scalars['Int']; }; export type Anime = Media & Episodic & WithTimestamps & { readonly __typename?: 'Anime'; /** The recommended minimum age group for this media */ readonly ageRating?: Maybe<AgeRatingEnum>; /** An explanation of why this received the age rating it did */ readonly ageRatingGuide?: Maybe<Scalars['String']>; /** The average rating of this media amongst all Kitsu users */ readonly averageRating?: Maybe<Scalars['Float']>; /** A large banner image for this media */ readonly bannerImage: Image; /** A list of categories for this media */ readonly categories: CategoryConnection; /** The characters who starred in this media */ readonly characters: MediaCharacterConnection; readonly createdAt: Scalars['ISO8601DateTime']; /** A brief (mostly spoiler free) summary or description of the media. */ readonly description: Scalars['Map']; /** the day that this media made its final release */ readonly endDate?: Maybe<Scalars['Date']>; /** The number of episodes in this series */ readonly episodeCount?: Maybe<Scalars['Int']>; /** The general length (in seconds) of each episode */ readonly episodeLength?: Maybe<Scalars['Int']>; /** Episodes for this media */ readonly episodes: EpisodeConnection; /** The number of users with this in their favorites */ readonly favoritesCount?: Maybe<Scalars['Int']>; readonly id: Scalars['ID']; /** A list of mappings for this media */ readonly mappings: MappingConnection; /** The time of the next release of this media */ readonly nextRelease?: Maybe<Scalars['ISO8601DateTime']>; /** The country in which the media was primarily produced */ readonly originalLocale?: Maybe<Scalars['String']>; /** The poster image of this media */ readonly posterImage: Image; /** The companies which helped to produce this media */ readonly productions: MediaProductionConnection; /** A list of quotes from this media */ readonly quotes: QuoteConnection; /** A list of reactions for this media */ readonly reactions: MediaReactionConnection; /** The season this was released in */ readonly season?: Maybe<ReleaseSeasonEnum>; /** Whether the media is Safe-for-Work */ readonly sfw: Scalars['Boolean']; /** The URL-friendly identifier of this media */ readonly slug: Scalars['String']; /** The staff members who worked on this media */ readonly staff: MediaStaffConnection; /** The day that this media first released */ readonly startDate?: Maybe<Scalars['Date']>; /** The current releasing status of this media */ readonly status: ReleaseStatusEnum; /** The stream links. */ readonly streamingLinks: StreamingLinkConnection; /** A secondary type for categorizing Anime. */ readonly subtype: AnimeSubtypeEnum; /** Description of when this media is expected to release */ readonly tba?: Maybe<Scalars['String']>; /** The titles for this media in various locales */ readonly titles: TitlesList; /** The total length (in seconds) of the entire series */ readonly totalLength?: Maybe<Scalars['Int']>; /** Anime or Manga. */ readonly type: Scalars['String']; readonly updatedAt: Scalars['ISO8601DateTime']; /** The number of users with this in their library */ readonly userCount?: Maybe<Scalars['Int']>; /** Video id for a trailer on YouTube */ readonly youtubeTrailerVideoId?: Maybe<Scalars['String']>; }; export type AnimeCategoriesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type AnimeCharactersArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type AnimeDescriptionArgs = { locales?: Maybe<ReadonlyArray<Scalars['String']>>; }; export type AnimeEpisodesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; number?: Maybe<ReadonlyArray<Scalars['Int']>>; }; export type AnimeMappingsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type AnimeProductionsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type AnimeQuotesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type AnimeReactionsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type AnimeStaffArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type AnimeStreamingLinksArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type AnimeAmountConsumed = AmountConsumed & { readonly __typename?: 'AnimeAmountConsumed'; /** Total media completed atleast once. */ readonly completed: Scalars['Int']; readonly id: Scalars['ID']; /** Total amount of media. */ readonly media: Scalars['Int']; /** The profile related to the user for this stat. */ readonly profile: Profile; /** Last time we fully recalculated this stat. */ readonly recalculatedAt: Scalars['ISO8601Date']; /** Total time spent in minutes. */ readonly time: Scalars['Int']; /** Total progress of library including reconsuming. */ readonly units: Scalars['Int']; }; export type AnimeCategoryBreakdown = CategoryBreakdown & { readonly __typename?: 'AnimeCategoryBreakdown'; /** A Map of category_id -> count for all categories present on the library entries */ readonly categories: Scalars['Map']; readonly id: Scalars['ID']; /** The profile related to the user for this stat. */ readonly profile: Profile; /** Last time we fully recalculated this stat. */ readonly recalculatedAt: Scalars['ISO8601Date']; /** The total amount of library entries. */ readonly total: Scalars['Int']; }; /** The connection type for Anime. */ export type AnimeConnection = { readonly __typename?: 'AnimeConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<AnimeEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<Anime>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; export type AnimeCreateInput = { readonly titles: TitlesListInput; readonly description: Scalars['Map']; readonly ageRating?: Maybe<AgeRatingEnum>; readonly ageRatingGuide?: Maybe<Scalars['String']>; readonly tba?: Maybe<Scalars['String']>; readonly startDate?: Maybe<Scalars['Date']>; readonly endDate?: Maybe<Scalars['Date']>; readonly posterImage?: Maybe<Scalars['Upload']>; readonly bannerImage?: Maybe<Scalars['Upload']>; readonly youtubeTrailerVideoId?: Maybe<Scalars['String']>; readonly episodeCount?: Maybe<Scalars['Int']>; readonly episodeLength?: Maybe<Scalars['Int']>; }; /** Autogenerated return type of AnimeCreate */ export type AnimeCreatePayload = { readonly __typename?: 'AnimeCreatePayload'; readonly anime?: Maybe<Anime>; readonly errors?: Maybe<ReadonlyArray<Error>>; }; /** Autogenerated return type of AnimeDelete */ export type AnimeDeletePayload = { readonly __typename?: 'AnimeDeletePayload'; readonly anime?: Maybe<GenericDelete>; readonly errors?: Maybe<ReadonlyArray<Error>>; }; /** An edge in a connection. */ export type AnimeEdge = { readonly __typename?: 'AnimeEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<Anime>; }; export type AnimeMutations = { readonly __typename?: 'AnimeMutations'; /** Create an Anime. */ readonly create?: Maybe<AnimeCreatePayload>; /** Delete an Anime. */ readonly delete?: Maybe<AnimeDeletePayload>; /** Update an Anime. */ readonly update?: Maybe<AnimeUpdatePayload>; }; export type AnimeMutationsCreateArgs = { input: AnimeCreateInput; }; export type AnimeMutationsDeleteArgs = { input: GenericDeleteInput; }; export type AnimeMutationsUpdateArgs = { input: AnimeUpdateInput; }; export enum AnimeSubtypeEnum { Tv = 'TV', /** Spinoffs or Extras of the original. */ Special = 'SPECIAL', /** Original Video Animation. Anime directly released to video market. */ Ova = 'OVA', /** Original Net Animation (Web Anime). */ Ona = 'ONA', Movie = 'MOVIE', Music = 'MUSIC' } export type AnimeUpdateInput = { readonly id: Scalars['ID']; readonly titles?: Maybe<TitlesListInput>; readonly description?: Maybe<Scalars['Map']>; readonly ageRating?: Maybe<AgeRatingEnum>; readonly ageRatingGuide?: Maybe<Scalars['String']>; readonly tba?: Maybe<Scalars['String']>; readonly startDate?: Maybe<Scalars['Date']>; readonly endDate?: Maybe<Scalars['Date']>; readonly posterImage?: Maybe<Scalars['Upload']>; readonly bannerImage?: Maybe<Scalars['Upload']>; readonly youtubeTrailerVideoId?: Maybe<Scalars['String']>; readonly episodeCount?: Maybe<Scalars['Int']>; readonly episodeLength?: Maybe<Scalars['Int']>; }; /** Autogenerated return type of AnimeUpdate */ export type AnimeUpdatePayload = { readonly __typename?: 'AnimeUpdatePayload'; readonly anime?: Maybe<Anime>; readonly errors?: Maybe<ReadonlyArray<Error>>; }; /** Information about a specific Category */ export type Category = WithTimestamps & { readonly __typename?: 'Category'; /** The child categories. */ readonly children?: Maybe<CategoryConnection>; readonly createdAt: Scalars['ISO8601DateTime']; /** A brief summary or description of the catgory. */ readonly description: Scalars['Map']; readonly id: Scalars['ID']; /** Whether the category is Not-Safe-for-Work. */ readonly isNsfw: Scalars['Boolean']; /** The parent category. Each category can have one parent. */ readonly parent?: Maybe<Category>; /** The URL-friendly identifier of this Category. */ readonly slug: Scalars['String']; /** The name of the category. */ readonly title: Scalars['Map']; readonly updatedAt: Scalars['ISO8601DateTime']; }; /** Information about a specific Category */ export type CategoryChildrenArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** Information about a specific Category */ export type CategoryDescriptionArgs = { locales?: Maybe<ReadonlyArray<Scalars['String']>>; }; /** Information about a specific Category */ export type CategoryTitleArgs = { locales?: Maybe<ReadonlyArray<Scalars['String']>>; }; /** Generic Category Breakdown based on Media */ export type CategoryBreakdown = { /** A Map of category_id -> count for all categories present on the library entries */ readonly categories: Scalars['Map']; readonly id: Scalars['ID']; /** The profile related to the user for this stat. */ readonly profile: Profile; /** Last time we fully recalculated this stat. */ readonly recalculatedAt: Scalars['ISO8601Date']; /** The total amount of library entries. */ readonly total: Scalars['Int']; }; /** The connection type for Category. */ export type CategoryConnection = { readonly __typename?: 'CategoryConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<CategoryEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<Category>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type CategoryEdge = { readonly __typename?: 'CategoryEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<Category>; }; /** A single chapter of a manga */ export type Chapter = Unit & WithTimestamps & { readonly __typename?: 'Chapter'; readonly createdAt: Scalars['ISO8601DateTime']; /** A brief summary or description of the unit */ readonly description: Scalars['Map']; readonly id: Scalars['ID']; /** The manga this chapter is in. */ readonly manga: Manga; /** The sequence number of this unit */ readonly number: Scalars['Int']; /** When this chapter was released */ readonly releasedAt?: Maybe<Scalars['ISO8601Date']>; /** A thumbnail image for the unit */ readonly thumbnail?: Maybe<Image>; /** The titles for this unit in various locales */ readonly titles: TitlesList; readonly updatedAt: Scalars['ISO8601DateTime']; /** The volume this chapter is in. */ readonly volume?: Maybe<Volume>; }; /** A single chapter of a manga */ export type ChapterDescriptionArgs = { locales?: Maybe<ReadonlyArray<Scalars['String']>>; }; /** The connection type for Chapter. */ export type ChapterConnection = { readonly __typename?: 'ChapterConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<ChapterEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<Chapter>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type ChapterEdge = { readonly __typename?: 'ChapterEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<Chapter>; }; /** Information about a Character in the Kitsu database */ export type Character = WithTimestamps & { readonly __typename?: 'Character'; readonly createdAt: Scalars['ISO8601DateTime']; /** A brief summary or description of the character. */ readonly description: Scalars['Map']; readonly id: Scalars['ID']; /** An image of the character */ readonly image?: Maybe<Image>; /** Media this character appears in. */ readonly media?: Maybe<MediaCharacterConnection>; /** The name for this character in various locales */ readonly names?: Maybe<TitlesList>; /** The original media this character showed up in */ readonly primaryMedia?: Maybe<Media>; /** The URL-friendly identifier of this character */ readonly slug: Scalars['String']; readonly updatedAt: Scalars['ISO8601DateTime']; }; /** Information about a Character in the Kitsu database */ export type CharacterDescriptionArgs = { locales?: Maybe<ReadonlyArray<Scalars['String']>>; }; /** Information about a Character in the Kitsu database */ export type CharacterMediaArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export enum CharacterRoleEnum { /** A character who appears throughout a series and is a focal point of the media */ Main = 'MAIN', /** A character who appears in multiple episodes but is not a main character */ Recurring = 'RECURRING', /** A background character who generally only appears in a few episodes */ Background = 'BACKGROUND', /** A character from a different franchise making a (usually brief) appearance */ Cameo = 'CAMEO' } /** Information about a VA (Person) voicing a Character in a Media */ export type CharacterVoice = WithTimestamps & { readonly __typename?: 'CharacterVoice'; readonly createdAt: Scalars['ISO8601DateTime']; readonly id: Scalars['ID']; /** The company who hired this voice actor to play this role */ readonly licensor?: Maybe<Producer>; /** The BCP47 locale tag for the voice acting role */ readonly locale: Scalars['String']; /** The MediaCharacter node */ readonly mediaCharacter: MediaCharacter; /** The person who voice acted this role */ readonly person: Person; readonly updatedAt: Scalars['ISO8601DateTime']; }; /** The connection type for CharacterVoice. */ export type CharacterVoiceConnection = { readonly __typename?: 'CharacterVoiceConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<CharacterVoiceEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<CharacterVoice>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type CharacterVoiceEdge = { readonly __typename?: 'CharacterVoiceEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<CharacterVoice>; }; /** A comment on a post */ export type Comment = WithTimestamps & { readonly __typename?: 'Comment'; /** The user who created this comment for the parent post. */ readonly author: Profile; /** Unmodified content. */ readonly content: Scalars['String']; /** Html formatted content. */ readonly contentFormatted: Scalars['String']; readonly createdAt: Scalars['ISO8601DateTime']; readonly id: Scalars['ID']; /** Users who liked this comment */ readonly likes: ProfileConnection; /** The parent comment if this comment was a reply to another. */ readonly parent?: Maybe<Comment>; /** The post that this comment is attached to. */ readonly post: Post; /** Replies to this comment */ readonly replies: CommentConnection; readonly updatedAt: Scalars['ISO8601DateTime']; }; /** A comment on a post */ export type CommentLikesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; sort?: Maybe<ReadonlyArray<Maybe<CommentLikeSortOption>>>; }; /** A comment on a post */ export type CommentRepliesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; sort?: Maybe<ReadonlyArray<Maybe<CommentSortOption>>>; }; /** The connection type for Comment. */ export type CommentConnection = { readonly __typename?: 'CommentConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<CommentEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<Comment>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type CommentEdge = { readonly __typename?: 'CommentEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<Comment>; }; export enum CommentLikeSortEnum { Following = 'FOLLOWING', CreatedAt = 'CREATED_AT' } export type CommentLikeSortOption = { readonly on: CommentLikeSortEnum; readonly direction: SortDirection; }; export enum CommentSortEnum { Following = 'FOLLOWING', CreatedAt = 'CREATED_AT', LikesCount = 'LIKES_COUNT' } export type CommentSortOption = { readonly on: CommentSortEnum; readonly direction: SortDirection; }; /** An Episode of a Media */ export type Episode = Unit & WithTimestamps & { readonly __typename?: 'Episode'; /** The anime this episode is in */ readonly anime: Anime; readonly createdAt: Scalars['ISO8601DateTime']; /** A brief summary or description of the unit */ readonly description: Scalars['Map']; readonly id: Scalars['ID']; /** The length of the episode in seconds */ readonly length?: Maybe<Scalars['Int']>; /** The sequence number of this unit */ readonly number: Scalars['Int']; /** When this episode aired */ readonly releasedAt?: Maybe<Scalars['ISO8601DateTime']>; /** A thumbnail image for the unit */ readonly thumbnail?: Maybe<Image>; /** The titles for this unit in various locales */ readonly titles: TitlesList; readonly updatedAt: Scalars['ISO8601DateTime']; }; /** An Episode of a Media */ export type EpisodeDescriptionArgs = { locales?: Maybe<ReadonlyArray<Scalars['String']>>; }; /** The connection type for Episode. */ export type EpisodeConnection = { readonly __typename?: 'EpisodeConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<EpisodeEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<Episode>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; export type EpisodeCreateInput = { readonly mediaId: Scalars['ID']; readonly mediaType: MediaTypeEnum; readonly titles: TitlesListInput; readonly number: Scalars['Int']; readonly description?: Maybe<Scalars['Map']>; readonly length?: Maybe<Scalars['Int']>; readonly releasedAt?: Maybe<Scalars['Date']>; readonly thumbnailImage?: Maybe<Scalars['Upload']>; }; /** Autogenerated return type of EpisodeCreate */ export type EpisodeCreatePayload = { readonly __typename?: 'EpisodeCreatePayload'; readonly episode?: Maybe<Episode>; readonly errors?: Maybe<ReadonlyArray<Error>>; }; /** Autogenerated return type of EpisodeDelete */ export type EpisodeDeletePayload = { readonly __typename?: 'EpisodeDeletePayload'; readonly episode?: Maybe<GenericDelete>; readonly errors?: Maybe<ReadonlyArray<Error>>; }; /** An edge in a connection. */ export type EpisodeEdge = { readonly __typename?: 'EpisodeEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<Episode>; }; export type EpisodeMutations = { readonly __typename?: 'EpisodeMutations'; /** Create an Episode. */ readonly create?: Maybe<EpisodeCreatePayload>; /** Delete an Episode. */ readonly delete?: Maybe<EpisodeDeletePayload>; /** Update an Episode. */ readonly update?: Maybe<EpisodeUpdatePayload>; }; export type EpisodeMutationsCreateArgs = { input: EpisodeCreateInput; }; export type EpisodeMutationsDeleteArgs = { input: GenericDeleteInput; }; export type EpisodeMutationsUpdateArgs = { input: EpisodeUpdateInput; }; export type EpisodeUpdateInput = { readonly id: Scalars['ID']; readonly titles?: Maybe<TitlesListInput>; readonly number?: Maybe<Scalars['Int']>; readonly description?: Maybe<Scalars['Map']>; readonly length?: Maybe<Scalars['Int']>; readonly releasedAt?: Maybe<Scalars['Date']>; readonly thumbnailImage?: Maybe<Scalars['Upload']>; }; /** Autogenerated return type of EpisodeUpdate */ export type EpisodeUpdatePayload = { readonly __typename?: 'EpisodeUpdatePayload'; readonly episode?: Maybe<Episode>; readonly errors?: Maybe<ReadonlyArray<Error>>; }; /** An episodic media in the Kitsu database */ export type Episodic = { /** The number of episodes in this series */ readonly episodeCount?: Maybe<Scalars['Int']>; /** The general length (in seconds) of each episode */ readonly episodeLength?: Maybe<Scalars['Int']>; /** Episodes for this media */ readonly episodes: EpisodeConnection; /** The total length (in seconds) of the entire series */ readonly totalLength?: Maybe<Scalars['Int']>; }; /** An episodic media in the Kitsu database */ export type EpisodicEpisodesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; number?: Maybe<ReadonlyArray<Scalars['Int']>>; }; /** Generic error fields used by all errors. */ export type Error = { /** The error code. */ readonly code?: Maybe<Scalars['String']>; /** A description of the error */ readonly message: Scalars['String']; /** Which input value this error came from */ readonly path?: Maybe<ReadonlyArray<Scalars['String']>>; }; /** Favorite media, characters, and people for a user */ export type Favorite = WithTimestamps & { readonly __typename?: 'Favorite'; readonly createdAt: Scalars['ISO8601DateTime']; readonly id: Scalars['ID']; /** The kitsu object that is mapped */ readonly item: FavoriteItemUnion; readonly updatedAt: Scalars['ISO8601DateTime']; /** The user who favorited this item */ readonly user: Profile; }; /** The connection type for Favorite. */ export type FavoriteConnection = { readonly __typename?: 'FavoriteConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<FavoriteEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<Favorite>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type FavoriteEdge = { readonly __typename?: 'FavoriteEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<Favorite>; }; /** Objects which are Favoritable */ export type FavoriteItemUnion = Anime | Character | Manga | Person; export type Generic = Error & { readonly __typename?: 'Generic'; /** The error code. */ readonly code?: Maybe<Scalars['String']>; /** A description of the error */ readonly message: Scalars['String']; /** Which input value this error came from */ readonly path?: Maybe<ReadonlyArray<Scalars['String']>>; }; export type GenericDelete = { readonly __typename?: 'GenericDelete'; readonly id: Scalars['ID']; }; export type GenericDeleteInput = { readonly id: Scalars['ID']; }; export type Image = { readonly __typename?: 'Image'; /** A blurhash-encoded version of this image */ readonly blurhash?: Maybe<Scalars['String']>; /** The original image */ readonly original: ImageView; /** The various generated views of this image */ readonly views: ReadonlyArray<ImageView>; }; export type ImageViewsArgs = { names?: Maybe<ReadonlyArray<Scalars['String']>>; }; export type ImageView = WithTimestamps & { readonly __typename?: 'ImageView'; readonly createdAt: Scalars['ISO8601DateTime']; /** The height of the image */ readonly height?: Maybe<Scalars['Int']>; /** The name of this view of the image */ readonly name: Scalars['String']; readonly updatedAt: Scalars['ISO8601DateTime']; /** The URL of this view of the image */ readonly url: Scalars['String']; /** The width of the image */ readonly width?: Maybe<Scalars['Int']>; }; /** The user library filterable by media_type and status */ export type Library = { readonly __typename?: 'Library'; /** All Library Entries for a specific Media */ readonly all: LibraryEntryConnection; /** Library Entries for a specific Media filtered by the completed status */ readonly completed: LibraryEntryConnection; /** Library Entries for a specific Media filtered by the current status */ readonly current: LibraryEntryConnection; /** Library Entries for a specific Media filtered by the dropped status */ readonly dropped: LibraryEntryConnection; /** Library Entries for a specific Media filtered by the on_hold status */ readonly onHold: LibraryEntryConnection; /** Library Entries for a specific Media filtered by the planned status */ readonly planned: LibraryEntryConnection; /** Random anime or manga from this library */ readonly randomMedia?: Maybe<Media>; }; /** The user library filterable by media_type and status */ export type LibraryAllArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; mediaType: MediaTypeEnum; status?: Maybe<ReadonlyArray<LibraryEntryStatusEnum>>; }; /** The user library filterable by media_type and status */ export type LibraryCompletedArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; mediaType: MediaTypeEnum; }; /** The user library filterable by media_type and status */ export type LibraryCurrentArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; mediaType: MediaTypeEnum; }; /** The user library filterable by media_type and status */ export type LibraryDroppedArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; mediaType: MediaTypeEnum; }; /** The user library filterable by media_type and status */ export type LibraryOnHoldArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; mediaType: MediaTypeEnum; }; /** The user library filterable by media_type and status */ export type LibraryPlannedArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; mediaType: MediaTypeEnum; }; /** The user library filterable by media_type and status */ export type LibraryRandomMediaArgs = { mediaType: MediaTypeEnum; status: ReadonlyArray<LibraryEntryStatusEnum>; }; /** Information about a specific media entry for a user */ export type LibraryEntry = WithTimestamps & { readonly __typename?: 'LibraryEntry'; readonly createdAt: Scalars['ISO8601DateTime']; /** History of user actions for this library entry. */ readonly events?: Maybe<LibraryEventConnection>; /** When the user finished this media. */ readonly finishedAt?: Maybe<Scalars['ISO8601DateTime']>; readonly id: Scalars['ID']; /** The last unit consumed */ readonly lastUnit?: Maybe<Unit>; /** The media related to this library entry. */ readonly media: Media; /** The next unit to be consumed */ readonly nextUnit?: Maybe<Unit>; /** Notes left by the profile related to this library entry. */ readonly notes?: Maybe<Scalars['String']>; /** If the media related to the library entry is Not-Safe-for-Work. */ readonly nsfw: Scalars['Boolean']; /** If this library entry is publicly visibile from their profile, or hidden. */ readonly private: Scalars['Boolean']; /** The number of episodes/chapters this user has watched/read */ readonly progress: Scalars['Int']; /** When the user last watched an episode or read a chapter of this media. */ readonly progressedAt?: Maybe<Scalars['ISO8601DateTime']>; /** How much you enjoyed this media (lower meaning not liking). */ readonly rating?: Maybe<Scalars['Int']>; /** The reaction based on the media of this library entry. */ readonly reaction?: Maybe<MediaReaction>; /** Amount of times this media has been rewatched. */ readonly reconsumeCount: Scalars['Int']; /** If the profile is currently rewatching this media. */ readonly reconsuming: Scalars['Boolean']; /** When the user started this media. */ readonly startedAt?: Maybe<Scalars['ISO8601DateTime']>; readonly status: LibraryEntryStatusEnum; readonly updatedAt: Scalars['ISO8601DateTime']; /** The user who created this library entry. */ readonly user: Profile; /** Volumes that the profile owns (physically or digital). */ readonly volumesOwned: Scalars['Int']; }; /** Information about a specific media entry for a user */ export type LibraryEntryEventsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; mediaTypes?: Maybe<ReadonlyArray<MediaTypeEnum>>; }; /** The connection type for LibraryEntry. */ export type LibraryEntryConnection = { readonly __typename?: 'LibraryEntryConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<LibraryEntryEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<LibraryEntry>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; export type LibraryEntryCreateInput = { readonly userId: Scalars['ID']; readonly mediaId: Scalars['ID']; readonly mediaType: MediaTypeEnum; readonly status: LibraryEntryStatusEnum; readonly progress?: Maybe<Scalars['Int']>; readonly private?: Maybe<Scalars['Boolean']>; readonly notes?: Maybe<Scalars['String']>; readonly reconsumeCount?: Maybe<Scalars['Int']>; readonly reconsuming?: Maybe<Scalars['Boolean']>; readonly volumesOwned?: Maybe<Scalars['Int']>; readonly rating?: Maybe<Scalars['Int']>; readonly startedAt?: Maybe<Scalars['ISO8601DateTime']>; readonly finishedAt?: Maybe<Scalars['ISO8601DateTime']>; }; /** Autogenerated return type of LibraryEntryCreate */ export type LibraryEntryCreatePayload = { readonly __typename?: 'LibraryEntryCreatePayload'; readonly errors?: Maybe<ReadonlyArray<Error>>; readonly libraryEntry?: Maybe<LibraryEntry>; }; /** Autogenerated return type of LibraryEntryDelete */ export type LibraryEntryDeletePayload = { readonly __typename?: 'LibraryEntryDeletePayload'; readonly errors?: Maybe<ReadonlyArray<Error>>; readonly libraryEntry?: Maybe<GenericDelete>; }; /** An edge in a connection. */ export type LibraryEntryEdge = { readonly __typename?: 'LibraryEntryEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<LibraryEntry>; }; export type LibraryEntryMutations = { readonly __typename?: 'LibraryEntryMutations'; /** Create a library entry */ readonly create?: Maybe<LibraryEntryCreatePayload>; /** Delete a library entry */ readonly delete?: Maybe<LibraryEntryDeletePayload>; /** Update a library entry */ readonly update?: Maybe<LibraryEntryUpdatePayload>; /** Update library entry progress by id */ readonly updateProgressById?: Maybe<LibraryEntryUpdateProgressByIdPayload>; /** Update library entry progress by media */ readonly updateProgressByMedia?: Maybe<LibraryEntryUpdateProgressByMediaPayload>; /** Update library entry rating by id */ readonly updateRatingById?: Maybe<LibraryEntryUpdateRatingByIdPayload>; /** Update library entry rating by media */ readonly updateRatingByMedia?: Maybe<LibraryEntryUpdateRatingByMediaPayload>; /** Update library entry status by id */ readonly updateStatusById?: Maybe<LibraryEntryUpdateStatusByIdPayload>; /** Update library entry status by media */ readonly updateStatusByMedia?: Maybe<LibraryEntryUpdateStatusByMediaPayload>; }; export type LibraryEntryMutationsCreateArgs = { input: LibraryEntryCreateInput; }; export type LibraryEntryMutationsDeleteArgs = { input: GenericDeleteInput; }; export type LibraryEntryMutationsUpdateArgs = { input: LibraryEntryUpdateInput; }; export type LibraryEntryMutationsUpdateProgressByIdArgs = { input: LibraryEntryUpdateProgressByIdInput; }; export type LibraryEntryMutationsUpdateProgressByMediaArgs = { input: LibraryEntryUpdateProgressByMediaInput; }; export type LibraryEntryMutationsUpdateRatingByIdArgs = { input: LibraryEntryUpdateRatingByIdInput; }; export type LibraryEntryMutationsUpdateRatingByMediaArgs = { input: LibraryEntryUpdateRatingByMediaInput; }; export type LibraryEntryMutationsUpdateStatusByIdArgs = { input: LibraryEntryUpdateStatusByIdInput; }; export type LibraryEntryMutationsUpdateStatusByMediaArgs = { input: LibraryEntryUpdateStatusByMediaInput; }; export enum LibraryEntryStatusEnum { /** The user is currently reading or watching this media. */ Current = 'CURRENT', /** The user plans to read or watch this media in future. */ Planned = 'PLANNED', /** The user completed this media. */ Completed = 'COMPLETED', /** The user started but paused reading or watching this media. */ OnHold = 'ON_HOLD', /** The user started but chose not to finish this media. */ Dropped = 'DROPPED' } export type LibraryEntryUpdateInput = { readonly id: Scalars['ID']; readonly status?: Maybe<LibraryEntryStatusEnum>; readonly progress?: Maybe<Scalars['Int']>; readonly private?: Maybe<Scalars['Boolean']>; readonly notes?: Maybe<Scalars['String']>; readonly reconsumeCount?: Maybe<Scalars['Int']>; readonly reconsuming?: Maybe<Scalars['Boolean']>; readonly volumesOwned?: Maybe<Scalars['Int']>; readonly rating?: Maybe<Scalars['Int']>; readonly startedAt?: Maybe<Scalars['ISO8601DateTime']>; readonly finishedAt?: Maybe<Scalars['ISO8601DateTime']>; }; /** Autogenerated return type of LibraryEntryUpdate */ export type LibraryEntryUpdatePayload = { readonly __typename?: 'LibraryEntryUpdatePayload'; readonly errors?: Maybe<ReadonlyArray<Error>>; readonly libraryEntry?: Maybe<LibraryEntry>; }; export type LibraryEntryUpdateProgressByIdInput = { readonly id: Scalars['ID']; readonly progress: Scalars['Int']; }; /** Autogenerated return type of LibraryEntryUpdateProgressById */ export type LibraryEntryUpdateProgressByIdPayload = { readonly __typename?: 'LibraryEntryUpdateProgressByIdPayload'; readonly errors?: Maybe<ReadonlyArray<Error>>; readonly libraryEntry?: Maybe<LibraryEntry>; }; export type LibraryEntryUpdateProgressByMediaInput = { readonly mediaId: Scalars['ID']; readonly mediaType: MediaTypeEnum; readonly progress: Scalars['Int']; }; /** Autogenerated return type of LibraryEntryUpdateProgressByMedia */ export type LibraryEntryUpdateProgressByMediaPayload = { readonly __typename?: 'LibraryEntryUpdateProgressByMediaPayload'; readonly errors?: Maybe<ReadonlyArray<Error>>; readonly libraryEntry?: Maybe<LibraryEntry>; }; export type LibraryEntryUpdateRatingByIdInput = { readonly id: Scalars['ID']; /** A number between 2 - 20 */ readonly rating: Scalars['Int']; }; /** Autogenerated return type of LibraryEntryUpdateRatingById */ export type LibraryEntryUpdateRatingByIdPayload = { readonly __typename?: 'LibraryEntryUpdateRatingByIdPayload'; readonly errors?: Maybe<ReadonlyArray<Error>>; readonly libraryEntry?: Maybe<LibraryEntry>; }; export type LibraryEntryUpdateRatingByMediaInput = { readonly mediaId: Scalars['ID']; readonly mediaType: MediaTypeEnum; /** A number between 2 - 20 */ readonly rating: Scalars['Int']; }; /** Autogenerated return type of LibraryEntryUpdateRatingByMedia */ export type LibraryEntryUpdateRatingByMediaPayload = { readonly __typename?: 'LibraryEntryUpdateRatingByMediaPayload'; readonly errors?: Maybe<ReadonlyArray<Error>>; readonly libraryEntry?: Maybe<LibraryEntry>; }; export type LibraryEntryUpdateStatusByIdInput = { readonly id: Scalars['ID']; readonly status: LibraryEntryStatusEnum; }; /** Autogenerated return type of LibraryEntryUpdateStatusById */ export type LibraryEntryUpdateStatusByIdPayload = { readonly __typename?: 'LibraryEntryUpdateStatusByIdPayload'; readonly errors?: Maybe<ReadonlyArray<Error>>; readonly libraryEntry?: Maybe<LibraryEntry>; }; export type LibraryEntryUpdateStatusByMediaInput = { readonly mediaId: Scalars['ID']; readonly mediaType: MediaTypeEnum; readonly status: LibraryEntryStatusEnum; }; /** Autogenerated return type of LibraryEntryUpdateStatusByMedia */ export type LibraryEntryUpdateStatusByMediaPayload = { readonly __typename?: 'LibraryEntryUpdateStatusByMediaPayload'; readonly errors?: Maybe<ReadonlyArray<Error>>; readonly libraryEntry?: Maybe<LibraryEntry>; }; /** History of user actions for a library entry. */ export type LibraryEvent = WithTimestamps & { readonly __typename?: 'LibraryEvent'; /** The data that was changed for this library event. */ readonly changedData: Scalars['Map']; readonly createdAt: Scalars['ISO8601DateTime']; readonly id: Scalars['ID']; /** The type of library event. */ readonly kind: LibraryEventKindEnum; /** The library entry related to this library event. */ readonly libraryEntry: LibraryEntry; /** The media related to this library event. */ readonly media: Media; readonly updatedAt: Scalars['ISO8601DateTime']; /** The user who created this library event */ readonly user: Profile; }; /** The connection type for LibraryEvent. */ export type LibraryEventConnection = { readonly __typename?: 'LibraryEventConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<LibraryEventEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<LibraryEvent>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type LibraryEventEdge = { readonly __typename?: 'LibraryEventEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<LibraryEvent>; }; export enum LibraryEventKindEnum { /** Progress or Time Spent was added/updated. */ Progressed = 'PROGRESSED', /** Status or Reconsuming was added/updated. */ Updated = 'UPDATED', /** Reaction was added/updated. */ Reacted = 'REACTED', /** Rating was added/updated. */ Rated = 'RATED', /** Notes were added/updated. */ Annotated = 'ANNOTATED' } export type LockInput = { readonly id: Scalars['ID']; readonly lockedReason: LockedReasonEnum; }; export enum LockedReasonEnum { Spam = 'SPAM', TooHeated = 'TOO_HEATED', Closed = 'CLOSED' } export type Manga = Media & WithTimestamps & { readonly __typename?: 'Manga'; /** The recommended minimum age group for this media */ readonly ageRating?: Maybe<AgeRatingEnum>; /** An explanation of why this received the age rating it did */ readonly ageRatingGuide?: Maybe<Scalars['String']>; /** The average rating of this media amongst all Kitsu users */ readonly averageRating?: Maybe<Scalars['Float']>; /** A large banner image for this media */ readonly bannerImage: Image; /** A list of categories for this media */ readonly categories: CategoryConnection; /** The number of chapters in this manga. */ readonly chapterCount?: Maybe<Scalars['Int']>; /** The estimated number of chapters in this manga. */ readonly chapterCountGuess?: Maybe<Scalars['Int']>; /** The chapters in the manga. */ readonly chapters?: Maybe<ChapterConnection>; /** The characters who starred in this media */ readonly characters: MediaCharacterConnection; readonly createdAt: Scalars['ISO8601DateTime']; /** A brief (mostly spoiler free) summary or description of the media. */ readonly description: Scalars['Map']; /** the day that this media made its final release */ readonly endDate?: Maybe<Scalars['Date']>; /** The number of users with this in their favorites */ readonly favoritesCount?: Maybe<Scalars['Int']>; readonly id: Scalars['ID']; /** A list of mappings for this media */ readonly mappings: MappingConnection; /** The time of the next release of this media */ readonly nextRelease?: Maybe<Scalars['ISO8601DateTime']>; /** The country in which the media was primarily produced */ readonly originalLocale?: Maybe<Scalars['String']>; /** The poster image of this media */ readonly posterImage: Image; /** The companies which helped to produce this media */ readonly productions: MediaProductionConnection; /** A list of quotes from this media */ readonly quotes: QuoteConnection; /** A list of reactions for this media */ readonly reactions: MediaReactionConnection; /** Whether the media is Safe-for-Work */ readonly sfw: Scalars['Boolean']; /** The URL-friendly identifier of this media */ readonly slug: Scalars['String']; /** The staff members who worked on this media */ readonly staff: MediaStaffConnection; /** The day that this media first released */ readonly startDate?: Maybe<Scalars['Date']>; /** The current releasing status of this media */ readonly status: ReleaseStatusEnum; /** A secondary type for categorizing Manga. */ readonly subtype: MangaSubtypeEnum; /** Description of when this media is expected to release */ readonly tba?: Maybe<Scalars['String']>; /** The titles for this media in various locales */ readonly titles: TitlesList; /** Anime or Manga. */ readonly type: Scalars['String']; readonly updatedAt: Scalars['ISO8601DateTime']; /** The number of users with this in their library */ readonly userCount?: Maybe<Scalars['Int']>; /** The number of volumes in this manga. */ readonly volumeCount?: Maybe<Scalars['Int']>; }; export type MangaCategoriesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type MangaChaptersArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type MangaCharactersArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type MangaDescriptionArgs = { locales?: Maybe<ReadonlyArray<Scalars['String']>>; }; export type MangaMappingsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type MangaProductionsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type MangaQuotesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type MangaReactionsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type MangaStaffArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type MangaAmountConsumed = AmountConsumed & { readonly __typename?: 'MangaAmountConsumed'; /** Total media completed atleast once. */ readonly completed: Scalars['Int']; readonly id: Scalars['ID']; /** Total amount of media. */ readonly media: Scalars['Int']; /** The profile related to the user for this stat. */ readonly profile: Profile; /** Last time we fully recalculated this stat. */ readonly recalculatedAt: Scalars['ISO8601Date']; /** Total progress of library including reconsuming. */ readonly units: Scalars['Int']; }; export type MangaCategoryBreakdown = CategoryBreakdown & { readonly __typename?: 'MangaCategoryBreakdown'; /** A Map of category_id -> count for all categories present on the library entries */ readonly categories: Scalars['Map']; readonly id: Scalars['ID']; /** The profile related to the user for this stat. */ readonly profile: Profile; /** Last time we fully recalculated this stat. */ readonly recalculatedAt: Scalars['ISO8601Date']; /** The total amount of library entries. */ readonly total: Scalars['Int']; }; /** The connection type for Manga. */ export type MangaConnection = { readonly __typename?: 'MangaConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<MangaEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<Manga>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type MangaEdge = { readonly __typename?: 'MangaEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<Manga>; }; export enum MangaSubtypeEnum { Manga = 'MANGA', Novel = 'NOVEL', /** Chinese comics produced in China and in the Greater China region. */ Manhua = 'MANHUA', Oneshot = 'ONESHOT', /** Self published work. */ Doujin = 'DOUJIN', /** A style of South Korean comic books and graphic novels */ Manhwa = 'MANHWA', /** Original English Language. */ Oel = 'OEL' } /** Media Mappings from External Sites (MAL, Anilist, etc..) to Kitsu. */ export type Mapping = WithTimestamps & { readonly __typename?: 'Mapping'; readonly createdAt: Scalars['ISO8601DateTime']; /** The ID of the media from the external site. */ readonly externalId: Scalars['ID']; /** The name of the site which kitsu media is being linked from. */ readonly externalSite: MappingExternalSiteEnum; readonly id: Scalars['ID']; /** The kitsu object that is mapped. */ readonly item: MappingItemUnion; readonly updatedAt: Scalars['ISO8601DateTime']; }; /** The connection type for Mapping. */ export type MappingConnection = { readonly __typename?: 'MappingConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<MappingEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<Mapping>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; export type MappingCreateInput = { readonly externalSite: MappingExternalSiteEnum; readonly externalId: Scalars['ID']; readonly itemId: Scalars['ID']; readonly itemType: MappingItemEnum; }; /** Autogenerated return type of MappingCreate */ export type MappingCreatePayload = { readonly __typename?: 'MappingCreatePayload'; readonly errors?: Maybe<ReadonlyArray<Error>>; readonly mapping?: Maybe<Mapping>; }; /** Autogenerated return type of MappingDelete */ export type MappingDeletePayload = { readonly __typename?: 'MappingDeletePayload'; readonly errors?: Maybe<ReadonlyArray<Error>>; readonly mapping?: Maybe<GenericDelete>; }; /** An edge in a connection. */ export type MappingEdge = { readonly __typename?: 'MappingEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<Mapping>; }; export enum MappingExternalSiteEnum { MyanimelistAnime = 'MYANIMELIST_ANIME', MyanimelistManga = 'MYANIMELIST_MANGA', MyanimelistCharacters = 'MYANIMELIST_CHARACTERS', MyanimelistPeople = 'MYANIMELIST_PEOPLE', MyanimelistProducers = 'MYANIMELIST_PRODUCERS', AnilistAnime = 'ANILIST_ANIME', AnilistManga = 'ANILIST_MANGA', Thetvdb = 'THETVDB', ThetvdbSeries = 'THETVDB_SERIES', ThetvdbSeason = 'THETVDB_SEASON', Anidb = 'ANIDB', Animenewsnetwork = 'ANIMENEWSNETWORK', Mangaupdates = 'MANGAUPDATES', Hulu = 'HULU', ImdbEpisodes = 'IMDB_EPISODES', Aozora = 'AOZORA', Trakt = 'TRAKT', Mydramalist = 'MYDRAMALIST' } export enum MappingItemEnum { Anime = 'ANIME', Manga = 'MANGA', Category = 'CATEGORY', Character = 'CHARACTER', Episode = 'EPISODE', Person = 'PERSON', Producer = 'PRODUCER' } /** Objects which are Mappable */ export type MappingItemUnion = Anime | Category | Character | Episode | Manga | Person | Producer; export type MappingMutations = { readonly __typename?: 'MappingMutations'; /** Create a Mapping */ readonly create?: Maybe<MappingCreatePayload>; /** Delete a Mapping */ readonly delete?: Maybe<MappingDeletePayload>; /** Update a Mapping */ readonly update?: Maybe<MappingUpdatePayload>; }; export type MappingMutationsCreateArgs = { input: MappingCreateInput; }; export type MappingMutationsDeleteArgs = { input: GenericDeleteInput; }; export type MappingMutationsUpdateArgs = { input: MappingUpdateInput; }; export type MappingUpdateInput = { readonly id: Scalars['ID']; readonly externalSite?: Maybe<MappingExternalSiteEnum>; readonly externalId?: Maybe<Scalars['ID']>; readonly itemId?: Maybe<Scalars['ID']>; readonly itemType?: Maybe<MappingItemEnum>; }; /** Autogenerated return type of MappingUpdate */ export type MappingUpdatePayload = { readonly __typename?: 'MappingUpdatePayload'; readonly errors?: Maybe<ReadonlyArray<Error>>; readonly mapping?: Maybe<Mapping>; }; /** A media in the Kitsu database */ export type Media = { /** The recommended minimum age group for this media */ readonly ageRating?: Maybe<AgeRatingEnum>; /** An explanation of why this received the age rating it did */ readonly ageRatingGuide?: Maybe<Scalars['String']>; /** The average rating of this media amongst all Kitsu users */ readonly averageRating?: Maybe<Scalars['Float']>; /** A large banner image for this media */ readonly bannerImage: Image; /** A list of categories for this media */ readonly categories: CategoryConnection; /** The characters who starred in this media */ readonly characters: MediaCharacterConnection; /** A brief (mostly spoiler free) summary or description of the media. */ readonly description: Scalars['Map']; /** the day that this media made its final release */ readonly endDate?: Maybe<Scalars['Date']>; /** The number of users with this in their favorites */ readonly favoritesCount?: Maybe<Scalars['Int']>; readonly id: Scalars['ID']; /** A list of mappings for this media */ readonly mappings: MappingConnection; /** The time of the next release of this media */ readonly nextRelease?: Maybe<Scalars['ISO8601DateTime']>; /** The country in which the media was primarily produced */ readonly originalLocale?: Maybe<Scalars['String']>; /** The poster image of this media */ readonly posterImage: Image; /** The companies which helped to produce this media */ readonly productions: MediaProductionConnection; /** A list of quotes from this media */ readonly quotes: QuoteConnection; /** A list of reactions for this media */ readonly reactions: MediaReactionConnection; /** Whether the media is Safe-for-Work */ readonly sfw: Scalars['Boolean']; /** The URL-friendly identifier of this media */ readonly slug: Scalars['String']; /** The staff members who worked on this media */ readonly staff: MediaStaffConnection; /** The day that this media first released */ readonly startDate?: Maybe<Scalars['Date']>; /** The current releasing status of this media */ readonly status: ReleaseStatusEnum; /** Description of when this media is expected to release */ readonly tba?: Maybe<Scalars['String']>; /** The titles for this media in various locales */ readonly titles: TitlesList; /** Anime or Manga. */ readonly type: Scalars['String']; /** The number of users with this in their library */ readonly userCount?: Maybe<Scalars['Int']>; }; /** A media in the Kitsu database */ export type MediaCategoriesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** A media in the Kitsu database */ export type MediaCharactersArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** A media in the Kitsu database */ export type MediaDescriptionArgs = { locales?: Maybe<ReadonlyArray<Scalars['String']>>; }; /** A media in the Kitsu database */ export type MediaMappingsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** A media in the Kitsu database */ export type MediaProductionsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** A media in the Kitsu database */ export type MediaQuotesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** A media in the Kitsu database */ export type MediaReactionsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** A media in the Kitsu database */ export type MediaStaffArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** Information about a Character starring in a Media */ export type MediaCharacter = WithTimestamps & { readonly __typename?: 'MediaCharacter'; /** The character */ readonly character: Character; readonly createdAt: Scalars['ISO8601DateTime']; readonly id: Scalars['ID']; /** The media */ readonly media: Media; /** The role this character had in the media */ readonly role: CharacterRoleEnum; readonly updatedAt: Scalars['ISO8601DateTime']; /** The voices of this character */ readonly voices?: Maybe<CharacterVoiceConnection>; }; /** Information about a Character starring in a Media */ export type MediaCharacterVoicesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; locale?: Maybe<ReadonlyArray<Scalars['String']>>; }; /** The connection type for MediaCharacter. */ export type MediaCharacterConnection = { readonly __typename?: 'MediaCharacterConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<MediaCharacterEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<MediaCharacter>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type MediaCharacterEdge = { readonly __typename?: 'MediaCharacterEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<MediaCharacter>; }; /** The connection type for Media. */ export type MediaConnection = { readonly __typename?: 'MediaConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<MediaEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<Media>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; }; /** An edge in a connection. */ export type MediaEdge = { readonly __typename?: 'MediaEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<Media>; }; /** The role a company played in the creation or localization of a media */ export type MediaProduction = WithTimestamps & { readonly __typename?: 'MediaProduction'; /** The production company */ readonly company: Producer; readonly createdAt: Scalars['ISO8601DateTime']; readonly id: Scalars['ID']; /** The media */ readonly media: Media; /** The role this company played */ readonly role: MediaProductionRoleEnum; readonly updatedAt: Scalars['ISO8601DateTime']; }; /** The connection type for MediaProduction. */ export type MediaProductionConnection = { readonly __typename?: 'MediaProductionConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<MediaProductionEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<MediaProduction>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type MediaProductionEdge = { readonly __typename?: 'MediaProductionEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<MediaProduction>; }; export enum MediaProductionRoleEnum { Producer = 'PRODUCER', Licensor = 'LICENSOR', Studio = 'STUDIO', Serialization = 'SERIALIZATION' } /** A simple review that is 140 characters long expressing how you felt about a media */ export type MediaReaction = WithTimestamps & { readonly __typename?: 'MediaReaction'; /** The author who wrote this reaction. */ readonly author: Profile; readonly createdAt: Scalars['ISO8601DateTime']; readonly id: Scalars['ID']; /** The library entry related to this reaction. */ readonly libraryEntry: LibraryEntry; /** Users who liked this reaction. */ readonly likes: ProfileConnection; /** The media related to this reaction. */ readonly media: Media; /** When this media reaction was written based on media progress. */ readonly progress: Scalars['Int']; /** The reaction text related to a media. */ readonly reaction: Scalars['String']; readonly updatedAt: Scalars['ISO8601DateTime']; }; /** A simple review that is 140 characters long expressing how you felt about a media */ export type MediaReactionLikesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** The connection type for MediaReaction. */ export type MediaReactionConnection = { readonly __typename?: 'MediaReactionConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<MediaReactionEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<MediaReaction>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type MediaReactionEdge = { readonly __typename?: 'MediaReactionEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<MediaReaction>; }; /** Information about a person working on an anime */ export type MediaStaff = WithTimestamps & { readonly __typename?: 'MediaStaff'; readonly createdAt: Scalars['ISO8601DateTime']; readonly id: Scalars['ID']; /** The media */ readonly media: Media; /** The person */ readonly person: Person; /** The role this person had in the creation of this media */ readonly role: Scalars['String']; readonly updatedAt: Scalars['ISO8601DateTime']; }; /** The connection type for MediaStaff. */ export type MediaStaffConnection = { readonly __typename?: 'MediaStaffConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<MediaStaffEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<MediaStaff>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type MediaStaffEdge = { readonly __typename?: 'MediaStaffEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<MediaStaff>; }; /** これはアニメやマンガです */ export enum MediaTypeEnum { Anime = 'ANIME', Manga = 'MANGA' } export type Mutation = { readonly __typename?: 'Mutation'; readonly anime: AnimeMutations; readonly episode: EpisodeMutations; readonly libraryEntry: LibraryEntryMutations; readonly mapping: MappingMutations; readonly post: PostMutations; readonly pro: ProMutations; }; /** Information about pagination in a connection. */ export type PageInfo = { readonly __typename?: 'PageInfo'; /** When paginating forwards, the cursor to continue. */ readonly endCursor?: Maybe<Scalars['String']>; /** When paginating forwards, are there more items? */ readonly hasNextPage: Scalars['Boolean']; /** When paginating backwards, are there more items? */ readonly hasPreviousPage: Scalars['Boolean']; /** When paginating backwards, the cursor to continue. */ readonly startCursor?: Maybe<Scalars['String']>; }; /** A Voice Actor, Director, Animator, or other person who works in the creation and localization of media */ export type Person = WithTimestamps & { readonly __typename?: 'Person'; /** The day when this person was born */ readonly birthday?: Maybe<Scalars['Date']>; readonly createdAt: Scalars['ISO8601DateTime']; /** A brief biography or description of the person. */ readonly description: Scalars['Map']; readonly id: Scalars['ID']; /** An image of the person */ readonly image?: Maybe<Image>; /** Information about the person working on specific media */ readonly mediaStaff?: Maybe<MediaStaffConnection>; /** The primary name of this person. */ readonly name: Scalars['String']; /** The name of this person in various languages */ readonly names: TitlesList; /** The URL-friendly identifier of this person. */ readonly slug: Scalars['String']; readonly updatedAt: Scalars['ISO8601DateTime']; /** The voice-acting roles this person has had. */ readonly voices?: Maybe<CharacterVoiceConnection>; }; /** A Voice Actor, Director, Animator, or other person who works in the creation and localization of media */ export type PersonDescriptionArgs = { locales?: Maybe<ReadonlyArray<Scalars['String']>>; }; /** A Voice Actor, Director, Animator, or other person who works in the creation and localization of media */ export type PersonMediaStaffArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** A Voice Actor, Director, Animator, or other person who works in the creation and localization of media */ export type PersonVoicesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** A post that is visible to your followers and globally in the news-feed. */ export type Post = WithTimestamps & { readonly __typename?: 'Post'; /** The user who created this post. */ readonly author: Profile; /** All comments on this post */ readonly comments: CommentConnection; /** Unmodified content. */ readonly content: Scalars['String']; /** Html formatted content. */ readonly contentFormatted: Scalars['String']; readonly createdAt: Scalars['ISO8601DateTime']; /** Users that are watching this post */ readonly follows: ProfileConnection; readonly id: Scalars['ID']; /** If a post is Not-Safe-for-Work. */ readonly isNsfw: Scalars['Boolean']; /** If this post spoils the tagged media. */ readonly isSpoiler: Scalars['Boolean']; /** Users that have liked this post */ readonly likes: ProfileConnection; /** When this post was locked. */ readonly lockedAt?: Maybe<Scalars['ISO8601DateTime']>; /** The user who locked this post. */ readonly lockedBy?: Maybe<Profile>; /** The reason why this post was locked. */ readonly lockedReason?: Maybe<LockedReasonEnum>; /** The media tagged in this post. */ readonly media?: Maybe<Media>; readonly updatedAt: Scalars['ISO8601DateTime']; }; /** A post that is visible to your followers and globally in the news-feed. */ export type PostCommentsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; sort?: Maybe<ReadonlyArray<Maybe<CommentSortOption>>>; }; /** A post that is visible to your followers and globally in the news-feed. */ export type PostFollowsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** A post that is visible to your followers and globally in the news-feed. */ export type PostLikesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; sort?: Maybe<ReadonlyArray<Maybe<PostLikeSortOption>>>; }; /** The connection type for Post. */ export type PostConnection = { readonly __typename?: 'PostConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<PostEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<Post>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type PostEdge = { readonly __typename?: 'PostEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<Post>; }; export enum PostLikeSortEnum { Following = 'FOLLOWING', CreatedAt = 'CREATED_AT' } export type PostLikeSortOption = { readonly on: PostLikeSortEnum; readonly direction: SortDirection; }; /** Autogenerated return type of PostLock */ export type PostLockPayload = { readonly __typename?: 'PostLockPayload'; readonly errors?: Maybe<ReadonlyArray<Error>>; readonly post?: Maybe<Post>; }; export type PostMutations = { readonly __typename?: 'PostMutations'; /** Lock a Post. */ readonly lock?: Maybe<PostLockPayload>; /** Unlock a Post. */ readonly unlock?: Maybe<PostUnlockPayload>; }; export type PostMutationsLockArgs = { input: LockInput; }; export type PostMutationsUnlockArgs = { input: UnlockInput; }; export enum PostSortEnum { CreatedAt = 'CREATED_AT' } export type PostSortOption = { readonly on: PostSortEnum; readonly direction: SortDirection; }; /** Autogenerated return type of PostUnlock */ export type PostUnlockPayload = { readonly __typename?: 'PostUnlockPayload'; readonly errors?: Maybe<ReadonlyArray<Error>>; readonly post?: Maybe<Post>; }; export type ProMutations = { readonly __typename?: 'ProMutations'; /** Set the user's discord tag */ readonly setDiscord?: Maybe<ProSetDiscordPayload>; /** Set the user's Hall-of-Fame message */ readonly setMessage?: Maybe<ProSetMessagePayload>; /** End the user's pro subscription */ readonly unsubscribe?: Maybe<ProUnsubscribePayload>; }; export type ProMutationsSetDiscordArgs = { discord: Scalars['String']; }; export type ProMutationsSetMessageArgs = { message: Scalars['String']; }; /** Autogenerated return type of ProSetDiscord */ export type ProSetDiscordPayload = { readonly __typename?: 'ProSetDiscordPayload'; readonly discord: Scalars['String']; }; /** Autogenerated return type of ProSetMessage */ export type ProSetMessagePayload = { readonly __typename?: 'ProSetMessagePayload'; readonly message: Scalars['String']; }; /** A subscription to Kitsu PRO */ export type ProSubscription = WithTimestamps & { readonly __typename?: 'ProSubscription'; /** The account which is subscribed to Pro benefits */ readonly account: Account; /** The billing service used for this subscription */ readonly billingService: RecurringBillingServiceEnum; readonly createdAt: Scalars['ISO8601DateTime']; /** The tier of Pro the account is subscribed to */ readonly tier: ProTierEnum; readonly updatedAt: Scalars['ISO8601DateTime']; }; export enum ProTierEnum { /** Aozora Pro (only hides ads) */ AoPro = 'AO_PRO', /** Aozora Pro+ (only hides ads) */ AoProPlus = 'AO_PRO_PLUS', /** Basic tier of Kitsu Pro */ Pro = 'PRO', /** Top tier of Kitsu Pro */ Patron = 'PATRON' } /** Autogenerated return type of ProUnsubscribe */ export type ProUnsubscribePayload = { readonly __typename?: 'ProUnsubscribePayload'; readonly expiresAt?: Maybe<Scalars['ISO8601DateTime']>; }; /** A company involved in the creation or localization of media */ export type Producer = WithTimestamps & { readonly __typename?: 'Producer'; readonly createdAt: Scalars['ISO8601DateTime']; readonly id: Scalars['ID']; /** The name of this production company */ readonly name: Scalars['String']; readonly updatedAt: Scalars['ISO8601DateTime']; }; /** A user profile on Kitsu */ export type Profile = WithTimestamps & { readonly __typename?: 'Profile'; /** A short biographical blurb about this profile */ readonly about?: Maybe<Scalars['String']>; /** An avatar image to easily identify this profile */ readonly avatarImage?: Maybe<Image>; /** A banner to display at the top of the profile */ readonly bannerImage?: Maybe<Image>; /** When the user was born */ readonly birthday?: Maybe<Scalars['ISO8601Date']>; /** All comments to any post this user has made. */ readonly comments: CommentConnection; readonly createdAt: Scalars['ISO8601DateTime']; /** Favorite media, characters, and people */ readonly favorites: FavoriteConnection; /** People that follow the user */ readonly followers: ProfileConnection; /** People the user is following */ readonly following: ProfileConnection; /** What the user identifies as */ readonly gender?: Maybe<Scalars['String']>; readonly id: Scalars['ID']; /** The user library of their media */ readonly library: Library; /** A list of library events for this user */ readonly libraryEvents: LibraryEventConnection; /** The user's general location */ readonly location?: Maybe<Scalars['String']>; /** Media reactions written by this user. */ readonly mediaReactions: MediaReactionConnection; /** A non-unique publicly visible name for the profile. Minimum of 3 characters and any valid Unicode character */ readonly name: Scalars['String']; /** Post pinned to the user profile */ readonly pinnedPost?: Maybe<Post>; /** All posts this profile has made. */ readonly posts: PostConnection; /** The message this user has submitted to the Hall of Fame */ readonly proMessage?: Maybe<Scalars['String']>; /** The PRO level the user currently has */ readonly proTier?: Maybe<ProTierEnum>; /** Links to the user on other (social media) sites. */ readonly siteLinks?: Maybe<SiteLinkConnection>; /** The URL-friendly identifier for this profile */ readonly slug?: Maybe<Scalars['String']>; /** The different stats we calculate for this user. */ readonly stats: ProfileStats; readonly updatedAt: Scalars['ISO8601DateTime']; /** A fully qualified URL to the profile */ readonly url?: Maybe<Scalars['String']>; /** The character this profile has declared as their waifu or husbando */ readonly waifu?: Maybe<Character>; /** The properly-gendered term for the user's waifu. This should normally only be 'Waifu' or 'Husbando' but some people are jerks, including the person who wrote this... */ readonly waifuOrHusbando?: Maybe<Scalars['String']>; }; /** A user profile on Kitsu */ export type ProfileCommentsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** A user profile on Kitsu */ export type ProfileFavoritesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** A user profile on Kitsu */ export type ProfileFollowersArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** A user profile on Kitsu */ export type ProfileFollowingArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** A user profile on Kitsu */ export type ProfileLibraryEventsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; kind?: Maybe<ReadonlyArray<LibraryEventKindEnum>>; }; /** A user profile on Kitsu */ export type ProfileMediaReactionsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** A user profile on Kitsu */ export type ProfilePostsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; sort?: Maybe<ReadonlyArray<Maybe<PostSortOption>>>; }; /** A user profile on Kitsu */ export type ProfileSiteLinksArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** The connection type for Profile. */ export type ProfileConnection = { readonly __typename?: 'ProfileConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<ProfileEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<Profile>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type ProfileEdge = { readonly __typename?: 'ProfileEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<Profile>; }; /** The different types of user stats that we calculate. */ export type ProfileStats = { readonly __typename?: 'ProfileStats'; /** The total amount of anime you have watched over your whole life. */ readonly animeAmountConsumed: AnimeAmountConsumed; /** The breakdown of the different categories related to the anime you have completed */ readonly animeCategoryBreakdown: AnimeCategoryBreakdown; /** The total amount of manga you ahve read over your whole life. */ readonly mangaAmountConsumed: MangaAmountConsumed; /** The breakdown of the different categories related to the manga you have completed */ readonly mangaCategoryBreakdown: MangaCategoryBreakdown; }; export type Query = { readonly __typename?: 'Query'; /** All Anime in the Kitsu database */ readonly anime: AnimeConnection; /** All Anime with specific Status */ readonly animeByStatus?: Maybe<AnimeConnection>; /** All Categories in the Kitsu Database */ readonly categories?: Maybe<CategoryConnection>; /** Kitsu account details. You must supply an Authorization token in header. */ readonly currentAccount?: Maybe<Account>; /** Find a single Anime by ID */ readonly findAnimeById?: Maybe<Anime>; /** Find a single Anime by Slug */ readonly findAnimeBySlug?: Maybe<Anime>; /** Find a single Category by ID */ readonly findCategoryById?: Maybe<Category>; /** Find a single Category by Slug */ readonly findCategoryBySlug?: Maybe<Category>; /** Find a single Character by ID */ readonly findCharacterById?: Maybe<Character>; /** Find a single Character by Slug */ readonly findCharacterBySlug?: Maybe<Character>; /** Find a single Library Entry by ID */ readonly findLibraryEntryById?: Maybe<LibraryEntry>; /** Find a single Library Event by ID */ readonly findLibraryEventById?: Maybe<LibraryEvent>; /** Find a single Manga by ID */ readonly findMangaById?: Maybe<Manga>; /** Find a single Manga by Slug */ readonly findMangaBySlug?: Maybe<Manga>; /** Find a single Person by ID */ readonly findPersonById?: Maybe<Person>; /** Find a single Person by Slug */ readonly findPersonBySlug?: Maybe<Person>; /** Find a single Post by ID */ readonly findPostById?: Maybe<Post>; /** Find a single User by ID */ readonly findProfileById?: Maybe<Profile>; /** Find a single User by Slug */ readonly findProfileBySlug?: Maybe<Profile>; /** List trending media on Kitsu */ readonly globalTrending: MediaConnection; /** List of Library Entries by MediaType and MediaId */ readonly libraryEntriesByMedia?: Maybe<LibraryEntryConnection>; /** List of Library Entries by MediaType */ readonly libraryEntriesByMediaType?: Maybe<LibraryEntryConnection>; /** List trending media within your network */ readonly localTrending: MediaConnection; /** Find a specific Mapping Item by External ID and External Site. */ readonly lookupMapping?: Maybe<MappingItemUnion>; /** All Manga in the Kitsu database */ readonly manga: MangaConnection; /** All Manga with specific Status */ readonly mangaByStatus?: Maybe<MangaConnection>; /** Patrons sorted by a Proprietary Magic Algorithm */ readonly patrons: ProfileConnection; /** Random anime or manga */ readonly randomMedia: Media; /** Search for Anime by title using Algolia. The most relevant results will be at the top. */ readonly searchAnimeByTitle: AnimeConnection; /** Search for Manga by title using Algolia. The most relevant results will be at the top. */ readonly searchMangaByTitle: MangaConnection; /** Search for any media (Anime, Manga) by title using Algolia. If no media_type is supplied, it will search for both. The most relevant results will be at the top. */ readonly searchMediaByTitle: MediaConnection; /** Search for User by username using Algolia. The most relevant results will be at the top. */ readonly searchProfileByUsername?: Maybe<ProfileConnection>; /** Get your current session info */ readonly session: Session; }; export type QueryAnimeArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type QueryAnimeByStatusArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; status: ReleaseStatusEnum; }; export type QueryCategoriesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type QueryFindAnimeByIdArgs = { id: Scalars['ID']; }; export type QueryFindAnimeBySlugArgs = { slug: Scalars['String']; }; export type QueryFindCategoryByIdArgs = { id: Scalars['ID']; }; export type QueryFindCategoryBySlugArgs = { slug: Scalars['String']; }; export type QueryFindCharacterByIdArgs = { id: Scalars['ID']; }; export type QueryFindCharacterBySlugArgs = { slug: Scalars['String']; }; export type QueryFindLibraryEntryByIdArgs = { id: Scalars['ID']; }; export type QueryFindLibraryEventByIdArgs = { id: Scalars['ID']; }; export type QueryFindMangaByIdArgs = { id: Scalars['ID']; }; export type QueryFindMangaBySlugArgs = { slug: Scalars['String']; }; export type QueryFindPersonByIdArgs = { id: Scalars['ID']; }; export type QueryFindPersonBySlugArgs = { slug: Scalars['String']; }; export type QueryFindPostByIdArgs = { id: Scalars['ID']; }; export type QueryFindProfileByIdArgs = { id: Scalars['ID']; }; export type QueryFindProfileBySlugArgs = { slug: Scalars['String']; }; export type QueryGlobalTrendingArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; mediaType: MediaTypeEnum; }; export type QueryLibraryEntriesByMediaArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; mediaType: MediaTypeEnum; mediaId: Scalars['ID']; }; export type QueryLibraryEntriesByMediaTypeArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; mediaType: MediaTypeEnum; }; export type QueryLocalTrendingArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; mediaType: MediaTypeEnum; }; export type QueryLookupMappingArgs = { externalId: Scalars['ID']; externalSite: MappingExternalSiteEnum; }; export type QueryMangaArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type QueryMangaByStatusArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; status: ReleaseStatusEnum; }; export type QueryPatronsArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type QueryRandomMediaArgs = { mediaType: MediaTypeEnum; ageRatings: ReadonlyArray<AgeRatingEnum>; }; export type QuerySearchAnimeByTitleArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; title: Scalars['String']; }; export type QuerySearchMangaByTitleArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; title: Scalars['String']; }; export type QuerySearchMediaByTitleArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; title: Scalars['String']; mediaType?: Maybe<MediaTypeEnum>; }; export type QuerySearchProfileByUsernameArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; username: Scalars['String']; }; /** A quote from a media */ export type Quote = WithTimestamps & { readonly __typename?: 'Quote'; readonly createdAt: Scalars['ISO8601DateTime']; readonly id: Scalars['ID']; /** The lines of the quote */ readonly lines: QuoteLineConnection; /** The media this quote is excerpted from */ readonly media: Media; readonly updatedAt: Scalars['ISO8601DateTime']; }; /** A quote from a media */ export type QuoteLinesArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** The connection type for Quote. */ export type QuoteConnection = { readonly __typename?: 'QuoteConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<QuoteEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<Quote>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type QuoteEdge = { readonly __typename?: 'QuoteEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<Quote>; }; /** A line in a quote */ export type QuoteLine = WithTimestamps & { readonly __typename?: 'QuoteLine'; /** The character who said this line */ readonly character: Character; /** The line that was spoken */ readonly content: Scalars['String']; readonly createdAt: Scalars['ISO8601DateTime']; readonly id: Scalars['ID']; /** The quote this line is in */ readonly quote: Quote; readonly updatedAt: Scalars['ISO8601DateTime']; }; /** The connection type for QuoteLine. */ export type QuoteLineConnection = { readonly __typename?: 'QuoteLineConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<QuoteLineEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<QuoteLine>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type QuoteLineEdge = { readonly __typename?: 'QuoteLineEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<QuoteLine>; }; export enum RatingSystemEnum { /** 1-20 displayed as 4 smileys - Awful (1), Meh (8), Good (14) and Great (20) */ Simple = 'SIMPLE', /** 1-20 in increments of 2 displayed as 5 stars in 0.5 star increments */ Regular = 'REGULAR', /** 1-20 in increments of 1 displayed as 1-10 in 0.5 increments */ Advanced = 'ADVANCED' } export enum RecurringBillingServiceEnum { /** Bill a credit card via Stripe */ Stripe = 'STRIPE', /** Bill a PayPal account */ Paypal = 'PAYPAL', /** Billed through Apple In-App Subscription */ Apple = 'APPLE', /** Billed through Google Play Subscription */ GooglePlay = 'GOOGLE_PLAY' } export enum ReleaseSeasonEnum { /** Released during the Winter season */ Winter = 'WINTER', /** Released during the Spring season */ Spring = 'SPRING', /** Released during the Summer season */ Summer = 'SUMMER', /** Released during the Fall season */ Fall = 'FALL' } export enum ReleaseStatusEnum { /** The release date has not been announced yet */ Tba = 'TBA', /** This media is no longer releasing */ Finished = 'FINISHED', /** This media is currently releasing */ Current = 'CURRENT', /** This media is releasing soon */ Upcoming = 'UPCOMING', /** This media is not released yet */ Unreleased = 'UNRELEASED' } /** Information about a user session */ export type Session = { readonly __typename?: 'Session'; /** The account associated with this session */ readonly account?: Maybe<Account>; /** Single sign-on token for Nolt */ readonly noltToken: Scalars['String']; /** The profile associated with this session */ readonly profile?: Maybe<Profile>; }; /** A link to a user's profile on an external site. */ export type SiteLink = WithTimestamps & { readonly __typename?: 'SiteLink'; /** The user profile the site is linked to. */ readonly author: Profile; readonly createdAt: Scalars['ISO8601DateTime']; readonly id: Scalars['ID']; readonly updatedAt: Scalars['ISO8601DateTime']; /** A fully qualified URL of the user profile on an external site. */ readonly url: Scalars['String']; }; /** The connection type for SiteLink. */ export type SiteLinkConnection = { readonly __typename?: 'SiteLinkConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<SiteLinkEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<SiteLink>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type SiteLinkEdge = { readonly __typename?: 'SiteLinkEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<SiteLink>; }; export enum SitePermissionEnum { /** Administrator/staff member of Kitsu */ Admin = 'ADMIN', /** Moderator of community behavior */ CommunityMod = 'COMMUNITY_MOD', /** Maintainer of the Kitsu media database */ DatabaseMod = 'DATABASE_MOD' } export enum SortDirection { Ascending = 'ASCENDING', Descending = 'DESCENDING' } /** Media that is streamable. */ export type Streamable = { /** Spoken language is replaced by language of choice. */ readonly dubs: ReadonlyArray<Scalars['String']>; /** Which regions this video is available in. */ readonly regions: ReadonlyArray<Scalars['String']>; /** The site that is streaming this media. */ readonly streamer: Streamer; /** Languages this is translated to. Usually placed at bottom of media. */ readonly subs: ReadonlyArray<Scalars['String']>; }; /** The streaming company. */ export type Streamer = WithTimestamps & { readonly __typename?: 'Streamer'; readonly createdAt: Scalars['ISO8601DateTime']; readonly id: Scalars['ID']; /** The name of the site that is streaming this media. */ readonly siteName: Scalars['String']; /** Additional media this site is streaming. */ readonly streamingLinks: StreamingLinkConnection; readonly updatedAt: Scalars['ISO8601DateTime']; /** Videos of the media being streamed. */ readonly videos: VideoConnection; }; /** The streaming company. */ export type StreamerStreamingLinksArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** The streaming company. */ export type StreamerVideosArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; /** The stream link. */ export type StreamingLink = Streamable & WithTimestamps & { readonly __typename?: 'StreamingLink'; readonly createdAt: Scalars['ISO8601DateTime']; /** Spoken language is replaced by language of choice. */ readonly dubs: ReadonlyArray<Scalars['String']>; readonly id: Scalars['ID']; /** The media being streamed */ readonly media: Media; /** Which regions this video is available in. */ readonly regions: ReadonlyArray<Scalars['String']>; /** The site that is streaming this media. */ readonly streamer: Streamer; /** Languages this is translated to. Usually placed at bottom of media. */ readonly subs: ReadonlyArray<Scalars['String']>; readonly updatedAt: Scalars['ISO8601DateTime']; /** Fully qualified URL for the streaming link. */ readonly url: Scalars['String']; }; /** The connection type for StreamingLink. */ export type StreamingLinkConnection = { readonly __typename?: 'StreamingLinkConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<StreamingLinkEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<StreamingLink>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type StreamingLinkEdge = { readonly __typename?: 'StreamingLinkEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<StreamingLink>; }; export enum TitleLanguagePreferenceEnum { /** Prefer the most commonly-used title for media */ Canonical = 'CANONICAL', /** Prefer the romanized title for media */ Romanized = 'ROMANIZED', /** Prefer the localized title for media */ Localized = 'LOCALIZED' } export type TitlesList = { readonly __typename?: 'TitlesList'; /** A list of additional, alternative, abbreviated, or unofficial titles */ readonly alternatives?: Maybe<ReadonlyArray<Scalars['String']>>; /** The official or de facto international title */ readonly canonical?: Maybe<Scalars['String']>; /** The locale code that identifies which title is used as the canonical title */ readonly canonicalLocale?: Maybe<Scalars['String']>; /** The list of localized titles keyed by locale */ readonly localized: Scalars['Map']; }; export type TitlesListLocalizedArgs = { locales?: Maybe<ReadonlyArray<Scalars['String']>>; }; export type TitlesListInput = { readonly canonical?: Maybe<Scalars['String']>; readonly localized?: Maybe<Scalars['Map']>; readonly alternatives?: Maybe<ReadonlyArray<Scalars['String']>>; readonly canonicalLocale?: Maybe<Scalars['String']>; }; /** Media units such as episodes or chapters */ export type Unit = { /** A brief summary or description of the unit */ readonly description: Scalars['Map']; readonly id: Scalars['ID']; /** The sequence number of this unit */ readonly number: Scalars['Int']; /** A thumbnail image for the unit */ readonly thumbnail?: Maybe<Image>; /** The titles for this unit in various locales */ readonly titles: TitlesList; }; /** Media units such as episodes or chapters */ export type UnitDescriptionArgs = { locales?: Maybe<ReadonlyArray<Scalars['String']>>; }; export type UnlockInput = { readonly id: Scalars['ID']; }; /** The media video. */ export type Video = Streamable & WithTimestamps & { readonly __typename?: 'Video'; readonly createdAt: Scalars['ISO8601DateTime']; /** Spoken language is replaced by language of choice. */ readonly dubs: ReadonlyArray<Scalars['String']>; /** The episode of this video */ readonly episode: Episode; readonly id: Scalars['ID']; /** Which regions this video is available in. */ readonly regions: ReadonlyArray<Scalars['String']>; /** The site that is streaming this media. */ readonly streamer: Streamer; /** Languages this is translated to. Usually placed at bottom of media. */ readonly subs: ReadonlyArray<Scalars['String']>; readonly updatedAt: Scalars['ISO8601DateTime']; /** The url of the video. */ readonly url: Scalars['String']; }; /** The connection type for Video. */ export type VideoConnection = { readonly __typename?: 'VideoConnection'; /** A list of edges. */ readonly edges?: Maybe<ReadonlyArray<Maybe<VideoEdge>>>; /** A list of nodes. */ readonly nodes?: Maybe<ReadonlyArray<Maybe<Video>>>; /** Information to aid in pagination. */ readonly pageInfo: PageInfo; /** The total amount of nodes. */ readonly totalCount: Scalars['Int']; }; /** An edge in a connection. */ export type VideoEdge = { readonly __typename?: 'VideoEdge'; /** A cursor for use in pagination. */ readonly cursor: Scalars['String']; /** The item at the end of the edge. */ readonly node?: Maybe<Video>; }; /** A manga volume which can contain multiple chapters. */ export type Volume = WithTimestamps & { readonly __typename?: 'Volume'; /** The chapters in this volume. */ readonly chapters?: Maybe<ChapterConnection>; readonly createdAt: Scalars['ISO8601DateTime']; readonly id: Scalars['ID']; /** The isbn number of this volume. */ readonly isbn: ReadonlyArray<Scalars['String']>; /** The manga this volume is in. */ readonly manga: Manga; /** The volume number. */ readonly number: Scalars['Int']; /** The date when this chapter was released. */ readonly published?: Maybe<Scalars['ISO8601Date']>; /** The titles for this chapter in various locales */ readonly titles: TitlesList; readonly updatedAt: Scalars['ISO8601DateTime']; }; /** A manga volume which can contain multiple chapters. */ export type VolumeChaptersArgs = { after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; }; export type WithTimestamps = { readonly createdAt: Scalars['ISO8601DateTime']; readonly updatedAt: Scalars['ISO8601DateTime']; };
the_stack
import { expect, test } from '@jest/globals'; import { ReceiveType, ReflectionClass, resolveReceiveType } from '../src/reflection/reflection'; import { AutoIncrement, BackReference, isReferenceType, MapName, MongoId, PrimaryKey, Reference, UUID } from '../src/reflection/type'; import { cast, cloneClass, serialize } from '../src/serializer-facade'; import { createReference } from '../src/reference'; import { unpopulatedSymbol } from '../src/core'; (BigInt.prototype as any).toJSON = function () { return this.toString(); }; function roundTrip<T>(value: T | any, type?: ReceiveType<T>): T { const t = resolveReceiveType(type); // console.log('roundTrip', stringifyType(t)); const json = serialize(value, {}, undefined, undefined, type); const res = cast<T>(json, {}, undefined, undefined, type); return res; } function serializeToJson<T>(value: T | any, type?: ReceiveType<T>): T { const json = serialize(value, {}, undefined, undefined, type); return json; } function deserializeFromJson<T>(value: any, type?: ReceiveType<T>): T { const res = cast<T>(value, {}, undefined, undefined, type); return res; } enum MyEnum { a, b, c } class Config { color: string = '#fff'; big: boolean = false; } class Model { id: number = 0; title: string = ''; config?: Config; } test('basics with value', () => { expect(roundTrip<string>('asd')).toBe('asd'); expect(roundTrip<number>(22)).toBe(22); expect(roundTrip<boolean>(false)).toBe(false); expect(roundTrip<Date>(new Date)).toBeInstanceOf(Date); }); test('model', () => { { const item = new Model; item.id = 23; item.title = '2322'; const back = roundTrip<Model>(item); expect(back).toEqual({ id: 23, title: '2322' }); expect(back).toBeInstanceOf(Model); } }); test('with implicit default value', () => { const defaultDate = new Date; class Product { id: number = 0; created: Date = defaultDate; } //having a default value doesn't mean we are optional; expect(ReflectionClass.from(Product).getProperty('created')!.isOptional()).toBe(false); expect(roundTrip<Product>({ id: 23 } as any)).toEqual({ id: 23, created: defaultDate }); expect(deserializeFromJson<Product>({ id: 23, created: undefined } as any)).toEqual({ id: 23, created: defaultDate }); expect(roundTrip<Product>({ id: 23, created: undefined } as any)).toEqual({ id: 23, created: defaultDate }); expect(roundTrip<Partial<Product>>({ id: 23 } as any)).toEqual({ id: 23 }); expect(roundTrip<Partial<Product>>({ id: 23, created: undefined } as any)).toEqual({ id: 23 }); //not set properties are omitted expect('created' in roundTrip<Partial<Product>>({ id: 23 } as any)).toEqual(false); //we need to keep undefined values otherwise there is not way to reset a value //for JSON/BSON on the transport layer is null used to communicate the fact that we set explicitly `created` to undefined expect('created' in serializeToJson<Partial<Product>>({ id: 23, created: undefined } as any)).toEqual(true); expect('created' in roundTrip<Partial<Product>>({ id: 23, created: undefined } as any)).toEqual(true); }); test('partial keeps explicitely undefined fields', () => { expect(roundTrip<Partial<Model>>({})).toEqual({}); expect('name' in roundTrip<Partial<Model>>({})).toBe(false); expect(roundTrip<Partial<Model>>({ title: undefined })).toEqual({ title: undefined }); { const item = serializeToJson<Partial<Model>>({ title: undefined }); expect(item).toEqual({ title: null }); } { const item = roundTrip<Partial<Model>>({ title: undefined }); expect('title' in item).toBe(true); //all fields in partial become optional } { const item = roundTrip<Partial<Model>>({}); expect('title' in item).toBe(false); } class Purchase { id: number & PrimaryKey & AutoIncrement = 0; sentAt?: Date; canceledAt?: Date; } expect(roundTrip<Partial<Purchase>>({ sentAt: undefined })).toEqual({ sentAt: undefined }); expect('sentAt' in roundTrip<Partial<Purchase>>({ sentAt: undefined })).toEqual(true); }); test('record removes undefined when not allowed', () => { expect(roundTrip<Record<string, string>>({})).toEqual({}); expect(roundTrip<Record<string, string>>({ foo: 'bar' })).toEqual({ foo: 'bar' }); expect(roundTrip<Record<string, string>>({ foo: undefined } as any)).toEqual({}); expect('foo' in roundTrip<Record<string, string>>({ foo: undefined } as any)).toEqual(false); }); test('record allows undefined when allowed', () => { expect(serializeToJson<Record<string, string | undefined>>({})).toEqual({}); expect(serializeToJson<Record<string, string | undefined>>({ foo: 'bar' })).toEqual({ foo: 'bar' }); expect(serializeToJson<Record<string, string | undefined>>({ foo: undefined } as any)).toEqual({ foo: null }); expect('foo' in serializeToJson<Record<string, string | undefined>>({ foo: undefined } as any)).toEqual(true); expect(roundTrip<Record<string, string | undefined>>({})).toEqual({}); expect(roundTrip<Record<string, string | undefined>>({ foo: 'bar' })).toEqual({ foo: 'bar' }); expect(roundTrip<Record<string, string | undefined>>({ foo: undefined } as any)).toEqual({ foo: undefined }); expect('foo' in roundTrip<Record<string, string | undefined>>({ foo: undefined } as any)).toEqual(true); }); test('bigint', () => { expect(roundTrip<bigint>(0n)).toEqual(0n); expect(roundTrip<bigint>(5n)).toEqual(5n); expect(roundTrip<bigint>(12n)).toEqual(12n); expect(roundTrip<bigint>(12012020202020202020202020202020202020n)).toEqual(12012020202020202020202020202020202020n); expect(roundTrip<bigint>(16n ** 16n ** 2n)).toEqual(16n ** 16n ** 2n); expect(roundTrip<bigint>(16n ** 16n ** 3n)).toEqual(16n ** 16n ** 3n); }); test('union basics', () => { expect(roundTrip<string | number>('asd')).toEqual('asd'); expect(roundTrip<string | number>(23)).toEqual(23); expect(roundTrip<boolean | number>(true)).toEqual(true); expect(roundTrip<boolean | number>(23)).toEqual(23); expect(roundTrip<bigint | number>(23)).toEqual(23); expect(roundTrip<bigint | number>(23n)).toEqual(23n); expect(roundTrip<string | Model>(new Model)).toBeInstanceOf(Model); { const item = new Model; item.id = 23; item.title = '23'; const back = roundTrip<string | Model>(item); expect(back).toEqual({ id: 23, title: '23' }); } { const item = new Model; item.id = 23; item.title = '23'; const back = roundTrip<Model>(item); expect(back).toEqual({ id: 23, title: '23' }); } expect(roundTrip<string | Model>('asd')).toEqual('asd'); expect(roundTrip<string | Model | undefined>(undefined)).toEqual(undefined); expect(roundTrip<string | Model | undefined>(null)).toEqual(undefined); expect(roundTrip<string | Model | null>(undefined)).toEqual(null); expect(roundTrip<string | Model | null>(null)).toEqual(null); }); test('union 2', () => { interface s { type: 'm'; name: string; } expect(deserializeFromJson<undefined | s>({ type: 'm', name: 'Peter' })).toEqual({ type: 'm', name: 'Peter' }); expect(serializeToJson<undefined | s>({ type: 'm', name: 'Peter' })).toEqual({ type: 'm', name: 'Peter' }); expect(roundTrip<undefined | s>({ type: 'm', name: 'Peter' })).toEqual({ type: 'm', name: 'Peter' }); }); test('union 3', () => { expect(deserializeFromJson<string | Model>('asd')).toBe('asd'); expect(deserializeFromJson<string | Model>({ id: 0, title: 'foo' } as any)).toEqual({ id: 0, title: 'foo' }); expect(deserializeFromJson<string | Model | undefined>(undefined)).toBe(undefined); expect(deserializeFromJson<string | Model | null>(null)).toBe(null); expect(serializeToJson<string | Model>('asd')).toBe('asd'); expect(serializeToJson<string | Model>({ id: 0, title: 'foo' } as any)).toEqual({ id: 0, title: 'foo' }); expect(serializeToJson<string | Model | undefined>(undefined)).toBe(null); expect(serializeToJson<string | Model | null>(null)).toBe(null); expect(roundTrip<string | Model>('asd')).toBe('asd'); expect(roundTrip<string | Model>({ id: 0, title: 'foo' } as any)).toBeInstanceOf(Model); }); test('model 1', () => { class Model { //filter is not used yet filter?: Record<string, string | number | boolean | RegExp>; skip?: number; itemsPerPage: number = 50; limit?: number; parameters: { [name: string]: any } = {}; sort?: Record<any, any>; } { const model = { filter: { $regex: /Peter/ }, itemsPerPage: 50, parameters: {} }; expect(roundTrip<Model>(model as any)).toEqual(model); } { const o = { parameters: { teamName: 'Team a' } }; expect(serializeToJson<Model>(o)).toEqual(o); } { const model = { itemsPerPage: 50, parameters: { teamName: 'Team a' }, filter: undefined, skip: undefined, limit: undefined, sort: undefined }; expect(roundTrip<Model>(model as any)).toEqual(model); } }); class Team { id: number & PrimaryKey & AutoIncrement = 0; version: number = 0; lead?: User & Reference; constructor(public name: string) { } } class User { id: number & PrimaryKey & AutoIncrement = 0; version: number = 0; teams: Team[] & BackReference<{ via: typeof UserTeam }> = []; constructor(public name: string) { } } class UserTeam { id: number & PrimaryKey & AutoIncrement = 0; version: number = 0; constructor( public team: Team & Reference, public user: User & Reference, ) { } } test('relation 1', () => { const team = ReflectionClass.from(Team); const user = ReflectionClass.from(User); //they have to be different, otherwise User would have the Reference annotations applied expect(team.getProperty('lead').type === user.type).toBe(false); expect(isReferenceType(user.type)).toBe(false); { const user = new User('foo'); expect(roundTrip<User>(user)).toEqual(user); } { const team = new Team('foo'); expect(roundTrip<Team>(team)).toEqual(team); } { const team = new Team('foo'); const user = new User('foo'); user.id = 12; team.lead = user; expect(serializeToJson<Team>(team)).toEqual(team); expect(deserializeFromJson<Team>(team)).toEqual(team); expect(roundTrip<Team>(team)).toEqual(team); } { const team = new Team('foo'); team.id = 1; team.version = 2; team.lead = createReference(User, { id: 12 }); const json = { id: 1, version: 2, name: 'foo', lead: 12 as any }; expect(serializeToJson<Team>(team)).toEqual(json); const back = deserializeFromJson<Team>(json); expect(back).toEqual(team); expect(back.lead).toBeInstanceOf(User); expect(back.lead!.id).toBe(12); expect(roundTrip<Team>(team)).toEqual(team); } }); test('relation 2', () => { { const user = new User('foo'); user.teams = unpopulatedSymbol as any; //emulates an unpopulated relation const user2 = cloneClass(user); user2.teams = []; expect(roundTrip<User>(user)).toEqual(user2); } { const user = new User('foo'); user.teams.push(new Team('bar')); expect(serializeToJson<User>(user)).toEqual(user); expect(roundTrip<User>(user)).toEqual(user); } { const items: User[] = [ cast<User>({ name: 'Peter 1', id: 1, version: 0, }), cast<User>({ name: 'Peter 2', id: 2, version: 0, }), cast<User>({ name: 'Marc 1', id: 3, version: 0, }) ]; expect(roundTrip<User[]>(items)).toEqual(items); } }); // test('invalid', () => { // expect(roundTrip<UUID>(new Model as any)).toEqual(RoundTripExcluded); // }); test('regex', () => { expect(roundTrip<RegExp>(/foo/)).toEqual(/foo/); }); test('explicitly set undefined on optional triggers default value', () => { class Product { id: number = 0; created?: Date = new Date; } //no value means the default triggers expect(roundTrip<Product>({ id: 23 }).created).toBeInstanceOf(Date); //this is important for database patches expect(roundTrip<Product>({ id: 23, created: undefined }).created).toBe(undefined); expect('created' in roundTrip<Product>({ id: 23, created: undefined })).toBe(true); }); test('partial explicitly set undefined on optional is handled', () => { class Product { id: number = 0; created?: Date = new Date; } //no value means the default triggers expect(roundTrip<Partial<Product>>({ id: 23 }).created).toBe(undefined); //this is important for database patches expect(roundTrip<Partial<Product>>({ id: 23, created: undefined }).created).toBe(undefined); expect('created' in roundTrip<Partial<Product>>({ id: 23, created: undefined })).toBe(true); }); test('partial explicitly set undefined on required is not ignored', () => { class Product { id: number = 0; created: Date = new Date; } //no value means the default triggers expect(roundTrip<Partial<Product>>({ id: 23 }).created).toBe(undefined); //this is important for database patches //important to keep undefined, as t.partial() makes all properties optional, no matter what it originally was, otherwise it would be a partial expect(roundTrip<Partial<Product>>({ id: 23, created: undefined }).created).toBe(undefined); expect('created' in roundTrip<Partial<Product>>({ id: 23, created: undefined } as any)).toBe(true); }); test('explicitely set undefined on required is ignored', () => { class Product { id: number = 0; created: Date = new Date; } expect(roundTrip<Product>({ id: 23 } as any).created).toBeInstanceOf(Date); expect(roundTrip<Product>({ id: 23, created: undefined } as any).created).toBeInstanceOf(Date); }); test('partial does not return the model on root', () => { expect(roundTrip<Partial<Model>>({ id: 23 } as any)).toEqual({ id: 23 }); expect(roundTrip<Partial<Model>>({ id: 23 } as any)).not.toBeInstanceOf(Model); }); test('partial returns the model at second level', () => { const config = new Config; config.color = 'red'; expect(roundTrip<Partial<Model>>({ id: 23, config: config } as any)).toEqual({ id: 23, config: { big: false, color: 'red' } }); expect(roundTrip<Partial<Model>>({ id: 23, config: config } as any).config).toBeInstanceOf(Config); }); test('partial allowed undefined', () => { class Product { id: number = 0; created?: Date; } expect(roundTrip<Partial<Product>>({ id: 23, created: undefined } as any)).not.toBeInstanceOf(Product); expect(roundTrip<Partial<Product>>({ id: 23 } as any).created).toBe(undefined); expect('created' in roundTrip<Partial<Product>>({ id: 23 } as any)).toBe(false); //important for database patches expect(roundTrip<Partial<Product>>({ id: 23, created: undefined } as any).created).toBe(undefined); expect('created' in roundTrip<Partial<Product>>({ id: 23, created: undefined } as any)).toBe(true); }); test('optional basics', () => { expect(roundTrip<string | undefined>(undefined)).toBe(undefined); expect(roundTrip<string | undefined>(null)).toBe(undefined); expect(roundTrip<number | undefined>(undefined)).toBe(undefined); expect(roundTrip<number | undefined>(null)).toBe(undefined); expect(roundTrip<boolean | undefined>(undefined)).toBe(undefined); expect(roundTrip<boolean | undefined>(null)).toBe(undefined); expect(roundTrip<UUID | undefined>(undefined)).toBe(undefined); expect(roundTrip<UUID | undefined>(null)).toBe(undefined); expect(roundTrip<MongoId | undefined>(undefined)).toBe(undefined); expect(roundTrip<MongoId | undefined>(null)).toBe(undefined); expect(roundTrip<Date | undefined>(undefined)).toBe(undefined); expect(roundTrip<Date | undefined>(null)).toBe(undefined); expect(roundTrip<Record<string, string> | undefined>(undefined)).toBe(undefined); expect(roundTrip<Record<string, string> | undefined>(null)).toBe(undefined); expect(roundTrip<any[] | undefined>(undefined)).toBe(undefined); expect(roundTrip<any[] | undefined>(null)).toBe(undefined); expect(roundTrip<Partial<{ a: string }> | undefined>(undefined)).toBe(undefined); expect(roundTrip<Partial<{ a: string }> | undefined>(null)).toBe(undefined); // expect(roundTrip(t.patch({a: t.string}).optional, undefined)).toBe(undefined); // expect(roundTrip(t.patch({a: t.string}).optional, null)).toBe(undefined); expect(roundTrip<'a' | undefined>(undefined)).toBe(undefined); expect(roundTrip<'a' | undefined>(null)).toBe(undefined); expect(roundTrip<MyEnum | undefined>(undefined)).toBe(undefined); expect(roundTrip<MyEnum | undefined>(null)).toBe(undefined); expect(roundTrip<Model | undefined>(undefined)).toBe(undefined); expect(roundTrip<Model | undefined>(null)).toBe(undefined); expect(roundTrip<ArrayBuffer | undefined>(undefined)).toBe(undefined); expect(roundTrip<ArrayBuffer | undefined>(null)).toBe(undefined); expect(roundTrip<Uint8Array | undefined>(undefined)).toBe(undefined); expect(roundTrip<Uint8Array | undefined>(null)).toBe(undefined); }); test('nullable container', () => { interface s { tags: string[] | null; tagMap: Record<string, string> | null; tagPartial: Partial<{ name: string }> | null; } expect(roundTrip<s>({ tags: null, tagMap: null, tagPartial: null })).toEqual({ tags: null, tagMap: null, tagPartial: null }); expect(roundTrip<s>({} as any)).toEqual({ tags: null, tagMap: null, tagPartial: null }); expect(serializeToJson<s>({} as any)).toEqual({ tags: null, tagMap: null, tagPartial: null }); }); test('nullable basics', () => { expect(roundTrip<string | null>(undefined)).toBe(null); expect(roundTrip<string | null>(null)).toBe(null); expect(roundTrip<number | null>(undefined)).toBe(null); expect(roundTrip<number | null>(null)).toBe(null); expect(roundTrip<boolean | null>(undefined)).toBe(null); expect(roundTrip<boolean | null>(null)).toBe(null); expect(roundTrip<Date | null>(undefined)).toBe(null); expect(roundTrip<Date | null>(null)).toBe(null); expect(roundTrip<UUID | null>(undefined)).toBe(null); expect(roundTrip<UUID | null>(null)).toBe(null); expect(roundTrip<MongoId | null>(undefined)).toBe(null); expect(roundTrip<MongoId | null>(null)).toBe(null); expect(roundTrip<Record<string, string> | null>(undefined)).toBe(null); expect(roundTrip<Record<string, string> | null>(null)).toBe(null); expect(roundTrip<any[] | null>(undefined)).toBe(null); expect(roundTrip<any[] | null>(null)).toBe(null); expect(roundTrip<Partial<{ a: string }> | null>(undefined)).toBe(null); expect(roundTrip<Partial<{ a: string }> | null>(null)).toBe(null); expect(roundTrip<'a' | null>(undefined)).toBe(null); expect(roundTrip<'a' | null>(null)).toBe(null); expect(roundTrip<MyEnum | null>(undefined)).toBe(null); expect(roundTrip<MyEnum | null>(null)).toBe(null); expect(roundTrip<Model | null>(undefined)).toBe(null); expect(roundTrip<Model | null>(null)).toBe(null); expect(roundTrip<ArrayBuffer | null>(undefined)).toBe(null); expect(roundTrip<ArrayBuffer | null>(null)).toBe(null); expect(roundTrip<Uint8Array | null>(undefined)).toBe(null); expect(roundTrip<Uint8Array | null>(null)).toBe(null); }); test('constructor argument', () => { class Product { id: number = 0; constructor(public title: string) { } } class Purchase { id: number = 0; constructor(public product: Product) { } } { const item = roundTrip<Purchase>({ id: 4, product: new Product('asd') }); expect(item.product).toBeInstanceOf(Product); } }); test('omit circular reference 1', () => { class Model { another?: Model; constructor( public id: number = 0 ) { } } expect(ReflectionClass.from(Model).hasCircularReference()).toBe(true); { const model = new Model(1); const model2 = new Model(2); model.another = model2; const plain = serializeToJson<Model>(model); expect(plain.another).toBeInstanceOf(Object); expect(plain.another!.id).toBe(2); } { const model = new Model(1); model.another = model; const plain = serializeToJson<Model>(model); expect(plain.another).toBe(undefined); } }); test('omit circular reference 2', () => { class Config { constructor(public model: Model) { } } class Model { id: number = 0; config?: Config; } expect(ReflectionClass.from(Model).hasCircularReference()).toBe(true); expect(ReflectionClass.from(Config).hasCircularReference()).toBe(true); { const model = new Model; const config = new Config(model); model.config = config; const plain = serializeToJson<Model>(model); expect(plain.config).toBeInstanceOf(Object); expect(plain.config!.model).toBe(undefined); } { const model = new Model; const model2 = new Model; const config = new Config(model2); model.config = config; const plain = serializeToJson<Model>(model); expect(plain.config).toBeInstanceOf(Object); expect(plain.config!.model).toBeInstanceOf(Object); } }); test('omit circular reference 3', () => { class User { id: number = 0; public images: Image[] = []; constructor(public name: string) { } } class Image { id: number = 0; constructor( public user: User, public title: string, ) { if (user.images && !user.images.includes(this)) { user.images.push(this); } } } expect(ReflectionClass.from(User).hasCircularReference()).toBe(true); expect(ReflectionClass.from(Image).hasCircularReference()).toBe(true); { const user = new User('foo'); const image = new Image(user, 'bar'); { const plain = serializeToJson<User>(user); expect(plain.images.length).toBe(1); expect(plain.images[0]).toBeInstanceOf(Object); expect(plain.images[0].title).toBe('bar'); } { const plain = serializeToJson<Image>(image); expect(plain.user).toBeInstanceOf(Object); expect(plain.user.name).toBe('foo'); } } { const user = new User('foo'); const plain = serializeToJson<User>(user); expect(plain.images.length).toBe(0); } }); test('promise', () => { //make sure promise is automatically forwarded to its first generic type expect(serializeToJson<Promise<string>>('1')).toBe('1'); expect(deserializeFromJson<Promise<string>>('1' as any)).toBe('1'); expect(roundTrip<Promise<string>>('1' as any)).toBe('1'); }); test('class inheritance', () => { class A { id: number = 0; } class B extends A { username: string = ''; } expect(deserializeFromJson<A>({ id: 2 })).toEqual({ id: 2 }); expect(serializeToJson<A>({ id: 2 })).toEqual({ id: 2 }); expect(deserializeFromJson<B>({ id: 2, username: 'Peter' })).toEqual({ id: 2, username: 'Peter' }); expect(serializeToJson<B>({ id: 2, username: 'Peter' })).toEqual({ id: 2, username: 'Peter' }); }); test('mapName interface', () => { interface A { type: string & MapName<'~type'>; } expect(deserializeFromJson<A>({ '~type': 'abc' })).toEqual({ 'type': 'abc' }); expect(serializeToJson<A>({ 'type': 'abc' })).toEqual({ '~type': 'abc' }); expect(deserializeFromJson<A | string>({ '~type': 'abc' })).toEqual({ 'type': 'abc' }); expect(serializeToJson<A | string>({ 'type': 'abc' })).toEqual({ '~type': 'abc' }); expect(serializeToJson<A | string>('abc')).toEqual('abc'); }); test('mapName class', () => { class A { id: string & MapName<'~id'> = ''; constructor(public type: string & MapName<'~type'>) { } } expect(deserializeFromJson<A>({ '~id': '1', '~type': 'abc' })).toEqual({ 'id': '1', 'type': 'abc' }); expect(serializeToJson<A>({ id: '1', 'type': 'abc' })).toEqual({ '~id': '1', '~type': 'abc' }); expect(deserializeFromJson<A | string>({ '~id': '', '~type': 'abc' })).toEqual({ id: '', 'type': 'abc' }); expect(serializeToJson<A | string>({ id: '1', 'type': 'abc' })).toEqual({ '~id': '1', '~type': 'abc' }); expect(serializeToJson<A | string>('abc')).toEqual('abc'); }); test('dynamic properties', () => { class A { [index: string]: any; getType(): string { return String(this['~type'] || this['type'] || ''); } } const back1 = deserializeFromJson<A>({ '~type': 'abc' }); expect(back1.getType()).toBe('abc'); const back2 = deserializeFromJson<A>({ 'type': 'abc' }); expect(back2.getType()).toBe('abc'); });
the_stack
import React from 'react'; import { fireEvent, render } from '@testing-library/react'; import { ComboBox, ComboBoxProps } from './ComboBox'; import { SvgCaretDownSmall } from '@itwin/itwinui-icons-react'; const renderComponent = (props?: Partial<ComboBoxProps<number>>) => { return render( <ComboBox options={[ { label: 'Item 0', value: 0 }, { label: 'Item 1', value: 1 }, { label: 'Item 2', value: 2 }, ]} {...props} />, ); }; const assertBaseElement = (container: HTMLElement) => { const rootElement = container.querySelector( '.iui-input-container', ) as HTMLDivElement; expect(rootElement).toHaveClass('iui-inline-icon'); const input = rootElement.querySelector('.iui-input') as HTMLInputElement; expect(input).toHaveAttribute('role', 'combobox'); expect(input).toHaveAttribute('autocapitalize', 'none'); expect(input).toHaveAttribute('autocorrect', 'off'); expect(input).toHaveAttribute('spellcheck', 'false'); return input; }; it('should render in its most basic state', () => { const { container } = renderComponent(); const id = container.querySelector('.iui-input-container')?.id; const input = assertBaseElement(container); input.focus(); expect(input).toHaveAttribute('aria-expanded', 'true'); expect(input).toHaveAttribute('aria-controls', `${id}-list`); expect(input).toHaveAttribute('aria-autocomplete', 'list'); const list = container.querySelector('.iui-menu') as HTMLUListElement; expect(list).toBeVisible(); expect(list.id).toEqual(`${id}-list`); expect(list).toHaveAttribute('role', 'listbox'); expect(list.children).toHaveLength(3); list.querySelectorAll('.iui-menu-item').forEach((item, index) => { expect(item).toHaveTextContent(`Item ${index}`); expect(item).not.toHaveAttribute('aria-selected'); expect(item.id).toEqual(`${id}-option${index}`); }); }); it('should render with selected value', () => { const { container } = renderComponent({ value: 2 }); const input = assertBaseElement(container); expect(input.value).toEqual('Item 2'); input.focus(); container.querySelectorAll('.iui-menu-item').forEach((item, index) => { expect(item).toHaveTextContent(`Item ${index}`); if (index === 2) { expect(item).toHaveClass('iui-active'); expect(item).toHaveAttribute('aria-selected', 'true'); } }); }); it('should render caret icon correctly', () => { const { container } = renderComponent(); let icon = container.querySelector('.iui-input-icon svg') as HTMLElement; const { container: { firstChild: caretDown }, } = render(<SvgCaretDownSmall aria-hidden />); expect(icon).toEqual(caretDown); expect(container.querySelector('.iui-menu')).toBeFalsy(); // open fireEvent.click(icon); icon = container.querySelector('.iui-input-icon svg') as HTMLElement; expect(icon).toEqual(caretDown); expect(container.querySelector('.iui-menu')).toBeVisible(); // close fireEvent.click(icon); icon = container.querySelector('.iui-input-icon svg') as HTMLElement; expect(icon).toEqual(caretDown); expect(container.querySelector('.iui-menu')).not.toBeVisible(); }); it('should filter list according to text input', () => { const emptyText = 'No options 🙁'; const { container } = renderComponent({ options: [ { label: 'Item0', value: 0 }, { label: 'Item-1', value: 1 }, { label: 'Item-2', value: 2 }, { label: 'Item-3', value: 3 }, ], emptyStateMessage: emptyText, }); const input = assertBaseElement(container); input.focus(); const menu = container.querySelector('.iui-menu') as HTMLElement; // no filter expect(menu.children).toHaveLength(4); // filter with all items fireEvent.change(input, { target: { value: 'Item' } }); expect(menu.children).toHaveLength(4); // 3 items fireEvent.change(input, { target: { value: 'Item-' } }); expect(menu.children).toHaveLength(3); // only 1 item fireEvent.change(input, { target: { value: 'Item-2' } }); expect(menu.children).toHaveLength(1); expect(menu.firstElementChild).toHaveTextContent('Item-2'); // no items fireEvent.change(input, { target: { value: 'Item-5' } }); expect(menu.children).toHaveLength(1); expect(menu.firstElementChild).toHaveTextContent(emptyText); // 1 item fireEvent.change(input, { target: { value: 'Item-3' } }); expect(menu.children).toHaveLength(1); expect(menu.firstElementChild).toHaveTextContent('Item-3'); // clear filter fireEvent.change(input, { target: { value: '' } }); expect(menu.children).toHaveLength(4); }); it('should accept custom filter function', () => { const { container } = renderComponent({ options: [ { label: 'ItemZero', value: 0 }, { label: 'Item-one', value: 1 }, { label: 'Item-two', value: 2 }, { label: 'Item-three', value: 3 }, ], filterFunction: (options, str) => options.filter( (option) => option.label.includes(str) || option.value.toString().includes(str), ), }); const input = assertBaseElement(container); input.focus(); const menu = container.querySelector('.iui-menu') as HTMLElement; // no filter expect(menu.children).toHaveLength(4); // 3 items fireEvent.change(input, { target: { value: 'Item-' } }); expect(menu.children).toHaveLength(3); // only 1 item fireEvent.change(input, { target: { value: '2' } }); expect(menu.children).toHaveLength(1); expect(menu.firstElementChild).toHaveTextContent('Item-two'); // only 1 item fireEvent.change(input, { target: { value: 'Zero' } }); expect(menu.children).toHaveLength(1); expect(menu.firstElementChild).toHaveTextContent('ItemZero'); // no items fireEvent.change(input, { target: { value: 'five' } }); expect(menu.children).toHaveLength(1); expect(menu.firstElementChild).toHaveTextContent('No options'); }); it('should select value on click', () => { const mockOnChange = jest.fn(); const { container, getByText } = renderComponent({ onChange: mockOnChange }); const input = assertBaseElement(container); input.focus(); getByText('Item 1').click(); expect(mockOnChange).toHaveBeenCalledWith(1); expect(container.querySelector('.iui-menu')).not.toBeVisible(); expect(input.value).toEqual('Item 1'); input.blur(); input.focus(); expect( container.querySelector('.iui-menu-item.iui-active.iui-focused'), ).toHaveTextContent('Item 1'); }); it('should handle keyboard navigation', () => { const id = 'test-component'; const mockOnChange = jest.fn(); const { container } = renderComponent({ id, onChange: mockOnChange }); const input = assertBaseElement(container); input.focus(); expect(input).toHaveAttribute('aria-controls', `${id}-list`); const items = container.querySelectorAll('.iui-menu-item'); // focus index 0 fireEvent.keyDown(input, { key: 'ArrowDown' }); expect(input).toHaveAttribute('aria-activedescendant', `${id}-option0`); expect(items[0]).toHaveClass('iui-focused'); // 0 -> 1 fireEvent.keyDown(input, { key: 'ArrowDown' }); expect(input).toHaveAttribute('aria-activedescendant', `${id}-option1`); expect(items[1]).toHaveClass('iui-focused'); expect(items[0]).not.toHaveClass('iui-focused'); // 1 -> 2 fireEvent.keyDown(input, { key: 'ArrowDown' }); expect(input).toHaveAttribute('aria-activedescendant', `${id}-option2`); expect(items[2]).toHaveClass('iui-focused'); // 2 -> 2 fireEvent.keyDown(input, { key: 'ArrowDown' }); expect(input).toHaveAttribute('aria-activedescendant', `${id}-option2`); expect(items[2]).toHaveClass('iui-focused'); // 2 -> 1 fireEvent.keyDown(input, { key: 'ArrowUp' }); expect(input).toHaveAttribute('aria-activedescendant', `${id}-option1`); expect(items[1]).toHaveClass('iui-focused'); expect(items[2]).not.toHaveClass('iui-focused'); // 1 -> 0 fireEvent.keyDown(input, { key: 'ArrowUp' }); expect(input).toHaveAttribute('aria-activedescendant', `${id}-option0`); expect(items[0]).toHaveClass('iui-focused'); // select 0 fireEvent.keyDown(input, { key: 'Enter' }); expect(mockOnChange).toHaveBeenCalledWith(0); expect(container.querySelector('.iui-menu')).not.toBeVisible(); // reopen menu fireEvent.keyDown(input, { key: 'Enter' }); expect(items[0]).toHaveClass('iui-active iui-focused'); // filter and focus item 2 fireEvent.change(input, { target: { value: 'Item 2' } }); fireEvent.keyDown(input, { key: 'ArrowDown' }); expect(items[2]).toHaveClass('iui-focused'); expect(input).toHaveAttribute('aria-activedescendant', `${id}-option2`); // select 2 fireEvent.keyDown(input, { key: 'Enter' }); expect(mockOnChange).toHaveBeenCalledWith(2); expect(container.querySelector('.iui-menu')).not.toBeVisible(); // reopen fireEvent.keyDown(input, { key: 'ArrowDown' }); expect(items[2]).toHaveClass('iui-active iui-focused'); expect(input).toHaveAttribute('aria-activedescendant', `${id}-option2`); // close fireEvent.keyDown(input, { key: 'Escape' }); expect(container.querySelector('.iui-menu')).not.toBeVisible(); // reopen and close fireEvent.keyDown(input, { key: 'X' }); expect(container.querySelector('.iui-menu')).toBeVisible(); fireEvent.keyDown(input, { key: 'Tab' }); expect(container.querySelector('.iui-menu')).not.toBeVisible(); }); it('should accept inputProps', () => { const inputId = 'test-input'; const { container } = renderComponent({ inputProps: { id: inputId, name: 'input-name', required: true }, }); const input = assertBaseElement(container); expect(input.name).toBe('input-name'); expect(input.required).toBeTruthy(); expect(input.id).toBe(inputId); input.focus(); expect(container.querySelector('.iui-input-container')?.id).toBe( `${inputId}-cb`, ); expect(container.querySelector('.iui-menu')?.id).toBe(`${inputId}-cb-list`); }); it('should accept status prop', () => { const { container } = renderComponent({ status: 'negative' }); expect(container.querySelector('.iui-input-container')).toHaveClass( 'iui-negative', ); });
the_stack
import Q = require("q"); import _ = require("underscore"); import Validation = require("./Validation"); /** * Basic validation rules that enables to validate an value against common constraints. * * Assertions with conditions. * * + basic constraints (Type,EqualTo,Required) * + string constraints (Email,Pattern, Url,MinLength,MaxLength) * + numeric constraints (Digits,SignedDigits,Min,Max,Range,MultipleOf) * + date constraints (Data,DateISO) */ module Validators { class NumberFce { static GetNegDigits(value:string):number { if (value === undefined) return 0; var digits = value.toString().split('.'); if (digits.length > 1) { return digits[1].length; } return 0; } } /** * Return true if it is a valid string letter representation, otherwise false. */ export class LettersOnlyValidator implements Validation.IStringValidator { private lettersRegexp = /^[A-Za-z]+$/; isAcceptable(s:string) { return this.lettersRegexp.test(s); } tagName = "lettersonly"; } /** * Return true if it is a valid zip code, otherwise false. */ export class ZipCodeValidator implements Validation.IStringValidator { private numberRegexp = /^[0-9]+$/; isAcceptable(s:string) { return s.length === 5 && this.numberRegexp.test(s); } tagName = "zipcode"; } /** * Return true if it is a valid Internet email address as defined by RFC 5322, section 3.4.1, otherwise false */ export class EmailValidator implements Validation.IStringValidator { // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/ private emailRegexp = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; isAcceptable(s:string) { return this.emailRegexp.test(s); } tagName = "email"; } /** * Return true if it is a valid URI, according to [RFC3986], otherwise false. */ export class UrlValidator implements Validation.IStringValidator { // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/ private urlRegexp = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; isAcceptable(s:string) { return this.urlRegexp.test(s); } tagName = "url"; } /** * Return true if it is a valid Luhn card number based on http://en.wikipedia.org/wiki/Luhn/, otherwise false; */ export class CreditCardValidator implements Validation.IStringValidator { //taken from http://jqueryvalidation.org/creditcard-method/ isAcceptable(value:string) { // accept only spaces, digits and dashes if (/[^0-9 \-]+/.test(value)) { return false; } var nCheck = 0, nDigit = 0, bEven = false, n, cDigit; value = value.replace(/\D/g, ""); // Basing min and max length on // http://developer.ean.com/general_info/Valid_Credit_Card_Types if (value.length < 13 || value.length > 19) { return false; } for (n = value.length - 1; n >= 0; n--) { cDigit = value.charAt(n); nDigit = parseInt(cDigit, 10); if (bEven) { if (( nDigit *= 2 ) > 9) { nDigit -= 9; } } nCheck += nDigit; bEven = !bEven; } return ( nCheck % 10 ) === 0; } tagName = "creditcard"; } /** * Return true if it is not empty value, otherwise false. */ export class RequiredValidator implements Validation.IStringValidator { isAcceptable(s:string) { return s !== undefined && s !== ""; } tagName = "required"; } /** * Return true if a value is equal (using strict equal) to passed value, otherwise false. */ export class EqualToValidator implements Validation.IPropertyValidator { /** * * @param Value */ constructor(public Value?:any) { } isAcceptable(s:any) { return s === this.Value; } tagName = "equalTo"; } /** * Return true if it is a valid string date representation (can be parsed as date), otherwise false. */ export class DateValidator implements Validation.IStringValidator { isAcceptable(s:string) { return !/Invalid|NaN/.test(new Date(s).toString()); } tagName = "date"; } /** * Return true if it is a valid string ISO date representation (can be parsed as ISO date), otherwise false. */ export class DateISOValidator implements Validation.IStringValidator { isAcceptable(s:string) { return /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(s); } tagName = "dateISO"; } /** * Return true if it is a valid number representation, otherwise false. */ export class NumberValidator implements Validation.IStringValidator { isAcceptable(s:string) { return /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(s); } tagName = "number"; } /** * Return true if it is a valid digit representation, otherwise false. */ export class DigitValidator implements Validation.IStringValidator { isAcceptable(s:string) { return /^\d+$/.test(s); } tagName = "digit"; } /** * Return true if it is a valid positive or negative digit representation, otherwise false. */ export class SignedDigitValidator implements Validation.IStringValidator { isAcceptable(s:string) { return /^-?\d+$/.test(s); } tagName = "signedDigit"; } var MinimalDefaultValue = 0; /** * Return true if string length is greater or equal to MinLength property. */ export class MinLengthValidator implements Validation.IStringValidator { /** * Default constructor * @param MinLength - minimal number of characters. */ constructor(public MinLength?:number) { if (MinLength === undefined) this.MinLength = MinimalDefaultValue; } isAcceptable(s:string) { return s.length >= this.MinLength; } tagName = "minlength"; } var MaximalDefaultValue = 0; /** * Return true if string length is less or equal to MaxLength property. */ export class MaxLengthValidator implements Validation.IStringValidator { /** * Default constructor. * @param MaxLength - maximal number of characters. */ constructor(public MaxLength?:number) { if (MaxLength === undefined) this.MaxLength = MaximalDefaultValue; } isAcceptable(s:string) { return s.length <= this.MaxLength; } tagName = "maxlength"; } /** * Return true if string length is between MinLength and MaxLength property. */ export class RangeLengthValidator implements Validation.IStringValidator { /** * Default constructor. * @param RangeLength - array [minimal number of characters, maximal number of characters] */ constructor(public RangeLength?:Array<number>) { if (RangeLength === undefined) this.RangeLength = [MinimalDefaultValue, MaximalDefaultValue]; } isAcceptable(s:string) { return s.length >= this.MinLength && s.length <= this.MaxLength; } public get MinLength():number { return this.RangeLength[0]; } public get MaxLength():number { return this.RangeLength[1]; } tagName = "rangelength"; } /** * Return true only for these conditions * if "Exclusive" is false, then the instance is valid if it is greater than, or equal to, the value of "minimum"; * if "Exclusive" is true, the instance is valid if it is strictly greater than the value of "minimum". * * @require underscore */ export class MinValidator implements Validation.IPropertyValidator { /** * Default constructor. * @param Min - the value of "minimum" * @param Exclusive - true = strictly greater, otherwise greater or equal to the value of "minimum"; */ constructor(public Min?:number,public Exclusive?:boolean) { if (Min === undefined) this.Min = MinimalDefaultValue; } isAcceptable(s:any) { if (!_.isNumber(s)) s = parseFloat(s); return this.Exclusive?( s> this.Min):( s >= this.Min); } tagName = "min"; } /** * Return true if the number of items in array is lower or equal to the value of "minimum". * * @require underscore */ export class MinItemsValidator implements Validation.IPropertyValidator { /** * Default constructor. * @param Max - the value of "minimum" */ constructor(public Min?:number) { if (Min === undefined) this.Min = MinimalDefaultValue; } isAcceptable(s:any) { if (_.isArray(s)) return s.length >=this.Min; return false; } tagName = "minItems"; } /** * Return true only for these conditions * if "Exclusive" is false, then the instance is valid if it is lower than, or equal to, the value of "maximum"; * if "Exclusive" is true, the instance is valid if it is strictly lower than the value of "maximum". * * @require underscore */ export class MaxValidator implements Validation.IPropertyValidator { /** * Default constructor * @param Max - the value of "maximum" * @param Exclusive - true = strictly lower, otherwise lower or equal to the value of "maximum"; */ constructor(public Max?:number, public Exclusive?:boolean) { if (Max === undefined) this.Max = MaximalDefaultValue; } isAcceptable(s:any) { if (!_.isNumber(s)) s = parseFloat(s); return this.Exclusive? (s<this.Max): (s<=this.Max); } tagName = "max"; } /** * Return true if an number of items in array is greater or equal to the value of "maximum". * * @require underscore */ export class MaxItemsValidator implements Validation.IPropertyValidator { /** * Default constructor. * @param Max - the value of "maximum" */ constructor(public Max?:number) { if (Max === undefined) this.Max = MaximalDefaultValue; } isAcceptable(s:any) { if (_.isArray(s)) return s.length <=this.Max; return false; } tagName = "maxItems"; } /** * Return true if the array contains unique items (using strict equality), otherwise false. * * @require underscore */ export class UniqItemsValidator implements Validation.IPropertyValidator { isAcceptable(s:any) { if (_.isArray(s)) return _.uniq(s).length === s.length; return false; } tagName = "uniqItems"; } /** * Return true if value is between Min and Max property. * * @require underscore */ export class RangeValidator implements Validation.IPropertyValidator { /** * Default constructor. * @param Range - array [the value of "minimum", the value of "maximum"] */ constructor(public Range?:Array<number>) { if (Range === undefined) this.Range = [MinimalDefaultValue, MaximalDefaultValue]; } isAcceptable(s:any) { if (!_.isNumber(s)) s = parseFloat(s); return s >= this.Min && s <= this.Max; } /** * Return the value of "minimum" * @returns {number} */ public get Min():number { return this.Range[0]; } /** * Return the value of "maximum" * @returns {number} */ public get Max():number { return this.Range[1]; } tagName = "range"; } /** * Return true if an value is any of predefined values (using strict equality), otherwise false. * * @require underscore */ export class EnumValidator implements Validation.IPropertyValidator { /** * Default constructor. * @param Enum - array of values */ constructor(public Enum?:Array<number>) { if (Enum === undefined) this.Enum = []; } isAcceptable(s:any) { return _.contains(this.Enum,s); } tagName = "enum"; } /** * Return true if an value is a specified type, otherwise false. * * @require underscore */ export class TypeValidator implements Validation.IPropertyValidator { /** * Default constructor. * @param Type - keywords that defines an concrete type */ constructor(public Type:string) { if (this.Type === undefined) this.Type = "string"; } isAcceptable(s:any) { if (this.Type === "string") return _.isString(s); if (this.Type === "boolean") return _.isBoolean(s); if (this.Type === "number") return _.isNumber(s); if (this.Type === "integer") return /^\d+$/.test(s); if (this.Type === "object") return _.isObject(s); if (this.Type === "array") return _.isArray(s); return false; } tagName = "type"; } /** * Return true if an value is multiplier of passed number step, otherwise false. */ export class StepValidator implements Validation.IPropertyValidator { private StepDefaultValue = "1"; /** * Default constructor. * @param Step - step multiplier */ constructor(public Step?:string) { if (Step === undefined) this.Step = this.StepDefaultValue; } isAcceptable(s:any) { var maxNegDigits = Math.max(NumberFce.GetNegDigits(s), NumberFce.GetNegDigits(this.Step)); var multiplier = Math.pow(10, maxNegDigits); return (parseInt(s,10) * multiplier) % (parseInt(this.Step,10) * multiplier) === 0; } tagName = "step"; } /** * Return true if a numeric instance is valid against "multipleOf" if the result of the division of the instance by this keyword's value is an integer, otherwise false. * * @require underscore */ export class MultipleOfValidator implements Validation.IPropertyValidator { private MultipleOfDefaultValue = 1; /** * Default constructor * @param Divider */ constructor(public Divider?:number) { if (Divider === undefined) this.Divider = this.MultipleOfDefaultValue; } isAcceptable(s:any) { if (!_.isNumber(s)) return false; return (s % this.Divider) % 1 === 0; } tagName = "multipleOf"; } /** * Return true if an value is valid against specified pattern, otherwise false. */ export class PatternValidator implements Validation.IStringValidator { /** * Default constructor. * @param Pattern - pattern */ constructor(public Pattern?:string) { } isAcceptable(s:string) { return new RegExp(this.Pattern).test(s); } tagName = "pattern"; } /** * Return true if an value is any of predefined values (using strict equality), otherwise false. * Predefined values are fetched async with options service. * * @require underscore * @require Q */ export class ContainsValidator implements Validation.IAsyncPropertyValidator { /** * Default constructor. * @param Options - async service that returns array of values. * * */ constructor(public Options:Q.Promise<Array<any>>) { if (Options === undefined) this.Options = Q.when([]); } isAcceptable(s:string):Q.Promise<boolean> { var deferred:Q.Deferred<boolean> = Q.defer<boolean>(); this.Options.then(function (result) { var hasSome = _.some(result, function (item) { return item === s; }); if (hasSome) deferred.resolve(true); deferred.resolve(false); }); return deferred.promise; } isAsync = true; tagName = "contains"; } export interface IRemoteOptions{ url:any; type?:string; data?:any; } /** * Return true if remote service returns true, otherwise false. * * @require underscore * @require Q * @require axios * * @example * ```typescript * url: 'http://test/validateEmail', * ``` */ export class RemoteValidator implements Validation.IAsyncPropertyValidator { private axios:any; /** * Default constructor * @param Options - remote service url + options */ constructor(public Options?:IRemoteOptions) { this.axios = require('axios'); } isAcceptable(s:any):Q.Promise<boolean> { var deferred:Q.Deferred<boolean> = Q.defer<boolean>(); this.axios.post(this.Options.url, { method: this.Options.type || "get", data: _.extend({} || this.Options.data, { "value": s }) } ).then(function (response) { var isAcceptable = response === true || response === "true"; deferred.resolve(isAcceptable); }) .catch(function (response) { deferred.resolve(false); console.log(response); }); return deferred.promise; } isAsync = true; tagName = "remote"; } } export = Validators;
the_stack
export type ApiMethod = | 'onMenuShareTimeline' | 'onMenuShareAppMessage' | 'onMenuShareQQ' | 'onMenuShareWeibo' | 'onMenuShareQZone' | 'startRecord' | 'stopRecord' | 'onVoiceRecordEnd' | 'playVoice' | 'pauseVoice' | 'stopVoice' | 'onVoicePlayEnd' | 'uploadVoice' | 'downloadVoice' | 'chooseImage' | 'previewImage' | 'uploadImage' | 'downloadImage' | 'translateVoice' | 'getNetworkType' | 'openLocation' | 'getLocation' | 'hideOptionMenu' | 'showOptionMenu' | 'hideMenuItems' | 'showMenuItems' | 'hideAllNonBaseMenuItem' | 'showAllNonBaseMenuItem' | 'closeWindow' | 'scanQRCode' | 'chooseWXPay' | 'openProductSpecificView' | 'addCard' | 'chooseCard' | 'openCard'; /** 所有菜单基本类 */ export type MenuBase = | 'menuItem:exposeArticle' | 'menuItem:setFont' | 'menuItem:dayMode' | 'menuItem:nightMode' | 'menuItem:refresh' | 'menuItem:profile' | 'menuItem:addContact'; /** 所有菜单传播类 */ export type MenuShare = | 'menuItem:share:appMessage' | 'menuItem:share:timeline' | 'menuItem:share:qq' | 'menuItem:share:weiboApp' | 'menuItem:favorite' | 'menuItem:share:facebook' | 'menuItem:share:QZone'; /** 所有菜单保护类 */ export type MenuProtected = | 'menuItem:editTag' | 'menuItem:delete' | 'menuItem:copyUrl' | 'menuItem:originPage' | 'menuItem:readMode' | 'menuItem:openWithQQBrowser' | 'menuItem:openWithSafari' | 'menuItem:share:email' | 'menuItem:share:brand'; export interface ConfigOptions { /** 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 */ debug?: boolean; /** 必填,公众号的唯一标识 */ appId: string; /** 必填,生成签名的时间戳 */ timestamp: number; /** 必填,生成签名的随机串 */ nonceStr: string; /** 必填,签名,见附录1 */ signature: string; /** 必填,需要使用的JS接口列表,所有JS接口列表见附录2 */ jsApiList: ApiMethod[]; } /** 通过config接口注入权限验证配置 */ export declare function config(options: ConfigOptions): void; /** 通过ready接口处理成功验证 */ export declare function ready(fn: () => void): void; /** 通过error接口处理失败验证 */ export declare function error(fn: (res: { errMsg: string }) => void): void; export interface CallbackBase { /** 接口调用成功时执行的回调函数 */ success?(...args: any[]): void; /** 接口调用失败的回调函数 */ fail?(...args: any[]): void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?(...args: any[]): void; } export interface ICheckJsApi extends CallbackBase { /** 需要检测的JS接口列表,所有JS接口列表见附录2 */ jsApiList: ApiMethod[]; /** 以键值对的形式返回,可用的api值true,不可用为false */ success(res: { checkResult: { [api: string]: boolean }; errMsg: string }): void; } /** 判断当前客户端版本是否支持指定JS接口 */ export declare function checkJsApi(params: ICheckJsApi): void; export interface onMenuShareBase { /** 用户确认分享后执行的回调函数 */ success?(): void; /** 用户取消分享后执行的回调函数 */ cancel?(): void; } export interface onMenuShareTimelineParam extends onMenuShareBase { /** 分享标题 */ title: string; /** 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 */ link: string; /** 分享图标 */ imgUrl: string; } /** 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口 */ export declare function onMenuShareTimeline(params: onMenuShareTimelineParam): void; export interface onMenuShareAppMessageParam extends onMenuShareTimelineParam { /** 分享描述 */ desc: string; /** 分享类型,music、video或link,不填默认为link */ type?: 'music' | 'video' | 'link'; /** 如果type是music或video,则要提供数据链接,默认为空 */ dataUrl?: string; } /** 获取“分享给朋友”按钮点击状态及自定义分享内容接口 */ export declare function onMenuShareAppMessage(params: onMenuShareAppMessageParam): void; export interface onMenuShareQQParam extends onMenuShareTimelineParam { /** 分享描述 */ desc: string; } /** 获取“分享给朋友”按钮点击状态及自定义分享内容接口 */ export declare function onMenuShareQQ(params: onMenuShareQQParam): void; export interface onMenuShareWeiboParam extends onMenuShareTimelineParam { /** 分享描述 */ desc: string; } /** 获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口 */ export declare function onMenuShareWeibo(params: onMenuShareWeiboParam): void; export interface onMenuShareQZoneParam extends onMenuShareTimelineParam { /** 分享描述 */ desc: string; } /** 获取“分享到QQ空间”按钮点击状态及自定义分享内容接口 */ export declare function onMenuShareQZone(params: onMenuShareQZoneParam): void; export type ImageSizeType = 'original' | 'compressed'; export type ImageSourceType = 'album' | 'camera'; export interface chooseImageParam extends CallbackBase { /** 最多可以选择的图片张数,默认9 */ count?: number; /** 可以指定是原图还是压缩图,默认二者都有 */ sizeType?: ImageSizeType[]; /** 可以指定来源是相册还是相机,默认二者都有 */ sourceType?: ImageSourceType[]; /** 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片 */ success(res: { sourceType: string; localIds: string[]; errMsg: string }): void; } /** 拍照或从手机相册中选图接口 */ export declare function chooseImage(params: chooseImageParam): void; export interface previewImageParam extends CallbackBase { /** 当前显示图片的http链接 */ current: string; /** 需要预览的图片http链接列表 */ urls: string[]; } /** 预览图片接口 */ export declare function previewImage(params: previewImageParam): void; export interface uploadImageParam extends CallbackBase { /** 需要上传的图片的本地ID,由chooseImage接口获得 */ localId: string; /** 默认为1,显示进度提示 */ isShowProgressTips?: number; /** 返回图片的服务器端ID(即 media_id) */ success(res: { serverId: string }): void; } /** * 上传图片接口 * 备注:上传图片有效期3天,可用微信多媒体接口下载图片到自己的服务器,此处获得的 serverId 即 media_id。 */ export declare function uploadImage(params: uploadImageParam): void; export interface downloadImageParam extends CallbackBase { /** 需要下载的图片的服务器端ID,由uploadImage接口获得 */ serverId: string; /** 默认为1,显示进度提示 */ isShowProgressTips?: number; /** 返回图片下载后的本地ID */ success(res: { localId: string }): void; } /** 下载图片接口 */ export declare function downloadImage(params: downloadImageParam): void; export interface getLocalImgDataParam extends CallbackBase { /** 图片的localID */ localId: string; /** localData是图片的base64数据,可以用img标签显示 */ success(res: { localData: string }): void; } /** * 获取本地图片接口 * 备注:此接口仅在 iOS WKWebview 下提供,用于兼容 iOS WKWebview 不支持 localId 直接显示图片的问题。具体可参考《iOS网页开发适配指南》 */ export declare function getLocalImgData(params: getLocalImgDataParam): void; /** 开始录音接口 */ export declare function startRecord(): void; export interface startRecordParam extends CallbackBase { success(res: { localId: string }): void; } /** 停止录音接口 */ export declare function startRecord(params: startRecordParam): void; export interface onVoiceRecordEndParam extends CallbackBase { /** 录音时间超过一分钟没有停止的时候会执行 complete 回调 */ complete(res: { localId: string }): void; } /** * 监听录音自动停止接口 * 注:这里回调的是 `complete` */ export declare function onVoiceRecordEnd(params: onVoiceRecordEndParam): void; export interface playVoiceParam extends CallbackBase { /** 需要播放的音频的本地ID,由stopRecord接口获得 */ localId: string; } /** 播放语音接口 */ export declare function playVoice(params: playVoiceParam): void; export interface pauseVoiceParam extends CallbackBase { /** 需要暂停的音频的本地ID,由stopRecord接口获得 */ localId: string; } /** 暂停播放接口 */ export declare function pauseVoice(params: pauseVoiceParam): void; export interface stopVoiceParam extends CallbackBase { /** 需要停止的音频的本地ID,由stopRecord接口获得 */ localId: string; } /** 停止播放接口 */ export declare function stopVoice(params: stopVoiceParam): void; export interface onVoicePlayEndParam extends CallbackBase { /** 返回音频的本地ID */ success(res: { localId: string }): void; } /** 监听语音播放完毕接口 */ export declare function onVoicePlayEnd(params: onVoicePlayEndParam): void; export interface uploadVoiceParam extends CallbackBase { /** 需要上传的音频的本地ID,由stopRecord接口获得 */ localId: string; /** 默认为1,显示进度提示 */ isShowProgressTips?: number; /** 返回音频的服务器端ID */ success(res: { serverId: string }): void; } /** * 上传语音接口 * 备注:上传语音有效期3天,可用微信多媒体接口下载语音到自己的服务器,此处获得的 serverId 即 media_id,参考文档 .目前多媒体文件下载接口的频率限制为10000次/天,如需要调高频率,请登录微信公众平台,在开发 - 接口权限的列表中,申请提高临时上限。 */ export declare function uploadVoice(params: uploadVoiceParam): void; export interface downloadVoiceParam extends CallbackBase { /** 需要下载的音频的服务器端ID,由uploadVoice接口获得 */ serverId: string; /** 默认为1,显示进度提示 */ isShowProgressTips?: number; /** 返回音频的本地ID */ success(res: { localId: string }): void; } /** 下载语音接口 */ export declare function downloadVoice(params: downloadVoiceParam): void; export interface translateVoiceParam extends CallbackBase { /** 需要识别的音频的本地Id,由录音相关接口获得 */ localId: string; /** 默认为1,显示进度提示 */ isShowProgressTips?: number; /** 语音识别的结果 */ success(res: { translateResult: string }): void; } /** 识别音频并返回识别结果接口 */ export declare function translateVoice(params: translateVoiceParam): void; /** 网络类型 */ export type networkType = '2g' | '3g' | '4g' | 'wifi'; export interface getNetworkTypeParam extends CallbackBase { /** 返回网络类型2g,3g,4g,wifi */ success(res: { networkType: networkType }): void; } /** 获取网络状态接口 */ export declare function getNetworkType(params: getNetworkTypeParam): void; export interface openLocationParam extends CallbackBase { /** 纬度,浮点数,范围为90 ~ -90 */ latitude: number; /** 经度,浮点数,范围为180 ~ -180。 */ longitude: number; /** 位置名 */ name: string; /** 地址详情说明 */ address: string; /** 地图缩放级别,整形值,范围从1~28。默认为最大 */ scale: number; /** 在查看位置界面底部显示的超链接,可点击跳转 */ infoUrl: string; } /** 使用微信内置地图查看位置接口 */ export declare function openLocation(params: openLocationParam): void; export interface getLocationSuccessData { /** 纬度,浮点数,范围为90 ~ -90 */ latitude: number; /** 经度,浮点数,范围为180 ~ -180。 */ longitude: number; /** 速度,以米/每秒计 */ speed: number; /** 位置精度 */ accuracy: number; } export interface getLocationParam extends CallbackBase { /** 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02' */ type: 'wgs84' | 'gcj02'; success(res: getLocationSuccessData): void; } /** 获取地理位置接口 */ export declare function getLocation(params: getLocationParam): void; export interface startSearchBeaconsParam extends CallbackBase { /** 摇周边的业务ticket, 系统自动添加在摇出来的页面链接后面 */ ticket: string; /** 开启查找完成后的回调函数 */ complete(argv: any): void; } /** * 开启查找周边ibeacon设备接口 * 注:这里成功的回调是 `complete` */ export declare function startSearchBeacons(params: startSearchBeaconsParam): void; export interface stopSearchBeaconsParam extends CallbackBase { /** 关闭查找完成后的回调函数 */ complete(argv: any): void; } /** * 关闭查找周边ibeacon设备接口 * 注:这里成功的回调是 `complete` */ export declare function stopSearchBeacons(params: stopSearchBeaconsParam): void; export interface onSearchBeaconsParam extends CallbackBase { /** 回调函数,可以数组形式取得该商家注册的在周边的相关设备列表 */ complete(argv: any): void; } /** * 监听周边ibeacon设备接口 * 注:这里成功的回调是 `complete` */ export declare function onSearchBeacons(params: onSearchBeaconsParam): void; /** 关闭当前网页窗口接口 */ export declare function closeWindow(): void; export interface hideMenuItemsParam extends CallbackBase { /** 要隐藏的菜单项,只能隐藏“传播类”和“保护类”按钮 */ menuList: Array<MenuShare | MenuProtected>; } /** 批量隐藏功能按钮接口 */ export declare function hideMenuItems(params: hideMenuItemsParam): void; export interface showMenuItemsParam extends CallbackBase { /** 要显示的菜单项 */ menuList: Array<MenuShare | MenuProtected>; } /** 批量显示功能按钮接口 */ export declare function showMenuItems(params: showMenuItemsParam): void; /** 隐藏所有非基础按钮接口 */ export declare function hideAllNonBaseMenuItem(): void; /** 显示所有功能按钮接口 */ export declare function showAllNonBaseMenuItem(): void; /** 扫二维码类型 */ export type scanType = 'qrCode' | 'barCode'; export interface scanQRCodeParam extends CallbackBase { /** 默认为0,扫描结果由微信处理,1则直接返回扫描结果 */ needResult: 0 | 1; /** 可以指定扫二维码还是一维码,默认二者都有 */ scanType: scanType[]; /** 当needResult 为 1 时,扫码返回的结果 */ success(res: { resultStr: string }): void; } /** 调起微信扫一扫接口 */ export declare function scanQRCode(params: scanQRCodeParam): void; export interface openProductSpecificViewParam extends CallbackBase { /** 商品id */ productId: string; /** 0.默认值,普通商品详情页1.扫一扫商品详情页2.小店商品详情页 */ viewType: '0' | '1' | '2'; } /** 跳转微信商品页接口 */ export declare function openProductSpecificView(params: openProductSpecificViewParam): void; export interface chooseCardParam extends CallbackBase { /** 门店ID。shopID用于筛选出拉起带有指定location_list(shopID)的卡券列表,非必填。 */ shopId?: string; /** 卡券类型,用于拉起指定卡券类型的卡券列表。当cardType为空时,默认拉起所有卡券的列表,非必填。 */ cardType?: string; /** 卡券ID,用于拉起指定cardId的卡券列表,当cardId为空时,默认拉起所有卡券的列表,非必填。 */ cardId?: string; /** 时间戳。 */ timestamp: number; /** 随机字符串。 */ nonceStr: string; /** 签名方式,目前仅支持SHA1 */ signType: string; /** 签名。 */ cardSign: string; /** 用户选中的卡券列表信息 */ success(res: { cardList: string[] }): void; } /** * 拉取适用卡券列表并获取用户选择信息 * 特别提醒: 拉取列表仅与用户本地卡券有关,拉起列表异常为空的情况通常有三种:签名错误、时间戳无效、筛选机制有误。请开发者依次排查定位原因。 */ export declare function chooseCard(params: chooseCardParam): void; export interface addCardListItem { /** 卡券Id */ cardId: string; /** 卡券扩展字段 */ cardExt: string; } export interface addCardParam extends CallbackBase { /** 需要添加的卡券列表 */ cardList: addCardListItem[]; /** 添加的卡券列表信息 */ success(res: { cardList: string[] }): void; } /** * 批量添加卡券接口 * 建议: 开发者一次添加的卡券不超过5张,否则会遇到超时报错。 */ export declare function addCard(params: addCardParam): void; export interface openCardListItem { /** 卡券Id */ cardId: string; /** 指定的卡券code码,只能被领一次。自定义code模式的卡券必须填写,非自定义code和预存code模式的卡券不必填写。详情见:是否自定义code码 */ code: string; } export interface openCardParam extends CallbackBase { /** 需要添加的卡券列表 */ cardList: openCardListItem[]; } /** 查看微信卡包中的卡券接口 */ export declare function openCard(params: openCardParam): void; export interface chooseWXPayParam extends CallbackBase { /** 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符 */ timestamp: number; /** 支付签名随机串,不长于 32 位 */ nonceStr: string; /** 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=***) */ package: string; /** 签名方式,默认为'SHA1',使用新版支付需传入'MD5' */ signType: 'SHA1' | 'MD5'; /** 支付签名 */ paySign: string; /** 支付成功后的回调函数 */ success(res: any): void; } /** 发起一个微信支付请求 */ export declare function chooseWXPay(params: chooseWXPayParam): void;
the_stack
import Dimensions = Utils.Measurements.Dimensions; import DisplayObject = etch.drawing.DisplayObject; import IDisplayContext = etch.drawing.IDisplayContext; import Point = etch.primitives.Point; import Size = minerva.Size; import {OptionADSR} from './Options/OptionADSR'; import {ButtonArray} from './Options/OptionButtonArray'; import {Device} from '../Device'; import {IApp} from '../IApp'; import {IBlock} from './../Blocks/IBlock'; import {OptionActionButton as ActionButton} from './Options/OptionActionButton'; import {OptionButton as Button} from './Options/OptionButton'; import {OptionHandle} from './Options/OptionHandle'; import {OptionSample as Sample} from './Options/OptionSample'; import {OptionSampleLocal as SampleLocal} from './Options/OptionSampleLocal'; import {OptionSubHandle} from './Options/OptionSubHandle'; import {OptionSwitch as Switch} from './Options/OptionSwitch'; import {Option} from './Options/Option'; import {Parametric} from './Options/OptionParametric'; import {Slider} from './Options/OptionSlider'; import {SwitchArray} from './Options/OptionSwitchArray'; import {WaveImage} from './Options/OptionWaveImage'; import {WaveRegion} from './Options/OptionWaveRegion'; import {WaveSlider} from './Options/OptionWaveSlider'; declare var App: IApp; export class OptionsPanel extends DisplayObject { public Position: Point; public Size: Size; public Margin: number; public Range: number; private _NameWidth: number; private _Name: string; public Scale: number; public Sketch; public Options: Option[]; public SliderColours: string[]; private _Units: number; private _SliderRoll: boolean[]; private _PanelCloseRoll: boolean; public SelectedBlock: IBlock; public InitJson; private _JsonMemory; public Hover: boolean; public Opening: boolean; public Outline: Point[] = []; private _DrawReady: boolean; public Canvas: any; public Animating: boolean; constructor() { super(); } Init(drawTo: IDisplayContext): void { super.Init(drawTo); this._Units = 1.7; this.Position = new Point(0,0); this.Size = new Size(1,1); this.Scale = 0; this.Margin = 0; this.Range = 100; this._Name = ""; this._NameWidth = 0; this.Hover = false; this.Opening = false; this._DrawReady = false; this.Animating = false; this.Sketch = drawTo; this.Options = []; this.SliderColours = []; this._SliderRoll = []; this.InitJson = { "name" : "Init", "parameters" : [ ] }; //this.CreateCanvas(); this.Canvas = App.SubCanvas[0]; this.Populate(this.InitJson,false); } /*CreateCanvas() { this.Canvas = document.createElement("canvas"); document.body.appendChild(this.Canvas); }*/ get Ctx(): CanvasRenderingContext2D{ return this.Canvas.getContext("2d"); } //------------------------------------------------------------------------------------------- // POPULATE //------------------------------------------------------------------------------------------- Populate(json,open) { this._JsonMemory = json; var units = App.Unit; var ctx = this.Ctx; var dataType = units*10; this._PanelCloseRoll = false; // GET NUMBER OF SLIDERS // var n = json.parameters.length; // FIXED or ACCORDION // var panelH; var maxHeight = 240; var getHeight = 0; var heightScale = 1; var optionHeight = []; for (var i=0;i<n;i++) { if (json.parameters[i].type == "slider") { getHeight += 48; optionHeight[i] = 48 * units; } else if (json.parameters[i].type == "sample") { getHeight += 48; optionHeight[i] = 48 * units; } else if (json.parameters[i].type == "samplelocal") { getHeight += 48; optionHeight[i] = 48 * units; } else if (json.parameters[i].type == "actionbutton") { getHeight += 48; optionHeight[i] = 48 * units; } else if (json.parameters[i].type == "waveslider") { getHeight += 48; optionHeight[i] = 48 * units; } else if (json.parameters[i].type == "waveimage") { getHeight += 48; optionHeight[i] = 48 * units; } else if (json.parameters[i].type == "waveregion") { getHeight += 60; optionHeight[i] = 60 * units; } else if (json.parameters[i].type == "buttons") { getHeight += 48; optionHeight[i] = 48 * units; } else if (json.parameters[i].type == "ADSR") { getHeight += 120; optionHeight[i] = 120 * units; } else if (json.parameters[i].type == "parametric") { getHeight += 140; optionHeight[i] = 140 * units; } else if (json.parameters[i].type == "switches") { getHeight += 60; optionHeight[i] = 60 * units; } else { console.log("Option type not recognised"); } } if (getHeight > maxHeight) { heightScale = (1/getHeight) * maxHeight; getHeight = maxHeight; } panelH = (getHeight + 40) * units; // TEXT MARGIN // var panelM = 0; ctx.font = "300 "+dataType+"px Dosis"; if (n==1 && (json.parameters[0].type=="ADSR" || json.parameters[0].type=="parametric")) { // NO MARGIN FOR STANDALONE ENVELOPE panelM = (69*units); } else { for (var i=0;i<n;i++) { if (ctx.measureText(json.parameters[i].name.toUpperCase()).width > panelM) { panelM = ctx.measureText(json.parameters[i].name.toUpperCase()).width; } } panelM += (79*units); } var panelW; if (App.Metrics.Device !== Device.mobile) { panelW = 450*units; } else { panelW = App.Width + (44*units); } var panelR = panelW - (panelM + (25*units)); // NAME // var name = json.name; var nameW = ctx.measureText(name.toUpperCase()).width; // POPULATE PANEL // this.Size.width = panelW; this.Size.height = panelH; this.Margin = panelM; this.Range = panelR; this._Name = json.name; this._NameWidth = nameW; var order = App.ThemeManager.OptionsOrder; this.SliderColours = [App.Palette[order[0]],App.Palette[order[1]],App.Palette[order[2]],App.Palette[order[3]],App.Palette[order[4]]]; // DEFINE OUTLINE FOR HITTEST var topY = - (panelH*0.5); var margin = this.Margin; this.Outline = []; this.Outline.push( new Point(0, 0), // block new Point(44*units, 0), new Point(44*units,topY), // top left new Point(margin - (25*units), topY), // name tab start new Point(margin - (5*units), topY - (20*units)), new Point(margin + (5*units) + this._NameWidth, topY - (20*units)), new Point(margin + (25*units) + this._NameWidth, topY), // name tab end new Point(panelW - (40*units), topY), // close start new Point(panelW - (20*units), topY - (20*units)), new Point(panelW, topY), // top right new Point(panelW, panelH*0.5), // bottom right new Point(44*units, panelH*0.5), // bottom left new Point(44*units, 44*units) ); // POPULATE OPTIONS // var optionTotalY = 0; var optionList = []; for (var i=0;i<n;i++) { var option = json.parameters[i]; // SET HEIGHT // optionHeight[i] = Math.round(optionHeight[i] * heightScale); // scale heights var optionY = Math.round((- (this.Size.height*0.5)) + (20*units) + optionTotalY); // SLIDER // if (option.type == "slider") { var sliderO = this.Margin; if (option.props.centered==true) { sliderO += ((this.Range/100) * 50); } var log = option.props.logarithmic; var sliderX; if (log==true) { sliderX = this.logPosition(0, this.Range, option.props.min, option.props.max, option.props.value); } else { sliderX = this.linPosition(0, this.Range, option.props.min, option.props.max, option.props.value); log = false; } optionList.push(new Slider(new Point(sliderX,optionY),new Size(1,optionHeight[i]),sliderO,option.props.value,option.props.min,option.props.max,option.props.quantised,option.name,option.setting,log)); if (option.props.convertDisplay) { optionList[i].DisplayConversion = option.props.convertDisplay; } } // WAVE SLIDER // else if (option.type == "waveslider") { var sliderO = this.Margin; var waveform = []; if (option.props.wavearray) { waveform = option.props.wavearray; } var log = option.props.logarithmic; var sliderX; if (log==true) { sliderX = this.logPosition(0, this.Range, option.props.min, option.props.max, option.props.value); } else { sliderX = this.linPosition(0, this.Range, option.props.min, option.props.max, option.props.value); log = false; } optionList.push(new WaveSlider(new Point(sliderX,optionY),new Size(1,optionHeight[i]),sliderO,option.props.value,option.props.min,option.props.max,option.props.quantised,option.name,option.setting,log,waveform,option.props.spread)); } // WAVE IMAGE // else if (option.type == "waveimage") { var sliderO = this.Margin; var waveform = []; if (option.props.wavearray) { waveform = option.props.wavearray; } optionList.push(new WaveImage(new Point(0,optionY),new Size(1,optionHeight[i]),sliderO,option.name,waveform)); } // WAVE REGION // else if (option.type == "waveregion") { var handles = []; var sliderO = this.Margin; var waveform = []; if (option.props.wavearray) { waveform = option.props.wavearray; } var emptystring = ""; if (option.props.emptystring) { emptystring = option.props.emptystring; } var startX = this.linPosition(0, this.Range, option.props.min, option.props.max, option.nodes[0].value); var endX = this.linPosition(0, this.Range, option.props.min, option.props.max, option.nodes[1].value); var loopStartX = this.linPosition(0, this.Range, option.props.min, option.props.max, option.nodes[2].value); var loopEndX = this.linPosition(0, this.Range, option.props.min, option.props.max, option.nodes[3].value); var xs = [startX,endX,loopStartX,loopEndX]; for (var j=0; j<4; j++) { handles[j] = new OptionHandle(new Point(xs[j],optionY),option.nodes[j].value,option.props.min, option.props.max,this.Range,0,0,0,0,option.nodes[j].setting,""); } optionList.push(new WaveRegion(new Point(0,optionY),new Size(1,optionHeight[i]),sliderO,option.props.value,option.props.min,option.props.max,option.props.quantised,option.name,option.setting,log,waveform,handles,option.props.mode,emptystring)); } // SAMPLE LOADER // else if (option.type == "sample") { optionList.push(new Sample(new Point(sliderX,optionY),new Size(1,optionHeight[i]),option.name,option.props.track,option.props.user,option.props.permalink,option.setting)); } // LOCAL SAMPLE LOADER // else if (option.type == "samplelocal") { optionList.push(new SampleLocal(new Point(sliderX,optionY),new Size(1,optionHeight[i]),option.name,option.props.track,option.setting)); } // ACTION BUTTON // else if (option.type == "actionbutton") { optionList.push(new ActionButton(new Point(sliderX,optionY),new Size(1,optionHeight[i]),option.name,option.props.text,option.setting)); } // SWITCH ARRAY // else if (option.type == "switches") { var switches = []; var margin = 20*units; var switchWidth = 60*units; switchWidth = (this.Range - (margin * 3)) / 4; //var switchX = [0,(this.Range*0.5) - (switchWidth*0.5),this.Range - switchWidth]; var switchStartX = (this.Range * 0.5) - (((switchWidth * option.switches.length) + (margin * (option.switches.length -1))) * 0.5); var switchX = 0; for (var j=0; j<option.switches.length; j++) { switchX = switchStartX + (j * (switchWidth + margin)); switches[j] = new Switch(new Point(switchX,optionY), option.switches[j].name, option.switches[j].setting, option.switches[j].value,new Size(switchWidth,optionHeight[i]*0.43),option.switches[j].lit, option.switches[j].mode); } optionList.push(new SwitchArray(new Point(sliderX,optionY),new Size(1,optionHeight[i]),switches)); } // BUTTONS // else if (option.type == "buttons") { var buttons = []; var margin = 20*units; var buttonWidth = (this.Range - (margin * (option.buttons.length-1))) / option.buttons.length; buttonWidth = this.Range / 5; var buttonStartX = (this.Range * 0.5) - (buttonWidth * (option.buttons.length * 0.5)); var buttonX = 0; for (var j=0; j<option.buttons.length; j++) { buttonX = buttonStartX + (j * (buttonWidth)); buttons[j] = new Button(new Point(buttonX,optionY), option.buttons[j].name, j==option.props.value, j, new Size(buttonWidth,optionHeight[i])); } optionList.push(new ButtonArray(new Point(0,optionY),new Size(this.Range,optionHeight[i]),option.name,option.setting,buttons,option.props.mode)); } // ENVELOPE // else if (option.type == "ADSR") { var Xrange, handleX, Yrange, handleY; var handles = []; //TODO: tidy up this construction, is a mess. Move some within OptionADSR Xrange = option.nodes[0].max - option.nodes[0].min; handleX = ( (this.Range*0.28) / Xrange ) * (option.nodes[0].value-option.nodes[0].min); Yrange = option.nodes[2].max - option.nodes[2].min; handleY = ( (optionHeight[i]*0.8) / Yrange ) * (option.nodes[2].value-option.nodes[2].min); handles[0] = new OptionHandle(new Point(handleX,handleY),option.nodes[0].value,option.nodes[0].min,option.nodes[0].max,this.Range*0.28,0,0,0,0,option.nodes[0].setting,""); Xrange = option.nodes[1].max - option.nodes[1].min; handleX = ( (this.Range*0.28) / Xrange ) * (option.nodes[1].value-option.nodes[1].min); handles[1] = new OptionHandle(new Point(handleX,handleY),option.nodes[1].value,option.nodes[1].min,option.nodes[1].max,this.Range*0.28,option.nodes[2].value,option.nodes[2].min,option.nodes[2].max,(optionHeight[i]*0.8),option.nodes[1].setting,option.nodes[2].setting); Xrange = option.nodes[3].max - option.nodes[3].min; handleX = ( (this.Range*0.4) / Xrange ) * (option.nodes[3].value-option.nodes[3].min); handles[2] = new OptionHandle(new Point(handleX,handleY),option.nodes[3].value,option.nodes[3].min,option.nodes[3].max,this.Range*0.4,0,0,0,0,option.nodes[3].setting,""); optionList.push(new OptionADSR(new Point(0,optionY),new Size(this.Range,optionHeight[i]),option.name,handles[0],handles[1],handles[2])); } // PARAMETRIC // else if (option.type == "parametric") { // HANDLES // var handles = []; var subHandles = []; var Xmin, Xmax, Xval, Xrange, handleX, Ymin, Ymax, Yval, Yrange, handleY; var Qmin, Qmax, Qval, QRmin, QRmax, QX; for (var j=0; j<4; j++) { Xmin = option.nodes[j].x_min; Xmax = option.nodes[j].x_max; Xval = option.nodes[j].x_value; Ymin = option.nodes[j].y_min; Ymax = option.nodes[j].y_max; Yval = option.nodes[j].y_value; Xrange = Xmax - Xmin; handleX = ( this.Range / Xrange ) * (Xval-Xmin); handleX = this.logPosition(0, this.Range, Xmin, Xmax, Xval); Yrange = Ymax - Ymin; handleY = ( (optionHeight[i]*0.7) / Yrange ) * (Yval-Ymin); handles[j] = new OptionHandle(new Point(handleX,handleY),Xval,Xmin,Xmax,this.Range,Yval,Ymin,Ymax,(optionHeight[i]*0.7),option.nodes[j].x_setting,option.nodes[j].y_setting); handles[j].XLog = true; // SUB // Qmin = option.nodes[j].q_min; Qmax = option.nodes[j].q_max; Qval = option.nodes[j].q_value; QRmin = (this.Range/100) * 2; QRmax = (this.Range/100) * 10; QX = this.logPosition(QRmin, QRmax, Qmin, Qmax, Qval); subHandles[j] = new OptionSubHandle(new Point(QX,handleY),Qval,Qmin,Qmax,QRmin,QRmax,option.nodes[j].q_setting); } // COMPONENT // optionList.push(new Parametric(new Point(0,optionY),new Size(this.Range,optionHeight[i]),option.name,handles[0],handles[1],handles[2],handles[3])); optionList[i].SubHandles = subHandles; optionList[i].PlotGraph(); } // UPDATE TOTAL LIST HEIGHT // optionTotalY += optionHeight[i]; } this.Options = optionList; // update slider array //if (open){ // this.PanelScale(this,1,200); //} this._DrawReady = true; } RefreshOption(i, json) { this.Options[i].Refresh(i, json); this._DrawReady = true; } UpdateOptions() { this.SelectedBlock.UpdateOptionsForm(); var json = this.SelectedBlock.OptionsForm; // GET NUMBER OF OPTIONS // var n = json.parameters.length; for (var i=0;i<n;i++) { var option = json.parameters[i]; // SLIDER // if (option.type == "slider") { this.Options[i].Value = option.props.value; var sliderO = this.Margin; if (option.props.centered==true) { sliderO += ((this.Range/100) * 50); } var log = option.props.logarithmic; if (log==true) { this.Options[i].Position.x = this.logPosition(0, this.Range, option.props.min, option.props.max, option.props.value); } else { this.Options[i].Position.x = this.linPosition(0, this.Range, option.props.min, option.props.max, option.props.value); } } // WAVE SLIDER // else if (option.type == "waveslider") { this.Options[i].Value = option.props.value; this.Options[i].Spread = option.props.spread; this.Options[i].Mode = option.props.mode; } } this._DrawReady = true; } Update() { if (this._JsonMemory.updateeveryframe==true) { //this.UpdateOptions(); } if (this.Animating) { this._DrawReady = true; } } //------------------------------------------------------------------------------------------- // DRAWING //------------------------------------------------------------------------------------------- Draw() { var units = App.Unit; var ctxOuter = App.Canvas.Ctx; var ctx = this.Ctx; // DRAW OFFSCREEN // if (this._DrawReady) { this.DrawToOffscreenCanvas(ctx); this._DrawReady = false; } if (this.Scale > 0) { ctxOuter.globalAlpha = 1; var xOff = 0; if (App.Metrics.Device === Device.mobile) { xOff = 44 * units; } // START A TRANSFORM HERE // ctxOuter.setTransform(this.Scale, 0, 0, this.Scale, this.Position.x + xOff, this.Position.y); ctxOuter.drawImage(this.Canvas,0,-Math.round(App.Metrics.C.y)); ctxOuter.setTransform(1, 0, 0, 1, 0, 0); } } DrawToOffscreenCanvas(ctx) { ctx.clearRect(0,0,App.Width,App.Height); var units = App.Unit; var xOff = 0; if (App.Metrics.Device === Device.mobile) { xOff = -44 * units; } ctx.setTransform(1, 0, 0, 1, xOff, Math.round(App.Metrics.C.y)); var sx = 0; var sy = 0; // PANEL // ctx.font = App.Metrics.TxtMid; ctx.textAlign = "right"; // DRAW PANEL // App.FillColor(ctx,App.Palette[2]); ctx.globalAlpha = 0.16; this.panelDraw(sx, sy + (5 * units)); //App.FillColor(ctx,App.Palette[2]); ctx.globalAlpha = 0.9; this.panelDraw(sx, sy); ctx.globalAlpha = 1; // CLOSE X // App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]); ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(sx + this.Size.width - (24 * units), sy - (this.Size.height * 0.5) + (4 * units)); ctx.lineTo(sx + this.Size.width - (16 * units), sy - (this.Size.height * 0.5) - (4 * units)); ctx.moveTo(sx + this.Size.width - (24 * units), sy - (this.Size.height * 0.5) - (4 * units)); ctx.lineTo(sx + this.Size.width - (16 * units), sy - (this.Size.height * 0.5) + (4 * units)); ctx.stroke(); ctx.lineWidth = 1; // TITLE // App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]); ctx.textAlign = "left"; ctx.fillText(this._Name.toUpperCase(), this.Margin, (-this.Size.height * 0.5)); // DRAW OPTIONS // for (var i = 0; i < this.Options.length; i++) { this.Options[i].Draw(ctx,units,i,this); } ctx.setTransform(1, 0, 0, 1, 0, 0); } // PANEL BLACK BG // panelDraw(x,y) { var units = App.Unit; var ctx = this.Ctx; ctx.beginPath(); ctx.moveTo(x + (44*units), y - (this.Size.height*0.5)); // tl ctx.lineTo(x + this.Margin - (25*units), y - (this.Size.height*0.5)); // name tab start ctx.lineTo(x + this.Margin - (5*units), y - (this.Size.height*0.5) - (20*units)); ctx.lineTo(x + this.Margin + (5*units) + this._NameWidth, y - (this.Size.height*0.5) - (20*units)); ctx.lineTo(x + this.Margin + (25*units) + this._NameWidth, y - (this.Size.height*0.5)); // name tab end ctx.lineTo(x + this.Size.width - (40*units), y - (this.Size.height*0.5)); // close start ctx.lineTo(x + this.Size.width - (20*units), y - (this.Size.height*0.5) - (20*units)); ctx.lineTo(x + this.Size.width, y - (this.Size.height*0.5)); // tr ctx.lineTo(x + this.Size.width, y + (this.Size.height*0.5)); // br ctx.lineTo(x + (44*units), y + (this.Size.height*0.5)); // bl ctx.lineTo(x + (44*units), y + (44*units)); ctx.lineTo(x, y); // block ctx.lineTo(x + (44*units), y); ctx.closePath(); ctx.fill(); } diagonalFill(x,y,w,h,s) { var pr = App.Metrics.PixelRatio; s = s *pr; var ctx = this.Ctx; var lineNo = Math.round((w+h) / (s)); var pos1 = new Point(0,0); var pos2 = new Point(0,0); ctx.beginPath(); for (var j=0;j<lineNo;j++) { pos1.x = (s * 0.5) + (s * j); pos1.y = 0; pos2.x = pos1.x - h; pos2.y = h; if (pos2.x<0) { pos2.y = h + pos2.x; pos2.x = 0; } if (pos1.x>w) { pos1.y = (pos1.x-w); pos1.x = w; } ctx.moveTo(x + pos1.x, y + pos1.y); ctx.lineTo(x + pos2.x, y + pos2.y); } ctx.stroke(); } /*vertFill(x,y,w,h,s) { var ctx = this.Ctx; var lineNo = Math.round(w / s); x = Math.round(x); ctx.beginPath(); for (var j=0;j<lineNo;j++) { ctx.moveTo(x + (s*j), y); ctx.lineTo(x + (s*j), y + h); } ctx.stroke(); }*/ NumberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } //------------------------------------------------------------------------------------------- // TWEEN //------------------------------------------------------------------------------------------- PanelScale(panel,destination,t) { var psTween = new window.TWEEN.Tween({x:panel.Scale}); psTween.to({ x: destination }, t); psTween.onUpdate(function() { panel.Scale = this.x; }); psTween.start(this.LastVisualTick); psTween.easing( window.TWEEN.Easing.Quintic.InOut ); } //------------------------------------------------------------------------------------------- // INTERACTION //------------------------------------------------------------------------------------------- Open(block) { block.UpdateOptionsForm(); if (block.OptionsForm) { var newBlock: boolean = (block!==this.SelectedBlock); if(this.Scale==1 && newBlock) { this.Close(); } this.Opening = true; this.SelectedBlock = block; App.MainScene.MainSceneDragger.Jump(block.Position,new Point(App.Metrics.OptionsPoint.x,App.Metrics.OptionsPoint.y)); var me = this; setTimeout(function() { me.Opening = false; me.Populate(block.OptionsForm,true); me.PanelScale(me,1,200); },400); } } Refresh() { if (this.Scale==1) { this.SelectedBlock.UpdateOptionsForm(); this.Populate(this.SelectedBlock.OptionsForm, false); } } Resize() { if (!App.Width) return; if (App.Metrics.Device !== Device.mobile) { this.Position.x = Math.round(App.Width*App.Metrics.OptionsPoint.x); this.Position.y = Math.round(App.Height*App.Metrics.OptionsPoint.y); } else { this.Position.x = -44 * App.Unit; this.Position.y = Math.round(App.Height*0.65); } } Close() { this.PanelScale(this,0,200); if (App.Stage) { var tut = App.MainScene.Tutorial; if (tut.Open) { tut.CheckTask(); } } } //TODO: move into interaction functions within option components, as with drawing MouseDown(mx,my) { this.RolloverCheck(mx,my); var tut = App.MainScene.Tutorial; if (tut.Open) { tut.OptionsInteract = true; } for (var i=0;i<this.Options.length;i++) { if (this._SliderRoll[i]) { this.Options[i].Selected = true; this.SliderSet(i,mx); } if (this.Options[i].Type=="ADSR") { var xStart = [0, this.Options[i].Handles[0].Position.x,this.Range*0.6]; for (var j=0;j<this.Options[i].Handles.length;j++) { if (this.Options[i].HandleRoll[j]) { this.Options[i].Handles[j].Selected = true; this.HandleSet(i, j, xStart[j],this.Options[i].Size.height*0.9,mx, my); } } } if (this.Options[i].Type=="waveregion") { for (var j=this.Options[i].Handles.length-1;j>-1;j--) { if (this.Options[i].HandleRoll[j]) { var handles = this.Options[i].Handles; handles[j].Selected = true; this.HandleSet(i, j, 0,this.Options[i].Size.height,mx, my); if (handles[3].Position.x < (handles[2].Position.x+1)) { // loopend before loopstart this.HandleSet(i, 3, 0, this.Options[i].Size.height, (handles[2].Position.x+1) + this.Position.x + this.Margin, my); } if (handles[3].Position.x < (handles[0].Position.x)) { // loopend before start this.HandleSet(i, 3, 0, this.Options[i].Size.height, (handles[0].Position.x) + this.Position.x + this.Margin, my); } if (handles[1].Position.x < (handles[0].Position.x+1)) { // end before start this.HandleSet(i, 1, 0, this.Options[i].Size.height, (handles[0].Position.x+1) + this.Position.x + this.Margin, my); } return; } } } if (this.Options[i].Type=="switches") { for (var j=0;j<this.Options[i].Switches.length;j++) { if (this.Options[i].HandleRoll[j]) { this.SwitchValue(this.Options[i].Switches[j],"Selected","Setting"); return; } } } if (this.Options[i].Type=="buttons") { for (var j=0;j<this.Options[i].Buttons.length;j++) { if (this.Options[i].HandleRoll[j]) { for (var h=0;h<this.Options[i].Buttons.length;h++) { this.Options[i].Buttons[h].Selected = false; } this.Options[i].Buttons[j].Selected = true; this.PushValue(this.Options[i],j,"Setting"); return; } } } if (this.Options[i].Type=="parametric") { for (var j=0;j<this.Options[i].Handles.length;j++) { if (this.Options[i].HandleRoll[j]) { this.Options[i].Handles[j].Selected = true; this.HandleSet(i, j, 0,this.Options[i].Size.height*0.8,mx, my); this.Options[i].PlotGraph(); break; } } for (var j=0;j<this.Options[i].SubHandles.length;j++) { if (this.Options[i].SubHandleRoll[j]) { this.Options[i].SubHandles[j].Selected = true; this.SubHandleSet(this.Options[i].SubHandles[j],this.Options[i].Handles[j].Position.x, mx); this.Options[i].PlotGraph(); break; } } } if (this.Options[i].Type=="sample") { if (this.Options[i].HandleRoll[0]) { this.Sketch.SoundcloudPanel.OpenPanel(); return; } if (this.Options[i].HandleRoll[1] && this.Options[i].Permalink!=="") { window.open("" + this.Options[i].Permalink, "_blank"); return; } } if (this.Options[i].Type=="samplelocal") { if (this.Options[i].HandleRoll[0]) { var val = 0; // console.log("" + this.Options[i].Setting +" | "+ val); // SET VALUE IN BLOCK // this.SelectedBlock.SetParam(this.Options[i].Setting, val); return; } } if (this.Options[i].Type=="actionbutton") { if (this.Options[i].HandleRoll[0]) { var val = 0; // console.log("" + this.Options[i].Setting +" | "+ val); // SET VALUE IN BLOCK // this.SelectedBlock.SetParam(this.Options[i].Setting, val); return; } } } if (this._PanelCloseRoll) { this.Close(); } } MouseUp() { for (var i=0;i<this.Options.length;i++) { this.Options[i].Selected = false; if (this.Options[i].Type=="ADSR" || this.Options[i].Type=="waveregion") { for (var j=0;j<this.Options[i].Handles.length;j++) { this.Options[i].Handles[j].Selected = false; } } if (this.Options[i].Type=="parametric") { for (var j=0;j<this.Options[i].Handles.length;j++) { this.Options[i].Handles[j].Selected = false; this.Options[i].SubHandles[j].Selected = false; } } } //if (this.Hover) { this._DrawReady = true; //} } MouseMove(mx,my) { this.RolloverCheck(mx,my); for (var i=0;i<this.Options.length;i++) { if (this.Options[i].Type=="slider" || this.Options[i].Type == "waveslider") { if (this.Options[i].Selected) { this.SliderSet(i, mx); } } if (this.Options[i].Type=="ADSR") { var xStart = [0, this.Options[i].Handles[0].Position.x,this.Range*0.6]; for (var j=0;j<this.Options[i].Handles.length;j++) { if (this.Options[i].Handles[j].Selected) { this.HandleSet(i, j, xStart[j], this.Options[i].Size.height*0.9, mx, my); } } } if (this.Options[i].Type=="waveregion") { for (var j=0;j<this.Options[i].Handles.length;j++) { var handles = this.Options[i].Handles; if (handles[j].Selected) { this.HandleSet(i, j, 0, this.Options[i].Size.height, mx, my); } } if (handles[3].Position.x < (handles[2].Position.x+1)) { // loopend before loopstart this.HandleSet(i, 3, 0, this.Options[i].Size.height, (handles[2].Position.x+1) + this.Position.x + this.Margin, my); } if (handles[3].Position.x < (handles[0].Position.x)) { // loopend before start this.HandleSet(i, 3, 0, this.Options[i].Size.height, (handles[0].Position.x) + this.Position.x + this.Margin, my); } if (handles[1].Position.x < (handles[0].Position.x+1)) { // end before start this.HandleSet(i, 1, 0, this.Options[i].Size.height, (handles[0].Position.x+1) + this.Position.x + this.Margin, my); } } if (this.Options[i].Type=="parametric") { for (var j=0;j<this.Options[i].Handles.length;j++) { if (this.Options[i].Handles[j].Selected) { this.HandleSet(i, j, 0, this.Options[i].Size.height*0.8, mx, my); this.Options[i].PlotGraph(); } } for (var j=0;j<this.Options[i].SubHandles.length;j++) { if (this.Options[i].SubHandles[j].Selected) { this.SubHandleSet(this.Options[i].SubHandles[j],this.Options[i].Handles[j].Position.x, mx); this.Options[i].PlotGraph(); } } } } } RolloverCheck(mx,my) { var units = App.Unit; //this.Hover = Dimensions.hitRect(this.Position.x,this.Position.y - (this.Size.height*0.5), this.Size.width, this.Size.height,mx,my); this.Hover = this.OutlineTest(new Point(mx,my)); for (var i=0;i<this.Options.length;i++) { if (this.Options[i].Type == "slider" || this.Options[i].Type == "waveslider") { this._SliderRoll[i] = Dimensions.hitRect(this.Position.x + this.Margin - (10*units),this.Position.y + this.Options[i].Position.y,this.Range + (20*units),this.Options[i].Size.height,mx,my); } else if (this.Options[i].Type == "ADSR") { this.Options[i].HandleRoll[0] = Dimensions.hitRect(this.Position.x + this.Margin + this.Options[i].Handles[0].Position.x - (10 * units), this.Position.y + this.Options[i].Position.y + (this.Options[i].Size.height * 0.1) - (10 * units), (20 * units), (20 * units), mx, my); this.Options[i].HandleRoll[1] = Dimensions.hitRect(this.Position.x + this.Margin + this.Options[i].Handles[0].Position.x + this.Options[i].Handles[1].Position.x - (10 * units), this.Position.y + this.Options[i].Position.y + (this.Options[i].Size.height * 0.9) - this.Options[i].Handles[1].Position.y - (10 * units), (20 * units), (20 * units), mx, my); this.Options[i].HandleRoll[2] = Dimensions.hitRect(this.Position.x + this.Margin + (this.Range * 0.6) + this.Options[i].Handles[2].Position.x - (10 * units), this.Position.y + this.Options[i].Position.y + (this.Options[i].Size.height * 0.9) - (10 * units), (20 * units), (20 * units), mx, my); } else if (this.Options[i].Type == "waveregion") { for (var j=0; j<4; j++) { if ( (!this.Options[i].Mode && j>1) || (this.Options[i].Mode && j==1)) { this.Options[i].HandleRoll[j] = false; } else { this.Options[i].HandleRoll[j] = Dimensions.hitRect(this.Position.x + this.Margin + this.Options[i].Handles[j].Position.x - (10 * units), this.Position.y + this.Options[i].Position.y, (20 * units), this.Options[i].Size.height, mx, my); } } } else if (this.Options[i].Type == "switches") { for (var j=0; j<this.Options[i].Switches.length; j++) { this.Options[i].HandleRoll[j] = Dimensions.hitRect(this.Position.x + this.Margin + this.Options[i].Switches[j].Position.x, this.Position.y + this.Options[i].Position.y, this.Options[i].Switches[j].Size.width, this.Options[i].Size.height * 0.7, mx, my); } } else if (this.Options[i].Type == "buttons") { for (var j=0; j<this.Options[i].Buttons.length; j++) { this.Options[i].HandleRoll[j] = Dimensions.hitRect(this.Position.x + this.Margin + this.Options[i].Buttons[j].Position.x, this.Position.y + this.Options[i].Position.y, this.Options[i].Buttons[j].Size.width, this.Options[i].Size.height, mx, my); } } else if (this.Options[i].Type == "parametric") { for (var j=0; j<this.Options[i].Handles.length; j++) { this.Options[i].HandleRoll[j] = Dimensions.hitRect(this.Position.x + this.Margin + this.Options[i].Handles[j].Position.x - (10 * units), this.Position.y + this.Options[i].Position.y + (this.Options[i].Size.height * 0.8) - this.Options[i].Handles[j].Position.y - (10 * units), (20 * units), (20 * units), mx, my); if (j!==0 && j!==this.Options[i].Handles.length-1) { this.Options[i].SubHandleRoll[j] = Dimensions.hitRect(this.Position.x + this.Margin + this.Options[i].Handles[j].Position.x - this.Options[i].SubHandles[j].Position.x - (10 * units), this.Position.y + this.Options[i].Position.y + (this.Options[i].Size.height * 0.9) - (10 * units), (this.Options[i].SubHandles[j].Position.x * 2) + (20 * units), (20 * units), mx, my); } } } else if (this.Options[i].Type == "sample") { this.Options[i].HandleRoll[0] = Dimensions.hitRect(this.Position.x + this.Margin + (this.Range * 0.65), this.Position.y + this.Options[i].Position.y, (this.Range * 0.35), this.Options[i].Size.height, mx, my); this.Options[i].HandleRoll[1] = Dimensions.hitRect(this.Position.x + this.Margin + (this.Range * 0.5), this.Position.y + this.Options[i].Position.y, (this.Range * 0.15), this.Options[i].Size.height, mx, my); } else if (this.Options[i].Type == "samplelocal") { this.Options[i].HandleRoll[0] = Dimensions.hitRect(this.Position.x + this.Margin + (this.Range * 0.65), this.Position.y + this.Options[i].Position.y, (this.Range * 0.35), this.Options[i].Size.height, mx, my); } else if (this.Options[i].Type == "actionbutton") { this.Options[i].HandleRoll[0] = Dimensions.hitRect(this.Position.x + this.Margin + (this.Range * 0.25), this.Position.y + this.Options[i].Position.y, (this.Range * 0.5), this.Options[i].Size.height, mx, my); } } if (this.Scale==1) { this._PanelCloseRoll = Dimensions.hitRect(this.Position.x + this.Size.width - (30*units),this.Position.y - (this.Size.height*0.5) - (10*units),20*units,20*units,mx,my); } } //------------------------------------------------------------------------------------------- // MATHS //------------------------------------------------------------------------------------------- OutlineTest(point: Point): boolean { this.Ctx.beginPath(); this.Ctx.moveTo(this.Position.x + this.Outline[0].x, this.Position.y + this.Outline[0].y); for (var i = 1; i < this.Outline.length; i++) { this.Ctx.lineTo(this.Position.x + this.Outline[i].x, this.Position.y + this.Outline[i].y); } this.Ctx.closePath(); return this.Ctx.isPointInPath(point.x, point.y); } // DRAGGING A HANDLE // HandleSet(n,h,xStart,yRange,mx,my) { var mPosX = mx - (this.Position.x + this.Margin + xStart); var mPosY = my - (this.Position.y + this.Options[n].Position.y + (yRange)); this.Options[n].Handles[h].Position.x = mPosX; this.Options[n].Handles[h].Position.y = -mPosY; this.Options[n].Handles[h].Position.x = this.ValueInRange(this.Options[n].Handles[h].Position.x,0,this.Options[n].Handles[h].XRange); this.Options[n].Handles[h].Position.y = this.ValueInRange(this.Options[n].Handles[h].Position.y,0,this.Options[n].Handles[h].YRange); var log = false; if (this.Options[n].Handles[h].Log==true) { log = true; } var xlog = false; if (this.Options[n].Handles[h].XLog==true) { xlog = true; } var ylog = false; if (this.Options[n].Handles[h].YLog==true) { ylog = true; } this.UpdateValue(this.Options[n].Handles[h],"XValue","XMin","XMax",0, this.Options[n].Handles[h].XRange,"XSetting","x",xlog); if (this.Options[n].Handles[h].YSetting!=="") { this.UpdateValue(this.Options[n].Handles[h],"YValue","YMin","YMax",0, this.Options[n].Handles[h].YRange,"YSetting","y",ylog); } } // DRAGGING A SUB HANDLE // SubHandleSet(handle,origin,mx) { var mPosX = mx - (this.Position.x + this.Margin + origin); if (mPosX<0) { mPosX = -mPosX; } handle.Position.x = mPosX; handle.Position.x = this.ValueInRange(handle.Position.x,handle.RangeMin,handle.RangeMax); this.UpdateValue(handle,"Value","Min","Max",handle.RangeMin,handle.RangeMax,"Setting","x",true); } // DRAGGING A SLIDER // SliderSet(n,mx) { var mPos = mx - (this.Position.x + this.Margin); this.Options[n].Position.x = mPos; this.Options[n].Position.x = this.ValueInRange(this.Options[n].Position.x,0,this.Range); var log = false; if (this.Options[n].Log==true) { log = true; } this.UpdateValue(this.Options[n],"Value","Min","Max",0, this.Range,"Setting","x",log); } // UPDATE THE VALUE IN THE BLOCK // UpdateValue(object,value,min,max,rangemin,rangemax,setting,axis,log) { this._DrawReady = true; // CALCULATE VALUE // if (log==true) { object[""+value] = this.logValue(rangemin,rangemax,object[""+min],object[""+max],object.Position[""+axis]); } else { object[""+value] = this.linValue(rangemin,rangemax,object[""+min],object[""+max],object.Position[""+axis]); } // QUANTIZE // if (object.Quantised) { object[""+value] = Math.round(object[""+value]); if (log==true) { object.Position["" + axis] = this.logPosition(rangemin, rangemax, object["" + min], object["" + max], object["" + value]); } else { object.Position["" + axis] = this.linPosition(rangemin, rangemax, object["" + min], object["" + max], object["" + value]); } } // console.log("" + object[""+setting] +" | "+ object[""+value]); // SET VALUE IN BLOCK // //Utils.Events.Debounce(function() { //console.log("debounce"); this.SelectedBlock.SetParam(object[""+setting], object[""+value]); //}, 100); // UPDATE VALUES IN OTHER OPTIONS // if (this._Name.toUpperCase()=="GRANULAR" && ("" + object[""+setting])=="spread") { this.UpdateOptions(); } } SwitchValue(object,value,setting) { this._DrawReady = true; // console.log("from " + object[""+setting] +" | "+ object[""+value]); object[""+value] = ! object[""+value]; var val = 0; if (object[""+value]) { val = 1; } // console.log("to " + object[""+setting] +" | "+ val); // SET VALUE IN BLOCK // this.SelectedBlock.SetParam(object[""+setting], val); } PushValue(object,value,setting) { this._DrawReady = true; // console.log("" + object[""+setting] +" | "+ value); // SET VALUE IN BLOCK // this.SelectedBlock.SetParam(object[""+setting], value); } ValueInRange(value,floor,ceiling) { if (value < floor) { value = floor; } if (value> ceiling) { value = ceiling; } return value; } logValue(minpos,maxpos,minval,maxval,position) { var minlval = Math.log(minval); var maxlval = Math.log(maxval); var scale = (maxlval - minlval) / (maxpos - minpos); //console.log("" +minval + " | " +maxval + " | " +position); return Math.exp((position - minpos) * scale + minlval); } logPosition(minpos,maxpos,minval,maxval,value) { var minlval = Math.log(minval); var maxlval = Math.log(maxval); var scale = (maxlval - minlval) / (maxpos - minpos); //console.log("" +minval + " | " +maxval + " | " +value); return minpos + (Math.log(value) - minlval) / scale; } linValue(minpos,maxpos,minval,maxval,position) { var scale = (maxval - minval) / (maxpos - minpos); //console.log("" +minval + " | " +maxval + " | " +position); return (position - minpos) * scale + minval; } linPosition(minpos,maxpos,minval,maxval,value) { var scale = (maxval - minval) / (maxpos - minpos); //console.log("" +minval + " | " +maxval + " | " +value); return minpos + (value - minval) / scale; } }
the_stack
export default { name: 'github-dark', base: 'vs-dark', inherit: true, rules: [ { token: 'comment', foreground: '#8B949E' }, { token: 'punctuation.definition.comment', foreground: '#8B949E' }, { token: 'string.comment', foreground: '#8B949E' }, { token: 'constant', foreground: '#79C0FF' }, { token: 'entity.name.constant', foreground: '#79C0FF' }, { token: 'variable.other.constant', foreground: '#79C0FF' }, { token: 'variable.language', foreground: '#79C0FF' }, { token: 'entity', foreground: '#79C0FF' }, { token: 'entity.name', foreground: '#FFA657' }, { token: 'meta.export.default', foreground: '#FFA657' }, { token: 'meta.definition.variable', foreground: '#FFA657' }, { token: 'variable.parameter.function', foreground: '#C9D1D9' }, { token: 'meta.jsx.children', foreground: '#C9D1D9' }, { token: 'meta.block', foreground: '#C9D1D9' }, { token: 'meta.tag.attributes', foreground: '#C9D1D9' }, { token: 'entity.name.constant', foreground: '#C9D1D9' }, { token: 'meta.object.member', foreground: '#C9D1D9' }, { token: 'meta.embedded.expression', foreground: '#C9D1D9' }, { token: 'entity.name.function', foreground: '#D2A8FF' }, { token: 'entity.name.tag', foreground: '#7EE787' }, { token: 'support.class.component', foreground: '#7EE787' }, { token: 'keyword', foreground: '#FF7B72' }, { token: 'storage', foreground: '#FF7B72' }, { token: 'storage.type', foreground: '#FF7B72' }, { token: 'storage.modifier.package', foreground: '#C9D1D9' }, { token: 'storage.modifier.import', foreground: '#C9D1D9' }, { token: 'storage.type.java', foreground: '#C9D1D9' }, { token: 'string', foreground: '#A5D6FF' }, { token: 'punctuation.definition.string', foreground: '#A5D6FF' }, { token: 'string punctuation.section.embedded source', foreground: '#A5D6FF' }, { token: 'support', foreground: '#79C0FF' }, { token: 'meta.property-name', foreground: '#79C0FF' }, { token: 'variable', foreground: '#FFA657' }, { token: 'variable.other', foreground: '#C9D1D9' }, { token: 'invalid.broken', foreground: '#FFA198', fontStyle: 'italic' }, { token: 'invalid.deprecated', foreground: '#FFA198', fontStyle: 'italic' }, { token: 'invalid.illegal', foreground: '#FFA198', fontStyle: 'italic' }, { token: 'invalid.unimplemented', foreground: '#FFA198', fontStyle: 'italic' }, { token: 'carriage-return', foreground: '#0D1117', background: '#FF7B72', fontStyle: 'italic underline' }, { token: 'message.error', foreground: '#FFA198' }, { token: 'string source', foreground: '#C9D1D9' }, { token: 'string variable', foreground: '#79C0FF' }, { token: 'source.regexp', foreground: '#A5D6FF' }, { token: 'string.regexp', foreground: '#A5D6FF' }, { token: 'string.regexp.character-class', foreground: '#A5D6FF' }, { token: 'string.regexp constant.character.escape', foreground: '#A5D6FF' }, { token: 'string.regexp source.ruby.embedded', foreground: '#A5D6FF' }, { token: 'string.regexp string.regexp.arbitrary-repitition', foreground: '#A5D6FF' }, { token: 'string.regexp constant.character.escape', foreground: '#7EE787', fontStyle: 'bold' }, { token: 'support.constant', foreground: '#79C0FF' }, { token: 'support.variable', foreground: '#79C0FF' }, { token: 'meta.module-reference', foreground: '#79C0FF' }, { token: 'punctuation.definition.list.begin.markdown', foreground: '#FFA657' }, { token: 'markup.heading', foreground: '#79C0FF', fontStyle: 'bold' }, { token: 'markup.heading entity.name', foreground: '#79C0FF', fontStyle: 'bold' }, { token: 'markup.quote', foreground: '#7EE787' }, { token: 'markup.italic', foreground: '#C9D1D9', fontStyle: 'italic' }, { token: 'markup.bold', foreground: '#C9D1D9', fontStyle: 'bold' }, { token: 'markup.raw', foreground: '#79C0FF' }, { token: 'markup.deleted', foreground: '#FFA198', background: '#490202' }, { token: 'meta.diff.header.from-file', foreground: '#FFA198', background: '#490202' }, { token: 'punctuation.definition.deleted', foreground: '#FFA198', background: '#490202' }, { token: 'markup.inserted', foreground: '#7EE787', background: '#04260F' }, { token: 'meta.diff.header.to-file', foreground: '#7EE787', background: '#04260F' }, { token: 'punctuation.definition.inserted', foreground: '#7EE787', background: '#04260F' }, { token: 'markup.changed', foreground: '#FFA657', background: '#5A1E02' }, { token: 'punctuation.definition.changed', foreground: '#FFA657', background: '#5A1E02' }, { token: 'markup.ignored', foreground: '#161B22', background: '#79C0FF' }, { token: 'markup.untracked', foreground: '#161B22', background: '#79C0FF' }, { token: 'meta.diff.range', foreground: '#D2A8FF', fontStyle: 'bold' }, { token: 'meta.diff.header', foreground: '#79C0FF' }, { token: 'meta.separator', foreground: '#79C0FF', fontStyle: 'bold' }, { token: 'meta.output', foreground: '#79C0FF' }, { token: 'brackethighlighter.tag', foreground: '#8B949E' }, { token: 'brackethighlighter.curly', foreground: '#8B949E' }, { token: 'brackethighlighter.round', foreground: '#8B949E' }, { token: 'brackethighlighter.square', foreground: '#8B949E' }, { token: 'brackethighlighter.angle', foreground: '#8B949E' }, { token: 'brackethighlighter.quote', foreground: '#8B949E' }, { token: 'brackethighlighter.unmatched', foreground: '#FFA198' }, { token: 'constant.other.reference.link', foreground: '#A5D6FF', fontStyle: 'underline' }, { token: 'string.other.link', foreground: '#A5D6FF', fontStyle: 'underline' }, { token: 'token.info-token', foreground: '#6796E6' }, { token: 'token.warn-token', foreground: '#CD9731' }, { token: 'token.error-token', foreground: '#F44747' }, { token: 'token.debug-token', foreground: '#B267E6' }, // Github dark dimmed // { // token: 'comment', // foreground: '#6A737D', // }, // { // token: 'punctuation.definition.comment', // foreground: '#6A737D', // }, // { // token: 'string.comment', // foreground: '#6A737D', // }, // { // token: 'constant', // foreground: '#79B8FF', // }, // { // token: 'entity.name.constant', // foreground: '#79B8FF', // }, // { // token: 'variable.other.constant', // foreground: '#79B8FF', // }, // { // token: 'variable.language', // foreground: '#79B8FF', // }, // { // token: 'entity', // foreground: '#B392F0', // }, // { // token: 'entity.name', // foreground: '#B392F0', // }, // { // token: 'variable.parameter.function', // foreground: '#E1E4E8', // }, // { // token: 'entity.name.tag', // foreground: '#85E89D', // }, // { // token: 'keyword', // foreground: '#F97583', // }, // { // token: 'storage', // foreground: '#F97583', // }, // { // token: 'storage.type', // foreground: '#F97583', // }, // { // token: 'storage.modifier.package', // foreground: '#E1E4E8', // }, // { // token: 'storage.modifier.import', // foreground: '#E1E4E8', // }, // { // token: 'storage.type.java', // foreground: '#E1E4E8', // }, // { // token: 'string', // foreground: '#9ECBFF', // }, // { // token: 'punctuation.definition.string', // foreground: '#9ECBFF', // }, // { // token: 'string punctuation.section.embedded source', // foreground: '#9ECBFF', // }, // { // token: 'support', // foreground: '#79B8FF', // }, // { // token: 'meta.property-name', // foreground: '#79B8FF', // }, // { // token: 'variable', // foreground: '#FFAB70', // }, // { // token: 'variable.other', // foreground: '#E1E4E8', // }, // { // token: 'invalid.broken', // foreground: '#FDAEB7', // fontStyle: 'italic' // }, // { // token: 'invalid.deprecated', // foreground: '#FDAEB7', // fontStyle: 'italic' // }, // { // token: 'invalid.illegal', // foreground: '#FDAEB7', // fontStyle: 'italic' // }, // { // token: 'invalid.unimplemented', // foreground: '#FDAEB7', // fontStyle: 'italic' // }, // { // token: 'carriage-return', // foreground: '#24292E', // background: '#F97583', // fontStyle: 'italic underline' // }, // { // token: 'message.error', // foreground: '#FDAEB7', // }, // { // token: 'string source', // foreground: '#E1E4E8', // }, // { // token: 'string variable', // foreground: '#79B8FF', // }, // { // token: 'source.regexp', // foreground: '#DBEDFF', // }, // { // token: 'string.regexp', // foreground: '#DBEDFF', // }, // { // token: 'string.regexp.character-class', // foreground: '#DBEDFF', // }, // { // token: 'string.regexp constant.character.escape', // foreground: '#DBEDFF', // }, // { // token: 'string.regexp source.ruby.embedded', // foreground: '#DBEDFF', // }, // { // token: 'string.regexp string.regexp.arbitrary-repitition', // foreground: '#DBEDFF', // }, // { // token: 'string.regexp constant.character.escape', // foreground: '#85E89D', // fontStyle: 'bold' // }, // { // token: 'support.constant', // foreground: '#79B8FF', // }, // { // token: 'support.variable', // foreground: '#79B8FF', // }, // { // token: 'meta.module-reference', // foreground: '#79B8FF', // }, // { // token: 'punctuation.definition.list.begin.markdown', // foreground: '#FFAB70', // }, // { // token: 'markup.heading', // foreground: '#79B8FF', // fontStyle: 'bold' // }, // { // token: 'markup.heading entity.name', // foreground: '#79B8FF', // fontStyle: 'bold' // }, // { // token: 'markup.quote', // foreground: '#85E89D', // }, // { // token: 'markup.italic', // foreground: '#E1E4E8', // fontStyle: 'italic' // }, // { // token: 'markup.bold', // foreground: '#E1E4E8', // fontStyle: 'bold' // }, // { // token: 'markup.raw', // foreground: '#79B8FF', // }, // { // token: 'markup.deleted', // foreground: '#FDAEB7', // background: '#86181D', // }, // { // token: 'meta.diff.header.from-file', // foreground: '#FDAEB7', // background: '#86181D', // }, // { // token: 'punctuation.definition.deleted', // foreground: '#FDAEB7', // background: '#86181D', // }, // { // token: 'markup.inserted', // foreground: '#85E89D', // background: '#144620', // }, // { // token: 'meta.diff.header.to-file', // foreground: '#85E89D', // background: '#144620', // }, // { // token: 'punctuation.definition.inserted', // foreground: '#85E89D', // background: '#144620', // }, // { // token: 'markup.changed', // foreground: '#FFAB70', // background: '#C24E00', // }, // { // token: 'punctuation.definition.changed', // foreground: '#FFAB70', // background: '#C24E00', // }, // { // token: 'markup.ignored', // foreground: '#2F363D', // background: '#79B8FF', // }, // { // token: 'markup.untracked', // foreground: '#2F363D', // background: '#79B8FF', // }, // { // token: 'meta.diff.range', // foreground: '#B392F0', // fontStyle: 'bold' // }, // { // token: 'meta.diff.header', // foreground: '#79B8FF', // }, // { // token: 'meta.separator', // foreground: '#79B8FF', // fontStyle: 'bold' // }, // { // token: 'meta.output', // foreground: '#79B8FF', // }, // { // token: 'brackethighlighter.tag', // foreground: '#D1D5DA', // }, // { // token: 'brackethighlighter.curly', // foreground: '#D1D5DA', // }, // { // token: 'brackethighlighter.round', // foreground: '#D1D5DA', // }, // { // token: 'brackethighlighter.square', // foreground: '#D1D5DA', // }, // { // token: 'brackethighlighter.angle', // foreground: '#D1D5DA', // }, // { // token: 'brackethighlighter.quote', // foreground: '#D1D5DA', // }, // { // token: 'brackethighlighter.unmatched', // foreground: '#FDAEB7', // }, // { // token: 'constant.other.reference.link', // foreground: '#DBEDFF', // fontStyle: 'underline' // }, // { // token: 'string.other.link', // foreground: '#DBEDFF', // fontStyle: 'underline' // }, // { // token: 'token.info-token', // foreground: '#6796E6', // }, // { // token: 'token.warn-token', // foreground: '#CD9731', // }, // { // token: 'token.error-token', // foreground: '#F44747', // }, // { // token: 'token.debug-token', // foreground: '#B267E6', // } ], colors: { "activityBar.activeBorder": "#f78166", "activityBar.background": "#0d1117", "activityBar.border": "#30363d", "activityBar.foreground": "#c9d1d9", "activityBar.inactiveForeground": "#8b949e", "activityBarBadge.background": "#1f6feb", "activityBarBadge.foreground": "#f0f6fc", "badge.background": "#1f6feb", "badge.foreground": "#f0f6fc", "breadcrumb.activeSelectionForeground": "#8b949e", "breadcrumb.focusForeground": "#c9d1d9", "breadcrumb.foreground": "#8b949e", "breadcrumbPicker.background": "#161b22", "button.background": "#238636", "button.foreground": "#ffffff", "button.hoverBackground": "#2ea043", "button.secondaryBackground": "#282e33", "button.secondaryForeground": "#c9d1d9", "button.secondaryHoverBackground": "#30363d", "checkbox.background": "#161b22", "checkbox.border": "#30363d", "debugToolBar.background": "#161b22", "descriptionForeground": "#8b949e", "diffEditor.insertedTextBackground": "#2ea04326", "diffEditor.removedTextBackground": "#f8514926", "dropdown.background": "#161b22", "dropdown.border": "#30363d", "dropdown.foreground": "#c9d1d9", "dropdown.listBackground": "#161b22", "editor.background": "#0d1117", "editor.findMatchBackground": "#ffd33d44", "editor.findMatchHighlightBackground": "#ffd33d22", "editor.focusedStackFrameHighlightBackground": "#3fb95025", "editor.foldBackground": "#6e76811a", "editor.foreground": "#c9d1d9", "editor.inactiveSelectionBackground": "#3392ff22", "editor.lineHighlightBackground": "#6e76811a", "editor.linkedEditingBackground": "#3392ff22", "editor.selectionBackground": "#3392ff44", "editor.selectionHighlightBackground": "#17e5e633", "editor.selectionHighlightBorder": "#17e5e600", "editor.stackFrameHighlightBackground": "#d2992225", "editor.wordHighlightBackground": "#17e5e600", "editor.wordHighlightBorder": "#17e5e699", "editor.wordHighlightStrongBackground": "#17e5e600", "editor.wordHighlightStrongBorder": "#17e5e666", "editorBracketMatch.background": "#17e5e650", "editorBracketMatch.border": "#17e5e600", "editorCursor.foreground": "#58a6ff", "editorGroup.border": "#30363d", "editorGroupHeader.tabsBackground": "#010409", "editorGroupHeader.tabsBorder": "#30363d", "editorGutter.addedBackground": "#2ea04366", "editorGutter.deletedBackground": "#f8514966", "editorGutter.modifiedBackground": "#bb800966", "editorIndentGuide.activeBackground": "#30363d", "editorIndentGuide.background": "#21262d", "editorLineNumber.activeForeground": "#c9d1d9", "editorLineNumber.foreground": "#8b949e", "editorOverviewRuler.border": "#010409", "editorWhitespace.foreground": "#484f58", "editorWidget.background": "#161b22", "errorForeground": "#f85149", "focusBorder": "#1f6feb", "foreground": "#c9d1d9", "gitDecoration.addedResourceForeground": "#3fb950", "gitDecoration.conflictingResourceForeground": "#db6d28", "gitDecoration.deletedResourceForeground": "#f85149", "gitDecoration.ignoredResourceForeground": "#484f58", "gitDecoration.modifiedResourceForeground": "#d29922", "gitDecoration.submoduleResourceForeground": "#8b949e", "gitDecoration.untrackedResourceForeground": "#3fb950", "input.background": "#0d1117", "input.border": "#30363d", "input.foreground": "#c9d1d9", "input.placeholderForeground": "#484f58", "list.activeSelectionBackground": "#6e768166", "list.activeSelectionForeground": "#c9d1d9", "list.focusBackground": "#388bfd26", "list.focusForeground": "#c9d1d9", "list.highlightForeground": "#58a6ff", "list.hoverBackground": "#6e76811a", "list.hoverForeground": "#c9d1d9", "list.inactiveFocusBackground": "#388bfd26", "list.inactiveSelectionBackground": "#6e768166", "list.inactiveSelectionForeground": "#c9d1d9", "notificationCenterHeader.background": "#161b22", "notificationCenterHeader.foreground": "#8b949e", "notifications.background": "#161b22", "notifications.border": "#30363d", "notifications.foreground": "#c9d1d9", "notificationsErrorIcon.foreground": "#f85149", "notificationsInfoIcon.foreground": "#58a6ff", "notificationsWarningIcon.foreground": "#d29922", "panel.background": "#010409", "panel.border": "#30363d", "panelInput.border": "#30363d", "panelTitle.activeBorder": "#f78166", "panelTitle.activeForeground": "#c9d1d9", "panelTitle.inactiveForeground": "#8b949e", "peekViewEditor.background": "#0d111788", "peekViewEditor.matchHighlightBackground": "#ffd33d33", "peekViewResult.background": "#0d1117", "peekViewResult.matchHighlightBackground": "#ffd33d33", "pickerGroup.border": "#30363d", "pickerGroup.foreground": "#8b949e", "progressBar.background": "#1f6feb", "quickInput.background": "#161b22", "quickInput.foreground": "#c9d1d9", "scrollbar.shadow": "#00000088", "scrollbarSlider.activeBackground": "#484f5888", "scrollbarSlider.background": "#484f5833", "scrollbarSlider.hoverBackground": "#484f5844", "settings.headerForeground": "#8b949e", "settings.modifiedItemIndicator": "#bb800966", "sideBar.background": "#010409", "sideBar.border": "#30363d", "sideBar.foreground": "#c9d1d9", "sideBarSectionHeader.background": "#010409", "sideBarSectionHeader.border": "#30363d", "sideBarSectionHeader.foreground": "#c9d1d9", "sideBarTitle.foreground": "#c9d1d9", "statusBar.background": "#0d1117", "statusBar.border": "#30363d", "statusBar.debuggingBackground": "#da3633", "statusBar.debuggingForeground": "#f0f6fc", "statusBar.foreground": "#8b949e", "statusBar.noFolderBackground": "#0d1117", "statusBarItem.prominentBackground": "#161b22", "tab.activeBackground": "#0d1117", "tab.activeBorder": "#0d1117", "tab.activeBorderTop": "#f78166", "tab.activeForeground": "#c9d1d9", "tab.border": "#30363d", "tab.hoverBackground": "#0d1117", "tab.inactiveBackground": "#010409", "tab.inactiveForeground": "#8b949e", "tab.unfocusedActiveBorder": "#0d1117", "tab.unfocusedActiveBorderTop": "#30363d", "tab.unfocusedHoverBackground": "#6e76811a", "terminal.ansiBlack": "#484f58", "terminal.ansiBlue": "#58a6ff", "terminal.ansiBrightBlack": "#6e7681", "terminal.ansiBrightBlue": "#79c0ff", "terminal.ansiBrightCyan": "#56d4dd", "terminal.ansiBrightGreen": "#56d364", "terminal.ansiBrightMagenta": "#d2a8ff", "terminal.ansiBrightRed": "#ffa198", "terminal.ansiBrightWhite": "#f0f6fc", "terminal.ansiBrightYellow": "#e3b341", "terminal.ansiCyan": "#39c5cf", "terminal.ansiGreen": "#3fb950", "terminal.ansiMagenta": "#bc8cff", "terminal.ansiRed": "#ff7b72", "terminal.ansiWhite": "#b1bac4", "terminal.ansiYellow": "#d29922", "terminal.foreground": "#8b949e", "textBlockQuote.background": "#010409", "textBlockQuote.border": "#30363d", "textCodeBlock.background": "#6e768166", "textLink.activeForeground": "#58a6ff", "textLink.foreground": "#58a6ff", "textPreformat.foreground": "#8b949e", "textSeparator.foreground": "#21262d", "titleBar.activeBackground": "#0d1117", "titleBar.activeForeground": "#8b949e", "titleBar.border": "#30363d", "titleBar.inactiveBackground": "#010409", "titleBar.inactiveForeground": "#8b949e", "tree.indentGuidesStroke": "#21262d", "welcomePage.buttonBackground": "#21262d", "welcomePage.buttonHoverBackground": "#30363d", //"activityBar.dropBorder": "#c9d1d9", //"banner.background": "#6e768166", //"banner.foreground": "#c9d1d9", //"banner.iconForeground": "#3794ff", //"breadcrumb.background": "#0d1117", //"charts.blue": "#3794ff", //"charts.foreground": "#c9d1d9", //"charts.green": "#89d185", //"charts.lines": "#c9d1d980", //"charts.orange": "#d18616", //"charts.purple": "#b180d7", //"charts.red": "#f14c4c", //"charts.yellow": "#cca700", //"checkbox.foreground": "#c9d1d9", //"debugConsole.errorForeground": "#f85149", //"debugConsole.infoForeground": "#3794ff", //"debugConsole.sourceForeground": "#c9d1d9", //"debugConsole.warningForeground": "#cca700", //"debugConsoleInputIcon.foreground": "#c9d1d9", //"debugExceptionWidget.background": "#420b0d", //"debugExceptionWidget.border": "#a31515", //"debugIcon.breakpointCurrentStackframeForeground": "#ffcc00", //"debugIcon.breakpointDisabledForeground": "#848484", //"debugIcon.breakpointForeground": "#e51400", //"debugIcon.breakpointStackframeForeground": "#89d185", //"debugIcon.breakpointUnverifiedForeground": "#848484", //"debugIcon.continueForeground": "#75beff", //"debugIcon.disconnectForeground": "#f48771", //"debugIcon.pauseForeground": "#75beff", //"debugIcon.restartForeground": "#89d185", //"debugIcon.startForeground": "#89d185", //"debugIcon.stepBackForeground": "#75beff", //"debugIcon.stepIntoForeground": "#75beff", //"debugIcon.stepOutForeground": "#75beff", //"debugIcon.stepOverForeground": "#75beff", //"debugIcon.stopForeground": "#f48771", //"debugTokenExpression.boolean": "#4e94ce", //"debugTokenExpression.error": "#f48771", //"debugTokenExpression.name": "#c586c0", //"debugTokenExpression.number": "#b5cea8", //"debugTokenExpression.string": "#ce9178", //"debugTokenExpression.value": "#cccccc99", //"debugView.exceptionLabelBackground": "#6c2022", //"debugView.exceptionLabelForeground": "#c9d1d9", //"debugView.stateLabelBackground": "#88888844", //"debugView.stateLabelForeground": "#c9d1d9", //"debugView.valueChangedHighlight": "#569cd6", //"diffEditor.diagonalFill": "#cccccc33", //"editor.findRangeHighlightBackground": "#3a3d4166", //"editor.hoverHighlightBackground": "#264f7840", //"editor.inlineValuesBackground": "#ffc80033", //"editor.inlineValuesForeground": "#ffffff80", //"editor.lineHighlightBorder": "#282828", //"editor.rangeHighlightBackground": "#ffffff0b", //"editor.snippetFinalTabstopHighlightBorder": "#525252", //"editor.snippetTabstopHighlightBackground": "#7c7c7c4d", //"editor.symbolHighlightBackground": "#ffd33d22", //"editorActiveLineNumber.foreground": "#c6c6c6", //"editorBracketHighlight.foreground1": "#ffd700", //"editorBracketHighlight.foreground2": "#da70d6", //"editorBracketHighlight.foreground3": "#179fff", //"editorBracketHighlight.foreground4": "#00000000", //"editorBracketHighlight.foreground5": "#00000000", //"editorBracketHighlight.foreground6": "#00000000", //"editorBracketHighlight.unexpectedBracket.foreground": "#ff1212cc", //"editorCodeLens.foreground": "#999999", //"editorError.foreground": "#f14c4c", //"editorGhostText.foreground": "#ffffff56", //"editorGroup.dropBackground": "#53595d80", //"editorGroupHeader.noTabsBackground": "#0d1117", //"editorGutter.background": "#0d1117", //"editorGutter.commentRangeForeground": "#c5c5c5", //"editorGutter.foldingControlForeground": "#c5c5c5", //"editorHint.foreground": "#eeeeeeb3", //"editorHoverWidget.background": "#161b22", //"editorHoverWidget.border": "#454545", //"editorHoverWidget.foreground": "#c9d1d9", //"editorHoverWidget.statusBarBackground": "#1a2029", //"editorInfo.foreground": "#3794ff", //"editorInlayHint.background": "#1f6feb99", //"editorInlayHint.foreground": "#f0f6fccc", //"editorInlayHint.parameterBackground": "#1f6feb99", //"editorInlayHint.parameterForeground": "#f0f6fccc", //"editorInlayHint.typeBackground": "#1f6feb99", //"editorInlayHint.typeForeground": "#f0f6fccc", //"editorLightBulb.foreground": "#ffcc00", //"editorLightBulbAutoFix.foreground": "#75beff", //"editorLink.activeForeground": "#4e94ce", //"editorMarkerNavigation.background": "#0d1117", //"editorMarkerNavigationError.background": "#f14c4c", //"editorMarkerNavigationError.headerBackground": "#f14c4c1a", //"editorMarkerNavigationInfo.background": "#3794ff", //"editorMarkerNavigationInfo.headerBackground": "#3794ff1a", //"editorMarkerNavigationWarning.background": "#cca700", //"editorMarkerNavigationWarning.headerBackground": "#cca7001a", //"editorOverviewRuler.addedForeground": "#2ea0433d", //"editorOverviewRuler.bracketMatchForeground": "#a0a0a0", //"editorOverviewRuler.commonContentForeground": "#60606066", //"editorOverviewRuler.currentContentForeground": "#40c8ae80", //"editorOverviewRuler.deletedForeground": "#f851493d", //"editorOverviewRuler.errorForeground": "#ff1212b3", //"editorOverviewRuler.findMatchForeground": "#d186167e", //"editorOverviewRuler.incomingContentForeground": "#40a6ff80", //"editorOverviewRuler.infoForeground": "#3794ff", //"editorOverviewRuler.modifiedForeground": "#bb80093d", //"editorOverviewRuler.rangeHighlightForeground": "#007acc99", //"editorOverviewRuler.selectionHighlightForeground": "#a0a0a0cc", //"editorOverviewRuler.warningForeground": "#cca700", //"editorOverviewRuler.wordHighlightForeground": "#a0a0a0cc", //"editorOverviewRuler.wordHighlightStrongForeground": "#c0a0c0cc", //"editorPane.background": "#0d1117", //"editorRuler.foreground": "#5a5a5a", //"editorSuggestWidget.background": "#161b22", //"editorSuggestWidget.border": "#454545", //"editorSuggestWidget.focusHighlightForeground": "#58a6ff", //"editorSuggestWidget.foreground": "#c9d1d9", //"editorSuggestWidget.highlightForeground": "#58a6ff", //"editorSuggestWidget.selectedBackground": "#6e768166", //"editorSuggestWidget.selectedForeground": "#c9d1d9", //"editorUnnecessaryCode.opacity": "#000000aa", //"editorWarning.foreground": "#cca700", //"editorWidget.border": "#454545", //"editorWidget.foreground": "#c9d1d9", //"extensionBadge.remoteBackground": "#1f6feb", //"extensionBadge.remoteForeground": "#f0f6fc", //"extensionButton.prominentBackground": "#238636", //"extensionButton.prominentForeground": "#ffffff", //"extensionButton.prominentHoverBackground": "#2ea043", //"extensionIcon.starForeground": "#ff8e00", //"gitDecoration.renamedResourceForeground": "#73c991", //"gitDecoration.stageDeletedResourceForeground": "#c74e39", //"gitDecoration.stageModifiedResourceForeground": "#e2c08d", //"icon.foreground": "#c5c5c5", //"inputOption.activeBackground": "#1f6feb66", //"inputOption.activeBorder": "#007acc00", //"inputOption.activeForeground": "#ffffff", //"inputValidation.errorBackground": "#5a1d1d", //"inputValidation.errorBorder": "#be1100", //"inputValidation.infoBackground": "#063b49", //"inputValidation.infoBorder": "#007acc", //"inputValidation.warningBackground": "#352a05", //"inputValidation.warningBorder": "#b89500", //"interactive.activeCodeBorder": "#3794ff", //"interactive.inactiveCodeBorder": "#6e768166", //"issues.closed": "#cb2431", //"issues.newIssueDecoration": "#ffffff48", //"issues.open": "#22863a", //"keybindingLabel.background": "#8080802b", //"keybindingLabel.border": "#33333399", //"keybindingLabel.bottomBorder": "#44444499", //"keybindingLabel.foreground": "#cccccc", //"list.deemphasizedForeground": "#8c8c8c", //"list.dropBackground": "#062f4a", //"list.errorForeground": "#f88070", //"list.filterMatchBackground": "#ffd33d22", //"list.focusHighlightForeground": "#58a6ff", //"list.focusOutline": "#1f6feb", //"list.invalidItemForeground": "#b89500", //"list.warningForeground": "#cca700", //"listFilterWidget.background": "#653723", //"listFilterWidget.noMatchesOutline": "#be1100", //"listFilterWidget.outline": "#00000000", //"menu.background": "#161b22", //"menu.foreground": "#c9d1d9", //"menu.selectionBackground": "#6e768166", //"menu.selectionForeground": "#c9d1d9", //"menu.separatorBackground": "#bbbbbb", //"menubar.selectionBackground": "#ffffff1a", //"menubar.selectionForeground": "#8b949e", //"merge.commonContentBackground": "#60606029", //"merge.commonHeaderBackground": "#60606066", //"merge.currentContentBackground": "#40c8ae33", //"merge.currentHeaderBackground": "#40c8ae80", //"merge.incomingContentBackground": "#40a6ff33", //"merge.incomingHeaderBackground": "#40a6ff80", //"minimap.errorHighlight": "#ff1212b3", //"minimap.findMatchHighlight": "#d18616", //"minimap.foregroundOpacity": "#000000", //"minimap.selectionHighlight": "#264f78", //"minimap.selectionOccurrenceHighlight": "#676767", //"minimap.warningHighlight": "#cca700", //"minimapGutter.addedBackground": "#587c0c", //"minimapGutter.deletedBackground": "#94151b", //"minimapGutter.modifiedBackground": "#0c7d9d", //"minimapSlider.activeBackground": "#484f5844", //"minimapSlider.background": "#484f581a", //"minimapSlider.hoverBackground": "#484f5822", //"notebook.cellBorderColor": "#6e768166", //"notebook.cellEditorBackground": "#c9d1d90a", //"notebook.cellInsertionIndicator": "#1f6feb", //"notebook.cellStatusBarItemHoverBackground": "#ffffff26", //"notebook.cellToolbarSeparator": "#80808059", //"notebook.focusedCellBorder": "#1f6feb", //"notebook.focusedEditorBorder": "#1f6feb", //"notebook.inactiveFocusedCellBorder": "#6e768166", //"notebook.selectedCellBackground": "#6e768166", //"notebook.selectedCellBorder": "#6e768166", //"notebook.symbolHighlightBackground": "#ffffff0b", //"notebookScrollbarSlider.activeBackground": "#484f5888", //"notebookScrollbarSlider.background": "#484f5833", //"notebookScrollbarSlider.hoverBackground": "#484f5844", //"notebookStatusErrorIcon.foreground": "#f85149", //"notebookStatusRunningIcon.foreground": "#c9d1d9", //"notebookStatusSuccessIcon.foreground": "#89d185", //"notificationLink.foreground": "#58a6ff", //"panel.dropBorder": "#c9d1d9", //"panelSection.border": "#30363d", //"panelSection.dropBackground": "#53595d80", //"panelSectionHeader.background": "#80808033", //"peekView.border": "#3794ff", //"peekViewEditorGutter.background": "#0d111788", //"peekViewResult.fileForeground": "#ffffff", //"peekViewResult.lineForeground": "#bbbbbb", //"peekViewResult.selectionBackground": "#3399ff33", //"peekViewResult.selectionForeground": "#ffffff", //"peekViewTitle.background": "#3794ff1a", //"peekViewTitleDescription.foreground": "#ccccccb3", //"peekViewTitleLabel.foreground": "#ffffff", //"ports.iconRunningProcessForeground": "#1f6feb", //"problemsErrorIcon.foreground": "#f14c4c", //"problemsInfoIcon.foreground": "#3794ff", //"problemsWarningIcon.foreground": "#cca700", //"quickInputList.focusBackground": "#6e768166", //"quickInputList.focusForeground": "#c9d1d9", //"quickInputTitle.background": "#ffffff1b", //"sash.hoverBorder": "#1f6feb", //"scm.providerBorder": "#454545", //"searchEditor.findMatchBackground": "#ffd33d16", //"searchEditor.textInputBorder": "#30363d", //"settings.checkboxBackground": "#161b22", //"settings.checkboxBorder": "#30363d", //"settings.checkboxForeground": "#c9d1d9", //"settings.dropdownBackground": "#161b22", //"settings.dropdownBorder": "#30363d", //"settings.dropdownForeground": "#c9d1d9", //"settings.dropdownListBorder": "#454545", //"settings.focusedRowBackground": "#80808024", //"settings.focusedRowBorder": "#ffffff1f", //"settings.numberInputBackground": "#0d1117", //"settings.numberInputBorder": "#30363d", //"settings.numberInputForeground": "#c9d1d9", //"settings.rowHoverBackground": "#80808012", //"settings.textInputBackground": "#0d1117", //"settings.textInputBorder": "#30363d", //"settings.textInputForeground": "#c9d1d9", //"sideBar.dropBackground": "#53595d80", //"sideBySideEditor.border": "#30363d", //"statusBar.debuggingBorder": "#30363d", //"statusBar.noFolderBorder": "#30363d", //"statusBar.noFolderForeground": "#8b949e", //"statusBarItem.activeBackground": "#ffffff2e", //"statusBarItem.errorBackground": "#b91007", //"statusBarItem.errorForeground": "#ffffff", //"statusBarItem.hoverBackground": "#ffffff1f", //"statusBarItem.prominentForeground": "#8b949e", //"statusBarItem.prominentHoverBackground": "#0000004d", //"statusBarItem.remoteBackground": "#1f6feb", //"statusBarItem.remoteForeground": "#f0f6fc", //"statusBarItem.warningBackground": "#7a6400", //"statusBarItem.warningForeground": "#ffffff", //"symbolIcon.arrayForeground": "#c9d1d9", //"symbolIcon.booleanForeground": "#c9d1d9", //"symbolIcon.classForeground": "#ee9d28", //"symbolIcon.colorForeground": "#c9d1d9", //"symbolIcon.constantForeground": "#c9d1d9", //"symbolIcon.constructorForeground": "#b180d7", //"symbolIcon.enumeratorForeground": "#ee9d28", //"symbolIcon.enumeratorMemberForeground": "#75beff", //"symbolIcon.eventForeground": "#ee9d28", //"symbolIcon.fieldForeground": "#75beff", //"symbolIcon.fileForeground": "#c9d1d9", //"symbolIcon.folderForeground": "#c9d1d9", //"symbolIcon.functionForeground": "#b180d7", //"symbolIcon.interfaceForeground": "#75beff", //"symbolIcon.keyForeground": "#c9d1d9", //"symbolIcon.keywordForeground": "#c9d1d9", //"symbolIcon.methodForeground": "#b180d7", //"symbolIcon.moduleForeground": "#c9d1d9", //"symbolIcon.namespaceForeground": "#c9d1d9", //"symbolIcon.nullForeground": "#c9d1d9", //"symbolIcon.numberForeground": "#c9d1d9", //"symbolIcon.objectForeground": "#c9d1d9", //"symbolIcon.operatorForeground": "#c9d1d9", //"symbolIcon.packageForeground": "#c9d1d9", //"symbolIcon.propertyForeground": "#c9d1d9", //"symbolIcon.referenceForeground": "#c9d1d9", //"symbolIcon.snippetForeground": "#c9d1d9", //"symbolIcon.stringForeground": "#c9d1d9", //"symbolIcon.structForeground": "#c9d1d9", //"symbolIcon.textForeground": "#c9d1d9", //"symbolIcon.typeParameterForeground": "#c9d1d9", //"symbolIcon.unitForeground": "#c9d1d9", //"symbolIcon.variableForeground": "#75beff", //"tab.activeModifiedBorder": "#3399cc", //"tab.inactiveModifiedBorder": "#3399cc80", //"tab.lastPinnedBorder": "#21262d", //"tab.unfocusedActiveBackground": "#0d1117", //"tab.unfocusedActiveForeground": "#c9d1d980", //"tab.unfocusedActiveModifiedBorder": "#3399cc80", //"tab.unfocusedInactiveBackground": "#010409", //"tab.unfocusedInactiveForeground": "#8b949e80", //"tab.unfocusedInactiveModifiedBorder": "#3399cc40", //"terminal.border": "#30363d", //"terminal.dropBackground": "#53595d80", //"terminal.selectionBackground": "#ffffff40", //"terminal.tab.activeBorder": "#0d1117", //"testing.iconErrored": "#f14c4c", //"testing.iconFailed": "#f14c4c", //"testing.iconPassed": "#73c991", //"testing.iconQueued": "#cca700", //"testing.iconSkipped": "#848484", //"testing.iconUnset": "#848484", //"testing.message.error.decorationForeground": "#f14c4c", //"testing.message.error.lineBackground": "#ff000033", //"testing.message.info.decorationForeground": "#c9d1d980", //"testing.peekBorder": "#f14c4c", //"testing.peekHeaderBackground": "#f14c4c1a", //"testing.runAction": "#73c991", //"toolbar.activeBackground": "#63666750", //"toolbar.hoverBackground": "#5a5d5e50", //"tree.tableColumnsBorder": "#cccccc20", //"welcomePage.progress.background": "#0d1117", //"welcomePage.progress.foreground": "#58a6ff", //"welcomePage.tileBackground": "#161b22", //"welcomePage.tileHoverBackground": "#1a2029", //"welcomePage.tileShadow.": "#0000005c", //"widget.shadow": "#0000005c", //"activityBar.activeBackground": null, //"activityBar.activeFocusBorder": null, //"button.border": null, //"contrastActiveBorder": null, //"contrastBorder": null, //"debugToolBar.border": null, //"diffEditor.border": null, //"diffEditor.insertedTextBorder": null, //"diffEditor.removedTextBorder": null, //"editor.findMatchBorder": null, //"editor.findMatchHighlightBorder": null, //"editor.findRangeHighlightBorder": null, //"editor.rangeHighlightBorder": null, //"editor.selectionForeground": null, //"editor.snippetFinalTabstopHighlightBackground": null, //"editor.snippetTabstopHighlightBorder": null, //"editor.symbolHighlightBorder": null, //"editorCursor.background": null, //"editorError.background": null, //"editorError.border": null, //"editorGhostText.border": null, //"editorGroup.emptyBackground": null, //"editorGroup.focusedEmptyBorder": null, //"editorGroupHeader.border": null, //"editorHint.border": null, //"editorInfo.background": null, //"editorInfo.border": null, //"editorOverviewRuler.background": null, //"editorSuggestWidget.selectedIconForeground": null, //"editorUnnecessaryCode.border": null, //"editorWarning.background": null, //"editorWarning.border": null, //"editorWidget.resizeBorder": null, //"inputValidation.errorForeground": null, //"inputValidation.infoForeground": null, //"inputValidation.warningForeground": null, //"list.activeSelectionIconForeground": null, //"list.filterMatchBorder": null, //"list.inactiveFocusOutline": null, //"list.inactiveSelectionIconForeground": null, //"menu.border": null, //"menu.selectionBorder": null, //"menubar.selectionBorder": null, //"merge.border": null, //"minimap.background": null, //"notebook.cellHoverBackground": null, //"notebook.focusedCellBackground": null, //"notebook.inactiveSelectedCellBorder": null, //"notebook.outputContainerBackgroundColor": null, //"notebook.outputContainerBorderColor": null, //"notificationCenter.border": null, //"notificationToast.border": null, //"panelSectionHeader.border": null, //"panelSectionHeader.foreground": null, //"peekViewEditor.matchHighlightBorder": null, //"quickInput.list.focusBackground": null, //"quickInputList.focusIconForeground": null, //"searchEditor.findMatchBorder": null, //"selection.background": null, //"tab.hoverBorder": null, //"tab.hoverForeground": null, //"tab.unfocusedHoverBorder": null, //"tab.unfocusedHoverForeground": null, //"terminal.background": null, //"terminalCursor.background": null, //"terminalCursor.foreground": null, //"testing.message.info.lineBackground": null, //"toolbar.hoverOutline": null, //"walkThrough.embeddedEditorBackground": null, //"welcomePage.background": null, //"window.activeBorder": null, //"window.inactiveBorder": null // --- Github dark dimmed // 'activityBar.activeBackground': '#3399FF', // 'activityBar.activeBorder': '#BF0060', // 'activityBar.background': '#3399FF', // 'activityBar.border': '#1B1F23', // 'activityBar.foreground': '#15202B', // 'activityBar.inactiveForeground': '#15202B99', // 'activityBarBadge.background': '#BF0060', // 'activityBarBadge.foreground': '#E7E7E7', // 'badge.background': '#044289', // 'badge.foreground': '#C8E1FF', // 'breadcrumb.activeSelectionForeground': '#D1D5DA', // 'breadcrumb.focusForeground': '#E1E4E8', // 'breadcrumb.foreground': '#959DA5', // 'breadcrumbPicker.background': '#2B3036', // 'button.background': '#176F2C', // 'button.foreground': '#DCFFE4', // 'button.hoverBackground': '#22863A', // 'button.secondaryBackground': '#444D56', // 'button.secondaryForeground': '#FFFFFF', // 'button.secondaryHoverBackground': '#586069', // 'checkbox.background': '#444D56', // 'checkbox.border': '#1B1F23', // 'debugToolBar.background': '#2B3036', // descriptionForeground: '#959DA5', // 'diffEditor.insertedTextBackground': '#28A74530', // 'diffEditor.removedTextBackground': '#D73A4930', // "minimap.background": "#24292E", // "minimap.hoverBackground": "#00000028", // 'dropdown.background': '#2F363D', // 'dropdown.border': '#1B1F23', // 'dropdown.foreground': '#E1E4E8', // 'dropdown.listBackground': '#24292E', // 'editor.background': '#24292E', // 'editor.findMatchBackground': '#FFD33D44', // 'editor.findMatchHighlightBackground': '#FFD33D22', // 'editor.focusedStackFrameHighlightBackground': '#2B6A3033', // 'editor.foldBackground': '#58606915', // 'editor.foreground': '#E1E4E8', // 'editor.inactiveSelectionBackground': '#3392FF22', // 'editor.lineHighlightBackground': '#2B3036', // 'editor.linkedEditingBackground': '#3392FF22', // 'editor.selectionBackground': '#3392FF44', // 'editor.selectionHighlightBackground': '#17E5E633', // 'editor.selectionHighlightBorder': '#17E5E600', // 'editor.stackFrameHighlightBackground': '#C6902625', // 'editor.wordHighlightBackground': '#17E5E600', // 'editor.wordHighlightBorder': '#17E5E699', // 'editor.wordHighlightStrongBackground': '#17E5E600', // 'editor.wordHighlightStrongBorder': '#17E5E666', // 'editorBracketMatch.background': '#17E5E650', // 'editorBracketMatch.border': '#17E5E600', // 'editorCursor.foreground': '#C8E1FF', // 'editorGroup.border': '#1B1F23', // 'editorGroupHeader.tabsBackground': '#1F2428', // 'editorGroupHeader.tabsBorder': '#1B1F23', // 'editorGutter.addedBackground': '#28A745', // 'editorGutter.deletedBackground': '#EA4A5A', // 'editorGutter.modifiedBackground': '#2188FF', // 'editorIndentGuide.activeBackground': '#444D56', // 'editorIndentGuide.background': '#2F363D', // 'editorLineNumber.activeForeground': '#E1E4E8', // 'editorLineNumber.foreground': '#444D56', // 'editorOverviewRuler.border': '#1B1F23', // 'editorWhitespace.foreground': '#444D56', // 'editorWidget.background': '#1F2428', // errorForeground: '#F97583', // focusBorder: '#005CC5', // foreground: '#D1D5DA', // 'gitDecoration.addedResourceForeground': '#34D058', // 'gitDecoration.conflictingResourceForeground': '#FFAB70', // 'gitDecoration.deletedResourceForeground': '#EA4A5A', // 'gitDecoration.ignoredResourceForeground': '#6A737D', // 'gitDecoration.modifiedResourceForeground': '#79B8FF', // 'gitDecoration.submoduleResourceForeground': '#6A737D', // 'gitDecoration.untrackedResourceForeground': '#34D058', // 'input.background': '#2F363D', // 'input.border': '#1B1F23', // 'input.foreground': '#E1E4E8', // 'input.placeholderForeground': '#959DA5', // 'list.activeSelectionBackground': '#39414A', // 'list.activeSelectionForeground': '#E1E4E8', // 'list.focusBackground': '#044289', // 'list.hoverBackground': '#282E34', // 'list.hoverForeground': '#E1E4E8', // 'list.inactiveFocusBackground': '#1D2D3E', // 'list.inactiveSelectionBackground': '#282E34', // 'list.inactiveSelectionForeground': '#E1E4E8', // 'notificationCenterHeader.background': '#24292E', // 'notificationCenterHeader.foreground': '#959DA5', // 'notifications.background': '#2F363D', // 'notifications.border': '#1B1F23', // 'notifications.foreground': '#E1E4E8', // 'notificationsErrorIcon.foreground': '#EA4A5A', // 'notificationsInfoIcon.foreground': '#79B8FF', // 'notificationsWarningIcon.foreground': '#FFAB70', // 'panel.background': '#1F2428', // 'panel.border': '#1B1F23', // 'panelInput.border': '#2F363D', // 'panelTitle.activeBorder': '#F9826C', // 'panelTitle.activeForeground': '#E1E4E8', // 'panelTitle.inactiveForeground': '#959DA5', // 'peekViewEditor.background': '#1F242888', // 'peekViewEditor.matchHighlightBackground': '#FFD33D33', // 'peekViewResult.background': '#1F2428', // 'peekViewResult.matchHighlightBackground': '#FFD33D33', // 'pickerGroup.border': '#444D56', // 'pickerGroup.foreground': '#E1E4E8', // 'progressBar.background': '#0366D6', // 'quickInput.background': '#24292E', // 'quickInput.foreground': '#E1E4E8', // 'scrollbar.shadow': '#00000088', // 'settings.headerForeground': '#E1E4E8', // 'settings.modifiedItemIndicator': '#0366D6', // 'sideBar.background': '#1F2428', // 'sideBar.border': '#1B1F23', // 'sideBar.foreground': '#D1D5DA', // 'sideBarSectionHeader.background': '#1F2428', // 'sideBarSectionHeader.border': '#1B1F23', // 'sideBarSectionHeader.foreground': '#E1E4E8', // 'sideBarTitle.foreground': '#E1E4E8', // 'statusBar.background': '#007FFF', // 'statusBar.border': '#1B1F23', // 'statusBar.debuggingBackground': '#931C06', // 'statusBar.debuggingForeground': '#FFFFFF', // 'statusBar.foreground': '#E7E7E7', // 'statusBar.noFolderBackground': '#24292E', // 'statusBarItem.hoverBackground': '#3399FF', // 'statusBarItem.prominentBackground': '#282E34', // 'tab.activeBackground': '#24292E', // 'tab.activeBorder': '#24292E', // 'tab.activeBorderTop': '#F9826C', // 'tab.activeForeground': '#E1E4E8', // 'tab.border': '#1B1F23', // 'tab.hoverBackground': '#24292E', // 'tab.inactiveBackground': '#1F2428', // 'tab.inactiveForeground': '#959DA5', // 'tab.unfocusedActiveBorder': '#24292E', // 'tab.unfocusedActiveBorderTop': '#1B1F23', // 'tab.unfocusedHoverBackground': '#24292E', // 'terminal.foreground': '#D1D5DA', // 'textBlockQuote.background': '#24292E', // 'textBlockQuote.border': '#444D56', // 'textCodeBlock.background': '#2F363D', // 'textLink.activeForeground': '#C8E1FF', // 'textLink.foreground': '#79B8FF', // 'textPreformat.foreground': '#D1D5DA', // 'textSeparator.foreground': '#586069', // 'titleBar.activeBackground': '#007FFF', // 'titleBar.activeForeground': '#E7E7E7', // 'titleBar.border': '#1B1F23', // 'titleBar.inactiveBackground': '#007FFF99', // 'titleBar.inactiveForeground': '#E7E7E799', // 'tree.indentGuidesStroke': '#2F363D', // 'welcomePage.buttonBackground': '#2F363D', // 'welcomePage.buttonHoverBackground': '#444D56' } }
the_stack
import { ChronoGraph, CommitArguments, CommitResult, CommitZero } from "../chrono/Graph.js" import { Identifier } from "../chrono/Identifier.js" import { SyncEffectHandler, YieldableValue } from "../chrono/Transaction.js" import { AnyConstructor, Mixin } from "../class/Mixin.js" import { DEBUG, debug, DEBUG_ONLY, SourceLinePoint } from "../environment/Debug.js" import { CalculationIterator, runGeneratorSyncWithEffect } from "../primitives/Calculation.js" import { EntityMeta } from "../schema/EntityMeta.js" import { Field, Name } from "../schema/Field.js" import { defineProperty, uppercaseFirst } from "../util/Helpers.js" import { EntityIdentifier, FieldIdentifier, MinimalEntityIdentifier } from "./Identifier.js" import { Replica } from "./Replica.js" const isEntityMarker = Symbol('isEntity') //--------------------------------------------------------------------------------------------------------------------- /** * Entity [[Mixin|mixin]]. When applied to some base class (recommended one is [[Base]]), turns it into entity. * Entity may have several fields, which are properties decorated with [[field]] decorator. * * To apply this mixin use the `Entity.mix` property, which represents the mixin lambda. * * Another decorator, [[calculate]], marks the method, that will be used to calculate the value of field. * * Example: * * ```ts * class Author extends Entity.mix(Base) { * @field() * firstName : string * @field() * lastName : string * @field() * fullName : string * * @calculate('fullName') * calculateFullName () : string { * return this.firstName + ' ' + this.lastName * } * } * ``` * */ export class Entity extends Mixin( [], (base : AnyConstructor) => { class Entity extends base { // marker in the prototype to identify whether the parent class is Entity mixin itself // it is not used for `instanceof` purposes and not be confused with the [MixinInstanceOfProperty] // (though it is possible to use MixinInstanceOfProperty for this purpose, that would require to // make it public [isEntityMarker] () {} $calculations : { [s in keyof this] : string } $writes : { [s in keyof this] : string } $buildProposed : { [s in keyof this] : string } /** * A reference to the graph, this entity belongs to. Initially empty, and is populated when the entity instance * is added to the replica ([[Replica.addEntity]]) */ graph : Replica /** * An [[EntityMeta]] instance, representing the "meta" information about the entity class. It is shared among all instances * of the class. */ get $entity () : EntityMeta { // this will lazily create an EntityData instance in the prototype return createEntityOnPrototype(this.constructor.prototype) } /** * An object, which properties corresponds to the ChronoGraph [[Identifier]]s, created for every field. * * For example: * * ```ts * class Author extends Entity.mix(Base) { * @field() * firstName : string * @field() * lastName : string * } * * const author = Author.new() * * // identifier for the field `firstName` * author.$.firstName * * const firstName = replica.read(author.$.firstName) * ``` */ get $ () : { [s in keyof this] : FieldIdentifier } { const $ = {} this.$entity.forEachField((field, name) => { $[ name ] = this.createFieldIdentifier(field) }) if (DEBUG) { const proxy = new Proxy($, { get (entity : Entity, property : string | number | symbol, receiver : any) : any { if (!entity[ property ]) debug(new Error(`Attempt to read a missing field ${String(property)} on ${entity}`)) entity[ property ].SOURCE_POINT = SourceLinePoint.fromThisCall() return entity[ property ] } }) return defineProperty(this as any, '$', proxy) } else { return defineProperty(this as any, '$', $) } } /** * A graph identifier, that represents the whole entity. */ get $$ () : EntityIdentifier { return defineProperty(this, '$$', MinimalEntityIdentifier.new({ name : this.$entityName, entity : this.$entity, calculation : this.calculateSelf, context : this, self : this, })) } get $entityName () : string { return this.constructor.name || this.$entity.name } * calculateSelf () : CalculationIterator<this> { return this } createFieldIdentifier (field : Field) : FieldIdentifier { const name = field.name const entity = this.$entity const constructor = this.constructor as EntityConstructor const skeleton = entity.$skeleton if (!skeleton[ name ]) skeleton[ name ] = constructor.getIdentifierTemplateClass(this, field) const identifier = new skeleton[ name ]() identifier.context = this identifier.self = this identifier.name = `${this.$$.name}.$.${field.name}` return identifier } forEachFieldIdentifier<T extends this> (func : (field : FieldIdentifier, name : string) => any) { this.$entity.forEachField((field, name) => func(this.$[ name ], name)) } /** * This method is called when entity is added to some replica. * * @param replica */ enterGraph (replica : Replica) { if (this.graph) throw new Error('Already entered replica') this.graph = replica replica.addIdentifier(this.$$) this.$entity.forEachField((field, name) => { const identifier : FieldIdentifier = this.$[ name ] replica.addIdentifier(identifier, identifier.DATA) identifier.DATA = undefined }) } /** * This method is called when entity is removed from the replica it's been added to. */ leaveGraph (graph : Replica) { const ownGraph = this.graph const removeFrom = graph || ownGraph if (!removeFrom) return this.$entity.forEachField((field, name) => removeFrom.removeIdentifier(this.$[ name ])) removeFrom.removeIdentifier(this.$$) if (removeFrom === ownGraph) this.graph = undefined } // isPropagating () { // return this.getGraph().isPropagating // } propagate (arg? : CommitArguments) : CommitResult { return this.commit(arg) } /** * This is a convenience method, that just delegates to the [[ChronoGraph.commit]] method of this entity's graph. * * If there's no graph (entity has not been added to any replica) a [[CommitZero]] constant will be returned. */ commit (arg? : CommitArguments) : CommitResult { const graph = this.graph if (!graph) return CommitZero return graph.commit(arg) } async propagateAsync () : Promise<CommitResult> { return this.commitAsync() } /** * This is a convenience method, that just delegates to the [[ChronoGraph.commitAsync]] method of this entity's graph. * * If there's no graph (entity has not been added to any replica) a resolved promise with [[CommitZero]] constant will be returned. */ async commitAsync (arg? : CommitArguments) : Promise<CommitResult> { const graph = this.graph if (!graph) return Promise.resolve(CommitZero) return graph.commitAsync(arg) } /** * An [[EntityMeta]] instance, representing the "meta" information about the entity class. It is shared among all instances * of the class. */ static get $entity () : EntityMeta { return ensureEntityOnPrototype(this.prototype) } static getIdentifierTemplateClass (me : Entity, field : Field) : typeof Identifier { const name = field.name const config : Partial<FieldIdentifier> = { name : `${me.$$.name}.$.${name}`, field : field } //------------------ if (field.hasOwnProperty('sync')) config.sync = field.sync if (field.hasOwnProperty('lazy')) config.lazy = field.lazy if (field.hasOwnProperty('equality')) config.equality = field.equality //------------------ const calculationFunction = me.$calculations && me[ me.$calculations[ name ] ] if (calculationFunction) config.calculation = calculationFunction //------------------ const writeFunction = me.$writes && me[ me.$writes[ name ] ] if (writeFunction) config.write = writeFunction //------------------ const buildProposedFunction = me.$buildProposed && me[ me.$buildProposed[ name ] ] if (buildProposedFunction) { config.buildProposedValue = buildProposedFunction config.proposedValueIsBuilt = true } //------------------ const template = field.getIdentifierClass(calculationFunction).new(config) const TemplateClass = function () {} as any as typeof Identifier TemplateClass.prototype = template return TemplateClass } // unfortunately, the better typing: // run <Name extends AllowedNames<this, AnyFunction>> (methodName : Name, ...args : Parameters<this[ Name ]>) // : ReturnType<this[ Name ]> extends CalculationIterator<infer Res> ? Res : ReturnType<this[ Name ]> // yields "types are exceedingly long and possibly infinite on the application side // TODO file a TS bug report run (methodName : keyof this, ...args : any[]) : any { const onEffect : SyncEffectHandler = (effect : YieldableValue) => { if (effect instanceof Identifier) return this.graph.read(effect) throw new Error("Helper methods can not yield effects during computation") } return runGeneratorSyncWithEffect(onEffect, this[ methodName ] as any, args, this) } static createPropertyAccessorsFor (fieldName : string) { // idea is to indicate to the v8, that `propertyKey` is a constant and thus // it can optimize access by it const propertyKey = fieldName const target = this.prototype Object.defineProperty(target, propertyKey, { get : function (this : Entity) : any { return (this.$[ propertyKey ] as FieldIdentifier).getFromGraph(this.graph) }, set : function (this : Entity, value : any) { (this.$[ propertyKey ] as FieldIdentifier).writeToGraph(this.graph, value) } }) } static createMethodAccessorsFor (fieldName : string) { // idea is to indicate to the v8, that `propertyKey` is a constant and thus // it can optimize access by it const propertyKey = fieldName const target = this.prototype const getterFnName = `get${ uppercaseFirst(propertyKey) }` const setterFnName = `set${ uppercaseFirst(propertyKey) }` const putterFnName = `put${ uppercaseFirst(propertyKey) }` if (!(getterFnName in target)) { target[ getterFnName ] = function (this : Entity) : any { return (this.$[ propertyKey ] as FieldIdentifier).getFromGraph(this.graph) } } if (!(setterFnName in target)) { target[ setterFnName ] = function (this : Entity, value : any, ...args) : CommitResult | Promise<CommitResult> { (this.$[ propertyKey ] as FieldIdentifier).writeToGraph(this.graph, value, ...args) return this.graph ? (this.graph.autoCommitMode === 'sync' ? this.graph.commit() : this.graph.commitAsync()) : Promise.resolve(CommitZero) } } if (!(putterFnName in target)) { target[ putterFnName ] = function (this : Entity, value : any, ...args) : any { (this.$[ propertyKey ] as FieldIdentifier).writeToGraph(this.graph, value, ...args) } } } } return Entity }){} export type EntityConstructor = typeof Entity //--------------------------------------------------------------------------------------------------------------------- export const createEntityOnPrototype = (proto : any) : EntityMeta => { let parent = Object.getPrototypeOf(proto) // the `hasOwnProperty` condition will be `true` for the `Entity` mixin itself // if the parent is `Entity` mixin, then this is a top-level entity return defineProperty(proto, '$entity', EntityMeta.new({ parentEntity : parent.hasOwnProperty(isEntityMarker) ? null : parent.$entity, name : proto.constructor.name })) } //--------------------------------------------------------------------------------------------------------------------- export const ensureEntityOnPrototype = (proto : any) : EntityMeta => { if (!proto.hasOwnProperty('$entity')) createEntityOnPrototype(proto) return proto.$entity } export type FieldDecorator<Default extends AnyConstructor = typeof Field> = <T extends Default = Default> (fieldConfig? : Partial<InstanceType<T>>, fieldCls? : T | Default) => PropertyDecorator /* * The "generic" field decorator, in the sense, that it allows specifying both field config and field class. * This means it can create any field instance. */ export const generic_field : FieldDecorator<typeof Field> = <T extends typeof Field = typeof Field> (fieldConfig? : Partial<InstanceType<T>>, fieldCls : T | typeof Field = Field) : PropertyDecorator => { return function (target : Entity, fieldName : string) : void { const entity = ensureEntityOnPrototype(target) const field = entity.addField( fieldCls.new(Object.assign(fieldConfig || {}, { name : fieldName })) ) const cons = target.constructor as typeof Entity cons.createPropertyAccessorsFor(fieldName) cons.createMethodAccessorsFor(fieldName) } } //--------------------------------------------------------------------------------------------------------------------- /** * Field decorator. The type signature is: * * ```ts * field : <T extends typeof Field = typeof Field> (fieldConfig? : Partial<InstanceType<T>>, fieldCls : T | typeof Field = Field) => PropertyDecorator * ``` * Its a function, that accepts field config object and optionally a field class (default is [[Field]]) and returns a property decorator. * * Example: * * ```ts * const ignoreCaseCompare = (a : string, b : string) : boolean => a.toUpperCase() === b.toUpperCase() * * class MyField extends Field {} * * class Author extends Entity.mix(Base) { * @field({ equality : ignoreCaseCompare }) * firstName : string * * @field({ lazy : true }, MyField) * lastName : string * } * ``` * * For every field, there are generated get and set accessors, with which you can read/write the data: * * ```ts * const author = Author.new({ firstName : 'Mark' }) * * author.firstName // Mark * author.lastName = 'Twain' * ``` * * The getters are basically using [[Replica.get]] and setters [[Replica.write]]. * * Note, that if the identifier is asynchronous, reading from it will return a promise. But, immediately after the [[Replica.commit]] call, getter will return * plain value. This is a compromise between the convenience and correctness and this behavior may change (or made configurable) in the future. * * Additionally to the accessors, the getter and setter methods are generated. The getter method's name is formed as `get` followed by the field name * with upper-cased first letter. The setter's name is formed in the same way, with `set` prefix. * * The getter method is an exact equivalent of the get accessor. The setter method, in addition to data write, immediately after that * performs a call to [[Replica.commit]] (or [[Replica.commitAsync]], depending from the [[Replica.autoCommitMode]] option) * and return its result. * * ```ts * const author = Author.new({ firstName : 'Mark' }) * * author.getFirstName() // Mark * await author.setLastName('Twain') // issues asynchronous commit * ``` */ export const field : typeof generic_field = generic_field //--------------------------------------------------------------------------------------------------------------------- /** * Decorator for the method, that calculates a value of some field * * ```ts * * @entity() * class Author extends Entity.mix(Base) { * @field() * firstName : string * @field() * lastName : string * @field() * fullName : string * * @calculate('fullName') * calculateFullName () : string { * return this.firstName + ' ' + this.lastName * } * } * ``` * * @param fieldName The name of the field the decorated method should be "tied" to. */ export const calculate = function (fieldName : Name) : MethodDecorator { // `target` will be a prototype of the class with Entity mixin return function (target : Entity, propertyKey : string, _descriptor : TypedPropertyDescriptor<any>) : void { ensureEntityOnPrototype(target) let calculations : Entity[ '$calculations' ] if (!target.$calculations) { calculations = target.$calculations = {} as any } else { if (!target.hasOwnProperty('$calculations')) { calculations = target.$calculations = Object.create(target.$calculations) } else calculations = target.$calculations } calculations[ fieldName ] = propertyKey } } //--------------------------------------------------------------------------------------------------------------------- export const write = function (fieldName : Name) : MethodDecorator { // `target` will be a prototype of the class with Entity mixin return function (target : Entity, propertyKey : string, _descriptor : TypedPropertyDescriptor<any>) : void { ensureEntityOnPrototype(target) let writes : Entity[ '$writes' ] if (!target.$writes) { writes = target.$writes = {} as any } else { if (!target.hasOwnProperty('$writes')) { writes = target.$writes = Object.create(target.$writes) } else writes = target.$writes } writes[ fieldName ] = propertyKey } } //--------------------------------------------------------------------------------------------------------------------- export const build_proposed = function (fieldName : Name) : MethodDecorator { // `target` will be a prototype of the class with Entity mixin return function (target : Entity, propertyKey : string, _descriptor : TypedPropertyDescriptor<any>) : void { ensureEntityOnPrototype(target) let buildProposed : Entity[ '$buildProposed' ] if (!target.$buildProposed) { buildProposed = target.$buildProposed = {} as any } else { if (!target.hasOwnProperty('$buildProposed')) { buildProposed = target.$buildProposed = Object.create(target.$buildProposed) } else buildProposed = target.$buildProposed } buildProposed[ fieldName ] = propertyKey } }
the_stack
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { ATN } from "antlr4ts/atn/ATN"; import { ATNDeserializer } from "antlr4ts/atn/ATNDeserializer"; import { CharStream } from "antlr4ts/CharStream"; import { Lexer } from "antlr4ts/Lexer"; import { LexerATNSimulator } from "antlr4ts/atn/LexerATNSimulator"; import { NotNull } from "antlr4ts/Decorators"; import { Override } from "antlr4ts/Decorators"; import { RuleContext } from "antlr4ts/RuleContext"; import { Vocabulary } from "antlr4ts/Vocabulary"; import { VocabularyImpl } from "antlr4ts/VocabularyImpl"; import * as Utils from "antlr4ts/misc/Utils"; export class CommonRegexLexer extends Lexer { public static readonly Quoted = 1; public static readonly BlockQuoted = 2; public static readonly BellChar = 3; public static readonly ControlChar = 4; public static readonly EscapeChar = 5; public static readonly FormFeed = 6; public static readonly NewLine = 7; public static readonly CarriageReturn = 8; public static readonly Tab = 9; public static readonly Backslash = 10; public static readonly HexChar = 11; public static readonly Dot = 12; public static readonly DecimalDigit = 13; public static readonly NotDecimalDigit = 14; public static readonly CharWithProperty = 15; public static readonly CharWithoutProperty = 16; public static readonly WhiteSpace = 17; public static readonly NotWhiteSpace = 18; public static readonly WordChar = 19; public static readonly NotWordChar = 20; public static readonly CharacterClassStart = 21; public static readonly CharacterClassEnd = 22; public static readonly Caret = 23; public static readonly Hyphen = 24; public static readonly QuestionMark = 25; public static readonly Plus = 26; public static readonly Star = 27; public static readonly OpenBrace = 28; public static readonly CloseBrace = 29; public static readonly Comma = 30; public static readonly EndOfSubject = 31; public static readonly Pipe = 32; public static readonly OpenParen = 33; public static readonly CloseParen = 34; public static readonly LessThan = 35; public static readonly GreaterThan = 36; public static readonly SingleQuote = 37; public static readonly Underscore = 38; public static readonly Colon = 39; public static readonly Hash = 40; public static readonly Equals = 41; public static readonly Exclamation = 42; public static readonly Ampersand = 43; public static readonly ALC = 44; public static readonly BLC = 45; public static readonly CLC = 46; public static readonly DLC = 47; public static readonly ELC = 48; public static readonly FLC = 49; public static readonly GLC = 50; public static readonly HLC = 51; public static readonly ILC = 52; public static readonly JLC = 53; public static readonly KLC = 54; public static readonly LLC = 55; public static readonly MLC = 56; public static readonly NLC = 57; public static readonly OLC = 58; public static readonly PLC = 59; public static readonly QLC = 60; public static readonly RLC = 61; public static readonly SLC = 62; public static readonly TLC = 63; public static readonly ULC = 64; public static readonly VLC = 65; public static readonly WLC = 66; public static readonly XLC = 67; public static readonly YLC = 68; public static readonly ZLC = 69; public static readonly AUC = 70; public static readonly BUC = 71; public static readonly CUC = 72; public static readonly DUC = 73; public static readonly EUC = 74; public static readonly FUC = 75; public static readonly GUC = 76; public static readonly HUC = 77; public static readonly IUC = 78; public static readonly JUC = 79; public static readonly KUC = 80; public static readonly LUC = 81; public static readonly MUC = 82; public static readonly NUC = 83; public static readonly OUC = 84; public static readonly PUC = 85; public static readonly QUC = 86; public static readonly RUC = 87; public static readonly SUC = 88; public static readonly TUC = 89; public static readonly UUC = 90; public static readonly VUC = 91; public static readonly WUC = 92; public static readonly XUC = 93; public static readonly YUC = 94; public static readonly ZUC = 95; public static readonly D1 = 96; public static readonly D2 = 97; public static readonly D3 = 98; public static readonly D4 = 99; public static readonly D5 = 100; public static readonly D6 = 101; public static readonly D7 = 102; public static readonly D8 = 103; public static readonly D9 = 104; public static readonly D0 = 105; public static readonly OtherChar = 106; // tslint:disable:no-trailing-whitespace public static readonly channelNames: string[] = [ "DEFAULT_TOKEN_CHANNEL", "HIDDEN", ]; // tslint:disable:no-trailing-whitespace public static readonly modeNames: string[] = [ "DEFAULT_MODE", ]; public static readonly ruleNames: string[] = [ "Quoted", "BlockQuoted", "BellChar", "ControlChar", "EscapeChar", "FormFeed", "NewLine", "CarriageReturn", "Tab", "Backslash", "HexChar", "Dot", "DecimalDigit", "NotDecimalDigit", "CharWithProperty", "CharWithoutProperty", "WhiteSpace", "NotWhiteSpace", "WordChar", "NotWordChar", "CharacterClassStart", "CharacterClassEnd", "Caret", "Hyphen", "QuestionMark", "Plus", "Star", "OpenBrace", "CloseBrace", "Comma", "EndOfSubject", "Pipe", "OpenParen", "CloseParen", "LessThan", "GreaterThan", "SingleQuote", "Underscore", "Colon", "Hash", "Equals", "Exclamation", "Ampersand", "ALC", "BLC", "CLC", "DLC", "ELC", "FLC", "GLC", "HLC", "ILC", "JLC", "KLC", "LLC", "MLC", "NLC", "OLC", "PLC", "QLC", "RLC", "SLC", "TLC", "ULC", "VLC", "WLC", "XLC", "YLC", "ZLC", "AUC", "BUC", "CUC", "DUC", "EUC", "FUC", "GUC", "HUC", "IUC", "JUC", "KUC", "LUC", "MUC", "NUC", "OUC", "PUC", "QUC", "RUC", "SUC", "TUC", "UUC", "VUC", "WUC", "XUC", "YUC", "ZUC", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "D0", "OtherChar", "UnderscoreAlphaNumerics", "AlphaNumerics", "AlphaNumeric", "NonAlphaNumeric", "HexDigit", "ASCII", ]; private static readonly _LITERAL_NAMES: Array<string | undefined> = [ undefined, undefined, undefined, "'\\'", "'\\'", "'\\'", "'\\'", "'\\'", "'\\'", "'\\'", "'\\'", undefined, "'.'", "'\\'", "'\\'", undefined, undefined, "'\\'", "'\\'", "'\\'", "'\\'", "'['", "']'", "'^'", "'-'", "'?'", "'+'", "'*'", "'{'", "'}'", "','", "'$'", "'|'", "'('", "')'", "'<'", "'>'", "'''", "'_'", "':'", "'#'", "'='", "'!'", "'&'", "'a'", "'b'", "'c'", "'d'", "'e'", "'f'", "'g'", "'h'", "'i'", "'j'", "'k'", "'l'", "'m'", "'n'", "'o'", "'p'", "'q'", "'r'", "'s'", "'t'", "'u'", "'v'", "'w'", "'x'", "'y'", "'z'", "'A'", "'B'", "'C'", "'D'", "'E'", "'F'", "'G'", "'H'", "'I'", "'J'", "'K'", "'L'", "'M'", "'N'", "'O'", "'P'", "'Q'", "'R'", "'S'", "'T'", "'U'", "'V'", "'W'", "'X'", "'Y'", "'Z'", "'1'", "'2'", "'3'", "'4'", "'5'", "'6'", "'7'", "'8'", "'9'", "'0'", ]; private static readonly _SYMBOLIC_NAMES: Array<string | undefined> = [ undefined, "Quoted", "BlockQuoted", "BellChar", "ControlChar", "EscapeChar", "FormFeed", "NewLine", "CarriageReturn", "Tab", "Backslash", "HexChar", "Dot", "DecimalDigit", "NotDecimalDigit", "CharWithProperty", "CharWithoutProperty", "WhiteSpace", "NotWhiteSpace", "WordChar", "NotWordChar", "CharacterClassStart", "CharacterClassEnd", "Caret", "Hyphen", "QuestionMark", "Plus", "Star", "OpenBrace", "CloseBrace", "Comma", "EndOfSubject", "Pipe", "OpenParen", "CloseParen", "LessThan", "GreaterThan", "SingleQuote", "Underscore", "Colon", "Hash", "Equals", "Exclamation", "Ampersand", "ALC", "BLC", "CLC", "DLC", "ELC", "FLC", "GLC", "HLC", "ILC", "JLC", "KLC", "LLC", "MLC", "NLC", "OLC", "PLC", "QLC", "RLC", "SLC", "TLC", "ULC", "VLC", "WLC", "XLC", "YLC", "ZLC", "AUC", "BUC", "CUC", "DUC", "EUC", "FUC", "GUC", "HUC", "IUC", "JUC", "KUC", "LUC", "MUC", "NUC", "OUC", "PUC", "QUC", "RUC", "SUC", "TUC", "UUC", "VUC", "WUC", "XUC", "YUC", "ZUC", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "D0", "OtherChar", ]; public static readonly VOCABULARY: Vocabulary = new VocabularyImpl(CommonRegexLexer._LITERAL_NAMES, CommonRegexLexer._SYMBOLIC_NAMES, []); // @Override // @NotNull public get vocabulary(): Vocabulary { return CommonRegexLexer.VOCABULARY; } // tslint:enable:no-trailing-whitespace constructor(input: CharStream) { super(input); this._interp = new LexerATNSimulator(CommonRegexLexer._ATN, this); } // @Override public get grammarFileName(): string { return "CommonRegex.g4"; } // @Override public get ruleNames(): string[] { return CommonRegexLexer.ruleNames; } // @Override public get serializedATN(): string { return CommonRegexLexer._serializedATN; } // @Override public get channelNames(): string[] { return CommonRegexLexer.channelNames; } // @Override public get modeNames(): string[] { return CommonRegexLexer.modeNames; } public static readonly _serializedATN: string = "\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x02l\u01FC\b\x01" + "\x04\x02\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06" + "\x04\x07\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f\x04\r" + "\t\r\x04\x0E\t\x0E\x04\x0F\t\x0F\x04\x10\t\x10\x04\x11\t\x11\x04\x12\t" + "\x12\x04\x13\t\x13\x04\x14\t\x14\x04\x15\t\x15\x04\x16\t\x16\x04\x17\t" + "\x17\x04\x18\t\x18\x04\x19\t\x19\x04\x1A\t\x1A\x04\x1B\t\x1B\x04\x1C\t" + "\x1C\x04\x1D\t\x1D\x04\x1E\t\x1E\x04\x1F\t\x1F\x04 \t \x04!\t!\x04\"\t" + "\"\x04#\t#\x04$\t$\x04%\t%\x04&\t&\x04\'\t\'\x04(\t(\x04)\t)\x04*\t*\x04" + "+\t+\x04,\t,\x04-\t-\x04.\t.\x04/\t/\x040\t0\x041\t1\x042\t2\x043\t3\x04" + "4\t4\x045\t5\x046\t6\x047\t7\x048\t8\x049\t9\x04:\t:\x04;\t;\x04<\t<\x04" + "=\t=\x04>\t>\x04?\t?\x04@\t@\x04A\tA\x04B\tB\x04C\tC\x04D\tD\x04E\tE\x04" + "F\tF\x04G\tG\x04H\tH\x04I\tI\x04J\tJ\x04K\tK\x04L\tL\x04M\tM\x04N\tN\x04" + "O\tO\x04P\tP\x04Q\tQ\x04R\tR\x04S\tS\x04T\tT\x04U\tU\x04V\tV\x04W\tW\x04" + "X\tX\x04Y\tY\x04Z\tZ\x04[\t[\x04\\\t\\\x04]\t]\x04^\t^\x04_\t_\x04`\t" + "`\x04a\ta\x04b\tb\x04c\tc\x04d\td\x04e\te\x04f\tf\x04g\tg\x04h\th\x04" + "i\ti\x04j\tj\x04k\tk\x04l\tl\x04m\tm\x04n\tn\x04o\to\x04p\tp\x04q\tq\x03" + "\x02\x03\x02\x03\x02\x03\x03\x03\x03\x03\x03\x03\x03\x07\x03\xEB\n\x03" + "\f\x03\x0E\x03\xEE\v\x03\x03\x03\x03\x03\x03\x03\x03\x04\x03\x04\x03\x04" + "\x03\x05\x03\x05\x03\x05\x03\x06\x03\x06\x03\x06\x03\x07\x03\x07\x03\x07" + "\x03\b\x03\b\x03\b\x03\t\x03\t\x03\t\x03\n\x03\n\x03\n\x03\v\x03\v\x03" + "\f\x03\f\x03\f\x03\f\x03\f\x03\f\x03\f\x03\f\x03\f\x03\f\x06\f\u0114\n" + "\f\r\f\x0E\f\u0115\x03\f\x03\f\x05\f\u011A\n\f\x03\r\x03\r\x03\x0E\x03" + "\x0E\x03\x0E\x03\x0F\x03\x0F\x03\x0F\x03\x10\x03\x10\x03\x10\x03\x10\x03" + "\x10\x03\x10\x03\x10\x03\x11\x03\x11\x03\x11\x03\x11\x03\x11\x03\x11\x03" + "\x11\x03\x12\x03\x12\x03\x12\x03\x13\x03\x13\x03\x13\x03\x14\x03\x14\x03" + "\x14\x03\x15\x03\x15\x03\x15\x03\x16\x03\x16\x03\x17\x03\x17\x03\x18\x03" + "\x18\x03\x19\x03\x19\x03\x1A\x03\x1A\x03\x1B\x03\x1B\x03\x1C\x03\x1C\x03" + "\x1D\x03\x1D\x03\x1E\x03\x1E\x03\x1F\x03\x1F\x03 \x03 \x03!\x03!\x03\"" + "\x03\"\x03#\x03#\x03$\x03$\x03%\x03%\x03&\x03&\x03\'\x03\'\x03(\x03(\x03" + ")\x03)\x03*\x03*\x03+\x03+\x03,\x03,\x03-\x03-\x03.\x03.\x03/\x03/\x03" + "0\x030\x031\x031\x032\x032\x033\x033\x034\x034\x035\x035\x036\x036\x03" + "7\x037\x038\x038\x039\x039\x03:\x03:\x03;\x03;\x03<\x03<\x03=\x03=\x03" + ">\x03>\x03?\x03?\x03@\x03@\x03A\x03A\x03B\x03B\x03C\x03C\x03D\x03D\x03" + "E\x03E\x03F\x03F\x03G\x03G\x03H\x03H\x03I\x03I\x03J\x03J\x03K\x03K\x03" + "L\x03L\x03M\x03M\x03N\x03N\x03O\x03O\x03P\x03P\x03Q\x03Q\x03R\x03R\x03" + "S\x03S\x03T\x03T\x03U\x03U\x03V\x03V\x03W\x03W\x03X\x03X\x03Y\x03Y\x03" + "Z\x03Z\x03[\x03[\x03\\\x03\\\x03]\x03]\x03^\x03^\x03_\x03_\x03`\x03`\x03" + "a\x03a\x03b\x03b\x03c\x03c\x03d\x03d\x03e\x03e\x03f\x03f\x03g\x03g\x03" + "h\x03h\x03i\x03i\x03j\x03j\x03k\x03k\x03l\x03l\x06l\u01EC\nl\rl\x0El\u01ED" + "\x03m\x06m\u01F1\nm\rm\x0Em\u01F2\x03n\x03n\x03o\x03o\x03p\x03p\x03q\x03" + "q\x03\xEC\x02\x02r\x03\x02\x03\x05\x02\x04\x07\x02\x05\t\x02\x06\v\x02" + "\x07\r\x02\b\x0F\x02\t\x11\x02\n\x13\x02\v\x15\x02\f\x17\x02\r\x19\x02" + "\x0E\x1B\x02\x0F\x1D\x02\x10\x1F\x02\x11!\x02\x12#\x02\x13%\x02\x14\'" + "\x02\x15)\x02\x16+\x02\x17-\x02\x18/\x02\x191\x02\x1A3\x02\x1B5\x02\x1C" + "7\x02\x1D9\x02\x1E;\x02\x1F=\x02 ?\x02!A\x02\"C\x02#E\x02$G\x02%I\x02" + "&K\x02\'M\x02(O\x02)Q\x02*S\x02+U\x02,W\x02-Y\x02.[\x02/]\x020_\x021a" + "\x022c\x023e\x024g\x025i\x026k\x027m\x028o\x029q\x02:s\x02;u\x02<w\x02" + "=y\x02>{\x02?}\x02@\x7F\x02A\x81\x02B\x83\x02C\x85\x02D\x87\x02E\x89\x02" + "F\x8B\x02G\x8D\x02H\x8F\x02I\x91\x02J\x93\x02K\x95\x02L\x97\x02M\x99\x02" + "N\x9B\x02O\x9D\x02P\x9F\x02Q\xA1\x02R\xA3\x02S\xA5\x02T\xA7\x02U\xA9\x02" + "V\xAB\x02W\xAD\x02X\xAF\x02Y\xB1\x02Z\xB3\x02[\xB5\x02\\\xB7\x02]\xB9" + "\x02^\xBB\x02_\xBD\x02`\xBF\x02a\xC1\x02b\xC3\x02c\xC5\x02d\xC7\x02e\xC9" + "\x02f\xCB\x02g\xCD\x02h\xCF\x02i\xD1\x02j\xD3\x02k\xD5\x02l\xD7\x02\x02" + "\xD9\x02\x02\xDB\x02\x02\xDD\x02\x02\xDF\x02\x02\xE1\x02\x02\x03\x02\x05" + "\x05\x022;C\\c|\x05\x022;CHch\x03\x02\x02\x81\x02\u01FB\x02\x03\x03\x02" + "\x02\x02\x02\x05\x03\x02\x02\x02\x02\x07\x03\x02\x02\x02\x02\t\x03\x02" + "\x02\x02\x02\v\x03\x02\x02\x02\x02\r\x03\x02\x02\x02\x02\x0F\x03\x02\x02" + "\x02\x02\x11\x03\x02\x02\x02\x02\x13\x03\x02\x02\x02\x02\x15\x03\x02\x02" + "\x02\x02\x17\x03\x02\x02\x02\x02\x19\x03\x02\x02\x02\x02\x1B\x03\x02\x02" + "\x02\x02\x1D\x03\x02\x02\x02\x02\x1F\x03\x02\x02\x02\x02!\x03\x02\x02" + "\x02\x02#\x03\x02\x02\x02\x02%\x03\x02\x02\x02\x02\'\x03\x02\x02\x02\x02" + ")\x03\x02\x02\x02\x02+\x03\x02\x02\x02\x02-\x03\x02\x02\x02\x02/\x03\x02" + "\x02\x02\x021\x03\x02\x02\x02\x023\x03\x02\x02\x02\x025\x03\x02\x02\x02" + "\x027\x03\x02\x02\x02\x029\x03\x02\x02\x02\x02;\x03\x02\x02\x02\x02=\x03" + "\x02\x02\x02\x02?\x03\x02\x02\x02\x02A\x03\x02\x02\x02\x02C\x03\x02\x02" + "\x02\x02E\x03\x02\x02\x02\x02G\x03\x02\x02\x02\x02I\x03\x02\x02\x02\x02" + "K\x03\x02\x02\x02\x02M\x03\x02\x02\x02\x02O\x03\x02\x02\x02\x02Q\x03\x02" + "\x02\x02\x02S\x03\x02\x02\x02\x02U\x03\x02\x02\x02\x02W\x03\x02\x02\x02" + "\x02Y\x03\x02\x02\x02\x02[\x03\x02\x02\x02\x02]\x03\x02\x02\x02\x02_\x03" + "\x02\x02\x02\x02a\x03\x02\x02\x02\x02c\x03\x02\x02\x02\x02e\x03\x02\x02" + "\x02\x02g\x03\x02\x02\x02\x02i\x03\x02\x02\x02\x02k\x03\x02\x02\x02\x02" + "m\x03\x02\x02\x02\x02o\x03\x02\x02\x02\x02q\x03\x02\x02\x02\x02s\x03\x02" + "\x02\x02\x02u\x03\x02\x02\x02\x02w\x03\x02\x02\x02\x02y\x03\x02\x02\x02" + "\x02{\x03\x02\x02\x02\x02}\x03\x02\x02\x02\x02\x7F\x03\x02\x02\x02\x02" + "\x81\x03\x02\x02\x02\x02\x83\x03\x02\x02\x02\x02\x85\x03\x02\x02\x02\x02" + "\x87\x03\x02\x02\x02\x02\x89\x03\x02\x02\x02\x02\x8B\x03\x02\x02\x02\x02" + "\x8D\x03\x02\x02\x02\x02\x8F\x03\x02\x02\x02\x02\x91\x03\x02\x02\x02\x02" + "\x93\x03\x02\x02\x02\x02\x95\x03\x02\x02\x02\x02\x97\x03\x02\x02\x02\x02" + "\x99\x03\x02\x02\x02\x02\x9B\x03\x02\x02\x02\x02\x9D\x03\x02\x02\x02\x02" + "\x9F\x03\x02\x02\x02\x02\xA1\x03\x02\x02\x02\x02\xA3\x03\x02\x02\x02\x02" + "\xA5\x03\x02\x02\x02\x02\xA7\x03\x02\x02\x02\x02\xA9\x03\x02\x02\x02\x02" + "\xAB\x03\x02\x02\x02\x02\xAD\x03\x02\x02\x02\x02\xAF\x03\x02\x02\x02\x02" + "\xB1\x03\x02\x02\x02\x02\xB3\x03\x02\x02\x02\x02\xB5\x03\x02\x02\x02\x02" + "\xB7\x03\x02\x02\x02\x02\xB9\x03\x02\x02\x02\x02\xBB\x03\x02\x02\x02\x02" + "\xBD\x03\x02\x02\x02\x02\xBF\x03\x02\x02\x02\x02\xC1\x03\x02\x02\x02\x02" + "\xC3\x03\x02\x02\x02\x02\xC5\x03\x02\x02\x02\x02\xC7\x03\x02\x02\x02\x02" + "\xC9\x03\x02\x02\x02\x02\xCB\x03\x02\x02\x02\x02\xCD\x03\x02\x02\x02\x02" + "\xCF\x03\x02\x02\x02\x02\xD1\x03\x02\x02\x02\x02\xD3\x03\x02\x02\x02\x02" + "\xD5\x03\x02\x02\x02\x03\xE3\x03\x02\x02\x02\x05\xE6\x03\x02\x02\x02\x07" + "\xF2\x03\x02\x02\x02\t\xF5\x03\x02\x02\x02\v\xF8\x03\x02\x02\x02\r\xFB" + "\x03\x02\x02\x02\x0F\xFE\x03\x02\x02\x02\x11\u0101\x03\x02\x02\x02\x13" + "\u0104\x03\x02\x02\x02\x15\u0107\x03\x02\x02\x02\x17\u0109\x03\x02\x02" + "\x02\x19\u011B\x03\x02\x02\x02\x1B\u011D\x03\x02\x02\x02\x1D\u0120\x03" + "\x02\x02\x02\x1F\u0123\x03\x02\x02\x02!\u012A\x03\x02\x02\x02#\u0131\x03" + "\x02\x02\x02%\u0134\x03\x02\x02\x02\'\u0137\x03\x02\x02\x02)\u013A\x03" + "\x02\x02\x02+\u013D\x03\x02\x02\x02-\u013F\x03\x02\x02\x02/\u0141\x03" + "\x02\x02\x021\u0143\x03\x02\x02\x023\u0145\x03\x02\x02\x025\u0147\x03" + "\x02\x02\x027\u0149\x03\x02\x02\x029\u014B\x03\x02\x02\x02;\u014D\x03" + "\x02\x02\x02=\u014F\x03\x02\x02\x02?\u0151\x03\x02\x02\x02A\u0153\x03" + "\x02\x02\x02C\u0155\x03\x02\x02\x02E\u0157\x03\x02\x02\x02G\u0159\x03" + "\x02\x02\x02I\u015B\x03\x02\x02\x02K\u015D\x03\x02\x02\x02M\u015F\x03" + "\x02\x02\x02O\u0161\x03\x02\x02\x02Q\u0163\x03\x02\x02\x02S\u0165\x03" + "\x02\x02\x02U\u0167\x03\x02\x02\x02W\u0169\x03\x02\x02\x02Y\u016B\x03" + "\x02\x02\x02[\u016D\x03\x02\x02\x02]\u016F\x03\x02\x02\x02_\u0171\x03" + "\x02\x02\x02a\u0173\x03\x02\x02\x02c\u0175\x03\x02\x02\x02e\u0177\x03" + "\x02\x02\x02g\u0179\x03\x02\x02\x02i\u017B\x03\x02\x02\x02k\u017D\x03" + "\x02\x02\x02m\u017F\x03\x02\x02\x02o\u0181\x03\x02\x02\x02q\u0183\x03" + "\x02\x02\x02s\u0185\x03\x02\x02\x02u\u0187\x03\x02\x02\x02w\u0189\x03" + "\x02\x02\x02y\u018B\x03\x02\x02\x02{\u018D\x03\x02\x02\x02}\u018F\x03" + "\x02\x02\x02\x7F\u0191\x03\x02\x02\x02\x81\u0193\x03\x02\x02\x02\x83\u0195" + "\x03\x02\x02\x02\x85\u0197\x03\x02\x02\x02\x87\u0199\x03\x02\x02\x02\x89" + "\u019B\x03\x02\x02\x02\x8B\u019D\x03\x02\x02\x02\x8D\u019F\x03\x02\x02" + "\x02\x8F\u01A1\x03\x02\x02\x02\x91\u01A3\x03\x02\x02\x02\x93\u01A5\x03" + "\x02\x02\x02\x95\u01A7\x03\x02\x02\x02\x97\u01A9\x03\x02\x02\x02\x99\u01AB" + "\x03\x02\x02\x02\x9B\u01AD\x03\x02\x02\x02\x9D\u01AF\x03\x02\x02\x02\x9F" + "\u01B1\x03\x02\x02\x02\xA1\u01B3\x03\x02\x02\x02\xA3\u01B5\x03\x02\x02" + "\x02\xA5\u01B7\x03\x02\x02\x02\xA7\u01B9\x03\x02\x02\x02\xA9\u01BB\x03" + "\x02\x02\x02\xAB\u01BD\x03\x02\x02\x02\xAD\u01BF\x03\x02\x02\x02\xAF\u01C1" + "\x03\x02\x02\x02\xB1\u01C3\x03\x02\x02\x02\xB3\u01C5\x03\x02\x02\x02\xB5" + "\u01C7\x03\x02\x02\x02\xB7\u01C9\x03\x02\x02\x02\xB9\u01CB\x03\x02\x02" + "\x02\xBB\u01CD\x03\x02\x02\x02\xBD\u01CF\x03\x02\x02\x02\xBF\u01D1\x03" + "\x02\x02\x02\xC1\u01D3\x03\x02\x02\x02\xC3\u01D5\x03\x02\x02\x02\xC5\u01D7" + "\x03\x02\x02\x02\xC7\u01D9\x03\x02\x02\x02\xC9\u01DB\x03\x02\x02\x02\xCB" + "\u01DD\x03\x02\x02\x02\xCD\u01DF\x03\x02\x02\x02\xCF\u01E1\x03\x02\x02" + "\x02\xD1\u01E3\x03\x02\x02\x02\xD3\u01E5\x03\x02\x02\x02\xD5\u01E7\x03" + "\x02\x02\x02\xD7\u01EB\x03\x02\x02\x02\xD9\u01F0\x03\x02\x02\x02\xDB\u01F4" + "\x03\x02\x02\x02\xDD\u01F6\x03\x02\x02\x02\xDF\u01F8\x03\x02\x02\x02\xE1" + "\u01FA\x03\x02\x02\x02\xE3\xE4\x07^\x02\x02\xE4\xE5\x05\xDDo\x02\xE5\x04" + "\x03\x02\x02\x02\xE6\xE7\x07^\x02\x02\xE7\xE8\x07S\x02\x02\xE8\xEC\x03" + "\x02\x02\x02\xE9\xEB\v\x02\x02\x02\xEA\xE9\x03\x02\x02\x02\xEB\xEE\x03" + "\x02\x02\x02\xEC\xED\x03\x02\x02\x02\xEC\xEA\x03\x02\x02\x02\xED\xEF\x03" + "\x02\x02\x02\xEE\xEC\x03\x02\x02\x02\xEF\xF0\x07^\x02\x02\xF0\xF1\x07" + "G\x02\x02\xF1\x06\x03\x02\x02\x02\xF2\xF3\x07^\x02\x02\xF3\xF4\x07c\x02" + "\x02\xF4\b\x03\x02\x02\x02\xF5\xF6\x07^\x02\x02\xF6\xF7\x07e\x02\x02\xF7" + "\n\x03\x02\x02\x02\xF8\xF9\x07^\x02\x02\xF9\xFA\x07g\x02\x02\xFA\f\x03" + "\x02\x02\x02\xFB\xFC\x07^\x02\x02\xFC\xFD\x07h\x02\x02\xFD\x0E\x03\x02" + "\x02\x02\xFE\xFF\x07^\x02\x02\xFF\u0100\x07p\x02\x02\u0100\x10\x03\x02" + "\x02\x02\u0101\u0102\x07^\x02\x02\u0102\u0103\x07t\x02\x02\u0103\x12\x03" + "\x02\x02\x02\u0104\u0105\x07^\x02\x02\u0105\u0106\x07v\x02\x02\u0106\x14" + "\x03\x02\x02\x02\u0107\u0108\x07^\x02\x02\u0108\x16\x03\x02\x02\x02\u0109" + "\u010A\x07^\x02\x02\u010A\u010B\x07z\x02\x02\u010B\u0119\x03\x02\x02\x02" + "\u010C\u010D\x05\xDFp\x02\u010D\u010E\x05\xDFp\x02\u010E\u011A\x03\x02" + "\x02\x02\u010F\u0110\x07}\x02\x02\u0110\u0111\x05\xDFp\x02\u0111\u0113" + "\x05\xDFp\x02\u0112\u0114\x05\xDFp\x02\u0113\u0112\x03\x02\x02\x02\u0114" + "\u0115\x03\x02\x02\x02\u0115\u0113\x03\x02\x02\x02\u0115\u0116\x03\x02" + "\x02\x02\u0116\u0117\x03\x02\x02\x02\u0117\u0118\x07\x7F\x02\x02\u0118" + "\u011A\x03\x02\x02\x02\u0119\u010C\x03\x02\x02\x02\u0119\u010F\x03\x02" + "\x02\x02\u011A\x18\x03\x02\x02\x02\u011B\u011C\x070\x02\x02\u011C\x1A" + "\x03\x02\x02\x02\u011D\u011E\x07^\x02\x02\u011E\u011F\x07f\x02\x02\u011F" + "\x1C\x03\x02\x02\x02\u0120\u0121\x07^\x02\x02\u0121\u0122\x07F\x02\x02" + "\u0122\x1E\x03\x02\x02\x02\u0123\u0124\x07^\x02\x02\u0124\u0125\x07r\x02" + "\x02\u0125\u0126\x07}\x02\x02\u0126\u0127\x03\x02\x02\x02\u0127\u0128" + "\x05\xD7l\x02\u0128\u0129\x07\x7F\x02\x02\u0129 \x03\x02\x02\x02\u012A" + "\u012B\x07^\x02\x02\u012B\u012C\x07R\x02\x02\u012C\u012D\x07}\x02\x02" + "\u012D\u012E\x03\x02\x02\x02\u012E\u012F\x05\xD7l\x02\u012F\u0130\x07" + "\x7F\x02\x02\u0130\"\x03\x02\x02\x02\u0131\u0132\x07^\x02\x02\u0132\u0133" + "\x07u\x02\x02\u0133$\x03\x02\x02\x02\u0134\u0135\x07^\x02\x02\u0135\u0136" + "\x07U\x02\x02\u0136&\x03\x02\x02\x02\u0137\u0138\x07^\x02\x02\u0138\u0139" + "\x07y\x02\x02\u0139(\x03\x02\x02\x02\u013A\u013B\x07^\x02\x02\u013B\u013C" + "\x07Y\x02\x02\u013C*\x03\x02\x02\x02\u013D\u013E\x07]\x02\x02\u013E,\x03" + "\x02\x02\x02\u013F\u0140\x07_\x02\x02\u0140.\x03\x02\x02\x02\u0141\u0142" + "\x07`\x02\x02\u01420\x03\x02\x02\x02\u0143\u0144\x07/\x02\x02\u01442\x03" + "\x02\x02\x02\u0145\u0146\x07A\x02\x02\u01464\x03\x02\x02\x02\u0147\u0148" + "\x07-\x02\x02\u01486\x03\x02\x02\x02\u0149\u014A\x07,\x02\x02\u014A8\x03" + "\x02\x02\x02\u014B\u014C\x07}\x02\x02\u014C:\x03\x02\x02\x02\u014D\u014E" + "\x07\x7F\x02\x02\u014E<\x03\x02\x02\x02\u014F\u0150\x07.\x02\x02\u0150" + ">\x03\x02\x02\x02\u0151\u0152\x07&\x02\x02\u0152@\x03\x02\x02\x02\u0153" + "\u0154\x07~\x02\x02\u0154B\x03\x02\x02\x02\u0155\u0156\x07*\x02\x02\u0156" + "D\x03\x02\x02\x02\u0157\u0158\x07+\x02\x02\u0158F\x03\x02\x02\x02\u0159" + "\u015A\x07>\x02\x02\u015AH\x03\x02\x02\x02\u015B\u015C\x07@\x02\x02\u015C" + "J\x03\x02\x02\x02\u015D\u015E\x07)\x02\x02\u015EL\x03\x02\x02\x02\u015F" + "\u0160\x07a\x02\x02\u0160N\x03\x02\x02\x02\u0161\u0162\x07<\x02\x02\u0162" + "P\x03\x02\x02\x02\u0163\u0164\x07%\x02\x02\u0164R\x03\x02\x02\x02\u0165" + "\u0166\x07?\x02\x02\u0166T\x03\x02\x02\x02\u0167\u0168\x07#\x02\x02\u0168" + "V\x03\x02\x02\x02\u0169\u016A\x07(\x02\x02\u016AX\x03\x02\x02\x02\u016B" + "\u016C\x07c\x02\x02\u016CZ\x03\x02\x02\x02\u016D\u016E\x07d\x02\x02\u016E" + "\\\x03\x02\x02\x02\u016F\u0170\x07e\x02\x02\u0170^\x03\x02\x02\x02\u0171" + "\u0172\x07f\x02\x02\u0172`\x03\x02\x02\x02\u0173\u0174\x07g\x02\x02\u0174" + "b\x03\x02\x02\x02\u0175\u0176\x07h\x02\x02\u0176d\x03\x02\x02\x02\u0177" + "\u0178\x07i\x02\x02\u0178f\x03\x02\x02\x02\u0179\u017A\x07j\x02\x02\u017A" + "h\x03\x02\x02\x02\u017B\u017C\x07k\x02\x02\u017Cj\x03\x02\x02\x02\u017D" + "\u017E\x07l\x02\x02\u017El\x03\x02\x02\x02\u017F\u0180\x07m\x02\x02\u0180" + "n\x03\x02\x02\x02\u0181\u0182\x07n\x02\x02\u0182p\x03\x02\x02\x02\u0183" + "\u0184\x07o\x02\x02\u0184r\x03\x02\x02\x02\u0185\u0186\x07p\x02\x02\u0186" + "t\x03\x02\x02\x02\u0187\u0188\x07q\x02\x02\u0188v\x03\x02\x02\x02\u0189" + "\u018A\x07r\x02\x02\u018Ax\x03\x02\x02\x02\u018B\u018C\x07s\x02\x02\u018C" + "z\x03\x02\x02\x02\u018D\u018E\x07t\x02\x02\u018E|\x03\x02\x02\x02\u018F" + "\u0190\x07u\x02\x02\u0190~\x03\x02\x02\x02\u0191\u0192\x07v\x02\x02\u0192" + "\x80\x03\x02\x02\x02\u0193\u0194\x07w\x02\x02\u0194\x82\x03\x02\x02\x02" + "\u0195\u0196\x07x\x02\x02\u0196\x84\x03\x02\x02\x02\u0197\u0198\x07y\x02" + "\x02\u0198\x86\x03\x02\x02\x02\u0199\u019A\x07z\x02\x02\u019A\x88\x03" + "\x02\x02\x02\u019B\u019C\x07{\x02\x02\u019C\x8A\x03\x02\x02\x02\u019D" + "\u019E\x07|\x02\x02\u019E\x8C\x03\x02\x02\x02\u019F\u01A0\x07C\x02\x02" + "\u01A0\x8E\x03\x02\x02\x02\u01A1\u01A2\x07D\x02\x02\u01A2\x90\x03\x02" + "\x02\x02\u01A3\u01A4\x07E\x02\x02\u01A4\x92\x03\x02\x02\x02\u01A5\u01A6" + "\x07F\x02\x02\u01A6\x94\x03\x02\x02\x02\u01A7\u01A8\x07G\x02\x02\u01A8" + "\x96\x03\x02\x02\x02\u01A9\u01AA\x07H\x02\x02\u01AA\x98\x03\x02\x02\x02" + "\u01AB\u01AC\x07I\x02\x02\u01AC\x9A\x03\x02\x02\x02\u01AD\u01AE\x07J\x02" + "\x02\u01AE\x9C\x03\x02\x02\x02\u01AF\u01B0\x07K\x02\x02\u01B0\x9E\x03" + "\x02\x02\x02\u01B1\u01B2\x07L\x02\x02\u01B2\xA0\x03\x02\x02\x02\u01B3" + "\u01B4\x07M\x02\x02\u01B4\xA2\x03\x02\x02\x02\u01B5\u01B6\x07N\x02\x02" + "\u01B6\xA4\x03\x02\x02\x02\u01B7\u01B8\x07O\x02\x02\u01B8\xA6\x03\x02" + "\x02\x02\u01B9\u01BA\x07P\x02\x02\u01BA\xA8\x03\x02\x02\x02\u01BB\u01BC" + "\x07Q\x02\x02\u01BC\xAA\x03\x02\x02\x02\u01BD\u01BE\x07R\x02\x02\u01BE" + "\xAC\x03\x02\x02\x02\u01BF\u01C0\x07S\x02\x02\u01C0\xAE\x03\x02\x02\x02" + "\u01C1\u01C2\x07T\x02\x02\u01C2\xB0\x03\x02\x02\x02\u01C3\u01C4\x07U\x02" + "\x02\u01C4\xB2\x03\x02\x02\x02\u01C5\u01C6\x07V\x02\x02\u01C6\xB4\x03" + "\x02\x02\x02\u01C7\u01C8\x07W\x02\x02\u01C8\xB6\x03\x02\x02\x02\u01C9" + "\u01CA\x07X\x02\x02\u01CA\xB8\x03\x02\x02\x02\u01CB\u01CC\x07Y\x02\x02" + "\u01CC\xBA\x03\x02\x02\x02\u01CD\u01CE\x07Z\x02\x02\u01CE\xBC\x03\x02" + "\x02\x02\u01CF\u01D0\x07[\x02\x02\u01D0\xBE\x03\x02\x02\x02\u01D1\u01D2" + "\x07\\\x02\x02\u01D2\xC0\x03\x02\x02\x02\u01D3\u01D4\x073\x02\x02\u01D4" + "\xC2\x03\x02\x02\x02\u01D5\u01D6\x074\x02\x02\u01D6\xC4\x03\x02\x02\x02" + "\u01D7\u01D8\x075\x02\x02\u01D8\xC6\x03\x02\x02\x02\u01D9\u01DA\x076\x02" + "\x02\u01DA\xC8\x03\x02\x02\x02\u01DB\u01DC\x077\x02\x02\u01DC\xCA\x03" + "\x02\x02\x02\u01DD\u01DE\x078\x02\x02\u01DE\xCC\x03\x02\x02\x02\u01DF" + "\u01E0\x079\x02\x02\u01E0\xCE\x03\x02\x02\x02\u01E1\u01E2\x07:\x02\x02" + "\u01E2\xD0\x03\x02\x02\x02\u01E3\u01E4\x07;\x02\x02\u01E4\xD2\x03\x02" + "\x02\x02\u01E5\u01E6\x072\x02\x02\u01E6\xD4\x03\x02\x02\x02\u01E7\u01E8" + "\v\x02\x02\x02\u01E8\xD6\x03\x02\x02\x02\u01E9\u01EC\x07a\x02\x02\u01EA" + "\u01EC\x05\xDBn\x02\u01EB\u01E9\x03\x02\x02\x02\u01EB\u01EA\x03\x02\x02" + "\x02\u01EC\u01ED\x03\x02\x02\x02\u01ED\u01EB\x03\x02\x02\x02\u01ED\u01EE" + "\x03\x02\x02\x02\u01EE\xD8\x03\x02\x02\x02\u01EF\u01F1\x05\xDBn\x02\u01F0" + "\u01EF\x03\x02\x02\x02\u01F1\u01F2\x03\x02\x02\x02\u01F2\u01F0\x03\x02" + "\x02\x02\u01F2\u01F3\x03\x02\x02\x02\u01F3\xDA\x03\x02\x02\x02\u01F4\u01F5" + "\t\x02\x02\x02\u01F5\xDC\x03\x02\x02\x02\u01F6\u01F7\n\x02\x02\x02\u01F7" + "\xDE\x03\x02\x02\x02\u01F8\u01F9\t\x03\x02\x02\u01F9\xE0\x03\x02\x02\x02" + "\u01FA\u01FB\t\x04\x02\x02\u01FB\xE2\x03\x02\x02\x02\t\x02\xEC\u0115\u0119" + "\u01EB\u01ED\u01F2\x02"; public static __ATN: ATN; public static get _ATN(): ATN { if (!CommonRegexLexer.__ATN) { CommonRegexLexer.__ATN = new ATNDeserializer().deserialize(Utils.toCharArray(CommonRegexLexer._serializedATN)); } return CommonRegexLexer.__ATN; } }
the_stack
import { DecorationOptions, Range, TextEditorDecorationType, ThemableDecorationRenderOptions, ThemeColor, window, } from "vscode"; export interface VimHighlightUIAttributes { foreground?: number; background?: number; special?: number; reverse?: boolean; italic?: boolean; bold?: boolean; strikethrough?: boolean; // has special color underline?: boolean; // has special color undercurl?: boolean; blend?: number; } export interface HighlightConfiguration { /** * Ignore highlights */ ignoreHighlights: string[]; /** * What to do on unknown highlights. Either accept vim or use vscode decorator configuration */ unknownHighlight: "vim" | ThemableDecorationRenderOptions; /** * Map specific highlight to use either vim configuration or use vscode decorator configuration */ highlights: { [key: string]: "vim" | ThemableDecorationRenderOptions; }; } export interface HightlightExtMark { hlId: number; /** * mapping with virt_text_pos on ext_mark in neovim * currently support overylay option */ virtTextPos?: "overlay" | "right_align" | "eol"; virtText?: string; overlayPos?: number; line?: string; } /** * Convert VIM HL attributes to vscode text decoration attributes * @param uiAttrs VIM UI attribute * @param vimSpecialColor Vim special color */ function vimHighlightToVSCodeOptions(uiAttrs: VimHighlightUIAttributes): ThemableDecorationRenderOptions { const options: ThemableDecorationRenderOptions = {}; // for absent color keys color should not be changed if (uiAttrs.background) { options.backgroundColor = "#" + uiAttrs.background.toString(16); } if (uiAttrs.foreground) { options.color = "#" + uiAttrs.foreground.toString(16); } const specialColor = uiAttrs.special ? "#" + uiAttrs.special.toString(16) : ""; if (uiAttrs.reverse) { options.backgroundColor = new ThemeColor("editor.foreground"); options.color = new ThemeColor("editor.background"); } if (uiAttrs.italic) { options.fontStyle = "italic"; } if (uiAttrs.bold) { options.fontWeight = "bold"; } if (uiAttrs.strikethrough) { options.textDecoration = "line-through solid"; } if (uiAttrs.underline) { options.textDecoration = `underline ${specialColor} solid`; } if (uiAttrs.undercurl) { options.textDecoration = `underline ${specialColor} wavy`; } return options; } function isEditorThemeColor(s: string | ThemeColor | undefined): s is string { return typeof s === "string" && s.startsWith("theme."); } function normalizeDecorationConfig(config: ThemableDecorationRenderOptions): ThemableDecorationRenderOptions { const newConfig: ThemableDecorationRenderOptions = { ...config, after: config.after ? { ...config.after } : undefined, before: config.before ? { ...config.before } : undefined, }; if (isEditorThemeColor(newConfig.backgroundColor)) { newConfig.backgroundColor = new ThemeColor(newConfig.backgroundColor.slice(6)); } if (isEditorThemeColor(newConfig.borderColor)) { newConfig.borderColor = new ThemeColor(newConfig.borderColor.slice(6)); } if (isEditorThemeColor(newConfig.color)) { newConfig.borderColor = new ThemeColor(newConfig.color.slice(6)); } if (isEditorThemeColor(newConfig.outlineColor)) { newConfig.outlineColor = new ThemeColor(newConfig.outlineColor.slice(6)); } if (isEditorThemeColor(newConfig.overviewRulerColor)) { newConfig.overviewRulerColor = new ThemeColor(newConfig.overviewRulerColor.slice(6)); } if (newConfig.after) { if (isEditorThemeColor(newConfig.after.backgroundColor)) { newConfig.after.backgroundColor = new ThemeColor(newConfig.after.backgroundColor.slice(6)); } if (isEditorThemeColor(newConfig.after.borderColor)) { newConfig.after.borderColor = new ThemeColor(newConfig.after.borderColor.slice(6)); } if (isEditorThemeColor(newConfig.after.color)) { newConfig.after.color = new ThemeColor(newConfig.after.color.slice(6)); } } if (newConfig.before) { if (isEditorThemeColor(newConfig.before.backgroundColor)) { newConfig.before.backgroundColor = new ThemeColor(newConfig.before.backgroundColor.slice(6)); } if (isEditorThemeColor(newConfig.before.borderColor)) { newConfig.before.borderColor = new ThemeColor(newConfig.before.borderColor.slice(6)); } if (isEditorThemeColor(newConfig.before.color)) { newConfig.before.color = new ThemeColor(newConfig.before.color.slice(6)); } } return newConfig; } export class HighlightProvider { /** * Current HL. key is the grid id and values is two dimension array representing rows and cols. Array may contain empty values */ private highlights: Map<number, HightlightExtMark[][]> = new Map(); private prevGridHighlightsIds: Map<number, Set<string>> = new Map(); /** * Maps highlight id to highlight group name */ private highlightIdToGroupName: Map<number, string> = new Map(); /** * HL group name to text decorator * Not all HL groups are supported now */ private highlighGroupToDecorator: Map<string, TextEditorDecorationType> = new Map(); /** * Store configuration per decorator */ private decoratorConfigurations: Map<TextEditorDecorationType, ThemableDecorationRenderOptions> = new Map(); private configuration: HighlightConfiguration; /** * Set of ignored HL group ids. They can still be used with force flag (mainly for statusbar color decorations) */ private ignoredGroupIds: Set<number> = new Set(); /** * List of always ignored groups */ private alwaysIgnoreGroups = [ "Normal", "NormalNC", "NormalFloat", "NonText", "SpecialKey", "TermCursor", "TermCursorNC", "Cursor", "lCursor", "VisualNC", // "Visual", "Conceal", "CursorLine", "CursorLineNr", "ColorColumn", "LineNr", "StatusLine", "StatusLineNC", "VertSplit", "Title", "WildMenu", "Whitespace", ]; public constructor(conf: HighlightConfiguration) { this.configuration = conf; if (this.configuration.unknownHighlight !== "vim") { this.configuration.unknownHighlight = normalizeDecorationConfig(this.configuration.unknownHighlight); } for (const [key, config] of Object.entries(this.configuration.highlights)) { if (config !== "vim") { const options = normalizeDecorationConfig(config); this.configuration.highlights[key] = options; // precreate groups if configuration was defined this.createDecoratorForHighlightGroup(key, options); } } } public addHighlightGroup(id: number, name: string, vimUiAttrs: VimHighlightUIAttributes): void { if ( this.configuration.ignoreHighlights.includes(name) || this.configuration.ignoreHighlights.find((i) => i.startsWith("^") || i.endsWith("$") ? new RegExp(i).test(name) : false, ) ) { this.ignoredGroupIds.add(id); } this.highlightIdToGroupName.set(id, name); if (this.highlighGroupToDecorator.has(name)) { // we have already precreated decorator return; } else { const options = this.configuration.highlights[name] || this.configuration.unknownHighlight; const conf = options === "vim" ? vimHighlightToVSCodeOptions(vimUiAttrs) : options; this.createDecoratorForHighlightGroup(name, conf); } } public getHighlightGroupName(id: number, force = false): string | undefined { if (this.ignoredGroupIds.has(id) && !force) { return; } const name = this.highlightIdToGroupName.get(id); if (name && this.alwaysIgnoreGroups.includes(name)) { return; } return name; } public getDecoratorForHighlightGroup(name: string): TextEditorDecorationType | undefined { let dec = this.highlighGroupToDecorator.get(name); if (!dec && name.endsWith("Default")) { dec = this.highlighGroupToDecorator.get(name.slice(0, -7)); } if (!dec) { dec = this.highlighGroupToDecorator.get(name + "Default"); } return dec; } public getDecoratorOptions(decorator: TextEditorDecorationType): ThemableDecorationRenderOptions { return this.decoratorConfigurations.get(decorator)!; } public cleanRow(grid: number, row: number): void { const gridHl = this.highlights.get(grid); if (!gridHl) { return; } delete gridHl[row]; } public processHLCellsEvent( grid: number, row: number, start: number, lineText: string, external: boolean, cells: [string, number?, number?][], ): boolean { let cellHlId = 0; let cellIdx = start; if (!this.highlights.has(grid)) { this.highlights.set(grid, []); } const gridHl = this.highlights.get(grid)!; let hasUpdates = false; for (const [text, hlId, repeat] of cells) { // 2+bytes chars (such as chinese characters) have "" as second cell if (text === "") { continue; } // tab fill character if (text === "♥") { continue; } if (hlId != null) { cellHlId = hlId; } const groupName = this.getHighlightGroupName(cellHlId, external); const listCharsTab = "❥"; const repeatTo = text === "\t" || text === listCharsTab ? 1 : repeat || 1; // const repeatTo = // text === "\t" || line[cellIdx] === "\t" ? Math.ceil((repeat || tabSize) / tabSize) : repeat || 1; for (let i = 0; i < repeatTo; i++) { if (!gridHl[row]) { gridHl[row] = []; } if (groupName) { hasUpdates = true; const hlDeco: HightlightExtMark = { hlId: cellHlId, }; const curChar = lineText.slice(cellIdx, cellIdx + text.length); // text is not same as the cell text on buffer if (curChar != text && text != " " && text != "" && text != listCharsTab) { hlDeco.virtText = text; hlDeco.virtTextPos = "overlay"; hlDeco.overlayPos = lineText.length > 0 ? cellIdx : 1; } gridHl[row][cellIdx] = hlDeco; } else if (gridHl[row][cellIdx]) { hasUpdates = true; delete gridHl[row][cellIdx]; } cellIdx++; } } return hasUpdates; } public shiftGridHighlights(grid: number, by: number, from: number): void { const gridHl = this.highlights.get(grid); if (!gridHl) { return; } if (by > 0) { // remove clipped out rows for (let i = 0; i < by; i++) { delete gridHl[from + i]; } // first get non empty indexes, then process, seems faster than iterating whole array const idxs: number[] = []; gridHl.forEach((_row, idx) => { idxs.push(idx); }); // shift for (const idx of idxs) { if (idx <= from) { continue; } gridHl[idx - by] = gridHl[idx]; delete gridHl[idx]; } } else if (by < 0) { // remove clipped out rows for (let i = 0; i < Math.abs(by); i++) { delete gridHl[from !== 0 ? from + i : gridHl.length - 1 - i]; } const idxs: number[] = []; gridHl.forEach((_row, idx) => { idxs.push(idx); }); for (const idx of idxs.reverse()) { if (idx <= from) { continue; } gridHl[idx + Math.abs(by)] = gridHl[idx]; delete gridHl[idx]; } } } public getGridHighlights(grid: number, topLine: number): [TextEditorDecorationType, DecorationOptions[]][] { const result: [TextEditorDecorationType, DecorationOptions[]][] = []; const hlRanges: Map< string, Array<{ lineS: number; lineE: number; colS: number; colE: number; hl?: HightlightExtMark }> > = new Map(); const gridHl = this.highlights.get(grid); if (gridHl) { // let currHlId = 0; let currHlName = ""; let currHlStartRow = 0; let currHlEndRow = 0; let currHlStartCol = 0; let currHlEndCol = 0; // forEach faster than for in/of for arrays while iterating on array with empty values gridHl.forEach((rowHighlights, rowIdx) => { rowHighlights.forEach((hlDeco, cellIdx) => { const cellHlName = this.highlightIdToGroupName.get(hlDeco.hlId); if (cellHlName && hlDeco.virtTextPos === "overlay") { if (!hlRanges.has(cellHlName)) { hlRanges.set(cellHlName, []); } // it only has one character we don't need group like normal highlight hlRanges.get(cellHlName)!.push({ lineS: rowIdx, lineE: rowIdx, colS: hlDeco.overlayPos || cellIdx, colE: cellIdx + 1, hl: hlDeco, }); return; } if ( cellHlName && currHlName === cellHlName && // allow to extend prev HL if on same row and next cell OR previous row and end of range is end col currHlEndRow === rowIdx && currHlEndCol === cellIdx - 1 ) { currHlEndCol = cellIdx; } else { if (currHlName) { if (!hlRanges.has(currHlName)) { hlRanges.set(currHlName, []); } hlRanges.get(currHlName)!.push({ lineS: currHlStartRow, lineE: currHlEndRow, colS: currHlStartCol, colE: currHlEndCol, }); currHlName = ""; currHlStartCol = 0; currHlEndCol = 0; currHlStartRow = 0; currHlEndRow = 0; } if (cellHlName) { currHlName = cellHlName; currHlStartRow = rowIdx; currHlEndRow = rowIdx; currHlStartCol = cellIdx; currHlEndCol = cellIdx; } } }); }); if (currHlName) { if (!hlRanges.has(currHlName)) { hlRanges.set(currHlName, []); } hlRanges.get(currHlName)!.push({ lineS: currHlStartRow, lineE: currHlEndRow, colS: currHlStartCol, colE: currHlEndCol, }); } } for (const [groupName, ranges] of hlRanges) { const decorator = this.getDecoratorForHighlightGroup(groupName); if (!decorator) { continue; } const decoratorRanges = ranges.map((r) => { if (r.hl) { const conf = this.getDecoratorOptions(decorator); return this.createVirtTextDecorationOption( r.hl.virtText!, { ...conf, backgroundColor: conf.backgroundColor || new ThemeColor("editor.background") }, topLine + r.lineS, r.colS + 1, r.colE, ); } return { range: new Range(topLine + r.lineS, r.colS, topLine + r.lineE, r.colE + 1), } as DecorationOptions; }); result.push([decorator, decoratorRanges]); } const prevHighlights = this.prevGridHighlightsIds.get(grid); if (prevHighlights) { for (const groupName of prevHighlights) { if (!hlRanges.has(groupName)) { const decorator = this.getDecoratorForHighlightGroup(groupName); if (!decorator) { continue; } result.push([decorator, []]); } } } this.prevGridHighlightsIds.set(grid, new Set(hlRanges.keys())); return result; } public clearHighlights(grid: number): [TextEditorDecorationType, Range[]][] { const prevHighlights = this.prevGridHighlightsIds.get(grid); this.highlights.delete(grid); this.prevGridHighlightsIds.delete(grid); if (!prevHighlights) { return []; } const result: [TextEditorDecorationType, Range[]][] = []; for (const groupName of prevHighlights) { const decorator = this.getDecoratorForHighlightGroup(groupName); if (decorator) { result.push([decorator, []]); } } return result; } private createDecoratorForHighlightGroup(groupName: string, options: ThemableDecorationRenderOptions): void { const decorator = window.createTextEditorDecorationType(options); this.decoratorConfigurations.set(decorator, options); this.highlighGroupToDecorator.set(groupName, decorator); } public createVirtTextDecorationOption( text: string, conf: ThemableDecorationRenderOptions, lineNum: number, col: number, lineLength: number, ): DecorationOptions { const textDeco: DecorationOptions = { range: new Range(lineNum, col + text.length - 1, lineNum, col + text.length - 1), renderOptions: { // Inspired by https://github.com/VSCodeVim/Vim/blob/badecf1b7ecd239e3ed58720245b6f4a74e439b7/src/actions/plugins/easymotion/easymotion.ts#L64 after: { // What's up with the negative right // margin? That shifts the decoration to the // right. By default VSCode places the // decoration behind the text. If we // shift it one character to the right, // it will be on top. // Why do all that math in the right // margin? If we try to draw off the // end of the screen, VSCode will place // the text in a column we weren't // expecting. This code accounts for that. margin: `0 0 0 -${Math.min(text.length - (col + text.length - 1 - lineLength), text.length)}ch`, ...conf, ...conf.before, width: `${text.length}ch; position:absoulute; z-index:99;`, contentText: text, }, }, }; return textDeco; } }
the_stack
import $ from 'mdui.jq/es/$'; import contains from 'mdui.jq/es/functions/contains'; import extend from 'mdui.jq/es/functions/extend'; import { JQ } from 'mdui.jq/es/JQ'; import 'mdui.jq/es/methods/add'; import 'mdui.jq/es/methods/addClass'; import 'mdui.jq/es/methods/after'; import 'mdui.jq/es/methods/append'; import 'mdui.jq/es/methods/appendTo'; import 'mdui.jq/es/methods/attr'; import 'mdui.jq/es/methods/css'; import 'mdui.jq/es/methods/each'; import 'mdui.jq/es/methods/find'; import 'mdui.jq/es/methods/first'; import 'mdui.jq/es/methods/height'; import 'mdui.jq/es/methods/hide'; import 'mdui.jq/es/methods/index'; import 'mdui.jq/es/methods/innerWidth'; import 'mdui.jq/es/methods/is'; import 'mdui.jq/es/methods/on'; import 'mdui.jq/es/methods/remove'; import 'mdui.jq/es/methods/removeAttr'; import 'mdui.jq/es/methods/removeClass'; import 'mdui.jq/es/methods/show'; import 'mdui.jq/es/methods/text'; import 'mdui.jq/es/methods/trigger'; import 'mdui.jq/es/methods/val'; import Selector from 'mdui.jq/es/types/Selector'; import mdui from '../../mdui'; import '../../jq_extends/methods/transitionEnd'; import '../../jq_extends/static/guid'; import { componentEvent } from '../../utils/componentEvent'; import { $document, $window } from '../../utils/dom'; declare module '../../interfaces/MduiStatic' { interface MduiStatic { /** * 下拉选择组件 * * 请通过 `new mdui.Select()` 调用 */ Select: { /** * 实例化 Select 组件 * @param selector CSS 选择器、或 DOM 元素、或 JQ 对象 * @param options 配置参数 */ new ( selector: Selector | HTMLElement | ArrayLike<HTMLElement>, options?: OPTIONS, ): Select; }; } } type OPTIONS = { /** * 下拉框位置:`auto`、`top`、`bottom` */ position?: 'auto' | 'top' | 'bottom'; /** * 菜单与窗口上下边框至少保持多少间距 */ gutter?: number; }; type STATE = 'closing' | 'closed' | 'opening' | 'opened'; type EVENT = 'open' | 'opened' | 'close' | 'closed'; const DEFAULT_OPTIONS: OPTIONS = { position: 'auto', gutter: 16, }; class Select { /** * 原生 `<select>` 元素的 JQ 对象 */ public $native: JQ<HTMLSelectElement>; /** * 生成的 `<div class="mdui-select">` 元素的 JQ 对象 */ public $element: JQ = $(); /** * 配置参数 */ public options: OPTIONS = extend({}, DEFAULT_OPTIONS); /** * select 的 size 属性的值,根据该值设置 select 的高度 */ private size = 0; /** * 占位元素,显示已选中菜单项的文本 */ private $selected: JQ = $(); /** * 菜单项的外层元素的 JQ 对象 */ private $menu: JQ = $(); /** * 菜单项数组的 JQ 对象 */ private $items: JQ = $(); /** * 当前选中的菜单项的索引号 */ private selectedIndex = 0; /** * 当前选中菜单项的文本 */ private selectedText = ''; /** * 当前选中菜单项的值 */ private selectedValue = ''; /** * 唯一 ID */ private uniqueID: string; /** * 当前 select 的状态 */ private state: STATE = 'closed'; public constructor( selector: Selector | HTMLElement | ArrayLike<HTMLElement>, options: OPTIONS = {}, ) { this.$native = $(selector).first() as JQ<HTMLSelectElement>; this.$native.hide(); extend(this.options, options); // 为当前 select 生成唯一 ID this.uniqueID = $.guid(); // 生成 select this.handleUpdate(); // 点击 select 外面区域关闭 $document.on('click touchstart', (event: Event) => { const $target = $(event.target as HTMLElement); if ( this.isOpen() && !$target.is(this.$element) && !contains(this.$element[0], $target[0]) ) { this.close(); } }); } /** * 调整菜单位置 */ private readjustMenu(): void { const windowHeight = $window.height(); // mdui-select 高度 const elementHeight = this.$element.height(); // 菜单项高度 const $itemFirst = this.$items.first(); const itemHeight = $itemFirst.height(); const itemMargin = parseInt($itemFirst.css('margin-top')); // 菜单高度 const menuWidth = this.$element.innerWidth() + 0.01; // 必须比真实宽度多一点,不然会出现省略号 let menuHeight = itemHeight * this.size + itemMargin * 2; // mdui-select 在窗口中的位置 const elementTop = this.$element[0].getBoundingClientRect().top; let transformOriginY: string; let menuMarginTop: number; if (this.options.position === 'bottom') { menuMarginTop = elementHeight; transformOriginY = '0px'; } else if (this.options.position === 'top') { menuMarginTop = -menuHeight - 1; transformOriginY = '100%'; } else { // 菜单高度不能超过窗口高度 const menuMaxHeight = windowHeight - this.options.gutter! * 2; if (menuHeight > menuMaxHeight) { menuHeight = menuMaxHeight; } // 菜单的 margin-top menuMarginTop = -( itemMargin + this.selectedIndex * itemHeight + (itemHeight - elementHeight) / 2 ); const menuMaxMarginTop = -( itemMargin + (this.size - 1) * itemHeight + (itemHeight - elementHeight) / 2 ); if (menuMarginTop < menuMaxMarginTop) { menuMarginTop = menuMaxMarginTop; } // 菜单不能超出窗口 const menuTop = elementTop + menuMarginTop; if (menuTop < this.options.gutter!) { // 不能超出窗口上方 menuMarginTop = -(elementTop - this.options.gutter!); } else if (menuTop + menuHeight + this.options.gutter! > windowHeight) { // 不能超出窗口下方 menuMarginTop = -( elementTop + menuHeight + this.options.gutter! - windowHeight ); } // transform 的 Y 轴坐标 transformOriginY = `${ this.selectedIndex * itemHeight + itemHeight / 2 + itemMargin }px`; } // 设置样式 this.$element.innerWidth(menuWidth); this.$menu .innerWidth(menuWidth) .height(menuHeight) .css({ 'margin-top': menuMarginTop + 'px', 'transform-origin': 'center ' + transformOriginY + ' 0', }); } /** * select 是否为打开状态 */ private isOpen(): boolean { return this.state === 'opening' || this.state === 'opened'; } /** * 对原生 select 组件进行了修改后,需要调用该方法 */ public handleUpdate(): void { if (this.isOpen()) { this.close(); } this.selectedValue = this.$native.val() as string; // 保存菜单项数据的数组 type typeItemsData = { value: string; text: string; disabled: boolean; selected: boolean; index: number; }; const itemsData: typeItemsData[] = []; this.$items = $(); // 生成 HTML this.$native.find('option').each((index, option) => { const text = option.textContent || ''; const value = option.value; const disabled = option.disabled; const selected = this.selectedValue === value; itemsData.push({ value, text, disabled, selected, index, }); if (selected) { this.selectedText = text; this.selectedIndex = index; } this.$items = this.$items.add( '<div class="mdui-select-menu-item mdui-ripple"' + (disabled ? ' disabled' : '') + (selected ? ' selected' : '') + `>${text}</div>`, ); }); this.$selected = $( `<span class="mdui-select-selected">${this.selectedText}</span>`, ); this.$element = $( `<div class="mdui-select mdui-select-position-${this.options.position}" ` + `style="${this.$native.attr('style')}" ` + `id="${this.uniqueID}"></div>`, ) .show() .append(this.$selected); this.$menu = $('<div class="mdui-select-menu"></div>') .appendTo(this.$element) .append(this.$items); $(`#${this.uniqueID}`).remove(); this.$native.after(this.$element); // 根据 select 的 size 属性设置高度 this.size = parseInt(this.$native.attr('size') || '0'); if (this.size <= 0) { this.size = this.$items.length; if (this.size > 8) { this.size = 8; } } // 点击选项时关闭下拉菜单 // eslint-disable-next-line @typescript-eslint/no-this-alias const that = this; this.$items.on('click', function () { if (that.state === 'closing') { return; } const $item = $(this); const index = $item.index(); const data = itemsData[index]; if (data.disabled) { return; } that.$selected.text(data.text); that.$native.val(data.value); that.$items.removeAttr('selected'); $item.attr('selected', ''); that.selectedIndex = data.index; that.selectedValue = data.value; that.selectedText = data.text; that.$native.trigger('change'); that.close(); }); // 点击 $element 时打开下拉菜单 this.$element.on('click', (event: Event) => { const $target = $(event.target as HTMLElement); // 在菜单上点击时不打开 if ( $target.is('.mdui-select-menu') || $target.is('.mdui-select-menu-item') ) { return; } this.toggle(); }); } /** * 动画结束的回调 */ private transitionEnd(): void { this.$element.removeClass('mdui-select-closing'); if (this.state === 'opening') { this.state = 'opened'; this.triggerEvent('opened'); this.$menu.css('overflow-y', 'auto'); } if (this.state === 'closing') { this.state = 'closed'; this.triggerEvent('closed'); // 恢复样式 this.$element.innerWidth(''); this.$menu.css({ 'margin-top': '', height: '', width: '', }); } } /** * 触发组件事件 * @param name */ private triggerEvent(name: EVENT): void { componentEvent(name, 'select', this.$native, this); } /** * 切换下拉菜单的打开状态 */ public toggle(): void { this.isOpen() ? this.close() : this.open(); } /** * 打开下拉菜单 */ public open(): void { if (this.isOpen()) { return; } this.state = 'opening'; this.triggerEvent('open'); this.readjustMenu(); this.$element.addClass('mdui-select-open'); this.$menu.transitionEnd(() => this.transitionEnd()); } /** * 关闭下拉菜单 */ public close(): void { if (!this.isOpen()) { return; } this.state = 'closing'; this.triggerEvent('close'); this.$menu.css('overflow-y', ''); this.$element .removeClass('mdui-select-open') .addClass('mdui-select-closing'); this.$menu.transitionEnd(() => this.transitionEnd()); } /** * 获取当前菜单的状态。共包含四种状态:`opening`、`opened`、`closing`、`closed` */ public getState(): STATE { return this.state; } } mdui.Select = Select;
the_stack
import { getCookie, isObject, removeCookie, setCookie } from '@guardian/libs'; import { noop } from 'lib/noop'; import config from '../../../../lib/config'; import { fetchJson } from '../../../../lib/fetch-json'; import { dateDiffDays } from '../../../../lib/time-utils'; import { getLocalDate } from '../../../../types/dates'; import type { LocalDate } from '../../../../types/dates'; import type { UserFeaturesResponse } from '../../../../types/membership'; import { isUserLoggedIn } from '../identity/api'; // Persistence keys const USER_FEATURES_EXPIRY_COOKIE = 'gu_user_features_expiry'; const PAYING_MEMBER_COOKIE = 'gu_paying_member'; const AD_FREE_USER_COOKIE = 'GU_AF1'; const ACTION_REQUIRED_FOR_COOKIE = 'gu_action_required_for'; const DIGITAL_SUBSCRIBER_COOKIE = 'gu_digital_subscriber'; const HIDE_SUPPORT_MESSAGING_COOKIE = 'gu_hide_support_messaging'; // These cookies come from the user attributes API const RECURRING_CONTRIBUTOR_COOKIE = 'gu_recurring_contributor'; const ONE_OFF_CONTRIBUTION_DATE_COOKIE = 'gu_one_off_contribution_date'; // These cookies are dropped by support frontend at the point of making // a recurring contribution const SUPPORT_RECURRING_CONTRIBUTOR_MONTHLY_COOKIE = 'gu.contributions.recurring.contrib-timestamp.Monthly'; const SUPPORT_RECURRING_CONTRIBUTOR_ANNUAL_COOKIE = 'gu.contributions.recurring.contrib-timestamp.Annual'; const SUPPORT_ONE_OFF_CONTRIBUTION_COOKIE = 'gu.contributions.contrib-timestamp'; const ARTICLES_VIEWED_OPT_OUT_COOKIE = { name: 'gu_article_count_opt_out', daysToLive: 90, }; const CONTRIBUTIONS_REMINDER_SIGNED_UP = { name: 'gu_contributions_reminder_signed_up', daysToLive: 90, }; // TODO: isn’t this duplicated from commercial features? https://git.io/JMvcu const forcedAdFreeMode = !!/[#&]noadsaf(&.*)?$/.exec(window.location.hash); const userHasData = () => { const cookie = getCookie({ name: ACTION_REQUIRED_FOR_COOKIE }) ?? getCookie({ name: USER_FEATURES_EXPIRY_COOKIE }) ?? getCookie({ name: PAYING_MEMBER_COOKIE }) ?? getCookie({ name: RECURRING_CONTRIBUTOR_COOKIE }) ?? getCookie({ name: ONE_OFF_CONTRIBUTION_DATE_COOKIE }) ?? getCookie({ name: AD_FREE_USER_COOKIE }) ?? getCookie({ name: DIGITAL_SUBSCRIBER_COOKIE }) ?? getCookie({ name: HIDE_SUPPORT_MESSAGING_COOKIE }); return !!cookie; }; const accountDataUpdateWarning = (): string | null => getCookie({ name: ACTION_REQUIRED_FOR_COOKIE }); const adFreeDataIsPresent = (): boolean => { const cookieVal = getCookie({ name: AD_FREE_USER_COOKIE }); if (!cookieVal) return false; return !Number.isNaN(parseInt(cookieVal, 10)); }; const timeInDaysFromNow = (daysFromNow: number): string => { const tmpDate = new Date(); tmpDate.setDate(tmpDate.getDate() + daysFromNow); return tmpDate.getTime().toString(); }; /** * TODO: check that this validation is accurate */ const validateResponse = ( response: unknown, ): response is UserFeaturesResponse => { if (!isObject(response)) return false; if ( typeof response.showSupportMessaging === 'boolean' && isObject(response.contentAccess) && typeof response.contentAccess.paidMember === 'boolean' && typeof response.contentAccess.recurringContributor === 'boolean' && typeof response.contentAccess.digitalPack === 'boolean' ) { return true; } return true; }; const persistResponse = (JsonResponse: UserFeaturesResponse) => { setCookie({ name: USER_FEATURES_EXPIRY_COOKIE, value: timeInDaysFromNow(1), }); setCookie({ name: PAYING_MEMBER_COOKIE, value: String(JsonResponse.contentAccess.paidMember), }); setCookie({ name: RECURRING_CONTRIBUTOR_COOKIE, value: String(JsonResponse.contentAccess.recurringContributor), }); setCookie({ name: DIGITAL_SUBSCRIBER_COOKIE, value: String(JsonResponse.contentAccess.digitalPack), }); setCookie({ name: HIDE_SUPPORT_MESSAGING_COOKIE, value: String(!JsonResponse.showSupportMessaging), }); if (JsonResponse.oneOffContributionDate) { setCookie({ name: ONE_OFF_CONTRIBUTION_DATE_COOKIE, value: JsonResponse.oneOffContributionDate, }); } removeCookie({ name: ACTION_REQUIRED_FOR_COOKIE }); if (JsonResponse.alertAvailableFor) { setCookie({ name: ACTION_REQUIRED_FOR_COOKIE, value: JsonResponse.alertAvailableFor, }); } if ( adFreeDataIsPresent() && !forcedAdFreeMode && !JsonResponse.contentAccess.digitalPack ) { removeCookie({ name: AD_FREE_USER_COOKIE }); } if (JsonResponse.contentAccess.digitalPack) { setCookie({ name: AD_FREE_USER_COOKIE, value: timeInDaysFromNow(2) }); } }; const deleteOldData = (): void => { // We expect adfree cookies to be cleaned up by the logout process, but what if the user's login simply times out? removeCookie({ name: USER_FEATURES_EXPIRY_COOKIE }); removeCookie({ name: PAYING_MEMBER_COOKIE }); removeCookie({ name: RECURRING_CONTRIBUTOR_COOKIE }); removeCookie({ name: AD_FREE_USER_COOKIE }); removeCookie({ name: ACTION_REQUIRED_FOR_COOKIE }); removeCookie({ name: DIGITAL_SUBSCRIBER_COOKIE }); removeCookie({ name: HIDE_SUPPORT_MESSAGING_COOKIE }); removeCookie({ name: ONE_OFF_CONTRIBUTION_DATE_COOKIE }); }; const requestNewData = () => fetchJson( `${config.get<string>( 'page.userAttributesApiUrl', '/USER_ATTRIBUTE_API_NOT_FOUND', )}/me`, { mode: 'cors', credentials: 'include', }, ) .then((response) => { if (!validateResponse(response)) throw new Error('invalid response'); return response; }) .then(persistResponse) .catch(noop); const cookieIsExpiredOrMissing = (cookieName: string): boolean => { const expiryDateFromCookie = getCookie({ name: cookieName }); if (!expiryDateFromCookie) return true; const expiryTime = parseInt(expiryDateFromCookie, 10); const timeNow = new Date().getTime(); return timeNow >= expiryTime; }; const featuresDataIsOld = () => cookieIsExpiredOrMissing(USER_FEATURES_EXPIRY_COOKIE); const adFreeDataIsOld = (): boolean => { const { switches } = window.guardian.config; return ( Boolean(switches.adFreeStrictExpiryEnforcement) && cookieIsExpiredOrMissing(AD_FREE_USER_COOKIE) ); }; const userNeedsNewFeatureData = (): boolean => featuresDataIsOld() || (adFreeDataIsPresent() && adFreeDataIsOld()); const userHasDataAfterSignout = (): boolean => !isUserLoggedIn() && userHasData(); /** * Updates the user's data in a lazy fashion */ const refresh = (): Promise<void> => { if (isUserLoggedIn() && userNeedsNewFeatureData()) { return requestNewData(); } else if (userHasDataAfterSignout() && !forcedAdFreeMode) { deleteOldData(); } return Promise.resolve(); }; const supportSiteRecurringCookiePresent = () => getCookie({ name: SUPPORT_RECURRING_CONTRIBUTOR_MONTHLY_COOKIE }) != null || getCookie({ name: SUPPORT_RECURRING_CONTRIBUTOR_ANNUAL_COOKIE }) != null; /** * Does our _existing_ data say the user is a paying member? * This data may be stale; we do not wait for userFeatures.refresh() */ const isPayingMember = (): boolean => // If the user is logged in, but has no cookie yet, play it safe and assume they're a paying user isUserLoggedIn() && getCookie({ name: PAYING_MEMBER_COOKIE }) !== 'false'; // Expects milliseconds since epoch const getSupportFrontendOneOffContributionTimestamp = (): number | null => { const supportFrontendCookie = getCookie({ name: SUPPORT_ONE_OFF_CONTRIBUTION_COOKIE, }); if (supportFrontendCookie) { const ms = parseInt(supportFrontendCookie, 10); if (Number.isInteger(ms)) return ms; } return null; }; // Expects YYYY-MM-DD format const getAttributesOneOffContributionTimestamp = (): number | null => { const attributesCookie = getCookie({ name: ONE_OFF_CONTRIBUTION_DATE_COOKIE, }); if (attributesCookie) { const ms = Date.parse(attributesCookie); if (Number.isInteger(ms)) return ms; } return null; }; // number returned is Epoch time in milliseconds. // null value signifies no last contribution date. const getLastOneOffContributionTimestamp = (): number | null => getSupportFrontendOneOffContributionTimestamp() ?? getAttributesOneOffContributionTimestamp(); const getLastOneOffContributionDate = (): LocalDate | null => { const timestamp = getLastOneOffContributionTimestamp(); if (timestamp === null) { return null; } const date = new Date(timestamp); const year = date.getUTCFullYear(); const month = date.getUTCMonth() + 1; const day = date.getUTCDate(); return getLocalDate(year, month, day); }; const getLastRecurringContributionDate = (): number | null => { // Check for cookies, ensure that cookies parse, and ensure parsed results are integers const monthlyCookie = getCookie({ name: SUPPORT_RECURRING_CONTRIBUTOR_MONTHLY_COOKIE, }); const annualCookie = getCookie({ name: SUPPORT_RECURRING_CONTRIBUTOR_ANNUAL_COOKIE, }); const monthlyTime = monthlyCookie ? parseInt(monthlyCookie, 10) : null; const annualTime = annualCookie ? parseInt(annualCookie, 10) : null; const monthlyMS = monthlyTime && Number.isInteger(monthlyTime) ? monthlyTime : null; const annualMS = annualTime && Number.isInteger(annualTime) ? annualTime : null; if (!monthlyMS && !annualMS) { return null; } if (monthlyMS && annualMS) { return Math.max(monthlyMS, annualMS); } return monthlyMS ?? annualMS ?? null; }; const getDaysSinceLastOneOffContribution = (): number | null => { const lastContributionDate = getLastOneOffContributionTimestamp(); if (lastContributionDate === null) { return null; } return dateDiffDays(lastContributionDate, Date.now()); }; // defaults to last three months const isRecentOneOffContributor = (askPauseDays = 90): boolean => { const daysSinceLastContribution = getDaysSinceLastOneOffContribution(); if (daysSinceLastContribution === null) { return false; } return daysSinceLastContribution <= askPauseDays; }; // true if the user has completed their ask-free period const isPostAskPauseOneOffContributor = (askPauseDays = 90): boolean => { const daysSinceLastContribution = getDaysSinceLastOneOffContribution(); if (daysSinceLastContribution === null) { return false; } return daysSinceLastContribution > askPauseDays; }; const isRecurringContributor = (): boolean => // If the user is logged in, but has no cookie yet, play it safe and assume they're a contributor (isUserLoggedIn() && getCookie({ name: RECURRING_CONTRIBUTOR_COOKIE }) !== 'false') || supportSiteRecurringCookiePresent(); const isDigitalSubscriber = (): boolean => getCookie({ name: DIGITAL_SUBSCRIBER_COOKIE }) === 'true'; const shouldNotBeShownSupportMessaging = (): boolean => getCookie({ name: HIDE_SUPPORT_MESSAGING_COOKIE }) === 'true'; /* Whenever the checks are updated, please make sure to update applyRenderConditions.scala.js too, where the global CSS class, indicating the user should not see the revenue messages, is added to the body. Please also update readerRevenueRelevantCookies below, if changing the cookies which this function is dependent on. */ const shouldHideSupportMessaging = (): boolean => shouldNotBeShownSupportMessaging() || isRecentOneOffContributor() || // because members-data-api is unaware of one-off contributions so relies on cookie isRecurringContributor(); // guest checkout means that members-data-api isn't aware of all recurring contributions so relies on cookie const readerRevenueRelevantCookies = [ PAYING_MEMBER_COOKIE, DIGITAL_SUBSCRIBER_COOKIE, RECURRING_CONTRIBUTOR_COOKIE, SUPPORT_RECURRING_CONTRIBUTOR_MONTHLY_COOKIE, SUPPORT_RECURRING_CONTRIBUTOR_ANNUAL_COOKIE, SUPPORT_ONE_OFF_CONTRIBUTION_COOKIE, HIDE_SUPPORT_MESSAGING_COOKIE, ]; // For debug/test purposes const fakeOneOffContributor = (): void => { setCookie({ name: SUPPORT_ONE_OFF_CONTRIBUTION_COOKIE, value: Date.now().toString(), }); }; const isAdFreeUser = (): boolean => isDigitalSubscriber() || (adFreeDataIsPresent() && !adFreeDataIsOld()); // Extend the expiry of the contributions cookie by 1 year beyond the date of the contribution const extendContribsCookieExpiry = (): void => { const cookie = getCookie({ name: SUPPORT_ONE_OFF_CONTRIBUTION_COOKIE }); if (cookie) { const contributionDate = parseInt(cookie, 10); if (Number.isInteger(contributionDate)) { const daysToLive = 365 - dateDiffDays(contributionDate, Date.now()); setCookie({ name: SUPPORT_ONE_OFF_CONTRIBUTION_COOKIE, value: contributionDate.toString(), daysToLive, }); } } }; const canShowContributionsReminderFeature = (): boolean => { const signedUpForReminder = !!getCookie({ name: CONTRIBUTIONS_REMINDER_SIGNED_UP.name, }); const { switches } = window.guardian.config; return Boolean(switches.showContributionReminder) && !signedUpForReminder; }; export { accountDataUpdateWarning, isAdFreeUser, isPayingMember, isRecentOneOffContributor, isRecurringContributor, isDigitalSubscriber, shouldHideSupportMessaging, refresh, deleteOldData, getLastOneOffContributionTimestamp, getLastOneOffContributionDate, getLastRecurringContributionDate, getDaysSinceLastOneOffContribution, isPostAskPauseOneOffContributor, readerRevenueRelevantCookies, fakeOneOffContributor, shouldNotBeShownSupportMessaging, extendContribsCookieExpiry, ARTICLES_VIEWED_OPT_OUT_COOKIE, CONTRIBUTIONS_REMINDER_SIGNED_UP, canShowContributionsReminderFeature, };
the_stack
import React, { useEffect, useState, Children } from 'react'; import classNames from 'classnames'; import { useTranslation } from 'react-i18next'; import { FullscreenOutlined, FullscreenExitOutlined } from '@ant-design/icons'; import styles from './DecisionTree.module.less'; import { CKBJson } from '@antv/knowledge'; import uniqueId from '@antv/util/lib/unique-id'; import clone from '@antv/util/lib/clone'; import { transform } from '@antv/matrix-util'; import chartUrls from '../../data/chart-urls.json'; let graph: any; let decoGraph: any; let data: any; let purposeMap: any = {}; let graphAnimating: boolean = false; let aftercollapse: boolean = false; let animateShapes: any = []; declare global { interface HTMLElement { requestFullscreen?(): void; mozRequestFullscreen?(): void; msRequestFullscreen?(): void; webkitRequestFullscreen?(): void; webkitExitFullscreen?(): void; mozCancelFullscreen?(): void; msExitFullscreen?(): void; exitFullscreen?(): void; } interface Document extends HTMLElement {} } const DecisionTree = () => { const { t, i18n } = useTranslation(); let ckbData = CKBJson('zh-CN'); if (i18n.language === 'en') { ckbData = CKBJson(); } const [tooltipStates, setTooltipStates] = useState({ title: '', imgSrc: '', links: [], names: [], x: 0, y: 0, buttons: <a></a>, }); const [tooltipDisplayStates, setTooltipDisplayStates] = useState({ opacity: 0, display: 'none', }); const [screenStates, setScreenStates] = useState({ fullscreenDisplay: 'block', exitfullscreenDisplay: 'none', }); const [heightStates, setHeightStates] = useState({ height: '800px', }); const lightColors = [ '#FFC9E3', '#7CDBF2', '#5FE1E7', '#A1E71D', '#FFE269', '#FFA8A8', '#FFA1E3', '#A7C2FF', ]; const darkColors = [ '#FF68A7', '#5B63FF', '#44E6C1', '#1BE6B9', '#FF5A34', '#F76C6C', '#AE6CFF', '#7F86FF', ]; const shadowColors = [ '#f89fc9', '#9ba9ff', '#56d4d1', '#87e240', '#ffbe81', '#ffb0b0', '#d19fff', '#b4bfff', ]; const gColors: string[] = []; const shadowColorMap: any = {}; lightColors.forEach((lcolor, i) => { gColors.push('l(0) 0:' + lcolor + ' 1:' + darkColors[i]); shadowColorMap[lcolor] = shadowColors[i]; }); const fadeOutItem = (item: any) => { const nodeGroup = item.get('group'); const children = nodeGroup.get('children'); children.forEach((child: any, i: number) => { child.animate( (ratio: number) => { let opacity = 1 - 3 * ratio; if (opacity < 0) opacity = 0; return { opacity, }; }, { duration: 500, repeat: false, }, ); }); }; const layoutCfg = { type: 'compactBox', direction: 'LR', getHeight: (d: any) => { if (d.tag === 'purpose') { return 72; } return 24; }, getWidth: (d: any) => { if (d.id === 'antv') { return 10; } return 16; }, getVGap: () => { return 0; }, getHGap: (d: any) => { if (d.id === 'antv') { return 160; } return 140; }, }; const collapseExpandCfg = { type: 'collapse-expand', shouldBegin: (e: any) => { const model = e.item.getModel(); if (graphAnimating) return false; if (model.tag === 'purpose') { animateShapes.forEach((shape: any) => { if (shape && !shape.destroyed) shape.pauseAnimate(); }); graphAnimating = true; return true; } return false; }, onChange: (item: any, collapsed: boolean) => { const model = item.getModel(); const itemId = model.id; const nodes = graph.getNodes(); nodes.forEach((node: any) => { const nodeModel = node.getModel(); // collapse others if (nodeModel.tag === 'purpose' && nodeModel.id !== itemId) nodeModel.collapsed = true; if (nodeModel.tag === 'leaf' || nodeModel.tag === 'midpoint') { fadeOutItem(node); } }); const edges = graph.getEdges(); edges.forEach((edge: any) => { const targetNode = edge.get('targetNode'); if ( targetNode.getModel().tag === 'leaf' || targetNode.getModel().tag === 'midpoint' ) { fadeOutItem(edge); } }); }, }; let LIMIT_OVERFLOW_WIDTH = 1418.4; let LIMIT_OVERFLOW_HEIGHT = 650; let element = React.useRef<HTMLDivElement>(null); let wrapperElement = React.useRef<HTMLDivElement>(null); let CANVAS_WIDTH = 1320; let CANVAS_HEIGHT = 696; useEffect(() => { data = processData(ckbData); const G6 = require('@antv/g6/es'); G6.registerEdge( 'tree-edge', { afterDraw(cfg: any, group: any) { const keyShape = group.get('children')[0]; const sourceModel = cfg.source.getModel(); if (sourceModel.tag === 'purpose') { keyShape.attr({ opacity: 0, }); keyShape.animate( (ratio: number) => { return { opacity: ratio, }; }, { duration: 300, delay: 100, }, ); } }, }, 'cubic-horizontal', ); G6.registerNode('bubble', { drawShape( cfg: { size: number; color: string; label: string | undefined; labelCfg: any | undefined; }, group: any, ) { const hwRatio = 0.31; const r = cfg.size / 2; // a circle by path const path = [ ['M', -r, 0], ['C', -r, r / 2, -r / 2, r, 0, r], ['C', r / 2, r, r, r / 2, r, 0], ['C', r, -r / 2, r / 2, -r, 0, -r], ['C', -r / 2, -r, -r, -r / 2, -r, 0], ['Z'], ]; const keyShape = group.addShape('path', { attrs: { x: 0, y: 0, path, fill: cfg.color || 'steelblue', shadowColor: shadowColorMap[cfg.color.split(' ')[1].substr(2)], shadowBlur: 0, matrix: [1, 0, 0, 0, hwRatio, 0, 0, 0, 1], }, }); animateShapes.push(keyShape); let maskMatrix = [1, 0, 0, 0, hwRatio + 0.05, 0, 0, 0, 1]; maskMatrix = transform(maskMatrix, [ ['r', 0.13 * (Math.random() * 2 - 1)], ]); group.addShape('path', { attrs: { x: 0, y: 0, path, opacity: 0.15, fill: cfg.color || 'steelblue', matrix: maskMatrix, }, }); const height = 0.31 * 2 * r + 30; const width = 2 * r + 20; const rect = group.addShape('rect', { attrs: { x: -width / 2, y: -height / 2, width, height, fill: '#fff', opacity: 0, cursor: 'pointer', }, className: 'bubble-bbox-mask', }); return rect; }, afterDraw(cfg: any, group: any) { const self = this; const r = cfg.size / 2; if (cfg.label) { const labelCfg = cfg.labelCfg || {}; const labelStyle = labelCfg.style || {}; const label = group.addShape('text', { attrs: { text: cfg.label, x: 0, y: 0, fontSize: labelStyle.fontSize || 14, fontWeight: labelStyle.fontWeight || 'bold', fill: labelStyle.fill || '#fff', cursor: 'pointer', }, }); const labelBBox = label.getBBox(); label.attr({ x: -labelBBox.width / 2, y: labelBBox.height / 2, }); } const spNum = 10; // split points number const directions: number[] = [], rs: number[] = []; const floatRange = 0.1; const speedConst = 0.0015; self.changeDirections(spNum, directions); for (let i = 0; i < spNum; i++) { const rr = r + directions[i] * (Math.random() * r * speedConst); // +-r/6, the sign according to the directions if (rs[i] < (1 - floatRange) * r) rs[i] = (1 - floatRange) * r; else if (rs[i] > (1 + floatRange) * r) rs[i] = (1 + floatRange) * r; rs.push(rr); } const children = group.get('children'); const bubble = children[0]; bubble.animate( (ratio: number) => { const path = self.getBubblePath( r, spNum, directions, rs, floatRange, speedConst, ); return { path, }; }, { repeat: true, duration: 10000, delay: Math.random() * 1000, }, ); // const directions2: number[] = [], // rs2: number[] = []; // self.changeDirections(spNum, directions2); // const maskR = r * 1.03; // for (let i = 0; i < spNum; i++) { // const rr = // maskR + directions2[i] * (Math.random() * maskR * speedConst); // +-r/6, the sign according to the directions // if (rs2[i] < (1 - floatRange) * maskR) // rs2[i] = (1 - floatRange) * maskR; // else if (rs2[i] > (1 + floatRange) * maskR) // rs2[i] = (1 + floatRange) * maskR; // rs2.push(rr); // } // children[1].animate( // () => { // const path = self.getBubblePath( // maskR, // spNum, // directions2, // rs2, // floatRange, // speedConst, // ); // return { path }; // }, // { // repeat: true, // duration: 10000, // delay: Math.random() * 1000, // }, // ); }, changeDirections(num: number, directions: number[]) { for (let i = 0; i < num; i++) { if (!directions[i]) { const rand = Math.random(); const dire = rand > 0.5 ? 1 : -1; directions.push(dire); } else { directions[i] = -1 * directions[i]; } } return directions; }, getBubblePath( r: number, spNum: number, directions: number[], rs: number[], floatRange: number = 0.3, speedConst: number = 0.001, ) { const path = []; const cpNum = spNum * 2; // control points number const unitAngle = (Math.PI * 2) / spNum; // base angle for split points let angleSum = 0; let spAngleOffset = 0; // split point's offset const sps = []; const cps = []; for (let i = 0; i < spNum; i++) { const speed = speedConst * Math.random(); rs[i] = rs[i] + directions[i] * speed * r; // +-r/6, the sign according to the directions if (rs[i] < (1 - floatRange) * r) { rs[i] = (1 - floatRange) * r; directions[i] = -1 * directions[i]; } else if (rs[i] > (1 + floatRange) * r) { rs[i] = (1 + floatRange) * r; directions[i] = -1 * directions[i]; } const spX = rs[i] * Math.cos(angleSum); const spY = rs[i] * Math.sin(angleSum); sps.push({ x: spX, y: spY }); for (let j = 0; j < 2; j++) { const cpAngleRand = unitAngle / 3; const cpR = rs[i] / Math.cos(cpAngleRand); const sign = j === 0 ? -1 : 1; const x = cpR * Math.cos(angleSum + sign * cpAngleRand); const y = cpR * Math.sin(angleSum + sign * cpAngleRand); cps.push({ x, y }); } spAngleOffset = (Math.random() * unitAngle) / 3 - unitAngle / 6; angleSum += unitAngle; } path.push(['M', sps[0].x, sps[0].y]); for (let i = 1; i < spNum; i++) { path.push([ 'C', cps[2 * i - 1].x, cps[2 * i - 1].y, cps[2 * i].x, cps[2 * i].y, sps[i].x, sps[i].y, ]); } path.push([ 'C', cps[cpNum - 1].x, cps[cpNum - 1].y, cps[0].x, cps[0].y, sps[0].x, sps[0].y, ]); path.push(['Z']); return path; }, update(cfg: any, group: any) {}, setState(name: string, value: boolean, item: any) { if (name === 'highlight') { const group = item.get('group'); const keyShape = group.get('children')[0]; if (value) { keyShape.animate( { shadowBlur: 30, }, { duration: 150, callback: () => { graphAnimating = false; }, }, ); } else { keyShape.animate( { shadowBlur: 0, }, { duration: 150, callback: () => { graphAnimating = false; }, }, ); } } }, }); G6.registerNode( 'leaf', { afterDraw(cfg: any, group: any) { graphAnimating = true; const label = group.get('children')[1]; label.attr('opacity', 0); const shapes: any = [label]; let leftShapeBBox = group.getBBox(); const tagOffset = 8, textPadding = [4, 8]; let tags = clone(cfg.category); tags = tags.concat(cfg.family); // tags tags.forEach((cat: string) => { // tag text const text = group.addShape('text', { attrs: { text: cat, fill: '#8C8C8C', fontSize: 10, textAlign: 'start', textBaseline: 'middle', x: leftShapeBBox.maxX + tagOffset + textPadding[1], y: 0, opacity: 0, }, }); shapes.push(text); const textBBox = text.getBBox(); // back rect const rect = group.addShape('rect', { attrs: { radius: (textBBox.height + textPadding[0]) / 2, width: textBBox.width + textPadding[1] * 2, height: textBBox.height + textPadding[0], x: leftShapeBBox.maxX + tagOffset, y: leftShapeBBox.minY, fill: '#fff', stroke: '#d8d8d8', lineWidth: 1, opacity: 0, fontSize: 10, }, }); shapes.push(rect); text.toFront(); leftShapeBBox = rect.getBBox(); }); shapes.forEach((shape: any) => { shape.animate( (ratio: number) => { return { opacity: ratio, }; }, { duration: 200, repeat: false, delay: 200, callback: () => { graphAnimating = false; }, }, ); }); const groupBBox = group.getBBox(); group.addShape('rect', { attrs: { x: groupBBox.minX, y: groupBBox.minY, width: groupBBox.width, height: groupBBox.height, opacity: 0, fill: '#fff', cursor: 'pointer', }, }); }, setState(name: string, value: boolean, item: any) { if (name === 'dark') { const group = item.get('group'); group.stopAnimate(); if (value) { group.animate({ opacity: 0.5 }, { duration: 150 }); } else { group.animate({ opacity: 1 }, { duration: 150 }); } } }, }, 'circle', ); G6.registerNode( 'midpoint', { afterDraw(cfg: any, group: any) { const label = group.get('children')[1]; label.attr('opacity', 0); graphAnimating = true; label.animate( (ratio: number) => { return { opacity: ratio, }; }, { duration: 200, repeat: false, delay: 200, callback: () => { graphAnimating = false; }, }, ); // transparent rect for hover responsing const groupBBox = group.getBBox(); group.addShape('rect', { attrs: { x: groupBBox.minX, y: groupBBox.minY, width: groupBBox.width, height: groupBBox.height, opacity: 0, fill: '#fff', cursor: 'pointer', }, className: 'bubble-bbox-mask', }); }, setState(name: string, value: boolean, item: any) { if (name === 'dark') { const group = item.get('group'); group.stopAnimate(); if (value) { group.animate({ opacity: 0.5 }, { duration: 150 }); } else { group.animate({ opacity: 1 }, { duration: 150 }); } } }, }, 'circle', ); if (element && element.current) { CANVAS_WIDTH = element.current.offsetWidth; // 1320; CANVAS_HEIGHT = element.current.offsetHeight; // 696; } LIMIT_OVERFLOW_WIDTH = CANVAS_WIDTH - 100; LIMIT_OVERFLOW_HEIGHT = CANVAS_HEIGHT - 100; const decoData = { nodes: [ { id: 'deco1', size: 290, x: 0, y: 0 }, { id: 'deco2', size: 200, x: 1000, y: 0 }, { id: 'deco3', size: 160, x: 1300, y: 250 }, { id: 'deco4', size: 160, x: 100, y: 610 }, { id: 'deco5', size: 160, x: 1000, y: 630 }, ], }; decoGraph = new G6.Graph({ container: element.current as HTMLElement, width: CANVAS_WIDTH, height: CANVAS_HEIGHT * 2, defaultNode: { type: 'circle', shape: 'circle', style: { lineWidth: 0, opacity: 0.1, fill: 'l(1.6) 0:#FFA1E3 1:#AE6CFF', }, }, }); decoGraph.data(decoData); decoGraph.render(); graph = new G6.TreeGraph({ container: element.current as HTMLElement, width: CANVAS_WIDTH, height: CANVAS_HEIGHT * 2, layout: layoutCfg, modes: { default: [ { type: 'drag-canvas', direction: 'y', }, collapseExpandCfg, ], //'double-finger-drag-canvas', }, defaultEdge: { type: 'tree-edge', color: '#D8D8D8', sourceAnchor: 1, targetAnchor: 0, }, animate: true, animateCfg: { duration: 300, easing: 'easeQuadInOut', callback: () => { graphAnimating = false; }, }, }); loadData(data); const group = graph.get('group'); const graphBBox = group.getBBox(); graph.moveTo(Math.abs(graphBBox.x) + 200, Math.abs(graphBBox.y) + 60); let currentPurpose: any; graph.on('itemcollapsed', (e: any) => { const { item } = e; currentPurpose = item; aftercollapse = true; }); const paddingTop = 40; const oriGroupBBoxHeight = graph.get('group').getCanvasBBox().height + 2 * paddingTop; graph.on('afteranimate', () => { if (!currentPurpose || !aftercollapse) return; aftercollapse = false; const model = currentPurpose.getModel(); let matrix = graph.get('group').getMatrix(); if (!matrix) matrix = [1, 0, 0, 0, 1, 0, 0, 0, 1]; const canvasBBox = graph.get('group').getCanvasBBox(); const minY = canvasBBox.minY; const height = canvasBBox.height + paddingTop * 2; const move = -(minY - paddingTop); graphAnimating = true; let lastY = 0; graph.get('group').animate( (ratio: number) => { matrix = transform(matrix, [['t', 0, ratio * move - lastY]]); lastY = ratio * move; graph.get('group').setMatrix(matrix); }, { duration: 300, callback: () => { graphAnimating = false; }, }, ); CANVAS_HEIGHT = (800 * height) / oriGroupBBoxHeight + 2 * paddingTop; setHeightStates({ height: `${CANVAS_HEIGHT}px`, }); }); graph.on('afteranimate', () => { animateShapes.forEach((shape: any) => { if (shape && !shape.destroyed) shape.resumeAnimate(); }); }); // click root to expand graph.on('node:click', (e: any) => { const item = e.item; const model = item.getModel(); if (model.tag === 'purpose') { // update the colors for decoration circles decoGraph.getNodes().forEach((node: any) => { node.update({ style: { fill: model.color, }, }); }); graph.getNodes().forEach((node: any) => { const tag = node.getModel().tag; if (tag !== 'leaf' && tag !== 'midpoint') return; const circle = node.getKeyShape(); circle.animate( (ratio: number) => { return { opacity: ratio, }; }, { duration: 200, delay: 100, }, ); }); graph.getEdges().forEach((edge: any) => { if (edge.getModel().source === model.id) { const curve = edge.getKeyShape(); curve.animate( (ratio: number) => { return { opacity: ratio, }; }, { duration: 500, }, ); } }); } }); graph.on('node:mouseenter', (e: any) => { const { item } = e; const model = item.getModel(); // update the colors for decoration circles decoGraph.getNodes().forEach((node: any) => { node.update({ style: { fill: model.color, }, }); }); // highlight const nodes = graph.getNodes(); if (model.tag === 'leaf' || model.tag === 'midpoint') { nodes.forEach((node: any) => { const nodeModel = node.getModel(); if (nodeModel.tag !== 'leaf' && nodeModel.tag !== 'midpoint') return; if (nodeModel.id === model.id) { graph.setItemState(node, 'dark', false); } else { graph.setItemState(node, 'dark', true); } }); } else if (model.tag === 'purpose') { nodes.forEach((node: any) => { const nodeModel = node.getModel(); if (nodeModel.id === model.id) { graph.setItemState(node, 'highlight', true); } else { graph.setItemState(node, 'highlight', false); } }); } // tooltip const urls = (chartUrls as any)[model.id.split('-')[0]]; if (!urls || !urls.linkNames) { return; } const links: string[] = []; const links_en: string[] = []; urls.linkNames.forEach((name: string, i: number) => { const pro = urls.links[i].split('/')[1]; const pro_en = urls.links[i].split('/')[1]; const link = 'https://' + pro + '.antv.vision' + urls.links[i].substr(pro.length + 1); const link_en = 'https://' + pro_en + '.antv.vision' + urls.links_en[i].substr(pro_en.length + 1); links.push(link); links_en.push(link_en); }); const buttons = urls.linkNames ? ( urls.linkNames.map((name: string, i: number) => ( <div className={styles.button} style={{ width: `${100 / urls.linkNames.length}%` }} key={i} > <a href={i18n.language === 'zh' ? links[i] : links_en[i]} target="frame1" > {name} </a> </div> )) ) : ( <div /> ); const labelShape = item.get('group').findByClassName('node-label'); const shapeBBox = labelShape.getBBox(); const pos = graph.getCanvasByPoint( model.x + shapeBBox.maxX, model.y + shapeBBox.minY, ); setTooltipStates({ title: t(model.name), imgSrc: urls.imgSrc, links: urls.links, names: urls.linkNames, x: pos.x + 8, y: pos.y, buttons: <div className={styles.buttons}>{buttons}</div>, }); setTooltipDisplayStates({ opacity: 1, display: 'block', }); }); graph.on('node:mouseleave', (e: any) => { // cancel highlight const nodes = graph.getNodes(); nodes.forEach((node: any) => { graph.setItemState(node, 'dark', false); graph.setItemState(node, 'highlight', false); }); setTooltipDisplayStates({ opacity: 0, display: 'none', }); }); graph.on('canvas:click', () => { if (graphAnimating) return; Object.keys(purposeMap).forEach((purposeName: any) => { const purpose = purposeMap[purposeName]; if (purpose.tag !== 'purpose') return; purpose.collapsed = true; }); const nodes = graph.getNodes(); nodes.forEach((node: any) => { const nodeModel = node.getModel(); if (nodeModel.tag !== 'leaf') return; fadeOutItem(node); }); const edges = graph.getEdges(); edges.forEach((edge: any) => { const targetNode = edge.get('targetNode'); if (targetNode.getModel().tag !== 'leaf') return; fadeOutItem(edge); }); aftercollapse = true; graph.layout(); }); window.onresize = () => { if (element && element.current) { CANVAS_WIDTH = element.current.offsetWidth; // 1320; CANVAS_HEIGHT = element.current.offsetHeight; // 696; } if (graph) { graph.changeSize(CANVAS_WIDTH, CANVAS_HEIGHT * 2); decoGraph.changeSize(window.screen.width, window.screen.height * 2); } }; }, []); const loadData = (data: any) => { graph.data(data); graph.render(); }; const processData = (data: any) => { const root: any = { id: 'antv', children: [], type: 'image', shape: 'image', size: 66, img: 'https://gw.alipayobjects.com/zos/antfincdn/FLrTNDvlna/antv.png', anchorPoints: [ [-0.1, 0.5], [1.1, 0.5], ], tag: 'root', }; const bubbleCfg = { collapsed: true, type: 'bubble', shape: 'bubble', tag: 'purpose', size: 165, anchorPoints: [ [-0.08, 0.5], [1.1, 0.5], ], labelCfg: { style: { fontSize: 16, fill: '#fff', fontWeight: 350, }, }, }; purposeMap = {}; let purposeCount = 0; const relationMidPoints: any = []; Object.keys(data).forEach((chartId: any) => { const chart = data[chartId]; // remove the dulplicated parent-child tag such as Relation and Hierarchy let childExist = false, parentExist = false, parentIdx = -1; chart.purpose.forEach((pur: string, i: number) => { if (pur === t('层级') || pur === t('流向')) { childExist = true; } else if (pur === t('关系')) { parentExist = true; parentIdx = i; } }); if (childExist && parentExist) { delete chart.purpose[parentIdx]; } chart.purpose.forEach((pur: string) => { if (pur === t('聚类') || !pur) return; // temperal if (pur === t('层级') || pur === t('流向')) { if (!purposeMap[t('关系')]) { purposeCount++; const purpose = { id: t('关系'), label: t('关系'), children: [], color: gColors[purposeCount % gColors.length], gradientColor: gColors[purposeCount % gColors.length], ...bubbleCfg, labelCfg: bubbleCfg.labelCfg, }; root.children.push(purpose); purposeMap[t('关系')] = purpose; } if (!purposeMap[pur]) { const color = purposeMap[t('关系')].color.split(' ')[2].substr(2); const midPoint = { id: pur, type: 'midpoint', tag: 'midpoint', size: 6, label: pur, color, gradientColor: purposeMap[t('关系')].color, children: [], style: { fill: '#fff', stroke: '#d8d8d8', lineWidth: 2, }, labelCfg: { position: 'right', offset: 9, style: { fill: color, fontSize: 14, }, }, anchorPoints: [ [-0.5, 0.5], [9, 0.5], ], }; relationMidPoints.push(midPoint); purposeMap[pur] = midPoint; } } if (!purposeMap[pur]) { purposeCount++; const purpose = { id: pur, label: pur, children: [], gradientColor: gColors[purposeCount % gColors.length], color: gColors[purposeCount % gColors.length], ...bubbleCfg, labelCfg: bubbleCfg.labelCfg, }; root.children.push(purpose); purposeMap[pur] = purpose; } const leaf = processLeaf(chart, purposeMap[pur]); purposeMap[pur].children.push(leaf); }); }); relationMidPoints.forEach((midpoint: any) => { purposeMap[t('关系')].children.push(midpoint); }); Object.keys(purposeMap).forEach((purposeName: any) => { const purpose = purposeMap[purposeName]; const children = purpose.children; let childNum = children.length; children.forEach((child: any) => { const cc = child.children; if (cc) { childNum += cc.length; } }); purpose.label = `${purpose.label} (${childNum})`; }); return root; }; const processLeaf = (chart: any, parent: any) => { const cloneChart = clone(chart); let color = parent.color; if (color.split(' ').length > 2) { color = color.split(' ')[2].substr(2); } const cfg = { id: `${cloneChart.id}-${uniqueId()}`, shape: 'leaf', type: 'leaf', label: chart.name, tag: 'leaf', size: 6, parentId: parent.id, parentColor: parent.gradientColor, anchorPoints: [ [-0.5, 0.5], [1.1, 0.5], ], labelCfg: { position: 'right', offset: 9, style: { fill: color, fontSize: 14, }, }, style: { fill: '#fff', stroke: '#d8d8d8', lineWidth: 2, opacity: 0, }, }; return Object.assign({}, cloneChart, cfg); }; const tooltip = ( <div className={styles.tooltip} style={{ opacity: tooltipDisplayStates.opacity, display: tooltipDisplayStates.display, left: tooltipStates.x, top: tooltipStates.y, }} > <div className={styles.tooltipTitle}> {tooltipStates.title.replace('\n', '')} </div> <div className={styles.tooltipContent}> <img className={styles.tooltipImg} src={tooltipStates.imgSrc} alt="tooltip" /> <div className={styles.tooltipBtnsContainer}> <p className={styles.demoDescription}>demo</p> {tooltipStates.buttons} </div> </div> </div> ); const scrollToCanvas = () => { const element = document.getElementById('decisionTree'); if (element) { element.scrollIntoView({ behavior: 'smooth', block: 'start' }); } }; const handleFullScreen = () => { const fullscreenDom: HTMLDivElement = wrapperElement.current as HTMLDivElement; if (fullscreenDom) { setScreenStates({ fullscreenDisplay: 'none', exitfullscreenDisplay: 'block', }); if (fullscreenDom.requestFullscreen) { fullscreenDom.requestFullscreen(); } else if (fullscreenDom.mozRequestFullscreen) { fullscreenDom.mozRequestFullscreen(); } else if (fullscreenDom.msRequestFullscreen) { fullscreenDom.msRequestFullscreen(); } else if (fullscreenDom.webkitRequestFullscreen) { fullscreenDom.webkitRequestFullscreen(); } if (graph && window.screen) { graph.changeSize(window.screen.width, window.screen.height * 2); decoGraph.changeSize(window.screen.width, window.screen.height * 2); loadData(data); const group = graph.get('group'); const graphBBox = group.getBBox(); graph.moveTo(Math.abs(graphBBox.x) + 200, Math.abs(graphBBox.y) + 60); } } }; const handleExitFullscreen = () => { if (document) { setScreenStates({ fullscreenDisplay: 'block', exitfullscreenDisplay: 'none', }); if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } else if (document.mozCancelFullscreen) { document.mozCancelFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } if (graph && window.screen) { graph.changeSize(window.screen.width, window.screen.height * 2); decoGraph.changeSize(window.screen.width, window.screen.height * 2); loadData(data); const group = graph.get('group'); const graphBBox = group.getBBox(); graph.moveTo(Math.abs(graphBBox.x) + 200, Math.abs(graphBBox.y) + 60); } } }; return ( <div className={classNames(styles.wrapper, 'decisionTreePage')} ref={wrapperElement} > <div className={styles.topContaner}> <div className={styles.title} onClick={scrollToCanvas}> {t('图表分类')} </div> </div> <div className={styles.contentWrapper} style={{ height: heightStates.height }} > <div className={styles.rightbottom} /> <div className={styles.content}> <div key="block" className={styles.lefttop}> <div className={classNames(styles.mountNode, 'mountNode')} ref={element} /> <a href="https://github.com/antvis/G6" target="_blank" className={styles.canvasDescription} > Powered by G6 </a> <div onClick={handleFullScreen} className={classNames( styles.fullscreenExitIcon, styles.screenButton, )} style={{ display: screenStates.fullscreenDisplay }} > <FullscreenOutlined className={classNames( styles.fullscreenExitButton, styles.screenIcon, )} /> </div> <div onClick={handleExitFullscreen} className={classNames( styles.fullscreenExitButton, styles.screenButton, )} style={{ display: screenStates.exitfullscreenDisplay }} > <FullscreenExitOutlined className={classNames( styles.fullscreenExitIcon, styles.screenIcon, )} /> </div> </div> </div> {tooltip} </div> </div> ); }; export default DecisionTree;
the_stack
import { ProviderReadAttribute, ProviderReadWriteNotifyAttribute, ProviderReadNotifyAttribute, ProviderReadWriteAttribute } from "../../../../main/js/joynr/provider/ProviderAttribute"; import TestEnum from "../../../generated/joynr/tests/testTypes/TestEnum"; import ComplexRadioStation from "../../../generated/joynr/datatypes/exampleTypes/ComplexRadioStation"; import Country from "../../../generated/joynr/datatypes/exampleTypes/Country"; import TypeRegistrySingleton from "../../../../main/js/joynr/types/TypeRegistrySingleton"; describe("libjoynr-js.joynr.provider.ProviderAttribute", () => { let implementation: any; let isOn: ProviderReadWriteNotifyAttribute<boolean>; let isOnNotifyReadOnly: ProviderReadNotifyAttribute<boolean>; let isOnReadWrite: ProviderReadWriteAttribute<boolean>; let isOnReadOnly: ProviderReadAttribute<boolean>; let allAttributes: any[], allNotifyAttributes: any[]; beforeEach(() => { implementation = { value: { key: "value", 1: 0, object: {} }, get: jest.fn().mockImplementation(() => { return implementation.value; }), set: jest.fn().mockImplementation((newValue: any) => { implementation.value = newValue; }) }; const provider = {}; isOn = new ProviderReadWriteNotifyAttribute(provider, implementation, "isOn", "Boolean"); isOnNotifyReadOnly = new ProviderReadNotifyAttribute<boolean>( provider, implementation, "isOnNotifyReadOnly", "Boolean" ); isOnReadWrite = new ProviderReadWriteAttribute(provider, implementation, "isOnReadWrite", "Boolean"); isOnReadOnly = new ProviderReadAttribute(provider, implementation, "isOnReadOnly", "Boolean"); allAttributes = [isOn, isOnNotifyReadOnly, isOnReadWrite, isOnReadOnly]; allNotifyAttributes = [isOn, isOnNotifyReadOnly]; TypeRegistrySingleton.getInstance().addType(TestEnum); }); it("got initialized", done => { expect(isOn).toBeDefined(); expect(isOn).not.toBeNull(); expect(typeof isOn === "object").toBeTruthy(); done(); }); it("has correct members (ProviderAttribute with NOTIFYREADWRITE)", done => { expect(isOn.registerGetter).toBeDefined(); expect(isOn.registerSetter).toBeDefined(); expect(isOn.valueChanged).toBeDefined(); expect(isOn.registerObserver).toBeDefined(); expect(isOn.unregisterObserver).toBeDefined(); done(); }); it("has correct members (ProviderAttribute with NOTIFYREADONLY)", done => { expect(isOnNotifyReadOnly.registerGetter).toBeDefined(); // @ts-ignore expect(isOnNotifyReadOnly.registerSetter).toBeUndefined(); expect(isOnNotifyReadOnly.valueChanged).toBeDefined(); expect(isOnNotifyReadOnly.registerObserver).toBeDefined(); expect(isOnNotifyReadOnly.unregisterObserver).toBeDefined(); done(); }); it("has correct members (ProviderAttribute with READWRITE)", done => { expect(isOnReadWrite.registerGetter).toBeDefined(); expect(isOnReadWrite.registerSetter).toBeDefined(); // @ts-ignore expect(isOnReadWrite.valueChanged).toBeUndefined(); // @ts-ignore expect(isOnReadWrite.registerObserver).toBeUndefined(); // @ts-ignore expect(isOnReadWrite.unregisterObserver).toBeUndefined(); done(); }); it("has correct members (ProviderAttribute with READONLY)", done => { expect(isOnReadOnly.registerGetter).toBeDefined(); // @ts-ignore expect(isOnReadOnly.registerSetter).toBeUndefined(); // @ts-ignore expect(isOnReadOnly.valueChanged).toBeUndefined(); // @ts-ignore expect(isOnReadOnly.registerObserver).toBeUndefined(); // @ts-ignore expect(isOnReadOnly.unregisterObserver).toBeUndefined(); done(); }); it("call[G|S]etter calls through to registered [g|s]etters", done => { const testParam = "myTestParameter"; let promiseChain: any; const createFunc = function(attribute: any, promiseChain: Promise<any>) { const spy = jest.fn(); attribute.registerSetter(spy); return promiseChain .then(() => { return attribute.set(testParam); }) .then(() => { expect(spy).toHaveBeenCalled(); expect(spy).toHaveBeenCalledWith(testParam); }); }; promiseChain = Promise.all( allAttributes.map((attribute: any) => { if (attribute.get instanceof Function) { const spy = jest.fn(); spy.mockReturnValue(testParam); attribute.registerGetter(spy); return attribute.get().then((result: any) => { expect(spy).toHaveBeenCalled(); expect(result).toEqual([testParam]); }); } }) ); for (let i = 0; i < allAttributes.length; ++i) { if (allAttributes[i].set instanceof Function) { promiseChain = createFunc(allAttributes[i], promiseChain); } } promiseChain .then(() => { done(); return null; }) .catch(() => done.fail()); }); it("call[G|S]etter calls through to provided implementation", async () => { const testParam = "myTestParameter"; await Promise.all( allAttributes.map(async (attribute: any) => { // only check getter if the attribute is readable if (attribute.get instanceof Function) { implementation.get.mockClear(); implementation.get.mockReturnValue(testParam); const result = await attribute.get(); expect(implementation.get).toHaveBeenCalled(); expect(result).toEqual([testParam]); } }) ); for (let i = 0; i < allAttributes.length; ++i) { if (allAttributes[i].set instanceof Function) { const attribute = allAttributes[i]; implementation.set.mockClear(); await attribute.set(testParam); expect(implementation.set).toHaveBeenCalled(); expect(implementation.set).toHaveBeenCalledWith(testParam); } } }); it("implements the observer concept correctly", () => { const value = { key: "value", 1: 2, object: {} }; for (let i = 0; i < allNotifyAttributes.length; ++i) { const attribute = allNotifyAttributes[i]; const spy1 = jest.fn(); const spy2 = jest.fn(); attribute.registerObserver(spy1); attribute.registerObserver(spy2); expect(spy1).not.toHaveBeenCalled(); expect(spy2).not.toHaveBeenCalled(); attribute.valueChanged(value); expect(spy1).toHaveBeenCalled(); expect(spy1).toHaveBeenCalledWith([value]); expect(spy2).toHaveBeenCalled(); expect(spy2).toHaveBeenCalledWith([value]); attribute.unregisterObserver(spy2); attribute.valueChanged(value); expect(spy1.mock.calls.length).toEqual(2); expect(spy2.mock.calls.length).toEqual(1); attribute.unregisterObserver(spy1); attribute.valueChanged(value); expect(spy1.mock.calls.length).toEqual(2); expect(spy2.mock.calls.length).toEqual(1); } }); function setNewValueCallsValueChangedObserver(attribute: any, promiseChain: any) { const spy1 = jest.fn(); const spy2 = jest.fn(); attribute.registerObserver(spy1); attribute.registerObserver(spy2); expect(spy1).not.toHaveBeenCalled(); expect(spy2).not.toHaveBeenCalled(); let value = new ComplexRadioStation({ name: "nameValue", station: "stationValue", source: Country.GERMANY }); // expect 2 observers to be called return promiseChain .then(() => { return attribute.set(value); }) .then(() => { expect(spy1).toHaveBeenCalled(); expect(spy1).toHaveBeenCalledWith([value]); expect(spy2).toHaveBeenCalled(); expect(spy2).toHaveBeenCalledWith([value]); // expect one observer to be called attribute.unregisterObserver(spy2); value = new ComplexRadioStation({ name: "nameValue2", station: "stationValue2", source: Country.AUSTRIA }); return attribute.set(value); }) .then(() => { expect(spy1.mock.calls.length).toEqual(2); expect(spy2.mock.calls.length).toEqual(1); // expect no observers to be called, as none are registered attribute.unregisterObserver(spy1); value = new ComplexRadioStation({ name: "nameValue3", station: "stationValue3", source: Country.AUSTRALIA }); return attribute.set(value); }) .then(() => { expect(spy1.mock.calls.length).toEqual(2); expect(spy2.mock.calls.length).toEqual(1); }); } it("notifies observer when calling set with new value", async () => { const promiseChain = Promise.resolve(); for (let i = 0; i < allNotifyAttributes.length; ++i) { const attribute = allNotifyAttributes[i]; if (attribute.set) { await setNewValueCallsValueChangedObserver(attribute, promiseChain); } } }); async function setSameValueDoesNotCallValueChangedObserver(attribute: any) { const spy1 = jest.fn(); const spy2 = jest.fn(); attribute.registerObserver(spy1); attribute.registerObserver(spy2); expect(spy1).not.toHaveBeenCalled(); expect(spy2).not.toHaveBeenCalled(); const value = new ComplexRadioStation({ name: "nameValue", station: "stationValue", source: Country.GERMANY }); // expect 2 observers to be called await attribute.set(value); expect(spy1).toHaveBeenCalled(); expect(spy1).toHaveBeenCalledWith([value]); expect(spy2).toHaveBeenCalled(); expect(spy2).toHaveBeenCalledWith([value]); await attribute.set(value); expect(spy1.mock.calls.length).toEqual(1); expect(spy2.mock.calls.length).toEqual(1); } it("doesn't notify observer when calling set with same values", async () => { for (let i = 0; i < allNotifyAttributes.length; ++i) { const attribute = allNotifyAttributes[i]; if (attribute.set) { await setSameValueDoesNotCallValueChangedObserver(attribute); } } }); it("calls provided setter implementation with enum as operation argument", () => { const fixture = new ProviderReadWriteAttribute( {}, implementation, "testWithEnumAsAttributeType", TestEnum.ZERO._typeName ); return fixture.set("ZERO").then(() => { expect(implementation.set).toHaveBeenCalledWith(TestEnum.ZERO); }); }); });
the_stack
import { PdfDocument, PdfPage, PdfStandardFont, PdfTrueTypeFont, PdfGrid } from './../../../src/index'; import { PdfSolidBrush, PdfColor, PdfFont, PdfFontFamily, PdfStringFormat } from './../../../src/index'; import { RectangleF, PdfPen, PdfGraphicsState, PdfFontStyle, PdfTextAlignment,PdfPath, PointF,PdfArc, PdfFillMode, PdfLayoutBreakType, PdfLayoutType, PdfLayoutFormat } from './../../../src/index'; import { Utils } from './../utils.spec'; import { PdfShapeElement } from '../../../src/implementation/graphics/figures/base/pdf-shape-element'; import { ShapeLayouter } from '../../../src/implementation/graphics/figures/base/shape-layouter'; describe('UTC-01: Drawing Arc', () => { it('-EJ2-38403 Drawing arc1', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); //Arc bounds. let bounds : RectangleF = new RectangleF(0, 0, 200, 100); //Create new instance of PdfArc. let arc : PdfArc = new PdfArc(bounds, 0, 180); //Draw the arc to PDF page. arc.draw(page1, new PointF(0, 0)); //document.save('EJ2_38403_draw_arc1.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38403_draw_arc1.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-02: Drawing arc', () => { it('-EJ2-38403 Drawing arc2', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new instance of PdfArc. let arc : PdfArc = new PdfArc(200,100, 0, 180); // draw the arc arc.draw(page1, new PointF(50, 50)); // save the document. //document.save('EJ2_38403_draw_arc2.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38403_draw_arc2.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-03: Drawing Arc', () => { it('-EJ2-38403 Drawing Arc3', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); //Create new instance of PdfArc. let arc : PdfArc = new PdfArc(pen, 200, 100, 0, 180); //Draw the arc to PDF page. arc.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38403_draw_arc3.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38403_draw_arc3.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-04: Drawing Arc', () => { it('-EJ2-38403 Drawing Arc4', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new instance of PdfArc. let arc : PdfArc = new PdfArc(0,0,200,100, 0, 180); //Draw the arc to PDF page. arc.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38403_draw_arc4.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38403_draw_arc4.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-05: Drawing Arc', () => { it('-EJ2-38403 Drawing Arc5', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); //Create new instance of PdfArc. let arc : PdfArc = new PdfArc(pen, 0, 0, 200, 100, 0, 180); //Draw the arc to PDF page. arc.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38403_draw_arc5.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38403_draw_arc5.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-06: Drawing Arc', () => { it('-EJ2-38403 Drawing Arc6', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); let bounds : RectangleF = new RectangleF(0, 0, 200, 100); //Create new instance of PdfArc. let arc : PdfArc = new PdfArc(pen, bounds, 0, 180); //Draw the arc to PDF page. arc.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38403_draw_arc6.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38403_draw_arc6.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-07: Drawing Arc', () => { it('-EJ2-38403 Drawing Arc7', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); let bounds : RectangleF = new RectangleF(0, 0, 200, 100); //Create new instance of PdfArc. let arc : PdfArc = new PdfArc() arc.bounds = bounds; arc.pen = pen; arc.startAngle = 0; arc.sweepAngle = 180; //Draw the arc to PDF page. arc.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38403_draw_arc7.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38403_draw_arc7.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-08: Drawing Arc', () => { it('-EJ2-38403 Drawing Arc8', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); //Arc bounds. let bounds : RectangleF = new RectangleF(0, 0, 200, 100); //Create new instance of PdfArc. let arc : PdfArc = new PdfArc(bounds, 0, 180); //Draw PDF path to page. arc.draw(page1, 10, 10); // save the document. //document.save('EJ2_38403_draw_arc8.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38403_draw_arc8.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-09: Drawing Arc', () => { it('-EJ2-38403 Drawing Arc9', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let rect : RectangleF = new RectangleF(20, 30, 300, 100); //Arc bounds. let bounds : RectangleF = new RectangleF(0, 0, 200, 100); //Create new instance of PdfArc. let arc : PdfArc = new PdfArc(bounds, 0, 180); //Draw PDF path to page. arc.draw(page1, rect); // save the document. //document.save('EJ2_38403_draw_arc9.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38403_draw_arc9.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-10: Drawing Arc', () => { it('-EJ2-38403 Drawing Arc10', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); //Arc bounds. let bounds : RectangleF = new RectangleF(0, 0, 200, 100); //Create new instance of PdfArc. let arc : PdfArc = new PdfArc(bounds, 0, 180); let rect : RectangleF = new RectangleF(0, 0, 300, 100); let layoutFormat : PdfLayoutFormat = new PdfLayoutFormat(); layoutFormat.break = PdfLayoutBreakType.FitElement; layoutFormat.layout = PdfLayoutType.Paginate; layoutFormat.paginateBounds = new RectangleF(0, 0, 500, 350); //Draw PDF path to page. arc.draw(page1, rect, layoutFormat); // save the document. //document.save('EJ2_38403_draw_arc10.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38403_draw_arc10.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-11: Drawing Arc', () => { it('-EJ2-38403 Drawing Arc11', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); //Arc bounds. let bounds : RectangleF = new RectangleF(0, 0, 200, 100); //Create new instance of PdfArc. let arc : PdfArc = new PdfArc(bounds, 0, 180); let layoutFormat : PdfLayoutFormat = new PdfLayoutFormat(); layoutFormat.break = PdfLayoutBreakType.FitElement; layoutFormat.layout = PdfLayoutType.Paginate; layoutFormat.paginateBounds = new RectangleF(0, 0, 500, 350); //Draw PDF path to page. arc.draw(page1, 10, 30, layoutFormat); // save the document. //document.save('EJ2_38403_draw_arc11.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38403_draw_arc11.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-12: Drawing Arc', () => { it('-EJ2-38403 Drawing Acr12 ', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); //Arc bounds. let bounds : RectangleF = new RectangleF(0, 0, 200, 100); //Create new instance of PdfArc. let arc : PdfArc = new PdfArc(bounds, 0, 180); let layoutFormat : PdfLayoutFormat = new PdfLayoutFormat(); layoutFormat.break = PdfLayoutBreakType.FitElement; layoutFormat.layout = PdfLayoutType.Paginate; layoutFormat.paginateBounds = new RectangleF(0, 0, 500, 350); //Draw PDF path to page. arc.draw(page1, new PointF(10, 30), layoutFormat); // save the document. //document.save('EJ2_38403_draw_arc12.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38403_draw_arc12.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-13: Drawing Arc', () => { it('-EJ2-38403 Drawing Acr13 ', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); // set pen let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); // draw the path page1.graphics.drawArc(pen, 10, 10, 100, 200, 90, 270); // save the document. //document.save('EJ2_38403_draw_arc13.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38403_draw_arc13.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-14: Drawing Arc', () => { it('-EJ2-38403 Drawing Acr14 ', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let bounds : RectangleF = new RectangleF(10, 10, 100, 200); // set pen let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); // draw the path page1.graphics.drawArc(pen, bounds, 90, 270); // save the document. //document.save('EJ2_38403_draw_arc14.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38403_draw_arc14.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('PdfArc.ts', () => { describe('Constructor initializing',()=> { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); let brush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); let bounds : RectangleF = new RectangleF(0, 0, 200, 100); //Create new PDF Arc. let arc : PdfArc = new PdfArc(pen, bounds, 0, 180); let arc1 : PdfArc = new PdfArc(); arc1.x = 0; arc1.y = 0; arc1.width = 200; arc1.height = 100; arc1.startAngle = 0; arc1.sweepAngle = 180; let arc2 : PdfArc = new PdfArc(pen, 0, 0, 200, 100, 0, 180); let x: number = arc2.x; let y : number = arc2.y; let width : number = arc2.width; let height : number = arc2.height; it('-AddArc() method graphics helper calling)', () => { expect(function (): void {arc.drawGraphicsHelper(null, new PointF(0,0)); }).toThrowError(); }) it('-AddArc() Draw internal calling)', () => { expect(function (): void {arc.drawInternal(null); }).toThrowError(); }) }) })
the_stack
import { Component } from 'vue-property-decorator'; import { scaleLinear } from 'd3-scale'; import { select } from 'd3-selection'; import _ from 'lodash'; import $ from 'jquery'; import template from './heatmap.html'; import { Visualization, injectVisualizationTemplate, Scale, PlotMargins, DEFAULT_PLOT_MARGINS, getScale, multiplyVisuals, drawBrushBox, getBrushBox, AnyScale, } from '@/components/visualization'; import { fadeOut, getTransform } from '@/common/util'; import { getColorScale } from '@/common/color-scale'; import { SELECTED_COLOR } from '@/common/constants'; import { valueComparator, isContinuousDomain } from '@/data/util'; import { VisualProperties } from '@/data/visuals'; import ColorScaleSelect from '@/components/color-scale-select/color-scale-select'; import ColumnList from '@/components/column-list/column-list'; import ColumnSelect from '@/components/column-select/column-select'; import * as history from './history'; import { HistoryNodeEvent } from '@/store/history/types'; const DEFAULT_NUM_COLUMNS = 6; const ROW_LABEL_X_OFFSET_PX = 8; const COLUMN_LABEL_Y_OFFSET_PX = 8; const LABEL_SIZE_X_PX = 6; const LABEL_SIZE_Y_PX = 9; const SELECTED_ITEM_VISUALS = { border: SELECTED_COLOR, color: '#333', width: 1.5, }; interface HeatmapSave { columns: number[]; sortByColumn: number | null; colorScaleId: string; rowLabelColumn: number | null; areColumnLabelsVisible: boolean; } interface HeatmapItemProps { index: number; visuals: VisualProperties; label: string; hasVisuals: boolean; selected: boolean; cells: HeatmapCellProps[]; } interface HeatmapCellProps { columnIndex: number; color: string; } @Component({ template: injectVisualizationTemplate(template), components: { ColorScaleSelect, ColumnList, ColumnSelect, }, }) export default class Heatmap extends Visualization { protected NODE_TYPE = 'heatmap'; protected DEFAULT_WIDTH = 300; protected DEFAULT_HEIGHT = 350; private columns: number[] = []; private sortByColumn: number | null = null; private colorScaleId: string = 'red-green'; private rowLabelColumn: number | null = null; private areColumnLabelsVisible = true; private areColumnLabelsVertical = false; private areColumnLabelsVerticalChanged = false; // Scale in column direction private xScale!: Scale; // Scale in row direction private yScale!: Scale; // Scales from column values to [0, 1]. private columnScales!: Scale[]; private itemProps: HeatmapItemProps[] = []; private margins: PlotMargins = _.clone(DEFAULT_PLOT_MARGINS); public setColumns(columns: number[]) { this.columns = columns; this.draw(); } public applyColumns(columns: number[]) { if (!this.columns.length) { this.findDefaultColumns(); } else { this.columns = columns; } if (this.hasDataset()) { this.draw(); } } public setColorScale(colorScaleId: string) { this.colorScaleId = colorScaleId; this.draw(); } public setSortByColumn(column: number | null) { this.sortByColumn = column; this.draw(); } public setRowLabelColumn(column: number | null) { this.rowLabelColumn = column; this.draw(); } public setColumnLabelsVisible(value: boolean) { this.areColumnLabelsVisible = value; this.draw(); } protected created() { this.serializationChain.push((): HeatmapSave => ({ columns: this.columns, sortByColumn: this.sortByColumn, colorScaleId: this.colorScaleId, rowLabelColumn: this.rowLabelColumn, areColumnLabelsVisible: this.areColumnLabelsVisible, })); } protected draw() { this.drawHeatmap(); this.drawColumnLabels(); } protected brushed(brushPoints: Point[], isBrushStop?: boolean) { if (isBrushStop) { this.computeBrushedItems(brushPoints); this.computeSelection(); this.drawHeatmap(); this.propagateSelection(); } drawBrushBox(this.$refs.brush as SVGElement, !isBrushStop ? brushPoints : []); } protected findDefaultColumns() { if (!this.hasDataset()) { return; } const dataset = this.getDataset(); this.columns = dataset.getColumns() .filter(column => isContinuousDomain(column.type)) .slice(0, DEFAULT_NUM_COLUMNS) .map(column => column.index); } private computeBrushedItems(brushPoints: Point[]) { if (!this.isShiftPressed || !brushPoints.length) { this.selection.clear(); // reset selection if shift key is not down if (!brushPoints.length) { return; } } const box = getBrushBox(brushPoints); this.itemProps.forEach((props, rowIndex) => { const yl = this.yScale(rowIndex + 1); const yr = this.yScale(rowIndex); if (yr >= box.y && yl <= box.y + box.height) { this.selection.addItem(props.index); } }); } private drawHeatmap() { this.computeScales(); this.computeItemProps(); // Must be before updating left margin. Otherwise label strings are unknown. this.updateLeftMargin(); this.updateTopMargin(); this.drawGrid(); this.moveSelectedRowsToFront(); // Row labels are drawn based on xScale which may change for heatmap. this.drawRowLabels(); } private moveSelectedRowsToFront() { const $grid = $(this.$refs.grid); $grid.find('g[has-visuals=true]').appendTo(this.$refs.grid as SVGGElement); $grid.find('g[is-selected=true]').appendTo(this.$refs.grid as SVGGElement); } private computeItemProps() { const dataset = this.getDataset(); const colorScale = getColorScale(this.colorScaleId); const items = this.inputPortMap.in.getSubsetPackage().getItems(); if (this.sortByColumn !== null) { const columnType = dataset.getColumnType(this.sortByColumn); items.sort((a, b) => { const aValue = dataset.getCell(a.index, this.sortByColumn as number); const bValue = dataset.getCell(b.index, this.sortByColumn as number); // Heatmap draws from bottom to top. We want to sort from top to botto so we invert the sign. return -valueComparator(columnType)(aValue, bValue); }); } this.itemProps = items.map(item => { const props: HeatmapItemProps = { index: item.index, label: this.rowLabelColumn !== null ? dataset.getCell(item, this.rowLabelColumn).toString() : '', cells: this.columns.map((columnIndex, gridColumnIndex) => { const value = dataset.getCellForScale(item, columnIndex); return { columnIndex, color: colorScale(this.columnScales[gridColumnIndex](value)), }; }), visuals: _.clone(item.visuals), hasVisuals: !_.isEmpty(item.visuals), selected: this.selection.hasItem(item.index), }; if (props.selected) { _.extend(props.visuals, SELECTED_ITEM_VISUALS); multiplyVisuals(props.visuals); } return props; }); } private computeScales() { const pkg = this.inputPortMap.in.getSubsetPackage(); const numItems = pkg.numItems(); this.xScale = scaleLinear() .domain([0, this.columns.length]) .range([this.margins.left, this.svgWidth - this.margins.right]) as Scale; this.yScale = scaleLinear() .domain([0, numItems]) .range([this.svgHeight - this.margins.bottom, this.margins.top]) as Scale; const dataset = this.getDataset(); this.columnScales = this.columns.map(columnIndex => { return getScale( dataset.getColumnType(columnIndex), dataset.getDomain(columnIndex, pkg.getItemIndices()), [0, 1], ); }); } private updateLeftMargin() { if (this.rowLabelColumn !== null) { this.updateMargins(() => { this.drawRowLabels(); const maxLabelWidth = _.max($(this.$refs.rowLabels as SVGGElement).find('.label') .map((index: number, element: SVGGraphicsElement) => element.getBBox().width)) || 0; this.margins.left = DEFAULT_PLOT_MARGINS.left + maxLabelWidth; }); } else { this.margins.left = DEFAULT_PLOT_MARGINS.left; } (this.xScale as AnyScale).range([this.margins.left, this.svgWidth - this.margins.right]); } private updateTopMargin() { this.margins.top = DEFAULT_PLOT_MARGINS.top; if (this.areColumnLabelsVisible) { // TODO: we are not using virtual rendering to determine the maximum label length here. const dataset = this.getDataset(); const columnWidth = (this.svgWidth - this.margins.left - this.margins.right) / this.columns.length; const maxColumnNameLength = _.max(this.columns.map(columnIndex => dataset.getColumnName(columnIndex).length)) || 0; const oldVertical = this.areColumnLabelsVertical; if (columnWidth < maxColumnNameLength * LABEL_SIZE_X_PX) { this.areColumnLabelsVertical = true; this.margins.top += LABEL_SIZE_X_PX * maxColumnNameLength; } else { this.areColumnLabelsVertical = false; this.margins.top += LABEL_SIZE_Y_PX + COLUMN_LABEL_Y_OFFSET_PX; } if (this.areColumnLabelsVertical !== oldVertical) { this.areColumnLabelsVerticalChanged = true; } } (this.yScale as AnyScale).range([this.svgHeight - this.margins.bottom, this.margins.top]); } private drawGrid() { let rows = select(this.$refs.grid as SVGGElement).selectAll<SVGGElement, HeatmapItemProps>('g') .data(this.itemProps, d => d.index.toString()); fadeOut(rows.exit()); rows = rows.enter().append<SVGGElement>('g') .style('opacity', 0) .attr('id', d => d.index) .merge(rows) .attr('has-visuals', d => d.hasVisuals) .attr('is-selected', d => d.selected); const updatedRows = this.isTransitionFeasible(this.itemProps.length) ? rows.transition() : rows; updatedRows .style('stroke', d => d.visuals.border as string) .style('stroke-width', d => d.visuals.width + 'px') .attr('transform', (d, index) => getTransform([0, this.yScale(index + 1)])) .style('opacity', 1); const cellWidth = Math.ceil(this.xScale(1) - this.xScale(0)); const cellHeight = Math.ceil(this.yScale(0) - this.yScale(1)); const cellTransform = (cell: HeatmapCellProps, index: number) => getTransform([this.xScale(index), 0]); let cells = rows.selectAll<SVGRectElement, HeatmapCellProps>('rect') .data(d => d.cells, d => d.columnIndex.toString()); fadeOut(cells.exit()); cells = cells.enter().append<SVGRectElement>('rect') .style('opacity', 0) .attr('id', d => d.columnIndex) .attr('transform', cellTransform) .merge(cells); const updatedCells = this.isTransitionFeasible(this.itemProps.length) ? cells.transition() : cells; updatedCells .attr('fill', d => d.color) .attr('transform', cellTransform) .attr('width', cellWidth) .attr('height', cellHeight) .style('opacity', 1); } private drawRowLabels() { const svgRowLabels = select(this.$refs.rowLabels as SVGGElement); if (this.rowLabelColumn === null) { fadeOut(svgRowLabels.selectAll('*')); return; } const cellHeight = this.yScale(0) - this.yScale(1); const labelTransform = (row: HeatmapItemProps, index: number) => getTransform([ this.margins.left - ROW_LABEL_X_OFFSET_PX, this.yScale(index + 1) + cellHeight / 2, ]); let labels = svgRowLabels.selectAll<SVGTextElement, HeatmapItemProps>('text') .data(this.itemProps, d => d.index.toString()); fadeOut(labels.exit()); labels = labels.enter().append<SVGTextElement>('text') .attr('id', d => d.index) .attr('transform', labelTransform) .classed('label', true) .merge(labels) .text(d => d.label); const updatedLabels = this.isTransitionFeasible(this.itemProps.length) ? labels.transition() : labels; updatedLabels .style('fill', d => d.visuals.color as string) .style('stroke', d => d.visuals.border as string) .attr('transform', labelTransform); } private drawColumnLabels() { const svgColumnLabels = select(this.$refs.columnLabels as SVGGElement); if (!this.areColumnLabelsVisible) { fadeOut(svgColumnLabels.selectAll('*')); return; } let labelTransform: (columnIndex: number, index: number) => string; svgColumnLabels.classed('vertical', this.areColumnLabelsVertical); if (this.areColumnLabelsVertical) { labelTransform = (columnIndex, gridColumnIndex) => getTransform( [this.xScale(gridColumnIndex + .5) + LABEL_SIZE_Y_PX / 2, this.margins.top - COLUMN_LABEL_Y_OFFSET_PX], 1, -90, ); } else { labelTransform = (columnIndex, gridColumnIndex) => getTransform( [this.xScale(gridColumnIndex + .5), this.margins.top - COLUMN_LABEL_Y_OFFSET_PX], ); } const dataset = this.getDataset(); let labels = svgColumnLabels.selectAll<SVGTextElement, number>('.label') .data(this.columns, columnIndex => columnIndex.toString()); fadeOut(labels.exit()); labels = labels.enter().append<SVGTextElement>('text') .attr('id', d => d.toString()) .classed('label', true) .attr('transform', labelTransform) .merge(labels) .text(d => dataset.getColumnName(d)); let updatedLabels = this.isTransitionFeasible(this.columns.length) ? labels.transition() : labels; if (this.areColumnLabelsVerticalChanged) { this.areColumnLabelsVerticalChanged = false; let counter = updatedLabels.size(); updatedLabels = updatedLabels.transition() .on('end', () => { if (--counter === 0) { this.drawColumnLabels(); } }); } updatedLabels.attr('transform', labelTransform); } private onSelectColumns(columns: number[], prevColumns: number[]) { this.commitHistory(history.selectColumnsEvent(this, columns, prevColumns)); this.setColumns(columns); } private onSelectColorScale(colorScaleId: string, prevColorScaleId: string) { this.commitHistory(history.selectColorScaleEvent(this, colorScaleId, prevColorScaleId)); this.setColorScale(colorScaleId); } private onSelectSortByColumn(column: number | null, prevColumn: number | null) { this.commitHistory(history.selectSortByColumnEvent(this, column, prevColumn)); this.setSortByColumn(column); } private onSelectRowLabelColumn(column: number | null, prevColumn: number | null) { this.commitHistory(history.selectRowLabelColumnEvent(this, column, prevColumn)); this.setRowLabelColumn(column); } private onToggleColumnLabelsVisible(value: boolean) { this.commitHistory(history.toggleColumnLabelsVisibleEvent(this, value)); this.setColumnLabelsVisible(value); } }
the_stack
import { addCommand } from "../cmd"; import { exit } from "../lib/process"; import { Argv } from "yargs"; import { dispatch, initCore } from "../lib/core"; import { BaseArgs } from "../types"; import { authz, getEnvironmentsByEnvParentId, graphTypes, } from "@core/lib/graph"; import chalk from "chalk"; import Table from "cli-table3"; import { Api, Client, Logs, Model } from "@core/types"; import { findEnvironment } from "../lib/envs"; import { findApp, findBlock, findCliUser, findUser, logAndExitIfActionFailed, } from "../lib/args"; import { dateFromRelativeTime } from "@core/lib/utils/date"; import { autoModeOut, isAutoMode, getPrompt, alwaysWriteError, } from "../lib/console_io"; import moment from "moment"; import "moment-timezone"; const TZ_NAME = moment.tz.guess(); const TZ_ABBREV = moment.tz(TZ_NAME).zoneAbbr(); addCommand((yargs: Argv<BaseArgs>) => yargs.command( "logs", "View and filter audit logs.", (yargs) => yargs .option("host", { type: "boolean", describe: "View all logs for all orgs on the host (self-hosted only)", }) .option("errors", { type: "boolean", alias: ["error"], describe: "Filter by actions which resulted in errors", conflicts: ["no-errors"], }) .option("no-errors", { type: "boolean", describe: "Filter by actions which did not result in errors", }) .option("auth", { type: "boolean", describe: "Filter to actions related to authentication and authorization", conflicts: ["host"], }) .option("updates", { type: "boolean", describe: "Filter to all organization changes", conflicts: ["host"], }) .option("env-updates", { type: "boolean", describe: "Filter to environment config changes", }) .option("access", { type: "boolean", describe: "Filter to actions related to any fetch actions", conflicts: ["host"], }) .option("envkey-access", { type: "boolean", describe: "Filter to actions related to envkey fetches", conflicts: ["host", "client-access"], }) .option("client-access", { type: "boolean", describe: "Filter to actions related to user fetches", conflicts: ["host", "envkey-access"], }) .option("server-access", { type: "boolean", describe: "Filter to actions related to server envkey fetches", conflicts: [ "host", "envkey-access", "auth", "updates", "access", "envkey-access", "client-access", "local-access", ], }) .option("local-access", { type: "boolean", describe: "Filter to actions related to local key fetches", conflicts: [ "host", "envkey-access", "auth", "updates", "access", "envkey-access", "client-access", "server-access", ], }) .option("from", { type: "string", alias: ["start-time"], describe: "Show logs starting from this date-time, also supports time periods like 120s, 2m, 1h, 1d", coerce: coerceDate, }) .option("until", { type: "string", alias: ["end-time"], describe: "Show logs up to this date-time, also supports time periods like 120s, 2m, 1h, 1d", coerce: coerceDate, }) .option("person", { type: "string", alias: ["u"], describe: "Show actions done by, or done to, a specific person (email address)", conflicts: ["app", "block", "environment"], }) .option("desc", { type: "boolean", alias: ["descending"], describe: "Show newest logs first (default)", conflicts: ["asc"], }) .option("asc", { type: "boolean", alias: ["ascending"], describe: "Show oldest logs first", conflicts: ["desc"], }) .option("app", { type: "string", describe: "Show logs for a specific app", conflicts: ["block"], }) .option("block", { type: "string", describe: "Show logs for a specific block", }) .option("environment", { type: "string", alias: ["e"], describe: "Show logs for a specific environment", }) .option("local-overrides", { type: "string", alias: ["locals"], describe: "Show local override logs for a user (by email)", }) .option("ips", { type: "string", alias: ["ip"], describe: "Show logs for a specific accessor IP address using a comma-separated list of IPs", }) .option("envkey-short", { type: "string", describe: "Show logs for a generated envkey using its (by short key such as `6Lzi`)", conflicts: ["person", "local-overrides", "ips"], }) .option("page", { type: "number", alias: "p", describe: "Page number", }), async (argv) => { const prompt = getPrompt(); let { state, auth } = await initCore(argv, true); const exitWrapper = async (code: number = 0) => { await dispatch({ type: Client.ActionType.CLEAR_LOGS }); return exit(code); }; const payload = { pageNum: argv["page"] ? argv["page"] - 1 : 0, pageSize: isAutoMode() ? 100 : Math.floor(process.stdout.rows / 2 / 2), scope: "org", startsAt: argv.from, endsAt: argv.until ?? Date.now(), sortDesc: argv.desc || !argv.asc, error: argv["errors"] ? true : argv["no-errors"] ? false : undefined, } as Api.Net.ApiParamTypes["FetchLogs"]; // payload params that are highly modified are better added later (TS) const loggableTypes: Api.Net.ApiParamTypes["FetchLogs"]["loggableTypes"] = []; const actionTypes: string[] = []; let targetIds: string[] = []; // processing flags if (argv.host) { payload.scope = "host"; } // loggableTypes if (argv.auth) { loggableTypes.push("authAction"); } if (argv.updates) { loggableTypes.push("orgAction"); } if (argv.access) { loggableTypes.push("fetchMetaAction", "fetchEnvkeyAction"); } if (argv["envkey-access"]) { loggableTypes.push("fetchEnvkeyAction"); } if (argv["client-access"]) { loggableTypes.push("fetchMetaAction"); } if (argv["server-access"]) { loggableTypes.push("fetchEnvkeyAction"); targetIds.push(...graphTypes(state.graph).servers.map((s) => s.id)); } if (argv["local-access"]) { loggableTypes.push("fetchEnvkeyAction"); targetIds.push(...graphTypes(state.graph).localKeys.map((s) => s.id)); } // actionTypes if (argv["env-updates"]) { actionTypes.push(Api.ActionType.UPDATE_ENVS); } if (argv["environment"]) { // pass all environmentIds matching any app or block const { apps, blocks } = graphTypes(state.graph); const envIds: string[] = []; [...apps.map((a) => a.id), ...blocks.map((b) => b.id)].forEach( (envParentId) => { const env = findEnvironment( state.graph, envParentId, argv["environment"]! ); if (env) { envIds.push(env.id); } } ); targetIds.push(...envIds); } if (argv["person"]) { const user = findUser(state.graph, argv["person"]) || findCliUser(state.graph, argv["person"]); if (!user) { alwaysWriteError("person not found"); await exitWrapper(1); } payload.userIds = [user!.id]; targetIds.push(user!.id); } if (argv["app"]) { const appId = findApp(state.graph, argv["app"])?.id as string; if (!appId) { alwaysWriteError("app not found"); await exitWrapper(1); } const envs = getEnvironmentsByEnvParentId(state.graph)[appId]; if (envs) { targetIds.push(...envs.map((e) => e.id)); } } if (argv["block"]) { const blockId = findBlock(state.graph, argv["block"])?.id as string; if (!blockId) { alwaysWriteError("block not found"); await exitWrapper(1); } const envs = getEnvironmentsByEnvParentId(state.graph)[blockId]; if (envs) { targetIds.push(...envs.map((e) => e.id)); } } if (argv["local-overrides"]) { if (!targetIds.length) { // for some reason, yargs `check` did not work, but that would have been preferred alwaysWriteError( "local-overrides requires a valid app, block, or environment flag" ); await exitWrapper(1); } const user = findUser(state.graph, argv["local-overrides"]) || findCliUser(state.graph, argv["local-overrides"]); if (!user) { alwaysWriteError("local-overrides user not found"); await exitWrapper(1); } targetIds = targetIds.map((targetId) => `${targetId}|${user!.id}`); } if (argv["ips"]) { payload.ips = argv["ips"].split(","); } if (argv["envkey-short"]) { const generatedKey = graphTypes(state.graph).generatedEnvkeys.find( (g) => g.envkeyShort === argv["envkey-short"] ); if (!generatedKey) { alwaysWriteError("envkey-short not matched to generated envkey"); await exitWrapper(1); } targetIds.push(generatedKey!.id); } // final defaults, if options weren't provided payload.loggableTypes = loggableTypes.length ? loggableTypes : Logs.ORG_LOGGABLE_TYPES; payload.actionTypes = actionTypes.length ? actionTypes : undefined; payload.targetIds = targetIds.length ? targetIds : undefined; if (!authz.canFetchLogs(state.graph, auth.userId, auth.orgId, payload)) { alwaysWriteError( chalk.red.bold("You don't have permission to fetch the logs.") ); await exitWrapper(1); } let res: Client.DispatchResult; res = await dispatch({ type: Api.ActionType.FETCH_LOGS, payload: { ...payload, pageNum: 0 }, }); state = res.state; let totalLogsShown = state.loggedActionsWithTransactionIds.length; let totalLogsAvailable = <number>state.logsTotalCount; let totalPagesAvailable = Math.ceil( totalLogsAvailable / <number>payload.pageSize ); console.log( JSON.stringify({ totalLogsShown, totalLogsAvailable, totalPagesAvailable, }) ); readloop: while (true) { res = await dispatch({ type: Api.ActionType.FETCH_LOGS, payload, }); await logAndExitIfActionFailed(res, "Error fetching logs."); state = res.state; if (payload.pageNum == 0) { totalLogsShown = state.loggedActionsWithTransactionIds.length; totalLogsAvailable = <number>state.logsTotalCount; totalPagesAvailable = Math.ceil( totalLogsAvailable / <number>payload.pageSize ); } const directionText = payload.sortDesc ? "most recent first" : "oldest first"; const summary = `Page ${chalk.bold(payload.pageNum + 1)}${ isNaN(totalPagesAvailable) ? "" : " of " + totalPagesAvailable }, showing ${totalLogsShown} rows per page, ${directionText}.`; const choices: string[] = []; const instructions: string[] = []; if (payload.pageNum > 0 && totalLogsAvailable > 1) { choices.push("P"); instructions.push(`${chalk.bold("p")}revious`); } if (payload.pageNum < totalPagesAvailable - 1) { choices.push("N"); instructions.push(`${chalk.bold("n")}ext`); } if (choices.length > 0) { console.clear(); } console.log(""); writeLogTable( state.graph, state.deletedGraph || {}, state.loggedActionsWithTransactionIds.flatMap( ([, loggedActions]) => loggedActions ) ); autoModeOut({ pageNum: payload.pageNum, pageSize: payload.pageSize, totalCount: totalLogsAvailable, totalPages: totalPagesAvailable, logs: res.state.loggedActionsWithTransactionIds.flatMap( ([, loggedActions]) => loggedActions ) || [], }); if (isAutoMode()) { break; } if (choices.length == 0) { console.log(summary); break; } choices.push("Q"); instructions.push(`${chalk.bold("q")}uit`); // clear them to prevent building them up after paging await dispatch({ type: Client.ActionType.CLEAR_LOGS }); const { doNext } = await prompt<{ doNext: string }>({ type: "input", name: "doNext", required: true, // Here is the user display footer and instructions message: `${summary} ${chalk.blueBright( instructions.join(", ") )}, or page number:`, validate: (value) => choices.includes(value.toUpperCase()) || !isNaN(parseInt(value, 10)), }); const next = doNext.toUpperCase(); if (next == "P") { payload.pageNum = Math.max(0, payload.pageNum - 1); } else if (next == "N") { payload.pageNum = payload.pageNum + 1; } else if (next == "Q") { break readloop; } else { const possiblePageNumber = parseInt(doNext, 10); if (!isNaN(possiblePageNumber) && possiblePageNumber >= 0) { payload.pageNum = possiblePageNumber - 1; // zero based pagination } alwaysWriteError(chalk.blueBright(instructions)); } } await exitWrapper(0); } ) ); const isValidDateTime = (time: Date | object | null | undefined) => Boolean(time && time instanceof Date); const coerceDate = (value: string | undefined) => { if (!value) return; const time = dateFromRelativeTime(value); if (!isValidDateTime(time)) return; return +time!; }; const writeLogTable = ( graph: Client.Graph.UserGraph, deletedGraph: Client.Graph.UserGraph, logs: Logs.LoggedAction[] ) => { const table = new Table(); table.push( ...logs.map((l) => { let performedBy = ""; if (l.actorId) { const actor = graph[l.actorId] || deletedGraph[l.actorId]; if (!actor) { performedBy = "<unknown user>"; } else if (actor.type === "cliUser") { performedBy = `CLI: ${actor.name}`; } else if (actor.type === "orgUser") { performedBy = actor.email; } } // if (l.deviceId) { // const device = (graph[l.deviceId] || // deletedGraph[l.deviceId]) as Model.OrgUserDevice; // if (device) { // performedBy += ` - ${device.name}`; // } // } if ("generatedEnvkeyId" in l && l.generatedEnvkeyId) { const key = (graph[l.generatedEnvkeyId] || deletedGraph[l.generatedEnvkeyId]) as Model.GeneratedEnvkey; if (key) { const server = graph[key.keyableParentId] as Model.Server; performedBy = server ? server.name : "<unknown key>"; } } const errorOrOkMessage = l.error ? // ? `Error: ${l.errorStatus} ${l.errorReason}` `Error: ${l.errorStatus}` : "OK"; return [ performedBy, moment(l.createdAt).format(`YYYY-MM-DD HH:mm:ss.SSS`) + ` ${TZ_ABBREV}`, l.ip, l.actionType.split("/")[l.actionType.split("/").length - 1], errorOrOkMessage, ]; }) ); console.log(table.toString()); };
the_stack
import { PositionGizmo, RotationGizmo, ScaleGizmo, UtilityLayerRenderer, AbstractMesh, Node, TransformNode, LightGizmo, Light, IParticleSystem, Sound, Vector3, Quaternion, Camera, CameraGizmo, HemisphericLight, SkeletonViewer, Mesh, } from "babylonjs"; import { Nullable } from "../../../shared/types"; import { undoRedo } from "../tools/undo-redo"; import { InspectorNotifier } from "../gui/inspector/notifier"; import { Editor } from "../editor"; export enum GizmoType { None = 0, Position, Rotation, Scaling, } export class SceneGizmo { private _editor: Editor; public _gizmosLayer: UtilityLayerRenderer; private _currentGizmo: Nullable<PositionGizmo | RotationGizmo | ScaleGizmo> = null; private _positionGizmo: Nullable<PositionGizmo> = null; private _rotationGizmo: Nullable<RotationGizmo> = null; private _scalingGizmo: Nullable<ScaleGizmo> = null; private _lightGizmo: Nullable<LightGizmo> = null; private _cameraGizmo: Nullable<CameraGizmo> = null; private _initialValue: Nullable<Vector3 | Quaternion> = null; private _type: GizmoType = GizmoType.None; private _step: number = 0; private _skeletonViewer: Nullable<SkeletonViewer> = null; /** * Constructor. */ public constructor(editor: Editor) { this._editor = editor; // Create layer this._gizmosLayer = new UtilityLayerRenderer(editor.scene!); this._gizmosLayer.utilityLayerScene.postProcessesEnabled = false; // Register events this._editor.removedNodeObservable.add((n) => { if (this._currentGizmo && this._currentGizmo.attachedNode === n) { this.gizmoType = this._type; this.setAttachedNode(null); this._currentGizmo.attachedNode = null; } }) } /** * Returns the current type of gizmo being used in the preview. */ public get gizmoType(): GizmoType { return this._type; } /** * Sets the type of gizm to be used in the preview. */ public set gizmoType(type: GizmoType) { this._type = type; this._disposeGizmos(); if (type === GizmoType.None) { this._initialValue = null; return; } this._currentGizmo = null; switch (type) { case GizmoType.Position: this._currentGizmo = this._positionGizmo = new PositionGizmo(this._gizmosLayer); this._positionGizmo.planarGizmoEnabled = true; this._positionGizmo.onDragEndObservable.add(() => this._notifyGizmoEndDrag("position")); break; case GizmoType.Rotation: this._currentGizmo = this._rotationGizmo = new RotationGizmo(this._gizmosLayer, undefined, false); this._rotationGizmo.onDragEndObservable.add(() => { if (this._currentGizmo?.attachedMesh?.rotationQuaternion) { this._notifyGizmoEndDrag("rotationQuaternion"); } else { this._notifyGizmoEndDrag("rotation"); } }); break; case GizmoType.Scaling: this._currentGizmo = this._scalingGizmo = new ScaleGizmo(this._gizmosLayer); this._scalingGizmo.onDragEndObservable.add(() => this._notifyGizmoEndDrag("scaling")); break; } if (this._currentGizmo) { this._currentGizmo.snapDistance = this._step; this._currentGizmo.scaleRatio = 2.5; this._currentGizmo.onDragStartObservable.add(() => { if (!this._currentGizmo?.attachedMesh) { return; } switch (type) { case GizmoType.Position: this._initialValue = this._currentGizmo.attachedMesh.position.clone(); break; case GizmoType.Rotation: this._initialValue = this._currentGizmo.attachedMesh.rotationQuaternion?.clone() ?? Quaternion.Identity(); break; case GizmoType.Scaling: this._initialValue = this._currentGizmo.attachedMesh.scaling.clone(); break; } }); this._currentGizmo.xGizmo.dragBehavior.onDragObservable.add(() => this._notifyGizmoDrag()); this._currentGizmo.yGizmo.dragBehavior.onDragObservable.add(() => this._notifyGizmoDrag()); this._currentGizmo.zGizmo.dragBehavior.onDragObservable.add(() => this._notifyGizmoDrag()); if (this._positionGizmo) { this._positionGizmo.xPlaneGizmo.dragBehavior.onDragObservable.add(() => this._notifyGizmoDrag()); this._positionGizmo.yPlaneGizmo.dragBehavior.onDragObservable.add(() => this._notifyGizmoDrag()); this._positionGizmo.zPlaneGizmo.dragBehavior.onDragObservable.add(() => this._notifyGizmoDrag()); // A bit of hacking. this._positionGizmo.xPlaneGizmo["_coloredMaterial"].alpha = 0.3; this._positionGizmo.xPlaneGizmo["_hoverMaterial"].alpha = 1; this._positionGizmo.yPlaneGizmo["_coloredMaterial"].alpha = 0.3; this._positionGizmo.yPlaneGizmo["_hoverMaterial"].alpha = 1; this._positionGizmo.zPlaneGizmo["_coloredMaterial"].alpha = 0.3; this._positionGizmo.zPlaneGizmo["_hoverMaterial"].alpha = 1; } else if (this._scalingGizmo) { this._scalingGizmo.uniformScaleGizmo.dragBehavior.onDragObservable.add(() => this._notifyGizmoDrag()); } const node = this._editor.graph.lastSelectedObject; this.setAttachedNode(node); } } /** * Returns the current step used while using the gizmos. */ public get gizmoStep(): number { return this._step; } /** * Sets the current step used while using the gizmos. */ public set gizmoStep(steps: number) { this._step = steps; if (this._currentGizmo) { this._currentGizmo.snapDistance = steps; } } /** * Sets the given node attached to the current gizmos if exists. * @param node the node to attach to current gizmos if exists. */ public setAttachedNode(node: Nullable<Node | IParticleSystem | Sound>): void { // Skeleton gizmo if (this._skeletonViewer) { this._skeletonViewer.dispose(); this._skeletonViewer = null; } if (node instanceof Mesh && node.skeleton) { // this._skeletonViewer = new SkeletonViewer(node.skeleton, node, node.getScene(), false, (node.renderingGroupId > 0 ) ? node.renderingGroupId + 1 : 1, { // pauseAnimations: false, // returnToRest: false, // computeBonesUsingShaders: true, // useAllBones: false, // displayMode: SkeletonViewer.DISPLAY_SPHERE_AND_SPURS, // displayOptions: { // sphereBaseSize: 1, // sphereScaleUnit: 10, // sphereFactor: 0.9, // midStep: 0.1, // midStepFactor: 0.05, // } // }); } // Light? if (node instanceof Light) { this._setLightGizmo(node); } else { this._lightGizmo?.dispose(); this._lightGizmo = null; } // Camera? if (node instanceof Camera) { this._setCameraGizmo(node); } else { this._cameraGizmo?.dispose(); this._cameraGizmo = null; } // Camera or light? if (this._cameraGizmo || this._lightGizmo) { return; } // Mesh or transform node if (!node || !this._currentGizmo) { return; } // CHeck node has a billboard mode if (node instanceof TransformNode && node.billboardMode !== TransformNode.BILLBOARDMODE_NONE && this._type === GizmoType.Rotation) { return; } if (node instanceof AbstractMesh) { this._currentGizmo.attachedMesh = node; } else if (node instanceof Node) { this._currentGizmo.attachedNode = node; } } /** * Sets the light gizmo. */ private _setLightGizmo(light: Light): void { if (!this._lightGizmo) { this._lightGizmo = new LightGizmo(this._gizmosLayer); this._lightGizmo.scaleRatio = 2.5; } this._lightGizmo.light = light; if (!this._currentGizmo) { return; } if ((this._currentGizmo instanceof PositionGizmo || this._currentGizmo instanceof ScaleGizmo) && light instanceof HemisphericLight) { return; } this._currentGizmo.attachedMesh = this._lightGizmo.attachedMesh; } /** * Sets the camera gizmo. */ private _setCameraGizmo(camera: Camera): void { if (!this._cameraGizmo) { this._cameraGizmo = new CameraGizmo(this._gizmosLayer); } this._cameraGizmo.camera = camera; this._cameraGizmo.displayFrustum = true; if (this._currentGizmo) { this._currentGizmo.attachedNode = this._cameraGizmo.camera; } } /** * Disposes the currently enabled gizmos. */ private _disposeGizmos(): void { if (this._positionGizmo) { this._positionGizmo.dispose(); } if (this._rotationGizmo) { this._rotationGizmo.dispose(); } if (this._scalingGizmo) { this._scalingGizmo.dispose(); } if (this._lightGizmo) { this._lightGizmo.dispose(); } if (this._cameraGizmo) { this._cameraGizmo.dispose(); } this._currentGizmo = null; this._positionGizmo = null; this._rotationGizmo = null; this._scalingGizmo = null; this._lightGizmo = null; this._cameraGizmo = null; } /** * Notifies that the current gizmo is dragged. */ private _notifyGizmoDrag(): void { if (!this._currentGizmo) { return; } // Nothing to do for now... } /** * Notifies that the current gizmo ended dragging. * This is the place to support undo/redo. */ private _notifyGizmoEndDrag(propertyPath: string): void { if (!this._initialValue) { return; } const attachedMesh = this._currentGizmo?.attachedMesh; if (!attachedMesh) { return; } const property = attachedMesh[propertyPath]; if (!property || this._initialValue.equals(property)) { return; } const initialValue = this._initialValue.clone(); const endValue = property.clone(); const attachedLight = this._lightGizmo?.light; const attachedCamera = this._cameraGizmo?.camera; undoRedo.push({ description: `Changed object transform "${attachedMesh.name}" from "${endValue.toString()}" to "${initialValue.toString()}"`, common: () => InspectorNotifier.NotifyChange((attachedLight ?? attachedCamera ?? attachedMesh)[propertyPath]), redo: () => attachedMesh[propertyPath].copyFrom(endValue), undo: () => attachedMesh[propertyPath].copyFrom(initialValue), }); this._initialValue = null; } }
the_stack
import { App } from '../app/index'; // Import all public types with aliases, and re-export from the auth namespace. import { ActionCodeSettings as TActionCodeSettings } from './action-code-settings-builder'; import { Auth as TAuth } from './auth'; import { AuthFactorType as TAuthFactorType, AuthProviderConfig as TAuthProviderConfig, AuthProviderConfigFilter as TAuthProviderConfigFilter, CreateRequest as TCreateRequest, CreateMultiFactorInfoRequest as TCreateMultiFactorInfoRequest, CreatePhoneMultiFactorInfoRequest as TCreatePhoneMultiFactorInfoRequest, EmailSignInProviderConfig as TEmailSignInProviderConfig, ListProviderConfigResults as TListProviderConfigResults, MultiFactorCreateSettings as TMultiFactorCreateSettings, MultiFactorConfig as TMultiFactorConfig, MultiFactorConfigState as TMultiFactorConfigState, MultiFactorUpdateSettings as TMultiFactorUpdateSettings, OIDCAuthProviderConfig as TOIDCAuthProviderConfig, OIDCUpdateAuthProviderRequest as TOIDCUpdateAuthProviderRequest, SAMLAuthProviderConfig as TSAMLAuthProviderConfig, SAMLUpdateAuthProviderRequest as TSAMLUpdateAuthProviderRequest, UpdateAuthProviderRequest as TUpdateAuthProviderRequest, UpdateMultiFactorInfoRequest as TUpdateMultiFactorInfoRequest, UpdatePhoneMultiFactorInfoRequest as TUpdatePhoneMultiFactorInfoRequest, UpdateRequest as TUpdateRequest, } from './auth-config'; import { BaseAuth as TBaseAuth, DeleteUsersResult as TDeleteUsersResult, GetUsersResult as TGetUsersResult, ListUsersResult as TListUsersResult, SessionCookieOptions as TSessionCookieOptions, } from './base-auth'; import { EmailIdentifier as TEmailIdentifier, PhoneIdentifier as TPhoneIdentifier, ProviderIdentifier as TProviderIdentifier, UserIdentifier as TUserIdentifier, UidIdentifier as TUidIdentifier, } from './identifier'; import { CreateTenantRequest as TCreateTenantRequest, Tenant as TTenant, UpdateTenantRequest as TUpdateTenantRequest, } from './tenant'; import { ListTenantsResult as TListTenantsResult, TenantAwareAuth as TTenantAwareAuth, TenantManager as TTenantManager, } from './tenant-manager'; import { DecodedIdToken as TDecodedIdToken } from './token-verifier'; import { HashAlgorithmType as THashAlgorithmType, UserImportOptions as TUserImportOptions, UserImportRecord as TUserImportRecord, UserImportResult as TUserImportResult, UserMetadataRequest as TUserMetadataRequest, UserProviderRequest as TUserProviderRequest, } from './user-import-builder'; import { MultiFactorInfo as TMultiFactorInfo, MultiFactorSettings as TMultiFactorSettings, PhoneMultiFactorInfo as TPhoneMultiFactorInfo, UserInfo as TUserInfo, UserMetadata as TUserMetadata, UserRecord as TUserRecord, } from './user-record'; /** * Gets the {@link firebase-admin.auth#Auth} service for the default app or a * given app. * * `admin.auth()` can be called with no arguments to access the default app's * {@link firebase-admin.auth#Auth} service or as `admin.auth(app)` to access the * {@link firebase-admin.auth#Auth} service associated with a specific app. * * @example * ```javascript * // Get the Auth service for the default app * var defaultAuth = admin.auth(); * ``` * * @example * ```javascript * // Get the Auth service for a given app * var otherAuth = admin.auth(otherApp); * ``` * */ export declare function auth(app?: App): auth.Auth; /* eslint-disable @typescript-eslint/no-namespace */ export namespace auth { /** * Type alias to {@link firebase-admin.auth#ActionCodeSettings}. */ export type ActionCodeSettings = TActionCodeSettings; /** * Type alias to {@link firebase-admin.auth#Auth}. */ export type Auth = TAuth; /** * Type alias to {@link firebase-admin.auth#AuthFactorType}. */ export type AuthFactorType = TAuthFactorType; /** * Type alias to {@link firebase-admin.auth#AuthProviderConfig}. */ export type AuthProviderConfig = TAuthProviderConfig; /** * Type alias to {@link firebase-admin.auth#AuthProviderConfigFilter}. */ export type AuthProviderConfigFilter = TAuthProviderConfigFilter; /** * Type alias to {@link firebase-admin.auth#BaseAuth}. */ export type BaseAuth = TBaseAuth; /** * Type alias to {@link firebase-admin.auth#CreateMultiFactorInfoRequest}. */ export type CreateMultiFactorInfoRequest = TCreateMultiFactorInfoRequest; /** * Type alias to {@link firebase-admin.auth#CreatePhoneMultiFactorInfoRequest}. */ export type CreatePhoneMultiFactorInfoRequest = TCreatePhoneMultiFactorInfoRequest; /** * Type alias to {@link firebase-admin.auth#CreateRequest}. */ export type CreateRequest = TCreateRequest; /** * Type alias to {@link firebase-admin.auth#CreateTenantRequest}. */ export type CreateTenantRequest = TCreateTenantRequest; /** * Type alias to {@link firebase-admin.auth#DecodedIdToken}. */ export type DecodedIdToken = TDecodedIdToken; /** * Type alias to {@link firebase-admin.auth#DeleteUsersResult}. */ export type DeleteUsersResult = TDeleteUsersResult; /** * Type alias to {@link firebase-admin.auth#EmailIdentifier}. */ export type EmailIdentifier = TEmailIdentifier; /** * Type alias to {@link firebase-admin.auth#EmailSignInProviderConfig}. */ export type EmailSignInProviderConfig = TEmailSignInProviderConfig; /** * Type alias to {@link firebase-admin.auth#GetUsersResult}. */ export type GetUsersResult = TGetUsersResult; /** * Type alias to {@link firebase-admin.auth#HashAlgorithmType}. */ export type HashAlgorithmType = THashAlgorithmType; /** * Type alias to {@link firebase-admin.auth#ListProviderConfigResults}. */ export type ListProviderConfigResults = TListProviderConfigResults; /** * Type alias to {@link firebase-admin.auth#ListTenantsResult}. */ export type ListTenantsResult = TListTenantsResult; /** * Type alias to {@link firebase-admin.auth#ListUsersResult}. */ export type ListUsersResult = TListUsersResult; /** * Type alias to {@link firebase-admin.auth#MultiFactorCreateSettings}. */ export type MultiFactorCreateSettings = TMultiFactorCreateSettings; /** * Type alias to {@link firebase-admin.auth#MultiFactorConfig}. */ export type MultiFactorConfig = TMultiFactorConfig; /** * Type alias to {@link firebase-admin.auth#MultiFactorConfigState}. */ export type MultiFactorConfigState = TMultiFactorConfigState; /** * Type alias to {@link firebase-admin.auth#MultiFactorInfo}. */ export type MultiFactorInfo = TMultiFactorInfo; /** * Type alias to {@link firebase-admin.auth#MultiFactorUpdateSettings}. */ export type MultiFactorUpdateSettings = TMultiFactorUpdateSettings; /** * Type alias to {@link firebase-admin.auth#MultiFactorSettings}. */ export type MultiFactorSettings = TMultiFactorSettings; /** * Type alias to {@link firebase-admin.auth#OIDCAuthProviderConfig}. */ export type OIDCAuthProviderConfig = TOIDCAuthProviderConfig; /** * Type alias to {@link firebase-admin.auth#OIDCUpdateAuthProviderRequest}. */ export type OIDCUpdateAuthProviderRequest = TOIDCUpdateAuthProviderRequest; /** * Type alias to {@link firebase-admin.auth#PhoneIdentifier}. */ export type PhoneIdentifier = TPhoneIdentifier; /** * Type alias to {@link firebase-admin.auth#PhoneMultiFactorInfo}. */ export type PhoneMultiFactorInfo = TPhoneMultiFactorInfo; /** * Type alias to {@link firebase-admin.auth#ProviderIdentifier}. */ export type ProviderIdentifier = TProviderIdentifier; /** * Type alias to {@link firebase-admin.auth#SAMLAuthProviderConfig}. */ export type SAMLAuthProviderConfig = TSAMLAuthProviderConfig; /** * Type alias to {@link firebase-admin.auth#SAMLUpdateAuthProviderRequest}. */ export type SAMLUpdateAuthProviderRequest = TSAMLUpdateAuthProviderRequest; /** * Type alias to {@link firebase-admin.auth#SessionCookieOptions}. */ export type SessionCookieOptions = TSessionCookieOptions; /** * Type alias to {@link firebase-admin.auth#Tenant}. */ export type Tenant = TTenant; /** * Type alias to {@link firebase-admin.auth#TenantAwareAuth}. */ export type TenantAwareAuth = TTenantAwareAuth; /** * Type alias to {@link firebase-admin.auth#TenantManager}. */ export type TenantManager = TTenantManager; /** * Type alias to {@link firebase-admin.auth#UidIdentifier}. */ export type UidIdentifier = TUidIdentifier; /** * Type alias to {@link firebase-admin.auth#UpdateAuthProviderRequest}. */ export type UpdateAuthProviderRequest = TUpdateAuthProviderRequest; /** * Type alias to {@link firebase-admin.auth#UpdateMultiFactorInfoRequest}. */ export type UpdateMultiFactorInfoRequest = TUpdateMultiFactorInfoRequest; /** * Type alias to {@link firebase-admin.auth#UpdatePhoneMultiFactorInfoRequest}. */ export type UpdatePhoneMultiFactorInfoRequest = TUpdatePhoneMultiFactorInfoRequest; /** * Type alias to {@link firebase-admin.auth#UpdateRequest}. */ export type UpdateRequest = TUpdateRequest; /** * Type alias to {@link firebase-admin.auth#UpdateTenantRequest}. */ export type UpdateTenantRequest = TUpdateTenantRequest; /** * Type alias to {@link firebase-admin.auth#UserIdentifier}. */ export type UserIdentifier = TUserIdentifier; /** * Type alias to {@link firebase-admin.auth#UserImportOptions}. */ export type UserImportOptions = TUserImportOptions; /** * Type alias to {@link firebase-admin.auth#UserImportRecord}. */ export type UserImportRecord = TUserImportRecord; /** * Type alias to {@link firebase-admin.auth#UserImportResult}. */ export type UserImportResult = TUserImportResult; /** * Type alias to {@link firebase-admin.auth#UserInfo}. */ export type UserInfo = TUserInfo; /** * Type alias to {@link firebase-admin.auth#UserMetadata}. */ export type UserMetadata = TUserMetadata; /** * Type alias to {@link firebase-admin.auth#UserMetadataRequest}. */ export type UserMetadataRequest = TUserMetadataRequest; /** * Type alias to {@link firebase-admin.auth#UserProviderRequest}. */ export type UserProviderRequest = TUserProviderRequest; /** * Type alias to {@link firebase-admin.auth#UserRecord}. */ export type UserRecord = TUserRecord; }
the_stack
* Mailscript * 0.4.0 * DO NOT MODIFY - This file has been generated using oazapfts. * See https://www.npmjs.com/package/oazapfts */ import * as Oazapfts from 'oazapfts/lib/runtime' import * as QS from 'oazapfts/lib/runtime/query' export const defaults: Oazapfts.RequestOpts = { baseUrl: 'https://api.mailscript.com/v2', } const oazapfts = Oazapfts.runtime(defaults) export const servers = { apiServer: 'https://api.mailscript.com/v2', } export type User = { id: string displayName: string photoURL?: string email: string createdAt: string } export type ErrorResponse = { error: string } export type UpdateUserRequest = { displayName: string } export type SendRequest = { to: string from: string subject: string text?: string html?: string } export type AddWorkspaceRequest = { workspace: string } export type Workspace = { id: string owner: string createdAt: string createdBy: string } export type GetAllWorkspacesResponse = { list: Workspace[] } export type AddAddressRequest = { address: string } export type Address = { id: string owner: string displayName?: string createdAt: string createdBy: string } export type GetAllAddressesResponse = { list: Address[] } export type AddDomainRequest = { domain: string } export type DomainResponse = { domain: string records: { type: string name: string value: string }[] } export type GetAllDomainsResponse = { id?: string[] } export type CheckDomainVerify = { domain: string success: boolean } export type Criteria = { sentTo?: string subjectContains?: string from?: string domain?: string hasTheWords?: string hasAttachments?: boolean } export type Trigger = { id: string owner: string displayName?: string createdAt: string createdBy: string name: string criteria: Criteria } export type GetAllTriggersResponse = { list: Trigger[] } export type CriteriaOperand = { and?: string[] or?: string[] } export type AddTriggerRequest = { name: string criteria: Criteria | CriteriaOperand } export type AddTriggerResponse = { id: string } export type MailscriptEmailInput = { id: string name: string type: 'mailescript-email' owner: string createdAt: string createdBy: string address: string } export type GetAllInputsResponse = { list: MailscriptEmailInput[] } export type AddWorkflowRequest = { name: string input: string trigger?: string action: string } export type KeyValuePair = { key: string value: any } export type SetWorkflowRequest = { id: string pairs: KeyValuePair[] } export type Workflow = { id: string name: string owner: string createdAt: string createdBy: string input: string trigger: string action: string active?: boolean } export type GetAllWorkflowsResponse = { list: Workflow[] } export type Key = { id: string name: string read: boolean write: boolean createdBy: string createdAt: string } export type GetAllKeysResponse = { list: Key[] } export type AddKeyRequest = { name: string read: boolean write: boolean } export type AddKeyResponse = { id?: string } export type UpdateKeyRequest = { name: string read: boolean write: boolean } export type VerificationEmail = { id?: string type?: 'email' email?: string verified?: boolean verifiedBy?: string verifiedAt?: string } export type VerificationSms = { id?: string type?: 'sms' sms?: string verified?: boolean verifiedBy?: string verifiedAt?: string } export type GetAllVerificationsResponse = { list: (VerificationEmail | VerificationSms)[] } export type AddEmailVerificationRequest = { type: 'email' email: string } export type AddSmsVerificationRequest = { type: 'sms' sms: string } export type AddVerificationResponse = { id: string } export type VerifyEmailRequest = { email: string code: string } export type VerifySmsRequest = { sms: string code: string } export type ActionSend = { id: string name: string owner: string createdAt: string createdBy: string output: string config: { type: string subject: string text?: string html?: string } } export type ActionCombine = { id: string name: string owner: string createdAt: string createdBy: string list?: string[] } export type GetAllActionsResponse = { list: (ActionSend | ActionCombine)[] } export type AddActionCombineRequest = { name: string list: string[] } export type AddActionSmsRequest = { name: string type: 'sms' config: { number: string text: string } } export type AddActionWebhookRequest = { name: string type: 'webhook' config: { url: string opts: { headers: object method: 'POST' | 'GET' | 'DELETE' } body: string } } export type AddActionDaemonRequest = { name: string type: 'daemon' config: { daemon?: string body: string } } export type AddActionSendRequest = { name: string type: 'mailscript-email' config: { type?: 'send' to?: string subject: string text?: string html?: string from: string key: string } } export type AddActionForwardRequest = { name: string type: 'mailscript-email' config: { type: 'forward' forward: string from: string key: string } } export type AddActionReplyRequest = { name: string type: 'mailscript-email' config: { type: 'reply' text?: string html?: string from: string key: string } } export type AddActionReplyAllRequest = { name: string type: 'mailscript-email' config: { type: 'replyAll' text?: string html?: string from: string key: string } } export type AddActionAliasRequest = { name: string type: 'mailscript-email' config: { type?: 'alias' alias?: string } } export type AddActionResponse = { id: string } export type Integration = { id: string type: 'google' createdAt: string } export type GetAllIntegrationsResponse = { list: Integration[] } /** * Get the authenticated user */ export function getAuthenticatedUser(opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 200 data: User } | { status: 403 data: ErrorResponse } >('/user', { ...opts, }) } /** * Update a user */ export function updateUser( updateUserRequest: UpdateUserRequest, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 200 } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } >( '/user', oazapfts.json({ ...opts, method: 'PUT', body: updateUserRequest, }), ) } /** * Send an email */ export function send(sendRequest: SendRequest, opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 200 } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } >( '/send', oazapfts.json({ ...opts, method: 'POST', body: sendRequest, }), ) } /** * Claim a Mailscript workspace */ export function addWorkspace( addWorkspaceRequest: AddWorkspaceRequest, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 201 } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 405 data: ErrorResponse } >( '/workspaces', oazapfts.json({ ...opts, method: 'POST', body: addWorkspaceRequest, }), ) } /** * Get all workspaces you have access to */ export function getAllWorkspaces(opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 200 data: GetAllWorkspacesResponse } | { status: 403 data: ErrorResponse } | { status: 405 data: ErrorResponse } >('/workspaces', { ...opts, }) } /** * Claim a new Mailscript address */ export function addAddress( addAddressRequest: AddAddressRequest, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 200 } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 405 data: ErrorResponse } >( '/addresses', oazapfts.json({ ...opts, method: 'POST', body: addAddressRequest, }), ) } /** * Get all addresses you have access to */ export function getAllAddresses(opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 200 data: GetAllAddressesResponse } | { status: 403 data: ErrorResponse } | { status: 405 data: ErrorResponse } >('/addresses', { ...opts, }) } /** * Claim a new Domain */ export function addDomain( addDomainRequest: AddDomainRequest, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 200 data: DomainResponse } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 405 data: ErrorResponse } >( '/domains', oazapfts.json({ ...opts, method: 'POST', body: addDomainRequest, }), ) } /** * Get all domains you have access to */ export function getAllDomains(opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 200 data: GetAllDomainsResponse } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 405 data: ErrorResponse } >('/domains', { ...opts, }) } /** * Remove a domain */ export function removeDomainVerify( domain: string, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 200 } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 405 data: ErrorResponse } >(`/domains/${domain}`, { ...opts, method: 'DELETE', }) } /** * Get domain verification */ export function getDomainVerify(domain: string, opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 200 data: DomainResponse } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 405 data: ErrorResponse } >(`/domains/verify/${domain}`, { ...opts, }) } /** * Check a new Domain */ export function checkDomainVerify(domain: string, opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 200 data: CheckDomainVerify } | { status: 400 data: ErrorResponse } | { status: 401 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 405 data: ErrorResponse } >(`/domains/verify/${domain}`, { ...opts, method: 'POST', }) } /** * Delete a mailscript address */ export function deleteAddress(address: string, opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 204 } | { status: 403 data: ErrorResponse } | { status: 405 data: ErrorResponse } >(`/addresses/${address}`, { ...opts, method: 'DELETE', }) } /** * Get all triggers you have access to */ export function getAllTriggers(opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 200 data: GetAllTriggersResponse } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } >('/triggers', { ...opts, }) } /** * Setup a trigger */ export function addTrigger( addTriggerRequest: AddTriggerRequest, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 201 data: AddTriggerResponse } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } >( '/triggers', oazapfts.json({ ...opts, method: 'POST', body: addTriggerRequest, }), ) } /** * Update a trigger */ export function updateTrigger( trigger: string, addTriggerRequest: AddTriggerRequest, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 200 } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 404 data: ErrorResponse } >( `/triggers/${trigger}`, oazapfts.json({ ...opts, method: 'PUT', body: addTriggerRequest, }), ) } /** * Delete a trigger */ export function deleteTrigger(trigger: string, opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 204 } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 404 data: ErrorResponse } >(`/triggers/${trigger}`, { ...opts, method: 'DELETE', }) } /** * Get all inputs you have access to */ export function getAllInputs( { name, }: { name?: string } = {}, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 200 data: GetAllInputsResponse } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } >( `/inputs${QS.query( QS.form({ name, }), )}`, { ...opts, }, ) } /** * Setup workflow */ export function addWorkflow( addWorkflowRequest: AddWorkflowRequest, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 201 } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 405 data: ErrorResponse } >( '/workflows', oazapfts.json({ ...opts, method: 'POST', body: addWorkflowRequest, }), ) } /** * Set workflow property */ export function setWorkflow( setWorkflowRequest: SetWorkflowRequest, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 204 } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 405 data: ErrorResponse } >( '/workflows/set', oazapfts.json({ ...opts, method: 'POST', body: setWorkflowRequest, }), ) } /** * Get all workflows you have access to */ export function getAllWorkflows(opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 200 data: GetAllWorkflowsResponse } | { status: 403 data: ErrorResponse } | { status: 405 data: ErrorResponse } >('/workflows', { ...opts, }) } /** * Update an workflow */ export function updateWorkflow( workflow: string, addWorkflowRequest: AddWorkflowRequest, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 200 } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 404 data: ErrorResponse } >( `/workflows/${workflow}`, oazapfts.json({ ...opts, method: 'PUT', body: addWorkflowRequest, }), ) } /** * Delete a workflow */ export function deleteWorkflow(workflow: string, opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 204 } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 404 data: ErrorResponse } >(`/workflows/${workflow}`, { ...opts, method: 'DELETE', }) } /** * List address keys */ export function getAllKeys(address: string, opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 200 data: GetAllKeysResponse } | { status: 403 data: ErrorResponse } | { status: 404 data: ErrorResponse } >(`/addresses/${address}/keys`, { ...opts, }) } /** * Add address key */ export function addKey( address: string, addKeyRequest: AddKeyRequest, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 201 data: AddKeyResponse } | { status: 403 data: ErrorResponse } | { status: 404 data: ErrorResponse } >( `/addresses/${address}/keys`, oazapfts.json({ ...opts, method: 'POST', body: addKeyRequest, }), ) } /** * Get address key */ export function getKey( address: string, key: string, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 200 data: Key } | { status: 403 data: ErrorResponse } | { status: 404 data: ErrorResponse } >(`/addresses/${address}/keys/${key}`, { ...opts, }) } /** * Update an address key */ export function updateKey( address: string, key: string, updateKeyRequest: UpdateKeyRequest, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 200 data: Key } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 404 data: ErrorResponse } >( `/addresses/${address}/keys/${key}`, oazapfts.json({ ...opts, method: 'PUT', body: updateKeyRequest, }), ) } /** * Delete address key */ export function deleteKey( address: string, key: string, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 204 } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 404 data: ErrorResponse } >(`/addresses/${address}/keys/${key}`, { ...opts, method: 'DELETE', }) } /** * Get all verificats for the user */ export function getAllVerifications(opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 200 data: GetAllVerificationsResponse } | { status: 403 data: ErrorResponse } >('/verifications', { ...opts, }) } /** * Start verification process for external email address or sms number */ export function addVerification( body: AddEmailVerificationRequest | AddSmsVerificationRequest, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 201 data: AddVerificationResponse } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } >( '/verifications', oazapfts.json({ ...opts, method: 'POST', body, }), ) } /** * Verify an email address or sms number with a code */ export function verify( verification: string, body: VerifyEmailRequest | VerifySmsRequest, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 200 } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 404 data: ErrorResponse } >( `/verifications/${verification}/verify`, oazapfts.json({ ...opts, method: 'POST', body, }), ) } /** * Get all actions for the user */ export function getAllActions(opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 200 data: GetAllActionsResponse } | { status: 403 data: ErrorResponse } >('/actions', { ...opts, }) } /** * Add an action */ export function addAction( body: | AddActionCombineRequest | AddActionSmsRequest | AddActionWebhookRequest | AddActionDaemonRequest | AddActionSendRequest | AddActionForwardRequest | AddActionForwardRequest | AddActionReplyRequest | AddActionReplyAllRequest | AddActionAliasRequest, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 201 data: AddActionResponse } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } >( '/actions', oazapfts.json({ ...opts, method: 'POST', body, }), ) } /** * Update an action key */ export function updateAction( action: string, body: | AddActionCombineRequest | AddActionSmsRequest | AddActionWebhookRequest | AddActionDaemonRequest | AddActionSendRequest | AddActionForwardRequest | AddActionForwardRequest | AddActionReplyRequest | AddActionReplyAllRequest | AddActionAliasRequest, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 200 data: Key } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 404 data: ErrorResponse } >( `/actions/${action}`, oazapfts.json({ ...opts, method: 'PUT', body, }), ) } /** * Delete an action */ export function deleteAction(action: string, opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 204 } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 404 data: ErrorResponse } >(`/actions/${action}`, { ...opts, method: 'DELETE', }) } /** * Get a token for opening a daemon connection */ export function getDaemonToken(daemon: string, opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 200 data: { token: string } } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } >(`/daemons/${daemon}/token`, { ...opts, }) } /** * Get all integrations for the user */ export function getAllIntegrations(opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 200 data: GetAllIntegrationsResponse } | { status: 403 data: ErrorResponse } >('/integrations', { ...opts, }) } /** * Delete an integration */ export function deleteIntegration( integration: string, opts?: Oazapfts.RequestOpts, ) { return oazapfts.fetchJson< | { status: 204 } | { status: 400 data: ErrorResponse } | { status: 403 data: ErrorResponse } | { status: 404 data: ErrorResponse } >(`/integrations/${integration}`, { ...opts, method: 'DELETE', }) }
the_stack
import 'jasmine'; import NotFoundError from '../Errors/NotFoundError'; import TooManyResultsError from '../Errors/TooManyResultsError'; import DatabaseInterface from '../Databases/DatabaseInterface'; import PgSqlDatabase from '../Databases/PgSqlDatabase'; import MySqlDatabase from '../Databases/MySqlDatabase'; import SqliteDatabase from '../Databases/SqliteDatabase'; import CrudRepository from './CrudRepository'; import SqlQuery from '../Queries/SqlQuery'; import QueryIdentifier from '../Queries/QueryIdentifier'; const sql = SqlQuery.createFromTemplateString; class TestModel { public readonly id!: number; public readonly text!: string; public readonly number!: number; public readonly date!: Date; public relatedTests?: ReadonlyArray<RelatedTestModel>; public manyManyRelatedTests?: ReadonlyArray<RelatedTestModel>; public propertyUnrelatedToTheTable?: boolean; } class RelatedTestModel { public readonly id!: number; public readonly testId!: number; public test?: TestModel; } class TestRepository extends CrudRepository<TestModel> { constructor(database: DatabaseInterface) { super({ database, table: 'Test', primaryKey: 'id', model: TestModel, }); } async loadRelatedTestsRelationship(test: TestModel): Promise<TestModel> { return this.createModelFromAttributes({ ...test, relatedTests: await (new RelatedTestRepository(this.database)).search(sql` ${new QueryIdentifier('testId')} = ${test.id} `), }); } async loadManyManyRelatedTestsRelationship(test: TestModel) { return this.createModelFromAttributes({ ...test, manyManyRelatedTests: await (new RelatedTestRepository(this.database)).search(sql` ${new QueryIdentifier('id')} IN ( SELECT ${new QueryIdentifier('relatedTestId')} FROM ${new QueryIdentifier('ManyManyTest')} WHERE ${new QueryIdentifier('testId')} = ${test.id} ) `), }); } } class TestScopedRepository extends CrudRepository<TestModel> { constructor(database: DatabaseInterface) { super({ database, table: 'TestWithDuplicates', primaryKey: 'id', model: TestModel, scope: sql`number = 42`, }); } } class RelatedTestRepository extends CrudRepository<RelatedTestModel> { constructor(database: DatabaseInterface) { super({ database, table: 'RelatedTest', primaryKey: 'id', model: RelatedTestModel, }); } async loadTestRelationship(relatedTest: RelatedTestModel): Promise<RelatedTestModel> { return this.createModelFromAttributes({ ...relatedTest, test: await (new TestRepository(this.database)).get(relatedTest.testId), }); } } class TestWithDuplicatesRepository extends CrudRepository<TestModel> { constructor(database: DatabaseInterface) { super({ database, table: 'TestWithDuplicates', primaryKey: 'id', model: TestModel, }); } } // Instead of mocking everything, I chose to test the repository directly against real databases. // This offers a better coverage for any database differences. describe('CrudRepository - PgSqlDatabase', getTestForRepositoryWithDatabase(PgSqlDatabase, { host: 'pgsql', port: 5432, database: 'test', user: 'test', password: 'test' }, sql``)); describe('CrudRepository - MySqlDatabase', getTestForRepositoryWithDatabase(MySqlDatabase, { host: 'mysql', database: 'test', user: 'test', password: 'test', }, sql`PRIMARY KEY AUTO_INCREMENT`)); describe('CrudRepository - SqliteDatabase', getTestForRepositoryWithDatabase(SqliteDatabase, { filename: ':memory:', }, sql`PRIMARY KEY AUTOINCREMENT`)); function getTestForRepositoryWithDatabase(DatabaseClass: any, config: any, primaryKeyAttributes: SqlQuery) { return () => { let db: DatabaseInterface; let repository: TestRepository; let scopedRepository: TestScopedRepository; let relatedTestRepository: RelatedTestRepository; let repositoryWithDuplicates: TestWithDuplicatesRepository; beforeEach(async () => { db = new DatabaseClass(config); await db.query(sql` CREATE TEMPORARY TABLE ${new QueryIdentifier('Test')} ( ${new QueryIdentifier('id')} INTEGER NOT NULL ${primaryKeyAttributes}, ${new QueryIdentifier('text')} TEXT NOT NULL, ${new QueryIdentifier('number')} INTEGER NOT NULL, ${new QueryIdentifier('date')} DATE NOT NULL ); `); await db.query(sql` CREATE TEMPORARY TABLE ${new QueryIdentifier('RelatedTest')} ( ${new QueryIdentifier('id')} INTEGER NOT NULL ${primaryKeyAttributes}, ${new QueryIdentifier('testId')} INTEGER NOT NULL ); `); await db.query(sql` CREATE TEMPORARY TABLE ${new QueryIdentifier('ManyManyTest')} ( ${new QueryIdentifier('testId')} INTEGER NOT NULL, ${new QueryIdentifier('relatedTestId')} INTEGER NOT NULL ); `); await db.query(sql` CREATE TEMPORARY TABLE ${new QueryIdentifier('TestWithDuplicates')} ( ${new QueryIdentifier('id')} INTEGER NOT NULL, ${new QueryIdentifier('text')} TEXT NOT NULL, ${new QueryIdentifier('number')} INTEGER NOT NULL, ${new QueryIdentifier('date')} DATE NOT NULL ); `); repository = new TestRepository(db); scopedRepository = new TestScopedRepository(db); relatedTestRepository = new RelatedTestRepository(db); repositoryWithDuplicates = new TestWithDuplicatesRepository(db); }); afterEach(async () => { await db.query(sql`DROP TABLE ${new QueryIdentifier('Test')};`); await db.query(sql`DROP TABLE ${new QueryIdentifier('RelatedTest')};`); await db.query(sql`DROP TABLE ${new QueryIdentifier('ManyManyTest')};`); await db.query(sql`DROP TABLE ${new QueryIdentifier('TestWithDuplicates')};`); await db.disconnect(); }); it('get - normal case', async () => { await db.query(sql` INSERT INTO ${new QueryIdentifier('Test')} VALUES (1, 'test 1', 11, DATE('2020-01-01')), (2, 'test 2', 12, DATE('2020-01-03')); `); const result = await repository.get(2); expect(result).toBeInstanceOf(TestModel); expect(result.id).toEqual(2); expect(result.text).toEqual('test 2'); expect(result.number).toEqual(12); if (DatabaseClass === SqliteDatabase) { // We used the DATE function so SQLite stores a string expect(result.date).toBeInstanceOf(String); } else { expect(result.date).toBeInstanceOf(Date); } }); it('get - not found case', async () => { await expectAsync(repository.get(1)).toBeRejectedWithError(NotFoundError); }); it('get - too many results case', async () => { await db.query(sql` INSERT INTO ${new QueryIdentifier('TestWithDuplicates')} VALUES (1, 'test 1', 11, DATE('2020-01-01')), (1, 'test 2', 12, DATE('2020-01-01')); `); await expectAsync(repositoryWithDuplicates.get(1)).toBeRejectedWithError(TooManyResultsError); }); it('get - scoped case', async () => { await db.query(sql` INSERT INTO ${new QueryIdentifier('TestWithDuplicates')} VALUES (1, 'test 1', 42, DATE('2020-01-01')), (1, 'test 2', 43, DATE('2020-01-01')); `); const result = await scopedRepository.get(1); expect(result.text).toEqual('test 1'); }); it('get - not found in scope case', async () => { await db.query(sql`INSERT INTO ${new QueryIdentifier('TestWithDuplicates')} VALUES (1, 'test 2', 12, DATE('2020-01-01'));`); await expectAsync(scopedRepository.get(1)).toBeRejectedWithError(NotFoundError); }); it('search - normal case without filters', async () => { await db.query(sql` INSERT INTO ${new QueryIdentifier('Test')} VALUES (1, 'test 1', 11, DATE('2020-01-01')), (2, 'test 2', 12, DATE('2020-01-03')); `); const results = await repository.search(); expect(results.length).toEqual(2); expect(results[0]).toBeInstanceOf(TestModel); expect(results[0].id).toEqual(1); expect(results[0].text).toEqual('test 1'); expect(results[0].number).toEqual(11); if (DatabaseClass === SqliteDatabase) { // We used the DATE function so SQLite stores a string expect(results[0].date).toBeInstanceOf(String); } else { expect(results[0].date).toBeInstanceOf(Date); } expect(results[1]).toBeInstanceOf(TestModel); expect(results[1].id).toEqual(2); expect(results[1].text).toEqual('test 2'); expect(results[1].number).toEqual(12); if (DatabaseClass === SqliteDatabase) { // We used the DATE function so SQLite stores a string expect(results[1].date).toBeInstanceOf(String); } else { expect(results[1].date).toBeInstanceOf(Date); } }); it('search - no results case', async () => { const results = await repository.search(); expect(results.length).toEqual(0); }); it('search - with a filter', async () => { await db.query(sql` INSERT INTO ${new QueryIdentifier('Test')} VALUES (1, 'test 1', 11, DATE('2020-01-01')), (2, 'test 2', 12, DATE('2020-01-03')), (3, 'test 3', 13, DATE('2020-01-02')); `); const results = await repository.search(sql`number > 11 AND text LIKE '%2'`); expect(results.length).toEqual(1); expect(results[0].id).toEqual(2); }); it('search - with an order', async () => { await db.query(sql` INSERT INTO ${new QueryIdentifier('Test')} VALUES (1, 'test 1', 11, ('2020-01-01')), (2, 'test 2', 12, ('2020-01-03')); `); const results = await repository.search(null, sql`number DESC`); expect(results.length).toEqual(2); expect(results[0].id).toEqual(2); expect(results[1].id).toEqual(1); }); it('search - with a filter and order', async () => { await db.query(sql` INSERT INTO ${new QueryIdentifier('Test')} VALUES (1, 'test 1', 11, DATE('2020-01-01')), (2, 'test 2', 12, DATE('2020-01-03')), (3, 'test 3', 13, DATE('2020-01-02')); `); const results = await repository.search(sql`number > 11`, sql`number DESC`); expect(results.length).toEqual(2); expect(results[0].id).toEqual(3); expect(results[1].id).toEqual(2); }); it('search - scoped', async () => { await db.query(sql` INSERT INTO ${new QueryIdentifier('TestWithDuplicates')} VALUES (1, 'test 1', 42, DATE('2020-01-01')), (2, 'test 2', 42, DATE('2020-01-01')), (3, 'test 3', 13, DATE('2020-01-01')); `); const results = await scopedRepository.search(); expect(results.length).toEqual(2); expect(results[0].id).toEqual(1); expect(results[1].id).toEqual(2); }); it('search - scoped and filtered', async () => { await db.query(sql` INSERT INTO ${new QueryIdentifier('TestWithDuplicates')} VALUES (1, 'test 1', 42, DATE('2020-01-01')), (2, 'test 2', 42, DATE('2020-01-01')), (3, 'test 3', 13, DATE('2020-01-01')); `); const results = await scopedRepository.search(sql`text = 'test 2'`); expect(results.length).toEqual(1); expect(results[0].id).toEqual(2); }); it('create - normal case', async () => { const result = await repository.create({ id: 2, text: 'test 2', number: 12, date: new Date(), }); expect(result).toBeInstanceOf(TestModel); expect(result.id).toEqual(2); expect(result.text).toEqual('test 2'); expect(result.number).toEqual(12); if (DatabaseClass === SqliteDatabase) { // We used a Date object so SQLite stores a number this time expect(result.date).toBeInstanceOf(Number); } else { expect(result.date).toBeInstanceOf(Date); } }); it('update - normal case', async () => { await db.query(sql`INSERT INTO ${new QueryIdentifier('Test')} VALUES (1, 'test 1', 11, DATE('2020-01-01'));`); const model = new TestModel(); Object.assign(model, { id: 1, text: 'test 1', number: 11, date: new Date(), }); const result = await repository.update(model, { text: 'test 2', }); expect(result).toBeInstanceOf(TestModel); expect(result.id).toEqual(1); expect(result.text).toEqual('test 2'); expect(result.number).toEqual(11); }); it('update - not found case', async () => { const model = new TestModel(); Object.assign(model, { id: 1, text: 'test 1', number: 11, date: new Date(), }); await expectAsync( repository.update(model, { text: 'test 2' }) ).toBeRejectedWithError(NotFoundError); }); if (DatabaseClass === PgSqlDatabase) { // Only PgSql has this exception, cannot emulate it with the other engines it('update - too many results case', async () => { await db.query(sql` INSERT INTO ${new QueryIdentifier('TestWithDuplicates')} VALUES (1, 'test 1', 11, DATE('2020-01-01')), (1, 'test 1', 11, DATE('2020-01-01')); `); const model = new TestModel(); Object.assign(model, { id: 1, text: 'test 1', number: 11, date: new Date(), }); await expectAsync( repositoryWithDuplicates.update(model, { text: 'test 2' }) ).toBeRejectedWithError(TooManyResultsError); }); } it('update - should not affect unrelated properties', async () => { await db.query(sql`INSERT INTO ${new QueryIdentifier('Test')} VALUES (1, 'test 1', 11, DATE('2020-01-01'));`); const model = await repository.get(1); model.propertyUnrelatedToTheTable = true; const result = await repository.update(model, { text: 'test 2', }); expect(result.propertyUnrelatedToTheTable).toEqual(true); }); it('delete - normal case', async () => { await db.query(sql`INSERT INTO ${new QueryIdentifier('Test')} VALUES (1, 'test 1', 11, DATE('2020-01-01'));`); const model = new TestModel(); Object.assign(model, { id: 1, text: 'test 1', number: 11, date: new Date(), }); await repository.delete(model); }); it('load relationship - has one', async () => { await db.query(sql`INSERT INTO ${new QueryIdentifier('Test')} VALUES (1, 'test 1', 11, DATE('2020-01-01'));`); await db.query(sql`INSERT INTO ${new QueryIdentifier('RelatedTest')} VALUES (1, 1);`); const relatedModel = await relatedTestRepository.get(1); expect(relatedModel.testId).toBe(1); expect(relatedModel.test).toBeUndefined(); const newRelatedModel = await relatedTestRepository.loadTestRelationship(relatedModel); expect(relatedModel.test).toBeUndefined(); expect(newRelatedModel.test).not.toBeUndefined(); expect(newRelatedModel.test).toBeInstanceOf(TestModel); expect((<TestModel>newRelatedModel.test).id).toBe(1); }); it('load relationship - has many', async () => { await db.query(sql`INSERT INTO ${new QueryIdentifier('Test')} VALUES (1, 'test 1', 11, DATE('2020-01-01'));`); await db.query(sql`INSERT INTO ${new QueryIdentifier('Test')} VALUES (2, 'test 2', 12, DATE('2020-01-02'));`); await db.query(sql`INSERT INTO ${new QueryIdentifier('RelatedTest')} VALUES (1, 1);`); await db.query(sql`INSERT INTO ${new QueryIdentifier('RelatedTest')} VALUES (2, 1);`); await db.query(sql`INSERT INTO ${new QueryIdentifier('RelatedTest')} VALUES (3, 2);`); const model = await repository.get(1); expect(model.relatedTests).toBeUndefined(); const newModel = await repository.loadRelatedTestsRelationship(model); expect(model.relatedTests).toBeUndefined(); expect(newModel.relatedTests).not.toBeUndefined(); expect(newModel.relatedTests).toBeInstanceOf(Array); expect((<RelatedTestModel[]>newModel.relatedTests).length).toEqual(2); expect((<RelatedTestModel[]>newModel.relatedTests)[0]).toBeInstanceOf(RelatedTestModel); expect((<RelatedTestModel[]>newModel.relatedTests)[1]).toBeInstanceOf(RelatedTestModel); expect((<RelatedTestModel[]>newModel.relatedTests)[0].id).toEqual(1); expect((<RelatedTestModel[]>newModel.relatedTests)[1].id).toEqual(2); }); it('load relationship - many many', async () => { await db.query(sql`INSERT INTO ${new QueryIdentifier('Test')} VALUES (1, 'test 1', 11, DATE('2020-01-01'));`); await db.query(sql`INSERT INTO ${new QueryIdentifier('Test')} VALUES (2, 'test 2', 12, DATE('2020-01-02'));`); await db.query(sql`INSERT INTO ${new QueryIdentifier('RelatedTest')} VALUES (1, 1);`); await db.query(sql`INSERT INTO ${new QueryIdentifier('RelatedTest')} VALUES (2, 1);`); await db.query(sql`INSERT INTO ${new QueryIdentifier('RelatedTest')} VALUES (3, 2);`); await db.query(sql`INSERT INTO ${new QueryIdentifier('ManyManyTest')} VALUES (1, 1);`); await db.query(sql`INSERT INTO ${new QueryIdentifier('ManyManyTest')} VALUES (1, 2);`); await db.query(sql`INSERT INTO ${new QueryIdentifier('ManyManyTest')} VALUES (2, 1);`); await db.query(sql`INSERT INTO ${new QueryIdentifier('ManyManyTest')} VALUES (2, 2);`); await db.query(sql`INSERT INTO ${new QueryIdentifier('ManyManyTest')} VALUES (2, 3);`); const model = await repository.get(1); expect(model.manyManyRelatedTests).toBeUndefined(); const newModel = await repository.loadManyManyRelatedTestsRelationship(model); expect(model.manyManyRelatedTests).toBeUndefined(); expect(newModel.manyManyRelatedTests).not.toBeUndefined(); expect(newModel.manyManyRelatedTests).toBeInstanceOf(Array); expect((<RelatedTestModel[]>newModel.manyManyRelatedTests).length).toEqual(2); expect((<RelatedTestModel[]>newModel.manyManyRelatedTests)[0]).toBeInstanceOf(RelatedTestModel); expect((<RelatedTestModel[]>newModel.manyManyRelatedTests)[1]).toBeInstanceOf(RelatedTestModel); expect((<RelatedTestModel[]>newModel.manyManyRelatedTests)[0].id).toEqual(1); expect((<RelatedTestModel[]>newModel.manyManyRelatedTests)[1].id).toEqual(2); }); }; };
the_stack
import { INodeProperties, } from 'n8n-workflow'; export const storyManagementOperations: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { source: [ 'managementApi', ], resource: [ 'story', ], }, }, options: [ // { // name: 'Create', // value: 'create', // description: 'Create a story', // }, { name: 'Delete', value: 'delete', description: 'Delete a story', }, { name: 'Get', value: 'get', description: 'Get a story', }, { name: 'Get All', value: 'getAll', description: 'Get all stories', }, { name: 'Publish', value: 'publish', description: 'Publish a story', }, { name: 'Unpublish', value: 'unpublish', description: 'Unpublish a story', }, ], default: 'get', description: 'The operation to perform.', }, ]; export const storyManagementFields: INodeProperties[] = [ // /* -------------------------------------------------------------------------- */ // /* story:create */ // /* -------------------------------------------------------------------------- */ // { // displayName: 'Space ID', // name: 'space', // type: 'options', // typeOptions: { // loadOptionsMethod: 'getSpaces', // }, // default: '', // required: true, // displayOptions: { // show: { // source: [ // 'managementApi', // ], // resource: [ // 'story', // ], // operation: [ // 'create', // ], // }, // }, // description: 'The name of the space.', // }, // { // displayName: 'Name', // name: 'name', // type: 'string', // default: '', // required: true, // displayOptions: { // show: { // source: [ // 'managementApi', // ], // resource: [ // 'story', // ], // operation: [ // 'create', // ], // }, // }, // description: 'The name you give this story.', // }, // { // displayName: 'Slug', // name: 'slug', // type: 'string', // default: '', // required: true, // displayOptions: { // show: { // source: [ // 'managementApi', // ], // resource: [ // 'story', // ], // operation: [ // 'create', // ], // }, // }, // description: 'The slug/path you give this story.', // }, // { // displayName: 'JSON Parameters', // name: 'jsonParameters', // type: 'boolean', // default: false, // description: '', // displayOptions: { // show: { // source: [ // 'managementApi', // ], // resource: [ // 'story', // ], // operation: [ // 'create', // ], // }, // }, // }, // { // displayName: 'Additional Fields', // name: 'additionalFields', // type: 'collection', // placeholder: 'Add Field', // displayOptions: { // show: { // source: [ // 'managementApi', // ], // resource: [ // 'story', // ], // operation: [ // 'create', // ], // }, // }, // default: {}, // options: [ // { // displayName: 'Content', // name: 'contentUi', // type: 'fixedCollection', // description: 'Add Content', // typeOptions: { // multipleValues: false, // }, // displayOptions: { // show: { // '/jsonParameters': [ // false, // ], // }, // }, // placeholder: 'Add Content', // default: '', // options: [ // { // displayName: 'Content Data', // name: 'contentValue', // values: [ // { // displayName: 'Component', // name: 'component', // type: 'options', // typeOptions: { // loadOptionsMethod: 'getComponents', // loadOptionsDependsOn: [ // 'space', // ], // }, // default: '', // }, // { // displayName: 'Elements', // name: 'elementUi', // type: 'fixedCollection', // description: 'Add Body', // typeOptions: { // multipleValues: true, // }, // placeholder: 'Add Element', // default: '', // options: [ // { // displayName: 'Element', // name: 'elementValues', // values: [ // { // displayName: 'Component', // name: 'component', // type: 'options', // typeOptions: { // loadOptionsMethod: 'getComponents', // loadOptionsDependsOn: [ // 'space', // ], // }, // default: '', // }, // { // displayName: 'Element Data', // name: 'dataUi', // type: 'fixedCollection', // description: 'Add Data', // typeOptions: { // multipleValues: true, // }, // placeholder: 'Add Data', // default: '', // options: [ // { // displayName: 'Data', // name: 'dataValues', // values: [ // { // displayName: 'Key', // name: 'key', // type: 'string', // default: '', // }, // { // displayName: 'Value', // name: 'value', // type: 'string', // default: '', // }, // ], // }, // ], // }, // ], // }, // ], // }, // ], // }, // ], // }, // { // displayName: 'Content (JSON)', // name: 'contentJson', // type: 'string', // displayOptions: { // show: { // '/jsonParameters': [ // true, // ], // }, // }, // default: '', // }, // { // displayName: 'Parent ID', // name: 'parentId', // type: 'string', // default: '', // description: 'Parent story/folder numeric ID.', // }, // { // displayName: 'Path', // name: 'path', // type: 'string', // default: '', // description: 'Given real path, used in the preview editor.', // }, // { // displayName: 'Is Startpage', // name: 'isStartpage', // type: 'boolean', // default: false, // description: 'Is startpage of current folder.', // }, // { // displayName: 'First Published At', // name: 'firstPublishedAt', // type: 'dateTime', // default: '', // description: 'First publishing date.', // }, // ], // }, /* -------------------------------------------------------------------------- */ /* story:delete */ /* -------------------------------------------------------------------------- */ { displayName: 'Space ID', name: 'space', type: 'options', typeOptions: { loadOptionsMethod: 'getSpaces', }, default: '', required: true, displayOptions: { show: { source: [ 'managementApi', ], resource: [ 'story', ], operation: [ 'delete', ], }, }, description: 'The name of the space.', }, { displayName: 'Story ID', name: 'storyId', type: 'string', default: '', required: true, displayOptions: { show: { source: [ 'managementApi', ], resource: [ 'story', ], operation: [ 'delete', ], }, }, description: 'Numeric ID of the story.', }, /* -------------------------------------------------------------------------- */ /* story:get */ /* -------------------------------------------------------------------------- */ { displayName: 'Space ID', name: 'space', type: 'options', typeOptions: { loadOptionsMethod: 'getSpaces', }, default: '', required: true, displayOptions: { show: { source: [ 'managementApi', ], resource: [ 'story', ], operation: [ 'get', ], }, }, description: 'The name of the space.', }, { displayName: 'Story ID', name: 'storyId', type: 'string', default: '', required: true, displayOptions: { show: { source: [ 'managementApi', ], resource: [ 'story', ], operation: [ 'get', ], }, }, description: 'Numeric ID of the story.', }, /* -------------------------------------------------------------------------- */ /* story:getAll */ /* -------------------------------------------------------------------------- */ { displayName: 'Space ID', name: 'space', type: 'options', typeOptions: { loadOptionsMethod: 'getSpaces', }, default: '', required: true, displayOptions: { show: { source: [ 'managementApi', ], resource: [ 'story', ], operation: [ 'getAll', ], }, }, description: 'The name of the space', }, { displayName: 'Return All', name: 'returnAll', type: 'boolean', displayOptions: { show: { source: [ 'managementApi', ], resource: [ 'story', ], operation: [ 'getAll', ], }, }, default: false, description: 'Returns a list of your user contacts.', }, { displayName: 'Limit', name: 'limit', type: 'number', displayOptions: { show: { source: [ 'managementApi', ], resource: [ 'story', ], operation: [ 'getAll', ], returnAll: [ false, ], }, }, typeOptions: { minValue: 1, maxValue: 100, }, default: 50, description: 'How many results to return.', }, { displayName: 'Filters', name: 'filters', type: 'collection', placeholder: 'Add Filter', default: {}, displayOptions: { show: { source: [ 'managementApi', ], resource: [ 'story', ], operation: [ 'getAll', ], }, }, options: [ { displayName: 'Starts With', name: 'starts_with', type: 'string', default: '', description: 'Filter by slug.', }, ], }, /* -------------------------------------------------------------------------- */ /* story:publish */ /* -------------------------------------------------------------------------- */ { displayName: 'Space ID', name: 'space', type: 'options', typeOptions: { loadOptionsMethod: 'getSpaces', }, default: '', required: true, displayOptions: { show: { source: [ 'managementApi', ], resource: [ 'story', ], operation: [ 'publish', ], }, }, description: 'The name of the space.', }, { displayName: 'Story ID', name: 'storyId', type: 'string', default: '', required: true, displayOptions: { show: { source: [ 'managementApi', ], resource: [ 'story', ], operation: [ 'publish', ], }, }, description: 'Numeric ID of the story.', }, { displayName: 'Options', name: 'options', type: 'collection', placeholder: 'Add Option', displayOptions: { show: { source: [ 'managementApi', ], resource: [ 'story', ], operation: [ 'publish', ], }, }, default: {}, options: [ { displayName: 'Release ID', name: 'releaseId', type: 'string', default: '', description: 'Numeric ID of release.', }, { displayName: 'Language', name: 'language', type: 'string', default: '', description: 'Language code to publish the story individually (must be enabled in the space settings).', }, ], }, /* -------------------------------------------------------------------------- */ /* story:unpublish */ /* -------------------------------------------------------------------------- */ { displayName: 'Space ID', name: 'space', type: 'options', typeOptions: { loadOptionsMethod: 'getSpaces', }, default: '', required: true, displayOptions: { show: { source: [ 'managementApi', ], resource: [ 'story', ], operation: [ 'unpublish', ], }, }, description: 'The name of the space.', }, { displayName: 'Story ID', name: 'storyId', type: 'string', default: '', required: true, displayOptions: { show: { source: [ 'managementApi', ], resource: [ 'story', ], operation: [ 'unpublish', ], }, }, description: 'Numeric ID of the story.', }, ];
the_stack
module android.text { import View = android.view.View; import Layout = android.text.Layout; import TextDirectionHeuristic = android.text.TextDirectionHeuristic; import TextUtils = android.text.TextUtils; /** * Some objects that implement {@link TextDirectionHeuristic}. Use these with * the {@link BidiFormatter#unicodeWrap unicodeWrap()} methods in {@link BidiFormatter}. * Also notice that these direction heuristics correspond to the same types of constants * provided in the {@link android.view.View} class for {@link android.view.View#setTextDirection * setTextDirection()}, such as {@link android.view.View#TEXT_DIRECTION_RTL}. * <p>To support versions lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, * you can use the support library's {@link android.support.v4.text.TextDirectionHeuristicsCompat} * class. * */ export class TextDirectionHeuristics { /** * Always decides that the direction is left to right. */ static LTR:TextDirectionHeuristic; /** * Always decides that the direction is right to left. */ static RTL:TextDirectionHeuristic; /** * Determines the direction based on the first strong directional character, including bidi * format chars, falling back to left to right if it finds none. This is the default behavior * of the Unicode Bidirectional Algorithm. */ static FIRSTSTRONG_LTR:TextDirectionHeuristic; /** * Determines the direction based on the first strong directional character, including bidi * format chars, falling back to right to left if it finds none. This is similar to the default * behavior of the Unicode Bidirectional Algorithm, just with different fallback behavior. */ static FIRSTSTRONG_RTL:TextDirectionHeuristic; /** * If the text contains any strong right to left non-format character, determines that the * direction is right to left, falling back to left to right if it finds none. */ static ANYRTL_LTR:TextDirectionHeuristic; /** * Force the paragraph direction to the Locale direction. Falls back to left to right. */ static LOCALE:TextDirectionHeuristic; /** * State constants for taking care about true / false / unknown */ private static STATE_TRUE:number = 0; private static STATE_FALSE:number = 1; private static STATE_UNKNOWN:number = 2; private static isRtlText(directionality:number):number { return TextDirectionHeuristics.STATE_FALSE; //switch(directionality) { // case Character.DIRECTIONALITY_LEFT_TO_RIGHT: // return TextDirectionHeuristics.STATE_FALSE; // case Character.DIRECTIONALITY_RIGHT_TO_LEFT: // case Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC: // return TextDirectionHeuristics.STATE_TRUE; // default: // return TextDirectionHeuristics.STATE_UNKNOWN; //} } private static isRtlTextOrFormat(directionality:number):number { return TextDirectionHeuristics.STATE_FALSE; //switch(directionality) { // case Character.DIRECTIONALITY_LEFT_TO_RIGHT: // case Character.DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING: // case Character.DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE: // return TextDirectionHeuristics.STATE_FALSE; // case Character.DIRECTIONALITY_RIGHT_TO_LEFT: // case Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC: // case Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING: // case Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE: // return TextDirectionHeuristics.STATE_TRUE; // default: // return TextDirectionHeuristics.STATE_UNKNOWN; //} } } export module TextDirectionHeuristics { /** * Computes the text direction based on an algorithm. Subclasses implement * {@link #defaultIsRtl} to handle cases where the algorithm cannot determine the * direction from the text alone. */ export abstract class TextDirectionHeuristicImpl implements TextDirectionHeuristic { private mAlgorithm:TextDirectionHeuristics.TextDirectionAlgorithm; constructor(algorithm:TextDirectionHeuristics.TextDirectionAlgorithm) { this.mAlgorithm = algorithm; } /** * Return true if the default text direction is rtl. */ protected abstract defaultIsRtl():boolean ; isRtl(cs:string, start:number, count:number):boolean { if (cs == null || start < 0 || count < 0 || cs.length - count < start) { throw Error(`new IllegalArgumentException()`); } if (this.mAlgorithm == null) { return this.defaultIsRtl(); } return this.doCheck(cs, start, count); } private doCheck(cs:string, start:number, count:number):boolean { switch (this.mAlgorithm.checkRtl(cs, start, count)) { case TextDirectionHeuristics.STATE_TRUE: return true; case TextDirectionHeuristics.STATE_FALSE: return false; default: return this.defaultIsRtl(); } } } export class TextDirectionHeuristicInternal extends TextDirectionHeuristics.TextDirectionHeuristicImpl { private mDefaultIsRtl:boolean; constructor(algorithm:TextDirectionHeuristics.TextDirectionAlgorithm, defaultIsRtl:boolean) { super(algorithm); this.mDefaultIsRtl = defaultIsRtl; } protected defaultIsRtl():boolean { return this.mDefaultIsRtl; } } /** * Interface for an algorithm to guess the direction of a paragraph of text. */ export interface TextDirectionAlgorithm { /** * Returns whether the range of text is RTL according to the algorithm. */ checkRtl(cs:string, start:number, count:number):number ; } /** * Algorithm that uses the first strong directional character to determine the paragraph * direction. This is the standard Unicode Bidirectional algorithm. */ export class FirstStrong implements TextDirectionHeuristics.TextDirectionAlgorithm { checkRtl(cs:string, start:number, count:number):number { let result:number = TextDirectionHeuristics.STATE_UNKNOWN; for (let i:number = start, e:number = start + count; i < e && result == TextDirectionHeuristics.STATE_UNKNOWN; ++i) { result = TextDirectionHeuristics.STATE_FALSE; //result = TextDirectionHeuristics.isRtlTextOrFormat(Character.getDirectionality(cs.charAt(i))); } return result; } constructor() { } static INSTANCE:FirstStrong = new FirstStrong(); } /** * Algorithm that uses the presence of any strong directional non-format * character (e.g. excludes LRE, LRO, RLE, RLO) to determine the * direction of text. */ export class AnyStrong implements TextDirectionHeuristics.TextDirectionAlgorithm { private mLookForRtl:boolean; checkRtl(cs:string, start:number, count:number):number { let haveUnlookedFor:boolean = false; for (let i:number = start, e:number = start + count; i < e; ++i) { switch (TextDirectionHeuristics.isRtlText(0/*Character.getDirectionality(cs.charAt(i))*/)) { case TextDirectionHeuristics.STATE_TRUE: if (this.mLookForRtl) { return TextDirectionHeuristics.STATE_TRUE; } haveUnlookedFor = true; break; case TextDirectionHeuristics.STATE_FALSE: if (!this.mLookForRtl) { return TextDirectionHeuristics.STATE_FALSE; } haveUnlookedFor = true; break; default: break; } } if (haveUnlookedFor) { return this.mLookForRtl ? TextDirectionHeuristics.STATE_FALSE : TextDirectionHeuristics.STATE_TRUE; } return TextDirectionHeuristics.STATE_UNKNOWN; } constructor(lookForRtl:boolean) { this.mLookForRtl = lookForRtl; } static INSTANCE_RTL:AnyStrong = new AnyStrong(true); static INSTANCE_LTR:AnyStrong = new AnyStrong(false); } /** * Algorithm that uses the Locale direction to force the direction of a paragraph. */ export class TextDirectionHeuristicLocale extends TextDirectionHeuristics.TextDirectionHeuristicImpl { constructor() { super(null); } protected defaultIsRtl():boolean { return false; //const dir:number = TextUtils.getLayoutDirectionFromLocale(java.util.Locale.getDefault()); //return (dir == View.LAYOUT_DIRECTION_RTL); } static INSTANCE:TextDirectionHeuristicLocale = new TextDirectionHeuristicLocale(); } } //delay init TextDirectionHeuristics.LTR = new TextDirectionHeuristics.TextDirectionHeuristicInternal(null, /* no algorithm */false); TextDirectionHeuristics.RTL = new TextDirectionHeuristics.TextDirectionHeuristicInternal(null, /* no algorithm */true); TextDirectionHeuristics.FIRSTSTRONG_LTR = new TextDirectionHeuristics.TextDirectionHeuristicInternal(TextDirectionHeuristics.FirstStrong.INSTANCE, false); TextDirectionHeuristics.FIRSTSTRONG_RTL = new TextDirectionHeuristics.TextDirectionHeuristicInternal(TextDirectionHeuristics.FirstStrong.INSTANCE, true); TextDirectionHeuristics.ANYRTL_LTR = new TextDirectionHeuristics.TextDirectionHeuristicInternal(TextDirectionHeuristics.AnyStrong.INSTANCE_RTL, false); TextDirectionHeuristics.LOCALE = TextDirectionHeuristics.TextDirectionHeuristicLocale.INSTANCE; }
the_stack
import fs from 'fs'; import path from 'path'; import bayes from 'bayes'; import config from 'config'; import getUrls from 'get-urls'; import { clamp } from 'lodash'; import sanitizeHtml from 'sanitize-html'; import slackLib, { OPEN_COLLECTIVE_SLACK_CHANNEL } from '../lib/slack'; import models from '../models'; /** Return type when running a spam analysis */ export type SpamAnalysisReport = { /** When did the report occur */ date: string; /** What's the context of the report */ context: string; /** Data of the entity that was analyzed */ data: Record<string, unknown>; /** A score between 0 and 1. 0=NotSpam, 1=IsSpamForSure */ score: number; /** Detected spam keywords */ keywords: string[]; /** Detected blocked domains */ domains: string[]; /** Result of the Bayes check, spam or ham */ bayes: string; }; export type BayesClassifier = { /** Categorize a content string */ categorize(content: string): string; }; // Watched content const ANALYZED_FIELDS: string[] = ['name', 'website', 'description', 'longDescription']; // A map of spam keywords<>score. Please keep everything in there lowercase. const SPAM_KEYWORDS: { [keyword: string]: number } = { 'anti aging': 0.3, 'blood flow': 0.3, 'car seats': 0.2, 'fat burn': 0.3, 'male enhancement': 0.3, 'male health': 0.3, 'real estate': 0.2, 'weight loss': 0.3, assignment: 0.3, canzana: 0.3, casino: 0.2, cbd: 0.3, ciagra: 0.3, cream: 0.1, credit: 0.2, escort: 0.3, essay: 0.2, forex: 0.2, gummies: 0.2, keto: 0.3, loan: 0.2, maleenhancement: 0.3, malehealth: 0.3, model: 0.1, mortgage: 0.2, muscle: 0.1, natural: 0.1, oil: 0.1, pharmacy: 0.1, pills: 0.2, poker: 0.2, porn: 0.2, review: 0.1, serum: 0.2, skin: 0.1, testosterone: 0.3, truvalast: 0.3, writer: 0.2, }; // Any domain from there gives you a SPAM score of 1 export const SPAMMERS_DOMAINS = [ '1.bp.blogspot.com', '513-ohio-ads.com', '7smabu.com', 'abellarora.com', 'addwish.com', 'adskorner.com', 'adsyellowpages.com', 'adulted.instructure.com', 'advertise.lachanalebrand.com', 'advisoroffer.com', 'afterhourshealth.com', 'agarioforums.net', 'agencymumbai.com', 'airtravelmart.com', 'alertpills.com', 'alexanderstamps.com', 'allnutritionhub.com', 'allsupplementshop.com', 'alpha.trinidriver.com', 'amazonhealthmart.com', 'amirarticles.com', 'anime-planet.com', 'antiwrinklecream20.wixsite.com', 'anyflip.com', 'aopendoor.com', 'apnews.com', 'artio.net', 'atozfitnesstalks.com', 'avengersdiet.com', 'base2edu.instructure.com', 'bebee.com', 'benzinga.com', 'besttacticalwatch.wixsite.com', 'bhitmagazine.com.ng', 'biznutra.com', 'biznutrition.com', 'blackworldforum.com', 'bollyshake.com', 'bonfire.com', 'bookishelf.com', 'bookmarkextent.com', 'buddysupplement.com', 'bumpsweat.com', 'butywolka.eu', 'butywolka.pl', 'buypurelifeketo.com', 'buzrush.com', 'callgirldehradun.com', 'callgirlsindelhi.co.in', 'callupcontact.com', 'camobear.ca', 'canvas.elsevier.com', 'canvas.msstate.edu', 'canvas.pbsteacherline.org', 'canvas.redejuntos.org.br', 'caramellaapp.com', 'cartelhealth.com', 'cashforhomespittsburgh.com', 'cerld.com', 'classifieds.usatoday.com', 'clck.ru', 'clinicabalu.com', 'cole2.uconline.edu', 'community.hpe.com', 'community.robo3d.com', 'community.roku.com', 'completefoods.co', 'consultbestastro.com', 'copymethat.com', 'coub.com', 'create.arduino.cc', 'creativehealthcart.com', 'csopartnership.org', 'cutt.us', 'dailydealsreview.info', 'dakhoaquoctehanoi.webflow.io', 'dakshi.in', 'darknetweed.com', 'dasilex.co.uk', 'deadlinenews.co.uk', 'demandsupplement.com', 'designyourown.pk', 'deutschlandsupplements.de', 'dietarypillsstore.com', 'dietdoctor.com', 'diets2try.com', 'digitalvisi.com', 'djpod.com', 'doescbdoilwork.com', 'dragonsdenketo.com', 'dridainfotech.com', 'droidt99.com', 'ecuadortransparente.org', 'edu-24.info', 'elitecaretreatment.com', 'examine24x7.com', 'expatriates.com', 'faculdadearidesa.instructure.com', 'falseceilingexperts.in', 'faqssupplement.com', 'farm1.staticflickr.com', 'farmscbdoil.com', 'feedsfloor.com', 'finance.yahoo.com', 'fitcareketo.com', 'fitdiettrends.com', 'fitdiettrendz.com', 'fitnesscarezone.com', 'fitnessdietreviews.com', 'fitnessmegamart.com', 'fitnessprocentre.com', 'fitpedia.org', 'fordtremor.com', 'forexinthai.com', 'forum.fusioncharts.com', 'forum.zidoo.tv', 'francesupplements.fr', 'frogdoch.ch', 'gab.com', 'getyouroffers.xyz', 'givebutter.com', 'globenewswire.com', 'gocrowdera.com', 'goketogenics.com', 'gurgaonescorts.in', 'health4trend.com', 'healthcarthub.com', 'healthline.com', 'healthlinenutrition.com', 'healthmassive.com', 'healthmife.com', 'healthonlinecare.com', 'healthpubmed.com', 'healthsupplementcart.com', 'healthtalkrev.blogspot.com', 'healthtalkrev.com', 'healthtalkrevfacts.blogspot.com', 'healthverbs.com', 'healthyaustralia.com.au', 'healthycliq.com', 'healthygossips.com', 'healthymenuforchildren.blogspot.com', 'healthynutrishop.com', 'healthyslimdiet.com', 'healthytalkz.com', 'hearthis.at', 'herbalsupplementreview.com', 'herbalweightlossreview.com', 'hmdsupplements.com', 'hogheavenbar-b-que.com', 'homify.com', 'homify.in', 'hulkdiet.com', 'hulkpills.com', 'hulksupplement.com', 'hyalurolift.fr', 'hybridwatchshop.wixsite.com', 'hype.news', 'icefabrics.com', 'identifyscam.com', 'iexponet.com', 'image.makewebeasy.net', 'industrialcleaningpros.com', 'inkitt.com', 'innovationdiet.com', 'inova.instructure.com', 'insta-keto.org', 'ipsnews.net', 'isajain.com', 'italianiintegratori.it', 'itsmyurls.com', 'janvhikapoor.com', 'jobhub.live', 'jotform.com', 'justgiving.com', 'kandiez.co.ke', 'keto-bodytone.com', 'keto-top.org', 'keto-ultra-diet.com', 'ketoboostx.com', 'ketodietfitness.com', 'ketodietsplan.com', 'ketodietstores.com', 'ketodietwalmart.com', 'ketoerfahrungendeutschland.de', 'ketofasttrim.com', 'ketofitstore.com', 'ketogenicdietpills.com', 'ketogenicsupplementsreview.com', 'ketohour.com', 'ketopiller.com', 'ketoplanusa.com', 'ketopremiere.info', 'ketopure-org.over-blog.com', 'ketopure.org', 'ketopurediets.com', 'ketoreviews.co.uk', 'ketotop-diet.com', 'ketotrin.info', 'ketovatrudiet.info', 'ketoviante.info', 'kit.co', 'knowyourmeme.com', 'ko-fi.com', 'ktc.instructure.com', 'kursovezavseki.com', 'lakubet.co', 'laweekly.com', 'learningatpanania.com.au', 'logisticmart.com', 'lunaireketobhb.blogspot.com', 'mafiatek.my.id', 'maleenhancementtips.com', 'mariamd.com', 'market.acesinvensys.com', 'marketwatch.com', 'medixocentre.com', 'medlineplus.gov', 'menhealthdiets.com', 'merchantcircle.com', 'minimore.com', 'morioh.com', 'mrxmaleenhancement-point.blogspot.com', 'muckrack.com', 'my.desktopnexus.com', 'myfitnesspharm.com', 'myshorturl.net', 'myunbiasedreview.wordpress.com', 'nananke.com', 'naturalketopill.com', 'netchorus.com', 'netgearextendersetupp.com', 'netrockdeals.com', 'nhadat24.org', 'norgekosttilskudd.no', 'norton.com', 'note.com', 'nutraplatform.com', 'nutrifitweb.com', 'nutritioun.com', 'offer4cart.com', 'offernutra.com', 'office.com', 'officemaster.ae', 'onlineairlinesbooking.com', 'onlinereservationbooking.com', 'onnitsupplements.com', 'openeyetap.com', 'oppsofts.com', 'orderfitness.org', 'organicsupplementdietprogram.com', 'ourunbiasedreview.blogspot.com', 'paper.li', 'passportphotonow.co.uk', 'paste.softver.org.mk', 'patch.com', 'penzu.com', 'petsaw.com', 'pharmacistreviews.com', 'pillsfact.com', 'pillsfect.com', 'pillsmumy.com', 'pillsvibe.com', 'pilsadiet.com', 'plarium.com', 'pornlike.net', 'praltrix.info', 'prlog.org', 'products99.com', 'pubhtml5.com', 'publons.com', 'purefiter.com', 'purefitketopills.com', 'purnimasingh.com', 'realbuzz.com', 'redrealestate.com.pk', 'rembachduong.vn', 'reseau.1mile.com', 'reviewmypills.com', 'reviewography.com', 'reviewsbox.org', 'reviewsbox360.wixsite.com', 'reviewscart.co.uk', 'riovista.instructure.com', 'rise-up.co.uk', 'riteketopills.com', 'saatchiart.com', 'saturdaysale.com', 'sco.lt', 'shanorady.medium.com', 'sharktankdiets.com', 'shwetabasu.com', 'shwetachopra.com', 'sites.duke.edu', 'sites.psu.edu', 'situsslots.net', 'sj1250710.wixsite.com', 'skatafka.com', 'slimketopills.com', 'smore.com', 'snomoto.com', 'softage.net', 'soo.gd', 'spa-india.azurewebsites.net', 'spreaker.com', 'srsmedicare.com', 'stageit.com', 'startus.cc', 'staycure.com', 'steroidscience.org', 'streetgirls.in', 'streetinsider.com', 'stunxt.com', 'sugarbalance.store', 'sunnyspotrealty.net', 'suphe.net', 'supplement4muscle.com', 'supplementarmy.com', 'supplementblend.com', 'supplementdose.com', 'supplementenbelgie.be', 'supplementgear.com', 'supplementgo.com', 'supplementrise.com', 'supplementscare.co.za', 'supplementslove.com', 'supplementsnetherlands.nl', 'supplementsnewzealand.co.nz', 'supplementsonlinestore.com', 'supplementspeak.com', 'surveensaniya.com', 'sverigetillskott.se', 'switch-bot.com', 'switzerlandsupplements.ch', 'takeapills.com', 'tans.ca', 'tanyagupta.in', 'tapas.io', 'teamfeed.feedingamerica.org', 'techrum.vn', 'telegra.ph', 'teletype.in', 'termpapersite.com', 'thebackplane.com', 'thefitnesssupplement.com', 'thefitnesssupplementshop.blogspot.com', 'thehealthwind.com', 'theimagingprofessionals.co.uk', 'thenutritionvibe.com', 'theredfork.org', 'thietkevanan.com', 'time2trends.com', 'timeofhealth.info', 'timeofhealth.org', 'timesofnews24x7.com', 'tocal.instructure.com', 'toevolution.com', 'topcbdoilhub.com', 'topusatrendpills.com', 'totaldiet4you.com', 'totalketopills.com', 'training.dwfacademy.com', 'travelingpin.com', 'trentandallievan.com', 'triberr.com', 'tripoto.com', 'trippleresult.com', 'tryittoday.xyz', 'trypurenutrition.com', 'uagcasestore.com.au', 'uchearts.com', 'udaipurqueen.com', 'ultimate-guitar.com', 'unews.tv', 'usahealthpills.com', 'vashikaranexlove.com', 'verifiedexchange.com', 'verywellweightloss.com', 'videa.hu', 'viki.com', 'vle.ar-raniry.ac.id', 'webcampornodirecto.es', 'weddingwire.us', 'wellnessketoz.com', 'wfmj.com', 'wheretocare.com', 'wintersupplement.com', 'wiseintro.co', 'works.bepress.com', 'worldgymdiet.com', 'worthydiets.com', 'wow-keto.com', 'xn--testoultrasterreich-z6b.at', 'yarabook.com', 'yed.yworks.com', 'zaraaktar.com', 'zarakan.com', 'zephyr.com.pl', 'zobuz.com', ]; export const NON_SPAMMERS_DOMAINS = [ 'about.me', 'angel.co', 'behance.net', 'bit.do', 'bit.ly', 'crunchbase.com', 'dailymotion.com', 'dev.to', 'docs.google.com', 'dribbble.com', 'emailmeform.com', 'en.wikipedia.org', 'facebook.com', 'fda.gov', 'form.jotform.com', 'github.com', 'gmail.com', 'google.com', 'gumroad.com', 'i.imgur.com', 'img.over-blog-kiwi.com', 'instagram.com', 'is.gd', 'issuu.com', 'k12.instructure.com', 'linkedin.com', 'linktr.ee', 'm.facebook.com', 'marketwatch.com', 'medium.com', 'mndepted.instructure.com', 'moweb.com', 'myspace.com', 'ncbi.nlm.nih.gov', 'opencollective-production.s3.us-west-1.amazonaws.com', 'opencollective.com', 'pinterest.com', 'quora.com', 'rb.gy', 'reddit.com', 's3.amazonaws.com', 'scoop.it', 'service.elsevier.com', 'sites.google.com', 'soundcloud.com', 'surveymonkey.com', 't.me', 'teespring.com', 'twitter.com', 'utah.instructure.com', 'wattpad.com', 'youtu.be', 'youtube.com', 'zenodo.org', ]; /** * Returns suspicious keywords found in content */ export const getSuspiciousKeywords = (content: string): string[] => { if (!content) { return []; } return Object.keys(SPAM_KEYWORDS).reduce((result, keyword) => { if (content.toLowerCase().includes(keyword)) { result.push(keyword); } return result; }, []); }; /** * * Returns blocked domains found in content */ const getSpamDomains = (content: string): string[] => { if (!content) { return []; } const lowerCaseContent = content.toLowerCase(); return SPAMMERS_DOMAINS.reduce((result, domain) => { if (lowerCaseContent.includes(domain)) { result.push(domain); } return result; }, []); }; let bayesClassifier; const getBayesClassifier = async (): Promise<BayesClassifier> => { if (!bayesClassifier) { const bayesClassifierPath = path.join(__dirname, '..', '..', 'config', `collective-spam-bayes.json`); const bayesClassifierJson = await fs.promises.readFile(bayesClassifierPath, 'utf-8'); bayesClassifier = bayes.fromJson(bayesClassifierJson); } return bayesClassifier; }; const stringifyUrl = url => { return url .replace('http://', '') .replace('https://', '') .split('/') .join(' ') .split('-') .join(' ') .split('.') .join(' ') .split('?') .join(' ') .split('=') .join(' ') .split('&') .join(' ') .split('#') .join(' '); }; const addLine = (message: string, line: string): string => (line ? `${message}\n${line}` : message); export const collectiveBayesContent = async ( collective: typeof models.Collective, extraString = '', ): Promise<string> => { const slugString = (collective.slug || '').split('-').join(' '); const websiteString = stringifyUrl(collective.website || ''); const urls = getUrls(collective.longDescription || ''); const urlsString = [...urls].map(stringifyUrl).join(' '); const longDescriptionString = sanitizeHtml(collective.longDescription || '', { allowedTags: [], allowedAttributes: {}, }); return `${slugString} ${collective.name} ${collective.description} ${longDescriptionString} ${urlsString} ${websiteString} ${extraString}`; }; export const collectiveBayesCheck = async (collective: typeof models.Collective, extraString = ''): Promise<string> => { const content = await collectiveBayesContent(collective, extraString); const classifier = await getBayesClassifier(); return classifier.categorize(content); }; /** * Checks the values for this collective to try to determinate if it's a spammy profile. */ export const collectiveSpamCheck = async ( collective: typeof models.Collective, context: string, ): Promise<SpamAnalysisReport> => { const result = { score: 0, keywords: new Set<string>(), domains: new Set<string>() }; let bayesCheck = null; if (collective.description || collective.longDescription) { bayesCheck = await collectiveBayesCheck(collective, ''); if (bayesCheck === 'spam') { result.score += 0.5; } } ANALYZED_FIELDS.forEach(field => { // Check each field for SPAM keywords const suspiciousKeywords = getSuspiciousKeywords(collective[field] || ''); suspiciousKeywords.forEach(keyword => { result.keywords.add(keyword); result.score += SPAM_KEYWORDS[keyword]; }); // Check for blocked domains const blockedDomains = getSpamDomains(collective[field] || ''); if (blockedDomains.length) { blockedDomains.forEach(domain => result.domains.add(domain)); result.score = 1; } }); return { date: new Date().toISOString(), score: clamp(result.score, 0, 1), bayes: bayesCheck, keywords: Array.from(result.keywords), domains: Array.from(result.domains), data: collective.info || collective, context, }; }; /** * Post a message on Slack if the collective is suspicious */ export const notifyTeamAboutSuspiciousCollective = async (report: SpamAnalysisReport): Promise<void> => { const { score, keywords, domains, data } = report; let message = `*Suspicious collective data was submitted for collective:* https://opencollective.com/${data['slug']}`; message = addLine(message, `Score: ${score}`); message = addLine(message, keywords.length > 0 && `Keywords: \`${keywords.toString()}\``); message = addLine(message, domains.length > 0 && `Domains: \`${domains.toString()}\``); return slackLib.postMessageToOpenCollectiveSlack(message, OPEN_COLLECTIVE_SLACK_CHANNEL.ABUSE); }; /** * Post a message on Slack when the expense is marked as spam */ export const notifyTeamAboutSpamExpense = async (activity: typeof models.Activity): Promise<void> => { const { collective, expense, user } = activity.data; const expenseUrl = `${config.host.website}/${collective.slug}/expenses/${expense.id}`; const submittedByUserUrl = `${config.host.website}/${user.slug}`; let message = `*Expense was marked as spam:* ${expenseUrl}`; message = addLine(message, `Submitted by: ${submittedByUserUrl}`); return slackLib.postMessageToOpenCollectiveSlack(message, OPEN_COLLECTIVE_SLACK_CHANNEL.ABUSE); }; /** * If URL is an open collective redirect, returns the redirect link. */ export const resolveRedirect = (parsedUrl: URL): URL => { if ( parsedUrl.origin === config.host.website && parsedUrl.pathname === '/redirect' && parsedUrl.searchParams?.has('url') ) { try { return new URL(parsedUrl.searchParams.get('url')); } catch { // Ignore invalid redirect URLs } } return parsedUrl; };
the_stack
import type { GenericObject } from 'types/generic.type'; // States export type InternalPlayerState = 'buffering' | 'idle' | 'complete' | 'paused' | 'playing' | 'error' | 'loading' | 'stalled'; // Event Types export type TimeEvent = { position: number; duration?: number; currentTime?: number; seekRange?: { start: number; end: number; }; metadata?: GenericObject & { currentTime: number; }; type?: string; viewable?: number | boolean; } /** * The user pressed play, but sufficient data to start playback has not yet loaded. The buffering icon is visible in the display. */ export const STATE_BUFFERING: InternalPlayerState = 'buffering'; /** * Either playback has not started or playback was stopped due to a stop() call or an error. In this state, either the play or the error icon is visible in the display. */ export const STATE_IDLE: InternalPlayerState = 'idle'; /** * Playback has ended. The replay icon is visible in the display. */ export const STATE_COMPLETE: InternalPlayerState = 'complete'; /** * The video is currently paused. The play icon is visible in the display. */ export const STATE_PAUSED: InternalPlayerState = 'paused'; /** * The video is currently playing. No icon is visible in the display. */ export const STATE_PLAYING: InternalPlayerState = 'playing'; /** * Playback was stopped due to an error. In this state the error icon and a message are visible in the display. */ export const STATE_ERROR: InternalPlayerState = 'error'; /** * The user pressed play, but media has not yet loaded. */ export const STATE_LOADING: InternalPlayerState = 'loading'; /** * The user pressed play, but data is not being loaded. */ export const STATE_STALLED: InternalPlayerState = 'stalled'; // Touch Events /** * Event triggered while dragging the observed element. */ export const DRAG = 'drag'; /** * Event triggered when dragging the observed element begins. */ export const DRAG_START = 'dragStart'; /** * Event triggered when dragging the observed element ends. */ export const DRAG_END = 'dragEnd'; /** * Event triggered when a user clicks the observed element once. */ export const CLICK = 'click'; /** * Event triggered when a user clicks the observed element twice consecutively. */ export const DOUBLE_CLICK = 'doubleClick'; /** * Event triggered when the mouse is over the observed element. */ export const OVER = 'over'; /** * Event triggered while the mouse moves over the observed element. */ export const MOVE = 'move'; /** * Event triggered when a user presses the enter key on the observed element. */ export const ENTER = 'enter'; /** * Event triggered when the mouse is no longer over the observed element. */ export const OUT = 'out'; // Script Loaders /** * Event stream reproduction is stopped because of an error. */ export const ERROR = STATE_ERROR; /** * Event triggered when a non-fatal error is encountered */ export const WARNING = 'warning'; // Ad events /** * Event triggered when an ad is clicked. */ export const AD_CLICK = 'adClick'; /** * Event triggered once an ad tag is loaded containing companion creatives. */ export const AD_COMPANIONS = 'adCompanions'; /** * Event triggered when an ad has completed playback. */ export const AD_COMPLETE = 'adComplete'; /** * Event triggered when an error prevents the ad from playing. */ export const AD_ERROR = 'adError'; /** * Event triggered based on the IAB definition of an ad impression. This occurs the instant a video ad begins to play. */ export const AD_IMPRESSION = 'adImpression'; /** * Event triggered on instream adapter when vast media is loaded onto the video tag. */ export const AD_MEDIA_LOADED = 'mediaLoaded'; /** * Event triggered when metadata is obtained during ad playback. */ export const AD_META = 'adMeta'; /** * Event triggered when an ad is paused. */ export const AD_PAUSE = 'adPause'; /** * Event triggered when an ad starts or is resumed. */ export const AD_PLAY = 'adPlay'; /** * Event triggered when an ad is skipped. */ export const AD_SKIPPED = 'adSkipped'; /** * Event triggered while ad playback is in progress. */ export const AD_TIME = 'adTime'; /** * Event triggered for ad warnings (i.e. non-fatal errors) */ export const AD_WARNING = 'adWarning'; // Events /** * Triggered when the browsers' autoplay setting prohibits autostarting playback. */ export const AUTOSTART_NOT_ALLOWED = 'autostartNotAllowed'; /** * Event triggered when media playback ends because the last segment has been played. */ export const MEDIA_COMPLETE = STATE_COMPLETE; /** * Event triggered when the player's setup is complete and is ready to be used. This is the earliest point at which any API calls should be made. */ export const READY = 'ready'; /** * Event triggered when the playback position is either altered via API call, or due to user interaction. */ export const MEDIA_SEEK = 'seek'; /** * Fired just before the player begins playing. At this point the player will not have begun playing or buffering. This is the ideal moment to insert preroll ads using the playAd() API */ export const MEDIA_BEFOREPLAY = 'beforePlay'; /** * Fired just before the player completes playing. At this point the player will not have moved on to either showing the replay screen or advancing to the next playlistItem. This is the ideal moment to insert postroll ads using the playAd() API */ export const MEDIA_BEFORECOMPLETE = 'beforeComplete'; /** * Fired when buffer has reached the maximum capacity. */ export const MEDIA_BUFFER_FULL = 'bufferFull'; /** * Fired when a click on the video display is detected. */ export const DISPLAY_CLICK = 'displayClick'; /** * Fired when the final item in a playlist has played its final segment and has ended. */ export const PLAYLIST_COMPLETE = 'playlistComplete'; /** * Fired when changes to the casting status are detected, i.e. when connected or disconnected from a device. */ export const CAST_SESSION = 'cast'; /** * Fired when an attempt to reproduce media results in a failure, causing the player to stop playback and go into idle mode. */ export const MEDIA_ERROR = 'mediaError'; /** * Triggered by a video's first frame event, or the instant an audio file begins playback. */ export const MEDIA_FIRST_FRAME = 'firstFrame'; /** * Triggered the moment a request to play content is made. */ export const MEDIA_PLAY_ATTEMPT = 'playAttempt'; /** * Fired when playback is aborted or blocked. Pausing the video or changing the media results * in play attempts being aborted. In mobile browsers play attempts are blocked when not started by * a user gesture. */ export const MEDIA_PLAY_ATTEMPT_FAILED = 'playAttemptFailed'; /** * Fired when media has been loaded into the player. */ export const MEDIA_LOADED = 'loaded'; /** * Triggered when the video position changes after seeking, as opposed to MEDIA_SEEK which is triggered as a seek occurs. */ export const MEDIA_SEEKED = 'seeked'; // Setup Events /** * Triggered when the player's setup results in a failure. */ export const SETUP_ERROR = 'setupError'; // Utility /** * Triggered when the player's playback state changes. */ export const PLAYER_STATE = 'state'; /** * Fired when devices are available for casting. */ export const CAST_AVAILABLE = 'castAvailable'; // Model Changes /** * Fired when the currently playing item loads additional data into its buffer. This only applies to VOD media; live streaming media (HLS/DASH) does not expose this behavior. */ export const MEDIA_BUFFER = 'bufferChange'; /** * Fired as the playback position gets updated, while the player is playing. */ export const MEDIA_TIME = 'time'; /** * Fired when the playbackRate of the video tag changes. */ export const MEDIA_RATE_CHANGE = 'ratechange'; /** * Fired when a loaded item's media type is detected. */ export const MEDIA_TYPE = 'mediaType'; /** * Fired when the playback volume is altered. */ export const MEDIA_VOLUME = 'volume'; /** * Fired when media is muted; */ export const MEDIA_MUTE = 'mute'; /** * Fired when metadata embedded in the media file is obtained. */ export const MEDIA_META_CUE_PARSED = 'metadataCueParsed'; /** * Fired when metadata embedded in the media file is obtained. */ export const MEDIA_META = 'meta'; /** * Fired when the list of available quality levels is updated. */ export const MEDIA_LEVELS = 'levels'; /** * Fired when the active quality level is changed. */ export const MEDIA_LEVEL_CHANGED = 'levelsChanged'; /** * Fired when the visual quality of media is updated. */ export const MEDIA_VISUAL_QUALITY = 'visualQuality'; /** * Fired when controls are enabled or disabled by a script. */ export const CONTROLS = 'controls'; /** * Fired when the player toggles to/from fullscreen. */ export const FULLSCREEN = 'fullscreen'; /** * Fired when the player's on-page dimensions have changed. Is not fired in response to a fullscreen change. */ export const RESIZE = 'resize'; /** * Fired when a new playlist item has been loaded into the player. */ export const PLAYLIST_ITEM = 'playlistItem'; /** * Fired when an entirely new playlist has been loaded into the player. */ export const PLAYLIST_LOADED = 'playlist'; /** * Fired when the list of available audio tracks is updated. Happens shortly after a playlist item starts playing. */ export const AUDIO_TRACKS = 'audioTracks'; /** * Fired when the active audio track is changed. Happens in response to e.g. a user clicking the audio tracks menu or a script calling setCurrentAudioTrack(). */ export const AUDIO_TRACK_CHANGED = 'audioTrackChanged'; /** * Fired when the list of available subtitle tracks is updated. Happens shortly after a playlist item starts playing. */ export const SUBTITLES_TRACKS = 'subtitlesTracks'; /** * Fired when the active subtitle track is changed. Happens in response to e.g. a user clicking the subtitle tracks menu or a script calling setCurrentSubtitleTrack(). */ export const SUBTITLES_TRACK_CHANGED = 'subtitlesTrackChanged'; /** * Fired when the playback rate has been changed. */ export const PLAYBACK_RATE_CHANGED = 'playbackRateChanged'; // View Component Actions /** * Fired when a click has been detected on the logo element. */ export const LOGO_CLICK = 'logoClick'; // Model - Captions /** * Fired when the list of available captions tracks changes. This event is the ideal time to set default captions with the API. */ export const CAPTIONS_LIST = 'captionsList'; /** * Triggered whenever the active captions track is changed manually or via API. */ export const CAPTIONS_CHANGED = 'captionsChanged'; // Provider Communication /** * Fired the provider being utilized by JW Player for a particular media file is replaced by a new provider. */ export const PROVIDER_CHANGED = 'providerChanged'; /** * Triggered when a provider begins playback to signal availability of first frame. */ export const PROVIDER_FIRST_FRAME = 'providerFirstFrame'; // UI Events /** * Fired when user activity is detected on the targeted element. */ export const USER_ACTION = 'userAction'; /** * Fired when the instream adapter detects a click. */ export const INSTREAM_CLICK = 'instreamClick'; /** * Triggered when the player is resized to a width in a different breakpoint category. */ export const BREAKPOINT = 'breakpoint'; /** * Triggered when receiving a native 'fullscreenchange' event from a video tag */ export const NATIVE_FULLSCREEN = 'fullscreenchange'; /** * Triggered when a new bandwidth estimate is available */ export const BANDWIDTH_ESTIMATE = 'bandwidthEstimate'; /** * Triggered when the player starts/stops floating */ export const FLOAT = 'float';
the_stack
import { replaceAll } from "./util/utils"; type URLQueryParseState = "ParameterName" | "ParameterValue" | "Invalid"; /** * A class that handles the query portion of a URLBuilder. */ export class URLQuery { private readonly _rawQuery: { [queryParameterName: string]: string | string[] } = {}; /** * Get whether or not there any query parameters in this URLQuery. */ public any(): boolean { return Object.keys(this._rawQuery).length > 0; } /** * Set a query parameter with the provided name and value. If the parameterValue is undefined or * empty, then this will attempt to remove an existing query parameter with the provided * parameterName. */ public set(parameterName: string, parameterValue: any): void { if (parameterName) { if (parameterValue != undefined) { const newValue = Array.isArray(parameterValue) ? parameterValue : parameterValue.toString(); this._rawQuery[parameterName] = newValue; } else { delete this._rawQuery[parameterName]; } } } /** * Get the value of the query parameter with the provided name. If no parameter exists with the * provided parameter name, then undefined will be returned. */ public get(parameterName: string): string | string[] | undefined { return parameterName ? this._rawQuery[parameterName] : undefined; } /** * Get the string representation of this query. The return value will not start with a "?". */ public toString(): string { let result = ""; for (const parameterName in this._rawQuery) { if (result) { result += "&"; } const parameterValue = this._rawQuery[parameterName]; if (Array.isArray(parameterValue)) { const parameterStrings = []; for (const parameterValueElement of parameterValue) { parameterStrings.push(`${parameterName}=${parameterValueElement}`); } result += parameterStrings.join("&"); } else { result += `${parameterName}=${parameterValue}`; } } return result; } /** * Parse a URLQuery from the provided text. */ public static parse(text: string): URLQuery { const result = new URLQuery(); if (text) { if (text.startsWith("?")) { text = text.substring(1); } let currentState: URLQueryParseState = "ParameterName"; let parameterName = ""; let parameterValue = ""; for (let i = 0; i < text.length; ++i) { const currentCharacter: string = text[i]; switch (currentState) { case "ParameterName": switch (currentCharacter) { case "=": currentState = "ParameterValue"; break; case "&": parameterName = ""; parameterValue = ""; break; default: parameterName += currentCharacter; break; } break; case "ParameterValue": switch (currentCharacter) { case "&": result.set(parameterName, parameterValue); parameterName = ""; parameterValue = ""; currentState = "ParameterName"; break; default: parameterValue += currentCharacter; break; } break; default: throw new Error("Unrecognized URLQuery parse state: " + currentState); } } if (currentState === "ParameterValue") { result.set(parameterName, parameterValue); } } return result; } } /** * A class that handles creating, modifying, and parsing URLs. */ export class URLBuilder { private _scheme: string | undefined; private _host: string | undefined; private _port: string | undefined; private _path: string | undefined; private _query: URLQuery | undefined; /** * Set the scheme/protocol for this URL. If the provided scheme contains other parts of a URL * (such as a host, port, path, or query), those parts will be added to this URL as well. */ public setScheme(scheme: string | undefined): void { if (!scheme) { this._scheme = undefined; } else { this.set(scheme, "SCHEME"); } } /** * Get the scheme that has been set in this URL. */ public getScheme(): string | undefined { return this._scheme; } /** * Set the host for this URL. If the provided host contains other parts of a URL (such as a * port, path, or query), those parts will be added to this URL as well. */ public setHost(host: string | undefined): void { if (!host) { this._host = undefined; } else { this.set(host, "SCHEME_OR_HOST"); } } /** * Get the host that has been set in this URL. */ public getHost(): string | undefined { return this._host; } /** * Set the port for this URL. If the provided port contains other parts of a URL (such as a * path or query), those parts will be added to this URL as well. */ public setPort(port: number | string | undefined): void { if (port == undefined || port === "") { this._port = undefined; } else { this.set(port.toString(), "PORT"); } } /** * Get the port that has been set in this URL. */ public getPort(): string | undefined { return this._port; } /** * Set the path for this URL. If the provided path contains a query, then it will be added to * this URL as well. */ public setPath(path: string | undefined): void { if (!path) { this._path = undefined; } else { const schemeIndex = path.indexOf("://"); if (schemeIndex !== -1) { const schemeStart = path.lastIndexOf("/", schemeIndex); // Make sure to only grab the URL part of the path before setting the state back to SCHEME // this will handle cases such as "/a/b/c/https://microsoft.com" => "https://microsoft.com" this.set(schemeStart === -1 ? path : path.substr(schemeStart + 1), "SCHEME"); } else { this.set(path, "PATH"); } } } /** * Append the provided path to this URL's existing path. If the provided path contains a query, * then it will be added to this URL as well. */ public appendPath(path: string | undefined): void { if (path) { let currentPath: string | undefined = this.getPath(); if (currentPath) { if (!currentPath.endsWith("/")) { currentPath += "/"; } if (path.startsWith("/")) { path = path.substring(1); } path = currentPath + path; } this.set(path, "PATH"); } } /** * Get the path that has been set in this URL. */ public getPath(): string | undefined { return this._path; } /** * Set the query in this URL. */ public setQuery(query: string | undefined): void { if (!query) { this._query = undefined; } else { this._query = URLQuery.parse(query); } } /** * Set a query parameter with the provided name and value in this URL's query. If the provided * query parameter value is undefined or empty, then the query parameter will be removed if it * existed. */ public setQueryParameter(queryParameterName: string, queryParameterValue: any): void { if (queryParameterName) { if (!this._query) { this._query = new URLQuery(); } this._query.set(queryParameterName, queryParameterValue); } } /** * Get the value of the query parameter with the provided query parameter name. If no query * parameter exists with the provided name, then undefined will be returned. */ public getQueryParameterValue(queryParameterName: string): string | string[] | undefined { return this._query ? this._query.get(queryParameterName) : undefined; } /** * Get the query in this URL. */ public getQuery(): string | undefined { return this._query ? this._query.toString() : undefined; } /** * Set the parts of this URL by parsing the provided text using the provided startState. */ private set(text: string, startState: URLTokenizerState): void { const tokenizer = new URLTokenizer(text, startState); while (tokenizer.next()) { const token: URLToken | undefined = tokenizer.current(); if (token) { switch (token.type) { case "SCHEME": this._scheme = token.text || undefined; break; case "HOST": this._host = token.text || undefined; break; case "PORT": this._port = token.text || undefined; break; case "PATH": const tokenPath: string | undefined = token.text || undefined; if (!this._path || this._path === "/" || tokenPath !== "/") { this._path = tokenPath; } break; case "QUERY": this._query = URLQuery.parse(token.text); break; default: throw new Error(`Unrecognized URLTokenType: ${token.type}`); } } } } public toString(): string { let result = ""; if (this._scheme) { result += `${this._scheme}://`; } if (this._host) { result += this._host; } if (this._port) { result += `:${this._port}`; } if (this._path) { if (!this._path.startsWith("/")) { result += "/"; } result += this._path; } if (this._query && this._query.any()) { result += `?${this._query.toString()}`; } return result; } /** * If the provided searchValue is found in this URLBuilder, then replace it with the provided * replaceValue. */ public replaceAll(searchValue: string, replaceValue: string): void { if (searchValue) { this.setScheme(replaceAll(this.getScheme(), searchValue, replaceValue)); this.setHost(replaceAll(this.getHost(), searchValue, replaceValue)); this.setPort(replaceAll(this.getPort(), searchValue, replaceValue)); this.setPath(replaceAll(this.getPath(), searchValue, replaceValue)); this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue)); } } public static parse(text: string): URLBuilder { const result = new URLBuilder(); result.set(text, "SCHEME_OR_HOST"); return result; } } type URLTokenizerState = "SCHEME" | "SCHEME_OR_HOST" | "HOST" | "PORT" | "PATH" | "QUERY" | "DONE"; type URLTokenType = "SCHEME" | "HOST" | "PORT" | "PATH" | "QUERY"; export class URLToken { public constructor(public readonly text: string, public readonly type: URLTokenType) {} public static scheme(text: string): URLToken { return new URLToken(text, "SCHEME"); } public static host(text: string): URLToken { return new URLToken(text, "HOST"); } public static port(text: string): URLToken { return new URLToken(text, "PORT"); } public static path(text: string): URLToken { return new URLToken(text, "PATH"); } public static query(text: string): URLToken { return new URLToken(text, "QUERY"); } } /** * Get whether or not the provided character (single character string) is an alphanumeric (letter or * digit) character. */ export function isAlphaNumericCharacter(character: string): boolean { const characterCode: number = character.charCodeAt(0); return ( (48 /* '0' */ <= characterCode && characterCode <= 57) /* '9' */ || (65 /* 'A' */ <= characterCode && characterCode <= 90) /* 'Z' */ || (97 /* 'a' */ <= characterCode && characterCode <= 122) /* 'z' */ ); } /** * A class that tokenizes URL strings. */ export class URLTokenizer { readonly _textLength: number; _currentState: URLTokenizerState; _currentIndex: number; _currentToken: URLToken | undefined; public constructor(readonly _text: string, state?: URLTokenizerState) { this._textLength = _text ? _text.length : 0; this._currentState = state != undefined ? state : "SCHEME_OR_HOST"; this._currentIndex = 0; } /** * Get the current URLToken this URLTokenizer is pointing at, or undefined if the URLTokenizer * hasn't started or has finished tokenizing. */ public current(): URLToken | undefined { return this._currentToken; } /** * Advance to the next URLToken and return whether or not a URLToken was found. */ public next(): boolean { if (!hasCurrentCharacter(this)) { this._currentToken = undefined; } else { switch (this._currentState) { case "SCHEME": nextScheme(this); break; case "SCHEME_OR_HOST": nextSchemeOrHost(this); break; case "HOST": nextHost(this); break; case "PORT": nextPort(this); break; case "PATH": nextPath(this); break; case "QUERY": nextQuery(this); break; default: throw new Error(`Unrecognized URLTokenizerState: ${this._currentState}`); } } return !!this._currentToken; } } /** * Read the remaining characters from this Tokenizer's character stream. */ function readRemaining(tokenizer: URLTokenizer): string { let result = ""; if (tokenizer._currentIndex < tokenizer._textLength) { result = tokenizer._text.substring(tokenizer._currentIndex); tokenizer._currentIndex = tokenizer._textLength; } return result; } /** * Whether or not this URLTokenizer has a current character. */ function hasCurrentCharacter(tokenizer: URLTokenizer): boolean { return tokenizer._currentIndex < tokenizer._textLength; } /** * Get the character in the text string at the current index. */ function getCurrentCharacter(tokenizer: URLTokenizer): string { return tokenizer._text[tokenizer._currentIndex]; } /** * Advance to the character in text that is "step" characters ahead. If no step value is provided, * then step will default to 1. */ function nextCharacter(tokenizer: URLTokenizer, step?: number): void { if (hasCurrentCharacter(tokenizer)) { if (!step) { step = 1; } tokenizer._currentIndex += step; } } /** * Starting with the current character, peek "charactersToPeek" number of characters ahead in this * Tokenizer's stream of characters. */ function peekCharacters(tokenizer: URLTokenizer, charactersToPeek: number): string { let endIndex: number = tokenizer._currentIndex + charactersToPeek; if (tokenizer._textLength < endIndex) { endIndex = tokenizer._textLength; } return tokenizer._text.substring(tokenizer._currentIndex, endIndex); } /** * Read characters from this Tokenizer until the end of the stream or until the provided condition * is false when provided the current character. */ function readWhile(tokenizer: URLTokenizer, condition: (character: string) => boolean): string { let result = ""; while (hasCurrentCharacter(tokenizer)) { const currentCharacter: string = getCurrentCharacter(tokenizer); if (!condition(currentCharacter)) { break; } else { result += currentCharacter; nextCharacter(tokenizer); } } return result; } /** * Read characters from this Tokenizer until a non-alphanumeric character or the end of the * character stream is reached. */ function readWhileLetterOrDigit(tokenizer: URLTokenizer): string { return readWhile(tokenizer, (character: string) => isAlphaNumericCharacter(character)); } /** * Read characters from this Tokenizer until one of the provided terminating characters is read or * the end of the character stream is reached. */ function readUntilCharacter(tokenizer: URLTokenizer, ...terminatingCharacters: string[]): string { return readWhile( tokenizer, (character: string) => terminatingCharacters.indexOf(character) === -1 ); } function nextScheme(tokenizer: URLTokenizer): void { const scheme: string = readWhileLetterOrDigit(tokenizer); tokenizer._currentToken = URLToken.scheme(scheme); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; } else { tokenizer._currentState = "HOST"; } } function nextSchemeOrHost(tokenizer: URLTokenizer): void { const schemeOrHost: string = readUntilCharacter(tokenizer, ":", "/", "?"); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentToken = URLToken.host(schemeOrHost); tokenizer._currentState = "DONE"; } else if (getCurrentCharacter(tokenizer) === ":") { if (peekCharacters(tokenizer, 3) === "://") { tokenizer._currentToken = URLToken.scheme(schemeOrHost); tokenizer._currentState = "HOST"; } else { tokenizer._currentToken = URLToken.host(schemeOrHost); tokenizer._currentState = "PORT"; } } else { tokenizer._currentToken = URLToken.host(schemeOrHost); if (getCurrentCharacter(tokenizer) === "/") { tokenizer._currentState = "PATH"; } else { tokenizer._currentState = "QUERY"; } } } function nextHost(tokenizer: URLTokenizer): void { if (peekCharacters(tokenizer, 3) === "://") { nextCharacter(tokenizer, 3); } const host: string = readUntilCharacter(tokenizer, ":", "/", "?"); tokenizer._currentToken = URLToken.host(host); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; } else if (getCurrentCharacter(tokenizer) === ":") { tokenizer._currentState = "PORT"; } else if (getCurrentCharacter(tokenizer) === "/") { tokenizer._currentState = "PATH"; } else { tokenizer._currentState = "QUERY"; } } function nextPort(tokenizer: URLTokenizer): void { if (getCurrentCharacter(tokenizer) === ":") { nextCharacter(tokenizer); } const port: string = readUntilCharacter(tokenizer, "/", "?"); tokenizer._currentToken = URLToken.port(port); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; } else if (getCurrentCharacter(tokenizer) === "/") { tokenizer._currentState = "PATH"; } else { tokenizer._currentState = "QUERY"; } } function nextPath(tokenizer: URLTokenizer): void { const path: string = readUntilCharacter(tokenizer, "?"); tokenizer._currentToken = URLToken.path(path); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; } else { tokenizer._currentState = "QUERY"; } } function nextQuery(tokenizer: URLTokenizer): void { if (getCurrentCharacter(tokenizer) === "?") { nextCharacter(tokenizer); } const query: string = readRemaining(tokenizer); tokenizer._currentToken = URLToken.query(query); tokenizer._currentState = "DONE"; }
the_stack
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js'; import 'chrome://resources/cr_elements/cr_search_field/cr_search_field.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import 'chrome://resources/cr_elements/md_select_css.m.js'; import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js'; import 'chrome://resources/polymer/v3_0/iron-list/iron-list.js'; import '../settings_shared_css.js'; import './all_sites_icons.js'; import './clear_storage_dialog_css.js'; import './site_entry.js'; import {CrActionMenuElement} from 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js'; import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import {CrLazyRenderElement} from 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {I18nMixin, I18nMixinInterface} from 'chrome://resources/js/i18n_mixin.js'; import {WebUIListenerMixin, WebUIListenerMixinInterface} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {IronListElement} from 'chrome://resources/polymer/v3_0/iron-list/iron-list.js'; import {afterNextRender, html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {GlobalScrollTargetMixin} from '../global_scroll_target_mixin.js'; import {loadTimeData} from '../i18n_setup.js'; import {routes} from '../route.js'; import {Route, RouteObserverMixin, RouteObserverMixinInterface, Router} from '../router.js'; import {ALL_SITES_DIALOG, AllSitesAction2, ContentSetting, ContentSettingsTypes, SortMethod} from './constants.js'; import {LocalDataBrowserProxy, LocalDataBrowserProxyImpl} from './local_data_browser_proxy.js'; import {SiteSettingsMixin, SiteSettingsMixinInterface} from './site_settings_mixin.js'; import {OriginInfo, SiteGroup} from './site_settings_prefs_browser_proxy.js'; type ActionMenuModel = { actionScope: string, index: number, item: SiteGroup, origin: string, path: string, target: HTMLElement, }; type OpenMenuEvent = CustomEvent<ActionMenuModel>; type RemoveSiteEvent = CustomEvent<ActionMenuModel>; type SelectedItem = { item: SiteGroup, index: number, }; declare global { interface HTMLElementEventMap { 'open-menu': OpenMenuEvent; 'remove-site': RemoveSiteEvent; 'site-entry-selected': CustomEvent<SelectedItem>; } } interface AllSitesElement { $: { allSitesList: IronListElement, confirmClearAllData: CrLazyRenderElement<CrDialogElement>, confirmClearData: CrLazyRenderElement<CrDialogElement>, confirmRemoveSite: CrLazyRenderElement<CrDialogElement>, confirmResetSettings: CrLazyRenderElement<CrDialogElement>, menu: CrLazyRenderElement<CrActionMenuElement>, sortMethod: HTMLSelectElement, }; } // TODO(crbug.com/1234307): Remove when RouteObserverMixin is converted to // TypeScript. type Constructor<T> = new (...args: any[]) => T; const AllSitesElementBaseTemp = GlobalScrollTargetMixin( RouteObserverMixin( WebUIListenerMixin(I18nMixin(SiteSettingsMixin(PolymerElement)))) as unknown as Constructor<PolymerElement>); const AllSitesElementBase = AllSitesElementBaseTemp as unknown as { new (): PolymerElement & I18nMixinInterface & WebUIListenerMixinInterface & SiteSettingsMixinInterface & RouteObserverMixinInterface }; class AllSitesElement extends AllSitesElementBase { static get is() { return 'all-sites'; } static get template() { return html`{__html_template__}`; } static get properties() { return { // TODO(https://crbug.com/1037809): Refactor siteGroupMap to use an Object // instead of a Map so that it's observable by Polymer more naturally. As // it stands, one cannot use computed properties based off the value of // siteGroupMap nor can one use observable functions to listen to changes // to siteGroupMap. /** * Map containing sites to display in the widget, grouped into their * eTLD+1 names. */ siteGroupMap: { type: Object, value() { return new Map(); }, }, /** * Filtered site group list. */ filteredList_: { type: Array, }, /** * Needed by GlobalScrollTargetMixin. */ subpageRoute: { type: Object, value: routes.SITE_SETTINGS_ALL, readOnly: true, }, /** * The search query entered into the All Sites search textbox. Used to * filter the All Sites list. */ filter: { type: String, value: '', observer: 'forceListUpdate_', }, /** * All possible sort methods. */ sortMethods_: { type: Object, value: SortMethod, readOnly: true, }, /** * Stores the last selected item in the All Sites list. */ selectedItem_: Object, /** * Used to track the last-focused element across rows for the * focusRowBehavior. */ lastFocused_: Object, /** * Used to track whether the list of row items has been blurred for the * focusRowBehavior. */ listBlurred_: Boolean, actionMenuModel_: Object, /** * Used to determine if user is attempting to clear all site data * rather than a single site or origin's data. */ clearAllData_: Boolean, /** * The selected sort method. */ sortMethod_: String, /** * The total usage of all sites for this profile. */ totalUsage_: { type: String, value: '0 B', }, }; } siteGroupMap: Map<string, SiteGroup>; private filteredList_: Array<SiteGroup>; subpageRoute: Route; private filter: string; private selectedItem_: SelectedItem|null; private listBlurred_: boolean; private actionMenuModel_: ActionMenuModel|null; private clearAllData_: boolean; private sortMethod_?: SortMethod; private totalUsage_: string; private localDataBrowserProxy_: LocalDataBrowserProxy = LocalDataBrowserProxyImpl.getInstance(); ready() { super.ready(); this.addWebUIListener( 'onStorageListFetched', this.onStorageListFetched.bind(this)); this.addEventListener( 'site-entry-selected', (e: CustomEvent<SelectedItem>) => { this.selectedItem_ = e.detail; }); this.addEventListener('open-menu', this.onOpenMenu_.bind(this)); this.addEventListener('remove-site', this.onRemoveSite_.bind(this)); const sortParam = Router.getInstance().getQueryParameters().get('sort'); if (sortParam !== null && Object.values(SortMethod).includes(sortParam as SortMethod)) { this.$.sortMethod.value = sortParam; } this.sortMethod_ = this.$.sortMethod.value as (SortMethod | undefined); } connectedCallback() { super.connectedCallback(); // Set scrollOffset so the iron-list scrolling accounts for the space the // title takes. afterNextRender(this, () => { this.$.allSitesList.scrollOffset = this.$.allSitesList.offsetTop; }); } /** * Reload the site list when the all sites page is visited. * * RouteObserverBehavior */ currentRouteChanged(currentRoute: Route) { super.currentRouteChanged(currentRoute); if (currentRoute === routes.SITE_SETTINGS_ALL) { this.populateList_(); } } /** * Retrieves a list of all known sites with site details. */ private populateList_() { this.browserProxy.getAllSites().then((response) => { // Create a new map to make an observable change. const newMap = new Map(this.siteGroupMap); response.forEach(siteGroup => { newMap.set(siteGroup.etldPlus1, siteGroup); }); this.siteGroupMap = newMap; this.updateTotalUsage_(); this.forceListUpdate_(); }); } /** * Integrate sites using storage into the existing sites map, as there * may be overlap between the existing sites. * @param list The list of sites using storage. */ onStorageListFetched(list: Array<SiteGroup>) { // Create a new map to make an observable change. const newMap = new Map(this.siteGroupMap); list.forEach(storageSiteGroup => { newMap.set(storageSiteGroup.etldPlus1, storageSiteGroup); }); this.siteGroupMap = newMap; this.updateTotalUsage_(); this.forceListUpdate_(); this.focusOnLastSelectedEntry_(); } /** * Update the total usage by all sites for this profile after updates * to the list */ private updateTotalUsage_() { let usageSum = 0; for (const [etldPlus1, siteGroup] of this.siteGroupMap) { siteGroup.origins.forEach(origin => { usageSum += origin.usage; }); } this.browserProxy.getFormattedBytes(usageSum).then(totalUsage => { this.totalUsage_ = totalUsage; }); } /** * Filters the all sites list with the given search query text. * @param siteGroupMap The map of sites to filter. * @param searchQuery The filter text. */ private filterPopulatedList_( siteGroupMap: Map<string, SiteGroup>, searchQuery: string): Array<SiteGroup> { const result = []; for (const [etldPlus1, siteGroup] of siteGroupMap) { if (siteGroup.origins.find( originInfo => originInfo.origin.includes(searchQuery))) { result.push(siteGroup); } } return this.sortSiteGroupList_(result); } /** * Sorts the given SiteGroup list with the currently selected sort method. * @param siteGroupList The list of sites to sort. */ private sortSiteGroupList_(siteGroupList: Array<SiteGroup>): Array<SiteGroup> { const sortMethod = this.$.sortMethod.value; if (!sortMethod) { return siteGroupList; } if (sortMethod === SortMethod.MOST_VISITED) { siteGroupList.sort(this.mostVisitedComparator_); } else if (sortMethod === SortMethod.STORAGE) { siteGroupList.sort(this.storageComparator_); } else if (sortMethod === SortMethod.NAME) { siteGroupList.sort(this.nameComparator_); } return siteGroupList; } /** * Comparator used to sort SiteGroups by the amount of engagement the user has * with the origins listed inside it. Note only the maximum engagement is used * for each SiteGroup (as opposed to the sum) in order to prevent domains with * higher numbers of origins from always floating to the top of the list. */ private mostVisitedComparator_(siteGroup1: SiteGroup, siteGroup2: SiteGroup): number { const getMaxEngagement = (max: number, originInfo: OriginInfo) => { return (max > originInfo.engagement) ? max : originInfo.engagement; }; const score1 = siteGroup1.origins.reduce(getMaxEngagement, 0); const score2 = siteGroup2.origins.reduce(getMaxEngagement, 0); return score2 - score1; } /** * Comparator used to sort SiteGroups by the amount of storage they use. Note * this sorts in descending order. */ private storageComparator_(siteGroup1: SiteGroup, siteGroup2: SiteGroup): number { const getOverallUsage = (siteGroup: SiteGroup) => { let usage = 0; siteGroup.origins.forEach(originInfo => { usage += originInfo.usage; }); return usage; }; const siteGroup1Size = getOverallUsage(siteGroup1); const siteGroup2Size = getOverallUsage(siteGroup2); // Use the number of cookies as a tie breaker. return siteGroup2Size - siteGroup1Size || siteGroup2.numCookies - siteGroup1.numCookies; } /** * Comparator used to sort SiteGroups by their eTLD+1 name (domain). */ private nameComparator_(siteGroup1: SiteGroup, siteGroup2: SiteGroup): number { return siteGroup1.etldPlus1.localeCompare(siteGroup2.etldPlus1); } /** * Called when the user chooses a different sort method to the default. */ private onSortMethodChanged_() { this.sortMethod_ = this.$.sortMethod.value as SortMethod; this.filteredList_ = this.sortSiteGroupList_(this.filteredList_); // Force the iron-list to rerender its items, as the order has changed. this.$.allSitesList.fire('iron-resize'); } /** * Forces the all sites list to update its list of items, taking into account * the search query and the sort method, then re-renders it. */ private forceListUpdate_() { this.filteredList_ = this.filterPopulatedList_(this.siteGroupMap, this.filter); this.$.allSitesList.fire('iron-resize'); } /** * @return Whether the |siteGroupMap| is empty. */ private siteGroupMapEmpty_(): boolean { return !this.siteGroupMap.size; } /** * @return Whether the |filteredList_| is empty due to searching. */ private noSearchResultFound_(): boolean { return !this.filteredList_.length && !this.siteGroupMapEmpty_(); } /** * Focus on previously selected entry. */ private focusOnLastSelectedEntry_() { if (!this.selectedItem_ || this.siteGroupMap.size === 0) { return; } // Focus the site-entry to ensure the iron-list renders it, otherwise // the query selector will not be able to find it. Note the index is // used here instead of the item, in case the item was already removed. const index = Math.max(0, Math.min(this.selectedItem_.index, this.siteGroupMap.size)); this.$.allSitesList.focusItem(index); this.selectedItem_ = null; } /** * Open the overflow menu and ensure that the item is visible in the scroll * pane when its menu is opened (it is possible to open off-screen items using * keyboard shortcuts). */ private onOpenMenu_(e: OpenMenuEvent) { const index = e.detail.index; const list = this.$.allSitesList; if (index < list.firstVisibleIndex || index > list.lastVisibleIndex) { list.scrollToIndex(index); } const target = e.detail.target; this.actionMenuModel_ = e.detail; this.$.menu.get().showAt(target); } onRemoveSite_(e: RemoveSiteEvent) { this.actionMenuModel_ = e.detail; this.$.confirmRemoveSite.get().showModal(); } onConfirmRemoveSite_(e: Event) { const {index, actionScope, origin} = this.actionMenuModel_!; const siteGroupToUpdate = this.filteredList_[index]; const updatedSiteGroup: SiteGroup = { etldPlus1: siteGroupToUpdate.etldPlus1, hasInstalledPWA: siteGroupToUpdate.hasInstalledPWA, numCookies: siteGroupToUpdate.numCookies, origins: [] }; if (actionScope === 'origin') { this.browserProxy.clearOriginDataAndCookies(this.toUrl(origin)!.href); this.resetPermissionsForOrigin_(origin); updatedSiteGroup.origins = siteGroupToUpdate.origins.filter(o => o.origin !== origin); updatedSiteGroup.hasInstalledPWA = updatedSiteGroup.origins.some(o => o.isInstalled); updatedSiteGroup.numCookies -= siteGroupToUpdate.origins.find(o => o.origin === origin)!.numCookies; } else { this.browserProxy.clearEtldPlus1DataAndCookies( siteGroupToUpdate.etldPlus1); siteGroupToUpdate.origins.forEach(originEntry => { this.resetPermissionsForOrigin_(originEntry.origin); }); } this.updateSiteGroup_(index, updatedSiteGroup); this.$.allSitesList.fire('iron-resize'); this.updateTotalUsage_(); this.onCloseDialog_(e); } /** * Confirms the resetting of all content settings for an origin. */ private onConfirmResetSettings_(e: Event) { e.preventDefault(); const scope = this.actionMenuModel_!.actionScope === 'origin' ? 'Origin' : 'SiteGroup'; const scopes = [ALL_SITES_DIALOG.RESET_PERMISSIONS, scope, 'DialogOpened']; this.recordUserAction_(scopes); this.$.confirmResetSettings.get().showModal(); } /** * Confirms the clearing of all storage data for an etld+1. */ private onConfirmClearData_(e: Event) { e.preventDefault(); const {actionScope, index, origin} = this.actionMenuModel_!; const {origins, hasInstalledPWA} = this.filteredList_[index]; const scope = actionScope === 'origin' ? 'Origin' : 'SiteGroup'; const appInstalled = actionScope === 'origin' ? (origins.find(o => o.origin === origin) || {}).isInstalled : hasInstalledPWA; const installed = appInstalled ? 'Installed' : ''; const scopes = [ALL_SITES_DIALOG.CLEAR_DATA, scope, installed, 'DialogOpened']; this.recordUserAction_(scopes); this.$.confirmClearData.get().showModal(); } /** * Confirms the clearing of all storage data for all sites. */ private onConfirmClearAllData_(e: Event) { e.preventDefault(); this.clearAllData_ = true; const anyAppsInstalled = this.filteredList_.some(g => g.hasInstalledPWA); const scopes = [ALL_SITES_DIALOG.CLEAR_DATA, 'All']; const installed = anyAppsInstalled ? 'Installed' : ''; this.recordUserAction_([...scopes, installed, 'DialogOpened']); this.$.confirmClearAllData.get().showModal(); } private onCloseDialog_(e: Event) { chrome.metricsPrivate.recordUserAction('AllSites_DialogClosed'); (e.target as HTMLElement).closest('cr-dialog')!.close(); this.actionMenuModel_ = null; this.$.menu.get().close(); } /** * Get the appropriate label string for the clear data dialog based on whether * user is clearing data for an origin or siteGroup, and whether or not the * origin/siteGroup has an associated installed app. */ private getClearDataLabel_(): string { // actionMenuModel_ will be null when dialog closes if (this.actionMenuModel_ === null) { return ''; } const {index, origin} = this.actionMenuModel_; const {origins, hasInstalledPWA} = this.filteredList_[index]; if (origin) { const {isInstalled = false} = origins.find(o => o.origin === origin) || {}; const messageId = isInstalled ? 'siteSettingsOriginDeleteConfirmationInstalled' : 'siteSettingsOriginDeleteConfirmation'; return loadTimeData.substituteString( this.i18n(messageId), this.originRepresentation(origin)); } else { // Clear SiteGroup let messageId; if (hasInstalledPWA) { const multipleAppsInstalled = (this.filteredList_[index].origins || []) .filter(o => o.isInstalled) .length > 1; messageId = multipleAppsInstalled ? 'siteSettingsSiteGroupDeleteConfirmationInstalledPlural' : 'siteSettingsSiteGroupDeleteConfirmationInstalled'; } else { messageId = 'siteSettingsSiteGroupDeleteConfirmationNew'; } const displayName = this.actionMenuModel_.item.etldPlus1 || this.originRepresentation( this.actionMenuModel_.item.origins[0].origin); return loadTimeData.substituteString(this.i18n(messageId), displayName); } } /** * Get the appropriate label for the reset permissions confirmation * dialog, dependent on whether user is resetting permissions for an * origin or an entire SiteGroup. */ private getResetPermissionsLabel_(): string { if (this.actionMenuModel_ === null) { return ''; } if (this.actionMenuModel_.actionScope === 'origin') { return loadTimeData.substituteString( this.i18n('siteSettingsSiteResetConfirmation'), this.originRepresentation(this.actionMenuModel_.origin)); } return loadTimeData.substituteString( this.i18n('siteSettingsSiteGroupResetConfirmation'), this.actionMenuModel_.item.etldPlus1 || this.originRepresentation( this.actionMenuModel_.item.origins[0].origin)); } private getRemoveSiteTitle_(): string { if (this.actionMenuModel_ === null) { return ''; } const originScoped = this.actionMenuModel_.actionScope === 'origin'; const singleOriginSite = !originScoped && this.actionMenuModel_.item.origins.length === 1; const numInstalledApps = this.actionMenuModel_.item.origins .filter( o => !originScoped || this.actionMenuModel_!.origin === o.origin) .filter(o => o.isInstalled) .length; let messageId; if (originScoped || singleOriginSite) { if (numInstalledApps === 1) { messageId = 'siteSettingsRemoveSiteOriginAppDialogTitle'; } else { assert(numInstalledApps === 0); messageId = 'siteSettingsRemoveSiteOriginDialogTitle'; } } else { if (numInstalledApps > 1) { messageId = 'siteSettingsRemoveSiteGroupAppPluralDialogTitle'; } else if (numInstalledApps === 1) { messageId = 'siteSettingsRemoveSiteGroupAppDialogTitle'; } else { messageId = 'siteSettingsRemoveSiteGroupDialogTitle'; } } let displayOrigin; if (originScoped) { displayOrigin = this.actionMenuModel_.origin; } else if (singleOriginSite) { displayOrigin = this.actionMenuModel_.item.origins[0].origin; } else { displayOrigin = this.actionMenuModel_.item.etldPlus1; } return loadTimeData.substituteString( this.i18n(messageId), this.originRepresentation(displayOrigin)); } private getRemoveSiteLogoutBulletPoint_() { if (this.actionMenuModel_ === null) { return ''; } const originScoped = this.actionMenuModel_.actionScope === 'origin'; const singleOriginSite = !originScoped && this.actionMenuModel_.item.origins.length === 1; return originScoped || singleOriginSite ? this.i18n('siteSettingsRemoveSiteOriginLogout') : this.i18n('siteSettingsRemoveSiteGroupLogout'); } private showPermissionsBulletPoint_(): boolean { if (this.actionMenuModel_ === null) { return false; } // If the selected item if a site group, search all child origins for // permissions. If it is not, only look at the relevant origin. return this.actionMenuModel_.item.origins .filter( o => this.actionMenuModel_!.actionScope !== 'origin' || this.actionMenuModel_!.origin === o.origin) .some(o => o.hasPermissionSettings); } /** * Get the appropriate label for the clear all data confirmation * dialog, depending on whether or not any apps are installed. */ private getClearAllDataLabel_(): string { const anyAppsInstalled = this.filteredList_.some(g => g.hasInstalledPWA); const messageId = anyAppsInstalled ? 'siteSettingsClearAllStorageConfirmationInstalled' : 'siteSettingsClearAllStorageConfirmation'; return loadTimeData.substituteString( this.i18n(messageId), this.totalUsage_); } /** * Get the appropriate label for the clear data confirmation * dialog, depending on whether the user is clearing data for a * single origin or an entire site group. */ private getLogoutLabel_(): string { return this.actionMenuModel_!.actionScope === 'origin' ? this.i18n('siteSettingsSiteClearStorageSignOut') : this.i18n('siteSettingsSiteGroupDeleteSignOut'); } private recordUserAction_(scopes: Array<string>) { chrome.metricsPrivate.recordUserAction( ['AllSites', ...scopes].filter(Boolean).join('_')); } /** * Resets all permission settings for a single origin. */ private resetPermissionsForOrigin_(origin: string) { this.browserProxy.setOriginPermissions( origin, null, ContentSetting.DEFAULT); } /** * Resets all permissions for a single origin or all origins listed in * |siteGroup.origins|. */ private onResetSettings_(e: Event) { const {actionScope, index, origin} = this.actionMenuModel_!; const siteGroupToUpdate = this.filteredList_[index]; const updatedSiteGroup: SiteGroup = { etldPlus1: siteGroupToUpdate.etldPlus1, hasInstalledPWA: false, numCookies: siteGroupToUpdate.numCookies, origins: [], }; if (actionScope === 'origin') { this.browserProxy.recordAction(AllSitesAction2.RESET_ORIGIN_PERMISSIONS); this.recordUserAction_( [ALL_SITES_DIALOG.RESET_PERMISSIONS, 'Origin', 'Confirm']); this.resetPermissionsForOrigin_(origin); updatedSiteGroup.origins = siteGroupToUpdate.origins; const updatedOrigin = updatedSiteGroup.origins.find(o => o.origin === origin)!; updatedOrigin.hasPermissionSettings = false; if (updatedOrigin.numCookies <= 0 || updatedOrigin.usage <= 0) { updatedSiteGroup.origins = updatedSiteGroup.origins.filter(o => o.origin !== origin); } } else { // Reset permissions for entire site group this.browserProxy.recordAction( AllSitesAction2.RESET_SITE_GROUP_PERMISSIONS); this.recordUserAction_( [ALL_SITES_DIALOG.RESET_PERMISSIONS, 'SiteGroup', 'Confirm']); if (this.actionMenuModel_!.item.etldPlus1 !== siteGroupToUpdate.etldPlus1) { return; } siteGroupToUpdate.origins.forEach(originEntry => { this.resetPermissionsForOrigin_(originEntry.origin); if (originEntry.numCookies > 0 || originEntry.usage > 0) { originEntry.hasPermissionSettings = false; updatedSiteGroup.origins.push(originEntry); } }); } if (updatedSiteGroup.origins.length > 0) { this.set('filteredList_.' + index, updatedSiteGroup); } else if (siteGroupToUpdate.numCookies > 0) { // If there is no origin for this site group that has any data, // but the ETLD+1 has cookies in use, create a origin placeholder // for display purposes. const originPlaceHolder = { origin: `http://${siteGroupToUpdate.etldPlus1}/`, engagement: 0, usage: 0, numCookies: siteGroupToUpdate.numCookies, hasPermissionSettings: false, isInstalled: false, }; updatedSiteGroup.origins.push(originPlaceHolder); this.set('filteredList_.' + index, updatedSiteGroup); } else { this.splice('filteredList_', index, 1); } this.$.allSitesList.fire('iron-resize'); this.onCloseDialog_(e); } /** * Helper to remove data and cookies for an etldPlus1. * @param index The index of the target siteGroup in filteredList_ that should * be cleared. */ private clearDataForSiteGroupIndex_(index: number) { const siteGroupToUpdate = this.filteredList_[index]; const updatedSiteGroup: SiteGroup = { etldPlus1: siteGroupToUpdate.etldPlus1, hasInstalledPWA: siteGroupToUpdate.hasInstalledPWA, numCookies: 0, origins: [] }; this.browserProxy.clearEtldPlus1DataAndCookies(siteGroupToUpdate.etldPlus1); for (let i = 0; i < siteGroupToUpdate.origins.length; ++i) { const updatedOrigin = Object.assign({}, siteGroupToUpdate.origins[i]); if (updatedOrigin.hasPermissionSettings) { updatedOrigin.numCookies = 0; updatedOrigin.usage = 0; updatedSiteGroup.origins.push(updatedOrigin); } } this.updateSiteGroup_(index, updatedSiteGroup); } /** * Helper to remove data and cookies for an origin. * @param index The index of the target siteGroup in filteredList_ that should * be cleared. * @param origin The origin of the target origin that should be cleared. */ private clearDataForOrigin_(index: number, origin: string) { this.browserProxy.clearOriginDataAndCookies(this.toUrl(origin)!.href); const siteGroupToUpdate = this.filteredList_[index]; const updatedSiteGroup: SiteGroup = { etldPlus1: siteGroupToUpdate.etldPlus1, hasInstalledPWA: false, numCookies: 0, origins: [], }; const updatedOrigin = siteGroupToUpdate.origins.find(o => o.origin === origin)!; if (updatedOrigin.hasPermissionSettings) { updatedOrigin.numCookies = 0; updatedOrigin.usage = 0; updatedSiteGroup.origins = siteGroupToUpdate.origins; } else { updatedSiteGroup.origins = siteGroupToUpdate.origins.filter(o => o.origin !== origin); } updatedSiteGroup.hasInstalledPWA = updatedSiteGroup.origins.some(o => o.isInstalled); this.updateSiteGroup_(index, updatedSiteGroup); } /** * Updates the UI after permissions have been reset or data/cookies * have been cleared * @param index The index of the target siteGroup in filteredList_ that should * be updated. * @param updatedSiteGroup The SiteGroup object that represents the new state. */ private updateSiteGroup_(index: number, updatedSiteGroup: SiteGroup) { if (updatedSiteGroup.origins.length > 0) { this.set('filteredList_.' + index, updatedSiteGroup); } else { this.splice('filteredList_', index, 1); } this.siteGroupMap.delete(updatedSiteGroup.etldPlus1); } /** * Clear data and cookies for an etldPlus1. */ private onClearData_(e: Event) { const {index, actionScope, origin} = this.actionMenuModel_!; const scopes: Array<string> = [ALL_SITES_DIALOG.CLEAR_DATA]; if (actionScope === 'origin') { this.browserProxy.recordAction(AllSitesAction2.CLEAR_ORIGIN_DATA); const {origins} = this.filteredList_[index]; scopes.push('Origin'); const installed = (origins.find(o => o.origin === origin) || {}).isInstalled ? 'Installed' : ''; this.recordUserAction_([...scopes, installed, 'Confirm']); this.clearDataForOrigin_(index, origin); } else { this.browserProxy.recordAction(AllSitesAction2.CLEAR_SITE_GROUP_DATA); scopes.push('SiteGroup'); const {hasInstalledPWA} = this.filteredList_[index]; const installed = hasInstalledPWA ? 'Installed' : ''; this.recordUserAction_([...scopes, installed, 'Confirm']); this.clearDataForSiteGroupIndex_(index); } this.$.allSitesList.fire('iron-resize'); this.updateTotalUsage_(); this.onCloseDialog_(e); } /** * Clear data and cookies for all sites. */ private onClearAllData_(e: Event) { this.browserProxy.recordAction(AllSitesAction2.CLEAR_ALL_DATA); const scopes = [ALL_SITES_DIALOG.CLEAR_DATA, 'All']; const anyAppsInstalled = this.filteredList_.some(g => g.hasInstalledPWA); const installed = anyAppsInstalled ? 'Installed' : ''; this.recordUserAction_([...scopes, installed, 'Confirm']); for (let index = this.filteredList_.length - 1; index >= 0; index--) { this.clearDataForSiteGroupIndex_(index); } this.$.allSitesList.fire('iron-resize'); this.totalUsage_ = '0 B'; this.onCloseDialog_(e); } } customElements.define(AllSitesElement.is, AllSitesElement);
the_stack
import { sha256 } from "@core/lib/crypto/utils"; import { clearOrphanedEnvUpdatesProducer } from "@core/lib/client/blob"; import { getEnvironmentsQueuedForReencryptionIds } from "@core/lib/graph"; import { getBlobParamsEnvParentIds, getBlobParamsEnvironmentAndLocalIds, } from "@core/lib/blob"; import { v4 as uuid } from "uuid"; import { postApiAction } from "./lib/actions"; import { Client, Auth, Api, Blob } from "@core/types"; import * as R from "ramda"; import produce from "immer"; import { Reducer } from "redux"; import { getDefaultStore } from "./redux_store"; import { pick } from "@core/lib/utils/pick"; import { applyPatch } from "rfc6902"; import { log } from "@core/lib/utils/logger"; import { wait } from "@core/lib/utils/wait"; import { getState, waitForStateCondition } from "./lib/state"; import { clearRevokedOrOutdatedSessionPubkeys, processRevocationRequestsIfNeeded, processRootPubkeyReplacementsIfNeeded, verifyCurrentUser, verifyOrgKeyable, } from "./lib/trust"; import { keySetForGraphProposal, requiredEnvsForKeySet, fetchRequiredEnvs, encryptedKeyParamsForKeySet, } from "./lib/envs"; import { getAuth, getApiAuthParams, hasPendingConflicts, } from "@core/lib/client"; import { env } from "../../shared/src/env"; import { inspect } from "util"; const OUTDATED_GRAPH_REFRESH_MAX_JITTER_MS = 200; const actions: { [type: string]: Client.ActionParams; } = {}; export const clientAction = < ActionType extends Client.Action.EnvkeyAction = Client.Action.EnvkeyAction, SuccessType = any, FailureType = Client.ClientError, DispatchContextType = any, RootActionType extends Client.Action.EnvkeyAction = ActionType >( params: Client.ActionParams< ActionType, SuccessType, FailureType, DispatchContextType, RootActionType > ) => { if (actions[params.actionType]) { throw new Error("A client action with this type was already defined"); } actions[params.actionType] = params as Client.ActionParams; }, getActionParams = (type: Client.Action.EnvkeyAction["type"]) => { const params = actions[type as string]; if (!params) { throw new TypeError( `Unexpected Client Action when fetching Action Params! This probably means a configuration error has occurred.` ); } return params; }, dispatch = async < ActionType extends Client.Action.EnvkeyAction, DispatchContextType = any >( action: Client.Action.DispatchAction<ActionType>, context: Client.Context<DispatchContextType> ): Promise<Client.DispatchResult> => { const store = context.store ?? getDefaultStore(), actionParams = actions[action.type], tempId = uuid(); let accountState = getState(store, context); if (env.ENVKEY_CORE_DISPATCH_DEBUG_ENABLED === "1") { log(`debug:dispatch(${inspect(action, { depth: 2 })})`); } if (!actionParams) { log( "WARNING: no actionParams for action - did you forget to add a clientAction<>?", action ); } if ( actionParams && "serialAction" in actionParams && actionParams.serialAction && !context.skipWaitForSerialAction && accountState.isDispatchingSerialAction ) { await waitForStateCondition( store, context, (state) => !state.isDispatchingSerialAction ); } const handleSuccess = getHandleSuccess(actionParams, action, store, tempId), handleFailure = getHandleFailure(actionParams, action, store, tempId); if (actionParams.type == "clientAction") { const clientAction = action as Client.Action.ClientAction; dispatchStore<DispatchContextType>(clientAction, context, tempId, store); accountState = getState(store, context); if (actionParams.handler) { await (actionParams.handler as Client.ActionHandler)( accountState, clientAction, context ); } return { success: true, resultAction: clientAction, state: getState(store, context), }; } else if (actionParams.type == "asyncClientAction") { const clientAction = action as Client.Action.ClientAction; dispatchStore<DispatchContextType>(clientAction, context, tempId, store); accountState = getState(store, context); const dispatchSuccess: Parameters<Client.AsyncActionHandler>[2]["dispatchSuccess"] = async (successPayload, handlerOpts) => { try { const handleSuccessRes = await handleSuccess( clientAction, successPayload, handlerOpts ); return handleSuccessRes; } catch (error) { return handleFailure(clientAction, error, handlerOpts); } }, dispatchFailure: Parameters<Client.AsyncActionHandler>[2]["dispatchFailure"] = async (failurePayload, handlerOpts) => { return handleFailure(clientAction, failurePayload, handlerOpts); }; if (actionParams.apiActionCreator) { if (actionParams.bulkApiDispatcher) { let error: Client.ClientError | Error | undefined; const now = Date.now(), clientParams = (action as any).payload as any[], apiActions = await Promise.all( clientParams.map((params) => actionParams.apiActionCreator!(params, accountState, context) ) ).then((a) => a.map(R.prop("action"))), fullKeySet = apiActions .map((apiAction) => { const apiActionParams = actions[apiAction.type]; if ( !apiActionParams || !("graphProposer" in apiActionParams) || !apiActionParams.graphProposer ) { return { type: "keySet" } as Blob.KeySet; } return keySetForGraphProposal( accountState.graph, now, (graphDraft) => { if ( !apiActionParams || !("graphProposer" in apiActionParams) || !apiActionParams.graphProposer ) { return; } apiActionParams.graphProposer( apiAction as Api.Action.RequestAction, accountState, context )(graphDraft); }, apiActionParams.encryptedKeysScopeFn?.( accountState.graph, apiAction as Api.Action.RequestAction ) ); }) .reduce(R.mergeDeepRight, { type: "keySet" } as Blob.KeySet), { requiredEnvs, requiredChangesets } = requiredEnvsForKeySet( accountState.graph, fullKeySet ), fetchRes = await fetchRequiredEnvs( accountState, requiredEnvs, requiredChangesets, context ); let stateWithFetched: Client.State | undefined; if (fetchRes) { if (fetchRes.success) { stateWithFetched = fetchRes.state; } else { error = (fetchRes.resultAction as Client.Action.FailureAction) .payload; } } else { stateWithFetched = accountState; } if (!error) { try { let promises: Promise<Api.Action.RequestAction>[] = []; for (let apiAction of apiActions) { const apiActionParams = actions[apiAction.type]; if ( !apiActionParams || !("graphProposer" in apiActionParams) || !apiActionParams.graphProposer ) { promises.push( Promise.resolve(apiAction as Api.Action.RequestAction) ); continue; } const graphProducer = apiActionParams.graphProposer( apiAction as Api.Action.RequestAction, stateWithFetched!, context ), toSet = keySetForGraphProposal( stateWithFetched!.graph, now, graphProducer, apiActionParams.encryptedKeysScopeFn?.( accountState.graph, apiAction as Api.Action.RequestAction ) ); promises.push( encryptedKeyParamsForKeySet({ state: { ...stateWithFetched!, graph: produce(stateWithFetched!.graph, graphProducer), }, context, toSet, }).then((envParams) => { const res = { ...apiAction, payload: { ...apiAction.payload, ...envParams, }, } as Api.Action.RequestAction; return res; }) ); } const withEnvs = await Promise.all(promises); const res = await dispatch<Api.Action.BulkGraphAction>( { type: Api.ActionType.BULK_GRAPH_ACTION, payload: withEnvs.map((apiAction) => ({ ...apiAction, meta: { loggableType: "orgAction", graphUpdatedAt: stateWithFetched!.graphUpdatedAt, }, })) as Api.Action.BulkGraphAction["payload"], }, { ...context, rootClientAction: action as Client.Action.ClientAction, } ); if (res.success && res.retriedWithUpdatedGraph) { return res; } if (res.success) { const successPayload = actionParams.apiSuccessPayloadCreator ? await actionParams.apiSuccessPayloadCreator(res) : (res.resultAction as any)?.payload; return dispatchSuccess(successPayload, context); } else { return dispatchFailure( (res.resultAction as any)?.payload, context ); } } catch (err) { error = err; } } if (error) { const failurePayload = error instanceof Error ? { type: <const>"clientError", error, } : error; return dispatchFailure(failurePayload, context); } } else { const { action: apiAction, dispatchContext } = await actionParams.apiActionCreator( (action as Api.Action.RequestAction).payload, accountState, context ), apiRes = await dispatch(apiAction as Api.Action.RequestAction, { ...context, ...(dispatchContext ? { dispatchContext } : {}), rootClientAction: action as Client.Action.ClientAction, }); if (apiRes.success && apiRes.retriedWithUpdatedGraph) { return apiRes; } if (apiRes.success) { const successPayload = actionParams.apiSuccessPayloadCreator ? await actionParams.apiSuccessPayloadCreator( apiRes, dispatchContext ) : (apiRes.resultAction as any).payload; return dispatchSuccess(successPayload, context); } else { const failureAction = apiRes.resultAction as Client.Action.FailureAction; return dispatchFailure( failureAction.payload as Api.Net.ErrorResult, context ); } } } else if (actionParams.handler) { const handlerRes = await ( actionParams.handler as Client.AsyncActionHandler )(accountState, clientAction, { context, dispatchSuccess, dispatchFailure, }); return handlerRes; } else { return { success: true, resultAction: clientAction, state: getState(store, context), }; } } else if (actionParams.type == "apiRequestAction") { if (actionParams.bulkDispatchOnly) { throw new Error( "Cannot be dispatched directly, only as part of BULK_GRAPH_ACTION" ); } if (!context) { throw new Error("clientContext required for apiRequestAction"); } accountState = getState(store, context); let apiAuthParams: Auth.ApiAuthParams | undefined = context.auth, accountIdOrCliKey = context.accountIdOrCliKey, accountAuth = getAuth(accountState, accountIdOrCliKey); const hostUrl = context.hostUrl ?? accountAuth?.hostUrl; if (actionParams.authenticated && !apiAuthParams) { if (!accountAuth) { log("CORE PROC HANDLER - Action requires authentication err.", { actionParams, apiAuthParams, }); throw new Error("Action requires authentication."); } apiAuthParams = getApiAuthParams(accountAuth); } const meta = { ...pick( ["loggableType", "loggableType2", "loggableType3", "loggableType4"], actionParams ), auth: apiAuthParams, client: context.client, graphUpdatedAt: actionParams.graphAction ? accountState.graphUpdatedAt : undefined, } as Api.Action.RequestAction["meta"]; let payload = ( action as Client.Action.DispatchAction<Api.Action.RequestAction> ).payload, requestAction = { ...(action as Client.Action.DispatchAction<Api.Action.RequestAction>), payload, meta, } as Api.Action.RequestAction; dispatchStore<DispatchContextType>(requestAction, context, tempId, store); accountState = getState(store, context); (requestAction.meta as any).graphUpdatedAt = accountState.graphUpdatedAt!; let error: Client.ClientError | Error | undefined; const now = Date.now(); if (actionParams.graphProposer) { const graphProducer = actionParams.graphProposer( action as Api.Action.RequestAction, accountState, context ), proposedGraph = produce(accountState.graph, graphProducer), toSet = keySetForGraphProposal( accountState.graph, now, graphProducer, actionParams.encryptedKeysScopeFn?.( accountState.graph, action as Api.Action.RequestAction ) ); let stateWithFetched: Client.State | undefined; const { requiredEnvs, requiredChangesets } = requiredEnvsForKeySet( accountState.graph, toSet ), fetchRes = await fetchRequiredEnvs( accountState, requiredEnvs, requiredChangesets, context ); if (fetchRes) { if (fetchRes.success) { stateWithFetched = fetchRes.state; } else { error = (fetchRes.resultAction as Client.Action.FailureAction) .payload; } } else { stateWithFetched = accountState; } if (stateWithFetched && !error) { const envParams = await encryptedKeyParamsForKeySet({ state: { ...stateWithFetched!, graph: proposedGraph, }, context, toSet, }); payload = { ...payload, ...envParams }; } } requestAction = { ...requestAction, payload } as Api.Action.RequestAction; if (!error) { let res: Api.Net.ApiResult; const sanitizedRequestAction = R.evolve( { meta: R.omit(["clientContext", "dispatchContext", "hostUrl"]), }, requestAction ) as Api.Action.RequestAction; try { res = await postApiAction( sanitizedRequestAction, hostUrl, context.ipTestOverride ); const handleSuccessRes = await handleSuccess( requestAction, res, context ); return handleSuccessRes; } catch (err) { error = err; } } if (error) { const nodeFetchErr = error as Client.FetchError; const graphOutdated = nodeFetchErr.error?.message == "client graph outdated"; if (nodeFetchErr.error?.code == 400 && graphOutdated) { const delay = Math.random() * OUTDATED_GRAPH_REFRESH_MAX_JITTER_MS; await wait(delay); let refreshAction: Client.Action.EnvkeyAction | undefined; if (actionParams.refreshActionCreator) { refreshAction = actionParams.refreshActionCreator( context.rootClientAction ?? requestAction ); } else if (accountAuth && accountAuth.type == "clientUserAuth") { refreshAction = { type: Client.ActionType.GET_SESSION, payload: { skipWaitForReencryption: action.type == Api.ActionType.REENCRYPT_ENVS || undefined, }, }; } else if (accountAuth && accountAuth.type == "clientCliAuth") { refreshAction = { type: Client.ActionType.AUTHENTICATE_CLI_KEY, payload: { cliKey: context.accountIdOrCliKey! }, }; } if (!refreshAction) { return handleFailure(requestAction, error, context); } const refreshRes = await dispatch(refreshAction, context); if (!refreshRes.success) { return handleFailure( requestAction, (refreshRes.resultAction as any).payload as Api.Net.ErrorResult, context ); } if ( action.type == Api.ActionType.UPDATE_ENVS || action.type == Api.ActionType.REENCRYPT_ENVS ) { const blobs = ( action as Api.Action.RequestActions[ | "UpdateEnvs" | "ReencryptEnvs"] ).payload.blobs; const envParentIds = getBlobParamsEnvParentIds(blobs), environmentAndLocalIds = getBlobParamsEnvironmentAndLocalIds(blobs); try { await fetchRequiredEnvs( refreshRes.state, envParentIds, new Set<string>(), context, action.type == Api.ActionType.REENCRYPT_ENVS || undefined ); // If there are conflicts after fetching outdated envs, // the user must confirm before submitting env update. // So for now just pass through outdated error. if ( hasPendingConflicts( getState(store, context), undefined, Array.from(environmentAndLocalIds) ) ) { return handleFailure(requestAction, error, context); } } catch (err) { return handleFailure(requestAction, err, context); } } let promise: Promise<Client.DispatchResult>; if (context.rootClientAction) { promise = dispatch(context.rootClientAction, { ...context, skipWaitForSerialAction: true, }); } else { promise = dispatch(action, { ...context, skipWaitForSerialAction: true, }); } return promise.then((res) => ({ ...res, retriedWithUpdatedGraph: true, })); } return handleFailure(requestAction, error, context); } } log("ActionParams type not handled", { actionParams, action }); throw new Error("ActionParams type not handled"); }, clientReducer: () => Reducer< Client.ProcState, Client.ActionTypeWithContextMeta<Client.Action.EnvkeyAction> > = () => { const reducers = R.flatten<any>( Object.values(actions) .map((params) => { const reducers: Reducer< Client.ProcState, Client.ActionTypeWithContextMeta<Client.Action.EnvkeyAction> >[] = []; for (let k of <const>[ "stateProducer", "successStateProducer", "failureStateProducer", "endStateProducer", ]) { if ((params as any)[k]) { const stateProducer = (params as any)[k] as Client.StateProducer; reducers.push( ( procState: Client.ProcState = Client.defaultProcState, action: Client.ActionTypeWithContextMeta<Client.Action.EnvkeyAction> ) => { const isStartAction = action.type === params.actionType; const isSuccessAction = action.type == params.actionType + "_SUCCESS"; const isFailureAction = action.type == params.actionType + "_FAILURE"; if ( (k == "stateProducer" && isStartAction) || (k == "successStateProducer" && isSuccessAction) || (k == "failureStateProducer" && isFailureAction) || (k == "endStateProducer" && (isSuccessAction || isFailureAction)) ) { const clientState = getState(procState, action.meta); const updated = produce(clientState, (draft) => stateProducer(draft, action) ), accountId = action.meta.accountIdOrCliKey; const res = { ...procState, ...pick(Client.CLIENT_PROC_STATE_KEYS, updated), clientStates: { ...procState.clientStates, [action.meta.clientId]: pick( Client.CLIENT_STATE_KEYS, updated ), }, accountStates: accountId ? { ...procState.accountStates, [accountId]: pick( Client.ACCOUNT_STATE_KEYS, updated ), } : procState.accountStates, }; return res; } return procState; } ); } } if ("procStateProducer" in params) { reducers.push( ( procState: Client.ProcState = Client.defaultProcState, action: Client.ActionTypeWithContextMeta<Client.Action.EnvkeyAction> ) => { if (action.type === params.actionType) { return produce(procState, (draft) => params.procStateProducer!(draft, action) ); } else { return procState; } } ); } if (params.type == "apiRequestAction" && params.graphAction) { reducers.push( ( procState: Client.ProcState = Client.defaultProcState, action: Client.ActionTypeWithContextMeta<Client.Action.EnvkeyAction> ) => { if ( action.type == params.actionType + "_SUCCESS" && action.meta.accountIdOrCliKey ) { const accountIdOrCliKey = action.meta.accountIdOrCliKey; const payload = (action as Api.Action.RequestAction) .payload as Api.Net.ApiResult, accountState = getState(procState, action.meta); let updatedAccountState: | Client.PartialAccountState | undefined; let graphUpdated = false; if ("graph" in payload) { graphUpdated = true; updatedAccountState = { ...accountState, graph: payload.graph, graphUpdatedAt: payload.graphUpdatedAt, }; } else if ("diffs" in payload) { graphUpdated = true; const graphWithDiffs = produce( accountState.graph, (graphDraft) => { applyPatch(graphDraft, payload.diffs); } ); updatedAccountState = { ...accountState, graph: graphWithDiffs, graphUpdatedAt: payload.graphUpdatedAt, }; } if (graphUpdated && updatedAccountState) { const auth = procState.orgUserAccounts[accountIdOrCliKey] ?? procState.cliKeyAccounts[sha256(accountIdOrCliKey)]; if (auth) { const { userId: currentUserId } = auth; // clear out updates for any environments that no longer exist or that user is no longer permitted to write to updatedAccountState = produce( updatedAccountState, (draft) => clearOrphanedEnvUpdatesProducer(draft, currentUserId) ); } } const res = updatedAccountState && accountIdOrCliKey ? { ...procState, accountStates: { ...procState.accountStates, [accountIdOrCliKey]: updatedAccountState, }, } : procState; return res; } return procState; } ); } // store throttling error so we can notify user if (params.type == "apiRequestAction") { reducers.push( ( procState: Client.ProcState = Client.defaultProcState, action: Client.ActionTypeWithContextMeta<Client.Action.EnvkeyAction> ) => { if ( action.meta?.clientId && procState.clientStates[action.meta.clientId] && action.type == params.actionType + "_FAILURE" ) { const resAction = (<any>action) as { payload: Client.FetchError; }; if ([413, 429].includes(resAction.payload.error.code)) { return { ...procState, clientStates: { ...procState.clientStates, [action.meta.clientId]: { ...procState.clientStates[action.meta.clientId]!, throttleError: resAction.payload, }, }, }; } } return procState; } ); } if ("serialAction" in params && params.serialAction) { reducers.push( ( procState: Client.ProcState = Client.defaultProcState, action: Client.ActionTypeWithContextMeta<Client.Action.EnvkeyAction> ) => { const isStartAction = action.type === params.actionType; const isSuccessAction = action.type == params.actionType + "_SUCCESS"; const isFailureAction = action.type == params.actionType + "_FAILURE"; if (isStartAction || isSuccessAction || isFailureAction) { const clientState = getState(procState, action.meta); const updated = produce(clientState, (draft) => { if (isStartAction) { draft.isDispatchingSerialAction = true; } else if (isSuccessAction || isFailureAction) { delete draft.isDispatchingSerialAction; } }), accountId = action.meta.accountIdOrCliKey; const res = { ...procState, accountStates: accountId ? { ...procState.accountStates, [accountId]: pick(Client.ACCOUNT_STATE_KEYS, updated), } : procState.accountStates, }; return res; } return procState; } ); } reducers.push( ( procState: Client.ProcState = Client.defaultProcState, action: Client.ActionTypeWithContextMeta<Client.Action.EnvkeyAction> ) => { if ( action.meta && action.meta.accountIdOrCliKey && action.meta.clientId && action.meta.clientId != "core" && procState.accountStates[action.meta.accountIdOrCliKey] ) { return { ...procState, accountStates: { ...procState.accountStates, [action.meta.accountIdOrCliKey]: { ...procState.accountStates[ action.meta.accountIdOrCliKey ]!, accountLastActiveAt: Date.now(), }, }, }; } return procState; } ); reducers.push( ( procState: Client.ProcState = Client.defaultProcState, action: Client.ActionTypeWithContextMeta<Client.Action.EnvkeyAction> ) => action.type.startsWith("envkey/client/") && action.type != Client.ActionType.MERGE_PERSISTED ? { ...procState, lastActiveAt: Date.now(), } : procState ); return reducers; }) .filter(Boolean) ); return ( state: Client.ProcState = Client.defaultProcState, action: Client.ActionTypeWithContextMeta<Client.Action.EnvkeyAction> ) => { let reduced = state; for (let reducer of reducers) { reduced = reducer(reduced, action); } return reduced; }; }, dispatchStore = <DispatchContextType>( action: | Client.Action.EnvkeyAction | Client.Action.SuccessAction | Client.Action.FailureAction, contextMeta: Client.Context<DispatchContextType> | undefined, tempId: string, storeArg?: Client.ReduxStore ) => { const reduxAction = { ...action, meta: { ...("meta" in action ? action.meta : {}), ...(contextMeta ?? {}), tempId, } as any, }; const store = storeArg ?? getDefaultStore(); // log(reduxAction.type); // log("dispatching " + reduxAction.type); // const start = Date.now(); store.dispatch(reduxAction); // log( // "dispatched " + reduxAction.type + ": " + (Date.now() - start).toString() // ); }; const getHandleSuccess = <ActionType extends Client.Action.EnvkeyAction, DispatchContextType = any>( actionParams: Client.ActionParams, action: Client.Action.DispatchAction<ActionType>, store: Client.ReduxStore, tempId: string ) => async ( rootAction: Client.Action.EnvkeyAction, payload: any, apiSuccessContext: Client.Context ) => { let successAccountId: string | undefined; if ( "successAccountIdFn" in actionParams && actionParams.successAccountIdFn ) { successAccountId = actionParams.successAccountIdFn(payload); } const successAction = { type: action.type + "_SUCCESS", meta: { rootAction }, payload, }, contextParams = successAccountId ? { ...apiSuccessContext, accountIdOrCliKey: successAccountId, } : apiSuccessContext; dispatchStore<DispatchContextType>( successAction, contextParams, tempId, store ); let updatedState = getState(store, contextParams); // clear any newly revoked session keys if ( updatedState.trustedRoot && !R.isEmpty(updatedState.trustedSessionPubkeys) ) { clearRevokedOrOutdatedSessionPubkeys(updatedState, contextParams); updatedState = getState(store, contextParams); } if ("verifyCurrentUser" in actionParams && actionParams.verifyCurrentUser) { const res = await verifyCurrentUser(updatedState, contextParams); if (res) { updatedState = getState(store, contextParams); } else { throw new Error("Couldn't verify current user"); } } else { // process queued root pubkey replacements for successful api actions if ( actionParams.type == "apiRequestAction" && !actionParams.skipProcessRootPubkeyReplacements ) { await processRootPubkeyReplacementsIfNeeded( updatedState, contextParams, true ); updatedState = getState(store, contextParams); } if (updatedState.trustedRoot && contextParams.accountIdOrCliKey) { // ensure current user's trust chain is still valid const auth = getAuth(updatedState, contextParams.accountIdOrCliKey); if (auth && auth.privkey) { const res = await verifyOrgKeyable( updatedState, "deviceId" in auth ? auth.deviceId : auth.userId, contextParams ); if (res) { updatedState = getState(store, contextParams); } else { throw new Error("Updated graph broke current user's trust chain"); } } } } if ("successHandler" in actionParams && actionParams.successHandler) { await (actionParams.successHandler as Client.SuccessHandler)( updatedState, rootAction, payload, contextParams ); updatedState = getState(store, contextParams); } const auth = getAuth(updatedState, contextParams.accountIdOrCliKey); // clear any blobs orphaned by a graph action // runs in background on worker thread if ( auth && auth.privkey && actionParams.type == "apiRequestAction" && actionParams.graphAction ) { dispatch( { type: Client.ActionType.CLEAR_ORPHANED_BLOBS, }, contextParams ); } // reencrypt any environments that require it let toReencryptIds: string[] | undefined; if (auth) { toReencryptIds = getEnvironmentsQueuedForReencryptionIds( updatedState.graph, auth.userId ); } if ( auth && auth.privkey && actionParams.type == "apiRequestAction" && !actionParams.skipReencryptPermitted && !updatedState.isReencrypting && toReencryptIds && toReencryptIds.length > 0 ) { dispatch( { type: Client.ActionType.REENCRYPT_PERMITTED_LOOP, }, contextParams ); updatedState = getState(store, contextParams); } else if ( auth && auth.privkey && actionParams.type == "apiRequestAction" && !actionParams.skipProcessRevocationRequests && !contextParams.skipProcessRevocationRequests && !(toReencryptIds && toReencryptIds.length > 0) ) { // trigger processing any queued revocation requests const revocationRes = await processRevocationRequestsIfNeeded( updatedState, contextParams ); if (revocationRes && !revocationRes.success) { return revocationRes; } updatedState = getState(store, contextParams); } return { success: true, resultAction: successAction, state: updatedState, }; }; const getHandleFailure = <ActionType extends Client.Action.EnvkeyAction, DispatchContextType = any>( actionParams: Client.ActionParams, action: Client.Action.DispatchAction<ActionType>, store: Client.ReduxStore, tempId: string ) => async ( rootAction: Client.Action.EnvkeyAction, error: Error | Client.ClientError, failureContext: Client.Context ) => { const failurePayload = error instanceof Error ? { type: <const>"clientError", error, } : error, failureAction = { type: action.type + "_FAILURE", meta: { rootAction: rootAction }, payload: failurePayload, }; // log("", failurePayload); dispatchStore<DispatchContextType>( failureAction, failureContext, tempId, store ); const updatedState = getState(store, failureContext); if ("failureHandler" in actionParams && actionParams.failureHandler) { await (actionParams.failureHandler as Client.FailureHandler)( updatedState, rootAction, failurePayload, failureContext ); } return { success: false, resultAction: failureAction, state: updatedState, }; }; export type DispatchFn = typeof dispatch;
the_stack
// TODO events and async // Next available error: TD215: module TDev.AST { export class TypeResolver extends NodeVisitor { constructor(public parent:TypeChecker) { super() } private fixupKind(n:AstNode, k:Kind) { if (k instanceof UnresolvedKind && this.parent.topApp) { var k0 = this.parent.topApp.getDefinedKinds().filter(n => n.getName() == k.getName())[0] if (k0) k = k0 } if (k.getRoot() != k) { var pk = <ParametricKind>k var parms = pk.parameters.map(kk => this.fixupKind(n, kk)) if (parms.some((kk, i) => pk.parameters[i] != kk)) { k = pk.createInstance(parms) } } if (k.isError()) { if (k instanceof LibraryRefAbstractKind || k.getRecord() instanceof LibraryRecordDef) { if (k.parentLibrary().hasAbstractKind(k.getName())) { k = k.parentLibrary().getAbstractKind(k.getName()) } } } if (k.isError()) { this.parent.errorCount++; n.setError(lf("TD121: cannot find type {0}", k.toString())); } return k; } visitGlobalDef(node:GlobalDef) { node._kind = this.fixupKind(node, node.getKind()); } visitAction(node:Action) { var fixupLocal = (a:ActionParameter) => { var l = a.local; l._kind = this.fixupKind(node, l.getKind()); } if (node.modelParameter) fixupLocal(node.modelParameter); node.getInParameters().forEach(fixupLocal); node.getOutParameters().forEach(fixupLocal); } visitBlock(b:Block) { this.visitChildren(b); } visitRecordDef(r:RecordDef) { this.visitChildren(r); } visitRecordField(node:RecordField) { node.setKind(this.fixupKind(node, node.dataKind)) } visitApp(a:App) { this.visitChildren(a); } } export enum ActionSection { Normal, Init, Display, Lambda, } export interface InlineError { scope:string; message:string; line:string; lineNo:number; coremsg:string; hints:string; } export class TypeChecker extends NodeVisitor { private typeResolver:TypeResolver; private isTopExpr = false; static lastStoreLocalsAt:ExprHolder; static lintThumb : (a:Action, asm:string) => InlineError[]; constructor() { super() this.typeResolver = new TypeResolver(this); } static tcAction(a:Action, first:boolean, storeAt:ExprHolder = null) { var ctx = new TypeChecker(); ctx.topApp = Script; ctx.storeLocalsAt = storeAt; TypeChecker.lastStoreLocalsAt = storeAt; if (first) { TypeChecker.iterTokenUsage((t:TokenUsage) => { t.localCount = 0 }); ctx.countToUpdate = 1; } ctx.dispatch(a); } static tcFragment(e: ExprHolder) { var ctx = new TypeChecker(); ctx.topApp = Script; ctx.storeLocalsAt = e; TypeChecker.lastStoreLocalsAt = e; var es = mkExprStmt(e); ctx.dispatch(es); } static tcScript(a:App, ignoreLibErrors = false, isTop = false, depth = 0) : number { var ctx = new TypeChecker(); ctx.topApp = a; a.imports = new AppImports(); var prev = Script; ctx.storeLocalsAt = TypeChecker.lastStoreLocalsAt; ctx.ignoreLibErrors = ignoreLibErrors; try { setGlobalScript(a); ctx.typecheckLibraries(a); // this may be too often a.libNamespaceCache.recompute(); ctx.typeResolver.dispatch(a); if (isTop) { TypeChecker.iterTokenUsage((t:TokenUsage) => { t.globalCount = 0 }); ctx.countToUpdate = 2; } ctx.dispatch(a); a.addFeatures(LanguageFeature.Refs); // refs is fixed after one round if (ctx.numFixes > 0 && depth < 5) { // retry return TypeChecker.tcScript(a, ignoreLibErrors, isTop, depth + 1); } a.addFeatures(LanguageFeature.Current); a.things.forEach((t) => { if (ignoreLibErrors && t instanceof LibraryRef) { (<LibraryRef>t)._hasErrors = false return; } if (t.hasErrors()) ctx.errorCount++; }); return ctx.errorCount; } finally { setGlobalScript(prev); // rebinds "data", "code" etc. } } static tcApp(a:App) : number { return TypeChecker.tcScript(a, false, true); } static iterTokenUsage(f:(t:TokenUsage)=>void) { TDev.api.getKinds().forEach((k:Kind) => { if (!!k.singleton) { f(k.singleton.usage); } k.listProperties().forEach((p:IProperty) => { f(p.getUsage()); }); }); TDev.api.getKind("code").singleton.usage.apiFreq = TDev.Script.actions().length > 0 ? 1.0 : 0.0; TDev.api.getKind("data").singleton.usage.apiFreq = TDev.Script.variables().length > 0 ? 0.9 : 0.0; TDev.api.getKind("art").singleton.usage.apiFreq = TDev.Script.resources().length > 0 ? 0.8 : 0.0; api.core.allStmtUsage().forEach(f); } static resolveKind(k:Kind) { var ctx = new TypeChecker(); ctx.topApp = Script; var a = new GlobalDef() a._kind = k ctx.typeResolver.dispatch(a); return a._kind } public topApp:App; private currentAction:Action; private currentAnyAction:Stmt; private seenAwait = false; private numFixes = 0; private nothingLocals:LocalDef[] = []; private localScopes: LocalDef[][] = [[]]; private readOnlyLocals:LocalDef[] = []; private outsideScopeLocals:LocalDef[] = []; private invisibleLocals:LocalDef[] = []; private writtenLocals:LocalDef[] = []; private readLocals:LocalDef[] = []; private currLoop:Stmt; private inAtomic = false; private inShim = false; private actionSection = ActionSection.Normal; private pageInit:Block; private pageDisplay:Block; private saveFixes = 0; private outLocals:LocalDef[] = []; private reportedUnassigned = false; private allLocals :LocalDef[] = []; private recentErrors: string[] = []; private lastStmt:Stmt; public errorCount = 0; public countToUpdate = 0; private timestamp = 1; private seenCurrent = false; private missingLocals:LocalDef[] = []; private errorLevel = 0; private hintsToFlush:string[] = []; private topInline:InlineActions; public storeLocalsAt:ExprHolder = null; public ignoreLibErrors = false; private typeHint:Kind; // TSBUG should be private public markError(expr:Token, msg:string) { if (!!expr.getError()) return; if (this.errorLevel > 0) return; expr.setError(msg); this.recentErrors.push(msg); this.errorCount++; var loc = (<Expr>expr).loc; if (loc) { var i = loc.beg; var e = i + loc.len; while (i < e) { var t = loc.tokens[i] if (!t.getError()) t.setError(msg); i++; } } } private markHolderError(eh:ExprHolder, msg:string) { if (!!eh.getError()) return; if (!msg) return; if (this.errorLevel > 0) return; this.errorCount++; eh.setError(msg); } private setNodeError(n:AstNode, msg:string) { if (this.errorLevel == 0) { this.errorCount++; n.setError(msg) } } private typeCheck(expr:Stmt) { expr.clearError(); expr._kind = null; this.dispatch(expr); } private snapshotLocals() { var locs = []; this.localScopes.forEach((l) => { locs.pushRange(l); }); return locs; } public tcTokens(toks:Token[]) { var e = new ExprHolder(); e.tokens = toks this.expect(e, null, "void"); } private expectsMessage(whoExpects:string, tp:string) { switch (whoExpects) { case "if": return lf("TD118: 'if' condition wants {1:a}", whoExpects, tp); case "where": return lf("TD128: 'where' condition wants {1:a}", whoExpects, tp); case "while": return lf("TD129: 'while' condition wants {1:a}", whoExpects, tp); case "for": return lf("TD130: bound of 'for' wants {1:a}", whoExpects, tp); case "optional": return lf("TD186: this optional parameter wants {1:a}", whoExpects, tp); case "return": return lf("TD204: 'return' value wants {1:a}", whoExpects, tp); default: Util.die() } } private expect(expr:ExprHolder, tp:Kind, whoExpects:string) { this.hintsToFlush = []; if (expr.tokens.length == 1) { if (expr.isPlaceholder()) expr.tokens = []; } if (this.topApp.featureMissing(LanguageFeature.AllAsync) && expr.tokens.some(t => t.getOperator() == 'await')) { expr.tokens = expr.tokens.filter(t => t.getOperator() != 'await') this.numFixes++; } expr.clearError(); expr.tokens.forEach((t, i) => { if (!(t instanceof ThingRef)) return var tt = <ThingRef>t if (tt.forceLocal) return if (!(expr.tokens[i + 1] instanceof PropertyRef)) return var pp = <PropertyRef>expr.tokens[i + 1] var key = tt.data + "->" + pp.data if (AST.crossKindRenames.hasOwnProperty(key)) { var m = /(.*)->(.*)/.exec(AST.crossKindRenames[key]) tt.data = m[1] pp.data = m[2] } }) var parsed = ExprParser.parse1(expr.tokens); parsed.clearError(); parsed._kind = null; expr.parsed = parsed; this.seenAwait = false; this.recentErrors = []; var parseErr:Token = expr.tokens.filter((n:Token) => n.getError() != null)[0]; var prevLocals = this.allLocals.length; this.saveFixes = expr == this.storeLocalsAt ? 1 : 0; if (!parseErr) { this.isTopExpr = (whoExpects == "void"); this.dispatch(parsed); expr.hasFix = this.saveFixes > 1 } else { expr.hasFix = true if (this.errorLevel == 0) this.errorCount++; this.errorLevel++; this.dispatch(parsed); this.errorLevel--; } this.saveFixes = 0 expr._kind = expr.parsed.getKind(); var seenAssign = false; var prevTok = null var tokErr:Token = null expr.tokens.forEach((t) => { if (t instanceof PropertyRef) { var p = <PropertyRef>t; if (!p.prop) p.prop = p.getOrMakeProp(); if (prevTok && prevTok.getThing() instanceof LocalDef && prevTok.getThing().getName() == modelSymbol && AST.mkFakeCall(p).referencedRecordField()) p.skipArrow = true; else if (p.skipArrow) p.skipArrow = false; } else if (t instanceof ThingRef) { var tt = <ThingRef>t; if (tt._lastTypechecker != this) this.dispatch(tt); } else if (t.getOperator() == ":=") { seenAssign = true; } else if (t instanceof Literal) { if (!t._kind) { this.dispatch(t); } } prevTok = t if (!tokErr && t.getError() != null) tokErr = t }) if (whoExpects == "void") { if (seenAssign && (this.allLocals.length == prevLocals || !this.allLocals.slice(prevLocals).some(l => l.isRegular))) seenAssign = false; expr.looksLikeVarDef = seenAssign; } var errNode:AstNode = parseErr || tokErr || expr.parsed; this.markHolderError(expr, errNode.getError()); this.markHolderError(expr, this.recentErrors[0]); expr.isAwait = this.seenAwait; if (expr == this.storeLocalsAt) { this.seenCurrent = true; expr.locals = this.snapshotLocals(); } else { expr.locals = null; } if (!Util.check(expr.getKind() != null, "expr type unset")) { expr._kind = api.core.Unknown } if (!expr.getError() && tp != null && !expr.getKind().equals(tp)) { var msg = this.expectsMessage(whoExpects, tp.toString()) if (expr.getKind() != this.core.Unknown) msg += lf(", got {0:a} instead", expr.getKind().toString()) this.markHolderError(expr, msg); } if (!expr.getError() && parsed instanceof AST.Call) { var call = <AST.Call> parsed; if (tp == null && whoExpects == "void") { var par = call.prop().parentKind var act = call.anyCalledAction() if (AST.legacyMode && par == this.core.Number && call.prop().getName() == "=") expr.hint = lf("the '=' comparison has no effect here; did you mean assignment ':=' instead?"); else if (expr.getKind() != this.core.Nothing && expr.getKind() != this.core.Unknown && expr.getKind().getRoot() != this.core.Task) // call.calledAction() == null) // (par == core.Number || call.args.length == 0)) { var exception = !!(call.prop().getFlags() & PropertyFlags.IgnoreReturnValue); var k = expr.getKind() var msg = "" if (k.hasContext(KindContext.Parameter)) msg = lf("did you want to use this value?"); else msg = lf("now you can select a property on it"); if (call.prop() instanceof LibraryRef) expr.hint = lf("we have a library '{0}' here; {1}", call.prop().getName(), msg) else if ((par.isBuiltin || call.args.length == 1) && !exception) expr.hint = lf("'{0}' returns a '{1}'; {2}", call.prop().getName(), call.getKind(), msg) else if (!exception) { /* switch (expr.getKind().getName()) { case "Board": case "Sprite Set": case "Sprite": case "Json Object": case "Xml Object": case "Json Builder": case "Form Builder": case "Web Request": case "Web Response": case "OAuth Response": msgIt = storeIt; break; } */ expr.hint = lf("'{0}' returns a '{1}'; {2}", call.prop().getName(), call.getKind(), msg) } } else if (act && act.getOutParameters().length > 0) expr.hint = lf("'{0}' returns {1} values; you can use 'store in var' button to save them to locals", call.prop().getName(), act.getOutParameters().length) } } else if (tp == null && whoExpects == "void") { var k = expr.getKind(); if (k != this.core.Nothing && k != this.core.Unknown) { if (k.singleton) expr.hint = lf("now you can select a property of {0}; it doesn't do anything by itself", k) else expr.hint = lf("we have {0:a} here; did you want to do something with it?", k) } } if (this.hintsToFlush.length > 0) { var hh = this.hintsToFlush.join("\n") if (expr.hint) expr.hint += "\n" + hh else expr.hint = hh this.hintsToFlush = []; } if (expr.assignmentInfo() && expr.assignmentInfo().fixContextError && expr.tokens[1].getOperator() == ":=") { this.numFixes++; this.nothingLocals.push(<LocalDef>expr.tokens[0].getThing()); expr.tokens.splice(0, 2); } if (this.nothingLocals.length > 0 && expr.tokens.length == 1 && this.nothingLocals.indexOf(<LocalDef>expr.tokens[0].getThing()) >= 0) { expr.tokens = [] this.numFixes++; } if (this.topApp.featureMissing(LanguageFeature.Refs) && expr.tokens.some(t => !!t.tokenFix)) { var t0 = expr.tokens.filter(t => t.tokenFix == ":=")[0] if (t0) { var idx = expr.tokens.indexOf(t0) if (expr.tokens[idx + 1] && expr.tokens[idx + 1].getOperator() == "(") { expr.tokens[idx] = mkOp(":="); expr.tokens.splice(idx + 1, 1) if (expr.tokens.peek().getOperator() == ")") expr.tokens.pop() } } expr.tokens = expr.tokens.filter(t => t.tokenFix != "delete") this.numFixes++; } } private declareLocal(v:LocalDef) { this.localScopes.peek().push(v); this.allLocals.push(v); v._isMutable = false; v._isCaptured = false; v.lastUsedAt = this.timestamp++; this.recordLocalRead(v); } private lookupSymbol(t:ThingRef) : AST.Decl { var n = t.data; for (var i = this.localScopes.length - 1; i >= 0; i--) { var s = this.localScopes[i]; for (var j = s.length - 1; j >= 0; j--) if (s[j].getName() === n) return s[j]; } if (n == "...") n = "$skip"; if (t.forceLocal) return undefined; return TDev.api.getThing(n); } private scope(f : () => any) { this.localScopes.push(<LocalDef[]>[]); // STRBUG: this cast shouldn't be needed var r = f(); this.localScopes.pop(); return r; } private conditionalScope(f: () => any) { var prevWritten = this.writtenLocals.slice(0); var prevLoop = this.currLoop try { return this.scope(f); } finally { this.writtenLocals = prevWritten; this.currLoop = prevLoop } } private core = TDev.api.core; /////////////////////////////////////////////////////////////////////////////////////////////// // Visitors /////////////////////////////////////////////////////////////////////////////////////////////// public visitAstNode(node:AstNode) { Util.oops("typechecking " + node.nodeType() + " not implemented!"); } public visitAnyIf(node:If) { this.updateStmtUsage(node); this.expect(node.rawCondition, this.core.Boolean, "if"); var isComment = node.isTopCommentedOut() if (isComment) { var vis = new ClearErrors() vis.dispatch(node.rawThenBody) } var prevWritten = this.writtenLocals.slice(0); if (node.rawThenBody == this.pageInit) this.actionSection = ActionSection.Init; else if (node.rawThenBody == this.pageDisplay) this.actionSection = ActionSection.Display; if (isComment) this.errorLevel++ this.typeCheck(node.rawThenBody); node.rawThenBody.newlyWrittenLocals = this.writtenLocals.slice(prevWritten.length); if (node.rawElseBody.stmts.length == 1 && node.rawElseBody.stmts[0] instanceof If) { var ei = <If>node.rawElseBody.stmts[0] ei.isElseIf = true; node.setElse(Parser.emptyBlock()) var bl = node.parentBlock() var idx = bl.stmts.indexOf(node) bl.stmts.splice(idx + 1, 0, ei) bl.newChild(ei) } if (node.rawElseBody.isBlockPlaceholder()) { node.rawElseBody.newlyWrittenLocals = []; this.typeCheck(node.rawElseBody); } else { this.writtenLocals = prevWritten.slice(0); this.typeCheck(node.rawElseBody); node.rawElseBody.newlyWrittenLocals = this.writtenLocals.slice(prevWritten.length); } if (isComment) this.errorLevel-- this.writtenLocals = prevWritten; } public visitWhere(node:Where) { this.expect(node.condition, this.core.Boolean, 'where'); } public visitWhile(node:While) { this.updateStmtUsage(node); this.expect(node.condition, this.core.Boolean, 'while'); this.conditionalScope(() => { this.currLoop = node; this.typeCheck(node.body); }); } public visitBreakContinue(node:Call, tp:string) { node._kind = this.core.Nothing; node.topAffectedStmt = this.currLoop if (!this.currLoop) this.markError(node, lf("TD200: '{0}' can be only used inside a loop", tp)) if (!node.args[0].isPlaceholder()) this.markError(node, lf("TD205: '{0}' cannot take arguments", tp)) this.expectExpr(node.args[0], null, tp) } public visitBreak(node:Call) { this.visitBreakContinue(node, "break") } public visitContinue(node:Call) { this.visitBreakContinue(node, "continue") } public visitShow(node:Call) { node._kind = this.core.Nothing; this.expectExpr(node.args[0], null, "show") node.topPostCall = null; if (node.args[0].isPlaceholder()) { this.markError(node, lf("TD207: we need something to show")) } else { var tp = node.args[0].getKind() if (tp == api.core.Unknown) return var show = tp.getProperty("post to wall") if (!show) this.markError(node, lf("TD201: we don't know how to display {0}", tp.toString())) else node.topPostCall = mkFakeCall(PropertyRef.mkProp(show), [node.args[0]]) } } public visitReturn(node:Call) { node._kind = this.core.Nothing; node.topRetLocal = null; var exp = null if (!node.args[0].isPlaceholder()) { if (this.outLocals.length == 0) this.markError(node.args[0], lf("TD202: the function doesn't have output parameters; return with a value is not allowed")) else if (this.outLocals.length > 1) this.markError(node.args[0], lf("TD203: the function has more than one output parameter; return with a value is not allowed")) else { node.topRetLocal = this.outLocals[0] exp = node.topRetLocal.getKind() this.recordLocalWrite(node.topRetLocal) } } else { if (this.outLocals.length == 1) this.markError(node, lf("TD206: we need a value to return here")) } this.expectExpr(node.args[0], exp, "return") node.topAffectedStmt = this.currentAnyAction; this.checkAssignment(this.lastStmt) } public visitActionParameter(node:ActionParameter) { } public visitBlock(node:Block) { this.scope(() => { var ss = node.stmts; var unreach = false var reported = false for (var i = 0; i < ss.length; ++i) { this.typeCheck(ss[i]) if (unreach) { ss[i].isUnreachable = true if (!reported && !(ss[i] instanceof Comment)) { reported = true ss[i].addHint(lf("code after return, break or continue won't ever run")) } } if (ss[i].isJump()) unreach = true } for (var i = 0; i < ss.length; ++i) { if (ss[i] instanceof If) { var si = <If>ss[i] si.isElseIf = false; var end = i + 1 while (isElseIf(ss[end])) { end++; if (!(<If>ss[end - 1]).rawElseBody.isBlockPlaceholder()) break; } si.branches = [] while (i < end) { var innerIf = <If>ss[i++] innerIf.parentIf = si; si.branches.push({ condition: innerIf.rawCondition, body: innerIf.rawThenBody }) if (i == end) { si.branches.push({ condition: null, body: innerIf.rawElseBody }) innerIf.displayElse = true; } else { innerIf.displayElse = false; } } i--; this.writtenLocals.pushRange(Util.intersectArraysVA(si.branches.map(b => b.body.newlyWrittenLocals))) } } }) } private updateStmtUsage(s:Stmt, tp:string = null) { this.lastStmt = s if (this.countToUpdate != 0) { var u = api.core.stmtUsage(tp || s.nodeType()) if (this.countToUpdate == 1) u.localCount++; else u.globalCount++; } } public visitFor(node:For) { this.updateStmtUsage(node); this.expect(node.upperBound, this.core.Number, 'for'); node.boundLocal._kind = this.core.Number; this.readOnlyLocals.push(node.boundLocal); this.conditionalScope(() => { this.currLoop = node; this.declareLocal(node.boundLocal); this.typeCheck(node.body); }); } public visitForeach(node:Foreach) { this.updateStmtUsage(node); this.expect(node.collection, null, null); var k = node.collection.getKind(); if (!k.isEnumerable() && !node.collection.getError()) { if (k == this.core.Unknown) { this.markHolderError(node.collection, lf("TD119: i need something to iterate on")); } else { this.markHolderError(node.collection, lf("TD120: i cannot iterate over {0}", k.toString())); } } var ek: Kind; if (k instanceof RecordDefKind) ek = (<RecordDefKind>k).record.entryKind; var atProp = k.getProperty("at"); if (!ek && !!atProp) ek = atProp.getResult().getKind(); if (!!ek) node.boundLocal._kind = ek; this.readOnlyLocals.push(node.boundLocal); this.conditionalScope(() => { this.currLoop = node; this.declareLocal(node.boundLocal); this.typeCheck(node.conditions); this.typeCheck(node.body); }); } public visitBox(node:Box) { this.updateStmtUsage(node); this.typeCheck(node.body) } public visitComment(node:Comment) { this.updateStmtUsage(node); } private setOutLocals(locs:LocalDef[]) { this.outLocals = locs var isHiddenOut = locs.length == 1 locs.forEach(l => { l.isHiddenOut = isHiddenOut; l.isOut = true; }) } public visitAction(node:Action) { this.writtenLocals = []; this.readOnlyLocals = []; this.allLocals = []; this.currentAction = node; this.currentAnyAction = node; node.clearError(); this.actionSection = ActionSection.Normal; this.inAtomic = node.isAtomic; this.inShim = this.topApp.entireShim || node.getShimName() != null; node._compilerInlineBody = null; this.scope(() => { // TODO in - read-only? var prevErr = this.errorCount; this.setOutLocals(node.getOutParameters().map((p) => p.local)) this.reportedUnassigned = false; this.typeResolver.visitAction(node); var fixupLocalInp = (a:ActionParameter) => { this.declareLocal(a.local); if (node.isPage()) this.readOnlyLocals.push(a.local) } if (node.modelParameter) fixupLocalInp(node.modelParameter); node.getInParameters().forEach(fixupLocalInp); node.getOutParameters().forEach((a) => this.declareLocal(a.local)) if (node.isPage()) { this.pageInit = node.getPageBlock(true) this.pageDisplay = node.getPageBlock(false) } this.typeCheck(node.body); if (node.isActionTypeDef()) { var outp1 = node.getOutParameters()[1] if (outp1) { this.setNodeError(node, lf("TD171: function types support at most one output parameter; sorry")) } } else { if (!this.reportedUnassigned) this.checkAssignment(node); } node._hasErrors = this.errorCount > prevErr; node.allLocals = this.allLocals; }); if (// this.topApp.featureMissing(LanguageFeature.UnicodeModel) && node.modelParameter && node.modelParameter.local.getName() != modelSymbol) { node.modelParameter.local.setName(modelSymbol) this.numFixes++; } if (this.missingLocals.length > 0 && this.storeLocalsAt && this.storeLocalsAt.locals) { this.storeLocalsAt.locals.pushRange(this.missingLocals); } var inf = node.eventInfo; if (inf != null) { inf.disabled = false; if (inf.type.globalKind != null && !inf.onVariable) { var varName = node.getName().slice(inf.type.category.length); var v = this.topApp.variables().filter((v:GlobalDef) => v.getName() == varName)[0]; if (v === undefined) { node.setError(lf("TD122: i cannot find variable {0}", varName)) inf.disabled = true; } inf.onVariable = v; } if (!!inf.onVariable) { var newName = inf.type.category + inf.onVariable.getName() if (!Script.things.filter(t => t.getName() == newName)[0]) node.setName(newName); if (node.getName() != newName) inf.onVariable = null; } // these should never really happen - we do not allow users to edit the signature if (node.hasOutParameters()) node.setError(lf("TD123: events cannot have out parameters")); if (node.getInParameters().length != inf.type.inParameters.length) node.setError(lf("TD124: wrong number of in parameters to an event")); else { var inParms = node.getInParameters(); for (var i = 0; i < inParms.length; ++i) if (inParms[i].getKind() != inf.type.inParameters[i].getKind()) node.setError(lf("TD125: wrong type of parameter #{0}", i)); } if (this.topApp.isLibrary && !this.ignoreLibErrors) node.setError(lf("TD126: libraries cannot define global events")); } if (!node.isExternal) { if (this.topApp.isCloud && node.isPage()) node.setError(lf("TD177: cloud libraries cannot define pages")); if (this.topApp.isCloud && !node.isPrivate && node.isAtomic) node.setError(lf("TD178: cloud libraries cannot define atomic functions")); } if (!!node.getError()) node._hasErrors = true; node._errorsOK = undefined; if (node.isCompilerTest()) { node._errorsOK = runErrorChecker(node); } } public visitLibraryRef(node:LibraryRef) { } private persistentStorageError(whatr: AST.RecordDef, wherep: AST.RecordPersistence, where?: AST.RecordDef): string { var error: string; var wheres: string; switch (wherep) { case RecordPersistence.Cloud: wheres = lf("replicated "); break; case RecordPersistence.Partial: wheres = lf("replicated "); break; case RecordPersistence.Local: wheres = Script.isCloud ? lf("server-local ") :lf("locally persisted "); break; } wheres = wheres + (!where ? lf("variable") : (where.recordType === RecordType.Table ? lf("table") : lf("index"))); if (whatr.recordType === RecordType.Object) { return lf("TD169: {0:a} cannot be persisted between script runs", whatr.toString());; } else { Util.assert(whatr.recordType === RecordType.Table); var whats: string; switch (whatr.getRecordPersistence()) { case RecordPersistence.Cloud: whats = lf("replicated table rows"); break; case RecordPersistence.Local: whats = Script.isCloud ? lf("server-local table rows") : lf("locally persisted table rows"); break; case RecordPersistence.Temporary: whats = lf("temporary table rows"); break; case RecordPersistence.Partial: whats = lf("replicated table rows"); break; } return lf("TD166: cannot store {0} in a {1}", whats, wheres); } } visitGlobalDef(node: GlobalDef) { node.clearError(); if (node.isResource) { node.isTransient = true; node.cloudEnabled = false; } this.typeResolver.visitGlobalDef(node); if (node.getRecordPersistence() != RecordPersistence.Temporary && (node.getKind().getContexts() & KindContext.CloudField) == 0) { this.setNodeError(node, lf("TD165: {0:a} cannot be saved between script runs", node.getKind().toString())) if (this.topApp.featureMissing(LanguageFeature.LocalCloud)) { node.isTransient = true; node.cloudEnabled = false; this.numFixes++; } } if (node.getKind() instanceof RecordEntryKind) { var rdef = (<RecordEntryKind>(node.getKind())).getRecord(); if (rdef.recordType == RecordType.Decorator) { this.setNodeError(node, lf("TD175: must not store decorators in variables")); } else if (node.getRecordPersistence() > rdef.getRecordPersistence()) { this.setNodeError(node, this.persistentStorageError(rdef, node.getRecordPersistence())); if (!node.isTransient && this.topApp.featureMissing(LanguageFeature.LocalCloud)) { node.isTransient = true; node.cloudEnabled = false; this.numFixes++; } } } } private cyclefree(start,current: RecordDef) : boolean { return (current != start) && (!current._wasTypechecked || current.linkedtables.every((t: RecordDef) => this.cyclefree(start, t))); } public visitRecordField(node:RecordField) { node.clearError(); this.typeResolver.visitRecordField(node); var pers = node.def().getRecordPersistence() var cl = pers != RecordPersistence.Temporary; var ctx = cl ? (node.isKey ? KindContext.IndexKey : KindContext.CloudField) : (node.isKey ? KindContext.IndexKey : KindContext.GlobalVar); var k = node.dataKind var c = k.getContexts(); var newtype = node.def().recordType if (node.def().recordType == RecordType.Decorator && ctx == KindContext.IndexKey) ctx = KindContext.GcKey // check if this is a valid row key for an index or table if (!!(c & KindContext.RowKey) && (newtype == RecordType.Index || newtype == RecordType.Table)) { var other = (<RecordEntryKind>node.dataKind).getRecord() var otherpers = other.getRecordPersistence(); if (otherpers < pers && !(otherpers == RecordPersistence.Cloud && pers == RecordPersistence.Partial)) { this.setNodeError(node, this.persistentStorageError(other, pers, node.def())); this.errorCount++; if (this.topApp.featureMissing(LanguageFeature.LocalCloud) && pers != RecordPersistence.Cloud && other.getRecordPersistence() != RecordPersistence.Cloud) { node.def().persistent = false other.persistent = false this.numFixes++; } } if (node.isKey && newtype == RecordType.Table) // check links { if (!this.cyclefree(node.def(), other)) { this.setNodeError(node, lf("TD176: links must not be circular") ) } else node.def().linkedtables.push(other); } return; } if (!(c & ctx)) { if (cl) this.setNodeError(node, lf("TD167: {0:a} cannot be persisted between script runs", k.toString())); else this.setNodeError(node, lf("TD168: {0:a} cannot be used as a {1}", node.isKey ? lf("key") : lf("field"), k.toString())) if (this.topApp.featureMissing(LanguageFeature.LocalCloud) && pers == RecordPersistence.Local) { node.def().persistent = false; this.numFixes++; } } if (pers === RecordPersistence.Partial && node.isKey && node.isFirstChild()) { if (node.dataKind.getName() !== "User") { this.errorCount++; node.setError("A partially replicated Index should have a User as first key"); } } } public visitRecordDef(node:RecordDef) { node.isModel = false; node.linkedtables = []; this.visitChildren(node); } private typecheckLibraries(node:App) { node.libraries().forEach((l) => l.resolve()); node.libraries().forEach((l) => l.typeCheck()); } public visitApp(node:App) { this.typecheckLibraries(node); if (Cloud.isRestricted()) node.entireShim = /#entireshim/i.test(node.comment) || node.actions().some(a => a.isPage()) || node.libraries().some(l => l.resolved && l.resolved.entireShim) node.things.forEach((n:Decl) => { var wt = n._wasTypechecked; n._wasTypechecked = true; this.dispatch(n); if (!wt) n.notifyChange(); }); var usedNames = {} node.things.forEach((n) => { if (usedNames.hasOwnProperty(n.getName())) { // name clash, need to fix this.numFixes++; n.setName(node.freshName(n.getName() + " " + this.numFixes)) } else { usedNames[n.getName()] = n; } }) node.actions().forEach(a => { var d = a.getModelDef() if (d) d.isModel = true }) } public visitExprStmt(expr:ExprStmt) { this.updateStmtUsage(expr); this.expect(expr.expr, null, "void"); if (expr.isVarDef()) this.updateStmtUsage(expr, "var"); } private checkAssignment(node:Stmt) { var unassigned = this.outLocals.filter((v) => this.writtenLocals.indexOf(v) < 0); if (unassigned.length > 0) { this.reportedUnassigned = true; node.addHint(lf("the function may not always return a value; insert a return statement?")); } } private actionScope(k:Kind, f:()=>void) { this.scope(() => { var prevReadOnly = this.readOnlyLocals; var prevRead = this.readLocals; var prevOutsideScopeLocals = this.outsideScopeLocals; var prevWritten = this.writtenLocals; var prevSect = this.actionSection; var prevAtomic = this.inAtomic; var prevOut = this.outLocals; var prevRep = this.reportedUnassigned; var prevAct = this.currentAnyAction; var prevLoop = this.currLoop; var prevInvisibleLocals = this.invisibleLocals; this.currLoop = null; this.writtenLocals = []; this.readLocals = []; this.actionSection = ActionSection.Lambda; this.inAtomic = k instanceof ActionKind && (<ActionKind>k).isAtomic(); this.outsideScopeLocals = this.snapshotLocals() this.readOnlyLocals = AST.writableLocalsInClosures ? this.outsideScopeLocals.filter(l => !l.isRegular) : this.outsideScopeLocals.slice(0); if (Cloud.isRestricted()) this.invisibleLocals = this.snapshotLocals(); try { f() } finally { this.readLocals = prevRead; this.writtenLocals = prevWritten; this.readOnlyLocals = prevReadOnly; this.inAtomic = prevAtomic; this.actionSection = prevSect; this.outLocals = prevOut; this.currentAnyAction = prevAct; this.reportedUnassigned = prevRep; this.currLoop = prevLoop; this.invisibleLocals = prevInvisibleLocals; this.outsideScopeLocals = prevOutsideScopeLocals; } }) } private typeCheckInlineAction(inl:InlineAction) { this.actionScope(inl.name.getKind(), () => { this.currentAnyAction = inl; inl.inParameters.forEach((d) => this.declareLocal(d)); inl.outParameters.forEach((d) => this.declareLocal(d)); if (Cloud.isRestricted()) this.readOnlyLocals.pushRange(inl.inParameters) this.setOutLocals(inl.outParameters.slice(0)) this.reportedUnassigned = false; this.typeCheck(inl.body); if (!this.reportedUnassigned) this.checkAssignment(inl); this.computeClosure(inl); }) } public visitInlineActions(inl:InlineActions) { this.updateStmtUsage(inl) // cannot just use scope, as the next expression can introduce fresh variables var names = inl.normalActions().map(a => a.name); names.forEach((n) => { this.declareLocal(n); n.lambdaNameStatus = 2; }); inl.actions.forEach((iab:InlineActionBase) => { iab.clearError() }) this.topInline = inl this.expect(inl.expr, null, "void"); var p = this.localScopes.length - 1; this.localScopes[p] = this.localScopes[p].filter((l) => names.indexOf(l) < 0); var defined = (inl.expr.assignmentInfo() ? inl.expr.assignmentInfo().definedVars : null) || [] var prevScope = this.localScopes[p] this.localScopes[p] = prevScope.filter(l => defined.indexOf(l) < 0) var rename = (s:string) => s; // TODO inl.actions.forEach((iab:InlineActionBase) => { if (iab instanceof OptionalParameter) { var op = <OptionalParameter>iab var knd = op.recordField ? op.recordField.dataKind : null this.expect(op.expr, knd, "optional") return } var ia = <InlineAction>iab var coerced = false; var coerce = (locs:LocalDef[], parms:PropertyParameter[]) => { if (locs.length > parms.length) { locs.splice(parms.length, locs.length - parms.length) coerced = true; } else if (parms.length > locs.length) { coerced = true; parms.slice(locs.length).forEach((pp) => { locs.push(mkLocal(rename(pp.getName()), pp.getKind())) }); } locs.forEach((l, i) => { var pp = parms[i]; if (pp.getKind() != l.getKind()) { l.rename(rename(pp.getName())); l._kind = pp.getKind(); coerced = true; } }) } if (ia.isOptional && ia.recordField) { var ak = <ActionKind>ia.recordField.dataKind ia.name.setKind(ak) if (ak.isAction) { coerce(ia.inParameters, ak.getInParameters()) coerce(ia.outParameters, ak.getOutParameters()) } else { this.setNodeError(ia, lf("TD189: type of optional parameter '{0}' is not a function type", ia.getName())) } } else if (ia.name.lambdaNameStatus != 2 && ia.name.getKind().isAction) { var ak = <ActionKind>ia.name.getKind(); coerce(ia.inParameters, ak.getInParameters()) coerce(ia.outParameters, ak.getOutParameters()) } this.typeCheckInlineAction(ia); ia.closure.forEach(l => this.recordLocalRead(l)) }); this.localScopes[p] = prevScope } ///////////////////////////////////////////////// // Expression type-checking ///////////////////////////////////////////////// public visitThingRef(t:ThingRef) { if (Util.startsWith(t.data, ThingRef.placeholderPrefix)) { var kn = t.data.slice(ThingRef.placeholderPrefix.length); var plName = null var colon = kn.indexOf(':') if (colon > 0) { plName = kn.slice(colon + 1) kn = kn.slice(0, colon) } var k = api.getKind(kn); if (!k && /[_\[]/.test(kn)) { k = Parser.parseType(kn) if (k) k = TypeChecker.resolveKind(k) if (k == api.core.Unknown) k = null } if (!!k) { var pl = new PlaceholderDef(); pl.setName(""); pl._kind = k; if (plName) pl.label = plName t.def = pl } } t._lastTypechecker = this; if (t.def instanceof PlaceholderDef) { if (!t.isEscapeDef()) this.markError(t, (<PlaceholderDef>t.def).longError()); } else { if (!!t.def && !t.def.deleted && t.data != t.def.getName()) t.data = t.def.getName(); t.def = this.lookupSymbol(t); if (!t.def && t.namespaceLibraryName()) { if (!t.namespaceLibrary || t.namespaceLibrary.deleted) t.namespaceLibrary = Script.libraries().filter(l => l.getName() == t.namespaceLibraryName())[0] t.def = Script.libNamespaceCache.createSingleton(t.data, t.namespaceLibrary) } if (!t.def) { this.markError(t, lf("TD101: cannot find '{0}'", t.data)); var loc = mkLocal(t.data, this.core.Unknown); t.def = loc loc.isRegular = true if (this.seenCurrent) this.missingLocals.push(loc) this.declareLocal(loc) } } if (t.def instanceof LocalDef) this.recordLocalRead(<LocalDef>t.def) if (t.def instanceof LocalDef) t.forceLocal = true; else if (t.def instanceof SingletonDef) t.forceLocal = false; var l = <LocalDef>t.def; if (l instanceof LocalDef && l.lambdaNameStatus) { if (l.lambdaNameStatus == 1) this.markError(t, lf("TD102: lambda reference '{0}' cannot be used more than once", l.getName())) else { l.lambdaNameStatus = 1; if (this.typeHint && this.typeHint.isAction) { l._kind = this.typeHint; } } } t._kind = t.def.getKind(); if (t.def instanceof LocalDef) { var l = <LocalDef> t.def; if (!this.seenCurrent) l.lastUsedAt = this.timestamp++; } else if (this.countToUpdate != 0) { if (t.def instanceof SingletonDef) { var u = (<SingletonDef> t.def).usage; if (this.countToUpdate == 1) u.localCount++; else u.globalCount++; } } } public visitLiteral(l:Literal) { // Special, built-in type-checking for the literal that stands for a // field name. if (l instanceof FieldName) { var mkKind = () => { var mk = TDev.MultiplexRootProperty.md_make_kind(); mk.md_parametric("T"); var prop = TDev.MultiplexRootProperty .md_make_prop(mk, 0, TDev.api.core.Unknown, ":", "Whatever", [], mk.getParameter(0)); return prop.getResult().getKind(); } l._kind = mkKind(); } else switch (typeof l.data) { case "number": if (Cloud.isRestricted() && !this.inShim) { if (Util.between(-0x80000000, l.data, l.possiblyNegative ? 0x80000000 : 0x7fffffff) != l.data) { this.markError(l, lf("TD209: the number is outside of the allowed range (between {0} and {1})", -0x80000000, 0x7fffffff)); } else if (Math.round(l.data) != l.data) { this.markError(l, lf("TD210: fractional numbers not allowed")); } } l._kind = this.core.Number; break; case "string": l._kind = this.core.String; break; case "boolean": l._kind = this.core.Boolean; break; default: Util.die(); } } private typeCheckExpr(e:Expr) { e._kind = null; // e.error = null; this.dispatch(e); Util.assert(e.getKind() != null); } private expectExpr(expr:Expr, tp:Kind, whoExpects:string, skipTypecheck = false) { if (!skipTypecheck) { var prevHint = this.typeHint; this.typeHint = tp; this.typeCheckExpr(expr); this.typeHint = prevHint; } if (!Util.check(expr.getKind() != null, "expr type unset2")) { expr._kind = api.core.Unknown } if (tp != null && expr.getKind() !== tp) { var code = "TD103: " var suff = "" if (tp.getRoot() == api.core.Ref && (expr.referencedData() || expr.referencedRecordField())) { code = "TD164: " suff = lf("; are you missing  → ◈ref?") } var msg = lf("'{0}' expects {1} here", whoExpects, tp.toString()) var k = expr.getKind(); if (k != this.core.Unknown) msg += lf(", got {0}", k.toString()) this.markError(expr, code + msg + suff); } } private handleAsync(t:Call, args:Expr[]) { t._kind = this.core.Unknown; // will get overridden if (args.length != 2) { // cannot trigger this one? this.markError(t, lf("TD104: syntax error in async")); return; } // args[0] is 'this' var arg = args[1] if (arg instanceof Call) (<Call>arg).runAsAsync = true; this.expectExpr(arg, null, "async") var calledProp = arg.getCalledProperty(); var isAsyncable = calledProp && !!(calledProp.getFlags() & PropertyFlags.Async) if (calledProp == api.core.AsyncProp) isAsyncable = false; if (!isAsyncable) { this.markError(t, lf("TD157: 'async' keyword needs a non-atomic API or function to call")) return; } (<Call>arg).runAsAsync = true; if (calledProp && calledProp.forwardsTo() instanceof Action) { var act = <Action>calledProp.forwardsTo() if (act.getOutParameters().length > 1) this.markError(t, lf("TD170: cannot use 'async' on functions with more than one output parameter")) } t._kind = this.core.Task.createInstance([arg.getKind()]) } private computeClosure(inl:InlineAction) { inl.closure = []; inl.allLocals = []; this.readLocals.forEach(l => { if (this.outsideScopeLocals.indexOf(l) >= 0) { inl.closure.push(l) l._isCaptured = true } inl.allLocals.push(l) }) } private handleFun(t:Call, args:Expr[]) { var ak:ActionKind = null var resKind:Kind = null if (this.typeHint && this.typeHint.isAction) { ak = <ActionKind>this.typeHint var outp = ak.getOutParameters() if (outp.length != 1) this.markError(t, lf("TD194: lambda expressions need to return exactly one value; function type '{0}' returns {1}", ak.getName(), outp.length)) else resKind = outp[0].getKind() } else { this.markError(t, lf("TD195: lambda expressions can only be used as arguments of function type")) } this.actionScope(this.typeHint, () => { if (ak) { var synth = new InlineAction() synth.name = mkLocal(Random.uniqueId(), ak) this.declareLocal(synth.name) var names = t.propRef.fromOp.getFunArgs() || [] synth.inParameters = ak.getInParameters().map((p, i) => mkLocal(names[i] || p.getName(), p.getKind())) t.propRef.fromOp.funArgs = synth.inParameters synth.outParameters = ak.getOutParameters().map(p => mkLocal(p.getName(), p.getKind())) synth.inParameters.forEach(p => this.declareLocal(p)) synth.body = new CodeBlock() synth.body.parent = synth synth.parent = this.lastStmt.parent var bb = Parser.emptyExprStmt() synth.body.setChildren([bb]) var outp0 = synth.outParameters[0] if (outp0) { var resR = <ThingRef>mkThing(outp0.getName(), true) resR.def = outp0 bb.expr.parsed = mkFakeCall(PropertyRef.mkProp(api.core.AssignmentProp), [ resR, args[1] ]) t.funAction = synth } } this.expectExpr(args[1], resKind, "lambda expression") if (ak) this.computeClosure(synth); }); t._kind = ak || this.core.Unknown } private recordLocalRead(loc:LocalDef) { if (this.readLocals.indexOf(loc) < 0) this.readLocals.push(loc); } private recordLocalWrite(loc:LocalDef) { this.recordLocalRead(loc); if (this.writtenLocals.indexOf(loc) < 0) this.writtenLocals.push(loc); } private handleAssignment(t:Call, args:Expr[]) { t._kind = this.core.Nothing; if (args.length != 2) { // cannot trigger this one? this.markError(t, lf("TD104: syntax error in assignment")); return; } Util.assert(args.length == 2); var lhs = args[0].flatten(this.core.TupleProp); var rhs = args[1]; this.isTopExpr = true; this.typeCheckExpr(rhs); var info = new AssignmentInfo(); t._assignmentInfo = info; var sources = [AST.mkLocal("", rhs.getKind())]; var act = rhs.anyCalledAction() if (act != null) { sources = act.getOutParameters().map((a:AST.ActionParameter) => a.local); var missing = sources.length - lhs.length; if (missing > 0) { this.markError(t, lf("TD105: function '{0}' returns {1} more value{1:s}", act, missing)); info.missingArguments = missing; } } info.targets = lhs; info.sources = sources; for (var i = 0; i < lhs.length; ++i) { var trg = lhs[i]; var src = sources[i]; if (src == undefined) { this.markError(trg, lf("TD106: not enough values returned to assign to {0}", trg)); continue; } var prevErr = this.errorCount; if (trg.nodeType() === "thingRef") { var tr = <ThingRef> trg; tr._lastTypechecker = this; if (!!tr.def) tr.data = tr.def.getName(); var name = tr.data; var thing = this.lookupSymbol(tr); if (!thing) { var loc = mkLocal(name, src.getKind()); info.definedVars.push(loc); thing = loc; loc.isRegular = true this.declareLocal(loc) if (!src.getKind().hasContext(KindContext.Parameter)) { if (src.getKind() == api.core.Nothing && this.topApp.featureMissing(LanguageFeature.ContextCheck)) info.fixContextError = true; this.markError(tr, lf("TD155: '{0}' cannot be assigned to a local variable", src.getKind())) } } else { var loc = <LocalDef>thing; if (this.readOnlyLocals.indexOf(loc) >= 0) { if (!AST.writableLocalsInClosures && this.actionSection == ActionSection.Lambda) { this.markError(trg, lf("TD107: inline functions cannot assign to locals from outside like '{0}'", name)); } else { this.markError(trg, lf("TD108: you cannot assign to the local variable '{0}'", name)); } } else { if (this.outsideScopeLocals.indexOf(loc) >= 0) loc._isCaptured = true; this.recordLocalWrite(loc) } // if it wasn't captured yet anywhere, and we're not inside a loop, no reason to treat it as mutable just yet if (loc._isCaptured || this.currLoop) loc._isMutable = true; } this.typeCheckExpr(trg); } else { this.typeCheckExpr(trg); var gd = trg.referencedData(); var rcf = trg.referencedRecordField(); var setter = trg.getLiftedSetter(); if (rcf == null && gd == null && setter == null) { this.markError(trg, lf("TD109: cannot assign to this")); continue; } if (gd && gd.readonly) { this.markError(trg, lf("TD110: trying to assign to a read-only variable")); } else if (rcf && rcf.isKey) { this.markError(trg, lf("TD163: trying to assign to an index key")); } else { Util.assert(!!setter || trg.isRefValue()); } (<Call>trg).autoGet = false; } if (src.getKind() != trg.getKind() && prevErr == this.errorCount) this.markError(trg, lf("TD111: cannot assign from {0} to {1}", src.getKind(), trg.getKind())); } } private lintJavaScript(js:string, isAsync:boolean) { var toks:string[] = Lexer.tokenize(js).map(l => { switch (l.category) { case TokenType.Op: case TokenType.Id: case TokenType.Keyword: case TokenType.Label: return l.data; default: return "" } }).filter(s => !!s) var nextProtected = false var hasResume = false var hasUnprotected = 0 var hasOverprotected = 0 var brStack = [] var hasBrError = false toks.forEach((t, i) => { if ((t == "resume" || t == "checkAndResume") && toks[i + 1] == "(") hasResume = true if (t == "protect" && toks[i + 1] == "(") nextProtected = true if (t == "function") { if (isAsync) { if (!nextProtected) hasUnprotected++ } else { if (nextProtected) hasOverprotected++ } nextProtected = false } if (t == "(") brStack.push(")") if (t == "{") brStack.push("}") if (t == "[") brStack.push("]") if (t == ")" || t == "}" || t == "]") { if (brStack.peek() != t) { if (!hasBrError) this.hintsToFlush.push(lf("JS hint: possible brace mismatch: got '{0}', expecting '{1}'", t, brStack.peek())) hasBrError = true } else brStack.pop() } }) if (!hasBrError && brStack.length > 0) this.hintsToFlush.push(lf("JS hint: possible missing closing brace: '{0}'", brStack.peek())) if (isAsync && !hasResume) this.hintsToFlush.push(lf("JS hint: using 'javascript async' but no call to 'resume()'")) if (!isAsync && hasResume) this.hintsToFlush.push(lf("JS hint: using 'resume()' outside of 'javascript async'")) if (hasUnprotected) this.hintsToFlush.push(lf("JS hint: found function() without lib.protect(...) around it")) if (hasOverprotected) this.hintsToFlush.push(lf("JS hint: found function() with lib.protect(...) outside of `javascript async`")) } private checkStringLiteralArguments(t: Call) : (number) => boolean { var propName = t.prop().getName(); if (!t.args.slice(1).every(a => a.getStringLiteral() != null)) { this.markError(t, lf("TD179: arguments to `{0}` have to be string literals", propName)) return undefined; } var checkArgumentCount = (c: number) => { if (t.args.length != c) { this.markError(t, lf("TD181: wrong number of arguments to `{0}`", propName)) return false; } return true; } return checkArgumentCount; } private handleJavascriptImport(t:Call) { var checkArgumentCount = this.checkStringLiteralArguments(t); if (!checkArgumentCount) return; var propName = t.prop().getName(); switch (propName) { case "javascript": case "javascript async": if (!checkArgumentCount(3)) return; this.currentAction.getOutParameters().forEach(p => this.recordLocalWrite(p.local)) this.lintJavaScript(t.args[2].getStringLiteral(), /async/.test(t.prop().getName())) break; case "thumb": if (!Cloud.isRestricted()) { this.markError(t, lf("app->thumb not supported in full Touch Develop")) return; } if (!checkArgumentCount(2)) return; if (!this.inShim) this.markError(t, lf("TD213: app->thumb only supported inside of {asm:}")) if (this.currentAction._compilerInlineBody) this.markError(t, lf("TD214: only one app->thumb allowed")) this.currentAction._compilerInlineBody = this.lastStmt this.currentAction.getOutParameters().forEach(p => this.recordLocalWrite(p.local)) if (TypeChecker.lintThumb) { var errs = TypeChecker.lintThumb(this.currentAction, t.args[1].getStringLiteral()) if (errs.length > 0) { this.markError(t, lf("TD212: thumb assembler error")) this.lastStmt._inlineErrors = errs; } else { this.lastStmt._inlineErrors = null; } } break; case "import": if (!checkArgumentCount(4)) return; var manager = t.args[1].getStringLiteral() || "" var plugin = t.args[2].getStringLiteral() var v = t.args[3].getStringLiteral() if (v == null) v = "*"; switch (manager.trim().toLowerCase()) { case "npm": if (!this.topApp.canUseCapability(PlatformCapability.Npm)) this.unsupportedCapability(plugin, PlatformCapability.Npm); this.topApp.imports.importNpm(this, t, plugin, v); break; case "cordova": if (!this.topApp.canUseCapability(PlatformCapability.Cordova)) this.unsupportedCapability(plugin, PlatformCapability.Cordova); this.topApp.imports.importCordova(this, t, plugin, v); break; case "bower": this.topApp.imports.importBower(this, t, plugin, v); break; case "client": this.topApp.imports.importClientScript(this, t, plugin, v); break; case "pip": if (!this.topApp.canUseCapability(PlatformCapability.Npm)) this.unsupportedCapability(plugin, PlatformCapability.Npm); this.topApp.imports.importPip(this, t, plugin, v); break; case "touchdevelop": { if (!/^\/?[a-z]{4,}$/.test(v)) this.markError(t, lf("TD190: version must be a published script id")); else { if (!this.topApp.canUseCapability(PlatformCapability.EditorOnly)) this.unsupportedCapability(plugin, PlatformCapability.EditorOnly); this.topApp.imports.importTouchDevelop(this, t, plugin, v.replace(/^\/?/, "")); } break; } default: this.markError(t, lf("TD191: unknown package manager")); break; } break; } } public visitCall(t:Call) { var args = t.args; var prop = t.prop(); var wasTopExpr = this.isTopExpr this.isTopExpr = false if (this.inShim) t.isShim = this.inShim; t._assignmentInfo = null; if (prop === this.core.AssignmentProp) { this.handleAssignment(t, args); return; } if (prop === this.core.AsyncProp) { this.handleAsync(t, args); return; } if (prop == this.core.FunProp) { this.handleFun(t, args) return } var topInline = this.topInline this.topInline = null var prevErr = this.errorCount; this.typeCheckExpr(args[0]); var k0 = args[0].getKind(); if (this.topApp.featureMissing(LanguageFeature.Refs) && args[0].referencedRecordField() && /^(get|set|test and set|confirmed|clear|add)$/.test(t.propRef.data)) { this.numFixes++; prop = null; t.propRef.data = api.core.refPropPrefix + t.propRef.data if (/^.(get)$/.test(t.propRef.data)) { t.propRef.tokenFix = "delete"; } else if (/^.(set)$/.test(t.propRef.data)) { t.propRef.tokenFix = ":="; } } if (t.propRef.getText().slice(0,1) == api.core.refPropPrefix && args[0].allowRefUse()) { var innerCall = <Call>args[0] Util.assert(innerCall.autoGet) innerCall._kind = k0 = api.core.Ref.createInstance([k0]) innerCall.autoGet = false; } if (prop) { if (k0 != this.core.Unknown && prop.getInfixPriority() == 0 && prop.parentKind != k0) prop = null; // rebind } if (prop && prop.deleted) { var nn = prop.getName() if (nn) t.propRef.data = nn prop = null; } if (!prop || prop instanceof UnresolvedProperty) { prop = k0.getProperty(t.propRef.data); if (!prop && this.topApp.featureMissing(LanguageFeature.UppercaseMultiplex)) { if (k0 instanceof MultiplexKind) { var otherOption = (s:string) => false if (t.propRef.data[0] == recordSymbol) { var libsuffix = "\u00A0" + t.propRef.data.slice(1) otherOption = s => s.slice(-libsuffix.length) == libsuffix } prop = k0.listProperties().filter(p => p.getName().toLowerCase() == t.propRef.data || otherOption(p.getName()))[0] } else if (k0.getName() == "Create" && t.propRef.data == "collection of") { prop = k0.getProperty("Collection of") } } if (!prop) { var pref = k0.getName() + "->" var autoRenameKey = pref + t.propRef.data if (AST.propRenames.hasOwnProperty(autoRenameKey)) prop = k0.getProperty(AST.propRenames[autoRenameKey]) } if (!prop && args[0] instanceof ThingRef) { var nl = (<ThingRef>args[0]).namespaceLibrary if (nl && !nl.deleted) prop = nl.getKind().getProperty(t.propRef.data) } if (!prop) { if (prevErr == this.errorCount) this.markError(t, lf("TD112: i cannot find property '{0}' on {1}", t.propRef.data, k0)); prop = new UnresolvedProperty(k0, t.propRef.data); } t.propRef.prop = prop; } if (prop instanceof UnresolvedProperty) { args.slice(1).forEach((p:Expr) => { this.typeCheckExpr(p); }); t._kind = this.core.Unknown; return; } if (prop && prop.parentKind == this.core.App && /^(javascript|import|thumb)/.test(prop.getName())) { this.handleJavascriptImport(t); } var imports = prop.getImports(); if (imports) imports.forEach(imp => { switch (imp.manager) { case "cordova": this.topApp.imports.importCordova(this, null, imp.name, imp.version); break; case "npm": this.topApp.imports.importNpm(this, null, imp.name, imp.version); break; default: Util.assert(false, imp.manager + " not supported"); break; } }); t.autoGet = t.isRefValue(); var decl = prop.forwardsTo(); if (!!decl && decl.deleted) { try { Util.log("deleted decl name: " + decl.getName()) Util.log("deleted decl: " + decl.serialize()) } catch (e) { } Util.check(false, "deleted decl"); // should be handled above decl.deleted = false; // cannot trigger // this.markError(t, "TD113: '{0}' was deleted", t.propRef.data); } var cacc = t.calledExtensionAction() || t.calledAction(); if (cacc) { cacc.markUsed(); if (cacc.isPage()) { t._assignmentInfo = new AssignmentInfo(); t._assignmentInfo.isPagePush = true; } } if ((prop.getFlags() & PropertyFlags.Async) && !t.runAsAsync) { if (this.inAtomic) { if (this.actionSection == ActionSection.Init) { // it's ok } else if (this.actionSection == ActionSection.Display) { var isRun = prop.getName() == "run" && prop.parentKind.isAction if (cacc || isRun) { // TODO: fix this warning to something usable // this.hintsToFlush.push(Util.fmt("'{0}' may call non-atomic actions, which will fail at run time (search for 'atomic display' in the help)", prop.getName())); } else { this.markError(t, lf("TD172: '{0}' cannot be used in page display section (which is treated as 'atomic')", prop.getName())); } } else { this.markError(t, lf("TD158: '{0}' cannot be used in functions marked with 'atomic'", prop.getName())); } } this.seenAwait = true; } if (!prop.isImplementedAnywhere()) { if (prop.getFlags() & PropertyFlags.IsObsolete) this.hintsToFlush.push(lf("'{0}' is obsolete and not implemented", prop.getName())); else this.hintsToFlush.push(lf("'{0}' is currently not implemented", prop.getName())); } else if (Cloud.isRestricted() && prop.getCapability() && ! ((<Property>prop).allowInRestricted || (Cloud.hasPermission("post-raw") && prop.getCapability() == PlatformCapability.Network))) { this.markError(t, lf("TD211: this call is not supported in the restricted profile")) } else if (!Browser.isNodeJS && !this.topApp.canUseProperty(prop)) { this.unsupportedCapability(prop.getName(), prop.getCapability()); } else if (prop.getFlags() & PropertyFlags.IsObsolete) { this.hintsToFlush.push(lf("'{0}' is obsolete and should not be used", prop.getName())); } t._kind = prop.getResult().getKind(); var inP = prop.getParameters(); if (this.countToUpdate > 0) if (this.countToUpdate == 1) prop.getUsage().localCount++; else prop.getUsage().globalCount++; if (topInline) (()=>{ var impl = topInline.implicitAction() if (impl) { var implIdx = -1 inP.forEach((p, i) => { if (InlineActions.isImplicitActionKind(p.getKind())) implIdx = i }) if (implIdx < 0) { this.setNodeError(topInline, lf("TD182: '{0}' doesn't take an implicit inline function", prop)) } else { var tok = AST.mkThing(impl.getName(), true) // this.dispatch(tok) args.splice(implIdx, 0, tok) } } })() var optionsParm = OptionalParameter.optionsParameter(prop) if (optionsParm && inP.length > args.length) (()=>{ var lk = optionsParm.getKind() var rec = lk.getRecord() var maker = new PlaceholderDef() maker._kind = lk maker.escapeDef = { objectToMake: lk, optionalConstructor: topInline, isEmpty: true } var t = mkThing("_libobj_"); (<ThingRef>t).def = maker args.push(t) if (!topInline) return var used:StringMap<boolean> = {} topInline.optionalParameters().forEach(opt => { var fld = lk.getProperty(opt.getName()) var stmt = fld ? fld.forwardsToStmt() : null if (stmt instanceof AST.RecordField) { if (used.hasOwnProperty(opt.getName())) this.setNodeError(opt, lf("TD185: optional parameter '{0}' specified more than once", opt.getName())) used[opt.getName()] = true var rf = <AST.RecordField>stmt opt.recordField = rf maker.escapeDef.isEmpty = false } else if (!opt.getName()) { this.setNodeError(opt, lf("TD193: we need a name for optional parameter of '{0}' (from type '{1}')", prop, lk)) } else { this.setNodeError(opt, lf("TD183: '{0}' doesn't take optional parameter named '{1}' (in type '{2}')", prop, opt.getName(), lk)) } }) topInline = null })() if (topInline && topInline.optionalParameters().length > 0) if (optionsParm) this.markError(t, lf("TD188: '{0}' already has the optional parameters object passed explicitly", prop)) else this.markError(t, lf("TD184: '{0}' doesn't take optional parameters", prop)) if (inP.length < args.length) this.markError(t, lf("TD115: excessive parameter(s) supplied to {0}", prop)); else if (inP.length > args.length) this.markError(t, lf("TD116: not enough parameters supplied to {0}", prop)); var concatOk = (e:Expr) => { var k = e.getKind() if (k == api.core.Unknown) return; if (k == api.core.Nothing || k.singleton || k instanceof AST.LibraryRefKind) this.markError(e, lf("TD117: cannot use this expression as argument to ||; are you missing parenthesis?")); } // args[0] is already typechecked; typechecking it again is exponential if (prop == this.core.StringConcatProp) { this.typeCheckExpr(args[1]); concatOk(args[0]); concatOk(args[1]); if (this.saveFixes) this.fixConcat(t) return; } for (var i = 0; i < args.length; ++i) { if (i >= inP.length) { if (i > 0) this.typeCheckExpr(args[i]); } else { var expK = inP[i].getKind(); if (i == 0 && args[i].getThing() instanceof SingletonDef && expK instanceof LibraryRefKind) { (<ThingRef>args[i]).namespaceLibrary = (<LibraryRefKind>expK).lib; (<ThingRef>args[i]).namespaceLibraryName(); } else { this.expectExpr(args[i], expK, prop.getName(), i == 0); } args[i].languageHint = inP[i].languageHint var str = inP[i].getStringValues() if (str) { var emap = (<any>str).enumMap if (emap) { var lit = args[i].getLiteral() if (typeof lit == "string") { var picMap = inP[i].getStringValueArtIds(); if (picMap) args[i].hintArtId = picMap[lit]; if (str.indexOf(lit) >= 0) { args[i].enumVal = emap.hasOwnProperty(lit) ? emap[lit] : undefined } else { this.markError(args[i], lf("TD199: we didn't expect {0} here; try something like {1}", JSON.stringify(lit), str.map(s => JSON.stringify(s)).join(", ").slice(0, 100))) } } else { this.markError(args[i], lf("TD198: we need an enum string here, something like {0}", str.map(s => JSON.stringify(s)).join(", ").slice(0, 100))) } } else { // hints var lit = args[i].getLiteral() if (typeof lit == "string") { var picMap = inP[i].getStringValueArtIds(); if (picMap) args[i].hintArtId = picMap[lit]; if(str.indexOf(lit) >= 0) args[i].hintVal = lit; } } } if (/^bitmatrix|bitframe$/i.test(args[i].languageHint)) { var lit = args[i].getLiteral(); if (!(typeof lit == "string")) { this.markError(args[i], lf("TD179: we need a string here")); } } } } if (this.saveFixes) this.argumentFixes(t, inP) } private unsupportedCapability(name: string, cap: PlatformCapability) { var missing = App.capabilityString(cap & ~(this.topApp.getPlatform())); if (this.topApp.getPlatformRaw() & PlatformCapability.Current) this.hintsToFlush.push(lf("your current device does not support '{0}'; to develop scripts for other devices, enable the '{1}' capability in the platform settings in the script properties pane", name, missing)); else this.hintsToFlush.push(lf("your current platform settings do not include the '{1}' capability required for '{0}'; you can change platform settings in the script properties pane", name, missing)); if (this.currentAction) this.currentAction.numUnsupported++ } private cloneCall(t:Call, args:Expr[]) { return mkFakeCall(t.propRef, args) } private fixConcat(t:Call) { var prop = t.args[1].getCalledProperty() var c = <Call>t.args[1] if (prop && prop.getResult().getKind() == api.core.Nothing && c.args.length == 1) { t.savedFix = this.cloneCall(c, [this.cloneCall(t, [t.args[0], c.args[0]])]) this.saveFixes++ } } private argumentFixes(t:Call, inP:PropertyParameter[]) { if (t.prop() == api.core.TupleProp) { if (t.args[0].getKind() == api.core.String || t.args[1].getKind() == api.core.String) { t.savedFix = mkFakeCall(PropertyRef.mkProp(api.core.StringConcatProp), t.args.slice(0)) this.saveFixes++ } } else if (inP.length > t.args.length) { var args = t.args.slice(0) var locs = this.snapshotLocals() for (var i = args.length; i < inP.length; ++i) { var toks = Fixer.findDefault(inP[i], locs) var innExpr = ExprParser.parse1(toks) this.typeCheckExpr(innExpr) args.push(innExpr) } t.savedFix = this.cloneCall(t, args) this.saveFixes++ } } } class ClearErrors extends NodeVisitor { public visitAstNode(n:AstNode) { n.clearError() this.visitChildren(n) } } }
the_stack
import { FullIndex } from "data/index"; import { Context, LinkHandler } from "expression/context"; import { resolveSource, Datarow, matchingSourcePaths } from "data/resolver"; import { DataObject, LiteralValue, Values, Task, Grouping } from "data/value"; import { ListQuery, Query, QueryOperation, TableQuery } from "query/query"; import { Result } from "api/result"; import { Field } from "expression/field"; import { QuerySettings } from "settings"; function iden<T>(x: T): T { return x; } /** Operation diagnostics collected during the execution of each query step. */ export interface OperationDiagnostics { timeMs: number; incomingRows: number; outgoingRows: number; errors: { index: number; message: string }[]; } /** The meaning of the 'id' field for a data row - i.e., where it came from. */ export type IdentifierMeaning = { type: "group"; name: string; on: IdentifierMeaning } | { type: "path" }; /** A data row over an object. */ export type Pagerow = Datarow<DataObject>; /** An error during execution. */ export type ExecutionError = { index: number; message: string }; /** The result of executing query operations over incoming data rows; includes timing and error information. */ export interface CoreExecution { data: Pagerow[]; idMeaning: IdentifierMeaning; timeMs: number; ops: QueryOperation[]; diagnostics: OperationDiagnostics[]; } /** Shared execution code which just takes in arbitrary data, runs operations over it, and returns it + per-row errors. */ export function executeCore(rows: Pagerow[], context: Context, ops: QueryOperation[]): Result<CoreExecution, string> { let diagnostics = []; let identMeaning: IdentifierMeaning = { type: "path" }; let startTime = new Date().getTime(); for (let op of ops) { let opStartTime = new Date().getTime(); let incomingRows = rows.length; let errors: { index: number; message: string }[] = []; switch (op.type) { case "where": let whereResult: Pagerow[] = []; for (let index = 0; index < rows.length; index++) { let row = rows[index]; let value = context.evaluate(op.clause, row.data); if (!value.successful) errors.push({ index, message: value.error }); else if (Values.isTruthy(value.value)) whereResult.push(row); } rows = whereResult; break; case "sort": let sortFields = op.fields; let taggedData: { data: Pagerow; fields: LiteralValue[] }[] = []; outer: for (let index = 0; index < rows.length; index++) { let row = rows[index]; let rowSorts: LiteralValue[] = []; for (let sIndex = 0; sIndex < sortFields.length; sIndex++) { let value = context.evaluate(sortFields[sIndex].field, row.data); if (!value.successful) { errors.push({ index, message: value.error }); continue outer; } rowSorts.push(value.value); } taggedData.push({ data: row, fields: rowSorts }); } // Sort rows by the sort fields, and then return the finished result. taggedData.sort((a, b) => { for (let index = 0; index < sortFields.length; index++) { let factor = sortFields[index].direction === "ascending" ? 1 : -1; let le = context.binaryOps .evaluate("<", a.fields[index], b.fields[index], context) .orElse(false); if (Values.isTruthy(le)) return factor * -1; let ge = context.binaryOps .evaluate(">", a.fields[index], b.fields[index], context) .orElse(false); if (Values.isTruthy(ge)) return factor * 1; } return 0; }); rows = taggedData.map(v => v.data); break; case "limit": let limiting = context.evaluate(op.amount); if (!limiting.successful) return Result.failure("Failed to execute 'limit' statement: " + limiting.error); if (!Values.isNumber(limiting.value)) return Result.failure( `Failed to execute 'limit' statement: limit should be a number, but got '${Values.typeOf( limiting.value )}' (${limiting.value})` ); rows = rows.slice(0, limiting.value); break; case "group": let groupData: { data: Pagerow; key: LiteralValue }[] = []; for (let index = 0; index < rows.length; index++) { let value = context.evaluate(op.field.field, rows[index].data); if (!value.successful) { errors.push({ index, message: value.error }); continue; } groupData.push({ data: rows[index], key: value.value }); } // Sort by the key, which we will group on shortly. groupData.sort((a, b) => { let le = context.binaryOps.evaluate("<", a.key, b.key, context).orElse(false); if (Values.isTruthy(le)) return -1; let ge = context.binaryOps.evaluate(">", a.key, b.key, context).orElse(false); if (Values.isTruthy(ge)) return 1; return 0; }); // Then walk through and find fields that are equal. let finalGroupData: { key: LiteralValue; rows: DataObject[]; [groupKey: string]: LiteralValue }[] = []; if (groupData.length > 0) finalGroupData.push({ key: groupData[0].key, rows: [groupData[0].data.data], [op.field.name]: groupData[0].key, }); for (let index = 1; index < groupData.length; index++) { let curr = groupData[index], prev = groupData[index - 1]; if (context.binaryOps.evaluate("=", curr.key, prev.key, context).orElse(false)) { finalGroupData[finalGroupData.length - 1].rows.push(curr.data.data); } else { finalGroupData.push({ key: curr.key, rows: [curr.data.data], [op.field.name]: curr.key, }); } } rows = finalGroupData.map(d => { return { id: d.key, data: d }; }); identMeaning = { type: "group", name: op.field.name, on: identMeaning }; break; case "flatten": let flattenResult: Pagerow[] = []; for (let index = 0; index < rows.length; index++) { let row = rows[index]; let value = context.evaluate(op.field.field, row.data); if (!value.successful) { errors.push({ index, message: value.error }); continue; } let datapoints = Values.isArray(value.value) ? value.value : [value.value]; for (let v of datapoints) { let copy = Values.deepCopy(row); copy.data[op.field.name] = v; flattenResult.push(copy); } } rows = flattenResult; if (identMeaning.type == "group" && identMeaning.name == op.field.name) identMeaning = identMeaning.on; break; default: return Result.failure("Unrecognized query operation '" + op.type + "'"); } if (errors.length >= incomingRows && incomingRows > 0) { return Result.failure(`Every row during operation '${op.type}' failed with an error; first ${Math.min( 3, errors.length )}:\n ${errors .slice(0, 3) .map(d => "- " + d.message) .join("\n")}`); } diagnostics.push({ incomingRows, errors, outgoingRows: rows.length, timeMs: new Date().getTime() - opStartTime, }); } return Result.success({ data: rows, idMeaning: identMeaning, ops, diagnostics, timeMs: new Date().getTime() - startTime, }); } /** Expanded version of executeCore which adds an additional "extraction" step to the pipeline. */ export function executeCoreExtract( rows: Pagerow[], context: Context, ops: QueryOperation[], fields: Record<string, Field> ): Result<CoreExecution, string> { let internal = executeCore(rows, context, ops); if (!internal.successful) return internal; let core = internal.value; let startTime = new Date().getTime(); let errors: ExecutionError[] = []; let res: Pagerow[] = []; outer: for (let index = 0; index < core.data.length; index++) { let page: Pagerow = { id: core.data[index].id, data: {} }; for (let [name, field] of Object.entries(fields)) { let value = context.evaluate(field, core.data[index].data); if (!value.successful) { errors.push({ index: index, message: value.error }); continue outer; } page.data[name] = value.value; } res.push(page); } if (errors.length >= core.data.length && core.data.length > 0) { return Result.failure(`Every row during final data extraction failed with an error; first ${Math.max( errors.length, 3 )}:\n ${errors .slice(0, 3) .map(d => "- " + d.message) .join("\n")}`); } let execTime = new Date().getTime() - startTime; return Result.success({ data: res, idMeaning: core.idMeaning, diagnostics: core.diagnostics.concat([ { timeMs: execTime, incomingRows: core.data.length, outgoingRows: res.length, errors, }, ]), ops: core.ops.concat([{ type: "extract", fields }]), timeMs: core.timeMs + execTime, }); } export interface ListExecution { core: CoreExecution; data: { primary: LiteralValue; value?: LiteralValue }[]; primaryMeaning: IdentifierMeaning; } /** Execute a list-based query, returning the final results. */ export async function executeList( query: Query, index: FullIndex, origin: string, settings: QuerySettings ): Promise<Result<ListExecution, string>> { // Start by collecting all of the files that match the 'from' queries. let fileset = await resolveSource(query.source, index, origin); if (!fileset.successful) return Result.failure(fileset.error); // Extract information about the origin page to add to the root context. let rootContext = new Context(defaultLinkHandler(index, origin), settings, { this: index.pages.get(origin)?.toObject(index) ?? {}, }); let targetField = (query.header as ListQuery).format; let fields: Record<string, Field> = targetField ? { target: targetField } : {}; return executeCoreExtract(fileset.value, rootContext, query.operations, fields).map(core => { let data = core.data.map(p => iden({ primary: p.id, value: p.data["target"] ?? undefined, }) ); return { primaryMeaning: core.idMeaning, core, data }; }); } /** Result of executing a table query. */ export interface TableExecution { core: CoreExecution; names: string[]; data: { id: LiteralValue; values: LiteralValue[] }[]; idMeaning: IdentifierMeaning; } /** Execute a table query. */ export async function executeTable( query: Query, index: FullIndex, origin: string, settings: QuerySettings ): Promise<Result<TableExecution, string>> { // Start by collecting all of the files that match the 'from' queries. let fileset = await resolveSource(query.source, index, origin); if (!fileset.successful) return Result.failure(fileset.error); // Extract information about the origin page to add to the root context. let rootContext = new Context(defaultLinkHandler(index, origin), settings, { this: index.pages.get(origin)?.toObject(index) ?? {}, }); let targetFields = (query.header as TableQuery).fields; let fields: Record<string, Field> = {}; for (let field of targetFields) fields[field.name] = field.field; return executeCoreExtract(fileset.value, rootContext, query.operations, fields).map(core => { let names = targetFields.map(f => f.name); let data = core.data.map(p => iden({ id: p.id, values: targetFields.map(f => p.data[f.name]), }) ); return { core, names, data, idMeaning: core.idMeaning }; }); } /** The result of executing a task query. */ export interface TaskExecution { core: CoreExecution; tasks: Grouping<Task[]>; } /** Maps a raw core execution result to a task grouping which is much easier to */ function extractTaskGroupings(id: IdentifierMeaning, rows: DataObject[]): Grouping<Task[]> { switch (id.type) { case "path": return { type: "base", value: rows.map(r => Task.fromObject(r)) }; case "group": let key = id.name; return { type: "grouped", groups: rows.map(r => iden({ key: r[key], value: extractTaskGroupings(id.on, r.rows as DataObject[]), }) ), }; } } /** Execute a task query, returning all matching tasks. */ export async function executeTask( query: Query, origin: string, index: FullIndex, settings: QuerySettings ): Promise<Result<TaskExecution, string>> { let fileset = matchingSourcePaths(query.source, index, origin); if (!fileset.successful) return Result.failure(fileset.error); // Collect tasks from pages which match. let incomingTasks: Pagerow[] = []; for (let path of fileset.value) { let page = index.pages.get(path); if (!page) continue; let pageData = page.toObject(index); let rpage = page; let pageTasks = page.tasks.map(t => { let copy = t.toObject(); // Add page data to this copy. for (let [key, value] of Object.entries(pageData)) { if (key in copy) continue; copy[key] = value; } return { id: `${rpage.path}#${t.line}`, data: copy }; }); for (let task of pageTasks) incomingTasks.push(task); } // Extract information about the origin page to add to the root context. let rootContext = new Context(defaultLinkHandler(index, origin), settings, { this: index.pages.get(origin)?.toObject(index) ?? {}, }); return executeCore(incomingTasks, rootContext, query.operations).map(core => { return { core, tasks: extractTaskGroupings( core.idMeaning, core.data.map(r => r.data) ), }; }); } /** Execute a single field inline a file, returning the evaluated result. */ export function executeInline( field: Field, origin: string, index: FullIndex, settings: QuerySettings ): Result<LiteralValue, string> { return new Context(defaultLinkHandler(index, origin), settings, { this: index.pages.get(origin)?.toObject(index) ?? {}, }).evaluate(field); } /** The default link resolver used when creating contexts. */ export function defaultLinkHandler(index: FullIndex, origin: string): LinkHandler { return { resolve: link => { let realFile = index.metadataCache.getFirstLinkpathDest(link, origin); if (!realFile) return null; let realPage = index.pages.get(realFile.path); if (!realPage) return null; return realPage.toObject(index); }, normalize: link => { let realFile = index.metadataCache.getFirstLinkpathDest(link, origin); return realFile?.path ?? link; }, exists: link => { let realFile = index.metadataCache.getFirstLinkpathDest(link, origin); return !!realFile; }, }; }
the_stack
import 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js'; import 'chrome://resources/cr_elements/shared_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import 'chrome://resources/cr_elements/cr_tabs/cr_tabs.js'; import 'chrome://resources/polymer/v3_0/iron-media-query/iron-media-query.js'; import 'chrome://resources/polymer/v3_0/iron-pages/iron-pages.js'; import './history_clusters/clusters.js'; import './history_list.js'; import './history_toolbar.js'; import './query_manager.js'; import './shared_style.js'; import './side_bar.js'; import './strings.m.js'; import {CrDrawerElement} from 'chrome://resources/cr_elements/cr_drawer/cr_drawer.js'; import {CrLazyRenderElement} from 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js'; import {FindShortcutMixin, FindShortcutMixinInterface} from 'chrome://resources/cr_elements/find_shortcut_mixin.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {hasKeyModifiers} from 'chrome://resources/js/util.m.js'; import {WebUIListenerMixin, WebUIListenerMixinInterface} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {IronA11yAnnouncer} from 'chrome://resources/polymer/v3_0/iron-a11y-announcer/iron-a11y-announcer.js'; import {IronPagesElement} from 'chrome://resources/polymer/v3_0/iron-pages/iron-pages.js'; import {IronScrollTargetBehavior} from 'chrome://resources/polymer/v3_0/iron-scroll-target-behavior/iron-scroll-target-behavior.js'; import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {BrowserService} from './browser_service.js'; import {HistoryPageViewHistogram} from './constants.js'; import {ForeignSession, QueryResult, QueryState} from './externs.js'; import {HistoryListElement} from './history_list.js'; import {HistoryToolbarElement} from './history_toolbar.js'; import {HistoryQueryManagerElement} from './query_manager.js'; import {Page, TABBED_PAGES} from './router.js'; import {FooterInfo} from './side_bar.js'; let lazyLoadPromise: Promise<void>|null = null; export function ensureLazyLoaded(): Promise<void> { if (!lazyLoadPromise) { const script = document.createElement('script'); script.type = 'module'; script.src = './lazy_load.js'; document.body.appendChild(script); lazyLoadPromise = Promise.all([ customElements.whenDefined('history-synced-device-manager'), customElements.whenDefined('cr-action-menu'), customElements.whenDefined('cr-button'), customElements.whenDefined('cr-checkbox'), customElements.whenDefined('cr-dialog'), customElements.whenDefined('cr-drawer'), customElements.whenDefined('cr-icon-button'), customElements.whenDefined('cr-toolbar-selection-overlay'), ]) as unknown as Promise<void>; } return lazyLoadPromise; } // Adds click/auxclick listeners for any link on the page. If the link points // to a chrome: or file: url, then calls into the browser to do the // navigation. Note: This method is *not* re-entrant. Every call to it, will // re-add listeners on |document|. It's up to callers to ensure this is only // called once. export function listenForPrivilegedLinkClicks() { ['click', 'auxclick'].forEach(function(eventName) { document.addEventListener(eventName, function(evt: Event) { const e = evt as MouseEvent; // Ignore buttons other than left and middle. if (e.button > 1 || e.defaultPrevented) { return; } const eventPath = e.composedPath() as Array<HTMLElement>; let anchor: HTMLAnchorElement|null = null; if (eventPath) { for (let i = 0; i < eventPath.length; i++) { const element = eventPath[i]; if (element.tagName === 'A' && (element as HTMLAnchorElement).href) { anchor = element as HTMLAnchorElement; break; } } } // Fallback if Event.path is not available. let el = e.target as HTMLElement; if (!anchor && el.nodeType === Node.ELEMENT_NODE && el.webkitMatchesSelector('A, A *')) { while (el.tagName !== 'A') { el = el.parentElement as HTMLElement; } anchor = el as HTMLAnchorElement; } if (!anchor) { return; } if ((anchor.protocol === 'file:' || anchor.protocol === 'about:') && (e.button === 0 || e.button === 1)) { BrowserService.getInstance().navigateToUrl( anchor.href, anchor.target, e); e.preventDefault(); } }); }); } declare global { interface Window { // https://github.com/microsoft/TypeScript/issues/40807 requestIdleCallback(callback: () => void): void; } } export interface HistoryAppElement { $: { 'content': IronPagesElement, 'drawer': CrLazyRenderElement<CrDrawerElement>, 'history': HistoryListElement, 'tabs-container': Element, 'tabs-content': IronPagesElement, 'toolbar': HistoryToolbarElement, }; } const HistoryAppElementBase = mixinBehaviors( [IronScrollTargetBehavior], FindShortcutMixin(WebUIListenerMixin(PolymerElement))) as { new (): PolymerElement & FindShortcutMixinInterface & IronScrollTargetBehavior & WebUIListenerMixinInterface }; export class HistoryAppElement extends HistoryAppElementBase { static get is() { return 'history-app'; } static get properties() { return { // The id of the currently selected page. selectedPage_: { type: String, observer: 'selectedPageChanged_', }, queryResult_: Object, // Updated on synced-device-manager attach by chrome.sending // 'otherDevicesInitialized'. isUserSignedIn_: Boolean, pendingDelete_: Boolean, toolbarShadow_: { type: Boolean, reflectToAttribute: true, notify: true, }, queryState_: Object, // True if the window is narrow enough for the page to have a drawer. hasDrawer_: { type: Boolean, observer: 'hasDrawerChanged_', }, footerInfo: { type: Object, value() { return { managed: loadTimeData.getBoolean('isManaged'), otherFormsOfHistory: false, }; }, }, historyClustersEnabled_: { type: Boolean, value: () => loadTimeData.getBoolean('isHistoryClustersEnabled'), }, historyClustersVisible_: { type: Boolean, value: () => loadTimeData.getBoolean('isHistoryClustersVisible'), }, showHistoryClusters_: { type: Boolean, computed: 'computeShowHistoryClusters_(historyClustersEnabled_, historyClustersVisible_)', reflectToAttribute: true, }, // The index of the currently selected tab. selectedTab_: { type: Number, observer: 'selectedTabChanged_', }, tabsIcons_: { type: Array, value: () => ['images/list.svg', 'images/journeys.svg'], }, tabsNames_: { type: Array, value: () => { return [ loadTimeData.getString('historyListTabLabel'), loadTimeData.getString('historyClustersTabLabel') ]; }, }, }; } footerInfo: FooterInfo; private browserService_: BrowserService|null = null; private eventTracker_: EventTracker = new EventTracker(); private hasDrawer_: boolean; private historyClustersEnabled_: boolean; private historyClustersVisible_: boolean; private isUserSignedIn_: boolean = loadTimeData.getBoolean('isUserSignedIn'); private pendingDelete_: boolean; private queryResult_: QueryResult; private queryState_: QueryState; private selectedPage_: Page; private selectedTab_: number; private showHistoryClusters_: boolean; private tabsIcons_: Array<string>; private tabsNames_: Array<string>; private toolbarShadow_: boolean; constructor() { super(); this.queryResult_ = { info: undefined, results: undefined, sessionList: undefined, }; listenForPrivilegedLinkClicks(); } /** @override */ connectedCallback() { super.connectedCallback(); this.eventTracker_.add( document, 'keydown', e => this.onKeyDown_(e as KeyboardEvent)); this.addWebUIListener( 'sign-in-state-changed', (signedIn: boolean) => this.onSignInStateChanged_(signedIn)); this.addWebUIListener( 'has-other-forms-changed', (hasOtherForms: boolean) => this.onHasOtherFormsChanged_(hasOtherForms)); this.addWebUIListener( 'foreign-sessions-changed', (sessionList: Array<ForeignSession>) => this.setForeignSessions_(sessionList)); this.browserService_ = BrowserService.getInstance(); this.shadowRoot!.querySelector('history-query-manager')!.initialize(); this.browserService_!.getForeignSessions().then( sessionList => this.setForeignSessions_(sessionList)); } ready() { super.ready(); this.addEventListener('cr-toolbar-menu-tap', this.onCrToolbarMenuTap_); this.addEventListener('delete-selected', this.deleteSelected); this.addEventListener('history-checkbox-select', this.checkboxSelected); this.addEventListener('history-close-drawer', this.closeDrawer_); this.addEventListener('history-view-changed', this.historyViewChanged_); this.addEventListener('unselect-all', this.unselectAll); } /** @override */ disconnectedCallback() { super.disconnectedCallback(); this.eventTracker_.removeAll(); } private fire_(eventName: string, detail?: any) { this.dispatchEvent( new CustomEvent(eventName, {bubbles: true, composed: true, detail})); } private computeShowHistoryClusters_(): boolean { return this.historyClustersEnabled_ && this.historyClustersVisible_; } private historyClustersSelected_( _selectedPage: Page, _showHistoryClusters: boolean): boolean { return this.selectedPage_ === Page.HISTORY_CLUSTERS && this.showHistoryClusters_; } private onFirstRender_() { setTimeout(() => { this.browserService_!.recordTime( 'History.ResultsRenderedTime', window.performance.now()); }); // Focus the search field on load. Done here to ensure the history page // is rendered before we try to take focus. const searchField = this.$.toolbar.searchField; if (!searchField.narrow) { searchField.getSearchInput().focus(); } // Lazily load the remainder of the UI. ensureLazyLoaded().then(function() { window.requestIdleCallback(function() { // https://github.com/microsoft/TypeScript/issues/13569 (document as any).fonts.load('bold 12px Roboto'); }); }); } /** Overridden from IronScrollTargetBehavior */ _scrollHandler() { if (this.scrollTarget) { // When the tabs are visible, show the toolbar shadow for the synced // devices page only. this.toolbarShadow_ = this.scrollTarget.scrollTop !== 0 && (!this.showHistoryClusters_ || this.syncedTabsSelected_(this.selectedPage_!)); } } private onCrToolbarMenuTap_() { this.$.drawer.get().toggle(); } /** * Listens for history-item being selected or deselected (through checkbox) * and changes the view of the top toolbar. */ checkboxSelected() { this.$.toolbar.count = this.$.history.getSelectedItemCount(); } selectOrUnselectAll() { this.$.history.selectOrUnselectAll(); this.$.toolbar.count = this.$.history.getSelectedItemCount(); } /** * Listens for call to cancel selection and loops through all items to set * checkbox to be unselected. */ private unselectAll() { this.$.history.unselectAllItems(); this.$.toolbar.count = 0; } deleteSelected() { this.$.history.deleteSelectedWithPrompt(); } private onQueryFinished_() { this.$.history.historyResult( this.queryResult_.info!, this.queryResult_.results!); if (document.body.classList.contains('loading')) { document.body.classList.remove('loading'); this.onFirstRender_(); } } private onKeyDown_(e: KeyboardEvent) { if ((e.key === 'Delete' || e.key === 'Backspace') && !hasKeyModifiers(e)) { this.onDeleteCommand_(); return; } if (e.key === 'a' && !e.altKey && !e.shiftKey) { let hasTriggerModifier = e.ctrlKey && !e.metaKey; // <if expr="is_macosx"> hasTriggerModifier = !e.ctrlKey && e.metaKey; // </if> if (hasTriggerModifier && this.onSelectAllCommand_()) { e.preventDefault(); } } if (e.key === 'Escape') { this.unselectAll(); IronA11yAnnouncer.requestAvailability(); this.fire_( 'iron-announce', {text: loadTimeData.getString('itemsUnselected')}); e.preventDefault(); } } private onDeleteCommand_() { if (this.$.toolbar.count === 0 || this.pendingDelete_) { return; } this.deleteSelected(); } /** * @return Whether the command was actually triggered. */ private onSelectAllCommand_(): boolean { if (this.$.toolbar.searchField.isSearchFocused() || this.syncedTabsSelected_(this.selectedPage_!) || this.historyClustersSelected_( this.selectedPage_!, this.showHistoryClusters_)) { return false; } this.selectOrUnselectAll(); return true; } /** * @param sessionList Array of objects describing the sessions from other * devices. */ private setForeignSessions_(sessionList: Array<ForeignSession>) { this.set('queryResult_.sessionList', sessionList); } /** * Update sign in state of synced device manager after user logs in or out. */ private onSignInStateChanged_(isUserSignedIn: boolean) { this.isUserSignedIn_ = isUserSignedIn; } /** * Update sign in state of synced device manager after user logs in or out. */ private onHasOtherFormsChanged_(hasOtherForms: boolean) { this.set('footerInfo.otherFormsOfHistory', hasOtherForms); } private syncedTabsSelected_(_selectedPage: Page): boolean { return this.selectedPage_ === Page.SYNCED_TABS; } /** * @return Whether a loading spinner should be shown (implies the * backend is querying a new search term). */ private shouldShowSpinner_( querying: boolean, incremental: boolean, searchTerm: string): boolean { return querying && !incremental && searchTerm !== ''; } private selectedPageChanged_() { this.unselectAll(); this.historyViewChanged_(); this.maybeUpdateSelectedHistoryTab_(); } private updateScrollTarget_() { const topLevelIronPages = this.$['content']; const lowerLevelIronPages = this.$['tabs-content']; const topLevelHistoryPage = this.$['tabs-container']; if (topLevelIronPages.selectedItem && topLevelIronPages.selectedItem === topLevelHistoryPage) { // The top-level History page has another inner IronPages element that // can toggle between different pages. If this is the case, set the // scroll target to the currently selected inner tab. this.scrollTarget = lowerLevelIronPages.selectedItem as HTMLElement; } else if (topLevelIronPages.selectedItem) { this.scrollTarget = topLevelIronPages.selectedItem as HTMLElement; } else { this.scrollTarget = null; } } private selectedTabChanged_() { // Change in the currently selected tab requires change in the currently // selected page. this.selectedPage_ = TABBED_PAGES[this.selectedTab_]; } private maybeUpdateSelectedHistoryTab_() { // Change in the currently selected page may require change in the currently // selected tab. if (TABBED_PAGES.includes(this.selectedPage_)) { this.selectedTab_ = TABBED_PAGES.indexOf(this.selectedPage_); } } private historyViewChanged_() { // This allows the synced-device-manager to render so that it can be set // as the scroll target. requestAnimationFrame(() => { this._scrollHandler(); }); this.recordHistoryPageView_(); } private hasDrawerChanged_() { const drawer = this.$.drawer.getIfExists(); if (!this.hasDrawer_ && drawer && drawer.open) { drawer.cancel(); } } /** * This computed binding is needed to make the iron-pages selector update * when <synced-device-manager> or <history-clusters> is instantiated for the * first time. Otherwise the fallback selection will continue to be used after * the corresponding item is added as a child of iron-pages. */ private getSelectedPage_(selectedPage: string, _items: Array<any>): string { return selectedPage; } private closeDrawer_() { const drawer = this.$.drawer.get() as CrDrawerElement; if (drawer && drawer.open) { drawer.close(); } } private recordHistoryPageView_() { let histogramValue = HistoryPageViewHistogram.END; switch (this.selectedPage_) { case Page.HISTORY_CLUSTERS: histogramValue = HistoryPageViewHistogram.JOURNEYS; break; case Page.SYNCED_TABS: histogramValue = this.isUserSignedIn_ ? HistoryPageViewHistogram.SYNCED_TABS : HistoryPageViewHistogram.SIGNIN_PROMO; break; default: histogramValue = HistoryPageViewHistogram.HISTORY; break; } this.browserService_!.recordHistogram( 'History.HistoryPageView', histogramValue, HistoryPageViewHistogram.END); } // Override FindShortcutMixin methods. handleFindShortcut(modalContextOpen: boolean): boolean { if (modalContextOpen) { return false; } this.$.toolbar.searchField.showAndFocus(); return true; } // Override FindShortcutMixin methods. searchInputHasFocus(): boolean { return this.$.toolbar.searchField.isSearchFocused(); } static get template() { return html`{__html_template__}`; } } customElements.define(HistoryAppElement.is, HistoryAppElement);
the_stack
import { IExecuteFunctions, WAIT_TIME_UNLIMITED, } from 'n8n-core'; import { IDataObject, INodeExecutionData, INodeType, INodeTypeDescription, IWebhookFunctions, IWebhookResponseData, NodeOperationError, } from 'n8n-workflow'; import * as basicAuth from 'basic-auth'; import { Response } from 'express'; import * as fs from 'fs'; import * as formidable from 'formidable'; function authorizationError(resp: Response, realm: string, responseCode: number, message?: string) { if (message === undefined) { message = 'Authorization problem!'; if (responseCode === 401) { message = 'Authorization is required!'; } else if (responseCode === 403) { message = 'Authorization data is wrong!'; } } resp.writeHead(responseCode, { 'WWW-Authenticate': `Basic realm="${realm}"` }); resp.end(message); return { noWebhookResponse: true, }; } export class Wait implements INodeType { description: INodeTypeDescription = { displayName: 'Wait', name: 'wait', icon: 'fa:pause-circle', group: ['organization'], version: 1, description: 'Wait before continue with execution', defaults: { name: 'Wait', color: '#804050', }, inputs: ['main'], outputs: ['main'], credentials: [ { name: 'httpBasicAuth', required: true, displayOptions: { show: { incomingAuthentication: [ 'basicAuth', ], }, }, }, { name: 'httpHeaderAuth', required: true, displayOptions: { show: { incomingAuthentication: [ 'headerAuth', ], }, }, }, ], webhooks: [ { name: 'default', httpMethod: '={{$parameter["httpMethod"]}}', isFullPath: true, responseCode: '={{$parameter["responseCode"]}}', responseMode: '={{$parameter["responseMode"]}}', responseData: '={{$parameter["responseData"]}}', responseBinaryPropertyName: '={{$parameter["responseBinaryPropertyName"]}}', responseContentType: '={{$parameter["options"]["responseContentType"]}}', responsePropertyName: '={{$parameter["options"]["responsePropertyName"]}}', responseHeaders: '={{$parameter["options"]["responseHeaders"]}}', path: '={{$parameter["options"]["webhookSuffix"] || ""}}', restartWebhook: true, }, ], properties: [ { displayName: 'Webhook authentication', name: 'incomingAuthentication', type: 'options', displayOptions: { show: { resume: [ 'webhook', ], }, }, options: [ { name: 'Basic Auth', value: 'basicAuth', }, { name: 'Header Auth', value: 'headerAuth', }, { name: 'None', value: 'none', }, ], default: 'none', description: 'If and how incoming resume-webhook-requests to $resumeWebhookUrl should be authenticated for additional security.', }, { displayName: 'Resume', name: 'resume', type: 'options', options: [ { name: 'After time interval', value: 'timeInterval', description: 'Waits for a certain amount of time', }, { name: 'At specified time', value: 'specificTime', description: 'Waits until a specific date and time to continue', }, { name: 'On webhook call', value: 'webhook', description: 'Waits for a webhook call before continuing', }, ], default: 'timeInterval', description: 'Determines the waiting mode to use before the workflow continues', }, // ---------------------------------- // resume:specificTime // ---------------------------------- { displayName: 'Date and Time', name: 'dateTime', type: 'dateTime', displayOptions: { show: { resume: [ 'specificTime', ], }, }, default: '', description: 'The date and time to wait for before continuing', }, // ---------------------------------- // resume:timeInterval // ---------------------------------- { displayName: 'Wait Amount', name: 'amount', type: 'number', displayOptions: { show: { resume: [ 'timeInterval', ], }, }, typeOptions: { minValue: 0, numberPrecision: 2, }, default: 1, description: 'The time to wait', }, { displayName: 'Wait Unit', name: 'unit', type: 'options', displayOptions: { show: { resume: [ 'timeInterval', ], }, }, options: [ { name: 'Seconds', value: 'seconds', }, { name: 'Minutes', value: 'minutes', }, { name: 'Hours', value: 'hours', }, { name: 'Days', value: 'days', }, ], default: 'hours', description: 'The time unit of the Wait Amount value', }, // ---------------------------------- // resume:webhook // ---------------------------------- { displayName: 'The webhook URL will be generated at run time. It can be referenced with the <strong>$resumeWebhookUrl</strong> variable. Send it somewhere before getting to this node. <a href="https://docs.n8n.io/nodes/n8n-nodes-base.wait?utm_source=n8n_app&utm_medium=node_settings_modal-credential_link&utm_campaign=n8n-nodes-base.wait" target="_blank">More info</a>', name: 'webhookNotice', type: 'notice', displayOptions: { show: { resume: [ 'webhook', ], }, }, default: '', }, { displayName: 'HTTP Method', name: 'httpMethod', type: 'options', displayOptions: { show: { resume: [ 'webhook', ], }, }, options: [ { name: 'GET', value: 'GET', }, { name: 'HEAD', value: 'HEAD', }, { name: 'POST', value: 'POST', }, ], default: 'GET', description: 'The HTTP method of the Webhook call', }, { displayName: 'Response Code', name: 'responseCode', type: 'number', displayOptions: { show: { resume: [ 'webhook', ], }, }, typeOptions: { minValue: 100, maxValue: 599, }, default: 200, description: 'The HTTP Response code to return', }, { displayName: 'Respond', name: 'responseMode', type: 'options', displayOptions: { show: { resume: [ 'webhook', ], }, }, options: [ { name: 'Immediately', value: 'onReceived', description: 'As soon as this node executes', }, { name: 'When last node finishes', value: 'lastNode', description: 'Returns data of the last-executed node', }, { name: 'Using \'Respond to Webhook\' node', value: 'responseNode', description: 'Response defined in that node', }, ], default: 'onReceived', description: 'When and how to respond to the webhook', }, { displayName: 'Response Data', name: 'responseData', type: 'options', displayOptions: { show: { resume: [ 'webhook', ], responseMode: [ 'lastNode', ], }, }, options: [ { name: 'All Entries', value: 'allEntries', description: 'Returns all the entries of the last node. Always returns an array', }, { name: 'First Entry JSON', value: 'firstEntryJson', description: 'Returns the JSON data of the first entry of the last node. Always returns a JSON object', }, { name: 'First Entry Binary', value: 'firstEntryBinary', description: 'Returns the binary data of the first entry of the last node. Always returns a binary file', }, ], default: 'firstEntryJson', description: 'What data should be returned. If it should return all the items as array or only the first item as object', }, { displayName: 'Property Name', name: 'responseBinaryPropertyName', type: 'string', required: true, default: 'data', displayOptions: { show: { resume: [ 'webhook', ], responseData: [ 'firstEntryBinary', ], }, }, description: 'Name of the binary property to return', }, { displayName: 'Limit wait time', name: 'limitWaitTime', type: 'boolean', default: false, description: `If no webhook call is received, the workflow will automatically resume execution after the specified limit type`, displayOptions: { show: { resume: [ 'webhook', ], }, }, }, { displayName: 'Limit type', name: 'limitType', type: 'options', default: 'afterTimeInterval', description: `Sets the condition for the execution to resume. Can be a specified date or after some time.`, displayOptions: { show: { limitWaitTime: [ true, ], resume: [ 'webhook', ], }, }, options: [ { name: 'After time interval', description: 'Waits for a certain amount of time', value: 'afterTimeInterval', }, { name: 'At specified time', description: 'Waits until the set date and time to continue', value: 'atSpecifiedTime', }, ], }, { displayName: 'Amount', name: 'resumeAmount', type: 'number', displayOptions: { show: { limitType: [ 'afterTimeInterval', ], limitWaitTime: [ true, ], resume: [ 'webhook', ], }, }, typeOptions: { minValue: 0, numberPrecision: 2, }, default: 1, description: 'The time to wait', }, { displayName: 'Unit', name: 'resumeUnit', type: 'options', displayOptions: { show: { limitType: [ 'afterTimeInterval', ], limitWaitTime: [ true, ], resume: [ 'webhook', ], }, }, options: [ { name: 'Seconds', value: 'seconds', }, { name: 'Minutes', value: 'minutes', }, { name: 'Hours', value: 'hours', }, { name: 'Days', value: 'days', }, ], default: 'hours', description: 'Unit of the interval value', }, { displayName: 'Max Date and Time', name: 'maxDateAndTime', type: 'dateTime', displayOptions: { show: { limitType: [ 'atSpecifiedTime', ], limitWaitTime: [ true, ], resume: [ 'webhook', ], }, }, default: '', description: 'Continue execution after the specified date and time', }, { displayName: 'Options', name: 'options', type: 'collection', displayOptions: { show: { resume: [ 'webhook', ], }, }, placeholder: 'Add Option', default: {}, options: [ { displayName: 'Binary Data', name: 'binaryData', type: 'boolean', displayOptions: { show: { '/httpMethod': [ 'POST', ], }, }, default: false, description: 'Set to true if webhook will receive binary data', }, { displayName: 'Binary Property', name: 'binaryPropertyName', type: 'string', default: 'data', required: true, displayOptions: { show: { binaryData: [ true, ], }, }, description: `Name of the binary property to which to write the data of the received file. If the data gets received via "Form-Data Multipart" it will be the prefix and a number starting with 0 will be attached to it.`, }, { displayName: 'Response Data', name: 'responseData', type: 'string', displayOptions: { show: { '/responseMode': [ 'onReceived', ], }, }, default: '', placeholder: 'success', description: 'Custom response data to send', }, { displayName: 'Response Content-Type', name: 'responseContentType', type: 'string', displayOptions: { show: { '/responseData': [ 'firstEntryJson', ], '/responseMode': [ 'lastNode', ], }, }, default: '', placeholder: 'application/xml', description: 'Set a custom content-type to return if another one as the "application/json" should be returned', }, { displayName: 'Response Headers', name: 'responseHeaders', placeholder: 'Add Response Header', description: 'Add headers to the webhook response', type: 'fixedCollection', typeOptions: { multipleValues: true, }, default: {}, options: [ { name: 'entries', displayName: 'Entries', values: [ { displayName: 'Name', name: 'name', type: 'string', default: '', description: 'Name of the header', }, { displayName: 'Value', name: 'value', type: 'string', default: '', description: 'Value of the header', }, ], }, ], }, { displayName: 'Property Name', name: 'responsePropertyName', type: 'string', displayOptions: { show: { '/responseData': [ 'firstEntryJson', ], '/responseMode': [ 'lastNode', ], }, }, default: 'data', description: 'Name of the property to return the data of instead of the whole JSON', }, { displayName: 'Webhook Suffix', name: 'webhookSuffix', type: 'string', default: '', placeholder: 'webhook', description: 'This suffix path will be appended to the restart URL. Helpful when using multiple wait nodes. Note: Does not support expressions.', }, // { // displayName: 'Raw Body', // name: 'rawBody', // type: 'boolean', // displayOptions: { // hide: { // binaryData: [ // true, // ], // }, // }, // default: false, // description: 'Raw body (binary)', // }, ], }, ], }; async webhook(this: IWebhookFunctions): Promise<IWebhookResponseData> { // INFO: Currently (20.06.2021) 100% identical with Webook-Node const incomingAuthentication = this.getNodeParameter('incomingAuthentication') as string; const options = this.getNodeParameter('options', {}) as IDataObject; const req = this.getRequestObject(); const resp = this.getResponseObject(); const headers = this.getHeaderData(); const realm = 'Webhook'; if (incomingAuthentication === 'basicAuth') { // Basic authorization is needed to call webhook const httpBasicAuth = await this.getCredentials('httpBasicAuth'); if (httpBasicAuth === undefined || !httpBasicAuth.user || !httpBasicAuth.password) { // Data is not defined on node so can not authenticate return authorizationError(resp, realm, 500, 'No authentication data defined on node!'); } const basicAuthData = basicAuth(req); if (basicAuthData === undefined) { // Authorization data is missing return authorizationError(resp, realm, 401); } if (basicAuthData.name !== httpBasicAuth!.user || basicAuthData.pass !== httpBasicAuth!.password) { // Provided authentication data is wrong return authorizationError(resp, realm, 403); } } else if (incomingAuthentication === 'headerAuth') { // Special header with value is needed to call webhook const httpHeaderAuth = await this.getCredentials('httpHeaderAuth'); if (httpHeaderAuth === undefined || !httpHeaderAuth.name || !httpHeaderAuth.value) { // Data is not defined on node so can not authenticate return authorizationError(resp, realm, 500, 'No authentication data defined on node!'); } const headerName = (httpHeaderAuth.name as string).toLowerCase(); const headerValue = (httpHeaderAuth.value as string); if (!headers.hasOwnProperty(headerName) || (headers as IDataObject)[headerName] !== headerValue) { // Provided authentication data is wrong return authorizationError(resp, realm, 403); } } // @ts-ignore const mimeType = headers['content-type'] || 'application/json'; if (mimeType.includes('multipart/form-data')) { // @ts-ignore const form = new formidable.IncomingForm({ multiples: true }); return new Promise((resolve, reject) => { form.parse(req, async (err, data, files) => { const returnItem: INodeExecutionData = { binary: {}, json: { headers, params: this.getParamsData(), query: this.getQueryData(), body: data, }, }; let count = 0; for (const xfile of Object.keys(files)) { const processFiles: formidable.File[] = []; let multiFile = false; if (Array.isArray(files[xfile])) { processFiles.push(...files[xfile] as formidable.File[]); multiFile = true; } else { processFiles.push(files[xfile] as formidable.File); } let fileCount = 0; for (const file of processFiles) { let binaryPropertyName = xfile; if (binaryPropertyName.endsWith('[]')) { binaryPropertyName = binaryPropertyName.slice(0, -2); } if (multiFile === true) { binaryPropertyName += fileCount++; } if (options.binaryPropertyName) { binaryPropertyName = `${options.binaryPropertyName}${count}`; } const fileJson = file.toJSON() as unknown as IDataObject; const fileContent = await fs.promises.readFile(file.path); returnItem.binary![binaryPropertyName] = await this.helpers.prepareBinaryData(Buffer.from(fileContent), fileJson.name as string, fileJson.type as string); count += 1; } } resolve({ workflowData: [ [ returnItem, ], ], }); }); }); } if (options.binaryData === true) { return new Promise((resolve, reject) => { const binaryPropertyName = options.binaryPropertyName || 'data'; const data: Buffer[] = []; req.on('data', (chunk) => { data.push(chunk); }); req.on('end', async () => { const returnItem: INodeExecutionData = { binary: {}, json: { headers, params: this.getParamsData(), query: this.getQueryData(), body: this.getBodyData(), }, }; returnItem.binary![binaryPropertyName as string] = await this.helpers.prepareBinaryData(Buffer.concat(data)); return resolve({ workflowData: [ [ returnItem, ], ], }); }); req.on('error', (error) => { throw new NodeOperationError(this.getNode(), error); }); }); } const response: INodeExecutionData = { json: { headers, params: this.getParamsData(), query: this.getQueryData(), body: this.getBodyData(), }, }; if (options.rawBody) { response.binary = { data: { // @ts-ignore data: req.rawBody.toString(BINARY_ENCODING), mimeType, }, }; } let webhookResponse: string | undefined; if (options.responseData) { webhookResponse = options.responseData as string; } return { webhookResponse, workflowData: [ [ response, ], ], }; } async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> { const resume = this.getNodeParameter('resume', 0) as string; if (resume === 'webhook') { let waitTill = new Date(WAIT_TIME_UNLIMITED); const limitWaitTime = this.getNodeParameter('limitWaitTime', 0); if (limitWaitTime === true) { const limitType = this.getNodeParameter('limitType', 0); if (limitType === 'afterTimeInterval') { let waitAmount = this.getNodeParameter('resumeAmount', 0) as number; const resumeUnit = this.getNodeParameter('resumeUnit', 0); if (resumeUnit === 'minutes') { waitAmount *= 60; } if (resumeUnit === 'hours') { waitAmount *= 60 * 60; } if (resumeUnit === 'days') { waitAmount *= 60 * 60 * 24; } waitAmount *= 1000; waitTill = new Date(new Date().getTime() + waitAmount); } else { waitTill = new Date(this.getNodeParameter('maxDateAndTime', 0) as string); } } await this.putExecutionToWait(waitTill); return [this.getInputData()]; } let waitTill: Date; if (resume === 'timeInterval') { const unit = this.getNodeParameter('unit', 0) as string; let waitAmount = this.getNodeParameter('amount', 0) as number; if (unit === 'minutes') { waitAmount *= 60; } if (unit === 'hours') { waitAmount *= 60 * 60; } if (unit === 'days') { waitAmount *= 60 * 60 * 24; } waitAmount *= 1000; waitTill = new Date(new Date().getTime() + waitAmount); } else { // resume: dateTime const dateTime = this.getNodeParameter('dateTime', 0) as string; waitTill = new Date(dateTime); } const waitValue = Math.max(waitTill.getTime() - new Date().getTime(), 0); if (waitValue < 65000) { // If wait time is shorter than 65 seconds leave execution active because // we just check the database every 60 seconds. return new Promise((resolve, reject) => { setTimeout(() => { resolve([this.getInputData()]); }, waitValue); }); } // If longer than 60 seconds put execution to wait await this.putExecutionToWait(waitTill); return [this.getInputData()]; } }
the_stack
import { AgnosticMediaGalleryItem, AgnosticAttribute, AgnosticPrice, ProductGetters } from '@vue-storefront/core'; import { ProductVariant } from '@vue-storefront/shopify-api/src/types'; import { enhanceProduct } from '../helpers/internals'; import { formatAttributeList, capitalize } from './_utils'; type ProductVariantFilters = any // eslint-disable-next-line @typescript-eslint/no-unused-vars export const getProductName = (product: ProductVariant): string => product?.name || 'Product\'s name'; // eslint-disable-next-line @typescript-eslint/no-unused-vars export const getProductSlug = (product: ProductVariant): string => { if (product) { return product._slug; } }; // eslint-disable-next-line @typescript-eslint/no-unused-vars export const getProductPrice = (product: ProductVariant): AgnosticPrice => { return { regular: product?.price?.original || 0, special: product?.price?.current || 0 }; }; // eslint-disable-next-line @typescript-eslint/no-unused-vars export const getProductDiscountPercentage = (product): number => { const regular = parseFloat(product?.price?.original) || 0; const special = parseFloat(product?.price?.current) || 0; if (special < regular) { const discount = regular - special; const discountPercentage = (discount / regular) * 100; return Math.round(discountPercentage); } return 0; }; // eslint-disable-next-line @typescript-eslint/no-unused-vars export const getProductGallery = (product: ProductVariant): AgnosticMediaGalleryItem[] => (product ? product.images : []) .map((image) => { const imgPath = image.originalSrc.substring(0, image.originalSrc.lastIndexOf('.')); const imgext = image.originalSrc.split('.').pop(); const imgSmall = imgPath + '_160x160.' + imgext; const imgBig = imgPath + '_295x295.' + imgext; const imgNormal = imgPath + '_600x600.' + imgext; return ({ small: imgSmall, big: imgBig, normal: imgNormal }); }); export const getActiveVariantImage = (product) => { if (product) { let productImg = product._coverImage.originalSrc; if (product.variantBySelectedOptions && product.variantBySelectedOptions !== null) productImg = product.variantBySelectedOptions.image.originalSrc; for (let i = 1; i < (product.images).length; i++) { if (product.images[i].originalSrc === productImg) { return i; } } } }; // eslint-disable-next-line @typescript-eslint/no-unused-vars export const getProductFiltered = (products, filters: ProductVariantFilters | any = {}) => { if (!products) { return []; } products = Array.isArray(products) ? products : [products]; return (Object.keys(products).length > 0 ? enhanceProduct(products) : []) as ProductVariant[]; }; export const getFilteredSingle = (product) => { if (!product) { return []; } product = Array.isArray(product) ? product : [product]; return enhanceProduct(product) as ProductVariant[]; }; export const getSelectedVariant = (product: ProductVariant, attribs) => { return attribs; }; export const getProductOptions = (product: ProductVariant): Record<string, AgnosticAttribute | string> => { const productOptions = (product as any).options; return productOptions; }; // eslint-disable-next-line @typescript-eslint/no-unused-vars export const getProductAttributes = (products: ProductVariant, filterByAttributeName?: string[]): Record<string, AgnosticAttribute | string> => { const isSingleProduct = !Array.isArray(products); const productList = (isSingleProduct ? [products] : products) as ProductVariant[]; if (!products || productList.length === 0) { return {} as any; } /* const formatAttributes = (products): AgnosticAttribute[] =>{ return formatAttributeList(products.options); }; */ const formatAttributes = (product: ProductVariant): AgnosticAttribute[] => formatAttributeList(product.options).filter((attribute) => filterByAttributeName ? filterByAttributeName.includes(attribute.name) : attribute); const reduceToUniques = (prev, curr) => { const isAttributeExist = prev.some((el) => el.name === curr.name && el.value === curr.value); if (!isAttributeExist) { return [...prev, curr]; } return prev; }; const reduceByAttributeName = (prev, curr) => ({ ...prev, [capitalize(curr.name)]: isSingleProduct ? curr.value : [ ...(prev[curr.name] || []), { value: curr.value, label: curr.label } ] }); return productList .map((product) => formatAttributes(product)) .reduce((prev, curr) => [...prev, ...curr], []) .reduce(reduceToUniques, []) .reduce(reduceByAttributeName, {}); }; export const getProductDescription = (product: ProductVariant, isWantHtml?: boolean): any => { if (product) { if (isWantHtml) { return product._descriptionHtml; } return product._description; } }; export const getProductCategoryIds = (product: ProductVariant): string[] => (product as any)?._categoriesRef || ''; export const getProductVariantId = (product: ProductVariant): string => (product as any)?.variants[0].id || ''; export const getProductId = (product: ProductVariant): string => (product as any)?._id || ''; export const getProductOriginalId = (product): string => { if (product && product?._id) { const buff = Buffer.from(product?._id, 'base64'); const decodedId = buff.toString('ascii'); const extractedInfo = decodedId.split(/[\s/]+/).pop(); return extractedInfo; } return ''; }; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export const getFormattedPrice = (price: number) => String(price); export const getProductSaleStatus = (product: ProductVariant): boolean => { if (product && (product.availableForSale)) { return true; } return false; }; export const getProductCoverImage = (product, size = 'normal') => { let imgResolution = '600x600'; if (size === 'medium') { imgResolution = '295x295'; } else if (size === 'small') { imgResolution = '80x80'; } if (product && product._coverImage && product._coverImage.src) { const imgPath = product._coverImage.src.substring(0, product._coverImage.src.lastIndexOf('.')); const imgext = product._coverImage.src.split('.').pop(); const resizedImg = imgPath + '_' + imgResolution + '.' + imgext; return resizedImg; } return 'https://cdn.shopify.com/s/files/1/0407/1902/4288/files/placeholder_' + imgResolution + '.jpg?v=1625742127'; }; export const getProductCollections = (product, field = 'all') => { if (!product) { return; } if (product.collections && Object.keys(product.collections).length > 0) { const collections = []; Object.values(product.collections).map((collection: Record<string, unknown>) => { if (field === 'all') { collections.push({ id: collection.id, title: collection.title, slug: collection.handle }); } else { collections.push(collection[field]); } }); return collections; } return []; }; export const getPDPProductCoverImage = (product, size = 'normal') => { let imgResolution = '600x600'; if (size === 'medium') { imgResolution = '295x295'; } else if (size === 'small') { imgResolution = '80x80'; } if (product && product._coverImage && product._coverImage.originalSrc) { const imgPath = product._coverImage.originalSrc.substring(0, product._coverImage.originalSrc.lastIndexOf('.')); const imgext = product._coverImage.originalSrc.split('.').pop(); const resizedImg = imgPath + '_' + imgResolution + '.' + imgext; return resizedImg; } return 'https://cdn.shopify.com/s/files/1/0407/1902/4288/files/placeholder_' + imgResolution + '.jpg?v=1625742127'; }; export const getProductStockStatus = (product: ProductVariant): boolean => { if (product && product.variantBySelectedOptions && product.variantBySelectedOptions !== null) { if (product.variantBySelectedOptions.quantityAvailable > 0) { return true; } return false; } else if (product && product.totalInventory > 0) { return true; } return false; }; export const getProductStock = (product: ProductVariant): number => { if (product && product.variantBySelectedOptions && product.variantBySelectedOptions !== null) { return product.variantBySelectedOptions.quantityAvailable; } else if (product && product.totalInventory) { return product.totalInventory; } return 0; }; export const checkForWishlist = (product: ProductVariant): boolean => (product as any).isInWishlist ?? false; export const getBreadcrumbs = (product: ProductVariant): any => { const breadCrumbs = [ { text: 'Home', route: { link: '/' } } ]; if (product && product.productType) { breadCrumbs.push({ text: product.productType, route: { link: '#' } }); } if (product && product.name) { breadCrumbs.push({ text: getProductName(product), route: { link: '#' } }); } return breadCrumbs; }; // eslint-disable-next-line @typescript-eslint/no-unused-vars export const getProductTotalReviews = (product: ProductVariant): number => 0; // eslint-disable-next-line @typescript-eslint/no-unused-vars export const getProductAverageRating = (product: ProductVariant): number => 0; const productGetters: ProductGetters<ProductVariant, ProductVariantFilters> = { getName: getProductName, getSlug: getProductSlug, getPrice: getProductPrice, getGallery: getProductGallery, getCoverImage: getProductCoverImage, getCollections: getProductCollections, getVariantImage: getActiveVariantImage, getFiltered: getProductFiltered, getDiscountPercentage: getProductDiscountPercentage, getFilteredSingle, getProductOriginalId, getOptions: getProductOptions, getAttributes: getProductAttributes, getDescription: getProductDescription, getCategoryIds: getProductCategoryIds, getId: getProductId, getPDPCoverImage: getPDPProductCoverImage, getVariantId: getProductVariantId, getSaleStatus: getProductSaleStatus, getStockStatus: getProductStockStatus, getStock: getProductStock, getFormattedPrice, getTotalReviews: getProductTotalReviews, getAverageRating: getProductAverageRating, getBreadcrumbs, getSelectedVariant }; export default productGetters;
the_stack
import RBTreeNode from './red-black-tree-node' import Stack from '../../sequences/stack' import * as utils from '../../utils' /*************************************************************************************************** * A red-black tree is a binary tree that satisfies the red-black properties: * 1. Every node is either red or black * 2. The root is black * 3. Every leaf (null) is black * 4. If a node is red, both it's children are black * 5. For all ndoes, all paths from the node to descendant leaves contain the same number of black nodes * You might be wondering how did anyone come up with all these rules? * Red-black trees are really just isometries of 2-3-4 trees. If you lift up the red nodes into their * parents, the red-black tree becomes a 2-3-4 tree - a B-tree with branching factor 2. * The complex rules of red-black trees make perfect sense if you connect it back to 2-3-4 trees. * Since 2-3-4 trees support O(logn) insertions and deletions, so does the red-black tree. * Dont memorize red/black rotations and color flips. If you're going to code up a red-black tree, * just open up CLRS and translate the pseudocode. * search() - O(logn) * insert() - O(logn) * remove() - O(logn) * Implementation is based off CLRS, chapter 13. **************************************************************************************************/ class RedBlackTree<T> { root: RBTreeNode<T> | null private sz: number private compare: utils.CompareFunction<T> constructor(compareFunction?: utils.CompareFunction<T>) { this.root = null this.sz = 0 this.compare = compareFunction || utils.defaultCompare } /***************************************************************************** INSPECTION *****************************************************************************/ size(): number { return this.sz } isEmpty(): boolean { return this.size() === 0 } // O(n) height(): number { return this.heightHelper(this.root) } // O(n) because we recurse on all nodes in the tree private heightHelper(root: RBTreeNode<T> | null): number { if (root === null) return 0 return Math.max(this.heightHelper(root.left), this.heightHelper(root.right)) + 1 } /***************************************************************************** SEARCHING *****************************************************************************/ // All search operations can be implemented iteratively and in O(logn) time. // O(logn) because we're just tracing a path down the tree find(value: T): RBTreeNode<T> | null { let cur = this.root while (cur !== null && cur.value !== value) { if (this.compare(value, cur.value) < 0) cur = cur.left else cur = cur.right } return cur } // finds the min node in the subtree rooted at given root, or top-most parent by default // O(logn) because we're just tracing a path down the tree findMin(root?: RBTreeNode<T> | null): RBTreeNode<T> | null { let cur = root || this.root while (cur && cur.left !== null) { cur = cur.left } return cur } // finds the max node in the subtree rooted at given root, or top-most parent by default // O(logn) because we're just tracing a path down the tree findMax(root?: RBTreeNode<T> | null): RBTreeNode<T> | null { let cur = root || this.root while (cur && cur.right !== null) { cur = cur.right } return cur } // O(logn) since we follow a path down the tree or up the tree findSucessor(root: RBTreeNode<T>): RBTreeNode<T> | null { // if the right child exists, the successor is the left-most node of the right-child const rightChildExists = root.right !== null if (rightChildExists) return this.findMin(root.right) // otherwise, the successor is the lowest ancestor of the current node whose // left child is also an ancestor of the current node let cur = root let parent = root.parent // Go up the tree from cur until we find a node that is the left child of the parent. // If the node is the right child of the parent that means we haven't crossed // "up and over" to the successor side of the binary tree while (parent !== null && cur === parent.right) { cur = parent parent = parent.parent } return parent } // O(logn) since we follow a path down the tree or up the tree findPredecessor(root: RBTreeNode<T>): RBTreeNode<T> | null { // if the left child exists, the successor is the right-most node of the left-child const leftChildExists = root.left !== null if (leftChildExists) return this.findMax(root.left) // otherwise, the successor is the lowest ancestor of the current node whose // right child is also an ancestor of the current node let cur = root let parent = root.parent // Go up the tree from cur until we find a node that is the right child of the parent // If the node is the left child of the parent that means we haven't crossed // "up and over" to the predecessor side of the binary tree while (parent !== null && cur === parent.left) { cur = parent parent = parent.parent } return parent } /***************************************************************************** INSERTION/DELETION *****************************************************************************/ // O(logn) time since we follow a path down the tree insert(value: T): RBTreeNode<T> { let parent: RBTreeNode<T> | null = null let cur = this.root // walk down our tree until cur pointer is null while (cur !== null) { parent = cur if (this.compare(value, cur.value) < 0) cur = cur.left else cur = cur.right } const newNode = new RBTreeNode(value, 'red', parent) if (parent === null) { // if the root was empty, just set the root pointer to newNode this.root = newNode } else if (newNode.value < parent.value) { parent.left = newNode } else { parent.right = newNode } this.sz += 1 this.insertFix(newNode) return newNode } insertFix(z: RBTreeNode<T>): void { if (z.parent === null || z.parent.parent === null) throw new Error() while (z && z.parent && z.parent.parent && z.parent.color === 'red') { if (z.parent === z.parent.parent.left) { const y = z.parent.parent.right if (!y) throw new Error() if (y.color === 'red') { z.parent.color = 'black' y.color = 'black' z.parent.parent.color = 'red' z = z.parent.parent } else { if (z === z.parent.right) { z = z.parent this.leftRotate(z) } if (!z.parent || !z.parent.parent) throw new Error() z.parent.color = 'black' z.parent.parent.color = 'red' this.rightRotate(z.parent.parent) } } else { const y = z.parent.parent.left if (!y) throw new Error() if (y.color === 'red') { z.parent.color = 'black' y.color = 'black' z.parent.parent.color = 'red' z = z.parent.parent } else { if (z === z.parent.left) { z = z.parent this.rightRotate(z) } if (!z.parent || !z.parent.parent) throw new Error() z.parent.color = 'black' z.parent.parent.color = 'red' this.leftRotate(z.parent.parent) } } } if (!this.root) throw new Error() this.root.color = 'black' } remove(z: RBTreeNode<T>): boolean { let y: RBTreeNode<T> = z // temporary reference y let yOriginalColor = y.color let x: RBTreeNode<T> | null if (z.left === null) { x = z.right this.transplant(z, z.right) } else if (z.right === null) { x = z.left this.transplant(z, z.left) } else { y = this.findSucessor(z.right)! yOriginalColor = y.color x = y.right if (!x) throw new Error() if (y.parent === z) x.parent = y else { this.transplant(y, y.right) y.right = z.right y.right.parent = y } this.transplant(z, y) y.left = z.left y.left.parent = y y.color = z.color } if (yOriginalColor === 'black') this.removeFix(x!) this.sz -= 1 return true } private removeFix(x: RBTreeNode<T>): void { while (x !== this.root && x.color === 'black') { if (!x || !x.parent) throw new Error() if (x === x.parent.left) { let w = x.parent.right if (!w) throw new Error() if (w.color === 'red') { w.color = 'black' x.parent.color = 'red' this.leftRotate(x.parent) w = x.parent.right } if (!w || !w.left || !w.right) throw new Error() if (w.left.color === 'black' && w.right.color === 'black') { w.color = 'red' x = x.parent continue } else if (w.right.color === 'black') { w.left.color = 'black' w.color = 'red' this.rightRotate(w) w = x.parent.right } if (!w || !w.left || !w.right) throw new Error() if (w.right.color === 'red') { w.color = x.parent.color x.parent.color = 'black' w.right.color = 'black' this.leftRotate(x.parent) x = this.root! } } else { let w = x.parent.left if (!w) throw new Error() if (w.color === 'red') { w.color = 'black' x.parent.color = 'red' this.rightRotate(x.parent) w = x.parent.left } if (!w || !w.left || !w.right) throw new Error() if (w.right.color === 'black' && w.left.color === 'black') { w.color = 'red' x = x.parent continue } else if (w.left.color === 'black') { w.right.color = 'black' w.color = 'red' this.leftRotate(w) w = x.parent.left } if (!w || !w.left || !w.right) throw new Error() if (w.left.color === 'red') { w.color = x.parent.color x.parent.color = 'black' w.left.color = 'black' this.rightRotate(x.parent) x = this.root! } } } x.color = 'black' } private leftRotate(A: RBTreeNode<T>) { const P = A.parent // save A's parent for later const B = A.right if (B === null) throw new Error() A.right = B.left // swing B's predecessors to A // set B's predecessors parent to A now if (B.left !== null) B.left.parent = A // set BPredecessor.Parent = A B.left = A // rotate A left // link up parents A.parent = B B.parent = P if (P !== null) { if (P.left === A) P.left = B else P.right = B } else { // that means A was root, so now point root to B this.root = B } } private rightRotate(A: RBTreeNode<T>) { const P = A.parent const B = A.left if (B === null) throw new Error() A.left = B.right // swing B's successors to A since B.right will now be A // if B has a sucessor, set it's new parent to A now if (B.right !== null) B.right.parent = A // set BSuccessor.parent = A B.right = A // rotate A right // link up parents A.parent = B B.parent = P if (P !== null) { if (P.left === A) P.left = B else P.right = B } else { // that means A was root, so now point root to B this.root = B } } // Replaces the subtree rooted at u with the subtree rooted at v. Node u's // parent now becomes node v's parent. Note that transplant does not update // v.left or v.right private transplant(u: RBTreeNode<T>, v: RBTreeNode<T> | null) { if (u.parent === null) { this.root = v } else if (u == u.parent.left) { u.parent.left = v } else u.parent.right = v // set v's parent pointer to point to u's parent if (v) v.parent = u.parent } /***************************************************************************** READING *****************************************************************************/ inorderTraversal(): { [Symbol.iterator](): Iterator<T> } { let root = this.root const stack = new Stack<RBTreeNode<T>>() return { [Symbol.iterator]: (): Iterator<T> => ({ next(): IteratorResult<T> { // dig left while (root !== null) { stack.push(root) root = root.left } // we're done exploring the left branch if (stack.isEmpty()) { // if stack is empty, we have no more nodes to process return { value: null, done: true } } root = stack.pop()! // root is not null bc stack is not empty const value = root.value root = root.right return { value, done: false, } }, }), } } preorderTraversal(): { [Symbol.iterator](): Iterator<T> } { let root = this.root const stack = new Stack<RBTreeNode<T>>() if (root !== null) stack.push(root) return { [Symbol.iterator]: (): Iterator<T> => ({ next(): IteratorResult<T> { if (stack.isEmpty()) return { value: null, done: true } root = stack.pop()! // root is non-null bc stack is not empty const value = root.value if (root.right !== null) stack.push(root.right) if (root.left !== null) stack.push(root.left) return { value, done: false, } }, }), } } postorderTraversal(): { [Symbol.iterator](): Iterator<T> } { let root = this.root const stack1 = new Stack<RBTreeNode<T>>() const stack2 = new Stack<RBTreeNode<T>>() if (root !== null) stack1.push(root) while (!stack1.isEmpty()) { root = stack1.pop()! // non-null bc stack1 is not empty stack2.push(root) if (root.left !== null) stack1.push(root.left) if (root.right !== null) stack1.push(root.right) } return { [Symbol.iterator]: (): Iterator<T> => ({ next(): IteratorResult<T> { if (stack2.isEmpty()) return { value: null, done: true } const { value } = stack2.pop()! // non-null bc stack2 is not empty return { value, done: false, } }, }), } } } export default RedBlackTree
the_stack
import { pluginReadme } from "../../../../components/MarkdownRenderer/__tests__/test_state"; import { PluginMetadata, PropertyTypes, Primitives, ConfigurationGroup, PropertyLayoutVariants, ConfigurationProperty, } from "@codotype/core"; // // // // // React + TS Component Library Starter // // // // // Library Metadata const libraryMetadata: ConfigurationProperty = new Primitives.ConfigurationProperty( { identifier: "metadata", content: { label: "Package Metadata", description: "Configure the name of your NPM package and the component it exports", icon: "", documentation: "", }, type: PropertyTypes.INSTANCE, layoutVariant: PropertyLayoutVariants.COL_12, properties: [ new Primitives.ConfigurationProperty({ identifier: "packageName", content: { label: "Package Name", description: "What's the name of your component library package?", icon: "", // "https://seeklogo.com/images/J/jest-logo-F9901EBBF7-seeklogo.com.png", documentation: "", }, type: PropertyTypes.STRING, layoutVariant: PropertyLayoutVariants.CARD_COL_6, }), new Primitives.ConfigurationProperty({ identifier: "componentName", content: { label: "Component Name", description: "What's the name of the React component your library exports?", icon: "", // "https://seeklogo.com/images/J/jest-logo-F9901EBBF7-seeklogo.com.png", documentation: "", }, type: PropertyTypes.STRING, layoutVariant: PropertyLayoutVariants.CARD_COL_6, }), new Primitives.ConfigurationProperty({ identifier: "author", content: { label: "Author", description: "Who's the author of this component library?", icon: "", // "https://seeklogo.com/images/J/jest-logo-F9901EBBF7-seeklogo.com.png", documentation: "", }, type: PropertyTypes.STRING, layoutVariant: PropertyLayoutVariants.CARD_COL_6, }), new Primitives.ConfigurationProperty({ identifier: "license", content: { label: "License", description: "Which open-source license would you like to use?", icon: "", documentation: "", }, type: PropertyTypes.DROPDOWN, layoutVariant: PropertyLayoutVariants.CARD_COL_6, selectOptions: [ { value: "mit", label: "MIT" }, { value: "gpl", label: "GPL" }, { value: "none", label: "None" }, ], }), ], }, ); // // // // // Tooling Property const toolingProperty: ConfigurationProperty = new Primitives.ConfigurationProperty( { identifier: "tooling", content: { label: "Tooling", description: "Configure the tooling for developing your component library", icon: "", documentation: "All logos are property of their respecive copyright holders", }, type: PropertyTypes.INSTANCE, layoutVariant: PropertyLayoutVariants.COL_12, properties: [ new Primitives.ConfigurationProperty({ identifier: "jest", content: { label: "Jest", description: "Include Jest environment and snapshot tests for all your components", icon: "https://seeklogo.com/images/J/jest-logo-F9901EBBF7-seeklogo.com.png", documentation: "", }, type: PropertyTypes.BOOLEAN, layoutVariant: PropertyLayoutVariants.CARD_COL_6, }), new Primitives.ConfigurationProperty({ identifier: "prettier", content: { label: "Prettier", description: "Include Prettier .rc files and npm script for code formattting", icon: "https://seeklogo.com/images/P/prettier-logo-D5C5197E37-seeklogo.com.png", documentation: "", }, type: PropertyTypes.BOOLEAN, layoutVariant: PropertyLayoutVariants.CARD_COL_6, defaultValue: true, }), new Primitives.ConfigurationProperty({ identifier: "eslint", content: { label: "Eslint", description: "Include ESLint .rc files and npm script for code linting", icon: "https://cdn.freebiesupply.com/logos/large/2x/eslint-logo-png-transparent.png", documentation: "", }, type: PropertyTypes.BOOLEAN, layoutVariant: PropertyLayoutVariants.CARD_COL_6, defaultValue: true, }), new Primitives.ConfigurationProperty({ identifier: "storybook", content: { label: "Storybook", description: "Include Storybook environment and stories for all your components", icon: "https://pbs.twimg.com/profile_images/1100804485616566273/sOct-Txm.png", documentation: "", }, type: PropertyTypes.BOOLEAN, layoutVariant: PropertyLayoutVariants.CARD_COL_6, }), new Primitives.ConfigurationProperty({ identifier: "vsCodeDir", content: { label: "Include .vscode directory", description: "Include a .vscode directory in the root of your project for tuning editor behavior", icon: "https://user-images.githubusercontent.com/674621/71187801-14e60a80-2280-11ea-94c9-e56576f76baf.png", documentation: "", }, type: PropertyTypes.BOOLEAN, layoutVariant: PropertyLayoutVariants.CARD_COL_6, }), ], }, ); // // // // // GitHub Property const githubProperty: ConfigurationProperty = new Primitives.ConfigurationProperty( { identifier: "github", content: { label: "GitHub Settings", description: "Configure the community files included in your project", icon: "", documentation: "", }, type: PropertyTypes.INSTANCE, layoutVariant: PropertyLayoutVariants.COL_12, properties: [ new Primitives.ConfigurationProperty({ identifier: "changelog", content: { label: "Include CHANGELOG file", description: "Include a CHANGELOG.md file in the root of your project", icon: "", documentation: "", }, type: PropertyTypes.BOOLEAN, layoutVariant: PropertyLayoutVariants.CARD_COL_6, }), new Primitives.ConfigurationProperty({ identifier: "codeOfConduct", content: { label: "Include Code of Conduct", description: "Include a CODE_OF_CONDUCT.md file in the root of your project", icon: "", documentation: "", }, type: PropertyTypes.BOOLEAN, layoutVariant: PropertyLayoutVariants.CARD_COL_6, }), new Primitives.ConfigurationProperty({ identifier: "githubDir", content: { label: "Include .github directory", description: "Include a .github directory in the root of your project with issue and pull-request templates", icon: "", documentation: "", }, type: PropertyTypes.BOOLEAN, layoutVariant: PropertyLayoutVariants.CARD_COL_6, }), ], }, ); // // // // // Library Configuration Group const libraryConfiguration: ConfigurationGroup = new Primitives.ConfigurationGroup( { identifier: "libraryConfiguration", content: { label: "Configuration", description: "Configure the boilerplate code for your new React component library", icon: "", documentation: "", }, properties: [toolingProperty, libraryMetadata, githubProperty], }, ); // // // // // Export Plugin export const ReactComponentLibraryStarterPlugin: PluginMetadata = new Primitives.Plugin( { identifier: "react-component-library-starter", project_path: "react-component-library-starter", content: { label: "React + TypeScript Component Library Starter", description: "React + TypeScript Component Library Starter", icon: "https://miro.medium.com/max/500/1*cPh7ujRIfcHAy4kW2ADGOw.png", documentation: pluginReadme, }, configurationGroups: [libraryConfiguration], }, );
the_stack
/// <reference types="node" /> declare module '@mapbox/mapbox-sdk/lib/classes/mapi-client' { import { MapiRequest, MapiRequestOptions, DirectionsApproach } from '@mapbox/mapbox-sdk/lib/classes/mapi-request'; export default class MapiClient { constructor(config: SdkConfig); accessToken: string; origin?: string | undefined; createRequest(requestOptions: MapiRequestOptions): MapiRequest; } interface SdkConfig { accessToken: string; origin?: string | undefined; } } declare module '@mapbox/mapbox-sdk/lib/classes/mapi-request' { import { MapiResponse } from '@mapbox/mapbox-sdk/lib/classes/mapi-response'; import MapiClient from '@mapbox/mapbox-sdk/lib/classes/mapi-client'; import { MapiError } from '@mapbox/mapbox-sdk/lib/classes/mapi-error'; interface EventEmitter { response: MapiResponse; error: MapiError; downloadProgress: ProgressEvent; uploadProgress: ProgressEvent; } interface MapiRequestOptions { /** * The request's path, including colon-prefixed route parameters. */ path: string; /** * The request's origin. */ origin: string; /** * The request's HTTP method. */ method: string; /** * A query object, which will be transformed into a URL query string. */ query: any; /** * A route parameters object, whose values will be interpolated the path. */ params: any; /** * The request's headers. */ headers: any; /** * Data to send with the request. If the request has a body, it will also be sent with the header 'Content-Type: application/json'. */ body?: any; /** * A file to send with the request. The browser client accepts Blobs and ArrayBuffers. */ file: Blob | ArrayBuffer | string | NodeJS.ReadStream; /** * The encoding of the response. */ encoding: string; /** * The method to send the `file`. Options are `data` (x-www-form-urlencoded) or `form` (multipart/form-data) */ sendFileAs: 'data' | 'form'; } type MapiRequest = MapiRequestOptions & { /** * An event emitter. */ emitter: EventEmitter; /** * This request's MapiClient. */ client: MapiClient; /** * If this request has been sent and received a response, the response is available on this property. */ response?: MapiResponse | undefined; /** * If this request has been sent and received an error in response, the error is available on this property. */ error?: MapiError | Error | undefined; /** * If the request has been aborted (via abort), this property will be true. */ aborted: boolean; /** * If the request has been sent, this property will be true. * You cannot send the same request twice, so if you need to create a new request * that is the equivalent of an existing one, use clone. */ sent: boolean; url(accessToken?: string): string; send(): Promise<MapiResponse>; abort(): void; eachPage(callback: PageCallbackFunction): void; clone(): MapiRequest; }; interface PageCallbackFunction { error: MapiError; response: MapiResponse; next: () => void; } type Coordinates = [number, number]; type MapboxProfile = 'driving' | 'walking' | 'cycling' | 'driving-traffic'; type DirectionsApproach = 'unrestricted' | 'curb'; } declare module '@mapbox/mapbox-sdk/lib/classes/mapi-response' { import { MapiRequest } from '@mapbox/mapbox-sdk/lib/classes/mapi-request'; interface MapiResponse { /** * The response body, parsed as JSON. */ body: any; /** * The raw response body. */ rawBody: string; /** * The response's status code. */ statusCode: number; /** * The parsed response headers. */ headers: any; /** * The parsed response links */ links: any; /** * The response's originating MapiRequest. */ request: MapiRequest; hasNextPage(): boolean; nextPage(): MapiRequest | null; } } declare module '@mapbox/mapbox-sdk/lib/classes/mapi-error' { import { MapiRequest } from '@mapbox/mapbox-sdk/lib/classes/mapi-request'; interface MapiError { /** * The errored request. */ request: MapiRequest; /** * The type of error. Usually this is 'HttpError'. * If the request was aborted, so the error was not sent from the server, the type will be 'RequestAbortedError'. */ type: string; /** * The numeric status code of the HTTP response */ statusCode?: number | undefined; /** * If the server sent a response body, this property exposes that response, parsed as JSON if possible. */ body?: any; /** * Whatever message could be derived from the call site and HTTP response. */ message?: string | undefined; } } declare module '@mapbox/mapbox-sdk/services/datasets' { import { MapiRequest } from '@mapbox/mapbox-sdk/lib/classes/mapi-request'; import MapiClient, { SdkConfig } from '@mapbox/mapbox-sdk/lib/classes/mapi-client'; /********************************************************************************************************************* * Datasets Types *********************************************************************************************************************/ export default function Datasets(config: SdkConfig | MapiClient): DatasetsService; interface DatasetsService { /** * List datasets in your account. */ listDatasets(config?: { sortby?: 'created' | 'modified' | undefined }): MapiRequest; /** * Create a new, empty dataset. * @param config Object */ createDataset(config: { name?: string | undefined; description?: string | undefined }): MapiRequest; /** * Get metadata about a dataset. * @param config */ getMetadata(config: { datasetId: string }): MapiRequest; /** * Update user-defined properties of a dataset's metadata. * @param config */ updateMetadata(config: { datasetId?: string | undefined; name?: string | undefined; description?: string | undefined }): MapiRequest; /** * Delete a dataset, including all features it contains. * @param config */ deleteDataset(config: { datasetId: string }): MapiRequest; /** * List features in a dataset. * This endpoint supports pagination. Use MapiRequest#eachPage or manually specify the limit and start options. * @param config */ listFeatures(config: { datasetId: string; limit?: number | undefined; start?: string | undefined }): MapiRequest; /** * Add a feature to a dataset or update an existing one. * @param config */ putFeature(config: { datasetId: string; featureId: string; feature: DataSetsFeature }): MapiRequest; /** * Get a feature in a dataset. * @param config */ getFeature(config: { datasetId: string; featureId: string }): MapiRequest; /** * Delete a feature in a dataset. * @param config */ deleteFeature(config: { datasetId: string; featureId: string }): MapiRequest; } /** * All GeoJSON types except for FeatureCollection. */ type DataSetsFeature = | GeoJSON.Point | GeoJSON.MultiPoint | GeoJSON.LineString | GeoJSON.MultiLineString | GeoJSON.Polygon | GeoJSON.MultiPolygon | GeoJSON.GeometryCollection | GeoJSON.Feature<GeoJSON.Geometry, GeoJSON.GeoJsonProperties>; interface Dataset { /** * The username of the dataset owner */ owner: string; /** * Id for an existing dataset */ id: string; /* * Date and time the dataset was created */ created: string; /* * Date and time the dataset was last modified */ modified: string; /** * The extent of features in the dataset as an array of west, south, east, north coordinates */ bounds: number[]; /** * The number of features in the dataset */ features: number; /** * The size of the dataset in bytes */ size: number; /** * The name of the dataset */ name: string; /** * The description of the dataset */ description: string; } } declare module '@mapbox/mapbox-sdk/services/directions' { import * as GeoJSON from 'geojson'; import { LngLatLike } from 'mapbox-gl'; import MapiClient, { SdkConfig } from '@mapbox/mapbox-sdk/lib/classes/mapi-client'; import { MapiRequest, MapboxProfile, DirectionsApproach, Coordinates, } from '@mapbox/mapbox-sdk/lib/classes/mapi-request'; export default function Directions(config: SdkConfig | MapiClient): DirectionsService; interface DirectionsService { getDirections(request: DirectionsRequest): MapiRequest; } type DirectionsAnnotation = 'duration' | 'distance' | 'speed' | 'congestion'; type DirectionsGeometry = 'geojson' | 'polyline' | 'polyline6'; type DirectionsOverview = 'full' | 'simplified' | 'false'; type DirectionsUnits = 'imperial' | 'metric'; type DirectionsSide = 'left' | 'right'; type DirectionsMode = 'driving' | 'ferry' | 'unaccessible' | 'walking' | 'cycling' | 'train'; type DirectionsClass = 'toll' | 'ferry' | 'restricted' | 'motorway' | 'tunnel'; type ManeuverModifier = | 'uturn' | 'sharp right' | 'right' | 'slight right' | 'straight' | 'slight left' | 'left' | 'sharp left' | 'depart' | 'arrive'; type ManeuverType = | 'turn' | 'new name' | 'depart' | 'arrive' | 'merge' | 'on ramp' | 'off ramp' | 'fork' | 'end of road' | 'continue' | 'roundabout' | 'rotary' | 'roundabout turn' | 'notification' | 'exit roundabout' | 'exit rotary'; interface CommonDirectionsRequest { waypoints: DirectionsWaypoint[]; /** * Whether to try to return alternative routes. An alternative is classified as a route that is significantly * different than the fastest route, but also still reasonably fast. Such a route does not exist in all circumstances. * Currently up to two alternatives can be returned. Can be true or false (default). */ alternatives?: boolean | undefined; /** * Whether or not to return additional metadata along the route. Possible values are: duration , distance , speed , and congestion . * Several annotations can be used by including them as a comma-separated list. See the RouteLeg object for more details on * what is included with annotations. */ annotations?: DirectionsAnnotation[] | undefined; /** * Whether or not to return banner objects associated with the routeSteps . * Should be used in conjunction with steps . Can be true or false . The default is false . */ bannerInstructions?: boolean | undefined; /** * Sets the allowed direction of travel when departing intermediate waypoints. If true , the route will continue in the same * direction of travel. If false , the route may continue in the opposite direction of travel. Defaults to true for mapbox/driving and * false for mapbox/walking and mapbox/cycling . */ continueStraight?: boolean | undefined; /** * Format of the returned geometry. Allowed values are: geojson (as LineString ), * polyline with precision 5, polyline6 (a polyline with precision 6). The default value is polyline . */ geometries?: DirectionsGeometry | undefined; /** * Language of returned turn-by-turn text instructions. See supported languages . The default is en for English. */ language?: string | undefined; /** * Type of returned overview geometry. Can be full (the most detailed geometry available), * simplified (a simplified version of the full geometry), or false (no overview geometry). The default is simplified . */ overview?: DirectionsOverview | undefined; /** * Emit instructions at roundabout exits. Can be true or false . The default is false . */ roundaboutExits?: boolean | undefined; /** * Whether to return steps and turn-by-turn instructions. Can be true or false . The default is false . */ steps?: boolean | undefined; /** * Whether or not to return SSML marked-up text for voice guidance along the route. Should be used in conjunction with steps . * Can be true or false . The default is false . */ voiceInstructions?: boolean | undefined; /** * Which type of units to return in the text for voice instructions. Can be imperial or metric . Default is imperial . */ voiceUnits?: DirectionsUnits | undefined; } type DirectionsProfileExclusion = | { profile: 'walking'; exclude?: [] | undefined; } | { profile: 'cycling'; exclude?: Array<'ferry'> | undefined; } | { profile: 'driving' | 'driving-traffic'; exclude?: Array<'ferry' | 'toll' | 'motorway'> | undefined; }; type DirectionsRequest = CommonDirectionsRequest & DirectionsProfileExclusion; interface Waypoint { /** * Semicolon-separated list of {longitude},{latitude} coordinate pairs to visit in order. There can be between 2 and 25 coordinates. */ coordinates: Coordinates; /** * Used to filter the road segment the waypoint will be placed on by direction and dicates the anlge of approach. * This option should always be used in conjunction with a `radius`. The first values is angle clockwise from true * north between 0 and 360, and the second is the range of degrees the angle can deviate by. */ bearing?: Coordinates | undefined; /** * Used to indicate how requested routes consider from which side of the road to approach a waypoint. * Accepts unrestricted (default) or curb . If set to unrestricted , the routes can approach waypoints from either side of the road. * If set to curb , the route will be returned so that on arrival, the waypoint will be found on the side that corresponds with the * driving_side of the region in which the returned route is located. Note that the approaches parameter influences how you arrive at a waypoint, * while bearings influences how you start from a waypoint. If provided, the list of approaches must be the same length as the list of waypoints. * However, you can skip a coordinate and show its position in the list with the ; separator. */ approach?: DirectionsApproach | undefined; /** * Maximum distance in meters that each coordinate is allowed to move when snapped to a nearby road segment. * There must be as many radiuses as there are coordinates in the request, each separated by ';'. * Values can be any number greater than 0 or the string 'unlimited'. * A NoSegment error is returned if no routable road is found within the radius. */ radius?: number | 'unlimited' | undefined; } type DirectionsWaypoint = Waypoint & { /** * Custom name for the waypoint used for the arrival instruction in banners and voice instructions. */ waypointName?: string | undefined; }; interface DirectionsResponse { /** * Array of Route objects ordered by descending recommendation rank. May contain at most two routes. */ routes: Route[]; /** * Array of Waypoint objects. Each waypoints is an input coordinate snapped to the road and path network. * The waypoints appear in the array in the order of the input coordinates. */ waypoints: DirectionsWaypoint[]; /** * String indicating the state of the response. This is a separate code than the HTTP status code. * On normal valid responses, the value will be Ok. */ code: string; uuid: string; } interface Route { /** * Depending on the geometries parameter this is a GeoJSON LineString or a Polyline string. * Depending on the overview parameter this is the complete route geometry (full), a simplified geometry * to the zoom level at which the route can be displayed in full (simplified), or is not included (false) */ geometry: GeoJSON.LineString | GeoJSON.MultiLineString; /** * Array of RouteLeg objects. */ legs: Leg[]; /** * String indicating which weight was used. The default is routability which is duration-based, * with additional penalties for less desirable maneuvers. */ weight_name: string; /** * Float indicating the weight in units described by weight_name */ weight: number; /** * Float indicating the estimated travel time in seconds. */ duration: number; /** * Float indicating the distance traveled in meters. */ distance: number; /** * String of the locale used for voice instructions. Defaults to en, and can be any accepted instruction language. */ voiceLocale?: string | undefined; } interface Leg { /** * Depending on the summary parameter, either a String summarizing the route (true, default) or an empty String (false) */ summary: string; weight: number; /** * Number indicating the estimated travel time in seconds */ duration: number; /** * Depending on the steps parameter, either an Array of RouteStep objects (true, default) or an empty array (false) */ steps: Step[]; /** * Number indicating the distance traveled in meters */ distance: number; /** * An annotations object that contains additional details about each line segment along the route geometry. * Each entry in an annotations field corresponds to a coordinate along the route geometry. */ annotation: DirectionsAnnotation[]; } interface Step { /** * Array of objects representing all intersections along the step. */ intersections: Intersection[]; /** * The legal driving side at the location for this step. Either left or right. */ driving_side: DirectionsSide; /** * Depending on the geometries parameter this is a GeoJSON LineString or a * Polyline string representing the full route geometry from this RouteStep to the next RouteStep */ geometry: GeoJSON.LineString | GeoJSON.MultiLineString; /** * String indicating the mode of transportation. Possible values: */ mode: DirectionsMode; /** * One StepManeuver object */ maneuver: Maneuver; /** * Any road designations associated with the road or path leading from this step’s maneuver to the next step’s maneuver. * Optionally included, if data is available. If multiple road designations are associated with the road, they are separated by semicolons. * A road designation typically consists of an alphabetic network code (identifying the road type or numbering system), a space or hyphen, * and a route number. You should not assume that the network code is globally unique: for example, a network code of “NH” may appear on a * “National Highway” or “New Hampshire”. Moreover, a route number may not even uniquely identify a road within a given network. */ ref?: string | undefined; weight: number; /** * Number indicating the estimated time traveled time in seconds from the maneuver to the next RouteStep. */ duration: number; /** * String with the name of the way along which the travel proceeds */ name: string; /** * Number indicating the distance traveled in meters from the maneuver to the next RouteStep. */ distance: number; voiceInstructions: VoiceInstruction[]; bannerInstructions: BannerInstruction[]; /** * String with the destinations of the way along which the travel proceeds. Optionally included, if data is available. */ destinations?: string | undefined; /** * String with the exit numbers or names of the way. Optionally included, if data is available. */ exits?: string | undefined; /** * A string containing an IPA phonetic transcription indicating how to pronounce the name in the name property. * This property is omitted if pronunciation data is unavailable for the step. */ pronunciation?: string | undefined; } interface Instruction { /** * String that contains all the text that should be displayed. */ text: string; /** * Objects that, together, make up what should be displayed in the banner. * Includes additional information intended to be used to aid in visual layout */ components: Component[]; /** * The type of maneuver. May be used in combination with the modifier (and, if it is a roundabout, the degrees) to for an icon to * display. Possible values: 'turn', 'merge', 'depart', 'arrive', 'fork', 'off ramp', 'roundabout' */ type?: string | undefined; /** * The modifier for the maneuver. Can be used in combination with the type (and, if it is a roundabout, the degrees) * to for an icon to display. Possible values: 'left', 'right', 'slight left', 'slight right', 'sharp left', 'sharp right', 'straight', 'uturn' */ modifier?: ManeuverModifier | undefined; /** * The degrees at which you will be exiting a roundabout, assuming 180 indicates going straight through the roundabout. */ degrees?: number | undefined; /** * A string representing which side the of the street people drive on in that location. Can be 'left' or 'right'. */ driving_side: DirectionsSide; } interface BannerInstruction { /** * Float indicating in meters, how far from the upcoming maneuver * the banner instruction should begin being displayed. Only 1 banner should be displayed at a time. */ distanceAlongGeometry: number; /** * Most important content to display to the user. Our SDK displays this text larger and at the top. */ primary: Instruction; /** * Additional content useful for visual guidance. Our SDK displays this text slightly smaller and below the primary. Can be null. */ secondary?: Instruction[] | undefined; then?: any; /** * Additional information that is included if we feel the driver needs a heads up about something. * Can include information about the next maneuver (the one after the upcoming one) if the step is short - * can be null, or can be lane information. If we have lane information, that trumps information about the next maneuver. */ sub?: Sub | undefined; } interface Sub { /** * String that contains all the text that should be displayed. */ text: string; /** * Objects that, together, make up what should be displayed in the banner. * Includes additional information intended to be used to aid in visual layout */ components: Component[]; } interface Component { /** * String giving you more context about the component which may help in visual markup/display choices. * If the type of the components is unknown it should be treated as text. Note: Introduction of new types * is not considered a breaking change. See the Types of Banner Components table below for more info on each type. */ type: string; /** * The sub-string of the parent object's text that may have additional context associated with it. */ text: string; /** * The abbreviated form of text. If this is present, there will also be an abbr_priority value. * See the Examples of Abbreviations table below for an example of using abbr and abbr_priority. */ abbr?: string | undefined; /** * An integer indicating the order in which the abbreviation abbr should be used in place of text. * The highest priority is 0 and a higher integer value means it should have a lower priority. There are no gaps in * integer values. Multiple components can have the same abbr_priority and when this happens all components with the * same abbr_priority should be abbreviated at the same time. Finding no larger values of abbr_priority means that the * string is fully abbreviated. */ abbr_priority?: number | undefined; /** * String pointing to a shield image to use instead of the text. */ imageBaseURL?: string | undefined; /** * (present if component is lane): An array indicating which directions you can go from a lane (left, right, or straight). * If the value is ['left', 'straight'], the driver can go straight or left from that lane */ directions?: string[] | undefined; /** * (present if component is lane): A boolean telling you if that lane can be used to complete the upcoming maneuver. * If multiple lanes are active, then they can all be used to complete the upcoming maneuver. */ active: boolean; } interface VoiceInstruction { /** * Float indicating in meters, how far from the upcoming maneuver the voice instruction should begin. */ distanceAlongGeometry: number; /** * String containing the text of the verbal instruction. */ announcement: string; /** * String with SSML markup for proper text and pronunciation. Note: this property is designed for use with Amazon Polly. * The SSML tags contained here may not work with other text-to-speech engines. */ ssmlAnnouncement: string; } interface Maneuver { /** * Number between 0 and 360 indicating the clockwise angle from true north to the direction of travel right after the maneuver */ bearing_after: number; /** * Number between 0 and 360 indicating the clockwise angle from true north to the direction of travel right before the maneuver */ bearing_before: number; /** * Array of [ longitude, latitude ] coordinates for the point of the maneuver */ location: number[]; /** * Optional String indicating the direction change of the maneuver */ modifier?: ManeuverModifier | undefined; /** * String indicating the type of maneuver */ type: ManeuverType; /** * A human-readable instruction of how to execute the returned maneuver */ instruction: string; } interface Intersection { /** * Index into the bearings/entry array. Used to extract the bearing after the turn. Namely, The clockwise angle from true north to * the direction of travel after the maneuver/passing the intersection. * The value is not supplied for arrive maneuvers. */ out?: number | undefined; /** * A list of entry flags, corresponding in a 1:1 relationship to the bearings. * A value of true indicates that the respective road could be entered on a valid route. * false indicates that the turn onto the respective road would violate a restriction. */ entry: boolean[]; /** * A list of bearing values (for example [0,90,180,270]) that are available at the intersection. * The bearings describe all available roads at the intersection. */ bearings: number[]; /** * A [longitude, latitude] pair describing the location of the turn. */ location: number[]; /** * Index into bearings/entry array. Used to calculate the bearing before the turn. Namely, the clockwise angle from true * north to the direction of travel before the maneuver/passing the intersection. To get the bearing in the direction of driving, * the bearing has to be rotated by a value of 180. The value is not supplied for departure maneuvers. */ in?: number | undefined; /** * An array of strings signifying the classes of the road exiting the intersection. */ classes?: DirectionsClass[] | undefined; /** * Array of Lane objects that represent the available turn lanes at the intersection. * If no lane information is available for an intersection, the lanes property will not be present. */ lanes: Lane[]; } interface Lane { /** * Boolean value for whether this lane can be taken to complete the maneuver. For instance, if the lane array has four objects and the * first two are marked as valid, then the driver can take either of the left lanes and stay on the route. */ valid: boolean; /** * Array of signs for each turn lane. There can be multiple signs. For example, a turning lane can have a sign with an arrow pointing left and another sign with an arrow pointing straight. */ indications: string[]; } } declare module '@mapbox/mapbox-sdk/services/geocoding' { import { LngLatLike } from 'mapbox-gl'; import { MapiRequest, Coordinates } from '@mapbox/mapbox-sdk/lib/classes/mapi-request'; import { MapiResponse } from '@mapbox/mapbox-sdk/lib/classes/mapi-response'; import MapiClient, { SdkConfig } from '@mapbox/mapbox-sdk/lib/classes/mapi-client'; /********************************************************************************************************************* * Geocoder Types *********************************************************************************************************************/ export default function Geocoding(config: SdkConfig | MapiClient): GeocodeService; interface GeocodeService { forwardGeocode(request: GeocodeRequest): MapiRequest; reverseGeocode(request: GeocodeRequest): MapiRequest; } type BoundingBox = [number, number, number, number]; type GeocodeMode = 'mapbox.places' | 'mapbox.places-permanent'; type GeocodeQueryType = | 'country' | 'region' | 'postcode' | 'district' | 'place' | 'locality' | 'neighborhood' | 'address' | 'poi' | 'poi.landmark'; interface GeocodeRequest { /** * A location. This will be a place name for forward geocoding or a coordinate pair (longitude, latitude) for reverse geocoding. */ query: string | LngLatLike; /** * Either mapbox.places for ephemeral geocoding, or mapbox.places-permanent for storing results and batch geocoding. */ mode?: GeocodeMode; /** * Limit results to one or more countries. Options are ISO 3166 alpha 2 country codes */ countries?: string[] | undefined; /** * Bias local results based on a provided location. Options are longitude,latitude coordinates. */ proximity?: Coordinates | undefined; /** * Filter results by one or more feature types */ types?: GeocodeQueryType[] | undefined; /** * Forward geocoding only. Return autocomplete results or not. Options are true or false and the default is true . */ autocomplete?: boolean | undefined; /** * Forward geocoding only. Limit results to a bounding box. Options are in the format minLongitude,minLatitude,maxLongitude,maxLatitude. */ bbox?: BoundingBox | undefined; /** * Limit the number of results returned. The default is 5 for forward geocoding and 1 for reverse geocoding. */ limit?: number | undefined; /** * Specify the language to use for response text and, for forward geocoding, query result weighting. * Options are IETF language tags comprised of a mandatory ISO 639-1 language code and optionally one or more * IETF subtags for country or script. */ language?: string[] | undefined; /** * Specify whether to request additional etadat about the recommended navigation destination. Only applicable for address features. */ routing?: boolean | undefined; } interface GeocodeResponse { /** * "Feature Collection" , a GeoJSON type from the GeoJSON specification. */ type: string; /** * An array of space and punctuation-separated strings from the original query. */ query: string[]; /** * An array of feature objects. */ features: GeocodeFeature[]; /** * A string attributing the results of the Mapbox Geocoding API to Mapbox and links to Mapbox's terms of service and data sources. */ attribution: string; } interface GeocodeFeature { /** * A string feature id in the form {type}.{id} where {type} is the lowest hierarchy feature in the place_type field. * The {id} suffix of the feature id is unstable and may change within versions. */ id: string; /** * "Feature" , a GeoJSON type from the GeoJSON specification. */ type: string; /** * An array of feature types describing the feature. Options are country , region , postcode , district , place , locality , neighborhood , * address , poi , and poi.landmark . Most features have only one type, but if the feature has multiple types, * all applicable types will be listed in the array. (For example, Vatican City is a country , region , and place .) */ place_type: string[]; /** * A numerical score from 0 (least relevant) to 0.99 (most relevant) measuring how well each returned feature matches the query. * You can use the relevance property to remove results that don't fully match the query. */ relevance: number; /** * A string of the house number for the returned address feature. Note that unlike the * address property for poi features, this property is outside the properties object. */ address?: string | undefined; /** * An object describing the feature. The property object is unstable and only Carmen GeoJSON properties are guaranteed. * Your implementation should check for the presence of these values in a response before it attempts to use them. */ properties: GeocodeProperties; /** * A string representing the feature in the requested language, if specified. */ text: string; /** * A string representing the feature in the requested language, if specified, and its full result hierarchy. */ place_name: string; /** * A string analogous to the text field that more closely matches the query than results in the specified language. * For example, querying "Köln, Germany" with language set to English might return a feature with the * text "Cologne" and the matching_text "Köln". */ matching_text: string; /** * A string analogous to the place_name field that more closely matches the query than results in the specified language. * For example, querying "Köln, Germany" with language set to English might return a feature with the place_name "Cologne, Germany" * and a matching_place_name of "Köln, North Rhine-Westphalia, Germany". */ matching_place_name: string; /** * A string of the IETF language tag of the query's primary language. * Can be used to identity text and place_name properties on this object * in the format text_{language}, place_name_{language} and language_{language} */ language: string; /** * An array bounding box in the form [ minX,minY,maxX,maxY ] . */ bbox?: number[] | undefined; /** * An array in the form [ longitude,latitude ] at the center of the specified bbox . */ center: number[]; /** * An object describing the spatial geometry of the returned feature */ geometry: Geometry; /** * An array representing the hierarchy of encompassing parent features. Each parent feature may include any of the above properties */ context: GeocodeFeature[]; } interface Geometry { /** * Point, a GeoJSON type from the GeoJSON specification . */ type: string; /** * An array in the format [ longitude,latitude ] at the center of the specified bbox . */ coordinates: number[]; /** * A boolean value indicating if an address is interpolated along a road network. This field is only present when the feature is interpolated. */ interpolated: boolean; } interface GeocodeProperties extends GeocodeFeature { /** * The Wikidata identifier for the returned feature. */ wikidata?: string | undefined; /** * A string of comma-separated categories for the returned poi feature. */ category?: string | undefined; /** * A formatted string of the telephone number for the returned poi feature. */ tel?: string | undefined; /** * The name of a suggested Maki icon to visualize a poi feature based on its category . */ maki?: string | undefined; /** * A boolean value indicating whether a poi feature is a landmark. Landmarks are * particularly notable or long-lived features like schools, parks, museums and places of worship. */ landmark?: boolean | undefined; /** * The ISO 3166-1 country and ISO 3166-2 region code for the returned feature. */ short_code: string; } } declare module '@mapbox/mapbox-sdk/services/map-matching' { import { LngLatLike } from 'mapbox-gl'; import { DirectionsAnnotation, DirectionsGeometry, DirectionsOverview, Leg, } from '@mapbox/mapbox-sdk/services/directions'; import { MapiRequest, MapboxProfile, DirectionsApproach, Coordinates, } from '@mapbox/mapbox-sdk/lib/classes/mapi-request'; import MapiClient, { SdkConfig } from '@mapbox/mapbox-sdk/lib/classes/mapi-client'; /********************************************************************************************************************* * Map Matching Types *********************************************************************************************************************/ export default function MapMatching(config: SdkConfig | MapiClient): MapMatchingService; interface MapMatchingService { getMatch(request: MapMatchingRequest): MapiRequest; } interface MapMatchingRequest { /** * An ordered array of MapMatchingPoints, between 2 and 100 (inclusive). */ points: MapMatchingPoint[]; /** * A directions profile ID. (optional, default driving) */ profile?: MapboxProfile | undefined; /** * Specify additional metadata that should be returned. */ annotations?: DirectionsAnnotation | undefined; /** * Format of the returned geometry. (optional, default "polyline") */ geometries?: DirectionsGeometry | undefined; /** * Language of returned turn-by-turn text instructions. See supported languages. (optional, default "en") */ language?: string | undefined; /** * Type of returned overview geometry. (optional, default "simplified" */ overview?: DirectionsOverview | undefined; /** * Whether to return steps and turn-by-turn instructions. (optional, default false) */ steps?: boolean | undefined; /** * Whether or not to transparently remove clusters and re-sample traces for improved map matching results. (optional, default false) */ tidy?: boolean | undefined; } interface Point { coordinates: Coordinates; /** * Used to indicate how requested routes consider from which side of the road to approach a waypoint. */ approach?: DirectionsApproach | undefined; } interface MapMatchingPoint extends Point { /** * A number in meters indicating the assumed precision of the used tracking device. */ radius?: number | undefined; /** * Whether this coordinate is waypoint or not. The first and last coordinates will always be waypoints. */ isWaypoint?: boolean | undefined; /** * Custom name for the waypoint used for the arrival instruction in banners and voice instructions. * Will be ignored unless isWaypoint is true. */ waypointName?: boolean | undefined; /** * Datetime corresponding to the coordinate. */ timestamp?: string | number | Date | undefined; } interface MapMatchingResponse { /** * An array of Match objects. */ matchings: Matching[]; /** * An array of Tracepoint objects representing the location an input point was matched with. * Array of Waypoint objects representing all input points of the trace in the order they were matched. * If a trace point is omitted by map matching because it is an outlier, the entry will be null. */ tracepoints: Tracepoint[]; /** * A string depicting the state of the response; see below for options */ code: string; } interface Tracepoint { /** * Number of probable alternative matchings for this trace point. A value of zero indicates that this point was matched unambiguously. * Split the trace at these points for incremental map matching. */ alternatives_count: number; /** * Index of the waypoint inside the matched route. */ waypoint_index: number; location: number[]; name: string; /** * Index to the match object in matchings the sub-trace was matched to. */ matchings_index: number; } interface Matching { /** * a number between 0 (low) and 1 (high) indicating level of confidence in the returned match */ confidence: number; geometry: string; legs: Leg[]; distance: number; duration: number; weight_name: string; weight: number; } } declare module '@mapbox/mapbox-sdk/services/matrix' { import { DirectionsAnnotation } from '@mapbox/mapbox-sdk/services/directions'; import { Point } from '@mapbox/mapbox-sdk/services/map-matching'; import { MapiRequest, MapboxProfile } from '@mapbox/mapbox-sdk/lib/classes/mapi-request'; import MapiClient, { SdkConfig } from '@mapbox/mapbox-sdk/lib/classes/mapi-client'; /********************************************************************************************************************* * Matrix Types *********************************************************************************************************************/ export default function Matrix(config: SdkConfig | MapiClient): MatrixService; interface MatrixService { /** * Get a duration and/or distance matrix showing travel times and distances between coordinates. * @param request */ getMatrix(request: MatrixRequest): MapiRequest; } interface MatrixRequest { points: Point[]; profile?: MapboxProfile | undefined; sources?: number[] | 'all' | undefined; destinations?: number[] | 'all' | undefined; annotations?: DirectionsAnnotation[] | undefined; } interface MatrixResponse { code: string; durations?: number[][] | undefined; distances?: number[][] | undefined; destinations: Destination[]; sources: Destination[]; } interface Destination { location: number[]; name: string; } } declare module '@mapbox/mapbox-sdk/services/optimization' { import { Waypoint } from '@mapbox/mapbox-sdk/services/directions'; import { MapiRequest, MapboxProfile, DirectionsApproach } from '@mapbox/mapbox-sdk/lib/classes/mapi-request'; import { MapiResponse } from '@mapbox/mapbox-sdk/lib/classes/mapi-response'; import MapiClient, { SdkConfig } from '@mapbox/mapbox-sdk/lib/classes/mapi-client'; /********************************************************************************************************************* * Optimization Types *********************************************************************************************************************/ export default function Optimization(config: SdkConfig | MapiClient): OptimizationService; // SdkConfig | MapiClient interface OptimizationService { getOptimization(config: OptimizationRequest): MapiRequest; } interface OptimizationRequest { /** * A Mapbox Directions routing profile ID. */ profile: MapboxProfile; /** * A semicolon-separated list of {longitude},{latitude} coordinates. There must be between 2 and 12 coordinates. The first coordinate is the start and end point of the trip. */ waypoints: Waypoint[]; /** * Return additional metadata along the route. You can include several annotations as a comma-separated list. Possible values are: */ annotations?: OptimizationAnnotation[] | undefined; /** * Specify the destination coordinate of the returned route. Accepts any (default) or last . */ destination?: 'any' | 'last' | undefined; /** * Specify pick-up and drop-off locations for a trip by providing a ; delimited list of number pairs that correspond with the coordinates list. * The first number of a pair indicates the index to the coordinate of the pick-up location in the coordinates list, * and the second number indicates the index to the coordinate of the drop-off location in the coordinates list. * Each pair must contain exactly 2 numbers, which cannot be the same. * The returned solution will visit pick-up locations before visiting drop-off locations. The first location can only be a pick-up location, not a drop-off location. */ distributions?: Distribution[] | undefined; /** * The format of the returned geometry. Allowed values are: geojson (as LineString ), polyline (default, a polyline with precision 5), polyline6 (a polyline with precision 6). */ geometries?: 'geojson' | 'polyline' | 'polyline6' | undefined; /** * The language of returned turn-by-turn text instructions. See supported languages . The default is en (English). */ language?: string | undefined; /** * The type of the returned overview geometry. * Can be 'full' (the most detailed geometry available), 'simplified' (default, a simplified version of the full geometry), or 'false' (no overview geometry). */ overview?: 'full' | 'simplified' | 'false' | undefined; /** * The coordinate at which to start the returned route. Accepts any (default) or first . */ source?: 'any' | 'first' | undefined; /** * Whether to return steps and turn-by-turn instructions ( true ) or not ( false , default). */ steps?: boolean | undefined; /** * Indicates whether the returned route is roundtrip, meaning the route returns to the first location ( true , default) or not ( false ). * If roundtrip=false , the source and destination parameters are required but not all combinations will be possible. * See the Fixing Start and End Points section below for additional notes. */ roundtrip?: boolean | undefined; } interface Distribution { /** * Array index of the item containing coordinates for the pick-up location in the waypoints array */ pickup: number; /** * Array index of the item containing coordinates for the drop-off location in the waypoints array */ dropoff: number; } type OptimizationAnnotation = 'duration' | 'speed' | 'distance'; } declare module '@mapbox/mapbox-sdk/services/static' { import { LngLatLike, LngLatBoundsLike } from 'mapbox-gl'; import { MapiRequest } from '@mapbox/mapbox-sdk/lib/classes/mapi-request'; import MapiClient, { SdkConfig } from '@mapbox/mapbox-sdk/lib/classes/mapi-client'; /********************************************************************************************************************* * Static Map Types *********************************************************************************************************************/ export default function StaticMap(config: SdkConfig | MapiClient): StaticMapService; interface StaticMapService { /** * Get a static map image.. * @param request */ getStaticImage(request: StaticMapRequest): MapiRequest; } interface StaticMapRequest { ownerId: string; styleId: string; width: number; height: number; position: | { coordinates: LngLatLike | 'auto'; zoom: number; bearing?: number | undefined; pitch?: number | undefined; } | 'auto'; padding?: string | undefined; overlays?: Array<CustomMarkerOverlay | SimpleMarkerOverlay | PathOverlay | GeoJsonOverlay> | undefined; highRes?: boolean | undefined; insertOverlayBeforeLayer?: string | undefined; attribution?: boolean | undefined; logo?: boolean | undefined; } interface CustomMarkerOverlay { marker: CustomMarker; } interface CustomMarker { coordinates: LngLatLike; url: string; } interface SimpleMarkerOverlay { marker: SimpleMarker; } interface SimpleMarker { coordinates: LngLatLike; label?: string | undefined; color?: string | undefined; size?: 'large' | 'small' | undefined; } interface PathOverlay { path: Path; } interface Path { /** * An array of coordinates describing the path. */ coordinates: LngLatBoundsLike[]; strokeWidth?: number | undefined; strokeColor?: string | undefined; /** * Must be paired with strokeColor. */ strokeOpacity?: number | undefined; /** * Must be paired with strokeColor. */ fillColor?: string | undefined; /** * Must be paired with strokeColor. */ fillOpacity?: number | undefined; } interface GeoJsonOverlay { geoJson: GeoJSON.GeoJSON; } } declare module '@mapbox/mapbox-sdk/services/styles' { import { MapiRequest } from '@mapbox/mapbox-sdk/lib/classes/mapi-request'; import MapiClient, { SdkConfig } from '@mapbox/mapbox-sdk/lib/classes/mapi-client'; /********************************************************************************************************************* * Style Types *********************************************************************************************************************/ export default function Styles(config: SdkConfig | MapiClient): StylesService; interface StylesService { /** * Get a style. * @param styleId * @param ownerId */ getStyle(config: { styleId: string; ownerId?: string | undefined; metadata?: boolean | undefined; draft?: boolean | undefined; fresh?: boolean | undefined; }): MapiRequest; /** * Create a style. * @param style * @param ownerId */ createStyle(config: { style: Style; ownerId?: string | undefined }): MapiRequest; /** * Update a style. * @param styleId * @param style * @param lastKnownModification * @param ownerId */ // implicit any updateStyle(config: { styleId: string; style: Style; lastKnownModification?: string | number | Date | undefined; ownerId?: string | undefined; }): void; /** * Delete a style. * @param style * @param ownerId */ deleteStyle(config: { style: Style; ownerId?: string | undefined }): MapiRequest; /** * List styles in your account. * @param start * @param ownerId */ listStyles(config: { start?: string | undefined; ownerId?: string | undefined; fresh?: boolean | undefined }): MapiRequest; /** * Add an icon to a style, or update an existing one. * @param styleId * @param iconId * @param file * @param ownerId */ putStyleIcon(config: { styleId: string; iconId: string; file: Blob | ArrayBuffer | string; ownerId?: string | undefined; }): MapiRequest; /** * Remove an icon from a style. * @param styleId * @param iconId * @param ownerId */ // implicit any deleteStyleIcon(config: { styleId: string; iconId: string; ownerId?: string | undefined; draft?: boolean | undefined }): void; /** * Get a style sprite's image or JSON document. * @param styleId * @param format * @param highRes * @param ownerId */ getStyleSprite(config: { styleId: string; format?: 'json' | 'png' | undefined; highRes?: boolean | undefined; ownerId?: string | undefined; draft?: boolean | undefined; fresh?: boolean | undefined; }): MapiRequest; /** * Get a font glyph range. * @param fonts * @param start * @param end * @param ownerId */ getFontGlyphRange(config: { fonts: string[]; start: number; end: number; ownerId?: string | undefined }): MapiRequest; /** * Get embeddable HTML displaying a map. * @param config * @param styleId * @param scrollZoom * @param title * @param ownerId */ getEmbeddableHtml(config: { config: any; styleId: string; scrollZoom?: boolean | undefined; title?: boolean | undefined; fallback?: boolean | undefined; mapboxGLVersion?: string | undefined; mapboxGLGeocoderVersion?: string | undefined; ownerId?: string | undefined; draft?: string | undefined; }): MapiRequest; } interface Style { version: number; name: string; /** * Information about the style that is used in Mapbox Studio. */ metadata: string; sources: any; sprite: string; glyphs: string; layers: string[]; /** * Date and time the style was created. */ created: string; /** * The ID of the style. */ id: string; /** * Date and time the style was last modified. */ modified: string; /** * The username of the style owner. */ owner: string; /** * Access control for the style, either public or private . Private styles require an access token belonging to the owner, * while public styles may be requested with an access token belonging to any user. */ visibility: string; /** * Whether the style is a draft or has been published. */ draft: boolean; } } declare module '@mapbox/mapbox-sdk/services/tilequery' { import * as mapboxgl from 'mapbox-gl'; import { MapiRequest, Coordinates } from '@mapbox/mapbox-sdk/lib/classes/mapi-request'; import MapiClient, { SdkConfig } from '@mapbox/mapbox-sdk/lib/classes/mapi-client'; /********************************************************************************************************************* * Tile Query (Places) Types *********************************************************************************************************************/ export default function TileQuery(config: SdkConfig | MapiClient): TileQueryService; interface TileQueryService { /** * Get a static map image.. * @param request */ listFeatures(request: TileQueryRequest): MapiRequest; } interface TileQueryRequest { /** * The maps being queried. If you need to composite multiple layers, provide multiple map IDs. */ mapIds: string[]; /** * The longitude and latitude to be queried. */ coordinates: Coordinates; /** * The approximate distance in meters to query for features. (optional, default 0) */ radius?: number | undefined; /** * The number of features to return, between 1 and 50. (optional, default 5) */ limit?: number | undefined; /** * Whether or not to deduplicate results. (optional, default true) */ dedupe?: boolean | undefined; /** * Queries for a specific geometry type. */ geometry?: GeometryType | undefined; layers?: string[] | undefined; } type GeometryType = 'polygon' | 'linestring' | 'point'; } declare module '@mapbox/mapbox-sdk/services/tilesets' { import { MapiRequest } from '@mapbox/mapbox-sdk/lib/classes/mapi-request'; import MapiClient, { SdkConfig } from '@mapbox/mapbox-sdk/lib/classes/mapi-client'; /********************************************************************************************************************* * Tileset Types *********************************************************************************************************************/ export default function Tilesets(config: SdkConfig | MapiClient): TilesetsService; interface TilesetsService { listTilesets(config: { ownerId: string; type?: 'raster' | 'vector' | undefined; limit?: number | undefined; sortBy?: 'created' | 'modified' | undefined; start?: string | undefined; visibility?: 'public' | 'private' | undefined; }): MapiRequest; deleteTileset(config: { tilesetId: string }): MapiRequest; tileJSONMetadata(config: { tilesetId: string }): MapiRequest; createTilesetSource(config: { id: string; file: Blob | ArrayBuffer | string | NodeJS.ReadStream; ownerId?: string | undefined; }): MapiRequest; getTilesetSource(config: { id: string; ownerId?: string | undefined }): MapiRequest; listTilesetSources(config: { ownerId?: string | undefined; limit?: number | undefined; start?: string | undefined }): MapiRequest; deleteTilesetSource(config: { id: string; ownerId?: string | undefined }): MapiRequest; createTileset(config: { tilesetId: string; recipe: any; name: string; private?: boolean | undefined; description?: string | undefined; }): MapiRequest; publishTileset(config: { tilesetId: string }): MapiRequest; updateTileset(config: { tilesetId: string; name?: string | undefined; description?: string | undefined; private?: boolean | undefined; attribution?: Array<{ text?: string | undefined; link?: string | undefined }> | undefined; }): MapiRequest; tilesetStatus(config: { tilesetId: string }): MapiRequest; tilesetJob(config: { tilesetId: string; jobId: string }): MapiRequest; listTilesetJobs(config: { tilesetId: string; stage?: 'processing' | 'queued' | 'success' | 'failed' | undefined; limit?: number | undefined; start?: string | undefined; }): MapiRequest; getTilesetsQueue(): MapiRequest; validateRecipe(config: { recipe: any }): MapiRequest; getRecipe(config: { tilesetId: string }): MapiRequest; updateRecipe(config: { tilesetId: string; recipe: any }): MapiRequest; } interface Tileset { type: string; center: number[]; created: string; description: string; filesize: number; id: string; modified: string; name: string; visibility: string; status: string; } } declare module '@mapbox/mapbox-sdk/services/tokens' { import { MapiRequest } from '@mapbox/mapbox-sdk/lib/classes/mapi-request'; import { MapiResponse } from '@mapbox/mapbox-sdk/lib/classes/mapi-response'; import MapiClient, { SdkConfig } from '@mapbox/mapbox-sdk/lib/classes/mapi-client'; /********************************************************************************************************************* * Token Types *********************************************************************************************************************/ export default function Tokens(config: SdkConfig | MapiClient): TokensService; interface TokensService { /** * List your access tokens. */ listTokens(): MapiRequest; /** * Create a new access token. * @param request */ createToken(request: CreateTokenRequest): MapiRequest; /** * Create a new temporary access token. * @param request */ createTemporaryToken(request: TemporaryTokenRequest): MapiRequest; /** * Update an access token. * @param request */ updateToken(request: UpdateTokenRequest): MapiRequest; /** * Get data about the client's access token. */ getToken(): MapiRequest; /** * Delete an access token. * @param request */ deleteToken(request: { tokenId: string }): MapiRequest; /** * List your available scopes. Each item is a metadata object about the scope, not just the string scope. */ listScopes(): MapiRequest; } interface Token { /** * the identifier for the token */ id: string; /** * the type of token */ usage: string; /** * the client for the token, always 'api' */ client: string; /** * if the token is a default token */ default: boolean; /** * human friendly description of the token */ note: string; /** * array of scopes granted to the token */ scopes: string[]; /** * date and time the token was created */ created: string; /** * date and time the token was last modified */ modified: string; /** * the token itself */ token: string; } interface CreateTokenRequest { note?: string | undefined; scopes?: string[] | undefined; resources?: string[] | undefined; allowedUrls?: string[] | undefined; } interface TemporaryTokenRequest { expires: string; scopes: string[]; } interface UpdateTokenRequest extends CreateTokenRequest { tokenId: string; } interface TokenDetail { code: string; token: Token; } interface Scope { id: string; public: boolean; description: string; } } declare module '@mapbox/mapbox-sdk/services/uploads' { import { MapiRequest } from '@mapbox/mapbox-sdk/lib/classes/mapi-request'; import MapiClient, { SdkConfig } from '@mapbox/mapbox-sdk/lib/classes/mapi-client'; /********************************************************************************************************************* * Uploads Types *********************************************************************************************************************/ export default function Uploads(config: SdkConfig | MapiClient): UploadsService; interface UploadsService { /** * List the statuses of all recent uploads. * @param config */ listUploads(config?: { reverse?: boolean | undefined }): MapiRequest; /** * Create S3 credentials. */ createUploadCredentials(): MapiRequest; /** * Create an upload. * @param config */ createUpload(config: { tileset: string; url: string; name?: string | undefined }): MapiRequest; /** * Get an upload's status. * @param config */ // implicit any getUpload(config: { uploadId: string }): any; /** * Delete an upload. * @param config */ // implicit any deleteUpload(config: { uploadId: string }): any; } interface S3Credentials { accessKeyId: string; bucket: string; key: string; secretAccessKey: string; sessionToken: string; url: string; } interface UploadResponse { complete: boolean; tileset: string; error?: any; id: string; name: string; modified: string; created: string; owner: string; progress: number; } }
the_stack
import * as tf from '@tensorflow/tfjs-core'; import {ExplicitPadding} from '@tensorflow/tfjs-core/dist/ops/conv_util'; import {MLAutoPad, MLConv2dOptions, MLFilterOperandLayout, MLInputOperandLayout} from '../graph_builder'; import {ConstantOperand, MLOperand, OutputOperand} from '../operand'; import {FusedOperation, MLOperator, SingleOutputOperation} from '../operation'; import * as utils from '../utils'; import {Clamp} from './clamp'; import {LeakyRelu} from './leaky_relu'; import {Relu, Sigmoid} from './unary'; export class Conv2d extends SingleOutputOperation implements FusedOperation { private input_: MLOperand; private filter_: MLOperand; private bias_: MLOperand; private padding_?: [number, number, number, number]; private strides_?: [number, number]; private dilations_?: [number, number]; private groups_?: number; private inputLayout_?: MLInputOperandLayout; private filterLayout_?: MLFilterOperandLayout; private autoPad_?: MLAutoPad; private outputPadding_?: [number, number]; private outputSizes_?: [number, number]; private transpose_?: boolean; private activation_?: MLOperator; private fusedActivation_?: tf.fused.Activation; private leakyreluAlpha_?: number; private filterTensor_?: tf.Tensor4D; constructor( input: MLOperand, filter: MLOperand, options: MLConv2dOptions = {}) { super(input.builder); utils.validateOperand(input); this.input_ = input; utils.validateOperand(filter); this.filter_ = filter; utils.assert( !(options.autoPad === MLAutoPad.explicit && options.padding === undefined), 'The padding parameter should be assigned when autoPad is explicit.'); this.initOptions( options.padding, options.strides, options.dilations, options.groups, options.inputLayout, options.filterLayout, options.autoPad, options.transpose, options.outputPadding, options.outputSizes, options.bias, options.activation); } private initOptions( padding: [number, number, number, number] = [0, 0, 0, 0], strides: [number, number] = [1, 1], dilations: [number, number] = [1, 1], groups = 1, inputLayout: MLInputOperandLayout = MLInputOperandLayout.nchw, filterLayout: MLFilterOperandLayout = MLFilterOperandLayout.oihw, autoPad: MLAutoPad = MLAutoPad.explicit, transpose = false, outputPadding: [number, number] = [0, 0], outputSizes: [number, number] = undefined, bias: MLOperand = undefined, activation: MLOperator = undefined) { utils.assert( utils.isIntegerArray(padding) && padding.length === 4, 'The padding parameter is invalid.'); this.padding_ = padding; utils.assert( utils.isIntegerArray(strides) && strides.length === 2, 'The strides parameter is invalid.'); this.strides_ = strides; utils.assert( utils.isIntegerArray(dilations) && dilations.length === 2, 'The dilations parameter is invalid.'); this.dilations_ = dilations; utils.assert(utils.isInteger(groups), 'The gourps parameter is invalid.'); this.groups_ = groups; utils.assert( inputLayout in MLInputOperandLayout, 'The input layout parameter is invalid.'); this.inputLayout_ = inputLayout; utils.assert( filterLayout in MLFilterOperandLayout, 'The filter layout parameter is invalid.'); this.filterLayout_ = filterLayout; utils.assert(autoPad in MLAutoPad, 'The autoPad parameter is invalid.'); this.autoPad_ = autoPad; this.transpose_ = transpose; if (this.transpose_) { utils.assert( utils.isIntegerArray(outputPadding) && outputPadding.length === 2, 'The outputPadding parameter is invalid.'); this.outputPadding_ = outputPadding; utils.assert( outputSizes === undefined || (utils.isIntegerArray(outputSizes) && outputSizes.length === 2), 'The outputSizes parameter is invalid.'); this.outputSizes_ = outputSizes; } else { this.outputPadding_ = [0, 0]; this.outputSizes_ = undefined; } this.bias_ = bias; if (this.bias_) { utils.validateOperand(this.bias_); } if (activation instanceof Relu) { this.fusedActivation_ = 'relu'; this.activation_ = undefined; } else if (this.isRelu6(activation)) { this.fusedActivation_ = 'relu6'; this.activation_ = undefined; } else if (activation instanceof LeakyRelu) { this.fusedActivation_ = 'leakyrelu'; this.leakyreluAlpha_ = (activation).alpha; this.activation_ = undefined; } else if (activation instanceof Sigmoid) { this.fusedActivation_ = 'sigmoid'; this.activation_ = undefined; } else { this.fusedActivation_ = undefined; this.activation_ = activation; } } isRelu6(activation: MLOperator): boolean { if (activation instanceof Clamp) { const clamp = activation; if (Math.abs(clamp.minValue - 0.0) < 1e-5 && Math.abs(clamp.maxValue - 6.0) < 1e-5) { return true; } } return false; } getFusedOutputs(): OutputOperand[] { if (this.activation_) { return [this.activation_.apply(this.output)]; } else { return [this.output]; } } inputs(): MLOperand[] { const inputs = [this.input_, this.filter_]; if (this.bias_) { inputs.push(this.bias_); } return inputs; } run(inputTensors: Map<MLOperand, tf.Tensor>): tf.Tensor { let input: tf.Tensor4D = inputTensors.get(this.input_) as tf.Tensor4D; let filter: tf.Tensor4D; let bias: tf.Tensor1D; let fused = false; if (this.bias_) { bias = inputTensors.get(this.bias_) as tf.Tensor1D; } // tf.conv2d input layout (nhwc): [batch, height, width, inDepth] if (this.inputLayout_ === MLInputOperandLayout.nchw) { // nchw -> nhwc input = tf.transpose(input, [0, 2, 3, 1]); } const inputChannels = input.shape[3]; if (this.filterTensor_ === undefined) { filter = inputTensors.get(this.filter_) as tf.Tensor4D; if (this.transpose_ === false) { // tf.conv2d filter layout (hwio): [filterHeight, filterWidth, inDepth, // outDepth] if (this.filterLayout_ === MLFilterOperandLayout.oihw) { filter = tf.transpose(filter, [2, 3, 1, 0]); } else if (this.filterLayout_ === MLFilterOperandLayout.ohwi) { filter = tf.transpose(filter, [1, 2, 3, 0]); } else if (this.filterLayout_ === MLFilterOperandLayout.ihwo) { filter = tf.transpose(filter, [1, 2, 0, 3]); } } else { // tf.conv2dTranspose filter layout (hwoi): [filterHeight, filterWidth, // outDepth, inDepth] if (this.filterLayout_ === MLFilterOperandLayout.oihw) { filter = tf.transpose(filter, [2, 3, 0, 1]); } else if (this.filterLayout_ === MLFilterOperandLayout.hwio) { filter = tf.transpose(filter, [0, 1, 3, 2]); } else if (this.filterLayout_ === MLFilterOperandLayout.ohwi) { filter = tf.transpose(filter, [1, 2, 0, 3]); } else if (this.filterLayout_ === MLFilterOperandLayout.ihwo) { filter = tf.transpose(filter, [1, 2, 3, 0]); } } if (this.groups_ !== 1) { // filter layout hwio // tf.depthwiseConv2d filter layout: [filterHeight, filterWidth, // inChannels, channelMultiplier] filter = tf.transpose(filter, [0, 1, 3, 2]); } if (this.filter_ instanceof ConstantOperand) { this.filterTensor_ = filter; tf.keep(this.filterTensor_); } } else { filter = this.filterTensor_; } const padding: 'valid'|'same'|ExplicitPadding = utils.getPaddings( input, filter, this.padding_, this.strides_, this.outputPadding_, this.dilations_, this.autoPad_); let output; if (this.transpose_ === false) { if (this.groups_ === 1) { output = tf.fused.conv2d({ x: input, filter, strides: this.strides_, pad: padding, dataFormat: 'NHWC', dilations: this.dilations_, bias, activation: this.fusedActivation_, leakyreluAlpha: this.leakyreluAlpha_ }); fused = true; } else if ( this.groups_ === inputChannels && this.groups_ === filter.shape[2]) { if (padding === 'valid' || padding === 'same' || (padding instanceof Array && padding[1][0] === padding[1][1] && padding[1][0] === padding[2][0] && padding[1][0] === padding[2][1])) { let fusedDepthwisePad: 'valid'|'same'|number; if (padding === 'valid' || padding === 'same') { fusedDepthwisePad = padding; } else { fusedDepthwisePad = padding[1][0]; } output = tf.fused.depthwiseConv2d({ x: input, filter, strides: this.strides_, pad: fusedDepthwisePad, dataFormat: 'NHWC', dilations: this.dilations_, bias, activation: this.fusedActivation_, leakyreluAlpha: this.leakyreluAlpha_ }); fused = true; } else { output = tf.depthwiseConv2d( input, filter, this.strides_, padding, 'NHWC', this.dilations_); } } else { throw new Error( 'The tf.js convolution doesn\'t support groups parameter' + ` ${this.groups_}`); } } else { // transpose == true if (this.autoPad_ !== MLAutoPad.explicit) { this.outputSizes_ = [ input.shape[1] * this.strides_[0], input.shape[2] * this.strides_[1], ]; } // tf.conv2dTranspose outputShape: [batch, height, width, outDepth] const outputShape: [number, number, number, number] = [input.shape[0], 0, 0, filter.shape[2]]; if (this.outputSizes_ === undefined) { for (let i = 0; i < 2; ++i) { outputShape[i + 1] = this.strides_[i] * (input.shape[i + 1] - 1) + this.outputPadding_[i] + ((filter.shape[i] - 1) * this.dilations_[i] + 1) - this.padding_[i * 2] - this.padding_[i * 2 + 1]; } } else { outputShape[1] = this.outputSizes_[0]; outputShape[2] = this.outputSizes_[1]; } output = tf.conv2dTranspose( input, filter, outputShape, this.strides_, padding); } if (!fused) { if (bias) { // output is still nhwc output = tf.add(output, bias); } if (this.fusedActivation_ === 'relu') { output = tf.relu(output); } else if (this.fusedActivation_ === 'relu6') { output = tf.clipByValue(output, 0, 6); } else if (this.fusedActivation_ === 'leakyrelu') { output = tf.leakyRelu(output, this.leakyreluAlpha_); } else if (this.fusedActivation_ === 'sigmoid') { output = tf.sigmoid(output); } else if (this.fusedActivation_ !== undefined) { utils.assert(false, `The ${this.fusedActivation_} is un supported.`); } } if (this.inputLayout_ === MLInputOperandLayout.nchw) { // nhwc -> nchw output = tf.transpose(output, [0, 3, 1, 2]); } return output; } dispose(): void { if (this.filterTensor_) { tf.dispose(this.filterTensor_); } } }
the_stack
import * as anchor from '@project-serum/anchor'; import { assert } from 'chai'; import { BN } from '../sdk'; import { getFeedData, mockOracle, mockUserUSDCAccount, mockUSDCMint, setFeedPrice, } from './testHelpers'; import { calculateMarkPrice, PEG_PRECISION, PositionDirection, QUOTE_PRECISION, calculateTargetPriceTrade, convertToNumber, } from '../sdk'; import { Program } from '@project-serum/anchor'; import { Keypair, PublicKey } from '@solana/web3.js'; import { Admin, MARK_PRICE_PRECISION, FUNDING_PAYMENT_PRECISION, ClearingHouse, ClearingHouseUser, } from '../sdk/src'; import { initUserAccounts } from '../stress/stressUtils'; async function updateFundingRateHelper( clearingHouse: ClearingHouse, marketIndex: BN, priceFeedAddress: PublicKey, prices: Array<number> ) { for (let i = 0; i < prices.length; i++) { await new Promise((r) => setTimeout(r, 1000)); // wait 1 second const newprice = prices[i]; setFeedPrice(anchor.workspace.Pyth, newprice, priceFeedAddress); const marketsAccount0 = await clearingHouse.getMarketsAccount(); const marketData0 = marketsAccount0.markets[marketIndex.toNumber()]; const ammAccountState0 = marketData0.amm; const oraclePx0 = await getFeedData( anchor.workspace.Pyth, ammAccountState0.oracle ); const priceSpread0 = convertToNumber(ammAccountState0.lastMarkPriceTwap) - oraclePx0.twap; const frontEndFundingCalc0 = priceSpread0 / oraclePx0.twap / (24 * 3600); console.log( 'funding rate frontend calc0:', frontEndFundingCalc0, 'markTwap0:', ammAccountState0.lastMarkPriceTwap.toNumber() / MARK_PRICE_PRECISION.toNumber(), 'markTwap0:', ammAccountState0.lastMarkPriceTwap.toNumber(), 'oracleTwap0:', oraclePx0.twap, 'priceSpread', priceSpread0 ); const cumulativeFundingRateLongOld = ammAccountState0.cumulativeFundingRateLong; const cumulativeFundingRateShortOld = ammAccountState0.cumulativeFundingRateShort; const _tx = await clearingHouse.updateFundingRate( priceFeedAddress, marketIndex ); const CONVERSION_SCALE = FUNDING_PAYMENT_PRECISION.mul(MARK_PRICE_PRECISION); const marketsAccount = await clearingHouse.getMarketsAccount(); const marketData = marketsAccount.markets[marketIndex.toNumber()]; const ammAccountState = marketData.amm; const peroidicity = marketData.amm.fundingPeriod; const lastFundingRate = convertToNumber( ammAccountState.lastFundingRate, CONVERSION_SCALE ); console.log('last funding rate:', lastFundingRate); console.log( 'cumfunding rate:', convertToNumber(ammAccountState.cumulativeFundingRate, CONVERSION_SCALE), 'cumfunding rate long', convertToNumber( ammAccountState.cumulativeFundingRateLong, CONVERSION_SCALE ), 'cumfunding rate short', convertToNumber( ammAccountState.cumulativeFundingRateShort, CONVERSION_SCALE ) ); const lastFundingLong = ammAccountState.cumulativeFundingRateLong .sub(cumulativeFundingRateLongOld) .abs(); const lastFundingShort = ammAccountState.cumulativeFundingRateShort .sub(cumulativeFundingRateShortOld) .abs(); assert(ammAccountState.lastFundingRate.abs().gte(lastFundingLong.abs())); assert(ammAccountState.lastFundingRate.abs().gte(lastFundingShort.abs())); const oraclePx = await getFeedData( anchor.workspace.Pyth, ammAccountState.oracle ); const priceSpread = ammAccountState.lastMarkPriceTwap.toNumber() / MARK_PRICE_PRECISION.toNumber() - oraclePx.twap; const frontEndFundingCalc = priceSpread / ((24 * 3600) / Math.max(1, peroidicity.toNumber())); console.log( 'funding rate frontend calc:', frontEndFundingCalc, 'markTwap:', ammAccountState.lastMarkPriceTwap.toNumber() / MARK_PRICE_PRECISION.toNumber(), 'markTwap:', ammAccountState.lastMarkPriceTwap.toNumber(), 'oracleTwap:', oraclePx.twap, 'priceSpread:', priceSpread ); const s = new Date(ammAccountState.lastMarkPriceTwapTs.toNumber() * 1000); const sdate = s.toLocaleDateString('en-US'); const stime = s.toLocaleTimeString('en-US'); console.log('funding rate timestamp:', sdate, stime); // assert(Math.abs(frontEndFundingCalc - lastFundingRate) < 9e-6); } } describe('pyth-oracle', () => { const provider = anchor.AnchorProvider.local(undefined, { commitment: 'confirmed', preflightCommitment: 'confirmed', }); const connection = provider.connection; anchor.setProvider(provider); const program = anchor.workspace.Pyth; const chProgram = anchor.workspace.ClearingHouse as Program; let clearingHouse: Admin; let clearingHouse2: ClearingHouse; let usdcMint: Keypair; let userUSDCAccount: Keypair; const ammInitialQuoteAssetAmount = new anchor.BN(5 * 10 ** 13); const ammInitialBaseAssetAmount = new anchor.BN(5 * 10 ** 13); const usdcAmount = new BN(10 * 10 ** 6); let userAccount: ClearingHouseUser; let userAccount2: ClearingHouseUser; before(async () => { usdcMint = await mockUSDCMint(provider); userUSDCAccount = await mockUserUSDCAccount(usdcMint, usdcAmount, provider); clearingHouse = Admin.from( connection, provider.wallet, chProgram.programId, { commitment: 'confirmed', } ); await clearingHouse.initialize(usdcMint.publicKey, true); await clearingHouse.subscribe(); const price = 50000; await mockOracle(price, -6); await clearingHouse.initializeUserAccount(); userAccount = ClearingHouseUser.from( clearingHouse, provider.wallet.publicKey ); await userAccount.subscribe(); await clearingHouse.depositCollateral( usdcAmount, userUSDCAccount.publicKey ); // create <NUM_USERS> users with 10k that collectively do <NUM_EVENTS> actions const [_userUSDCAccounts, _user_keys, clearingHouses, userAccountInfos] = await initUserAccounts(1, usdcMint, usdcAmount, provider); clearingHouse2 = clearingHouses[0]; userAccount2 = userAccountInfos[0]; // await clearingHouse.depositCollateral( // await userAccount2.getPublicKey(), // usdcAmount, // userUSDCAccounts[1].publicKey // ); }); after(async () => { await clearingHouse.unsubscribe(); await userAccount.unsubscribe(); await clearingHouse2.unsubscribe(); await userAccount2.unsubscribe(); }); it('change feed price', async () => { const price = 50000; const expo = -9; const priceFeedAddress = await mockOracle(price, expo); const feedDataBefore = await getFeedData(program, priceFeedAddress); assert.ok(feedDataBefore.price === price); assert.ok(feedDataBefore.exponent === expo); const newPrice = 55000; await setFeedPrice(program, newPrice, priceFeedAddress); const feedDataAfter = await getFeedData(program, priceFeedAddress); assert.ok(feedDataAfter.price === newPrice); assert.ok(feedDataAfter.exponent === expo); }); it('oracle/vamm: funding rate calc 0hour periodicity', async () => { const priceFeedAddress = await mockOracle(40, -10); const periodicity = new BN(0); // 1 HOUR const marketIndex = new BN(0); await clearingHouse.initializeMarket( marketIndex, priceFeedAddress, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount, periodicity, new BN(39.99 * PEG_PRECISION.toNumber()) ); await updateFundingRateHelper( clearingHouse, marketIndex, priceFeedAddress, [42] ); }); it('oracle/vamm: funding rate calc2 0hour periodicity', async () => { const priceFeedAddress = await mockOracle(40, -10); const periodicity = new BN(0); const marketIndex = new BN(1); await clearingHouse.initializeMarket( marketIndex, priceFeedAddress, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount, periodicity, new BN(41.7 * PEG_PRECISION.toNumber()) ); // await clearingHouse.moveAmmToPrice( // marketIndex, // new BN(41.5 * MARK_PRICE_PRECISION.toNumber()) // ); await updateFundingRateHelper( clearingHouse, marketIndex, priceFeedAddress, [41.501, 41.499] ); }); it('oracle/vamm: asym funding rate calc 0hour periodicity', async () => { const marketIndex = new BN(1); // await clearingHouse.moveAmmToPrice( // marketIndex, // new BN(41.5 * MARK_PRICE_PRECISION.toNumber()) // ); console.log( 'PRICE', convertToNumber(calculateMarkPrice(clearingHouse.getMarket(marketIndex))) ); await clearingHouse.openPosition( PositionDirection.LONG, QUOTE_PRECISION, marketIndex ); await clearingHouse2.openPosition( PositionDirection.SHORT, QUOTE_PRECISION.div(new BN(2)), marketIndex ); const market = clearingHouse.getMarketsAccount().markets[marketIndex.toNumber()]; await updateFundingRateHelper( clearingHouse, marketIndex, market.amm.oracle, [41.501, 41.499] ); const marketNew = clearingHouse.getMarketsAccount().markets[marketIndex.toNumber()]; const fundingRateLong = marketNew.amm.cumulativeFundingRateLong.sub( market.amm.cumulativeFundingRateLong ); const fundingRateShort = marketNew.amm.cumulativeFundingRateShort.sub( market.amm.cumulativeFundingRateShort ); // more dollars long than short assert(fundingRateLong.gt(new BN(0))); assert(fundingRateShort.gt(new BN(0))); // assert(fundingRateShort.gt(fundingRateLong)); }); it('new LONG trade above oracle-mark limit fails', async () => { const marketIndex = new BN(1); const market = clearingHouse.getMarketsAccount().markets[marketIndex.toNumber()]; const baseAssetPriceWithMantissa = calculateMarkPrice(market); const targetPriceDefaultSlippage = baseAssetPriceWithMantissa.add( baseAssetPriceWithMantissa.div(new BN(11)) ); // < 10% increase console.log( 'SUCCEEDS: price from', convertToNumber(baseAssetPriceWithMantissa), '->', convertToNumber(targetPriceDefaultSlippage) ); const [_directionSuc, _tradeSizeSuc, _entryPriceSuc] = calculateTargetPriceTrade( clearingHouse.getMarket(marketIndex), BN.max(targetPriceDefaultSlippage, new BN(1)) ); // await clearingHouse.openPosition( // PositionDirection.LONG, // tradeSizeSuc, // marketIndex // ); // await clearingHouse.closePosition( // marketIndex // ); const targetPriceFails = baseAssetPriceWithMantissa.add( baseAssetPriceWithMantissa.div(new BN(9)) ); // > 10% increase console.log( 'FAILS: price from', convertToNumber(baseAssetPriceWithMantissa), '->', convertToNumber(targetPriceFails) ); const [_direction, tradeSize, _entryPrice] = calculateTargetPriceTrade( clearingHouse.getMarket(marketIndex), BN.max(targetPriceFails, new BN(1)) ); try { await clearingHouse.openPosition( PositionDirection.LONG, tradeSize, marketIndex ); assert(false, 'Order succeeded'); } catch (e) { if (e.message == 'Order succeeded') { assert(false, 'Order succeeded'); } assert(true); } }); });
the_stack