diff --git a/AISKU/README.md b/AISKU/README.md index 3417e6a5..a3b7275b 100644 --- a/AISKU/README.md +++ b/AISKU/README.md @@ -22,10 +22,18 @@ Application Insights SDK is a package that combines commonly used packages for Web scenarios. Refer to [our GitHub page](https://github.com/microsoft/applicationinsights-js) for more details on getting started. +## Beta Release Breaking changes + +- Removed ES3 / IE8 Support +- Removed V1 API Backward Compatibility (Upgrading V1 -> V3) + +See [Breaking Changes](./BETA_BREAKING_CHANGES.md) + ## CDN Version Release Summary (with Size tracking) | Version | Full Size | Raw Minified | GZip Size |---------|-----------|--------------|------------- +| <v3 beta> | [![full size size](https://img.badgesize.io/https://js.monitor.azure.com/beta/ai.3-beta.js.svg?label=full%20size&color=blue)](https://img.badgesize.io/https://js.monitor.azure.com/beta/ai.3-beta.js.svg?label=full%20size&color=blue)| ![minified size size](https://img.badgesize.io/https://js.monitor.azure.com/beta/ai.3-beta.min.js.svg?label=minified%20size&color=darkorchid) | ![gzip size](https://img.badgesize.io/https://js.monitor.azure.com/beta/ai.3-beta.min.js.svg?compression=gzip&softmax=30000&max=35000) | <nightly> | [![full size size](https://img.badgesize.io/https://js.monitor.azure.com/nightly/ai.2-nightly.js.svg?label=full%20size&color=blue)](https://img.badgesize.io/https://js.monitor.azure.com/nightly/ai.2-nightly.js.svg?label=full%20size&color=blue)| ![minified size size](https://img.badgesize.io/https://js.monitor.azure.com/nightly/ai.2-nightly.min.js.svg?label=minified%20size&color=darkorchid) | ![gzip size](https://img.badgesize.io/https://js.monitor.azure.com/nightly/ai.2-nightly.min.js.svg?compression=gzip&softmax=30000&max=35000) | 2.8.6: | [![full size size](https://img.badgesize.io/https://js.monitor.azure.com/scripts/b/ai.2.8.6.js.svg?label=full%20size&color=blue)](https://img.badgesize.io/https://js.monitor.azure.com/scripts/b/ai.2.8.6.js.svg?label=full%20size&color=blue)| ![minified size size](https://img.badgesize.io/https://js.monitor.azure.com/scripts/b/ai.2.8.6.min.js.svg?label=minified%20size&color=darkorchid) | ![gzip size](https://img.badgesize.io/https://js.monitor.azure.com/scripts/b/ai.2.8.6.min.js.svg?compression=gzip&softmax=30000&max=35000) | 2.8.5: | [![full size size](https://img.badgesize.io/https://js.monitor.azure.com/scripts/b/ai.2.8.5.js.svg?label=full%20size&color=blue)](https://img.badgesize.io/https://js.monitor.azure.com/scripts/b/ai.2.8.5.js.svg?label=full%20size&color=blue)| ![minified size size](https://img.badgesize.io/https://js.monitor.azure.com/scripts/b/ai.2.8.5.min.js.svg?label=minified%20size&color=darkorchid) | ![gzip size](https://img.badgesize.io/https://js.monitor.azure.com/scripts/b/ai.2.8.5.min.js.svg?compression=gzip&softmax=30000&max=35000) diff --git a/AISKU/Tests/Unit/src/ApplicationInsightsDeprecatedTests.ts b/AISKU/Tests/Unit/src/ApplicationInsightsDeprecatedTests.ts deleted file mode 100644 index c9fdc991..00000000 --- a/AISKU/Tests/Unit/src/ApplicationInsightsDeprecatedTests.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { IAppInsightsDeprecated } from "../../../src/ApplicationInsightsDeprecated"; -import { ApplicationInsightsContainer } from "../../../src/ApplicationInsightsContainer"; -import { Snippet } from "../../../src/Initialization"; -import { Sender } from "@microsoft/applicationinsights-channel-js"; -import { SinonSpy } from "sinon"; -import { AITestClass, Assert, PollingAssert } from "@microsoft/ai-test-framework"; - -export class ApplicationInsightsDeprecatedTests extends AITestClass { - private static readonly _instrumentationKey = 'b7170927-2d1c-44f1-acec-59f4e1751c11'; - private _aiDeprecated: IAppInsightsDeprecated; - private _snippet: Snippet; - - // Sinon - private errorSpy: SinonSpy; - private successSpy: SinonSpy; - private loggingSpy: SinonSpy; - private clearSpy: SinonSpy; - private _name = "ApplicationInsightsDeprecatedTests: "; - - constructor() { - super("ApplicationInsightsDeprecatedTests"); - - // this.assertNoEvents = false; - // this.assertNoHooks = false; - } - - public testInitialize() { - try { - this.useFakeServer = false; - this._snippet = { - config: { - instrumentationKey: ApplicationInsightsDeprecatedTests._instrumentationKey, - disableAjaxTracking: false, - disableFetchTracking: false, - maxBatchInterval: 2500 - }, - queue: [], - version: 1.0 - } - - this._aiDeprecated = ((ApplicationInsightsContainer.getAppInsights(this._snippet, this._snippet.version)) as IAppInsightsDeprecated); - // Setup Sinon stuff - const appInsights = (this._aiDeprecated as any).appInsightsNew; - const sender: Sender = appInsights.core.getTransmissionControls()[0][0] as Sender; - this.errorSpy = this.sandbox.spy(sender, '_onError'); - this.successSpy = this.sandbox.spy(sender, '_onSuccess'); - this.loggingSpy = this.sandbox.stub(appInsights.core.logger, 'throwInternal'); - } catch (e) { - console.error('Failed to initialize'); - } - } - - public testFinishedCleanup(): void { - if (this._snippet) { - if (this._snippet["unload"]) { - // force unload - this._snippet["unload"](false); - } else { - const appInsights = (this._aiDeprecated as any).appInsightsNew; - if (appInsights.unload) { - appInsights.unload(false); - } - } - } - } - - public registerTests() { - - this.addApiTests(); - this.testCase({ - name: 'config.oldApiSupport set to true returns support for 1.0 apis', - test: () => { - - Assert.ok(this._aiDeprecated, 'ApplicationInsights SDK exists'); - Assert.ok((this._aiDeprecated as IAppInsightsDeprecated).downloadAndSetup); // has legacy method - } - }); - } - - public addApiTests(): void { - this.testCaseAsync({ - name: this._name + 'ApplicationInsightsDeprecatedTests: trackEvent sends to backend', - stepDelay: 1, - steps: [() => { - this._aiDeprecated.trackEvent('event'); - }].concat(this.asserts(1)) - }); - - this.testCaseAsync({ - name: this._name + 'trackTrace sends to backend', - stepDelay: 1, - steps: [() => { - this._aiDeprecated.trackTrace('trace'); - }].concat(this.asserts(1)) - }); - - this.testCaseAsync({ - name: this._name + 'trackException sends to backend', - stepDelay: 1, - steps: [() => { - let exception: Error = null; - try { - window['a']['b'](); - Assert.ok(false, 'trackException test not run'); - } catch (e) { - exception = e; - this._aiDeprecated.trackException(exception); - } - Assert.ok(exception); - }].concat(this.asserts(1)) - }); - - this.testCaseAsync({ - name: this._name + "track metric", - stepDelay: 1, - steps: [ - () => { - console.log("* calling trackMetric " + new Date().toISOString()); - for (let i = 0; i < 100; i++) { - this._aiDeprecated.trackMetric("test" + i,Math.round(100 * Math.random())); - } - console.log("* done calling trackMetric " + new Date().toISOString()); - } - ].concat(this.asserts(100)) - }); - - this.testCaseAsync({ - name: this._name + "track page view", - stepDelay: 1, - steps: [ - () => { - this._aiDeprecated.trackPageView(); // sends 2 - } - ].concat(this.asserts(2)) - }); - } - - private boilerPlateAsserts = () => { - Assert.ok(this.successSpy.called, "success"); - Assert.ok(!this.errorSpy.called, "no error sending"); - const isValidCallCount = this.loggingSpy.callCount === 0; - Assert.ok(isValidCallCount, "logging spy was called 0 time(s)"); - if (!isValidCallCount) { - while (this.loggingSpy.args.length) { - Assert.ok(false, "[warning thrown]: " + this.loggingSpy.args.pop()); - } - } - } - private asserts: any = (expectedCount: number) => [() => { - const message = "polling: " + new Date().toISOString(); - Assert.ok(true, message); - console.log(message); - - if (this.successSpy.called) { - this.boilerPlateAsserts(); - this.testCleanup(); - } else if (this.errorSpy.called || this.loggingSpy.called) { - this.boilerPlateAsserts(); - } - }, - (PollingAssert.createPollingAssert(() => { - Assert.ok(true, "* checking success spy " + new Date().toISOString()); - - if(this.successSpy.called) { - let currentCount: number = 0; - this.successSpy.args.forEach(call => { - call[0].forEach(message => { - // Ignore the internal SendBrowserInfoOnUserInit message (Only occurs when running tests in a browser) - if (message.indexOf("AI (Internal): 72 ") == -1) { - currentCount ++; - } - }); - }); - console.log('curr: ' + currentCount + ' exp: ' + expectedCount); - return currentCount === expectedCount; - } else { - return false; - } - }, "sender succeeded", 30, 1000))]; -} \ No newline at end of file diff --git a/AISKU/Tests/Unit/src/CdnPackaging.tests.ts b/AISKU/Tests/Unit/src/CdnPackaging.tests.ts index 8dc1181a..af188a09 100644 --- a/AISKU/Tests/Unit/src/CdnPackaging.tests.ts +++ b/AISKU/Tests/Unit/src/CdnPackaging.tests.ts @@ -61,9 +61,9 @@ export class CdnPackagingChecks extends AITestClass { private _validateExpectedExports(theExports: any) { Assert.ok(theExports.ApplicationInsights, "ApplicationInsights exists"); - Assert.ok(theExports.Telemetry, "Telemetry exists"); - Assert.ok(theExports.Telemetry.DistributedTracingModes, "Telemetry.DistributedTracingModes exists"); - Assert.ok(theExports.Telemetry.Util, "Telemetry exists"); + Assert.ok(!theExports.Telemetry, "Telemetry no longer exists"); + // Assert.ok(theExports.Telemetry.DistributedTracingModes, "Telemetry.DistributedTracingModes exists"); + // Assert.ok(theExports.Telemetry.Util, "Telemetry exists"); Assert.ok(theExports.LoggingSeverity, "LoggingSeverity exists"); objForEachKey(LoggingSeverity, (name, value) => { @@ -74,7 +74,7 @@ export class CdnPackagingChecks extends AITestClass { Assert.ok(theExports.PerfEvent, "PerfEvent exists"); Assert.ok(theExports.PerfManager, "PerfManager exists"); Assert.ok(theExports.doPerf, "doPerf exists"); - Assert.ok(theExports.CoreUtils, "CoreUtils exists"); + Assert.ok(!theExports.CoreUtils, "CoreUtils no longer exists"); Assert.ok(theExports.newId, "newId exists"); Assert.ok(theExports.newGuid, "newGuid exists"); Assert.ok(theExports.random32, "random32 exists"); @@ -90,8 +90,8 @@ export class CdnPackagingChecks extends AITestClass { Assert.ok(theExports.isBeaconsSupported, "isBeaconsSupported exists"); - Assert.ok(theExports.Util, "Util exists"); - Assert.equal(theExports.Util, theExports.Telemetry.Util, "Telemetry.Util matches Util"); + Assert.ok(!theExports.Util, "Util no longer exists"); + // Assert.equal(theExports.Util, theExports.Telemetry.Util, "Telemetry.Util matches Util"); Assert.ok(theExports.RequestHeaders, "RequestHeaders exists"); objForEachKey(RequestHeaders, (name, value) => { Assert.equal(value, theExports.RequestHeaders[name], `Checking RequestHeaders.${value} === ${name}`); @@ -108,7 +108,6 @@ export class CdnPackagingChecks extends AITestClass { }); Assert.ok(theExports.DistributedTracingModes, "DistributedTracingModes exists"); - Assert.equal(theExports.DistributedTracingModes, theExports.Telemetry.DistributedTracingModes, "Telemetry.DistributedTracingModes equals DistributedTracingModes"); objForEachKey(DistributedTracingModes, (name, value) => { Assert.equal(name, theExports.DistributedTracingModes[value], `Checking DistributedTracingMode.${name} === ${value}`); Assert.equal(value, theExports.DistributedTracingModes[name], `Checking DistributedTracingMode.${value} === ${name}`); diff --git a/AISKU/Tests/Unit/src/SnippetInitialization.Tests.ts b/AISKU/Tests/Unit/src/SnippetInitialization.Tests.ts index 3571b0e0..b3e51136 100644 --- a/AISKU/Tests/Unit/src/SnippetInitialization.Tests.ts +++ b/AISKU/Tests/Unit/src/SnippetInitialization.Tests.ts @@ -1,12 +1,11 @@ -import { IAppInsightsDeprecated } from "../../../src/ApplicationInsightsDeprecated"; import { ApplicationInsightsContainer } from "../../../src/ApplicationInsightsContainer"; import { IApplicationInsights, Snippet } from "../../../src/Initialization"; import { Sender } from "@microsoft/applicationinsights-channel-js"; import { SinonSpy } from "sinon"; import { AITestClass, Assert, PollingAssert } from "@microsoft/ai-test-framework"; import { createSnippetV5 } from "./testSnippet"; -import { hasOwnProperty, isNotNullOrUndefined, ITelemetryItem, objForEachKey } from "@microsoft/applicationinsights-core-js"; -import { ContextTagKeys, DistributedTracingModes, IConfig, IDependencyTelemetry, RequestHeaders, Util } from "@microsoft/applicationinsights-common"; +import { hasOwnProperty, isNotNullOrUndefined, ITelemetryItem, newId, objForEachKey } from "@microsoft/applicationinsights-core-js"; +import { ContextTagKeys, DistributedTracingModes, IConfig, IDependencyTelemetry, RequestHeaders } from "@microsoft/applicationinsights-common"; import { getGlobal } from "@microsoft/applicationinsights-shims"; import { TelemetryContext } from "@microsoft/applicationinsights-properties-js"; @@ -72,12 +71,12 @@ export class SnippetInitializationTests extends AITestClass { private successSpy: SinonSpy; private loggingSpy: SinonSpy; private isFetchPolyfill:boolean = false; - private sessionPrefix: string = Util.newId(); + private sessionPrefix: string = newId(); private trackSpy: SinonSpy; private envelopeConstructorSpy: SinonSpy; - constructor(emulateEs3: boolean) { - super("SnippetInitializationTests", emulateEs3); + constructor(emulateIe: boolean) { + super("SnippetInitializationTests", emulateIe); } // Add any new snippet configurations to this map @@ -110,7 +109,7 @@ export class SnippetInitializationTests extends AITestClass { test: () => { let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix))) as any; Assert.ok(theSnippet, 'ApplicationInsights SDK exists'); - Assert.ok(!(theSnippet as IAppInsightsDeprecated).downloadAndSetup, "The [" + snippetName + "] snippet should NOT have the downloadAndSetup"); // has legacy method + Assert.ok(!(theSnippet as any).downloadAndSetup, "The [" + snippetName + "] snippet should NOT have the downloadAndSetup"); // has legacy method } }); @@ -505,8 +504,8 @@ export class SnippetInitializationTests extends AITestClass { ].concat(this.asserts(1)) }); - if (!this.isEmulatingEs3) { - // If we are emulating ES3 then XHR is not hooked + if (!this.isEmulatingIe) { + // If we are emulating IE then XHR is not hooked this.testCaseAsync({ name: "TelemetryContext: auto collection of ajax requests", stepDelay: 100, @@ -523,7 +522,7 @@ export class SnippetInitializationTests extends AITestClass { } let global = getGlobal(); - if (global && global.fetch && !this.isEmulatingEs3) { + if (global && global.fetch && !this.isEmulatingIe) { this.testCaseAsync({ name: "DependenciesPlugin: auto collection of outgoing fetch requests " + (this.isFetchPolyfill ? " using polyfill " : ""), stepDelay: 5000, @@ -830,7 +829,8 @@ export class SnippetInitializationTests extends AITestClass { let theSnippet = this._initializeSnippet(snippetCreator(getSnippetConfig(this.sessionPrefix))); const context = (theSnippet.context) as TelemetryContext; const authSpy: SinonSpy = this.sandbox.spy(context.user, 'setAuthenticatedUserContext'); - const cookieSpy: SinonSpy = this.sandbox.spy(Util, 'setCookie'); + let cookieMgr = theSnippet.getCookieMgr(); + const cookieSpy: SinonSpy = this.sandbox.spy(cookieMgr, 'set'); // Act context.user.setAuthenticatedUserContext('10002', 'account567'); diff --git a/AISKU/Tests/Unit/src/SnippetLegacyInitialization.Tests.ts b/AISKU/Tests/Unit/src/SnippetLegacyInitialization.Tests.ts deleted file mode 100644 index 4c78116e..00000000 --- a/AISKU/Tests/Unit/src/SnippetLegacyInitialization.Tests.ts +++ /dev/null @@ -1,384 +0,0 @@ -import { IAppInsightsDeprecated } from "../../../src/ApplicationInsightsDeprecated"; -import { ApplicationInsightsContainer } from "../../../src/ApplicationInsightsContainer"; -import { IApplicationInsights, Snippet } from "../../../src/Initialization"; -import { Sender } from "@microsoft/applicationinsights-channel-js"; -import { createLegacySnippet } from "./testLegacySnippet"; -import { SinonSpy } from "sinon"; -import { AITestClass, Assert, PollingAssert } from "@microsoft/ai-test-framework"; -import { hasOwnProperty, isNotNullOrUndefined } from "@microsoft/applicationinsights-core-js"; - -function getBasicLegacySnippetConfig() { - return { - instrumentationKey: 'b7170927-2d1c-44f1-acec-59f4e1751c11', - disableAjaxTracking: false, - disableFetchTracking: false, - maxBatchInterval: 500 - }; -} - -const _expectedProperties = [ - "config", - "core", - "context", - "cookie", - "appInsights", - "appInsightsNew", - "version" -]; - -const _expectedTrackMethods = [ - "startTrackEvent", - "stopTrackEvent", - "startTrackPage", - "stopTrackPage", - "trackException", - "trackEvent", - "trackMetric", - "trackPageView", - "trackTrace", - "setAuthenticatedUserContext", - "clearAuthenticatedUserContext", - "flush" -]; - -const _expectedMethodsAfterInitialization = [ - "getCookieMgr" -]; - -export class SnippetLegacyInitializationTests extends AITestClass { - - // Sinon - private errorSpy: SinonSpy; - private successSpy: SinonSpy; - private loggingSpy: SinonSpy; - - constructor(emulateEs3: boolean) { - super("SnippetLegacyInitializationTests", emulateEs3); - } - - public testInitialize() { - this._disableDynProtoBaseFuncs(); // We need to disable the useBaseInst performance setting as the sinon spy fools the internal logic and the spy is bypassed - this.useFakeServer = true; - this.fakeServerAutoRespond = true; - } - - public testCleanup() { - } - - public registerTests() { - - this.testCase({ - name: "Check support for 1.0 apis", - test: () => { - let theSnippet = this._initializeSnippet(createLegacySnippet(getBasicLegacySnippetConfig())); - Assert.ok(theSnippet, 'ApplicationInsights SDK exists'); - Assert.ok(theSnippet.downloadAndSetup, "The [Legacy] snippet should have the downloadAndSetup"); // has legacy method - } - }); - - this.testCaseAsync({ - name: "Public Members exist", - stepDelay: 1, - steps: [() => { - let theSnippet = this._initializeSnippet(createLegacySnippet(getBasicLegacySnippetConfig())) as any; - _expectedTrackMethods.forEach(method => { - Assert.ok(hasOwnProperty(theSnippet, method), `${method} exists`); - Assert.ok(theSnippet[method], `${method} exists`); - Assert.equal('function', typeof theSnippet[method], `${method} is a function`); - - let funcSpyNew; - let funcSpy; - if (method === "setAuthenticatedUserContext" || method === "clearAuthenticatedUserContext") { - //funcSpy = this.sandbox.spy(theSnippet.context.user, method); - funcSpyNew = this.sandbox.spy(theSnippet.appInsightsNew.context.user, method); - } else if (method === "flush") { - funcSpyNew = this.sandbox.spy(theSnippet.appInsightsNew, method); - } else { - funcSpy = this.sandbox.spy(theSnippet.appInsights, method); - funcSpyNew = this.sandbox.spy(theSnippet.appInsightsNew, method); - } - - try { - theSnippet[method](); - } catch(e) { - // Do nothing - } - - Assert.ok(funcSpyNew.called, "Function [" + method + "] of the new implementation should have been called") - if (funcSpy) { - Assert.ok(funcSpy.called, "Function [" + method + "] of the appInsights should have been called") - } - }); - - _expectedMethodsAfterInitialization.forEach(method => { - Assert.ok(hasOwnProperty(theSnippet, method), `${method} exists`); - Assert.ok(theSnippet[method], `${method} exists`); - Assert.equal('function', typeof theSnippet[method], `${method} is a function`); - - let funcSpy = this.sandbox.spy(theSnippet.appInsights, method); - let funcSpyNew = this.sandbox.spy(theSnippet.appInsightsNew, method); - - try { - theSnippet[method](); - } catch(e) { - // Do nothing - } - - Assert.ok(funcSpyNew.called, "Function [" + method + "] of the new implementation should have been called") - if (funcSpy) { - Assert.ok(funcSpy.called, "Function [" + method + "] of the appInsights should have been called") - } - }); - - }, PollingAssert.createPollingAssert(() => { - try { - Assert.ok(true, "* waiting for scheduled actions to send events " + new Date().toISOString()); - - if(this.successSpy.called) { - let currentCount: number = 0; - this.successSpy.args.forEach(call => { - call[0].forEach(message => { - // Ignore the internal SendBrowserInfoOnUserInit message (Only occurs when running tests in a browser) - if (!message || message.indexOf("AI (Internal): 72 ") == -1) { - currentCount ++; - } - }); - }); - return currentCount > 0; - } - - return false; - } catch (e) { - Assert.ok(false, "Exception:" + e); - } - }, "waiting for sender success", 30, 1000) as any] - }); - - this.testCase({ - name: "Check properties exist", - test: () => { - let theSnippet = this._initializeSnippet(createLegacySnippet(getBasicLegacySnippetConfig())) as any; - _expectedProperties.forEach(property => { - Assert.ok(hasOwnProperty(theSnippet, property), `${property} has own property`) - Assert.notEqual(undefined, theSnippet[property], `${property} exists`); - Assert.notEqual('function', typeof theSnippet[property], `${property} is not a function`); - }); - - Assert.ok(isNotNullOrUndefined(theSnippet.core), "Make sure the core is set"); - Assert.ok(isNotNullOrUndefined(theSnippet.appInsightsNew.core), "Make sure the appInsights core is set"); - Assert.equal(theSnippet.core, theSnippet.appInsightsNew.core, "Make sure the core instances are actually the same"); - } - }); - - - this.testCase({ - name: "Check cookie manager access", - test: () => { - let theSnippet = this._initializeSnippet(createLegacySnippet(getBasicLegacySnippetConfig())) as any; - - let coreCookieMgr = theSnippet.core.getCookieMgr(); - Assert.ok(isNotNullOrUndefined(coreCookieMgr), "Make sure the cookie manager is returned"); - Assert.equal(true, coreCookieMgr.isEnabled(), "Cookies should be enabled") - Assert.equal(coreCookieMgr, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned"); - - let appInsightsCookieMgr = theSnippet.appInsightsNew.core.getCookieMgr(); - Assert.ok(isNotNullOrUndefined(appInsightsCookieMgr), "Make sure the cookie manager is returned"); - Assert.equal(true, appInsightsCookieMgr.isEnabled(), "Cookies should be enabled") - Assert.equal(appInsightsCookieMgr, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned"); - Assert.equal(coreCookieMgr, appInsightsCookieMgr, "Make sure the cookie managers are the same"); - - Assert.equal(true, theSnippet.getCookieMgr().isEnabled(), "Cookies should be enabled") - - let appInsightsCookieMgr2 = theSnippet.appInsightsNew.appInsights.core.getCookieMgr(); - Assert.ok(isNotNullOrUndefined(appInsightsCookieMgr2), "Make sure the cookie manager is returned"); - Assert.equal(true, appInsightsCookieMgr2.isEnabled(), "Cookies should be enabled") - Assert.equal(appInsightsCookieMgr2, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned"); - Assert.equal(coreCookieMgr, appInsightsCookieMgr2, "Make sure the cookie managers are the same"); - } - }); - - this.testCase({ - name: "Check cookie manager access as disabled", - test: () => { - let theConfig = getBasicLegacySnippetConfig() as any; - theConfig.disableCookiesUsage = true; - let theSnippet = this._initializeSnippet(createLegacySnippet(theConfig)) as any; - - let coreCookieMgr = theSnippet.core.getCookieMgr(); - Assert.ok(isNotNullOrUndefined(coreCookieMgr), "Make sure the cookie manager is returned"); - Assert.equal(false, coreCookieMgr.isEnabled(), "Cookies should be disabled") - Assert.equal(coreCookieMgr, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned"); - - let appInsightsCookieMgr = theSnippet.appInsightsNew.core.getCookieMgr(); - Assert.ok(isNotNullOrUndefined(appInsightsCookieMgr), "Make sure the cookie manager is returned"); - Assert.equal(false, appInsightsCookieMgr.isEnabled(), "Cookies should be disabled") - Assert.equal(appInsightsCookieMgr, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned"); - Assert.equal(coreCookieMgr, appInsightsCookieMgr, "Make sure the cookie managers are the same"); - - Assert.equal(false, theSnippet.getCookieMgr().isEnabled(), "Cookies should be disabled") - - let appInsightsCookieMgr2 = theSnippet.appInsightsNew.appInsights.core.getCookieMgr(); - Assert.ok(isNotNullOrUndefined(appInsightsCookieMgr2), "Make sure the cookie manager is returned"); - Assert.equal(false, appInsightsCookieMgr2.isEnabled(), "Cookies should be disabled") - Assert.equal(appInsightsCookieMgr2, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned"); - Assert.equal(coreCookieMgr, appInsightsCookieMgr2, "Make sure the cookie managers are the same"); - } - }); - - this.addLegacyApiTests(createLegacySnippet); - } - - public addLegacyApiTests(snippetCreator: (config:any) => Snippet): void { - this.testCaseAsync({ - name: "[Legacy] trackEvent sends to backend", - stepDelay: 1, - steps: [() => { - let theSnippet = this._initializeSnippet(snippetCreator(getBasicLegacySnippetConfig())) as IAppInsightsDeprecated; - theSnippet.trackEvent("event"); - }].concat(this.asserts(1)) - }); - - this.testCaseAsync({ - name: "[Legacy] trackTrace sends to backend", - stepDelay: 1, - steps: [() => { - let theSnippet = this._initializeSnippet(snippetCreator(getBasicLegacySnippetConfig())) as IAppInsightsDeprecated; - theSnippet.trackTrace("trace"); - }].concat(this.asserts(1)) - }); - - this.testCaseAsync({ - name: "[Legacy] trackException sends to backend", - stepDelay: 1, - steps: [() => { - let exception: Error = null; - let theSnippet = this._initializeSnippet(snippetCreator(getBasicLegacySnippetConfig())) as IAppInsightsDeprecated; - - try { - window['a']['b'](); - Assert.ok(false, 'trackException test not run'); - } catch (e) { - exception = e; - theSnippet.trackException(exception); - } - Assert.ok(exception); - }].concat(this.asserts(1)) - }); - - this.testCaseAsync({ - name: "[Legacy] track metric", - stepDelay: 1, - steps: [ - () => { - let theSnippet = this._initializeSnippet(snippetCreator(getBasicLegacySnippetConfig())) as IAppInsightsDeprecated; - - console.log("* calling trackMetric " + new Date().toISOString()); - for (let i = 0; i < 100; i++) { - theSnippet.trackMetric("test" + i,Math.round(100 * Math.random())); - } - console.log("* done calling trackMetric " + new Date().toISOString()); - } - ].concat(this.asserts(100)) - }); - - this.testCaseAsync({ - name: "[Legacy] track page view", - stepDelay: 1, - steps: [ - () => { - let theSnippet = this._initializeSnippet(snippetCreator(getBasicLegacySnippetConfig())) as IAppInsightsDeprecated; - theSnippet.trackPageView(); // sends 2 - } - ].concat(this.asserts(2)) - }); - } - - private _initializeSnippet(snippet: Snippet): IAppInsightsDeprecated { - try { - // Call the initialization - ((ApplicationInsightsContainer.getAppInsights(snippet, snippet.version)) as IAppInsightsDeprecated); - - const appInsights = (snippet as any).appInsights; - this.onDone(() => { - if (snippet["unload"]) { - snippet["unload"](false); - } else if (snippet["appInsightsNew"]) { - snippet["appInsightsNew"].unload(false); - } - }); - - Assert.ok(appInsights, "The App insights instance should be populated"); - Assert.ok(appInsights.core, "The Core exists"); - Assert.equal(appInsights.core, (snippet as any).core, "The core instances should match"); - - Assert.equal(true, appInsights.isInitialized(), 'App Analytics is initialized'); - Assert.equal(true, appInsights.core.isInitialized(), 'Core is initialized'); - - const appInsightsNew = (snippet as any).appInsightsNew; - Assert.ok(appInsightsNew, "The App insights new instance should be populated"); - Assert.ok(appInsightsNew.core, "The Core exists"); - Assert.equal(appInsightsNew.core, (snippet as any).core, "The core instances should match"); - Assert.equal(true, appInsightsNew.appInsights.isInitialized(), 'App Analytics is initialized'); - Assert.equal(true, appInsightsNew.core.isInitialized(), 'Core is initialized'); - - // Setup Sinon stuff - const sender: Sender = appInsightsNew.core.getTransmissionControls()[0][0] as Sender; - this.errorSpy = this.sandbox.spy(sender, '_onError'); - this.successSpy = this.sandbox.spy(sender, '_onSuccess'); - this.loggingSpy = this.sandbox.stub(appInsights.core.logger, 'throwInternal'); - } catch (e) { - console.error('Failed to initialize'); - Assert.ok(false, e); - } - - // Note: Explicitly returning the original snippet as this should have been updated! - return snippet as IAppInsightsDeprecated; - } - - private boilerPlateAsserts = () => { - Assert.ok(this.successSpy.called, "success"); - Assert.ok(!this.errorSpy.called, "no error sending"); - const isValidCallCount = this.loggingSpy.callCount === 0; - Assert.ok(isValidCallCount, "logging spy was called 0 time(s)"); - if (!isValidCallCount) { - while (this.loggingSpy.args.length) { - Assert.ok(false, "[warning thrown]: " + this.loggingSpy.args.pop()); - } - } - } - private asserts: any = (expectedCount: number) => [() => { - const message = "polling: " + new Date().toISOString(); - Assert.ok(true, message); - console.log(message); - - if (this.successSpy.called) { - this.boilerPlateAsserts(); - this.testCleanup(); - } else if (this.errorSpy.called || this.loggingSpy.called) { - this.boilerPlateAsserts(); - } - }, - (PollingAssert.createPollingAssert(() => { - try { - Assert.ok(true, "* checking success spy " + new Date().toISOString()); - - if(this.successSpy.called) { - let currentCount: number = 0; - this.successSpy.args.forEach(call => { - call[0].forEach(message => { - // Ignore the internal SendBrowserInfoOnUserInit message (Only occurs when running tests in a browser) - if (!message || message.indexOf("AI (Internal): 72 ") == -1) { - currentCount ++; - } - }); - }); - console.log('curr: ' + currentCount + ' exp: ' + expectedCount); - return currentCount === expectedCount; - } - - return false; - } catch (e) { - Assert.ok(false, "Exception:" + e); - } - }, "sender succeeded", 30, 1000))]; -} \ No newline at end of file diff --git a/AISKU/Tests/Unit/src/aiskuunittests.ts b/AISKU/Tests/Unit/src/aiskuunittests.ts index cdac56f3..466241b2 100644 --- a/AISKU/Tests/Unit/src/aiskuunittests.ts +++ b/AISKU/Tests/Unit/src/aiskuunittests.ts @@ -5,21 +5,16 @@ import { CdnPackagingChecks } from './CdnPackaging.tests'; import { SanitizerE2ETests } from './sanitizer.e2e.tests'; import { ValidateE2ETests } from './validate.e2e.tests'; import { SenderE2ETests } from './sender.e2e.tests'; -import { ApplicationInsightsDeprecatedTests } from './ApplicationInsightsDeprecatedTests'; -import { SnippetLegacyInitializationTests } from './SnippetLegacyInitialization.Tests'; import { SnippetInitializationTests } from './SnippetInitialization.Tests'; export function runTests() { new AISKUSizeCheck().registerTests(); new ApplicationInsightsTests().registerTests(); new ApplicationInsightsFetchTests().registerTests(); - new ApplicationInsightsDeprecatedTests().registerTests(); new CdnPackagingChecks().registerTests(); new SanitizerE2ETests().registerTests(); new ValidateE2ETests().registerTests(); new SenderE2ETests().registerTests(); - new SnippetLegacyInitializationTests(false).registerTests(); new SnippetInitializationTests(false).registerTests(); - new SnippetLegacyInitializationTests(true).registerTests(); new SnippetInitializationTests(true).registerTests(); } \ No newline at end of file diff --git a/AISKU/Tests/Unit/src/applicationinsights.e2e.tests.ts b/AISKU/Tests/Unit/src/applicationinsights.e2e.tests.ts index 93977b59..adf3f7d8 100644 --- a/AISKU/Tests/Unit/src/applicationinsights.e2e.tests.ts +++ b/AISKU/Tests/Unit/src/applicationinsights.e2e.tests.ts @@ -2,8 +2,8 @@ import { AITestClass, Assert, PollingAssert, EventValidator, TraceValidator, Exc import { SinonSpy } from 'sinon'; import { ApplicationInsights, IApplicationInsights } from '../../../src/applicationinsights-web' import { Sender } from '@microsoft/applicationinsights-channel-js'; -import { IDependencyTelemetry, ContextTagKeys, Util, Event, Trace, Exception, Metric, PageView, PageViewPerformance, RemoteDependencyData, DistributedTracingModes, RequestHeaders, IAutoExceptionTelemetry } from '@microsoft/applicationinsights-common'; -import { AppInsightsCore, ITelemetryItem, getGlobal } from "@microsoft/applicationinsights-core-js"; +import { IDependencyTelemetry, ContextTagKeys, Event, Trace, Exception, Metric, PageView, PageViewPerformance, RemoteDependencyData, DistributedTracingModes, RequestHeaders, IAutoExceptionTelemetry } from '@microsoft/applicationinsights-common'; +import { AppInsightsCore, ITelemetryItem, getGlobal, newId } from "@microsoft/applicationinsights-core-js"; import { TelemetryContext } from '@microsoft/applicationinsights-properties-js'; @@ -35,7 +35,7 @@ export class ApplicationInsightsTests extends AITestClass { private successSpy: SinonSpy; private loggingSpy: SinonSpy; private userSpy: SinonSpy; - private _sessionPrefix: string = Util.newId(); + private _sessionPrefix: string = newId(); private trackSpy: SinonSpy; private envelopeConstructorSpy: SinonSpy; @@ -922,7 +922,8 @@ export class ApplicationInsightsTests extends AITestClass { // Setup const context = (this._ai.context) as TelemetryContext; const authSpy: SinonSpy = this.sandbox.spy(context.user, 'setAuthenticatedUserContext'); - const cookieSpy: SinonSpy = this.sandbox.spy(Util, 'setCookie'); + let cookieMgr = this._ai.getCookieMgr(); + const cookieSpy: SinonSpy = this.sandbox.spy(cookieMgr, 'set'); // Act context.user.setAuthenticatedUserContext('10002', 'account567'); diff --git a/AISKU/Tests/Unit/src/sanitizer.e2e.tests.ts b/AISKU/Tests/Unit/src/sanitizer.e2e.tests.ts index 54fd1e5e..79ae91fa 100644 --- a/AISKU/Tests/Unit/src/sanitizer.e2e.tests.ts +++ b/AISKU/Tests/Unit/src/sanitizer.e2e.tests.ts @@ -1,7 +1,8 @@ -import { ApplicationInsights, IApplicationInsights, Util, LoggingSeverity, _InternalMessageId } from '../../../src/applicationinsights-web' +import { ApplicationInsights, IApplicationInsights, LoggingSeverity, _InternalMessageId } from '../../../src/applicationinsights-web' import { Sender } from '@microsoft/applicationinsights-channel-js'; import { AITestClass, Assert, PollingAssert } from '@microsoft/ai-test-framework'; import { SinonSpy } from 'sinon'; +import { newId } from '@microsoft/applicationinsights-core-js'; export class SanitizerE2ETests extends AITestClass { private readonly _instrumentationKey = 'b7170927-2d1c-44f1-acec-59f4e1751c11'; @@ -69,7 +70,7 @@ export class SanitizerE2ETests extends AITestClass { steps: [ () => { this._ai.trackDependencyData({ - id: Util.newId(), + id: newId(), name: new Array(1234).join("a"), // exceeds max of 1024 responseCode: 200 }); diff --git a/AISKU/Tests/Unit/src/sender.e2e.tests.ts b/AISKU/Tests/Unit/src/sender.e2e.tests.ts index fb536ef1..7e550da4 100644 --- a/AISKU/Tests/Unit/src/sender.e2e.tests.ts +++ b/AISKU/Tests/Unit/src/sender.e2e.tests.ts @@ -1,7 +1,7 @@ import { ApplicationInsights, IApplicationInsights } from '../../../src/applicationinsights-web' import { Sender } from '@microsoft/applicationinsights-channel-js'; -import { Util } from '@microsoft/applicationinsights-common'; -import { getJSON } from '@microsoft/applicationinsights-core-js'; +import { utlGetSessionStorage } from '@microsoft/applicationinsights-common'; +import { getJSON, isArray } from '@microsoft/applicationinsights-core-js'; import { SinonSpy } from 'sinon'; import { Assert, AITestClass, PollingAssert} from "@microsoft/ai-test-framework" @@ -192,10 +192,10 @@ export class SenderE2ETests extends AITestClass { private _getBuffer(key: string): string[] { let prefixedKey = key; try { - const bufferJson = Util.getSessionStorage(null, key); + const bufferJson = utlGetSessionStorage(null, key); if (bufferJson) { let buffer: string[] = getJSON().parse(bufferJson); - if (buffer && Util.isArray(buffer)) { + if (buffer && isArray(buffer)) { return buffer; } } diff --git a/AISKU/package.json b/AISKU/package.json index 7a10c4a4..1d760d80 100644 --- a/AISKU/package.json +++ b/AISKU/package.json @@ -40,7 +40,7 @@ "devDependencies": { "@microsoft/ai-test-framework": "0.0.1", "@microsoft/applicationinsights-rollup-plugin-uglify3-js": "1.0.0", - "@microsoft/applicationinsights-rollup-es3": "1.1.3", + "@microsoft/applicationinsights-rollup-es5": "1.0.0", "sinon": "^7.3.1", "@microsoft/api-extractor": "^7.18.1", "finalhandler": "^1.1.1", @@ -74,7 +74,8 @@ "@microsoft/applicationinsights-common": "2.8.6", "@microsoft/applicationinsights-core-js": "2.8.6", "@microsoft/applicationinsights-dependencies-js": "2.8.6", - "@microsoft/applicationinsights-properties-js": "2.8.6" + "@microsoft/applicationinsights-properties-js": "2.8.6", + "@nevware21/ts-utils": "^0.4.1" }, "license": "MIT" } diff --git a/AISKU/rollup.config.js b/AISKU/rollup.config.js index d039cc16..a4a1d735 100644 --- a/AISKU/rollup.config.js +++ b/AISKU/rollup.config.js @@ -3,7 +3,7 @@ import { uglify } from "@microsoft/applicationinsights-rollup-plugin-uglify3-js" import replace from "@rollup/plugin-replace"; import cleanup from "rollup-plugin-cleanup"; import dynamicRemove from "@microsoft/dynamicproto-js/tools/rollup/node/removedynamic"; -import { es3Poly, es3Check, importCheck } from "@microsoft/applicationinsights-rollup-es3"; +import { es5Poly, es5Check, importCheck } from "@microsoft/applicationinsights-rollup-es5"; import { updateDistEsmFiles } from "../tools/updateDistEsm/updateDistEsm"; const packageJson = require("./package.json"); @@ -64,8 +64,8 @@ const browserRollupConfigFactory = (isProduction, libVersion = '2', format = 'um preferBuiltins: false }), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; @@ -121,8 +121,8 @@ const nodeUmdRollupConfigFactory = (isProduction) => { importCheck({ exclude: [ "applicationinsights-web" ] }), nodeResolve(), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; diff --git a/AISKU/src/ApplicationInsightsContainer.ts b/AISKU/src/ApplicationInsightsContainer.ts index e9195d84..74dbbb5f 100644 --- a/AISKU/src/ApplicationInsightsContainer.ts +++ b/AISKU/src/ApplicationInsightsContainer.ts @@ -1,31 +1,22 @@ -import { _legacyCookieMgr } from "@microsoft/applicationinsights-core-js"; -import { AppInsightsDeprecated, IAppInsightsDeprecated } from "./ApplicationInsightsDeprecated"; +import { throwUnsupported } from "@nevware21/ts-utils"; import { IApplicationInsights, Initialization as ApplicationInsights, Snippet } from "./Initialization"; export class ApplicationInsightsContainer { - public static getAppInsights(snippet: Snippet, version: number) : IApplicationInsights | IAppInsightsDeprecated { + public static getAppInsights(snippet: Snippet, version: number) : IApplicationInsights { const initialization = new ApplicationInsights(snippet); - const legacyMode = version >= 2 ? false: true; - // Side effect is to create, initialize and listen to the CoreUtils._canUseCookies changes - // Called here to support backward compatibility - _legacyCookieMgr(); - // Two target scenarios: - // 1. Customer runs v1 snippet + runtime. If customer updates just cdn location to new SDK, it will run in compat mode so old apis work + // Removed: 1. Customer runs v1 snippet + runtime. If customer updates just cdn location to new SDK, it will run in compat mode so old apis work // 2. Customer updates to new snippet (that uses cdn location to new SDK. This is same as a new customer onboarding // and all api signatures are expected to map to new SDK. Note new snippet specifies version - if (!legacyMode) { + if (version >= 2.0) { initialization.updateSnippetDefinitions(snippet); - initialization.loadAppInsights(legacyMode); + initialization.loadAppInsights(false); return initialization; // default behavior with new snippet } else { - const legacy = new AppInsightsDeprecated(snippet, initialization); // target scenario old snippet + updated endpoint - legacy.updateSnippetDefinitions(snippet); - initialization.loadAppInsights(legacyMode); - return legacy; + throwUnsupported("V1 API compatibility is no longer supported"); } } } diff --git a/AISKU/src/ApplicationInsightsDeprecated.ts b/AISKU/src/ApplicationInsightsDeprecated.ts deleted file mode 100644 index 85ce019f..00000000 --- a/AISKU/src/ApplicationInsightsDeprecated.ts +++ /dev/null @@ -1,463 +0,0 @@ -import dynamicProto from "@microsoft/dynamicproto-js"; -import { - DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, IAutoExceptionTelemetry, IConfig, IDependencyTelemetry, IEnvelope, IEventTelemetry, - IExceptionTelemetry, IMetricTelemetry, IPageViewTelemetry, ITraceTelemetry, ProcessLegacy, SeverityLevel, stringToBoolOrDefault -} from "@microsoft/applicationinsights-common"; -import { - IConfiguration, ICookieMgr, IDiagnosticLogger, ITelemetryItem, arrIndexOf, isFunction, proxyAssign, proxyFunctions, throwError -} from "@microsoft/applicationinsights-core-js"; -import { DfltAjaxCorrelationHeaderExDomains } from "@microsoft/applicationinsights-dependencies-js"; -import { Initialization as ApplicationInsights, Snippet } from "./Initialization"; -import { - STR_FLUSH, STR_GET_COOKIE_MGR, STR_SNIPPET, STR_START_TRACK_EVENT, STR_START_TRACK_PAGE, STR_STOP_TRACK_EVENT, STR_STOP_TRACK_PAGE -} from "./InternalConstants"; - -// This is an exclude list of properties that should not be updated during initialization -// They include a combination of private and internal property names -const _ignoreUpdateSnippetProperties = [ - STR_SNIPPET, "getDefaultConfig", "_hasLegacyInitializers", "_queue", "_processLegacyInitializers" -]; - -function getDefaultConfig(config?: any): any { - if (!config) { - config = ({} as any); - } - - // set default values - config.endpointUrl = config.endpointUrl || DEFAULT_BREEZE_ENDPOINT + DEFAULT_BREEZE_PATH; - config.sessionRenewalMs = 30 * 60 * 1000; - config.sessionExpirationMs = 24 * 60 * 60 * 1000; - config.maxBatchSizeInBytes = config.maxBatchSizeInBytes > 0 ? config.maxBatchSizeInBytes : 102400; // 100kb - config.maxBatchInterval = !isNaN(config.maxBatchInterval) ? config.maxBatchInterval : 15000; - config.enableDebug = stringToBoolOrDefault(config.enableDebug); - config.disableExceptionTracking = stringToBoolOrDefault(config.disableExceptionTracking); - config.disableTelemetry = stringToBoolOrDefault(config.disableTelemetry); - config.verboseLogging = stringToBoolOrDefault(config.verboseLogging); - config.emitLineDelimitedJson = stringToBoolOrDefault(config.emitLineDelimitedJson); - config.diagnosticLogInterval = config.diagnosticLogInterval || 10000; - config.autoTrackPageVisitTime = stringToBoolOrDefault(config.autoTrackPageVisitTime); - - if (isNaN(config.samplingPercentage) || config.samplingPercentage <= 0 || config.samplingPercentage >= 100) { - config.samplingPercentage = 100; - } - - config.disableAjaxTracking = stringToBoolOrDefault(config.disableAjaxTracking); - config.maxAjaxCallsPerView = !isNaN(config.maxAjaxCallsPerView) ? config.maxAjaxCallsPerView : 500; - - config.isBeaconApiDisabled = stringToBoolOrDefault(config.isBeaconApiDisabled, true); - config.disableCorrelationHeaders = stringToBoolOrDefault(config.disableCorrelationHeaders); - config.correlationHeaderExcludedDomains = config.correlationHeaderExcludedDomains || DfltAjaxCorrelationHeaderExDomains; - config.disableFlushOnBeforeUnload = stringToBoolOrDefault(config.disableFlushOnBeforeUnload); - config.disableFlushOnUnload = stringToBoolOrDefault(config.disableFlushOnUnload, config.disableFlushOnBeforeUnload); - config.enableSessionStorageBuffer = stringToBoolOrDefault(config.enableSessionStorageBuffer, true); - config.isRetryDisabled = stringToBoolOrDefault(config.isRetryDisabled); - config.isCookieUseDisabled = stringToBoolOrDefault(config.isCookieUseDisabled); - config.isStorageUseDisabled = stringToBoolOrDefault(config.isStorageUseDisabled); - config.isBrowserLinkTrackingEnabled = stringToBoolOrDefault(config.isBrowserLinkTrackingEnabled); - config.enableCorsCorrelation = stringToBoolOrDefault(config.enableCorsCorrelation); - - return config; -} - -export class AppInsightsDeprecated implements IAppInsightsDeprecated { - - public config: IConfig & IConfiguration; - public snippet: Snippet; - public context: ITelemetryContext; - public logger: IDiagnosticLogger; - public queue: Array<() => void>; - public appInsightsNew: ApplicationInsights; - - constructor(snippet: Snippet, appInsightsNew: ApplicationInsights) { - let _hasLegacyInitializers = false; - let _queue: Array<((env: IEnvelope) => boolean | void)> = []; - let _config: IConfiguration; - - dynamicProto(AppInsightsDeprecated, this, (_self) => { - _config = getDefaultConfig(snippet.config); - _self.config = _config; - _self.snippet = snippet; - _self.appInsightsNew = appInsightsNew; - _self.context = { addTelemetryInitializer: _addTelemetryInitializers.bind(_self) }; - - _self.addTelemetryInitializers = _addTelemetryInitializers; - - function _addTelemetryInitializers(callBack: (env: IEnvelope) => boolean | void) { - - // Add initializer to current processing only if there is any old telemetry initializer - if (!_hasLegacyInitializers) { - - appInsightsNew.addTelemetryInitializer(item => { - _processLegacyInitializers(item); // setup call back for each legacy processor - }) - - _hasLegacyInitializers = true; - } - - _queue.push(callBack); - } - - proxyFunctions(_self, appInsightsNew, [ - STR_GET_COOKIE_MGR, - STR_START_TRACK_PAGE, - STR_STOP_TRACK_PAGE, - STR_FLUSH, - STR_START_TRACK_EVENT, - STR_STOP_TRACK_EVENT - ]); - - _self.trackPageView = (name?: string, url?: string, properties?: {[key: string]: string }, measurements?: {[key: string]: number }, duration?: number) => { - const telemetry: IPageViewTelemetry = { - name, - uri: url, - properties, - measurements - }; - - // fix for props, measurements, duration - appInsightsNew.trackPageView(telemetry); - }; - - _self.trackEvent = (name: string, properties?: Object, measurements?: Object) => { - appInsightsNew.trackEvent({ name} as IEventTelemetry); - }; - - _self.trackDependency = (id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number) => { - appInsightsNew.trackDependencyData( - { - id, - target: absoluteUrl, - type: pathName, - duration: totalTime, - properties: { HttpMethod: method }, - success, - responseCode: resultCode - } as IDependencyTelemetry); - }; - - _self.trackException = (exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: any) => { - appInsightsNew.trackException({ - exception - } as IExceptionTelemetry); - }; - - _self.trackMetric = (name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) => { - appInsightsNew.trackMetric({name, average, sampleCount, min, max} as IMetricTelemetry); - }; - - _self.trackTrace = (message: string, properties?: { [name: string]: string; }, severityLevel?: any) => { - appInsightsNew.trackTrace({ message, severityLevel } as ITraceTelemetry); - }; - - _self.setAuthenticatedUserContext = (authenticatedUserId: string, accountId?: string, storeInCookie?: boolean) => { - appInsightsNew.context.user.setAuthenticatedUserContext(authenticatedUserId, accountId, storeInCookie); - }; - - _self.clearAuthenticatedUserContext = () => { - appInsightsNew.context.user.clearAuthenticatedUserContext(); - }; - - _self._onerror = (message: string, url: string, lineNumber: number, columnNumber: number, error: Error) => { - appInsightsNew._onerror({ message, url, lineNumber, columnNumber, error } as IAutoExceptionTelemetry); - }; - - _self.downloadAndSetup = (config: IConfig): void => { - throwError("downloadAndSetup not implemented in web SKU"); - }; - - _self.updateSnippetDefinitions = (snippet: Snippet) => { - // apply full appInsights to the global instance - // Note: This must be called before loadAppInsights is called - proxyAssign(snippet, this, (name: string) => { - // Not excluding names prefixed with "_" as we need to proxy some functions like _onError - return name && arrIndexOf(_ignoreUpdateSnippetProperties, name) === -1; - }); - }; - - // note: these are split into methods to enable unit tests - _self.loadAppInsights = () => { - - // initialize global instance of appInsights - // var appInsights = new Microsoft.ApplicationInsights.AppInsights(_self.config); - - // implement legacy version of trackPageView for 0.10< - if (_self.config["iKey"]) { - const originalTrackPageView = _self.trackPageView; - _self.trackPageView = (pagePath?: string, properties?: Object, measurements?: Object) => { - originalTrackPageView.apply(_self, [null, pagePath, properties, measurements]); - } - } - - // implement legacy pageView interface if it is present in the snippet - const legacyPageView = "logPageView"; - if (isFunction(_self.snippet[legacyPageView])) { - this[legacyPageView] = (pagePath?: string, properties?: {[key: string]: string }, measurements?: {[key: string]: number }) => { - _self.trackPageView(null, pagePath, properties, measurements); - } - } - - // implement legacy event interface if it is present in the snippet - const legacyEvent = "logEvent"; - if (isFunction(_self.snippet[legacyEvent])) { - this[legacyEvent] = (name: string, props?: Object, measurements?: Object) => { - _self.trackEvent(name, props, measurements); - } - } - - return this; - }; - - function _processLegacyInitializers(item: ITelemetryItem): ITelemetryItem { - // instead of mapping new to legacy and then back again and repeating in channel, attach callback for channel to call - item.tags[ProcessLegacy] = _queue; - return item; - } - - }); - } - - /** - * The array of telemetry initializers to call before sending each telemetry item. - */ - - public addTelemetryInitializers(callBack: (env: IEnvelope) => boolean | void) { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - /** - * Get the current cookie manager for this instance - */ - public getCookieMgr(): ICookieMgr { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - return null; - } - - startTrackPage(name?: string) { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - stopTrackPage(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - trackPageView(name?: string, url?: string, properties?: {[key: string]: string }, measurements?: {[key: string]: number }, duration?: number) { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - trackEvent(name: string, properties?: Object, measurements?: Object) { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number) { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: any) { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - trackTrace(message: string, properties?: { [name: string]: string; }, severityLevel?: any) { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - flush(async?: boolean) { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie?: boolean) { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - clearAuthenticatedUserContext() { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error) { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - startTrackEvent(name: string) { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - downloadAndSetup?(config: IConfig): void { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - public updateSnippetDefinitions(snippet: Snippet) { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } - - // note: these are split into methods to enable unit tests - public loadAppInsights() { - // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging - } -} - -export interface IAppInsightsDeprecated { - - /* - * Config object used to initialize AppInsights - */ - config: IConfig; - - context: ITelemetryContext; - - /* - * Initialization queue. Contains functions to run when appInsights initializes - */ - queue: Array<() => void>; - - /** - * Get the current cookie manager for this instance - */ - getCookieMgr(): ICookieMgr; - - /** - * Starts timing how long the user views a page or other item. Call this when the page opens. - * This method doesn't send any telemetry. Call `stopTrackPage` to log the page when it closes. - * @param name A string that identifies this item, unique within this HTML document. Defaults to the document title. - */ - startTrackPage(name?: string): void; - - /** - * Logs how long a page or other item was visible, after `startTrackPage`. Call this when the page closes. - * @param name The string you used as the name in startTrackPage. Defaults to the document title. - * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. - * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. - * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. - * @deprecated API is deprecated; supported only if input configuration specifies deprecated=true - */ - stopTrackPage(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }): void; - - /** - * Logs that a page or other item was viewed. - * @param name The string you used as the name in `startTrackPage`. Defaults to the document title. - * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. - * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. - * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. - * @param duration number - the number of milliseconds it took to load the page. Defaults to undefined. If set to default value, page load time is calculated internally. - */ - trackPageView(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, duration?: number): void; - - /** - * Start timing an extended event. Call `stopTrackEvent` to log the event when it ends. - * @param name A string that identifies this event uniquely within the document. - */ - startTrackEvent(name: string): void; - - - /** - * Log an extended event that you started timing with `startTrackEvent`. - * @param name The string you used to identify this event in `startTrackEvent`. - * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. - * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. - */ - stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }): void; - - /** - * Log a user action or other occurrence. - * @param name A string to identify this event in the portal. - * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. - * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. - */ - trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }): void; - - /** - * Log a dependency call - * @param id unique id, this is used by the backend to correlate server requests. Use newId() to generate a unique Id. - * @param method represents request verb (GET, POST, etc.) - * @param absoluteUrl absolute url used to make the dependency request - * @param pathName the path part of the absolute url - * @param totalTime total request time - * @param success indicates if the request was successful - * @param resultCode response code returned by the dependency request - */ - trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number): void; - - /** - * Log an exception you have caught. - * @param exception An Error from a catch clause, or the string error message. - * @param handledAt Not used - * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. - * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. - * @param severityLevel SeverityLevel - severity level - */ - trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: SeverityLevel): void; - - /** - * Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators. - * To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the - * telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals. - * @param name A string that identifies the metric. - * @param average Number representing either a single measurement, or the average of several measurements. - * @param sampleCount The number of measurements represented by the average. Defaults to 1. - * @param min The smallest measurement in the sample. Defaults to the average. - * @param max The largest measurement in the sample. Defaults to the average. - */ - trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }): void; - - /** - * Log a diagnostic message. - * @param message A message string - * @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty. - * @param severityLevel SeverityLevel - severity level - */ - trackTrace(message: string, properties?: { [name: string]: string; }, severityLevel?: SeverityLevel): void; - - - /** - * Immediately send all queued telemetry. - * @param {boolean} async - If flush should be call asynchronously - */ - flush(async?: boolean): void; - - - /** - * Sets the autheticated user id and the account id in this session. - * User auth id and account id should be of type string. They should not contain commas, semi-colons, equal signs, spaces, or vertical-bars. - * - * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service. - * @param accountId {string} - An optional string to represent the account associated with the authenticated user. - */ - setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie?: boolean): void; - - - /** - * Clears the authenticated user id and the account id from the user context. - */ - clearAuthenticatedUserContext(): void; - - /* - * Downloads and initializes AppInsights. You can override default script download location by specifying url property of `config`. - */ - downloadAndSetup?(config: IConfig): void; - - /** - * The custom error handler for Application Insights - * @param {string} message - The error message - * @param {string} url - The url where the error was raised - * @param {number} lineNumber - The line number where the error was raised - * @param {number} columnNumber - The column number for the line where the error was raised - * @param {Error} error - The Error object - */ - _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error): void; -} - -export interface ITelemetryContext { - - /** - * Adds a telemetry initializer to the collection. Telemetry initializers will be called one by one, - * in the order they were added, before the telemetry item is pushed for sending. - * If one of the telemetry initializers returns false or throws an error then the telemetry item will not be sent. - */ - addTelemetryInitializer(telemetryInitializer: (envelope: IEnvelope) => boolean | void): void; -} diff --git a/AISKU/src/Init.ts b/AISKU/src/Init.ts index fa5521ce..12418284 100644 --- a/AISKU/src/Init.ts +++ b/AISKU/src/Init.ts @@ -9,15 +9,13 @@ import { Snippet } from "./Initialization"; // Exports available from the Cdn bundles // ---------------------------------------------------------------------------------------------------- export { - Initialization as ApplicationInsights, Snippet, - Telemetry + Initialization as ApplicationInsights, Snippet } from "./Initialization"; export { LoggingSeverity, PerfEvent, PerfManager, doPerf, - CoreUtils, newId, newGuid, random32, @@ -34,7 +32,6 @@ export { } from "@microsoft/applicationinsights-core-js"; export { - Util, RequestHeaders, DisabledPropertyName, DEFAULT_BREEZE_ENDPOINT, diff --git a/AISKU/src/Initialization.ts b/AISKU/src/Initialization.ts index 72193e9b..e77f2bf2 100644 --- a/AISKU/src/Initialization.ts +++ b/AISKU/src/Initialization.ts @@ -6,13 +6,9 @@ import dynamicProto from "@microsoft/dynamicproto-js"; import { AnalyticsPlugin, ApplicationInsights } from "@microsoft/applicationinsights-analytics-js"; import { Sender } from "@microsoft/applicationinsights-channel-js"; import { - AnalyticsPluginIdentifier, BreezeChannelIdentifier, ConfigurationManager, ConnectionStringParser, ContextTagKeys, CorrelationIdHelper, - CtxTagKeys, DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, Data, DataSanitizer, DateTimeUtils, DisabledPropertyName, - DistributedTracingModes, Envelope, Event, Exception, Extensions, FieldType, HttpMethod, IAppInsights, IAutoExceptionTelemetry, IConfig, - ICorrelationIdHelper, IDataSanitizer, IDateTimeUtils, IDependencyTelemetry, IEventTelemetry, IExceptionTelemetry, IMetricTelemetry, - IPageViewPerformanceTelemetry, IPageViewTelemetry, IPropertiesPlugin, IRequestHeaders, ITelemetryContext as Common_ITelemetryContext, - ITraceTelemetry, IUrlHelper, IUtil, Metric, PageView, PageViewPerformance, ProcessLegacy, PropertiesPluginIdentifier, - RemoteDependencyData, RequestHeaders, SampleRate, SeverityLevel, TelemetryItemCreator, Trace, UrlHelper, Util, parseConnectionString + DEFAULT_BREEZE_PATH, IAppInsights, IAutoExceptionTelemetry, IConfig, IDependencyTelemetry, IEventTelemetry, IExceptionTelemetry, + IMetricTelemetry, IPageViewPerformanceTelemetry, IPageViewTelemetry, IPropertiesPlugin, IRequestHeaders, + ITelemetryContext as Common_ITelemetryContext, ITraceTelemetry, PropertiesPluginIdentifier, parseConnectionString } from "@microsoft/applicationinsights-common"; import { AppInsightsCore, IAppInsightsCore, IChannelControls, IConfiguration, ICookieMgr, ICustomProperties, IDiagnosticLogger, @@ -20,13 +16,14 @@ import { ITelemetryUnloadState, UnloadHandler, _eInternalMessageId, _throwInternal, addPageHideEventListener, addPageUnloadEventListener, arrForEach, arrIndexOf, createUniqueNamespace, doPerf, eLoggingSeverity, hasDocument, hasWindow, isArray, isFunction, isNullOrUndefined, isReactNative, isString, mergeEvtNamespace, objForEachKey, proxyAssign, proxyFunctions, removePageHideEventListener, - removePageUnloadEventListener, throwError + removePageUnloadEventListener } from "@microsoft/applicationinsights-core-js"; import { AjaxPlugin as DependenciesPlugin, IDependenciesPlugin } from "@microsoft/applicationinsights-dependencies-js"; import { DependencyListenerFunction, IDependencyListenerHandler } from "@microsoft/applicationinsights-dependencies-js/types/DependencyListener"; import { PropertiesPlugin } from "@microsoft/applicationinsights-properties-js"; +import { arrAppend, strIndexOf, throwUnsupported } from "@nevware21/ts-utils"; import { STR_ADD_TELEMETRY_INITIALIZER, STR_CLEAR_AUTHENTICATED_USER_CONTEXT, STR_EVT_NAMESPACE, STR_GET_COOKIE_MGR, STR_GET_PLUGIN, STR_POLL_INTERNAL_LOGS, STR_SET_AUTHENTICATED_USER_CONTEXT, STR_SNIPPET, STR_START_TRACK_EVENT, STR_START_TRACK_PAGE, @@ -34,7 +31,7 @@ import { STR_TRACK_PAGE_VIEW, STR_TRACK_TRACE } from "./InternalConstants"; -export { IUtil, ICorrelationIdHelper, IUrlHelper, IDateTimeUtils, IRequestHeaders }; +export { IRequestHeaders }; let _internalSdkSrc: string; @@ -57,7 +54,7 @@ export interface Snippet { } export interface IApplicationInsights extends IAppInsights, IDependenciesPlugin, IPropertiesPlugin { - appInsights: ApplicationInsights; + appInsights: AnalyticsPlugin; flush: (async?: boolean) => void; onunloadFlush: (async?: boolean) => void; getSender: () => Sender; @@ -100,57 +97,6 @@ export interface IApplicationInsights extends IAppInsights, IDependenciesPlugin, addUnloadCb(handler: UnloadHandler): void; } -// Re-exposing the Common classes as Telemetry, the list was taken by reviewing the generated code for the build while using -// the previous configuration :- -// import * as Common from "@microsoft/applicationinsights-common" -// export const Telemetry = Common; - -let fieldType = { - Default: FieldType.Default, - Required: FieldType.Required, - Array: FieldType.Array, - Hidden: FieldType.Hidden -}; - -/** - * Telemetry type classes, e.g. PageView, Exception, etc - */ -export const Telemetry = { - __proto__: null as any, - PropertiesPluginIdentifier, - BreezeChannelIdentifier, - AnalyticsPluginIdentifier, - Util, - CorrelationIdHelper, - UrlHelper, - DateTimeUtils, - ConnectionStringParser, - FieldType: fieldType, - RequestHeaders, - DisabledPropertyName, - ProcessLegacy, - SampleRate, - HttpMethod, - DEFAULT_BREEZE_ENDPOINT, - Envelope, - Event, - Exception, - Metric, - PageView, - RemoteDependencyData, - Trace, - PageViewPerformance, - Data, - SeverityLevel, - ConfigurationManager, - ContextTagKeys, - DataSanitizer: DataSanitizer as IDataSanitizer, - TelemetryItemCreator, - CtxTagKeys, - Extensions, - DistributedTracingModes -}; - /** * Application Insights API * @class Initialization @@ -207,7 +153,7 @@ export class Initialization implements IApplicationInsights { _self.snippet = snippet; _self.config = config; - _getSKUDefaults(); + _getSKUDefaults(config); _self.flush = (async: boolean = true) => { doPerf(_core, () => "AISKU.flush", () => { @@ -232,15 +178,16 @@ export class Initialization implements IApplicationInsights { }; _self.loadAppInsights = (legacyMode: boolean = false, logger?: IDiagnosticLogger, notificationManager?: INotificationManager): IApplicationInsights => { + if (legacyMode) { + throwUnsupported("Legacy Mode is no longer supported") + } + function _updateSnippetProperties(snippet: Snippet) { if (snippet) { let snippetVer = ""; if (!isNullOrUndefined(_snippetVersion)) { snippetVer += _snippetVersion; } - if (legacyMode) { - snippetVer += ".lg"; - } if (_self.context && _self.context.internal) { _self.context.internal.snippetVer = snippetVer || "-"; @@ -257,19 +204,9 @@ export class Initialization implements IApplicationInsights { }); } } - - // dont allow additional channels/other extensions for legacy mode; legacy mode is only to allow users to switch with no code changes! - if (legacyMode && _self.config.extensions && _self.config.extensions.length > 0) { - throwError("Extensions not allowed in legacy mode"); - } - + doPerf(_self.core, () => "AISKU.loadAppInsights", () => { - const extensions: any[] = []; - - extensions.push(_sender); - extensions.push(properties); - extensions.push(dependencies); - extensions.push(_self.appInsights); + const extensions = arrAppend([], [ _sender, properties, dependencies, _self.appInsights]); // initialize core _core.initialize(_self.config, extensions, logger, notificationManager); @@ -355,12 +292,15 @@ export class Initialization implements IApplicationInsights { }; let added = false; - let excludePageUnloadEvents = appInsightsInstance.appInsights.config.disablePageUnloadEvents; + let analyticsPlugin = appInsightsInstance.appInsights; + let theConfig = analyticsPlugin.config; + + let excludePageUnloadEvents = theConfig.disablePageUnloadEvents; if (!_houseKeepingNamespace) { _houseKeepingNamespace = mergeEvtNamespace(_evtNamespace, _core.evtNamespace && _core.evtNamespace()); } - if (!appInsightsInstance.appInsights.config.disableFlushOnBeforeUnload) { + if (!theConfig.disableFlushOnBeforeUnload) { // Hook the unload event for the document, window and body to ensure that the client events are flushed to the server // As just hooking the window does not always fire (on chrome) for page navigation's. if (addPageUnloadEventListener(performHousekeeping, excludePageUnloadEvents, _houseKeepingNamespace)) { @@ -375,14 +315,14 @@ export class Initialization implements IApplicationInsights { // A reactNative app may not have a window and therefore the beforeunload/pagehide events -- so don't // log the failure in this case if (!added && !isReactNative()) { - _throwInternal(appInsightsInstance.appInsights.core.logger, + _throwInternal(analyticsPlugin.core.logger, eLoggingSeverity.CRITICAL, _eInternalMessageId.FailedToAddHandlerForOnBeforeUnload, "Could not add handler for beforeunload and pagehide"); } } - if (!added && !appInsightsInstance.appInsights.config.disableFlushOnUnload) { + if (!added && !theConfig.disableFlushOnUnload) { // If we didn't add the normal set then attempt to add the pagehide and visibilitychange only addPageHideEventListener(performHousekeeping, excludePageUnloadEvents, _houseKeepingNamespace); } @@ -445,9 +385,9 @@ export class Initialization implements IApplicationInsights { ]); - function _getSKUDefaults() { - _self.config.diagnosticLogInterval = - _self.config.diagnosticLogInterval && _self.config.diagnosticLogInterval > 0 ? _self.config.diagnosticLogInterval : 10000; + function _getSKUDefaults(config: IConfiguration & IConfig) { + config.diagnosticLogInterval = + config.diagnosticLogInterval && config.diagnosticLogInterval > 0 ? config.diagnosticLogInterval : 10000; } // Using a function to support the dynamic adding / removal of plugins, so this will always return the current value @@ -648,6 +588,7 @@ export class Initialization implements IApplicationInsights { * Initialize this instance of ApplicationInsights * @returns {IApplicationInsights} * @memberof Initialization + * @param legacyMode - MUST always be false, it is no longer supported from v3.x onwards */ public loadAppInsights(legacyMode: boolean = false, logger?: IDiagnosticLogger, notificationManager?: INotificationManager): IApplicationInsights { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging @@ -778,21 +719,21 @@ export class Initialization implements IApplicationInsights { let url = sdkSrc.toLowerCase(); if (url) { let src = ""; - for (let idx = 0; idx < cdns.length; idx++) { - if (url.indexOf(cdns[idx]) !== -1) { + arrForEach(cdns, (value, idx) => { + if (strIndexOf(url, value) !== -1) { src = "cdn" + (idx + 1); - if (url.indexOf("/scripts/") === -1) { - if (url.indexOf("/next/") !== -1) { + if (strIndexOf(url, "/scripts/") === -1) { + if (strIndexOf(url, "/next/") !== -1) { src += "-next"; - } else if (url.indexOf("/beta/") !== -1) { + } else if (strIndexOf(url, "/beta/") !== -1) { src += "-beta"; } } _internalSdkSrc = src + (isModule ? ".mod" : ""); - break; + return -1; } - } + }); } } catch (e) { // eslint-disable-next-line no-empty diff --git a/AISKU/src/InternalConstants.ts b/AISKU/src/InternalConstants.ts index 26514e4a..5c9a9b0f 100644 --- a/AISKU/src/InternalConstants.ts +++ b/AISKU/src/InternalConstants.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!! -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +// ################################################################################################################################################### +// Note: DON'T Export these const from the package as we are still targeting IE/ES5 this will export a mutable variables that someone could change ### +// ################################################################################################################################################### // Generally you should only put values that are used more than 2 times and then only if not already exposed as a constant (such as SdkCoreNames) // as when using "short" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value. diff --git a/AISKU/src/applicationinsights-web.ts b/AISKU/src/applicationinsights-web.ts index 7ccf61b9..4bafce38 100644 --- a/AISKU/src/applicationinsights-web.ts +++ b/AISKU/src/applicationinsights-web.ts @@ -1,12 +1,10 @@ export { IApplicationInsights, Snippet, - Initialization as ApplicationInsights, - Telemetry + Initialization as ApplicationInsights } from "./Initialization"; export { ApplicationInsightsContainer } from "./ApplicationInsightsContainer"; -export { IAppInsightsDeprecated } from "./ApplicationInsightsDeprecated"; // Re-exports export { @@ -35,11 +33,9 @@ export { INotificationManager, IProcessTelemetryContext, Tags, - BaseCore, - CoreUtils, ICoreUtils + BaseCore } from "@microsoft/applicationinsights-core-js"; export { - Util, IUtil, IConfig, IDependencyTelemetry, IPageViewPerformanceTelemetry, @@ -60,7 +56,7 @@ export { RemoteDependencyData, Trace, DistributedTracingModes, - ICorrelationIdHelper, IUrlHelper, IDateTimeUtils, IRequestHeaders + IRequestHeaders } from "@microsoft/applicationinsights-common"; export { Sender } from "@microsoft/applicationinsights-channel-js"; export { ApplicationInsights as ApplicationAnalytics, IAppInsightsInternal } from "@microsoft/applicationinsights-analytics-js"; diff --git a/AISKU/tsconfig.json b/AISKU/tsconfig.json index 6dd05372..1015b6f0 100644 --- a/AISKU/tsconfig.json +++ b/AISKU/tsconfig.json @@ -4,7 +4,7 @@ "inlineSources": true, "noImplicitAny": true, "module": "es6", - "target": "es3", + "target": "es5", "moduleResolution": "Node", "alwaysStrict": true, "suppressImplicitAnyIndexErrors": true, diff --git a/AISKULight/README.md b/AISKULight/README.md index 91a5dae3..78701464 100644 --- a/AISKULight/README.md +++ b/AISKULight/README.md @@ -12,7 +12,7 @@ ms.devlang="na" ms.topic="article" ms.date="10/8/2019"/> - + # Microsoft Application Insights JavaScript SDK - Web Basic [![Build Status](https://dev.azure.com/mseng/AppInsights/_apis/build/status/AppInsights%20-%20DevTools/1DS%20JavaScript%20SDK%20web%20SKU?branchName=master)](https://dev.azure.com/mseng/AppInsights/_build/latest?definitionId=8184&branchName=master) @@ -24,6 +24,13 @@ Application Insights - Web Basic SDK Application Insights AI SKU Light is a package that combines minimum required packages for Web scenarios. Refer to [ApplicationInsights-JS](../README.MD) for more details on getting started. +## Beta Release Breaking changes + +- Removed ES3 / IE8 Support +- Removed V1 API Backward Compatibility (Upgrading V1 -> V3) + +See [Breaking Changes](./BETA_BREAKING_CHANGES.md) + ## Contributing This project welcomes contributions and suggestions. Most contributions require you to diff --git a/AISKULight/package.json b/AISKULight/package.json index c87a3e62..5d4c094b 100644 --- a/AISKULight/package.json +++ b/AISKULight/package.json @@ -29,7 +29,7 @@ "devDependencies": { "@microsoft/ai-test-framework": "0.0.1", "@microsoft/applicationinsights-rollup-plugin-uglify3-js": "1.0.0", - "@microsoft/applicationinsights-rollup-es3": "1.1.3", + "@microsoft/applicationinsights-rollup-es5": "1.0.0", "@microsoft/api-extractor": "^7.18.1", "grunt": "^1.5.3", "grunt-cli": "^1.4.3", @@ -56,7 +56,8 @@ "@microsoft/applicationinsights-shims": "2.0.1", "@microsoft/applicationinsights-common": "2.8.6", "@microsoft/applicationinsights-channel-js": "2.8.6", - "@microsoft/applicationinsights-core-js": "2.8.6" + "@microsoft/applicationinsights-core-js": "2.8.6", + "@nevware21/ts-utils": "^0.4.1" }, "license": "MIT" } diff --git a/AISKULight/rollup.config.js b/AISKULight/rollup.config.js index f4b5b7ee..ff7c9261 100644 --- a/AISKULight/rollup.config.js +++ b/AISKULight/rollup.config.js @@ -3,7 +3,7 @@ import { uglify } from "@microsoft/applicationinsights-rollup-plugin-uglify3-js" import replace from "@rollup/plugin-replace"; import cleanup from "rollup-plugin-cleanup"; import dynamicRemove from "@microsoft/dynamicproto-js/tools/rollup/node/removedynamic"; -import { es3Poly, es3Check, importCheck } from "@microsoft/applicationinsights-rollup-es3"; +import { es5Poly, es5Check, importCheck } from "@microsoft/applicationinsights-rollup-es5"; import { updateDistEsmFiles } from "../tools/updateDistEsm/updateDistEsm"; const packageJson = require("./package.json"); @@ -56,8 +56,8 @@ const browserRollupConfigFactory = (isProduction, libV = '2') => { preferBuiltins: false }), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; @@ -107,8 +107,8 @@ const nodeUmdRollupConfigFactory = (isProduction) => { importCheck({ exclude: [ "index" ] }), nodeResolve(), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; diff --git a/AISKULight/src/index.ts b/AISKULight/src/index.ts index fdae9761..9b06992a 100644 --- a/AISKULight/src/index.ts +++ b/AISKULight/src/index.ts @@ -167,7 +167,6 @@ export { IConfiguration, AppInsightsCore, IAppInsightsCore, - CoreUtils, ITelemetryItem, ILoadedPlugin, arrForEach, diff --git a/AISKULight/tsconfig.json b/AISKULight/tsconfig.json index bc13f464..eebbc082 100644 --- a/AISKULight/tsconfig.json +++ b/AISKULight/tsconfig.json @@ -4,7 +4,7 @@ "inlineSources": true, "noImplicitAny": true, "module": "es6", - "target": "es3", + "target": "es5", "moduleResolution": "Node", "alwaysStrict": true, "suppressImplicitAnyIndexErrors": true, diff --git a/BETA_BREAKING_CHANGES.md b/BETA_BREAKING_CHANGES.md new file mode 100644 index 00000000..220da4d4 --- /dev/null +++ b/BETA_BREAKING_CHANGES.md @@ -0,0 +1,181 @@ +# Beta Breaking Changes + +## ES3 (IE8) Support + +Previous internal polyfills for JavaScript features that are supported by ES5 but not at least IE8 have been removed. + +The SDK still uses internal polyfills for ES5 features that are not supported by IE9+, it will also start to use JavaScript object accessors (get / set) and object defineProperties, both of which cannot be polyfilled so for IE8 support you will need to either transpile the source code (not supported) or continue to use the latest v2.x (Supported). + +The SDK now uses [Object.defineProperty](https://caniuse.com/?search=defineProperty) and therefore support is limited to runtimes (or good polyfills) that can correctly implement this functionality. Without this the SDK will not function correctly. + +## Behavior changes + +| Function | Change +|----------------|-------------- +| strStartsWith | This is now uses the native [startsWith](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith) or a [polyfill if required](https://caniuse.com/?search=startsWith) that conforms the same functionality which will throw a TypeError for `null`, `undefined` values +| strEndsWith | This is now uses the native [endsWith](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith) or a [polyfill if required](https://caniuse.com/?search=endsWith) that conforms the same functionality which will throw a TypeError for `null`, `undefined` values + +## AISKU + +- V1 Snippet Usage +- All V1 API Compatibility Support + +| V1 API | Details +|-----------|--------------------- +| trackPageView | Use V2 API
`trackPageView(pageView?: IPageViewTelemetry)`

V1 Removed
`track(name?: string, url?: string, properties?: {[key: string]: string }, measurements?: {[key: string]: number }, duration?: number)` +| trackEvent | Use V2 API
`trackEvent(event: IEventTelemetry, customProperties?: ICustomProperties)`

V1 Removed
`trackEvent(name: string, properties?: Object, measurements?: Object)` +| trackDependency | Use V2 API
`trackDependencyData(dependency: IDependencyTelemetry)`

V1 Removed
`trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number)` +| trackException | Use V2 API
`trackException(exception: IExceptionTelemetry, customProperties?: ICustomProperties)`

V1 Removed
`trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: any)` +| trackMetric | Use V2 API
`trackMetric(metric: IMetricTelemetry, customProperties?: ICustomProperties)`

V1 Removed
`trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; })` +| trackTrace | Use V2 API
`trackTrace(trace: ITraceTelemetry, customProperties?: ICustomProperties)`

V1 Removed
`trackTrace(message: string, properties?: { [name: string]: string; }, severityLevel?: any)` +| _onerror | Use V2 API
`_onerror(exception: IAutoExceptionTelemetry)`

V1 Removed
`_onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error)` +| downloadAndSetup | Removed + +#### Exported Globals (NPM) + +- Telemetry +- ICoreUtils; CoreUtils +- IUtil; Util +- ICorrelationIdHelper +- IUrlHelper +- IDateTimeUtils +- DataSanitizer (from common module) +- IDataSanitizer (from common module) + +#### Exported Globals (CDN) + +The previously exported namespaced globals have been replaced with a reduced set of individual functions (Which where also exported by v2.8.x) + +> Note: Until the final release all of these "Removed" or "New Access" are subject to be changed. You should not be using the published `beta` for validation purposes and not in a production environment. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Previous CDN namespace / accessReplacement new access
Microsoft.ApplicationInsights.TelemetryRemoved
BreezeChannelIdentifierMicrosoft.ApplicationInsights.BreezeChannelIdentifier
PropertiesPluginIdentifierMicrosoft.ApplicationInsights.PropertiesPluginIdentifier
AnalyticsPluginIdentifierMicrosoft.ApplicationInsights.AnalyticsPluginIdentifier
DisabledPropertyNameMicrosoft.ApplicationInsights.DisabledPropertyName
ProcessLegacyRemoved
SampleRate"sampleRate"
HttpMethod"http.method"
DEFAULT_BREEZE_ENDPOINTMicrosoft.ApplicationInsights.DEFAULT_BREEZE_ENDPOINT
Microsoft.ApplicationInsights.Telemetry.UtilRemoved
NotSpecifiedRemoved
createDomEventRemoved
disableStorageRemoved
isInternalApplicationInsightsEndpointRemoved
canUseLocalStorageRemoved
getStorageRemoved
setStorageRemoved
removeStorageRemoved
canUseSessionStorageRemoved
getSessionStorageKeysRemoved
getSessionStorageRemoved
setSessionStorageRemoved
removeSessionStorageRemoved
disableCookiesRemoved
canUseCookiesRemoved
disallowsSameSiteNoneRemoved
setCookieRemoved
stringToBoolOrDefaultRemoved
getCookieRemoved
deleteCookieRemoved
trimRemoved
newIdMicrosoft.ApplicationInsights.newId
random32Microsoft.ApplicationInsights.random32
generateW3CIdMicrosoft.ApplicationInsights.generateW3CId
isArrayRemoved
isErrorRemoved
isDateRemoved
toISOStringForIE8Removed
getIEVersionRemoved
msToTimeSpanRemoved
isCrossOriginErrorRemoved
dumpRemoved
getExceptionNameRemoved
addEventHandlerMicrosoft.ApplicationInsights.addEventHandler
removeEventHandlerMicrosoft.ApplicationInsights.removeEventHandler
IsBeaconApiSupportedMicrosoft.ApplicationInsights.IsBeaconApiSupported
getExtensionappInsights.getPlugin("<plugin id>")?.plugin
Microsoft.ApplicationInsights.Telemetry.CorrelationIdHelperRemoved
Microsoft.ApplicationInsights.Telemetry.UrlHelperRemoved
Microsoft.ApplicationInsights.Telemetry.DateTimeUtilsRemoved
Microsoft.ApplicationInsights.Telemetry.ConnectionStringParserRemoved
Microsoft.ApplicationInsights.Telemetry.FieldType (enum)Removed
Microsoft.ApplicationInsights.Telemetry.RequestHeaders (enum)Microsoft.ApplicationInsights.RequestHeaders
Microsoft.ApplicationInsights.Telemetry.Envelope (class)Removed
Microsoft.ApplicationInsights.Telemetry.Event (class)Removed
Microsoft.ApplicationInsights.Telemetry.Exception (class)Removed
Microsoft.ApplicationInsights.Telemetry.Metric (class)Removed
Microsoft.ApplicationInsights.Telemetry.PageView (class)Removed
Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData (class)Removed
Microsoft.ApplicationInsights.Telemetry.Trace (class)Removed
Microsoft.ApplicationInsights.Telemetry.PageViewPerformance (class)Removed
Microsoft.ApplicationInsights.Telemetry.Data (class)Removed
Microsoft.ApplicationInsights.Telemetry.SeverityLevel (enum)Microsoft.ApplicationInsights.SeverityLevel
Microsoft.ApplicationInsights.Telemetry.ConfigurationManager (class)Removed
Microsoft.ApplicationInsights.Telemetry.ContextTagKeys (class)Removed
Microsoft.ApplicationInsights.Telemetry.DataSanitizerRemoved
Microsoft.ApplicationInsights.Telemetry.TelemetryItemCreatorRemoved
Microsoft.ApplicationInsights.Telemetry.CtxTagKeysRemoved
Microsoft.ApplicationInsights.Telemetry.Extensions (enum)Removed
Microsoft.ApplicationInsights.Telemetry.DistributedTracingMode (enum)Microsoft.ApplicationInsights.DistributedTracingMode
Microsoft.ApplicationInsights.UtilRemoved: see Microsoft.ApplicationInsights.Telemetry.Util
+ +### AISKU Light + +#### Exported Globals + +- CoreUtils + +### @microsoft/applicationinsights-common + +#### Exported Globals (NPM) + +- IUtil; Util + - Use the individual `utl` prefixed functions that are also exported in later v2 releases documented in the [Tree Shaking Recommendations](https://github.com/microsoft/ApplicationInsights-JS/blob/master/TreeShakingRecommendations.md). +- ICorrelationIdHelper; CorrelationIdHelper + - Use the individual `correlationId` prefixed functions that are also exported in later v2 releases documented in the [Tree Shaking Recommendations](https://github.com/microsoft/ApplicationInsights-JS/blob/master/TreeShakingRecommendations.md). +- IDateTimeUtils; DateTimeUtils; + - Use the individual `dateTimeUtils` prefixed functions that are also exported in later v2 releases documented in the [Tree Shaking Recommendations](https://github.com/microsoft/ApplicationInsights-JS/blob/master/TreeShakingRecommendations.md). +- IUrlHelper; UrlHelper + - Use the individual `url` prefixed functions that are also exported in later v2 releases documented in the [Tree Shaking Recommendations](https://github.com/microsoft/ApplicationInsights-JS/blob/master/TreeShakingRecommendations.md). +- IDataSanitizer, DataSanitizer + - Use the individual `dataSanitizer` prefixed functions that are also exported in later v2 releases documented in the [Tree Shaking Recommendations](https://github.com/microsoft/ApplicationInsights-JS/blob/master/TreeShakingRecommendations.md). + + +### @microsoft/applicationinsights-core-js + +All previously `@deprecated` marked functions and the legacy "global" cookie handling functions +#### Exported Globals (NPM) + +- ICoreUtils; CoreUtils + - See the replacements documented in the [Tree Shaking Recommendations](https://github.com/microsoft/ApplicationInsights-JS/blob/master/TreeShakingRecommendations.md). +- IEventHelper; EventHelper + - See the replacements documented in the [Tree Shaking Recommendations](https://github.com/microsoft/ApplicationInsights-JS/blob/master/TreeShakingRecommendations.md). +- EnumMap, createEnumMap + - Removed as not used internally, use the ts-utils support versions if required + +##### Removed no replacement + +- disableCookies +- canUseCookies +- getCookie +- setCookie +- deleteCookie +- _legacyCookieMgr + +## Browser Support + +Minimum JavaScript Language Specification: ES5 + +![Chrome](https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.githubusercontent.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![IE](https://raw.githubusercontent.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![Opera](https://raw.githubusercontent.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Safari](https://raw.githubusercontent.com/alrra/browser-logos/master/src/safari/safari_48x48.png) +--- | --- | --- | --- | --- | +Latest ✔ | Latest ✔ | 9+ Full ✔ | Latest ✔ | Latest ✔ | + +> Note: ES3/IE8 compatibilityhas been removed, so if you need to retain ES3 compatibility you will need to remain on the 2.x.x versions of the SDK. \ No newline at end of file diff --git a/README.md b/README.md index 92f296b5..a130ae87 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,18 @@ [![minified size size](https://img.badgesize.io/https://js.monitor.azure.com/scripts/b/ai.2.min.js.svg?label=minified%20size)](https://img.badgesize.io/https://js.monitor.azure.com/scripts/b/ai.2.min.js.svg?label=minified%20size) [![gzip size](https://img.badgesize.io/https://js.monitor.azure.com/scripts/b/ai.2.min.js.svg?compression=gzip&softmax=30000&max=35000)](https://img.badgesize.io/https://js.monitor.azure.com/scripts/b/ai.2.min.js.svg?compression=gzip&softmax=30000&max=35000) -> ***Note:*** The documentation for `applicationinsights-js@1.0.20` has moved [here](./legacy/README.md). If you are looking to upgrade to the new version of the SDK, please see the [Upgrade Guide](#upgrading-from-the-old-version-of-application-insights). For Node.js instrumentation reference this [repository](https://github.com/microsoft/ApplicationInsights-node.js). +## Beta (v3.x) Release Breaking changes + +- Removed ES3 / IE8 Support +- Removed V1 API Backward Compatibility (Upgrading V1 -> V3) + +See [Breaking Changes](./BETA_BREAKING_CHANGES.md) + +> ***Note:*** The documentation for `applicationinsights-js@1.0.20` has moved [here](./legacy/README.md). +> +> See the [V1 Upgrade Guide](#upgrading-from-the-old-version-of-application-insights). +> +> For Node.js instrumentation reference this [repository](https://github.com/microsoft/ApplicationInsights-node.js). ## Getting Started @@ -630,6 +641,11 @@ It is expected that most users will be using the `Public` URL, however, it is al [Changelist](./CHANGELIST.md) + +### Beta Breaking Changes + +See [the working beta breaking changes notes](./BETA_BREAKING_CHANGES.md) + ## Browser Support ![Chrome](https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.githubusercontent.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![IE](https://raw.githubusercontent.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![Opera](https://raw.githubusercontent.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Safari](https://raw.githubusercontent.com/alrra/browser-logos/master/src/safari/safari_48x48.png) @@ -661,7 +677,9 @@ git push ## ES3/IE8 Compatibility -> Future releases of the SDK numbered v3.x.x will be removing ES3 (IE8) support, so if you need to retain ES3 compatibility for your environment you will need to remain on the 2.x.x versions of the SDK or your runtime will need install polyfill's to your ES3 environment before loading / initializing the SDK. +__v3.x NO Longer supports ES3 / IE8__ + +> If you need to retain ES3 compatibility for your environment you will need to remain on the 2.x.x versions of the SDK or your runtime will need install polyfill's to your ES3 environment before loading / initializing the SDK. However, v3.x now uses [Object.defineProperty](https://caniuse.com/?search=defineProperty) so a polyfills that can correctly implement this functionality (if available) will be required, without this the SDK will not function correctly. As an SDK there are numerous users which cannot control the browsers that their customers use. As such we need to ensure that this SDK continues to "work" and does not break the JS execution when loaded by an older browser. While it would be ideal to just not support IE8 and older generation (ES3) browsers there are numerous large customers/users that continue to require pages to "work" and as noted they may or cannot control which browser that their end users choose to use. @@ -669,7 +687,7 @@ This does NOT mean that we will only support the lowest common set of features, As part of enabling ES3/IE8 support we have set the ```tsconfig.json``` to ES3 and ```uglify``` settings in ```rollup.config.js``` transformations to support ie8. This provides a first level of support which blocks anyone from adding unsupported ES3 features to the code and enables the generated javascript to be validily parsed in an ES3+ environment. -Ensuring that the generated code is compatible with ES3 is only the first step, JS parsers will still parse the code when an unsupport core function is used, it will just fail or throw an exception at runtime. Therefore, we also need to require/use polyfil implementations or helper functions to handle those scenarios. +Ensuring that the generated code is compatible with ES3 is only the first step, JS parsers will still parse the code when an unsupport core function is used, it will just fail or throw an exception at runtime. Therefore, we also need to require/use polyfill implementations or helper functions to handle those scenarios. It should also be noted that the overall goal of ES3/IE8 compatibility is the support at least the following 2 usage usage patterns. By supporting these two (2) basic use-cases, application/developers will be able to determine what browsers their users are using and whether they are experiencing any issues. As the SDK will report the data to the server, thus enabling the insights into whether they need to either fully support ES3/IE8 or provide some sort of browser upgrade notifications. @@ -696,6 +714,8 @@ For this case either provide a JSON polyfil or add the ["X-UA-Compatible"](https ### ES3/IE8 Packaging helper (ES3 rollup-plugin) +> Removed for v.3, only supported for 2.x + To ensure that the system conforms to the ES3 spec, by only using ES3 compatible code we have created a rollup plugin which has 2 functions - es3Poly() finds and rewrite several commonly incompatible functions (such as Object.defineProperty; Object.getOwnPropertyDescriptor; Object.create) with inline polyfill functions that either call the real implementation or provide a basic implementation so that the scripts can be loaded and executed. diff --git a/channels/applicationinsights-channel-js/Tests/Unit/src/Sample.tests.ts b/channels/applicationinsights-channel-js/Tests/Unit/src/Sample.tests.ts index 6b72a8b5..1a5f630b 100644 --- a/channels/applicationinsights-channel-js/Tests/Unit/src/Sample.tests.ts +++ b/channels/applicationinsights-channel-js/Tests/Unit/src/Sample.tests.ts @@ -1,7 +1,7 @@ import { AITestClass } from "@microsoft/ai-test-framework"; import { Sample } from "../../../src/TelemetryProcessors/Sample"; -import { ITelemetryItem } from "@microsoft/applicationinsights-core-js"; -import { PageView, TelemetryItemCreator, IPageViewTelemetry, Util } from "@microsoft/applicationinsights-common"; +import { ITelemetryItem, newId } from "@microsoft/applicationinsights-core-js"; +import { PageView, TelemetryItemCreator, IPageViewTelemetry } from "@microsoft/applicationinsights-common"; import { HashCodeScoreGenerator } from "../../../src/TelemetryProcessors/SamplingScoreGenerators/HashCodeScoreGenerator"; export class SampleTests extends AITestClass { @@ -118,7 +118,7 @@ export class SampleTests extends AITestClass { const totalItems = 1000; const ids = []; for (let i = 0; i < totalItems; ++i) { - ids.push(Util.newId()); + ids.push(newId()); } const sampleRates = [50, 33, 25, 20, 16, 10]; diff --git a/channels/applicationinsights-channel-js/Tests/Unit/src/Sender.tests.ts b/channels/applicationinsights-channel-js/Tests/Unit/src/Sender.tests.ts index d4a82167..34fea73a 100644 --- a/channels/applicationinsights-channel-js/Tests/Unit/src/Sender.tests.ts +++ b/channels/applicationinsights-channel-js/Tests/Unit/src/Sender.tests.ts @@ -2,7 +2,7 @@ import { AITestClass } from "@microsoft/ai-test-framework"; import { Sender } from "../../../src/Sender"; import { createOfflineListener, IOfflineListener } from '../../../src/Offline'; import { EnvelopeCreator } from '../../../src/EnvelopeCreator'; -import { Exception, CtxTagKeys, Util } from "@microsoft/applicationinsights-common"; +import { Exception, CtxTagKeys, isBeaconApiSupported } from "@microsoft/applicationinsights-common"; import { ITelemetryItem, AppInsightsCore, ITelemetryPlugin, DiagnosticLogger, NotificationManager, SendRequestReason, _InternalMessageId, LoggingSeverity, getGlobalInst, getGlobal } from "@microsoft/applicationinsights-core-js"; export class SenderTests extends AITestClass { @@ -179,7 +179,7 @@ export class SenderTests extends AITestClass { baseData: {} }; - QUnit.assert.ok(Util.IsBeaconApiSupported(), "Beacon API is supported"); + QUnit.assert.ok(isBeaconApiSupported(), "Beacon API is supported"); QUnit.assert.equal(false, sendBeaconCalled, "Beacon API was not called before"); QUnit.assert.equal(0, this._getXhrRequests().length, "xhr sender was not called before"); @@ -223,7 +223,7 @@ export class SenderTests extends AITestClass { baseData: {} }; - QUnit.assert.ok(Util.IsBeaconApiSupported(), "Beacon API is supported"); + QUnit.assert.ok(isBeaconApiSupported(), "Beacon API is supported"); QUnit.assert.equal(false, sendBeaconCalled, "Beacon API was not called before"); QUnit.assert.equal(0, this._getXhrRequests().length, "xhr sender was not called before"); @@ -281,7 +281,7 @@ export class SenderTests extends AITestClass { telemetryItems[i] = telemetryItem; } - QUnit.assert.ok(Util.IsBeaconApiSupported(), "Beacon API is supported"); + QUnit.assert.ok(isBeaconApiSupported(), "Beacon API is supported"); QUnit.assert.equal(false, sendBeaconCalled, "Beacon API was not called before"); QUnit.assert.equal(0, this._getXhrRequests().length, "xhr sender was not called before"); @@ -333,7 +333,7 @@ export class SenderTests extends AITestClass { baseData: {} }; - QUnit.assert.ok(Util.IsBeaconApiSupported(), "Beacon API is supported"); + QUnit.assert.ok(isBeaconApiSupported(), "Beacon API is supported"); QUnit.assert.equal(false, sendBeaconCalled, "Beacon API was not called before"); QUnit.assert.equal(0, this._getXhrRequests().length, "xhr sender was not called before"); @@ -384,7 +384,7 @@ export class SenderTests extends AITestClass { baseData: {} }; - QUnit.assert.ok(Util.IsBeaconApiSupported(), "Beacon API is supported"); + QUnit.assert.ok(isBeaconApiSupported(), "Beacon API is supported"); QUnit.assert.equal(false, sendBeaconCalled, "Beacon API was not called before"); QUnit.assert.equal(0, this._getXhrRequests().length, "xhr sender was not called before"); diff --git a/channels/applicationinsights-channel-js/package.json b/channels/applicationinsights-channel-js/package.json index bdc46ec7..20efc243 100644 --- a/channels/applicationinsights-channel-js/package.json +++ b/channels/applicationinsights-channel-js/package.json @@ -26,7 +26,7 @@ "devDependencies": { "@microsoft/ai-test-framework": "0.0.1", "@microsoft/applicationinsights-rollup-plugin-uglify3-js": "1.0.0", - "@microsoft/applicationinsights-rollup-es3": "1.1.3", + "@microsoft/applicationinsights-rollup-es5": "1.0.0", "@microsoft/api-extractor": "^7.18.1", "@types/sinon": "4.3.3", "grunt": "^1.5.3", @@ -51,7 +51,8 @@ "@microsoft/dynamicproto-js": "^1.1.6", "@microsoft/applicationinsights-shims": "2.0.1", "@microsoft/applicationinsights-core-js": "2.8.6", - "@microsoft/applicationinsights-common": "2.8.6" + "@microsoft/applicationinsights-common": "2.8.6", + "@nevware21/ts-utils": "^0.4.1" }, "license": "MIT" } diff --git a/channels/applicationinsights-channel-js/rollup.config.js b/channels/applicationinsights-channel-js/rollup.config.js index 5c6b6e15..5f75c58c 100644 --- a/channels/applicationinsights-channel-js/rollup.config.js +++ b/channels/applicationinsights-channel-js/rollup.config.js @@ -3,7 +3,7 @@ import { uglify } from "@microsoft/applicationinsights-rollup-plugin-uglify3-js" import replace from "@rollup/plugin-replace"; import cleanup from "rollup-plugin-cleanup"; import dynamicRemove from "@microsoft/dynamicproto-js/tools/rollup/node/removedynamic"; -import { es3Poly, es3Check, importCheck } from "@microsoft/applicationinsights-rollup-es3"; +import { es5Poly, es5Check, importCheck } from "@microsoft/applicationinsights-rollup-es5"; import { updateDistEsmFiles } from "../../tools/updateDistEsm/updateDistEsm"; const version = require("./package.json").version; @@ -55,8 +55,8 @@ const browserRollupConfigFactory = isProduction => { preferBuiltins: false }), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; @@ -106,8 +106,8 @@ const nodeUmdRollupConfigFactory = (isProduction) => { importCheck({ exclude: [ "applicationinsights-channel-js" ] }), nodeResolve(), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; diff --git a/channels/applicationinsights-channel-js/src/InternalConstants.ts b/channels/applicationinsights-channel-js/src/InternalConstants.ts index d6240c39..cfc710e7 100644 --- a/channels/applicationinsights-channel-js/src/InternalConstants.ts +++ b/channels/applicationinsights-channel-js/src/InternalConstants.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!! -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +// ################################################################################################################################################### +// Note: DON'T Export these const from the package as we are still targeting IE/ES5 this will export a mutable variables that someone could change ### +// ################################################################################################################################################### // Generally you should only put values that are used more than 2 times and then only if not already exposed as a constant (such as SdkCoreNames) // as when using "short" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value. diff --git a/channels/applicationinsights-channel-js/tsconfig.json b/channels/applicationinsights-channel-js/tsconfig.json index 7ef76a86..351b4930 100644 --- a/channels/applicationinsights-channel-js/tsconfig.json +++ b/channels/applicationinsights-channel-js/tsconfig.json @@ -5,7 +5,7 @@ "noImplicitAny": true, "module": "es6", "moduleResolution": "Node", - "target": "es3", + "target": "es5", "alwaysStrict": true, "suppressImplicitAnyIndexErrors": true, "allowSyntheticDefaultImports": true, diff --git a/common/Tests/Framework/package.json b/common/Tests/Framework/package.json index 4b330941..79553193 100644 --- a/common/Tests/Framework/package.json +++ b/common/Tests/Framework/package.json @@ -49,6 +49,7 @@ "tslib": "*" }, "dependencies": { - "@microsoft/dynamicproto-js": "^1.1.6" + "@microsoft/dynamicproto-js": "^1.1.6", + "@nevware21/ts-utils": "^0.4.1" } } diff --git a/common/Tests/Framework/src/AITestClass.ts b/common/Tests/Framework/src/AITestClass.ts index f70201f8..d127e251 100644 --- a/common/Tests/Framework/src/AITestClass.ts +++ b/common/Tests/Framework/src/AITestClass.ts @@ -76,7 +76,7 @@ export class AITestClass { protected clock: any; public sandbox: SinonSandbox; public fakeServerAutoRespond: boolean = false; - public isEmulatingEs3: boolean; + public isEmulatingIe: boolean; /** * Automatically assert that all registered events have been removed @@ -102,15 +102,15 @@ export class AITestClass { private _beaconHooks: any[] = []; private _dynProtoOpts: any = null; - // Simulate an Es3 environment + // Simulate an IE environment private _orgObjectFuncs: any = null; private _orgFetch: any = null; private _onDoneFuncs: VoidFunction[] = []; - constructor(name?: string, emulateEs3?: boolean) { - this._moduleName = (emulateEs3 ? "(ES3) " : "") + (name || _getObjName(this, "")); - this.isEmulatingEs3 = emulateEs3 + constructor(name?: string, emulateIE?: boolean) { + this._moduleName = (emulateIE ? "(IE) " : "") + (name || _getObjName(this, "")); + this.isEmulatingIe = emulateIE QUnit.module(this._moduleName); this.sandboxConfig.injectIntoThis = true; this.sandboxConfig.injectInto = null; @@ -221,8 +221,8 @@ export class AITestClass { self.clock = sinon.useFakeTimers(); } - if (self.isEmulatingEs3) { - self._emulateEs3(); + if (self.isEmulatingIe) { + self._emulateIE(); } if (testInfo.assertNoEvents === undefined) { @@ -352,7 +352,7 @@ export class AITestClass { }; // Register the test with QUnit - QUnit.test((this.isEmulatingEs3 ? "(ES3) " : "") + testInfo.name + " - (Async)", testMethod); + QUnit.test((this.isEmulatingIe ? "(IE) " : "") + testInfo.name + " - (Async)", testMethod); } /** Register a Javascript unit testcase. */ @@ -433,8 +433,8 @@ export class AITestClass { this.clock = sinon.useFakeTimers(); } - if (this.isEmulatingEs3) { - this._emulateEs3(); + if (this.isEmulatingIe) { + this._emulateIE(); } if (testInfo.assertNoEvents === undefined) { @@ -480,7 +480,7 @@ export class AITestClass { }; // Register the test with QUnit - QUnit.test((this.isEmulatingEs3 ? "(ES3) " : "") + testInfo.name, testMethod); + QUnit.test((this.isEmulatingIe ? "(IE) " : "") + testInfo.name, testMethod); } /** Creates an anonymous function that records arguments, this value, exceptions and return values for all calls. */ @@ -853,7 +853,7 @@ export class AITestClass { // Initialize the sandbox similar to what is done in sinon.js "test()" override. See note on class. _self.sandbox = sinon.createSandbox(this.sandboxConfig); - if (_self.isEmulatingEs3) { + if (_self.isEmulatingIe) { // As we removed Object.define we need to temporarily restore this for each sandbox call for (var field in _self.sandbox) { var value = _self.sandbox[field]; @@ -936,7 +936,7 @@ export class AITestClass { this._beaconHooks = []; this._cleanupAllHooks(); this._cleanupEvents(); - this._restoreEs3(); + this._restoreIE(); if (failed) { // Just cleanup the sandbox since the test has already failed. @@ -1034,7 +1034,7 @@ export class AITestClass { } } - private _restoreEs3() { + private _restoreIE() { this._restoreObject(this._orgObjectFuncs); this._orgObjectFuncs = null; @@ -1045,8 +1045,8 @@ export class AITestClass { } } - private _emulateEs3() { - const objectNames = [ "defineProperty", "defineProperties"]; + private _emulateIE() { + const objectNames = [ "assign"]; if (!this._orgObjectFuncs) { this._orgObjectFuncs = {}; for (var lp = 0; lp < objectNames.length; lp++) { @@ -1062,8 +1062,8 @@ export class AITestClass { global.fetch = null; } - // Lets pretend to also be IE8 - this.setUserAgent("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)"); + // Lets pretend to also be IE9 + this.setUserAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)"); } private _unhookXhr() { diff --git a/common/Tests/Selenium/ModuleLoader.js b/common/Tests/Selenium/ModuleLoader.js index 2f88d882..5464647e 100644 --- a/common/Tests/Selenium/ModuleLoader.js +++ b/common/Tests/Selenium/ModuleLoader.js @@ -36,6 +36,9 @@ function loadCommonModules(moduleLoader) { // Load DynamicProto moduleLoader.add("@microsoft/dynamicproto-js", "./node_modules/@microsoft/dynamicproto-js/lib/dist/umd/dynamicproto-js", true); + + // Load ts-utils + moduleLoader.add("@nevware21/ts-utils", "./node_modules/@nevware21/ts-utils/dist/umd/ts-utils"); } function ModuleLoader(config) { diff --git a/common/config/rush/npm-shrinkwrap.json b/common/config/rush/npm-shrinkwrap.json index bdec7c78..f0b451d5 100644 --- a/common/config/rush/npm-shrinkwrap.json +++ b/common/config/rush/npm-shrinkwrap.json @@ -12,6 +12,7 @@ "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -27,7 +28,7 @@ "@rush-temp/applicationinsights-js-release-tools": "file:./projects/applicationinsights-js-release-tools.tgz", "@rush-temp/applicationinsights-perfmarkmeasure-js": "file:./projects/applicationinsights-perfmarkmeasure-js.tgz", "@rush-temp/applicationinsights-properties-js": "file:./projects/applicationinsights-properties-js.tgz", - "@rush-temp/applicationinsights-rollup-es3": "file:./projects/applicationinsights-rollup-es3.tgz", + "@rush-temp/applicationinsights-rollup-es5": "file:./projects/applicationinsights-rollup-es5.tgz", "@rush-temp/applicationinsights-rollup-plugin-uglify3-js": "file:./projects/applicationinsights-rollup-plugin-uglify3-js.tgz", "@rush-temp/applicationinsights-shims": "file:./projects/applicationinsights-shims.tgz", "@rush-temp/applicationinsights-web": "file:./projects/applicationinsights-web.tgz", @@ -216,9 +217,9 @@ "peer": true }, "node_modules/@microsoft/api-extractor": { - "version": "7.29.0", - "resolved": "https://registry.npmjs.org/@microsoft/api-extractor/-/api-extractor-7.29.0.tgz", - "integrity": "sha512-tGU5DiwQ7/gN9Chi7cuAdspTuVY8hNcq5hBtvwAvb1H85tbiIHuqgoneHI60rkqlud7szkHJLiCkv75kQ0JLjw==", + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@microsoft/api-extractor/-/api-extractor-7.29.2.tgz", + "integrity": "sha512-MwT/Xi1DperfrBO+SU3f/xKdyR6bMvk59/WN6w7g1rHmDBMegan3Ya6npMo+abJAgQOtp6uExY/elHXcYE/Ofw==", "dependencies": { "@microsoft/api-extractor-model": "7.23.0", "@microsoft/tsdoc": "0.14.1", @@ -311,6 +312,14 @@ "typescript": ">=1" } }, + "node_modules/@nevware21/ts-utils": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@nevware21/ts-utils/-/ts-utils-0.4.2.tgz", + "integrity": "sha512-Yxk6QEVCo/0pjxK/vT/PqvTzXnxfXRvf0uE85+TdxAoYFzDFGhYRL4bwfwiXLg+2/2q20VeqsD4HFWO/Rf3u4g==", + "peerDependencies": { + "typescript": ">=1" + } + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -434,10 +443,11 @@ "node_modules/@rush-temp/ai-test-framework": { "version": "0.0.0", "resolved": "file:projects/ai-test-framework.tgz", - "integrity": "sha512-yjPY5CEUu3i2ksoKxuTL7H7IgVFUm0dZHkD4psM7fM9fBY7GWonKdwK0EBMjzhJg7DzKUwb9JSIyCArMPPYLgw==", + "integrity": "sha512-doBzGvzpTAICOB+Co9tTtCmLWQHi8WFlYkk6sjHjQYFQLWoD9i60TJnsvkduArcfy7A+/GODQMtuUr95TKa96g==", "dependencies": { "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -457,12 +467,13 @@ "node_modules/@rush-temp/applicationinsights-analytics-js": { "version": "0.0.0", "resolved": "file:projects/applicationinsights-analytics-js.tgz", - "integrity": "sha512-e+G6klxGEPEheslnNo9OI4lQ2XsUuhPcQU2EA14WArCCNpKAJl4IizSBOqBRGQsTfrbejhYQz/IHc2ISi1w3Rw==", + "integrity": "sha512-4ZG/Lpmj79vzNazdHUE9F+2rRASNtXqua0P9/XTMnuKWcpm23EE07WRXHXK6TcTjWAyDtMVp9k29q8Dhs7z1gA==", "dependencies": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -483,12 +494,13 @@ "node_modules/@rush-temp/applicationinsights-channel-js": { "version": "0.0.0", "resolved": "file:projects/applicationinsights-channel-js.tgz", - "integrity": "sha512-cD/vxlmvqByVryffR+1Oe55Aug15OjXog+hNxaBbeT+9CRmvrsWDBzHncglNv5AzhS9wIoRT20aPppDbYK+Jdw==", + "integrity": "sha512-6qlxhBlep8vKbE3d9FAVCSHMqisE1uGqmd9EbXDByMlDdG7rvttPb19CLdvpYla45yJDkV+ZkIyz4WuTn4VxsQ==", "dependencies": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -507,11 +519,12 @@ "node_modules/@rush-temp/applicationinsights-chrome-debug-extension": { "version": "0.0.0", "resolved": "file:projects/applicationinsights-chrome-debug-extension.tgz", - "integrity": "sha512-Qo/UzEbrM3wh0rJE4JCgV+SC9c7OvzRPSpXqekDj3a3XVd+LyHnFOJHdsbUWQYDz3tyWNhGDu6JCSKNZgPAzeA==", + "integrity": "sha512-hD7+Qbgzq0aXq63jQdhzcPWzM119klB1g6th90wUieq2FPT9DIVcTWvLdAwfOeOchCa8BuxNYZ7YD0CrPcHZ3A==", "dependencies": { "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -540,12 +553,13 @@ "node_modules/@rush-temp/applicationinsights-clickanalytics-js": { "version": "0.0.0", "resolved": "file:projects/applicationinsights-clickanalytics-js.tgz", - "integrity": "sha512-PKGsLGV7l758Aqu/wvumxNSIv8Ufsa0ZwAv9nrgZ6z0Mn2bJ51aEq3Zj9IjG/HgkkWISSqOpCgVD3impZAb9Ew==", + "integrity": "sha512-+HqAtLRk0o2WygoDHMMfLQa3667jT93gHOGMPJ2srTx/+r5MqE7WnzNTi+Yknfi3YLX90ieGdScKPsA70b80Mw==", "dependencies": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -563,12 +577,13 @@ "node_modules/@rush-temp/applicationinsights-common": { "version": "0.0.0", "resolved": "file:projects/applicationinsights-common.tgz", - "integrity": "sha512-4r7ARInSkJma/1h1AylJ3mEUo+SiAa5gI024vB0jtq+L1tNIlBA0pUgOBQ1dN8r+jcMKCehh33lerrfkiBVokg==", + "integrity": "sha512-l0TU23M8f1+chGFzKDTP6UmsH+KJVEF+plsSDjMzg/XB8wFuIc8h2gVFRjlDDkaS2p44TIR4TH3uty0nob50Hg==", "dependencies": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -586,12 +601,13 @@ "node_modules/@rush-temp/applicationinsights-core-js": { "version": "0.0.0", "resolved": "file:projects/applicationinsights-core-js.tgz", - "integrity": "sha512-SztEaTjL3N2Fd7vhsS+2H+xDY8sf58zNHxddDUZ5flTirdPMrsrZXm9YkNkRVsCRMl7f6BS4jh0Yi2Q5U2B9mA==", + "integrity": "sha512-UBhuXTCiGOYOQ7qjKT/lNVzb/O0A2CjYL1jZ5Nq88uQLLXlqjha+5KraHP+3LrQEISPZLjvXEvwUqfAMIi2t4Q==", "dependencies": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -612,12 +628,13 @@ "node_modules/@rush-temp/applicationinsights-debugplugin-js": { "version": "0.0.0", "resolved": "file:projects/applicationinsights-debugplugin-js.tgz", - "integrity": "sha512-1B0OdYdRnA38Irb/eHI/zn43tvJ/fdu3C6hWRdZHzYKkIxznR2UCtoUd4Soi+AcrYtEOOCxMw59gyuwx7CLXjQ==", + "integrity": "sha512-vbmtSvXaphFZvXleqnb7jKcfh6j3k5a1K2Nf9WI2KW2mQUPZHDnkmhtGZCpIGImE5w+j1SHam4qhv1yYAm77Nw==", "dependencies": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -635,12 +652,13 @@ "node_modules/@rush-temp/applicationinsights-dependencies-js": { "version": "0.0.0", "resolved": "file:projects/applicationinsights-dependencies-js.tgz", - "integrity": "sha512-lU58R0yLF8E+iRCBMc5ukK/d0G1Ppv8xscScpSFzW9iaq9nHnhPSbEqP2OZpj51xipkrkY4ZcssuSkj65dKkjg==", + "integrity": "sha512-YTcrHQjAb+mtmJqwdhImpAqloG0EQIHHeFZPhWghX3T7gXEB7dmwO3zkrEgtwFa9LGTBy7u71tO/KkThWN60sQ==", "dependencies": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -669,12 +687,13 @@ "node_modules/@rush-temp/applicationinsights-perfmarkmeasure-js": { "version": "0.0.0", "resolved": "file:projects/applicationinsights-perfmarkmeasure-js.tgz", - "integrity": "sha512-xgyX8+jt+V3QdwJdjkJSe/n3UVsxrWXDJszHIg849sm5iRR36AAdpeXWhNz5SPUDs41qwAooIuXLLdhDJE6rCQ==", + "integrity": "sha512-GfsHdlIEpK3hPMlZH/buFQa+TUQarzGd5buRR4LJoclMhOBYh4JtXWD29rJukS4/emzfGzaqKjN6F5tF+vnVMg==", "dependencies": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -692,12 +711,13 @@ "node_modules/@rush-temp/applicationinsights-properties-js": { "version": "0.0.0", "resolved": "file:projects/applicationinsights-properties-js.tgz", - "integrity": "sha512-CAYoZNh8Ptb6GpkKSdWSsaO1uuz5Rxrt2BuNft6lQAN2H84mVSjheseL5XUhjHkuMutBFS7VjmRcedLPkXyk/w==", + "integrity": "sha512-wzCBV7eGBbTaCxxBohPVtaXRf2YsMljnFSEqWxvbUh9JcrsrHGfmqRMOt+f+2rwreuFj4oock6g34n2J+zpANA==", "dependencies": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -715,10 +735,10 @@ "typescript": "^4.3.4" } }, - "node_modules/@rush-temp/applicationinsights-rollup-es3": { + "node_modules/@rush-temp/applicationinsights-rollup-es5": { "version": "0.0.0", - "resolved": "file:projects/applicationinsights-rollup-es3.tgz", - "integrity": "sha512-+AxiDd0vi6uL1M2WHFO5NbfJnw1FnrcyxmosJsM5cYKm1pHRWwzZ9PEYJVsk1S6u8dFoIeHP2D/EUOmlyFCFsQ==", + "resolved": "file:projects/applicationinsights-rollup-es5.tgz", + "integrity": "sha512-YHKm8PzgPPT18YRyhBsOEDqNV9KXJTh++RqbCY5vy9PVVPQoR9Zxv+oAy7paEx5WLGMKcQZpf2+nKuSQl5mzHA==", "dependencies": { "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", @@ -759,7 +779,7 @@ "node_modules/@rush-temp/applicationinsights-shims": { "version": "0.0.0", "resolved": "file:projects/applicationinsights-shims.tgz", - "integrity": "sha512-PqilXn6zDJYvEy4lW/egvZIS8XzY4/kLmXxMIBaOyK62aI1DFjPnsFiQ5qtNz8IJHCC68S2t+cqHgFL6Fvfqnw==", + "integrity": "sha512-5WZvcytfCP3WCp0Xk67itDYh2d+5Ecn1qYingby3i2vrXMEE1UeSYmHh5qCfr1NvoC6ZsEHWT7HbYIhEEZb8RA==", "dependencies": { "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", @@ -777,12 +797,13 @@ "node_modules/@rush-temp/applicationinsights-web": { "version": "0.0.0", "resolved": "file:projects/applicationinsights-web.tgz", - "integrity": "sha512-bugU7hij9rime4/A0uLAciSBFlqo7rihS/ah0vE6LS9oHo59PDkgiEYpeTSCwQ126ZuxVruiQYvYimtpMvaMbA==", + "integrity": "sha512-0xGuLIyex6oKs9qrzVpF/AGFgZNkMHQcRac2ZWdKcppWRZ9nUGKV6yyR6bEDaFIgWZ3/LmCYu3l7p+MtpbG4YQ==", "dependencies": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -806,12 +827,13 @@ "node_modules/@rush-temp/applicationinsights-web-basic": { "version": "0.0.0", "resolved": "file:projects/applicationinsights-web-basic.tgz", - "integrity": "sha512-mkYpKx1ZcYUcK4aZrMFPDmDsFKwoER7FkQCCSEJwC+lcbgr17luxoHBuwYjIoocJiyJq/pF4x4jiNYtVtrHEDA==", + "integrity": "sha512-wSNk4D25AzqkMQkju86LuywZarbeh4jA1/isbCHaKQsnl0dZ40WIn7QNGS75fbWdmExokEA74GeunHbQ1su4ZQ==", "dependencies": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -831,7 +853,7 @@ "node_modules/@rush-temp/applicationinsights-web-snippet": { "version": "0.0.0", "resolved": "file:projects/applicationinsights-web-snippet.tgz", - "integrity": "sha512-kePeqqOP1DTkf9PwnjtqhkeFZFmwSCfPEYrdbUyKsHQugP2nQPa1YVsTWQVtc9wV/jfKI0g+OUq4jBqOtAf4bQ==", + "integrity": "sha512-Zd16+VCs3dpwRQ642STeuQcXiGZq8iImSuPGQHniP0iEKsJoKWGSK95UoB2XElbJu/Hc22wA1sK5wUJULJpTiQ==", "dependencies": { "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", @@ -1038,9 +1060,9 @@ } }, "node_modules/@types/lodash": { - "version": "4.14.182", - "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.182.tgz", - "integrity": "sha512-/THyiqyQAP9AfARo4pF+aCGcyiQ94tX/Is2I7HofNRqoYLgN1PBoOWu2/zTA5zMxzP5EFutMtWtGAFRKUe961Q==" + "version": "4.14.183", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.183.tgz", + "integrity": "sha512-UXavyuxzXKMqJPEpFPri6Ku5F9af6ZJXUneHhvQJxavrEjuHkFp2YnDWHcxJiG7hk8ZkWqjcyNeW1s/smZv5cw==" }, "node_modules/@types/minimatch": { "version": "3.0.5", @@ -1116,14 +1138,14 @@ } }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.33.0.tgz", - "integrity": "sha512-jHvZNSW2WZ31OPJ3enhLrEKvAZNyAFWZ6rx9tUwaessTc4sx9KmgMNhVcqVAl1ETnT5rU5fpXTLmY9YvC1DCNg==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.33.1.tgz", + "integrity": "sha512-S1iZIxrTvKkU3+m63YUOxYPKaP+yWDQrdhxTglVDVEVBf+aCSw85+BmJnyUaQQsk5TXFG/LpBu9fa+LrAQ91fQ==", "peer": true, "dependencies": { - "@typescript-eslint/scope-manager": "5.33.0", - "@typescript-eslint/type-utils": "5.33.0", - "@typescript-eslint/utils": "5.33.0", + "@typescript-eslint/scope-manager": "5.33.1", + "@typescript-eslint/type-utils": "5.33.1", + "@typescript-eslint/utils": "5.33.1", "debug": "^4.3.4", "functional-red-black-tree": "^1.0.1", "ignore": "^5.2.0", @@ -1149,14 +1171,14 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.33.0.tgz", - "integrity": "sha512-cgM5cJrWmrDV2KpvlcSkelTBASAs1mgqq+IUGKJvFxWrapHpaRy5EXPQz9YaKF3nZ8KY18ILTiVpUtbIac86/w==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.33.1.tgz", + "integrity": "sha512-IgLLtW7FOzoDlmaMoXdxG8HOCByTBXrB1V2ZQYSEV1ggMmJfAkMWTwUjjzagS6OkfpySyhKFkBw7A9jYmcHpZA==", "peer": true, "dependencies": { - "@typescript-eslint/scope-manager": "5.33.0", - "@typescript-eslint/types": "5.33.0", - "@typescript-eslint/typescript-estree": "5.33.0", + "@typescript-eslint/scope-manager": "5.33.1", + "@typescript-eslint/types": "5.33.1", + "@typescript-eslint/typescript-estree": "5.33.1", "debug": "^4.3.4" }, "engines": { @@ -1176,13 +1198,13 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.33.0.tgz", - "integrity": "sha512-/Jta8yMNpXYpRDl8EwF/M8It2A9sFJTubDo0ATZefGXmOqlaBffEw0ZbkbQ7TNDK6q55NPHFshGBPAZvZkE8Pw==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.33.1.tgz", + "integrity": "sha512-8ibcZSqy4c5m69QpzJn8XQq9NnqAToC8OdH/W6IXPXv83vRyEDPYLdjAlUx8h/rbusq6MkW4YdQzURGOqsn3CA==", "peer": true, "dependencies": { - "@typescript-eslint/types": "5.33.0", - "@typescript-eslint/visitor-keys": "5.33.0" + "@typescript-eslint/types": "5.33.1", + "@typescript-eslint/visitor-keys": "5.33.1" }, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" @@ -1193,12 +1215,12 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.33.0.tgz", - "integrity": "sha512-2zB8uEn7hEH2pBeyk3NpzX1p3lF9dKrEbnXq1F7YkpZ6hlyqb2yZujqgRGqXgRBTHWIUG3NGx/WeZk224UKlIA==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.33.1.tgz", + "integrity": "sha512-X3pGsJsD8OiqhNa5fim41YtlnyiWMF/eKsEZGsHID2HcDqeSC5yr/uLOeph8rNF2/utwuI0IQoAK3fpoxcLl2g==", "peer": true, "dependencies": { - "@typescript-eslint/utils": "5.33.0", + "@typescript-eslint/utils": "5.33.1", "debug": "^4.3.4", "tsutils": "^3.21.0" }, @@ -1219,9 +1241,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.33.0.tgz", - "integrity": "sha512-nIMt96JngB4MYFYXpZ/3ZNU4GWPNdBbcB5w2rDOCpXOVUkhtNlG2mmm8uXhubhidRZdwMaMBap7Uk8SZMU/ppw==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.33.1.tgz", + "integrity": "sha512-7K6MoQPQh6WVEkMrMW5QOA5FO+BOwzHSNd0j3+BlBwd6vtzfZceJ8xJ7Um2XDi/O3umS8/qDX6jdy2i7CijkwQ==", "peer": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" @@ -1232,13 +1254,13 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.33.0.tgz", - "integrity": "sha512-tqq3MRLlggkJKJUrzM6wltk8NckKyyorCSGMq4eVkyL5sDYzJJcMgZATqmF8fLdsWrW7OjjIZ1m9v81vKcaqwQ==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.33.1.tgz", + "integrity": "sha512-JOAzJ4pJ+tHzA2pgsWQi4804XisPHOtbvwUyqsuuq8+y5B5GMZs7lI1xDWs6V2d7gE/Ez5bTGojSK12+IIPtXA==", "peer": true, "dependencies": { - "@typescript-eslint/types": "5.33.0", - "@typescript-eslint/visitor-keys": "5.33.0", + "@typescript-eslint/types": "5.33.1", + "@typescript-eslint/visitor-keys": "5.33.1", "debug": "^4.3.4", "globby": "^11.1.0", "is-glob": "^4.0.3", @@ -1259,15 +1281,15 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.33.0.tgz", - "integrity": "sha512-JxOAnXt9oZjXLIiXb5ZIcZXiwVHCkqZgof0O8KPgz7C7y0HS42gi75PdPlqh1Tf109M0fyUw45Ao6JLo7S5AHw==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.33.1.tgz", + "integrity": "sha512-uphZjkMaZ4fE8CR4dU7BquOV6u0doeQAr8n6cQenl/poMaIyJtBu8eys5uk6u5HiDH01Mj5lzbJ5SfeDz7oqMQ==", "peer": true, "dependencies": { "@types/json-schema": "^7.0.9", - "@typescript-eslint/scope-manager": "5.33.0", - "@typescript-eslint/types": "5.33.0", - "@typescript-eslint/typescript-estree": "5.33.0", + "@typescript-eslint/scope-manager": "5.33.1", + "@typescript-eslint/types": "5.33.1", + "@typescript-eslint/typescript-estree": "5.33.1", "eslint-scope": "^5.1.1", "eslint-utils": "^3.0.0" }, @@ -1283,12 +1305,12 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.33.0.tgz", - "integrity": "sha512-/XsqCzD4t+Y9p5wd9HZiptuGKBlaZO5showwqODii5C0nZawxWLF+Q6k5wYHBrQv96h6GYKyqqMHCSTqta8Kiw==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.33.1.tgz", + "integrity": "sha512-nwIxOK8Z2MPWltLKMLOEZwmfBZReqUdbEoHQXeCpa+sRVARe5twpJGHCB4dk9903Yaf0nMAlGbQfaAH92F60eg==", "peer": true, "dependencies": { - "@typescript-eslint/types": "5.33.0", + "@typescript-eslint/types": "5.33.1", "eslint-visitor-keys": "^3.3.0" }, "engines": { @@ -1682,9 +1704,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001374", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001374.tgz", - "integrity": "sha512-mWvzatRx3w+j5wx/mpFN5v5twlPrabG8NqX2c6e45LCpymdoGqNvRkRutFUqpRTXKFQFNQJasvK0YT7suW6/Hw==", + "version": "1.0.30001378", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001378.tgz", + "integrity": "sha512-JVQnfoO7FK7WvU4ZkBRbPjaot4+YqxogSDosHv0Hv5mWpUESmN+UubMU6L/hGz8QlQ2aY5U0vR6MOs6j/CXpNA==", "funding": [ { "type": "opencollective", @@ -2052,9 +2074,9 @@ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" }, "node_modules/electron-to-chromium": { - "version": "1.4.213", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.213.tgz", - "integrity": "sha512-+3DbGHGOCHTVB/Ms63bGqbyC1b8y7Fk86+7ltssB8NQrZtSCvZG6eooSl9U2Q0yw++fL2DpHKOdTU0NVEkFObg==" + "version": "1.4.224", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.224.tgz", + "integrity": "sha512-dOujC5Yzj0nOVE23iD5HKqrRSDj2SD7RazpZS/b/WX85MtO6/LzKDF4TlYZTBteB+7fvSg5JpWh0sN7fImNF8w==" }, "node_modules/emojis-list": { "version": "3.0.0", @@ -2106,9 +2128,9 @@ } }, "node_modules/eslint": { - "version": "8.21.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.21.0.tgz", - "integrity": "sha512-/XJ1+Qurf1T9G2M5IHrsjp+xrGT73RZf23xA1z5wB1ZzzEAWSZKvRwhWxTFp1rvkvCfwcvAUNAP31bhKTTGfDA==", + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.22.0.tgz", + "integrity": "sha512-ci4t0sz6vSRKdmkOGmprBo6fmI4PrphDFMy5JEq/fNS0gQkJM3rLmrqcp8ipMcdobH3KtUP40KniAE9W19S4wA==", "peer": true, "dependencies": { "@eslint/eslintrc": "^1.3.0", @@ -4605,9 +4627,9 @@ } }, "node_modules/rollup": { - "version": "2.77.2", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.77.2.tgz", - "integrity": "sha512-m/4YzYgLcpMQbxX3NmAqDvwLATZzxt8bIegO78FZLl+lAgKJBd1DRAOeEiZcKOIOPjxE6ewHWHNgGEalFXuz1g==", + "version": "2.78.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.78.0.tgz", + "integrity": "sha512-4+YfbQC9QEVvKTanHhIAFVUFSRsezvQF8vFOJwtGfb9Bb+r014S+qryr9PSmw8x6sMnPkmFBGAvIFVQxvJxjtg==", "bin": { "rollup": "dist/bin/rollup" }, @@ -5607,9 +5629,9 @@ "peer": true }, "@microsoft/api-extractor": { - "version": "7.29.0", - "resolved": "https://registry.npmjs.org/@microsoft/api-extractor/-/api-extractor-7.29.0.tgz", - "integrity": "sha512-tGU5DiwQ7/gN9Chi7cuAdspTuVY8hNcq5hBtvwAvb1H85tbiIHuqgoneHI60rkqlud7szkHJLiCkv75kQ0JLjw==", + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@microsoft/api-extractor/-/api-extractor-7.29.2.tgz", + "integrity": "sha512-MwT/Xi1DperfrBO+SU3f/xKdyR6bMvk59/WN6w7g1rHmDBMegan3Ya6npMo+abJAgQOtp6uExY/elHXcYE/Ofw==", "requires": { "@microsoft/api-extractor-model": "7.23.0", "@microsoft/tsdoc": "0.14.1", @@ -5681,6 +5703,12 @@ "integrity": "sha512-4ALgho4uvEBMFu5jiN+bVzGMbpCGPrKjb47jus8T3zlBpi+k/swe6lKb5j6HGQ7EBSN7C41mLU02GMo9ZSgX3Q==", "requires": {} }, + "@nevware21/ts-utils": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@nevware21/ts-utils/-/ts-utils-0.4.2.tgz", + "integrity": "sha512-Yxk6QEVCo/0pjxK/vT/PqvTzXnxfXRvf0uE85+TdxAoYFzDFGhYRL4bwfwiXLg+2/2q20VeqsD4HFWO/Rf3u4g==", + "requires": {} + }, "@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -5771,10 +5799,11 @@ }, "@rush-temp/ai-test-framework": { "version": "file:projects\\ai-test-framework.tgz", - "integrity": "sha512-yjPY5CEUu3i2ksoKxuTL7H7IgVFUm0dZHkD4psM7fM9fBY7GWonKdwK0EBMjzhJg7DzKUwb9JSIyCArMPPYLgw==", + "integrity": "sha512-doBzGvzpTAICOB+Co9tTtCmLWQHi8WFlYkk6sjHjQYFQLWoD9i60TJnsvkduArcfy7A+/GODQMtuUr95TKa96g==", "requires": { "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -5793,12 +5822,13 @@ }, "@rush-temp/applicationinsights-analytics-js": { "version": "file:projects\\applicationinsights-analytics-js.tgz", - "integrity": "sha512-e+G6klxGEPEheslnNo9OI4lQ2XsUuhPcQU2EA14WArCCNpKAJl4IizSBOqBRGQsTfrbejhYQz/IHc2ISi1w3Rw==", + "integrity": "sha512-4ZG/Lpmj79vzNazdHUE9F+2rRASNtXqua0P9/XTMnuKWcpm23EE07WRXHXK6TcTjWAyDtMVp9k29q8Dhs7z1gA==", "requires": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -5818,12 +5848,13 @@ }, "@rush-temp/applicationinsights-channel-js": { "version": "file:projects\\applicationinsights-channel-js.tgz", - "integrity": "sha512-cD/vxlmvqByVryffR+1Oe55Aug15OjXog+hNxaBbeT+9CRmvrsWDBzHncglNv5AzhS9wIoRT20aPppDbYK+Jdw==", + "integrity": "sha512-6qlxhBlep8vKbE3d9FAVCSHMqisE1uGqmd9EbXDByMlDdG7rvttPb19CLdvpYla45yJDkV+ZkIyz4WuTn4VxsQ==", "requires": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -5841,11 +5872,12 @@ }, "@rush-temp/applicationinsights-chrome-debug-extension": { "version": "file:projects\\applicationinsights-chrome-debug-extension.tgz", - "integrity": "sha512-Qo/UzEbrM3wh0rJE4JCgV+SC9c7OvzRPSpXqekDj3a3XVd+LyHnFOJHdsbUWQYDz3tyWNhGDu6JCSKNZgPAzeA==", + "integrity": "sha512-hD7+Qbgzq0aXq63jQdhzcPWzM119klB1g6th90wUieq2FPT9DIVcTWvLdAwfOeOchCa8BuxNYZ7YD0CrPcHZ3A==", "requires": { "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -5873,12 +5905,13 @@ }, "@rush-temp/applicationinsights-clickanalytics-js": { "version": "file:projects\\applicationinsights-clickanalytics-js.tgz", - "integrity": "sha512-PKGsLGV7l758Aqu/wvumxNSIv8Ufsa0ZwAv9nrgZ6z0Mn2bJ51aEq3Zj9IjG/HgkkWISSqOpCgVD3impZAb9Ew==", + "integrity": "sha512-+HqAtLRk0o2WygoDHMMfLQa3667jT93gHOGMPJ2srTx/+r5MqE7WnzNTi+Yknfi3YLX90ieGdScKPsA70b80Mw==", "requires": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -5895,12 +5928,13 @@ }, "@rush-temp/applicationinsights-common": { "version": "file:projects\\applicationinsights-common.tgz", - "integrity": "sha512-4r7ARInSkJma/1h1AylJ3mEUo+SiAa5gI024vB0jtq+L1tNIlBA0pUgOBQ1dN8r+jcMKCehh33lerrfkiBVokg==", + "integrity": "sha512-l0TU23M8f1+chGFzKDTP6UmsH+KJVEF+plsSDjMzg/XB8wFuIc8h2gVFRjlDDkaS2p44TIR4TH3uty0nob50Hg==", "requires": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -5917,12 +5951,13 @@ }, "@rush-temp/applicationinsights-core-js": { "version": "file:projects\\applicationinsights-core-js.tgz", - "integrity": "sha512-SztEaTjL3N2Fd7vhsS+2H+xDY8sf58zNHxddDUZ5flTirdPMrsrZXm9YkNkRVsCRMl7f6BS4jh0Yi2Q5U2B9mA==", + "integrity": "sha512-UBhuXTCiGOYOQ7qjKT/lNVzb/O0A2CjYL1jZ5Nq88uQLLXlqjha+5KraHP+3LrQEISPZLjvXEvwUqfAMIi2t4Q==", "requires": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -5942,12 +5977,13 @@ }, "@rush-temp/applicationinsights-debugplugin-js": { "version": "file:projects\\applicationinsights-debugplugin-js.tgz", - "integrity": "sha512-1B0OdYdRnA38Irb/eHI/zn43tvJ/fdu3C6hWRdZHzYKkIxznR2UCtoUd4Soi+AcrYtEOOCxMw59gyuwx7CLXjQ==", + "integrity": "sha512-vbmtSvXaphFZvXleqnb7jKcfh6j3k5a1K2Nf9WI2KW2mQUPZHDnkmhtGZCpIGImE5w+j1SHam4qhv1yYAm77Nw==", "requires": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -5964,12 +6000,13 @@ }, "@rush-temp/applicationinsights-dependencies-js": { "version": "file:projects\\applicationinsights-dependencies-js.tgz", - "integrity": "sha512-lU58R0yLF8E+iRCBMc5ukK/d0G1Ppv8xscScpSFzW9iaq9nHnhPSbEqP2OZpj51xipkrkY4ZcssuSkj65dKkjg==", + "integrity": "sha512-YTcrHQjAb+mtmJqwdhImpAqloG0EQIHHeFZPhWghX3T7gXEB7dmwO3zkrEgtwFa9LGTBy7u71tO/KkThWN60sQ==", "requires": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -5996,12 +6033,13 @@ }, "@rush-temp/applicationinsights-perfmarkmeasure-js": { "version": "file:projects\\applicationinsights-perfmarkmeasure-js.tgz", - "integrity": "sha512-xgyX8+jt+V3QdwJdjkJSe/n3UVsxrWXDJszHIg849sm5iRR36AAdpeXWhNz5SPUDs41qwAooIuXLLdhDJE6rCQ==", + "integrity": "sha512-GfsHdlIEpK3hPMlZH/buFQa+TUQarzGd5buRR4LJoclMhOBYh4JtXWD29rJukS4/emzfGzaqKjN6F5tF+vnVMg==", "requires": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -6018,12 +6056,13 @@ }, "@rush-temp/applicationinsights-properties-js": { "version": "file:projects\\applicationinsights-properties-js.tgz", - "integrity": "sha512-CAYoZNh8Ptb6GpkKSdWSsaO1uuz5Rxrt2BuNft6lQAN2H84mVSjheseL5XUhjHkuMutBFS7VjmRcedLPkXyk/w==", + "integrity": "sha512-wzCBV7eGBbTaCxxBohPVtaXRf2YsMljnFSEqWxvbUh9JcrsrHGfmqRMOt+f+2rwreuFj4oock6g34n2J+zpANA==", "requires": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -6041,9 +6080,9 @@ "typescript": "^4.3.4" } }, - "@rush-temp/applicationinsights-rollup-es3": { - "version": "file:projects\\applicationinsights-rollup-es3.tgz", - "integrity": "sha512-+AxiDd0vi6uL1M2WHFO5NbfJnw1FnrcyxmosJsM5cYKm1pHRWwzZ9PEYJVsk1S6u8dFoIeHP2D/EUOmlyFCFsQ==", + "@rush-temp/applicationinsights-rollup-es5": { + "version": "file:projects\\applicationinsights-rollup-es5.tgz", + "integrity": "sha512-YHKm8PzgPPT18YRyhBsOEDqNV9KXJTh++RqbCY5vy9PVVPQoR9Zxv+oAy7paEx5WLGMKcQZpf2+nKuSQl5mzHA==", "requires": { "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", @@ -6082,7 +6121,7 @@ }, "@rush-temp/applicationinsights-shims": { "version": "file:projects\\applicationinsights-shims.tgz", - "integrity": "sha512-PqilXn6zDJYvEy4lW/egvZIS8XzY4/kLmXxMIBaOyK62aI1DFjPnsFiQ5qtNz8IJHCC68S2t+cqHgFL6Fvfqnw==", + "integrity": "sha512-5WZvcytfCP3WCp0Xk67itDYh2d+5Ecn1qYingby3i2vrXMEE1UeSYmHh5qCfr1NvoC6ZsEHWT7HbYIhEEZb8RA==", "requires": { "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", @@ -6099,12 +6138,13 @@ }, "@rush-temp/applicationinsights-web": { "version": "file:projects\\applicationinsights-web.tgz", - "integrity": "sha512-bugU7hij9rime4/A0uLAciSBFlqo7rihS/ah0vE6LS9oHo59PDkgiEYpeTSCwQ126ZuxVruiQYvYimtpMvaMbA==", + "integrity": "sha512-0xGuLIyex6oKs9qrzVpF/AGFgZNkMHQcRac2ZWdKcppWRZ9nUGKV6yyR6bEDaFIgWZ3/LmCYu3l7p+MtpbG4YQ==", "requires": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -6127,12 +6167,13 @@ }, "@rush-temp/applicationinsights-web-basic": { "version": "file:projects\\applicationinsights-web-basic.tgz", - "integrity": "sha512-mkYpKx1ZcYUcK4aZrMFPDmDsFKwoER7FkQCCSEJwC+lcbgr17luxoHBuwYjIoocJiyJq/pF4x4jiNYtVtrHEDA==", + "integrity": "sha512-wSNk4D25AzqkMQkju86LuywZarbeh4jA1/isbCHaKQsnl0dZ40WIn7QNGS75fbWdmExokEA74GeunHbQ1su4ZQ==", "requires": { "@microsoft/api-extractor": "^7.18.1", "@microsoft/dynamicproto-js": "^1.1.6", "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", + "@nevware21/ts-utils": "^0.4.1", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "@rollup/plugin-replace": "^2.3.3", @@ -6151,7 +6192,7 @@ }, "@rush-temp/applicationinsights-web-snippet": { "version": "file:projects\\applicationinsights-web-snippet.tgz", - "integrity": "sha512-kePeqqOP1DTkf9PwnjtqhkeFZFmwSCfPEYrdbUyKsHQugP2nQPa1YVsTWQVtc9wV/jfKI0g+OUq4jBqOtAf4bQ==", + "integrity": "sha512-Zd16+VCs3dpwRQ642STeuQcXiGZq8iImSuPGQHniP0iEKsJoKWGSK95UoB2XElbJu/Hc22wA1sK5wUJULJpTiQ==", "requires": { "@nevware21/grunt-eslint-ts": "^0.2.2", "@nevware21/grunt-ts-plugin": "^0.4.3", @@ -6351,9 +6392,9 @@ } }, "@types/lodash": { - "version": "4.14.182", - "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.182.tgz", - "integrity": "sha512-/THyiqyQAP9AfARo4pF+aCGcyiQ94tX/Is2I7HofNRqoYLgN1PBoOWu2/zTA5zMxzP5EFutMtWtGAFRKUe961Q==" + "version": "4.14.183", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.183.tgz", + "integrity": "sha512-UXavyuxzXKMqJPEpFPri6Ku5F9af6ZJXUneHhvQJxavrEjuHkFp2YnDWHcxJiG7hk8ZkWqjcyNeW1s/smZv5cw==" }, "@types/minimatch": { "version": "3.0.5", @@ -6429,14 +6470,14 @@ } }, "@typescript-eslint/eslint-plugin": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.33.0.tgz", - "integrity": "sha512-jHvZNSW2WZ31OPJ3enhLrEKvAZNyAFWZ6rx9tUwaessTc4sx9KmgMNhVcqVAl1ETnT5rU5fpXTLmY9YvC1DCNg==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.33.1.tgz", + "integrity": "sha512-S1iZIxrTvKkU3+m63YUOxYPKaP+yWDQrdhxTglVDVEVBf+aCSw85+BmJnyUaQQsk5TXFG/LpBu9fa+LrAQ91fQ==", "peer": true, "requires": { - "@typescript-eslint/scope-manager": "5.33.0", - "@typescript-eslint/type-utils": "5.33.0", - "@typescript-eslint/utils": "5.33.0", + "@typescript-eslint/scope-manager": "5.33.1", + "@typescript-eslint/type-utils": "5.33.1", + "@typescript-eslint/utils": "5.33.1", "debug": "^4.3.4", "functional-red-black-tree": "^1.0.1", "ignore": "^5.2.0", @@ -6446,52 +6487,52 @@ } }, "@typescript-eslint/parser": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.33.0.tgz", - "integrity": "sha512-cgM5cJrWmrDV2KpvlcSkelTBASAs1mgqq+IUGKJvFxWrapHpaRy5EXPQz9YaKF3nZ8KY18ILTiVpUtbIac86/w==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.33.1.tgz", + "integrity": "sha512-IgLLtW7FOzoDlmaMoXdxG8HOCByTBXrB1V2ZQYSEV1ggMmJfAkMWTwUjjzagS6OkfpySyhKFkBw7A9jYmcHpZA==", "peer": true, "requires": { - "@typescript-eslint/scope-manager": "5.33.0", - "@typescript-eslint/types": "5.33.0", - "@typescript-eslint/typescript-estree": "5.33.0", + "@typescript-eslint/scope-manager": "5.33.1", + "@typescript-eslint/types": "5.33.1", + "@typescript-eslint/typescript-estree": "5.33.1", "debug": "^4.3.4" } }, "@typescript-eslint/scope-manager": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.33.0.tgz", - "integrity": "sha512-/Jta8yMNpXYpRDl8EwF/M8It2A9sFJTubDo0ATZefGXmOqlaBffEw0ZbkbQ7TNDK6q55NPHFshGBPAZvZkE8Pw==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.33.1.tgz", + "integrity": "sha512-8ibcZSqy4c5m69QpzJn8XQq9NnqAToC8OdH/W6IXPXv83vRyEDPYLdjAlUx8h/rbusq6MkW4YdQzURGOqsn3CA==", "peer": true, "requires": { - "@typescript-eslint/types": "5.33.0", - "@typescript-eslint/visitor-keys": "5.33.0" + "@typescript-eslint/types": "5.33.1", + "@typescript-eslint/visitor-keys": "5.33.1" } }, "@typescript-eslint/type-utils": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.33.0.tgz", - "integrity": "sha512-2zB8uEn7hEH2pBeyk3NpzX1p3lF9dKrEbnXq1F7YkpZ6hlyqb2yZujqgRGqXgRBTHWIUG3NGx/WeZk224UKlIA==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.33.1.tgz", + "integrity": "sha512-X3pGsJsD8OiqhNa5fim41YtlnyiWMF/eKsEZGsHID2HcDqeSC5yr/uLOeph8rNF2/utwuI0IQoAK3fpoxcLl2g==", "peer": true, "requires": { - "@typescript-eslint/utils": "5.33.0", + "@typescript-eslint/utils": "5.33.1", "debug": "^4.3.4", "tsutils": "^3.21.0" } }, "@typescript-eslint/types": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.33.0.tgz", - "integrity": "sha512-nIMt96JngB4MYFYXpZ/3ZNU4GWPNdBbcB5w2rDOCpXOVUkhtNlG2mmm8uXhubhidRZdwMaMBap7Uk8SZMU/ppw==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.33.1.tgz", + "integrity": "sha512-7K6MoQPQh6WVEkMrMW5QOA5FO+BOwzHSNd0j3+BlBwd6vtzfZceJ8xJ7Um2XDi/O3umS8/qDX6jdy2i7CijkwQ==", "peer": true }, "@typescript-eslint/typescript-estree": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.33.0.tgz", - "integrity": "sha512-tqq3MRLlggkJKJUrzM6wltk8NckKyyorCSGMq4eVkyL5sDYzJJcMgZATqmF8fLdsWrW7OjjIZ1m9v81vKcaqwQ==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.33.1.tgz", + "integrity": "sha512-JOAzJ4pJ+tHzA2pgsWQi4804XisPHOtbvwUyqsuuq8+y5B5GMZs7lI1xDWs6V2d7gE/Ez5bTGojSK12+IIPtXA==", "peer": true, "requires": { - "@typescript-eslint/types": "5.33.0", - "@typescript-eslint/visitor-keys": "5.33.0", + "@typescript-eslint/types": "5.33.1", + "@typescript-eslint/visitor-keys": "5.33.1", "debug": "^4.3.4", "globby": "^11.1.0", "is-glob": "^4.0.3", @@ -6500,26 +6541,26 @@ } }, "@typescript-eslint/utils": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.33.0.tgz", - "integrity": "sha512-JxOAnXt9oZjXLIiXb5ZIcZXiwVHCkqZgof0O8KPgz7C7y0HS42gi75PdPlqh1Tf109M0fyUw45Ao6JLo7S5AHw==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.33.1.tgz", + "integrity": "sha512-uphZjkMaZ4fE8CR4dU7BquOV6u0doeQAr8n6cQenl/poMaIyJtBu8eys5uk6u5HiDH01Mj5lzbJ5SfeDz7oqMQ==", "peer": true, "requires": { "@types/json-schema": "^7.0.9", - "@typescript-eslint/scope-manager": "5.33.0", - "@typescript-eslint/types": "5.33.0", - "@typescript-eslint/typescript-estree": "5.33.0", + "@typescript-eslint/scope-manager": "5.33.1", + "@typescript-eslint/types": "5.33.1", + "@typescript-eslint/typescript-estree": "5.33.1", "eslint-scope": "^5.1.1", "eslint-utils": "^3.0.0" } }, "@typescript-eslint/visitor-keys": { - "version": "5.33.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.33.0.tgz", - "integrity": "sha512-/XsqCzD4t+Y9p5wd9HZiptuGKBlaZO5showwqODii5C0nZawxWLF+Q6k5wYHBrQv96h6GYKyqqMHCSTqta8Kiw==", + "version": "5.33.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.33.1.tgz", + "integrity": "sha512-nwIxOK8Z2MPWltLKMLOEZwmfBZReqUdbEoHQXeCpa+sRVARe5twpJGHCB4dk9903Yaf0nMAlGbQfaAH92F60eg==", "peer": true, "requires": { - "@typescript-eslint/types": "5.33.0", + "@typescript-eslint/types": "5.33.1", "eslint-visitor-keys": "^3.3.0" } }, @@ -6789,9 +6830,9 @@ "peer": true }, "caniuse-lite": { - "version": "1.0.30001374", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001374.tgz", - "integrity": "sha512-mWvzatRx3w+j5wx/mpFN5v5twlPrabG8NqX2c6e45LCpymdoGqNvRkRutFUqpRTXKFQFNQJasvK0YT7suW6/Hw==" + "version": "1.0.30001378", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001378.tgz", + "integrity": "sha512-JVQnfoO7FK7WvU4ZkBRbPjaot4+YqxogSDosHv0Hv5mWpUESmN+UubMU6L/hGz8QlQ2aY5U0vR6MOs6j/CXpNA==" }, "chalk": { "version": "4.1.2", @@ -7060,9 +7101,9 @@ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" }, "electron-to-chromium": { - "version": "1.4.213", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.213.tgz", - "integrity": "sha512-+3DbGHGOCHTVB/Ms63bGqbyC1b8y7Fk86+7ltssB8NQrZtSCvZG6eooSl9U2Q0yw++fL2DpHKOdTU0NVEkFObg==" + "version": "1.4.224", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.224.tgz", + "integrity": "sha512-dOujC5Yzj0nOVE23iD5HKqrRSDj2SD7RazpZS/b/WX85MtO6/LzKDF4TlYZTBteB+7fvSg5JpWh0sN7fImNF8w==" }, "emojis-list": { "version": "3.0.0", @@ -7099,9 +7140,9 @@ "peer": true }, "eslint": { - "version": "8.21.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.21.0.tgz", - "integrity": "sha512-/XJ1+Qurf1T9G2M5IHrsjp+xrGT73RZf23xA1z5wB1ZzzEAWSZKvRwhWxTFp1rvkvCfwcvAUNAP31bhKTTGfDA==", + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.22.0.tgz", + "integrity": "sha512-ci4t0sz6vSRKdmkOGmprBo6fmI4PrphDFMy5JEq/fNS0gQkJM3rLmrqcp8ipMcdobH3KtUP40KniAE9W19S4wA==", "peer": true, "requires": { "@eslint/eslintrc": "^1.3.0", @@ -9001,9 +9042,9 @@ } }, "rollup": { - "version": "2.77.2", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.77.2.tgz", - "integrity": "sha512-m/4YzYgLcpMQbxX3NmAqDvwLATZzxt8bIegO78FZLl+lAgKJBd1DRAOeEiZcKOIOPjxE6ewHWHNgGEalFXuz1g==", + "version": "2.78.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.78.0.tgz", + "integrity": "sha512-4+YfbQC9QEVvKTanHhIAFVUFSRsezvQF8vFOJwtGfb9Bb+r014S+qryr9PSmw8x6sMnPkmFBGAvIFVQxvJxjtg==", "requires": { "fsevents": "~2.3.2" } diff --git a/extensions/applicationinsights-analytics-js/Tests/Unit/src/AnalyticsPlugin.tests.ts b/extensions/applicationinsights-analytics-js/Tests/Unit/src/AnalyticsPlugin.tests.ts index 7d75c8be..eead5d61 100644 --- a/extensions/applicationinsights-analytics-js/Tests/Unit/src/AnalyticsPlugin.tests.ts +++ b/extensions/applicationinsights-analytics-js/Tests/Unit/src/AnalyticsPlugin.tests.ts @@ -5,9 +5,9 @@ import { import { SinonStub, SinonSpy } from 'sinon'; import { Exception, SeverityLevel, Event, Trace, PageViewPerformance, IConfig, IExceptionInternal, - AnalyticsPluginIdentifier, Util, IAppInsights, Metric, PageView, RemoteDependencyData + AnalyticsPluginIdentifier, IAppInsights, Metric, PageView, RemoteDependencyData, utlCanUseLocalStorage, createDomEvent } from "@microsoft/applicationinsights-common"; -import { ITelemetryItem, AppInsightsCore, IPlugin, IConfiguration, IAppInsightsCore, setEnableEnvMocks, getLocation, dumpObj, __getRegisteredEvents } from "@microsoft/applicationinsights-core-js"; +import { ITelemetryItem, AppInsightsCore, IPlugin, IConfiguration, IAppInsightsCore, setEnableEnvMocks, getLocation, dumpObj, __getRegisteredEvents, createCookieMgr } from "@microsoft/applicationinsights-core-js"; import { Sender } from "@microsoft/applicationinsights-channel-js" import { PropertiesPlugin } from "@microsoft/applicationinsights-properties-js"; import { AnalyticsPlugin } from "../../../src/JavaScriptSDK/AnalyticsPlugin"; @@ -27,9 +27,10 @@ export class AnalyticsPluginTests extends AITestClass { private trackSpy:SinonSpy; private throwInternalSpy:SinonSpy; private exceptionHelper: any = new ExceptionHelper(); + private cookieMgr = createCookieMgr(); - constructor(name?: string, emulateEs3?: boolean) { - super(name, emulateEs3); + constructor(name?: string, emulateIe?: boolean) { + super(name, emulateIe); this.assertNoEvents = true; this.assertNoHooks = true; } @@ -38,18 +39,18 @@ export class AnalyticsPluginTests extends AITestClass { this._onerror = window.onerror; setEnableEnvMocks(false); super.testInitialize(); - Util.setCookie(undefined, 'ai_session', ""); - Util.setCookie(undefined, 'ai_user', ""); - if (Util.canUseLocalStorage()) { + this.cookieMgr.set('ai_session', ""); + this.cookieMgr.set('ai_user', ""); + if (utlCanUseLocalStorage()) { window.localStorage.clear(); } } public testCleanup() { super.testCleanup(); - Util.setCookie(undefined, 'ai_session', ""); - Util.setCookie(undefined, 'ai_user', ""); - if (Util.canUseLocalStorage()) { + this.cookieMgr.set('ai_session', ""); + this.cookieMgr.set('ai_user', ""); + if (utlCanUseLocalStorage()) { window.localStorage.clear(); } window.onerror = this._onerror; @@ -139,11 +140,11 @@ export class AnalyticsPluginTests extends AITestClass { Assert.equal(2, registeredEvents.length, "Two Events should be registered"); this.setLocationHref("secondUri"); - window.dispatchEvent(Util.createDomEvent('locationchange')); + window.dispatchEvent(createDomEvent('locationchange')); this.clock.tick(500); this.setLocationHref("thirdUri"); - window.dispatchEvent(Util.createDomEvent('locationchange')); + window.dispatchEvent(createDomEvent('locationchange')); this.clock.tick(500); // Assert @@ -190,11 +191,11 @@ export class AnalyticsPluginTests extends AITestClass { instrumentationKey: '', enableAutoRouteTracking: true } as IConfig & IConfiguration, [appInsights, channel, properties]); - window.dispatchEvent(Util.createDomEvent('locationchange')); + window.dispatchEvent(createDomEvent('locationchange')); this.clock.tick(200); // set up second dispatch - window.dispatchEvent(Util.createDomEvent('locationchange')); + window.dispatchEvent(createDomEvent('locationchange')); this.clock.tick(500); @@ -236,7 +237,7 @@ export class AnalyticsPluginTests extends AITestClass { instrumentationKey: '', enableAutoRouteTracking: true } as IConfig & IConfiguration, [appInsights, channel]); - window.dispatchEvent(Util.createDomEvent('locationchange')); + window.dispatchEvent(createDomEvent('locationchange')); // Assert Assert.ok(true, 'App does not crash when history object is incomplete'); diff --git a/extensions/applicationinsights-analytics-js/Tests/Unit/src/TelemetryItemCreator.tests.ts b/extensions/applicationinsights-analytics-js/Tests/Unit/src/TelemetryItemCreator.tests.ts index 510ac2d3..637ace41 100644 --- a/extensions/applicationinsights-analytics-js/Tests/Unit/src/TelemetryItemCreator.tests.ts +++ b/extensions/applicationinsights-analytics-js/Tests/Unit/src/TelemetryItemCreator.tests.ts @@ -26,8 +26,8 @@ export class TelemetryItemCreatorTests extends AITestClass { private _core: IAppInsightsCore; private _appInsights: AnalyticsPlugin; - constructor(name?: string, emulateEs3?: boolean) { - super(name, emulateEs3); + constructor(name?: string, emulateIe?: boolean) { + super(name, emulateIe); this.assertNoEvents = true; this.assertNoHooks = true; } diff --git a/extensions/applicationinsights-analytics-js/package.json b/extensions/applicationinsights-analytics-js/package.json index aa83340d..363c4e20 100644 --- a/extensions/applicationinsights-analytics-js/package.json +++ b/extensions/applicationinsights-analytics-js/package.json @@ -28,7 +28,7 @@ "devDependencies": { "@microsoft/ai-test-framework": "0.0.1", "@microsoft/applicationinsights-rollup-plugin-uglify3-js": "1.0.0", - "@microsoft/applicationinsights-rollup-es3": "1.1.3", + "@microsoft/applicationinsights-rollup-es5": "1.0.0", "@microsoft/applicationinsights-properties-js": "2.8.6", "@microsoft/applicationinsights-channel-js": "2.8.6", "@microsoft/api-extractor": "^7.18.1", @@ -57,7 +57,8 @@ "@microsoft/dynamicproto-js": "^1.1.6", "@microsoft/applicationinsights-shims": "2.0.1", "@microsoft/applicationinsights-core-js": "2.8.6", - "@microsoft/applicationinsights-common": "2.8.6" + "@microsoft/applicationinsights-common": "2.8.6", + "@nevware21/ts-utils": "^0.4.1" }, "license": "MIT" } diff --git a/extensions/applicationinsights-analytics-js/rollup.config.js b/extensions/applicationinsights-analytics-js/rollup.config.js index 77268d7c..c65a8cb4 100644 --- a/extensions/applicationinsights-analytics-js/rollup.config.js +++ b/extensions/applicationinsights-analytics-js/rollup.config.js @@ -3,7 +3,7 @@ import { uglify } from "@microsoft/applicationinsights-rollup-plugin-uglify3-js" import replace from "@rollup/plugin-replace"; import cleanup from "rollup-plugin-cleanup"; import dynamicRemove from "@microsoft/dynamicproto-js/tools/rollup/node/removedynamic"; -import { es3Poly, es3Check, importCheck } from "@microsoft/applicationinsights-rollup-es3"; +import { es5Poly, es5Check, importCheck } from "@microsoft/applicationinsights-rollup-es5"; import { updateDistEsmFiles } from "../../tools/updateDistEsm/updateDistEsm"; const version = require("./package.json").version; @@ -55,8 +55,8 @@ const browserRollupConfigFactory = isProduction => { preferBuiltins: false }), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; @@ -106,8 +106,8 @@ const nodeUmdRollupConfigFactory = (isProduction) => { importCheck({ exclude: [ "applicationinsights-analytics-js" ] }), nodeResolve(), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; diff --git a/extensions/applicationinsights-analytics-js/tsconfig.json b/extensions/applicationinsights-analytics-js/tsconfig.json index b5683862..3a367aca 100644 --- a/extensions/applicationinsights-analytics-js/tsconfig.json +++ b/extensions/applicationinsights-analytics-js/tsconfig.json @@ -5,7 +5,7 @@ "noImplicitAny": true, "module": "es6", "moduleResolution": "Node", - "target": "es3", + "target": "es5", "alwaysStrict": true, "suppressImplicitAnyIndexErrors": true, "allowSyntheticDefaultImports": true, diff --git a/extensions/applicationinsights-clickanalytics-js/Tests/Unit/src/ClickEventTest.ts b/extensions/applicationinsights-clickanalytics-js/Tests/Unit/src/ClickEventTest.ts index 92b840fe..335ec176 100644 --- a/extensions/applicationinsights-clickanalytics-js/Tests/Unit/src/ClickEventTest.ts +++ b/extensions/applicationinsights-clickanalytics-js/Tests/Unit/src/ClickEventTest.ts @@ -3,7 +3,7 @@ */ import { Assert, AITestClass } from "@microsoft/ai-test-framework"; - import { Util, IConfig } from "@microsoft/applicationinsights-common"; + import { IConfig, utlCanUseLocalStorage } from "@microsoft/applicationinsights-common"; import { ITelemetryItem, AppInsightsCore, IPlugin, IConfiguration, DiagnosticLogger} from '@microsoft/applicationinsights-core-js'; import { ClickAnalyticsPlugin, BehaviorMapValidator, BehaviorValueValidator, BehaviorEnumValidator } from '../../../src/ClickAnalyticsPlugin'; import { PageAction } from "../../../src/events/PageAction"; @@ -17,13 +17,13 @@ import { sanitizeUrl } from "../../../src/DataCollector"; export class ClickEventTest extends AITestClass { public testInitialize() { - if (Util.canUseLocalStorage()) { + if (utlCanUseLocalStorage()) { window.localStorage.clear(); } } public testCleanup() { - if (Util.canUseLocalStorage()) { + if (utlCanUseLocalStorage()) { window.localStorage.clear(); } } diff --git a/extensions/applicationinsights-clickanalytics-js/package.json b/extensions/applicationinsights-clickanalytics-js/package.json index b62d5eff..7533742f 100644 --- a/extensions/applicationinsights-clickanalytics-js/package.json +++ b/extensions/applicationinsights-clickanalytics-js/package.json @@ -24,7 +24,7 @@ "devDependencies": { "@microsoft/ai-test-framework": "0.0.1", "@microsoft/applicationinsights-rollup-plugin-uglify3-js": "1.0.0", - "@microsoft/applicationinsights-rollup-es3": "1.1.3", + "@microsoft/applicationinsights-rollup-es5": "1.0.0", "@microsoft/api-extractor": "^7.18.1", "typescript": "^4.3.4", "tslib": "^2.0.0", @@ -49,7 +49,8 @@ "@microsoft/applicationinsights-shims": "2.0.1", "@microsoft/applicationinsights-core-js": "2.8.6", "@microsoft/applicationinsights-common": "2.8.6", - "@microsoft/applicationinsights-properties-js": "2.8.6" + "@microsoft/applicationinsights-properties-js": "2.8.6", + "@nevware21/ts-utils": "^0.4.1" }, "repository": { "type": "git", diff --git a/extensions/applicationinsights-clickanalytics-js/rollup.config.js b/extensions/applicationinsights-clickanalytics-js/rollup.config.js index 4c80f3e3..f7d0ff5d 100644 --- a/extensions/applicationinsights-clickanalytics-js/rollup.config.js +++ b/extensions/applicationinsights-clickanalytics-js/rollup.config.js @@ -3,7 +3,7 @@ import { uglify } from "@microsoft/applicationinsights-rollup-plugin-uglify3-js" import replace from "@rollup/plugin-replace"; import cleanup from "rollup-plugin-cleanup"; import dynamicRemove from "@microsoft/dynamicproto-js/tools/rollup/node/removedynamic"; -import { es3Poly, es3Check, importCheck } from "@microsoft/applicationinsights-rollup-es3"; +import { es5Poly, es5Check, importCheck } from "@microsoft/applicationinsights-rollup-es5"; import { updateDistEsmFiles } from "../../tools/updateDistEsm/updateDistEsm"; const version = require("./package.json").version; @@ -61,8 +61,8 @@ const browserRollupConfigFactory = (isProduction, libVersion, format = 'umd', po preferBuiltins: false }), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; @@ -112,8 +112,8 @@ const nodeUmdRollupConfigFactory = (isProduction) => { importCheck({ exclude: [ "applicationinsights-clickanalytics-js" ] }), nodeResolve(), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; diff --git a/extensions/applicationinsights-clickanalytics-js/tsconfig.json b/extensions/applicationinsights-clickanalytics-js/tsconfig.json index 1096ccfb..397b615d 100644 --- a/extensions/applicationinsights-clickanalytics-js/tsconfig.json +++ b/extensions/applicationinsights-clickanalytics-js/tsconfig.json @@ -5,7 +5,7 @@ "noImplicitAny": true, "module": "es6", "moduleResolution": "Node", - "target": "es3", + "target": "es5", "alwaysStrict": true, "suppressImplicitAnyIndexErrors": true, "allowSyntheticDefaultImports": true, diff --git a/extensions/applicationinsights-debugplugin-js/package.json b/extensions/applicationinsights-debugplugin-js/package.json index 59fedfc0..f4a2e69b 100644 --- a/extensions/applicationinsights-debugplugin-js/package.json +++ b/extensions/applicationinsights-debugplugin-js/package.json @@ -26,7 +26,7 @@ }, "devDependencies": { "@microsoft/applicationinsights-rollup-plugin-uglify3-js": "1.0.0", - "@microsoft/applicationinsights-rollup-es3": "1.1.3", + "@microsoft/applicationinsights-rollup-es5": "1.0.0", "@microsoft/api-extractor": "^7.18.1", "typescript": "^4.3.4", "tslib": "^2.0.0", @@ -50,7 +50,8 @@ "@microsoft/dynamicproto-js": "^1.1.6", "@microsoft/applicationinsights-common": "2.8.6", "@microsoft/applicationinsights-core-js": "2.8.6", - "@microsoft/applicationinsights-shims": "2.0.1" + "@microsoft/applicationinsights-shims": "2.0.1", + "@nevware21/ts-utils": "^0.4.1" }, "license": "MIT" } diff --git a/extensions/applicationinsights-debugplugin-js/rollup.config.js b/extensions/applicationinsights-debugplugin-js/rollup.config.js index 0b9b7dcb..910adaaf 100644 --- a/extensions/applicationinsights-debugplugin-js/rollup.config.js +++ b/extensions/applicationinsights-debugplugin-js/rollup.config.js @@ -2,7 +2,7 @@ import nodeResolve from "@rollup/plugin-node-resolve"; import { uglify } from "@microsoft/applicationinsights-rollup-plugin-uglify3-js"; import replace from "@rollup/plugin-replace"; import cleanup from "rollup-plugin-cleanup"; -import { es3Poly, es3Check, importCheck } from "@microsoft/applicationinsights-rollup-es3"; +import { es5Poly, es5Check, importCheck } from "@microsoft/applicationinsights-rollup-es5"; import dynamicRemove from "@microsoft/dynamicproto-js/tools/rollup/node/removedynamic"; import { updateDistEsmFiles } from "../../tools/updateDistEsm/updateDistEsm"; @@ -61,8 +61,8 @@ const browserRollupConfigFactory = (isProduction, libVersion, format = 'umd', po preferBuiltins: false }), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; @@ -112,8 +112,8 @@ const nodeUmdRollupConfigFactory = (isProduction) => { importCheck({ exclude: [ "applicationinsights-debugplugin-js" ] }), nodeResolve(), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; diff --git a/extensions/applicationinsights-debugplugin-js/src/components/LogEntry.ts b/extensions/applicationinsights-debugplugin-js/src/components/LogEntry.ts index eb154db6..2d8a77e2 100644 --- a/extensions/applicationinsights-debugplugin-js/src/components/LogEntry.ts +++ b/extensions/applicationinsights-debugplugin-js/src/components/LogEntry.ts @@ -1,5 +1,4 @@ -import { Util } from "@microsoft/applicationinsights-common"; -import { isBoolean, isNumber, isObject, isString, objToString } from "@microsoft/applicationinsights-core-js"; +import { isArray, isBoolean, isError, isNumber, isObject, isString, objToString } from "@microsoft/applicationinsights-core-js"; import { MAX_DEPTH, formatLogElements, getTargetKeys, getTargetName, makeRegex, toggleClassName, traverseAndReplace } from "./helpers"; export class LogEntry { @@ -29,13 +28,13 @@ export class LogEntry { function _testObj(rg: RegExp, value: any, excludedKeys: string[], includeFunctions: boolean): boolean { if (value !== null && value !== undefined && value !== "") { - if (Util.isArray(value)) { + if (isArray(value)) { for (let lp = 0; lp < value.length; lp++) { if (_testObj(rg, value[lp], excludedKeys, includeFunctions)) { return true; } } - } else if (isObject(value) || Util.isError(value)) { + } else if (isObject(value) || isError(value)) { let keys = getTargetKeys(value, excludedKeys, includeFunctions); for (let lp = 0; lp < keys.length; lp++) { let key = keys[lp]; diff --git a/extensions/applicationinsights-debugplugin-js/src/components/helpers.ts b/extensions/applicationinsights-debugplugin-js/src/components/helpers.ts index e641c07b..bda2b36c 100644 --- a/extensions/applicationinsights-debugplugin-js/src/components/helpers.ts +++ b/extensions/applicationinsights-debugplugin-js/src/components/helpers.ts @@ -1,9 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -import { Util } from "@microsoft/applicationinsights-common"; import { - arrForEach, arrIndexOf, hasOwnProperty, isFunction, isObject, isString, isSymbol, objKeys + arrForEach, arrIndexOf, getIEVersion, hasOwnProperty, isArray, isError, isFunction, isObject, isString, isSymbol, objKeys } from "@microsoft/applicationinsights-core-js"; import { strShimPrototype } from "@microsoft/applicationinsights-shims"; @@ -227,7 +226,7 @@ function _toString(value: any) { export function getTargetKeys(target: any, excludedKeys: string[], includeFunctions: boolean) { let keys: string[] = objKeys(target); - if (!Util.isArray(target)) { + if (!isArray(target)) { try { if (Object[strGetOwnPropertyNames]) { // We need to use this for built in objects such as Error which don't return their values via objKeys because they are not enumerable for example @@ -273,8 +272,8 @@ export function formatLogElements(target: Object, tmLabel: string, key: string, thingsReferenced = []; } - let isObj = isObject(target) || Util.isError(target); - let isErr = target["baseType"] === "ExceptionData" || Util.isError(target); + let isObj = isObject(target) || isError(target); + let isErr = target["baseType"] === "ExceptionData" || isError(target); const children: HTMLElement[] = []; @@ -332,7 +331,7 @@ export function formatLogElements(target: Object, tmLabel: string, key: string, builder.className = "empty"; builder.innerText = ``; children.push(builder); - } else if (targetValue !== null && (isObject(targetValue) || Util.isError(targetValue))) { + } else if (targetValue !== null && (isObject(targetValue) || isError(targetValue))) { thingsReferenced.push(target); let formatted = formatLogElements(targetValue, null, key, level + 1, textFilter, excludeKeys, thingsReferenced, includeFunctions); thingsReferenced.pop(); @@ -393,7 +392,7 @@ export function formatLogElements(target: Object, tmLabel: string, key: string, let currentLine = document.createElement("span"); if (isObj || children.length) { innerText = `${key ? key : "obj"}: `; - if (Util.isArray(target)) { + if (isArray(target)) { innerText += `[${getTargetKeys(target, excludeKeys, includeFunctions).length}]`; } else { let targetName = getTargetName(target); @@ -437,7 +436,7 @@ export function formatLogElements(target: Object, tmLabel: string, key: string, } const openHandler = (evt: Event, forceState?: boolean) => { evt.stopPropagation(); - if (Util.getIEVersion()) { + if (getIEVersion()) { focusHandler(evt, target, level, excludeKeys, includeFunctions); } if (forceState !== undefined && openState === forceState) { diff --git a/extensions/applicationinsights-debugplugin-js/src/components/styleNodeSrc.ts b/extensions/applicationinsights-debugplugin-js/src/components/styleNodeSrc.ts index 95ba4775..04d92836 100644 --- a/extensions/applicationinsights-debugplugin-js/src/components/styleNodeSrc.ts +++ b/extensions/applicationinsights-debugplugin-js/src/components/styleNodeSrc.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. // @skip-file-minify -import { Util } from "@microsoft/applicationinsights-common"; +import { getIEVersion } from "@microsoft/applicationinsights-core-js"; const BG_INFO = "#F0F6FF", BG_ERROR = "#FEF0F1", @@ -15,7 +15,7 @@ const BG_INFO = "#F0F6FF", BORDER_GREY_160 = "1px solid #605E5C", BORDER_GREY_60 = "1px solid #B3B0AD"; -console.log(Util.getIEVersion()); +console.log(getIEVersion()); export const tempStyle = (prefix: string) => ` .${prefix}-dbg-lgr-dashboard { @@ -57,7 +57,7 @@ export const tempStyle = (prefix: string) => ` font-family: monospace; font-size: 16px; overflow-y: scroll; - overflow-x: ${(Util.getIEVersion()) ? "scroll" : "hidden"}; + overflow-x: ${(getIEVersion()) ? "scroll" : "hidden"}; border: ${BORDER_GREY_160}; border-radius: 2px; } @@ -66,7 +66,7 @@ export const tempStyle = (prefix: string) => ` outline: 2px solid black; } - ${Util.getIEVersion() && Util.getIEVersion() < 9 + ${getIEVersion() && getIEVersion() < 9 ? "" : `.${prefix}-dbg-lgr .tree-root div::before { content: ''; @@ -111,7 +111,7 @@ export const tempStyle = (prefix: string) => ` background-color: ${TEXT_MATCHED}; } - ${Util.getIEVersion() && Util.getIEVersion() < 9 + ${getIEVersion() && getIEVersion() < 9 ? "" : `.${prefix}-dbg-lgr .expandable.open::before { content: '[-] '; @@ -218,7 +218,7 @@ export const tempStyle = (prefix: string) => ` border-radius: 2px; } - ${Util.getIEVersion() && Util.getIEVersion() < 9 + ${getIEVersion() && getIEVersion() < 9 ? "" : `.${prefix}-dbg-lgr-dashboard .filterlist-input::after { content: ''; @@ -254,7 +254,7 @@ export const tempStyle = (prefix: string) => ` padding: 3px 8px; height: 32px; width: 100%; - ${(Util.getIEVersion()) ? "" : "box-sizing: border-box;"} + ${(getIEVersion()) ? "" : "box-sizing: border-box;"} } .${prefix}-dbg-lgr-dashboard .filterlist-toggle:focus { @@ -289,14 +289,14 @@ export const tempStyle = (prefix: string) => ` border-radius: 2px; vertical-align: middle; margin-right: 8px; - ${(Util.getIEVersion()) ? "" : "box-sizing: border-box;"} + ${(getIEVersion()) ? "" : "box-sizing: border-box;"} } .${prefix}-dbg-lgr-dashboard .checkbox.on { background-color: #0078D4; } - ${Util.getIEVersion() && Util.getIEVersion() < 9 + ${getIEVersion() && getIEVersion() < 9 ? "" : `.${prefix}-dbg-lgr-dashboard .checkbox.on::after { content: ''; @@ -317,7 +317,7 @@ export const tempStyle = (prefix: string) => ` border: ${BORDER_GREY_160}; } - ${Util.getIEVersion() && Util.getIEVersion() < 9 + ${getIEVersion() && getIEVersion() < 9 ? "" : `@media only screen and (max-width: 600px) { .${prefix}-dbg-lgr { @@ -332,7 +332,7 @@ export const tempStyle = (prefix: string) => ` export const permStyle = (prefix: string) => ` .${prefix}-debug-bin-container { position: fixed; - ${Util.getIEVersion() && Util.getIEVersion() < 9 + ${getIEVersion() && getIEVersion() < 9 ? `width: 100%; height: 100%; top: 0; @@ -362,7 +362,7 @@ export const permStyle = (prefix: string) => ` transition: 2s color linear; cursor: pointer; transition: .2s width ease-in-out, .2s height ease-in-out; - ${(Util.getIEVersion()) ? "" : "box-sizing: border-box;"} + ${(getIEVersion()) ? "" : "box-sizing: border-box;"} } .${prefix}-debug-bin-parent.active { @@ -411,7 +411,7 @@ export const permStyle = (prefix: string) => ` transition: 2s transform linear, 0s 2s font-weight linear; } - ${Util.getIEVersion() && Util.getIEVersion() < 9 + ${getIEVersion() && getIEVersion() < 9 ? "" : `.${prefix}-debug-bin-parent.notify::after { content: " (!)"; @@ -424,7 +424,7 @@ export const permStyle = (prefix: string) => ` transition: 0s transform linear, 0s font-weight linear; } - ${Util.getIEVersion() && Util.getIEVersion() < 9 + ${getIEVersion() && getIEVersion() < 9 ? "" : `.${prefix}-debug-bin-parent:focus > span::before, .${prefix}-debug-bin-parent:hover > span::before, diff --git a/extensions/applicationinsights-debugplugin-js/tsconfig.json b/extensions/applicationinsights-debugplugin-js/tsconfig.json index cfac50a7..03ce20f3 100644 --- a/extensions/applicationinsights-debugplugin-js/tsconfig.json +++ b/extensions/applicationinsights-debugplugin-js/tsconfig.json @@ -5,7 +5,7 @@ "noImplicitAny": true, "module": "es6", "moduleResolution": "Node", - "target": "es3", + "target": "es5", "alwaysStrict": true, "suppressImplicitAnyIndexErrors": true, "allowSyntheticDefaultImports": true, diff --git a/extensions/applicationinsights-dependencies-js/Tests/Unit/src/ajax.tests.ts b/extensions/applicationinsights-dependencies-js/Tests/Unit/src/ajax.tests.ts index 5697c50a..3a403231 100644 --- a/extensions/applicationinsights-dependencies-js/Tests/Unit/src/ajax.tests.ts +++ b/extensions/applicationinsights-dependencies-js/Tests/Unit/src/ajax.tests.ts @@ -50,8 +50,8 @@ export class AjaxTests extends AITestClass { private _ajax:AjaxMonitor = null; private _context:any = {}; - constructor(name?: string, emulateEs3?: boolean) { - super(name, emulateEs3); + constructor(name?: string, emulateIe?: boolean) { + super(name, emulateIe); this.assertNoEvents = true; this.assertNoHooks = true; } @@ -2152,8 +2152,8 @@ export class AjaxPerfTrackTests extends AITestClass { private _perfEntries: PerformanceEntry[]; private _context:any; - constructor(name?: string, emulateEs3?: boolean) { - super(name, emulateEs3); + constructor(name?: string, emulateIe?: boolean) { + super(name, emulateIe); this.assertNoEvents = true; this.assertNoHooks = true; this.useFakeServer = false; @@ -2744,8 +2744,8 @@ export class AjaxFrozenTests extends AITestClass { private _ajax:AjaxMonitor; private _context:any; - constructor(name?: string, emulateEs3?: boolean) { - super(name, emulateEs3); + constructor(name?: string, emulateIe?: boolean) { + super(name, emulateIe); this.assertNoEvents = true; this.assertNoHooks = true; diff --git a/extensions/applicationinsights-dependencies-js/package.json b/extensions/applicationinsights-dependencies-js/package.json index 6b3dd140..f08b9035 100644 --- a/extensions/applicationinsights-dependencies-js/package.json +++ b/extensions/applicationinsights-dependencies-js/package.json @@ -28,7 +28,7 @@ "devDependencies": { "@microsoft/ai-test-framework": "0.0.1", "@microsoft/applicationinsights-rollup-plugin-uglify3-js": "1.0.0", - "@microsoft/applicationinsights-rollup-es3": "1.1.3", + "@microsoft/applicationinsights-rollup-es5": "1.0.0", "@microsoft/api-extractor": "^7.18.1", "typescript": "^4.3.4", "tslib": "^2.0.0", @@ -54,7 +54,8 @@ "@microsoft/dynamicproto-js": "^1.1.6", "@microsoft/applicationinsights-shims": "2.0.1", "@microsoft/applicationinsights-core-js": "2.8.6", - "@microsoft/applicationinsights-common": "2.8.6" + "@microsoft/applicationinsights-common": "2.8.6", + "@nevware21/ts-utils": "^0.4.1" }, "license": "MIT" } diff --git a/extensions/applicationinsights-dependencies-js/rollup.config.js b/extensions/applicationinsights-dependencies-js/rollup.config.js index f1e17784..d011134d 100644 --- a/extensions/applicationinsights-dependencies-js/rollup.config.js +++ b/extensions/applicationinsights-dependencies-js/rollup.config.js @@ -3,7 +3,7 @@ import { uglify } from "@microsoft/applicationinsights-rollup-plugin-uglify3-js" import replace from "@rollup/plugin-replace"; import cleanup from "rollup-plugin-cleanup"; import dynamicRemove from "@microsoft/dynamicproto-js/tools/rollup/node/removedynamic"; -import { es3Poly, es3Check, importCheck } from "@microsoft/applicationinsights-rollup-es3"; +import { es5Poly, es5Check, importCheck } from "@microsoft/applicationinsights-rollup-es5"; import { updateDistEsmFiles } from "../../tools/updateDistEsm/updateDistEsm"; const version = require("./package.json").version; @@ -55,8 +55,8 @@ const browserRollupConfigFactory = isProduction => { preferBuiltins: false }), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; @@ -106,8 +106,8 @@ const nodeUmdRollupConfigFactory = (isProduction) => { importCheck({ exclude: [ "applicationinsights-dependencies-js" ] }), nodeResolve(), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; diff --git a/extensions/applicationinsights-dependencies-js/src/InternalConstants.ts b/extensions/applicationinsights-dependencies-js/src/InternalConstants.ts index b39667a6..8ab77843 100644 --- a/extensions/applicationinsights-dependencies-js/src/InternalConstants.ts +++ b/extensions/applicationinsights-dependencies-js/src/InternalConstants.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!! -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +// ################################################################################################################################################### +// Note: DON'T Export these const from the package as we are still targeting IE/ES5 this will export a mutable variables that someone could change ### +// ################################################################################################################################################### // Generally you should only put values that are used more than 2 times and then only if not already exposed as a constant (such as SdkCoreNames) // as when using "short" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value. diff --git a/extensions/applicationinsights-dependencies-js/src/ajax.ts b/extensions/applicationinsights-dependencies-js/src/ajax.ts index 9b5bdaf9..84f2d269 100644 --- a/extensions/applicationinsights-dependencies-js/src/ajax.ts +++ b/extensions/applicationinsights-dependencies-js/src/ajax.ts @@ -3,9 +3,10 @@ import dynamicProto from "@microsoft/dynamicproto-js"; import { - CorrelationIdHelper, DisabledPropertyName, IConfig, ICorrelationConfig, IDependencyTelemetry, IRequestContext, ITelemetryContext, - PropertiesPluginIdentifier, RemoteDependencyData, RequestHeaders, createDistributedTraceContextFromTrace, createTelemetryItem, - createTraceParent, dateTimeUtilsNow, eDistributedTracingModes, eRequestHeaders, formatTraceParent, isInternalApplicationInsightsEndpoint + DisabledPropertyName, IConfig, ICorrelationConfig, IDependencyTelemetry, IRequestContext, ITelemetryContext, PropertiesPluginIdentifier, + RemoteDependencyData, RequestHeaders, correlationIdCanIncludeCorrelationHeader, correlationIdGetCorrelationContext, + createDistributedTraceContextFromTrace, createTelemetryItem, createTraceParent, dateTimeUtilsNow, eDistributedTracingModes, + eRequestHeaders, formatTraceParent, isInternalApplicationInsightsEndpoint } from "@microsoft/applicationinsights-common"; import { BaseTelemetryPlugin, IAppInsightsCore, IConfiguration, ICustomProperties, IDistributedTraceContext, IInstrumentCallDetails, @@ -301,7 +302,7 @@ export class AjaxMonitor extends BaseTelemetryPlugin implements IDependenciesPlu _processDependencyListeners(_dependencyListeners, _self.core, ajaxData, xhr, input, init); if (input) { // Fetch - if (CorrelationIdHelper.canIncludeCorrelationHeader(_config, ajaxData.getAbsoluteUrl(), currentWindowHost)) { + if (correlationIdCanIncludeCorrelationHeader(_config, ajaxData.getAbsoluteUrl(), currentWindowHost)) { if (!init) { init = {}; } @@ -342,7 +343,7 @@ export class AjaxMonitor extends BaseTelemetryPlugin implements IDependenciesPlu return init; } else if (xhr) { // XHR - if (CorrelationIdHelper.canIncludeCorrelationHeader(_config, ajaxData.getAbsoluteUrl(), currentWindowHost)) { + if (correlationIdCanIncludeCorrelationHeader(_config, ajaxData.getAbsoluteUrl(), currentWindowHost)) { if (_isUsingAIHeaders) { const id = "|" + ajaxData.traceID + "." + ajaxData.spanID; xhr.setRequestHeader(RequestHeaders[eRequestHeaders.requestIdHeader], id); @@ -932,7 +933,7 @@ export class AjaxMonitor extends BaseTelemetryPlugin implements IDependenciesPlu const index = _indexOf(responseHeadersString.toLowerCase(), RequestHeaders[eRequestHeaders.requestContextHeaderLowerCase]); if (index !== -1) { const responseHeader = xhr.getResponseHeader(RequestHeaders[eRequestHeaders.requestContextHeader]); - return CorrelationIdHelper.getCorrelationContext(responseHeader); + return correlationIdGetCorrelationContext(responseHeader); } } } catch (e) { @@ -1142,7 +1143,7 @@ export class AjaxMonitor extends BaseTelemetryPlugin implements IDependenciesPlu if (response && response.headers) { try { const responseHeader: string = response.headers.get(RequestHeaders[eRequestHeaders.requestContextHeader]); - return CorrelationIdHelper.getCorrelationContext(responseHeader); + return correlationIdGetCorrelationContext(responseHeader); } catch (e) { _throwInternalWarning(_self, _eInternalMessageId.FailedMonitorAjaxGetCorrelationHeader, diff --git a/extensions/applicationinsights-dependencies-js/tsconfig.json b/extensions/applicationinsights-dependencies-js/tsconfig.json index b9e55252..701d6c01 100644 --- a/extensions/applicationinsights-dependencies-js/tsconfig.json +++ b/extensions/applicationinsights-dependencies-js/tsconfig.json @@ -5,7 +5,7 @@ "noImplicitAny": true, "module": "es6", "moduleResolution": "Node", - "target": "es3", + "target": "es5", "alwaysStrict": true, "suppressImplicitAnyIndexErrors": true, "allowSyntheticDefaultImports": true, diff --git a/extensions/applicationinsights-perfmarkmeasure-js/package.json b/extensions/applicationinsights-perfmarkmeasure-js/package.json index 410e2e8e..663160a1 100644 --- a/extensions/applicationinsights-perfmarkmeasure-js/package.json +++ b/extensions/applicationinsights-perfmarkmeasure-js/package.json @@ -28,7 +28,7 @@ "devDependencies": { "@microsoft/ai-test-framework": "0.0.1", "@microsoft/applicationinsights-rollup-plugin-uglify3-js": "1.0.0", - "@microsoft/applicationinsights-rollup-es3": "1.1.3", + "@microsoft/applicationinsights-rollup-es5": "1.0.0", "@microsoft/api-extractor": "^7.18.1", "typescript": "^4.3.4", "tslib": "^2.0.0", @@ -51,7 +51,8 @@ "dependencies": { "@microsoft/dynamicproto-js": "^1.1.6", "@microsoft/applicationinsights-shims": "2.0.1", - "@microsoft/applicationinsights-core-js": "2.8.6" + "@microsoft/applicationinsights-core-js": "2.8.6", + "@nevware21/ts-utils": "^0.4.1" }, "license": "MIT" } diff --git a/extensions/applicationinsights-perfmarkmeasure-js/rollup.config.js b/extensions/applicationinsights-perfmarkmeasure-js/rollup.config.js index eea397c1..89e2762f 100644 --- a/extensions/applicationinsights-perfmarkmeasure-js/rollup.config.js +++ b/extensions/applicationinsights-perfmarkmeasure-js/rollup.config.js @@ -3,7 +3,7 @@ import { uglify } from "@microsoft/applicationinsights-rollup-plugin-uglify3-js" import replace from "@rollup/plugin-replace"; import cleanup from "rollup-plugin-cleanup"; import dynamicRemove from "@microsoft/dynamicproto-js/tools/rollup/node/removedynamic"; -import { es3Poly, es3Check, importCheck } from "@microsoft/applicationinsights-rollup-es3"; +import { es5Poly, es5Check, importCheck } from "@microsoft/applicationinsights-rollup-es5"; import { updateDistEsmFiles } from "../../tools/updateDistEsm/updateDistEsm"; const version = require("./package.json").version; @@ -61,8 +61,8 @@ const browserRollupConfigFactory = (isProduction, libVersion, format = 'umd', po preferBuiltins: false }), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; @@ -112,8 +112,8 @@ const nodeUmdRollupConfigFactory = (isProduction) => { importCheck({ exclude: [ "applicationinsights-perfmarkmeasure-js" ] }), nodeResolve(), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; diff --git a/extensions/applicationinsights-perfmarkmeasure-js/tsconfig.json b/extensions/applicationinsights-perfmarkmeasure-js/tsconfig.json index 8f32dd75..af4a59ee 100644 --- a/extensions/applicationinsights-perfmarkmeasure-js/tsconfig.json +++ b/extensions/applicationinsights-perfmarkmeasure-js/tsconfig.json @@ -5,7 +5,7 @@ "noImplicitAny": true, "module": "es6", "moduleResolution": "Node", - "target": "es3", + "target": "es5", "alwaysStrict": true, "suppressImplicitAnyIndexErrors": true, "allowSyntheticDefaultImports": true, diff --git a/extensions/applicationinsights-properties-js/Tests/Unit/src/SessionManager.Tests.ts b/extensions/applicationinsights-properties-js/Tests/Unit/src/SessionManager.Tests.ts index 5ff2fb8e..9682b869 100644 --- a/extensions/applicationinsights-properties-js/Tests/Unit/src/SessionManager.Tests.ts +++ b/extensions/applicationinsights-properties-js/Tests/Unit/src/SessionManager.Tests.ts @@ -9,8 +9,8 @@ export class SessionManagerTests extends AITestClass { private core: AppInsightsCore; private _cookies: { [name: string ]: string } = {}; - constructor(emulateEs3: boolean) { - super("SessionManagerTests", emulateEs3); + constructor(emulateIe: boolean) { + super("SessionManagerTests", emulateIe); } public testInitialize() { diff --git a/extensions/applicationinsights-properties-js/Tests/Unit/src/TelemetryContext.Tests.ts b/extensions/applicationinsights-properties-js/Tests/Unit/src/TelemetryContext.Tests.ts index 24184d8c..8c812c37 100644 --- a/extensions/applicationinsights-properties-js/Tests/Unit/src/TelemetryContext.Tests.ts +++ b/extensions/applicationinsights-properties-js/Tests/Unit/src/TelemetryContext.Tests.ts @@ -8,8 +8,8 @@ export class TelemetryContextTests extends AITestClass { private core: AppInsightsCore; private _cookies: { [name: string ]: string } = {}; - constructor(emulateEs3?: boolean) { - super("TelemetryContextTests", emulateEs3); + constructor(emulateIe?: boolean) { + super("TelemetryContextTests", emulateIe); } public testInitialize() { diff --git a/extensions/applicationinsights-properties-js/package.json b/extensions/applicationinsights-properties-js/package.json index c1d049c1..40db3392 100644 --- a/extensions/applicationinsights-properties-js/package.json +++ b/extensions/applicationinsights-properties-js/package.json @@ -28,7 +28,7 @@ "devDependencies": { "@microsoft/ai-test-framework": "0.0.1", "@microsoft/applicationinsights-rollup-plugin-uglify3-js": "1.0.0", - "@microsoft/applicationinsights-rollup-es3": "1.1.3", + "@microsoft/applicationinsights-rollup-es5": "1.0.0", "@microsoft/api-extractor": "^7.18.1", "typescript": "^4.3.4", "tslib": "^2.0.0", @@ -55,7 +55,8 @@ "@microsoft/dynamicproto-js": "^1.1.6", "@microsoft/applicationinsights-shims": "2.0.1", "@microsoft/applicationinsights-core-js": "2.8.6", - "@microsoft/applicationinsights-common": "2.8.6" + "@microsoft/applicationinsights-common": "2.8.6", + "@nevware21/ts-utils": "^0.4.1" }, "license": "MIT" } diff --git a/extensions/applicationinsights-properties-js/rollup.config.js b/extensions/applicationinsights-properties-js/rollup.config.js index 7595aed3..5cbc1025 100644 --- a/extensions/applicationinsights-properties-js/rollup.config.js +++ b/extensions/applicationinsights-properties-js/rollup.config.js @@ -2,7 +2,7 @@ import nodeResolve from "@rollup/plugin-node-resolve"; import { uglify } from "@microsoft/applicationinsights-rollup-plugin-uglify3-js"; import replace from "@rollup/plugin-replace"; import cleanup from "rollup-plugin-cleanup"; -import { es3Poly, es3Check, importCheck } from "@microsoft/applicationinsights-rollup-es3"; +import { es5Poly, es5Check, importCheck } from "@microsoft/applicationinsights-rollup-es5"; import dynamicRemove from "@microsoft/dynamicproto-js/tools/rollup/node/removedynamic"; import { updateDistEsmFiles } from "../../tools/updateDistEsm/updateDistEsm"; @@ -55,8 +55,8 @@ const browserRollupConfigFactory = isProduction => { preferBuiltins: false }), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; @@ -106,8 +106,8 @@ const nodeUmdRollupConfigFactory = (isProduction) => { importCheck({ exclude: [ "applicationinsights-properties-js" ] }), nodeResolve(), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; diff --git a/extensions/applicationinsights-properties-js/src/Context/Internal.ts b/extensions/applicationinsights-properties-js/src/Context/Internal.ts index 1ee906c3..5236c350 100644 --- a/extensions/applicationinsights-properties-js/src/Context/Internal.ts +++ b/extensions/applicationinsights-properties-js/src/Context/Internal.ts @@ -4,7 +4,7 @@ import { IInternal } from "@microsoft/applicationinsights-common"; import { ITelemetryConfig } from "../Interfaces/ITelemetryConfig"; -const Version = "#version#"; +const Version = "2.8.5"; export class Internal implements IInternal { diff --git a/extensions/applicationinsights-properties-js/tsconfig.json b/extensions/applicationinsights-properties-js/tsconfig.json index e072c940..9a5e5ac3 100644 --- a/extensions/applicationinsights-properties-js/tsconfig.json +++ b/extensions/applicationinsights-properties-js/tsconfig.json @@ -5,7 +5,7 @@ "noImplicitAny": true, "module": "es6", "moduleResolution": "Node", - "target": "es3", + "target": "es5", "alwaysStrict": true, "suppressImplicitAnyIndexErrors": true, "allowSyntheticDefaultImports": true, diff --git a/gruntfile.js b/gruntfile.js index 492f3616..f94f6d1d 100644 --- a/gruntfile.js +++ b/gruntfile.js @@ -410,10 +410,10 @@ module.exports = function (grunt) { }, testHttp: false }, - "rollupes3": { + "rollupes5": { autoMinify: false, - path: "./tools/rollup-es3", - unitTestName: "es3rolluptests.js", + path: "./tools/rollup-es5", + unitTestName: "es5rolluptests.js", testHttp: false }, "shims": { @@ -613,7 +613,7 @@ module.exports = function (grunt) { grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-string-replace'); grunt.loadTasks('./tools/grunt-tasks'); - grunt.registerTask("default", ["ts:rollupuglify", "ts:rollupes3", "ts:rollupes3test", "qunit:rollupes3", "ts:shims", "ts:shimstest", "qunit:shims", "ts:default", "uglify:ai", "uglify:snippet"]); + grunt.registerTask("default", ["ts:rollupuglify", "ts:rollupes5", "ts:rollupes5test", "qunit:rollupes5", "ts:shims", "ts:shimstest", "qunit:shims", "ts:default", "uglify:ai", "uglify:snippet"]); grunt.registerTask("core", tsBuildActions("core")); grunt.registerTask("core-min", minTasks("core")); @@ -681,8 +681,8 @@ module.exports = function (grunt) { grunt.registerTask("aichannel-mintest", tsTestActions("aichannel", true)); grunt.registerTask("rollupuglify", tsBuildActions("rollupuglify")); - grunt.registerTask("rollupes3", tsBuildActions("rollupes3").concat(["ts:rollupes3-tests", "qunit:rollupes3"])); - grunt.registerTask("rollupes3test", [ "ts:rollupes3-tests", "qunit:rollupes3" ]); + grunt.registerTask("rollupes5", tsBuildActions("rollupes5").concat(["ts:rollupes5-tests", "qunit:rollupes5"])); + grunt.registerTask("rollupes5test", [ "ts:rollupes5-tests", "qunit:rollupes5" ]); grunt.registerTask("shims", tsBuildActions("shims").concat(["ts:shims-tests", "qunit:shims"])); grunt.registerTask("shimstest", ["ts:shims-tests", "qunit:shims"]); diff --git a/package.json b/package.json index c1b5d725..b0a0d6f3 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,7 @@ "mintest": "node common/scripts/install-run-rush.js mintest --verbose", "lint": "node common/scripts/install-run-rush.js lint --verbose", "perftest": "node common/scripts/install-run-rush.js perftest --verbose", - "rollupes3": "grunt rollupes3", + "rollupes5": "grunt rollupes5", "rupdate": "node common/scripts/install-run-rush.js update --recheck --purge --full", "serve": "grunt serve", "setVersion": "node ./tools/release-tools/setVersion.js", diff --git a/rush.json b/rush.json index cbf54800..fa5fc281 100644 --- a/rush.json +++ b/rush.json @@ -25,8 +25,8 @@ "shouldPublish": true }, { - "packageName": "@microsoft/applicationinsights-rollup-es3", - "projectFolder": "tools/rollup-es3", + "packageName": "@microsoft/applicationinsights-rollup-es5", + "projectFolder": "tools/rollup-es5", "shouldPublish": true }, { diff --git a/shared/AppInsightsCommon/README.md b/shared/AppInsightsCommon/README.md index f35822df..31e2c9cb 100644 --- a/shared/AppInsightsCommon/README.md +++ b/shared/AppInsightsCommon/README.md @@ -5,6 +5,13 @@ Common library for the Application Insights Javascript SDK +## Beta Release Breaking changes + +- Removed ES3 / IE8 Support +- Removed V1 API Backward Compatibility (Upgrading V1 -> V3) + +See [Breaking Changes](./BETA_BREAKING_CHANGES.md) + ## Build: ``` npm install -g grunt-cli diff --git a/shared/AppInsightsCommon/Tests/Unit/src/AppInsightsCommon.tests.ts b/shared/AppInsightsCommon/Tests/Unit/src/AppInsightsCommon.tests.ts index 2a1a9fbc..f497bb4f 100644 --- a/shared/AppInsightsCommon/Tests/Unit/src/AppInsightsCommon.tests.ts +++ b/shared/AppInsightsCommon/Tests/Unit/src/AppInsightsCommon.tests.ts @@ -1,10 +1,8 @@ +import { strRepeat } from "@nevware21/ts-utils"; import { Assert, AITestClass } from "@microsoft/ai-test-framework"; -import { - ITelemetryItem, AppInsightsCore, - IPlugin, IConfiguration, DiagnosticLogger -} from "@microsoft/applicationinsights-core-js"; +import { DiagnosticLogger } from "@microsoft/applicationinsights-core-js"; +import { dataSanitizeInput, dataSanitizeKey, dataSanitizeMessage, DataSanitizerValues, dataSanitizeString } from "../../../src/Telemetry/Common/DataSanitizer"; -import { DataSanitizer } from "../../../src/Telemetry/Common/DataSanitizer"; export class ApplicationInsightsTests extends AITestClass { logger = new DiagnosticLogger(); @@ -21,16 +19,16 @@ export class ApplicationInsightsTests extends AITestClass { name: 'DataSanitizerTests: messages are well processed.', test: () => { // const define - const MAX_MESSAGE_LENGTH = DataSanitizer.MAX_MESSAGE_LENGTH; + const MAX_MESSAGE_LENGTH = DataSanitizerValues.MAX_MESSAGE_LENGTH; // use cases const messageShort: String = "hi"; - const messageLong = new Array(MAX_MESSAGE_LENGTH + 1).join('abc'); + const messageLong = strRepeat("abc", MAX_MESSAGE_LENGTH + 1); // Assert - Assert.equal(messageShort.length, DataSanitizer.sanitizeMessage(this.logger, messageShort).length); - Assert.notEqual(messageLong.length, DataSanitizer.sanitizeMessage(this.logger, messageLong).length); - Assert.equal(MAX_MESSAGE_LENGTH, DataSanitizer.sanitizeMessage(this.logger, messageLong).length); + Assert.equal(messageShort.length, dataSanitizeMessage(this.logger, messageShort).length); + Assert.notEqual(messageLong.length, dataSanitizeMessage(this.logger, messageLong).length); + Assert.equal(MAX_MESSAGE_LENGTH, dataSanitizeMessage(this.logger, messageLong).length); } }); @@ -39,22 +37,22 @@ export class ApplicationInsightsTests extends AITestClass { test: () => { // const define const loggerStub = this.sandbox.stub(this.logger , "throwInternal"); - const MAX_MESSAGE_LENGTH = DataSanitizer.MAX_MESSAGE_LENGTH; + const MAX_MESSAGE_LENGTH = DataSanitizerValues.MAX_MESSAGE_LENGTH; // use cases const messageShort: String = "hi"; - const messageLong = new Array(MAX_MESSAGE_LENGTH + 2).join('a'); + const messageLong = strRepeat("a", MAX_MESSAGE_LENGTH + 2); // Act - DataSanitizer.sanitizeMessage(this.logger, messageShort); + dataSanitizeMessage(this.logger, messageShort); Assert.ok(loggerStub.notCalled); Assert.equal(0, loggerStub.callCount); - DataSanitizer.sanitizeMessage(this.logger, messageLong); + dataSanitizeMessage(this.logger, messageLong); Assert.ok(loggerStub.calledOnce); Assert.equal(1, loggerStub.callCount); - DataSanitizer.sanitizeMessage(this.logger, messageLong); + dataSanitizeMessage(this.logger, messageLong); Assert.ok(loggerStub.calledTwice); Assert.equal(2, loggerStub.callCount); @@ -65,22 +63,24 @@ export class ApplicationInsightsTests extends AITestClass { this.testCase({ name: 'DataSanitizerTests: messages are fully logged through console', test: () => { - const saniMsgSpy = this.sandbox.spy(DataSanitizer, "sanitizeMessage"); + const loggerStub = this.sandbox.stub(this.logger , "throwInternal"); // const define - const MAX_MESSAGE_LENGTH = DataSanitizer.MAX_MESSAGE_LENGTH; + const MAX_MESSAGE_LENGTH = DataSanitizerValues.MAX_MESSAGE_LENGTH; // use cases const messageShort: String = "hi"; - const messageLong = new Array(MAX_MESSAGE_LENGTH + 1).join('a'); + const messageLong = strRepeat("a", MAX_MESSAGE_LENGTH + 1); - const msgShortResult = DataSanitizer.sanitizeMessage(this.logger, messageShort); - Assert.ok(saniMsgSpy.returned(msgShortResult)); + Assert.equal(messageShort, dataSanitizeMessage(this.logger, messageShort)); + Assert.ok(loggerStub.notCalled); + Assert.equal(0, loggerStub.callCount); - const msgLongResult = DataSanitizer.sanitizeMessage(this.logger, messageLong); - Assert.ok(saniMsgSpy.returned(msgLongResult)); + Assert.equal(messageLong.substring(0, MAX_MESSAGE_LENGTH), dataSanitizeMessage(this.logger, messageLong)); + Assert.ok(loggerStub.calledOnce); + Assert.equal(1, loggerStub.callCount); - saniMsgSpy.restore(); + loggerStub.restore(); } }); @@ -89,16 +89,16 @@ export class ApplicationInsightsTests extends AITestClass { name: 'DataSanitizerTest: strings are well processed', test: () => { // const define - const MAX_STRING_LENGTH = DataSanitizer.MAX_STRING_LENGTH; + const MAX_STRING_LENGTH = DataSanitizerValues.MAX_STRING_LENGTH; // use cases const strShort: String = "hi"; - const strLong = new Array(MAX_STRING_LENGTH + 2).join('a'); + const strLong = strRepeat("a", MAX_STRING_LENGTH + 2); // Assert - Assert.equal(strShort.length, DataSanitizer.sanitizeString(this.logger, strShort).length); - Assert.notEqual(strLong.length, DataSanitizer.sanitizeString(this.logger, strLong).length); - Assert.equal(MAX_STRING_LENGTH, DataSanitizer.sanitizeString(this.logger, strLong).length); + Assert.equal(strShort.length, dataSanitizeString(this.logger, strShort).length); + Assert.notEqual(strLong.length, dataSanitizeString(this.logger, strLong).length); + Assert.equal(MAX_STRING_LENGTH, dataSanitizeString(this.logger, strLong).length); } }); @@ -107,22 +107,22 @@ export class ApplicationInsightsTests extends AITestClass { test: () => { // const define const loggerStub = this.sandbox.stub(this.logger , "throwInternal"); - const MAX_STRING_LENGTH = DataSanitizer.MAX_STRING_LENGTH; + const MAX_STRING_LENGTH = DataSanitizerValues.MAX_STRING_LENGTH; // use cases const strShort: String = "hi"; - const strLong = new Array(MAX_STRING_LENGTH + 2).join('a'); + const strLong = strRepeat("a", MAX_STRING_LENGTH + 2); // Act - DataSanitizer.sanitizeString(this.logger, strShort); + dataSanitizeString(this.logger, strShort); Assert.ok(loggerStub.notCalled); Assert.equal(0, loggerStub.callCount); - DataSanitizer.sanitizeString(this.logger, strLong); + dataSanitizeString(this.logger, strLong); Assert.ok(loggerStub.calledOnce); Assert.equal(1, loggerStub.callCount); - DataSanitizer.sanitizeString(this.logger, strLong); + dataSanitizeString(this.logger, strLong); Assert.ok(loggerStub.calledTwice); Assert.equal(2, loggerStub.callCount); @@ -133,22 +133,24 @@ export class ApplicationInsightsTests extends AITestClass { this.testCase({ name: 'DataSanitizerTests: strings are fully logged through console', test: () => { - const saniStrSpy = this.sandbox.spy(DataSanitizer, "sanitizeString"); + const loggerStub = this.sandbox.stub(this.logger , "throwInternal"); // const define - const MAX_STRING_LENGTH = DataSanitizer.MAX_STRING_LENGTH; + const MAX_STRING_LENGTH = DataSanitizerValues.MAX_STRING_LENGTH; // use cases const strShort: String = "hi"; - const strLong = new Array(MAX_STRING_LENGTH + 2).join('a'); + const strLong = strRepeat("a", MAX_STRING_LENGTH + 2); - const strShortResult = DataSanitizer.sanitizeString(this.logger, strShort); - Assert.ok(saniStrSpy.returned(strShortResult)); + Assert.equal(strShort, dataSanitizeString(this.logger, strShort)); + Assert.ok(loggerStub.notCalled); + Assert.equal(0, loggerStub.callCount); - const strLongResult = DataSanitizer.sanitizeString(this.logger, strLong); - Assert.ok(saniStrSpy.returned(strLongResult)); + Assert.equal(strLong.substring(0, MAX_STRING_LENGTH), dataSanitizeString(this.logger, strLong)); + Assert.ok(loggerStub.calledOnce); + Assert.equal(1, loggerStub.callCount); - saniStrSpy.restore(); + loggerStub.restore(); } }); @@ -157,16 +159,16 @@ export class ApplicationInsightsTests extends AITestClass { name: 'DataSanitizerTest: names are well processed', test: () => { // const define - const MAX_NAME_LENGTH = DataSanitizer.MAX_NAME_LENGTH; + const MAX_NAME_LENGTH = DataSanitizerValues.MAX_NAME_LENGTH; // use cases const nameShort: String = "hi"; - const nameLong = new Array(MAX_NAME_LENGTH + 2).join('a'); + const nameLong = strRepeat("a", MAX_NAME_LENGTH + 2); // Assert - Assert.equal(nameShort.length, DataSanitizer.sanitizeKey(this.logger, nameShort).length); - Assert.notEqual(nameLong.length, DataSanitizer.sanitizeKey(this.logger, nameLong).length); - Assert.equal(MAX_NAME_LENGTH, DataSanitizer.sanitizeKey(this.logger, nameLong).length); + Assert.equal(nameShort.length, dataSanitizeKey(this.logger, nameShort).length); + Assert.notEqual(nameLong.length, dataSanitizeKey(this.logger, nameLong).length); + Assert.equal(MAX_NAME_LENGTH, dataSanitizeKey(this.logger, nameLong).length); } }); @@ -175,22 +177,22 @@ export class ApplicationInsightsTests extends AITestClass { test: () => { // const define const loggerStub = this.sandbox.stub(this.logger , "throwInternal"); - const MAX_NAME_LENGTH = DataSanitizer.MAX_NAME_LENGTH; + const MAX_NAME_LENGTH = DataSanitizerValues.MAX_NAME_LENGTH; // use cases const nameShort: String = "hi"; - const nameLong = new Array(MAX_NAME_LENGTH + 2).join('a'); + const nameLong = strRepeat("a", MAX_NAME_LENGTH + 2); // Act - DataSanitizer.sanitizeKey(this.logger, nameShort); + dataSanitizeKey(this.logger, nameShort); Assert.ok(loggerStub.notCalled); Assert.equal(0, loggerStub.callCount); - DataSanitizer.sanitizeKey(this.logger, nameLong); + dataSanitizeKey(this.logger, nameLong); Assert.ok(loggerStub.calledOnce); Assert.equal(1, loggerStub.callCount); - DataSanitizer.sanitizeKey(this.logger, nameLong); + dataSanitizeKey(this.logger, nameLong); Assert.ok(loggerStub.calledTwice); Assert.equal(2, loggerStub.callCount); @@ -201,22 +203,23 @@ export class ApplicationInsightsTests extends AITestClass { this.testCase({ name: 'DataSanitizerTests: names are fully logged through console', test: () => { - const saniStrSpy = this.sandbox.spy(DataSanitizer, "sanitizeKey"); + const loggerStub = this.sandbox.stub(this.logger , "throwInternal"); // const define - const MAX_NAME_LENGTH = DataSanitizer.MAX_NAME_LENGTH; + const MAX_NAME_LENGTH = DataSanitizerValues.MAX_NAME_LENGTH; // use cases const nameShort: String = "hi"; - const nameLong = new Array(MAX_NAME_LENGTH + 2).join('a'); + const nameLong = strRepeat("a", MAX_NAME_LENGTH + 2); - const nameShortResult = DataSanitizer.sanitizeKey(this.logger, nameShort); - Assert.ok(saniStrSpy.returned(nameShortResult)); + Assert.equal(nameShort, dataSanitizeKey(this.logger, nameShort)); + Assert.ok(loggerStub.notCalled); - const nameLongResult = DataSanitizer.sanitizeKey(this.logger, nameLong); - Assert.ok(saniStrSpy.returned(nameLongResult)); + Assert.equal(nameLong.substring(0, MAX_NAME_LENGTH), dataSanitizeKey(this.logger, nameLong)); + Assert.ok(loggerStub.calledOnce); + Assert.equal(1, loggerStub.callCount); - saniStrSpy.restore(); + loggerStub.restore(); } }); @@ -228,17 +231,17 @@ export class ApplicationInsightsTests extends AITestClass { // use cases const inputShort: String = "hi"; - const inputLong = new Array(MAX_INPUT_LENGTH + 2).join('a'); + const inputLong = strRepeat("a", MAX_INPUT_LENGTH + 2); // Assert - Assert.equal(inputShort.length, DataSanitizer.sanitizeInput(this.logger, inputShort, MAX_INPUT_LENGTH, 0).length); - Assert.notEqual(inputLong.length, DataSanitizer.sanitizeInput(this.logger, inputLong, MAX_INPUT_LENGTH, 0).length); - Assert.equal(MAX_INPUT_LENGTH, DataSanitizer.sanitizeInput(this.logger, inputLong, MAX_INPUT_LENGTH, 0).length); + Assert.equal(inputShort.length, dataSanitizeInput(this.logger, inputShort, MAX_INPUT_LENGTH, 0).length); + Assert.notEqual(inputLong.length, dataSanitizeInput(this.logger, inputLong, MAX_INPUT_LENGTH, 0).length); + Assert.equal(MAX_INPUT_LENGTH, dataSanitizeInput(this.logger, inputLong, MAX_INPUT_LENGTH, 0).length); } }); this.testCase({ - name: 'DataSanitizerTests: throrwInternal function is called correctly in sanitizeInput function', + name: 'DataSanitizerTests: throwInternal function is called correctly in sanitizeInput function', test: () => { // const define const loggerStub = this.sandbox.stub(this.logger , "throwInternal"); @@ -246,18 +249,18 @@ export class ApplicationInsightsTests extends AITestClass { // use cases const inputShort: String = "hi"; - const inputLong = new Array(MAX_INPUT_LENGTH + 2).join('a'); + const inputLong = strRepeat("a", MAX_INPUT_LENGTH + 2); // Act - DataSanitizer.sanitizeInput(this.logger, inputShort, MAX_INPUT_LENGTH, 0); + dataSanitizeInput(this.logger, inputShort, MAX_INPUT_LENGTH, 0); Assert.ok(loggerStub.notCalled); Assert.equal(0, loggerStub.callCount); - DataSanitizer.sanitizeInput(this.logger, inputLong, MAX_INPUT_LENGTH, 0); + dataSanitizeInput(this.logger, inputLong, MAX_INPUT_LENGTH, 0); Assert.ok(loggerStub.calledOnce); Assert.equal(1, loggerStub.callCount); - DataSanitizer.sanitizeInput(this.logger, inputLong, MAX_INPUT_LENGTH, 0); + dataSanitizeInput(this.logger, inputLong, MAX_INPUT_LENGTH, 0); Assert.ok(loggerStub.calledTwice); Assert.equal(2, loggerStub.callCount); @@ -268,24 +271,25 @@ export class ApplicationInsightsTests extends AITestClass { this.testCase({ name: 'DataSanitizerTests: inputs are fully logged through console', test: () => { - const saniStrSpy = this.sandbox.spy(DataSanitizer, "sanitizeInput"); + const loggerStub = this.sandbox.stub(this.logger , "throwInternal"); // const define const MAX_INPUT_LENGTH = 1024; // use cases const inputShort: String = "hi"; - const inputLong = new Array(MAX_INPUT_LENGTH + 2).join('a'); + const inputLong = strRepeat("a", MAX_INPUT_LENGTH + 2); - const inputShortResult = DataSanitizer.sanitizeInput(this.logger, inputShort, MAX_INPUT_LENGTH, 0); - Assert.ok(saniStrSpy.returned(inputShortResult)); + Assert.equal(inputShort, dataSanitizeInput(this.logger, inputShort, MAX_INPUT_LENGTH, 0)); + Assert.ok(loggerStub.notCalled); + Assert.equal(0, loggerStub.callCount); - const inputLongResult = DataSanitizer.sanitizeInput(this.logger, inputLong, MAX_INPUT_LENGTH, 0); - Assert.ok(saniStrSpy.returned(inputLongResult)); + Assert.equal(inputLong.substring(0, MAX_INPUT_LENGTH), dataSanitizeInput(this.logger, inputLong, MAX_INPUT_LENGTH, 0)); + Assert.ok(loggerStub.calledOnce); + Assert.equal(1, loggerStub.callCount); - saniStrSpy.restore(); + loggerStub.restore(); } }); } - } diff --git a/shared/AppInsightsCommon/Tests/Unit/src/Util.tests.ts b/shared/AppInsightsCommon/Tests/Unit/src/Util.tests.ts index df6cdfec..3087c020 100644 --- a/shared/AppInsightsCommon/Tests/Unit/src/Util.tests.ts +++ b/shared/AppInsightsCommon/Tests/Unit/src/Util.tests.ts @@ -1,7 +1,9 @@ import { Assert, AITestClass } from "@microsoft/ai-test-framework"; -import { UrlHelper, CorrelationIdHelper, Util } from "../../../src/Util"; import { ICorrelationConfig } from "../../../src/Interfaces/ICorrelationConfig"; -import { strStartsWith } from "@microsoft/applicationinsights-core-js"; +import { getIEVersion, strStartsWith, uaDisallowsSameSiteNone } from "@microsoft/applicationinsights-core-js"; +import { correlationIdCanIncludeCorrelationHeader } from "../../../src/Util"; +import { createDomEvent } from "../../../src/DomHelperFuncs"; +import { urlParseFullHost, urlParseHost, urlParseUrl } from "../../../src/UrlHelperFuncs"; export class UtilTests extends AITestClass { private testRegexLists = (config: ICorrelationConfig, exp: boolean, host: string) => { @@ -9,7 +11,7 @@ export class UtilTests extends AITestClass { if (!strStartsWith(host, "http")) { requestUrl = "https://" + host; } - Assert.equal(exp, CorrelationIdHelper.canIncludeCorrelationHeader(config, requestUrl, "not used"), host); + Assert.equal(exp, correlationIdCanIncludeCorrelationHeader(config, requestUrl, "not used"), host); }; public testInitialize() { @@ -23,7 +25,7 @@ export class UtilTests extends AITestClass { test: () => { const origEvent = (window as any).Event; (window as any).Event = {}; - const event = Util.createDomEvent('something'); + const event = createDomEvent('something'); Assert.equal('something', event.type); (window as any).Event = origEvent; } @@ -38,7 +40,7 @@ export class UtilTests extends AITestClass { let passed; let match; try { - const host = UrlHelper.parseUrl("https://portal.azure.com/some/endpoint").host.toLowerCase(); + const host = urlParseUrl("https://portal.azure.com/some/endpoint").host.toLowerCase(); passed = true; match = host === "portal.azure.com"; } catch (e) { @@ -55,100 +57,100 @@ export class UtilTests extends AITestClass { this.testCase({ name: "UrlHelper: parseHost should return correct host name", test: () => { - Assert.equal("portal.azure.com", UrlHelper.parseHost("https://portal.azure.com/some/endpoint")); - Assert.equal("bing.com", UrlHelper.parseHost("http://www.bing.com")); - Assert.equal("bing.com", UrlHelper.parseHost("https://www2.bing.com/")); - Assert.equal("p.r.e.f.i.x.bing.com", UrlHelper.parseHost("http://wwW2.p.r.e.f.i.x.bing.com/")); + Assert.equal("portal.azure.com", urlParseHost("https://portal.azure.com/some/endpoint")); + Assert.equal("bing.com", urlParseHost("http://www.bing.com")); + Assert.equal("bing.com", urlParseHost("https://www2.bing.com/")); + Assert.equal("p.r.e.f.i.x.bing.com", urlParseHost("http://wwW2.p.r.e.f.i.x.bing.com/")); - Assert.equal("portal.azure.com", UrlHelper.parseHost("https://portal.azure.com/some/endpoint", false)); - Assert.equal("bing.com", UrlHelper.parseHost("http://www.bing.com", false)); - Assert.equal("bing.com", UrlHelper.parseHost("https://www2.bing.com/", false)); - Assert.equal("p.r.e.f.i.x.bing.com", UrlHelper.parseHost("http://wwW2.p.r.e.f.i.x.bing.com/", false)); + Assert.equal("portal.azure.com", urlParseHost("https://portal.azure.com/some/endpoint", false)); + Assert.equal("bing.com", urlParseHost("http://www.bing.com", false)); + Assert.equal("bing.com", urlParseHost("https://www2.bing.com/", false)); + Assert.equal("p.r.e.f.i.x.bing.com", urlParseHost("http://wwW2.p.r.e.f.i.x.bing.com/", false)); - Assert.equal("portal.azure.com", UrlHelper.parseHost("https://portal.azure.com/some/endpoint", true)); - Assert.equal("bing.com", UrlHelper.parseHost("http://www.bing.com", true)); - Assert.equal("bing.com", UrlHelper.parseHost("https://www2.bing.com/", true)); - Assert.equal("p.r.e.f.i.x.bing.com", UrlHelper.parseHost("http://wwW2.p.r.e.f.i.x.bing.com/", true)); + Assert.equal("portal.azure.com", urlParseHost("https://portal.azure.com/some/endpoint", true)); + Assert.equal("bing.com", urlParseHost("http://www.bing.com", true)); + Assert.equal("bing.com", urlParseHost("https://www2.bing.com/", true)); + Assert.equal("p.r.e.f.i.x.bing.com", urlParseHost("http://wwW2.p.r.e.f.i.x.bing.com/", true)); // Check with port included - Assert.equal("portal.azure.com", UrlHelper.parseHost("https://portal.azure.com:9999/some/endpoint")); - Assert.equal("bing.com", UrlHelper.parseHost("http://www.bing.com:9999")); - Assert.equal("bing.com", UrlHelper.parseHost("https://www2.bing.com:9999/")); - Assert.equal("p.r.e.f.i.x.bing.com", UrlHelper.parseHost("http://wwW2.p.r.e.f.i.x.bing.com:9999/")); + Assert.equal("portal.azure.com", urlParseHost("https://portal.azure.com:9999/some/endpoint")); + Assert.equal("bing.com", urlParseHost("http://www.bing.com:9999")); + Assert.equal("bing.com", urlParseHost("https://www2.bing.com:9999/")); + Assert.equal("p.r.e.f.i.x.bing.com", urlParseHost("http://wwW2.p.r.e.f.i.x.bing.com:9999/")); - Assert.equal("portal.azure.com", UrlHelper.parseHost("https://portal.azure.com:9999/some/endpoint", false)); - Assert.equal("bing.com", UrlHelper.parseHost("http://www.bing.com:9999", false)); - Assert.equal("bing.com", UrlHelper.parseHost("https://www2.bing.com:9999/", false)); - Assert.equal("p.r.e.f.i.x.bing.com", UrlHelper.parseHost("http://wwW2.p.r.e.f.i.x.bing.com:9999/", false)); + Assert.equal("portal.azure.com", urlParseHost("https://portal.azure.com:9999/some/endpoint", false)); + Assert.equal("bing.com", urlParseHost("http://www.bing.com:9999", false)); + Assert.equal("bing.com", urlParseHost("https://www2.bing.com:9999/", false)); + Assert.equal("p.r.e.f.i.x.bing.com", urlParseHost("http://wwW2.p.r.e.f.i.x.bing.com:9999/", false)); - Assert.equal("portal.azure.com:9999", UrlHelper.parseHost("https://portal.azure.com:9999/some/endpoint", true)); - Assert.equal("bing.com:9999", UrlHelper.parseHost("http://www.bing.com:9999", true)); - Assert.equal("bing.com:9999", UrlHelper.parseHost("https://www2.bing.com:9999/", true)); - Assert.equal("p.r.e.f.i.x.bing.com:9999", UrlHelper.parseHost("http://wwW2.p.r.e.f.i.x.bing.com:9999/", true)); + Assert.equal("portal.azure.com:9999", urlParseHost("https://portal.azure.com:9999/some/endpoint", true)); + Assert.equal("bing.com:9999", urlParseHost("http://www.bing.com:9999", true)); + Assert.equal("bing.com:9999", urlParseHost("https://www2.bing.com:9999/", true)); + Assert.equal("p.r.e.f.i.x.bing.com:9999", urlParseHost("http://wwW2.p.r.e.f.i.x.bing.com:9999/", true)); // Check with default ports present - Assert.equal("portal.azure.com", UrlHelper.parseHost("http://portal.azure.com:80/some/endpoint", true)); - Assert.equal("portal.azure.com", UrlHelper.parseHost("https://portal.azure.com:443/some/endpoint", true)); - Assert.equal("portal.azure.com:80", UrlHelper.parseHost("https://portal.azure.com:80/some/endpoint", true)); - Assert.equal("portal.azure.com:443", UrlHelper.parseHost("http://portal.azure.com:443/some/endpoint", true)); - Assert.equal("bing.com", UrlHelper.parseHost("http://www.bing.com:80", true)); - Assert.equal("bing.com", UrlHelper.parseHost("https://www2.bing.com:443/", true)); - Assert.equal("bing.com:80", UrlHelper.parseHost("https://www.bing.com:80", true)); - Assert.equal("bing.com:443", UrlHelper.parseHost("http://www2.bing.com:443/", true)); - Assert.equal("p.r.e.f.i.x.bing.com", UrlHelper.parseHost("http://wwW2.p.r.e.f.i.x.bing.com:80/", true)); - Assert.equal("p.r.e.f.i.x.bing.com", UrlHelper.parseHost("https://wwW2.p.r.e.f.i.x.bing.com:443/", true)); - Assert.equal("p.r.e.f.i.x.bing.com:443", UrlHelper.parseHost("http://wwW2.p.r.e.f.i.x.bing.com:443/", true)); - Assert.equal("p.r.e.f.i.x.bing.com:80", UrlHelper.parseHost("https://wwW2.p.r.e.f.i.x.bing.com:80/", true)); + Assert.equal("portal.azure.com", urlParseHost("http://portal.azure.com:80/some/endpoint", true)); + Assert.equal("portal.azure.com", urlParseHost("https://portal.azure.com:443/some/endpoint", true)); + Assert.equal("portal.azure.com:80", urlParseHost("https://portal.azure.com:80/some/endpoint", true)); + Assert.equal("portal.azure.com:443", urlParseHost("http://portal.azure.com:443/some/endpoint", true)); + Assert.equal("bing.com", urlParseHost("http://www.bing.com:80", true)); + Assert.equal("bing.com", urlParseHost("https://www2.bing.com:443/", true)); + Assert.equal("bing.com:80", urlParseHost("https://www.bing.com:80", true)); + Assert.equal("bing.com:443", urlParseHost("http://www2.bing.com:443/", true)); + Assert.equal("p.r.e.f.i.x.bing.com", urlParseHost("http://wwW2.p.r.e.f.i.x.bing.com:80/", true)); + Assert.equal("p.r.e.f.i.x.bing.com", urlParseHost("https://wwW2.p.r.e.f.i.x.bing.com:443/", true)); + Assert.equal("p.r.e.f.i.x.bing.com:443", urlParseHost("http://wwW2.p.r.e.f.i.x.bing.com:443/", true)); + Assert.equal("p.r.e.f.i.x.bing.com:80", urlParseHost("https://wwW2.p.r.e.f.i.x.bing.com:80/", true)); } }); this.testCase({ name: "UrlHelper: parseFullHost should return correct host name", test: () => { - Assert.equal("portal.azure.com", UrlHelper.parseFullHost("https://portal.azure.com/some/endpoint")); - Assert.equal("www.bing.com", UrlHelper.parseFullHost("http://www.bing.com")); - Assert.equal("www2.bing.com", UrlHelper.parseFullHost("https://www2.bing.com/")); - Assert.equal("wwW2.p.r.e.f.i.x.bing.com", UrlHelper.parseFullHost("http://wwW2.p.r.e.f.i.x.bing.com/")); + Assert.equal("portal.azure.com", urlParseFullHost("https://portal.azure.com/some/endpoint")); + Assert.equal("www.bing.com", urlParseFullHost("http://www.bing.com")); + Assert.equal("www2.bing.com", urlParseFullHost("https://www2.bing.com/")); + Assert.equal("wwW2.p.r.e.f.i.x.bing.com", urlParseFullHost("http://wwW2.p.r.e.f.i.x.bing.com/")); - Assert.equal("portal.azure.com", UrlHelper.parseFullHost("https://portal.azure.com/some/endpoint", false)); - Assert.equal("www.bing.com", UrlHelper.parseFullHost("http://www.bing.com", false)); - Assert.equal("www2.bing.com", UrlHelper.parseFullHost("https://www2.bing.com/", false)); - Assert.equal("wwW2.p.r.e.f.i.x.bing.com", UrlHelper.parseFullHost("http://wwW2.p.r.e.f.i.x.bing.com/", false)); + Assert.equal("portal.azure.com", urlParseFullHost("https://portal.azure.com/some/endpoint", false)); + Assert.equal("www.bing.com", urlParseFullHost("http://www.bing.com", false)); + Assert.equal("www2.bing.com", urlParseFullHost("https://www2.bing.com/", false)); + Assert.equal("wwW2.p.r.e.f.i.x.bing.com", urlParseFullHost("http://wwW2.p.r.e.f.i.x.bing.com/", false)); - Assert.equal("portal.azure.com", UrlHelper.parseFullHost("https://portal.azure.com/some/endpoint", true)); - Assert.equal("www.bing.com", UrlHelper.parseFullHost("http://www.bing.com", true)); - Assert.equal("www2.bing.com", UrlHelper.parseFullHost("https://www2.bing.com/", true)); - Assert.equal("wwW2.p.r.e.f.i.x.bing.com", UrlHelper.parseFullHost("http://wwW2.p.r.e.f.i.x.bing.com/", true)); + Assert.equal("portal.azure.com", urlParseFullHost("https://portal.azure.com/some/endpoint", true)); + Assert.equal("www.bing.com", urlParseFullHost("http://www.bing.com", true)); + Assert.equal("www2.bing.com", urlParseFullHost("https://www2.bing.com/", true)); + Assert.equal("wwW2.p.r.e.f.i.x.bing.com", urlParseFullHost("http://wwW2.p.r.e.f.i.x.bing.com/", true)); // Check with port included - Assert.equal("portal.azure.com", UrlHelper.parseFullHost("https://portal.azure.com:9999/some/endpoint")); - Assert.equal("www.bing.com", UrlHelper.parseFullHost("http://www.bing.com:9999")); - Assert.equal("www2.bing.com", UrlHelper.parseFullHost("https://www2.bing.com:9999/")); - Assert.equal("wwW2.p.r.e.f.i.x.bing.com", UrlHelper.parseFullHost("http://wwW2.p.r.e.f.i.x.bing.com:9999/")); + Assert.equal("portal.azure.com", urlParseFullHost("https://portal.azure.com:9999/some/endpoint")); + Assert.equal("www.bing.com", urlParseFullHost("http://www.bing.com:9999")); + Assert.equal("www2.bing.com", urlParseFullHost("https://www2.bing.com:9999/")); + Assert.equal("wwW2.p.r.e.f.i.x.bing.com", urlParseFullHost("http://wwW2.p.r.e.f.i.x.bing.com:9999/")); - Assert.equal("portal.azure.com", UrlHelper.parseFullHost("https://portal.azure.com:9999/some/endpoint", false)); - Assert.equal("www.bing.com", UrlHelper.parseFullHost("http://www.bing.com:9999", false)); - Assert.equal("www2.bing.com", UrlHelper.parseFullHost("https://www2.bing.com:9999/", false)); - Assert.equal("wwW2.p.r.e.f.i.x.bing.com", UrlHelper.parseFullHost("http://wwW2.p.r.e.f.i.x.bing.com:9999/", false)); + Assert.equal("portal.azure.com", urlParseFullHost("https://portal.azure.com:9999/some/endpoint", false)); + Assert.equal("www.bing.com", urlParseFullHost("http://www.bing.com:9999", false)); + Assert.equal("www2.bing.com", urlParseFullHost("https://www2.bing.com:9999/", false)); + Assert.equal("wwW2.p.r.e.f.i.x.bing.com", urlParseFullHost("http://wwW2.p.r.e.f.i.x.bing.com:9999/", false)); - Assert.equal("portal.azure.com:9999", UrlHelper.parseFullHost("https://portal.azure.com:9999/some/endpoint", true)); - Assert.equal("www.bing.com:9999", UrlHelper.parseFullHost("http://www.bing.com:9999", true)); - Assert.equal("www2.bing.com:9999", UrlHelper.parseFullHost("https://www2.bing.com:9999/", true)); - Assert.equal("wwW2.p.r.e.f.i.x.bing.com:9999", UrlHelper.parseFullHost("http://wwW2.p.r.e.f.i.x.bing.com:9999/", true)); + Assert.equal("portal.azure.com:9999", urlParseFullHost("https://portal.azure.com:9999/some/endpoint", true)); + Assert.equal("www.bing.com:9999", urlParseFullHost("http://www.bing.com:9999", true)); + Assert.equal("www2.bing.com:9999", urlParseFullHost("https://www2.bing.com:9999/", true)); + Assert.equal("wwW2.p.r.e.f.i.x.bing.com:9999", urlParseFullHost("http://wwW2.p.r.e.f.i.x.bing.com:9999/", true)); // Check with default ports present - Assert.equal("portal.azure.com", UrlHelper.parseFullHost("http://portal.azure.com:80/some/endpoint", true)); - Assert.equal("portal.azure.com", UrlHelper.parseFullHost("https://portal.azure.com:443/some/endpoint", true)); - Assert.equal("portal.azure.com:80", UrlHelper.parseFullHost("https://portal.azure.com:80/some/endpoint", true)); - Assert.equal("portal.azure.com:443", UrlHelper.parseFullHost("http://portal.azure.com:443/some/endpoint", true)); - Assert.equal("www.bing.com", UrlHelper.parseFullHost("http://www.bing.com:80", true)); - Assert.equal("www2.bing.com", UrlHelper.parseFullHost("https://www2.bing.com:443/", true)); - Assert.equal("www.bing.com:80", UrlHelper.parseFullHost("https://www.bing.com:80", true)); - Assert.equal("www2.bing.com:443", UrlHelper.parseFullHost("http://www2.bing.com:443/", true)); - Assert.equal("wwW2.p.r.e.f.i.x.bing.com", UrlHelper.parseFullHost("http://wwW2.p.r.e.f.i.x.bing.com:80/", true)); - Assert.equal("wwW2.p.r.e.f.i.x.bing.com", UrlHelper.parseFullHost("https://wwW2.p.r.e.f.i.x.bing.com:443/", true)); - Assert.equal("wwW2.p.r.e.f.i.x.bing.com:443", UrlHelper.parseFullHost("http://wwW2.p.r.e.f.i.x.bing.com:443/", true)); - Assert.equal("wwW2.p.r.e.f.i.x.bing.com:80", UrlHelper.parseFullHost("https://wwW2.p.r.e.f.i.x.bing.com:80/", true)); + Assert.equal("portal.azure.com", urlParseFullHost("http://portal.azure.com:80/some/endpoint", true)); + Assert.equal("portal.azure.com", urlParseFullHost("https://portal.azure.com:443/some/endpoint", true)); + Assert.equal("portal.azure.com:80", urlParseFullHost("https://portal.azure.com:80/some/endpoint", true)); + Assert.equal("portal.azure.com:443", urlParseFullHost("http://portal.azure.com:443/some/endpoint", true)); + Assert.equal("www.bing.com", urlParseFullHost("http://www.bing.com:80", true)); + Assert.equal("www2.bing.com", urlParseFullHost("https://www2.bing.com:443/", true)); + Assert.equal("www.bing.com:80", urlParseFullHost("https://www.bing.com:80", true)); + Assert.equal("www2.bing.com:443", urlParseFullHost("http://www2.bing.com:443/", true)); + Assert.equal("wwW2.p.r.e.f.i.x.bing.com", urlParseFullHost("http://wwW2.p.r.e.f.i.x.bing.com:80/", true)); + Assert.equal("wwW2.p.r.e.f.i.x.bing.com", urlParseFullHost("https://wwW2.p.r.e.f.i.x.bing.com:443/", true)); + Assert.equal("wwW2.p.r.e.f.i.x.bing.com:443", urlParseFullHost("http://wwW2.p.r.e.f.i.x.bing.com:443/", true)); + Assert.equal("wwW2.p.r.e.f.i.x.bing.com:80", urlParseFullHost("https://wwW2.p.r.e.f.i.x.bing.com:80/", true)); } }); @@ -214,38 +216,38 @@ export class UtilTests extends AITestClass { correlationHeaderDomains: ["azure.com", "prefix.bing.com", "*.microsoft.com"] } as ICorrelationConfig - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://azure.com:443", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://azure.com:80", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://azure.com", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://azure.com:443", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://azure.com:8000", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://azure.com:443", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://azure.com:80", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://azure.com", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "http://azure.com:443", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://azure.com:8000", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://monitor.azure.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://monitor.azure.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://monitor.azure.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "http://monitor.azure.com:443", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://prefix.bing.com:443", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://prefix.bing.com", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://prefix.bing.com:443", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://prefix.bing.com:80", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://prefix.bing.com:8000", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://prefix.bing.com:443", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://prefix.bing.com", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "http://prefix.bing.com:443", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://prefix.bing.com:80", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://prefix.bing.com:8000", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://ignore.microsoft.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://ignore.microsoft.com", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://ignore.microsoft.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://ignore.microsoft.com:80", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://ignore.microsoft.com:8080", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://ignore.microsoft.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://ignore.microsoft.com", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "http://ignore.microsoft.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://ignore.microsoft.com:80", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://ignore.microsoft.com:8080", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://something.microsoft.com:443", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://something.microsoft.com", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://something.microsoft.com:443", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://something.microsoft.com:80", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://something.microsoft.com:8000", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://something.microsoft.com:443", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://something.microsoft.com", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "http://something.microsoft.com:443", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://something.microsoft.com:80", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://something.microsoft.com:8000", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://microsoft.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://microsoft.com", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://microsoft.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://microsoft.com:80", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://microsoft.com:8000", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://microsoft.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://microsoft.com", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "http://microsoft.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://microsoft.com:80", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://microsoft.com:8000", "example.com")); } }); @@ -258,40 +260,40 @@ export class UtilTests extends AITestClass { correlationHeaderDomains: ["azure.com", "prefix.bing.com", "*.microsoft.com:8080"] } as ICorrelationConfig - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://azure.com:443", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://azure.com:80", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://azure.com", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://azure.com:443", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://azure.com:8000", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://azure.com:443", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://azure.com:80", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://azure.com", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "http://azure.com:443", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://azure.com:8000", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://monitor.azure.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://monitor.azure.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://monitor.azure.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "http://monitor.azure.com:443", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://prefix.bing.com:443", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://prefix.bing.com", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://prefix.bing.com:443", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://prefix.bing.com:80", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://prefix.bing.com:8000", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://prefix.bing.com:443", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://prefix.bing.com", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "http://prefix.bing.com:443", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://prefix.bing.com:80", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://prefix.bing.com:8000", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://ignore.microsoft.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://ignore.microsoft.com", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://ignore.microsoft.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://ignore.microsoft.com:80", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://ignore.microsoft.com:8080", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://ignore.microsoft.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://ignore.microsoft.com", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "http://ignore.microsoft.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://ignore.microsoft.com:80", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://ignore.microsoft.com:8080", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://something.microsoft.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://something.microsoft.com", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://something.microsoft.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://something.microsoft.com:80", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://something.microsoft.com:8000", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://something.microsoft.com:8080", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://something.microsoft.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://something.microsoft.com", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "http://something.microsoft.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://something.microsoft.com:80", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://something.microsoft.com:8000", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://something.microsoft.com:8080", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://microsoft.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://microsoft.com", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://microsoft.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://microsoft.com:80", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://microsoft.com:8000", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://microsoft.com:8080", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://microsoft.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://microsoft.com", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "http://microsoft.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://microsoft.com:80", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://microsoft.com:8000", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://microsoft.com:8080", "example.com")); } }); @@ -304,30 +306,30 @@ export class UtilTests extends AITestClass { correlationHeaderDomains: ["azure.com", "prefix.bing.com", "*.microsoft.com", "example.com"] } as ICorrelationConfig - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://example.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://example.com:80", "example.com")); - Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://example.com", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://example.com:8000", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://example.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://example.com:8080", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://example.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://example.com:80", "example.com")); + Assert.equal(true, correlationIdCanIncludeCorrelationHeader(config, "https://example.com", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "http://example.com:8000", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "http://example.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://example.com:8080", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://monitor.azure.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://monitor.azure.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://monitor.azure.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "http://monitor.azure.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://prefix.bing.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://prefix.bing.com", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://prefix.bing.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://prefix.bing.com:80", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://prefix.bing.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://prefix.bing.com", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "http://prefix.bing.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://prefix.bing.com:80", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://something.microsoft.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://something.microsoft.com", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://something.microsoft.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://something.microsoft.com:80", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://something.microsoft.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://something.microsoft.com", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "http://something.microsoft.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://something.microsoft.com:80", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://microsoft.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://microsoft.com", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "http://microsoft.com:443", "example.com")); - Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "https://microsoft.com:80", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://microsoft.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://microsoft.com", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "http://microsoft.com:443", "example.com")); + Assert.equal(false, correlationIdCanIncludeCorrelationHeader(config, "https://microsoft.com:80", "example.com")); } }); @@ -429,11 +431,11 @@ export class UtilTests extends AITestClass { ]; for (let lp = 0; lp < excludeValues.length; lp++) { - Assert.equal(true, Util.disallowsSameSiteNone(excludeValues[lp]), excludeValues[lp]); + Assert.equal(true, uaDisallowsSameSiteNone(excludeValues[lp]), excludeValues[lp]); } for (let lp = 0; lp < acceptValues.length; lp++) { - Assert.equal(false, Util.disallowsSameSiteNone(acceptValues[lp]), acceptValues[lp]); + Assert.equal(false, uaDisallowsSameSiteNone(acceptValues[lp]), acceptValues[lp]); } } }); @@ -526,32 +528,32 @@ export class UtilTests extends AITestClass { ]; for (let lp = 0; lp < notIEValues.length; lp++) { - let ieVersion = Util.getIEVersion(notIEValues[lp]); + let ieVersion = getIEVersion(notIEValues[lp]); Assert.equal(null, ieVersion, "Not IE: " + notIEValues[lp]); } - Assert.equal(7, Util.getIEVersion("Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)")); - Assert.equal(7, Util.getIEVersion("Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; en-US)")); - Assert.equal(7, Util.getIEVersion("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; Trident/4.0;)")); - Assert.equal(8, Util.getIEVersion("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)")); - Assert.equal(8, Util.getIEVersion("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)")); - Assert.equal(8, Util.getIEVersion("Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)")); - Assert.equal(8, Util.getIEVersion("Mozilla/4.0 (Compatible; MSIE 8.0; Windows NT 5.2; Trident/6.0)")); - Assert.equal(9, Util.getIEVersion("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.0)")); - Assert.equal(9, Util.getIEVersion("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1)")); - Assert.equal(10, Util.getIEVersion("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)")); - Assert.equal(10, Util.getIEVersion("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)")); - Assert.equal(11, Util.getIEVersion("Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko")); - Assert.equal(11, Util.getIEVersion("Mozilla/5.0 (Windows NT 6.2; Trident/7.0; rv:11.0) like Gecko")); - Assert.equal(11, Util.getIEVersion("Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko")); - Assert.equal(11, Util.getIEVersion("Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0) like Gecko")); - Assert.equal(11, Util.getIEVersion("Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko")); + Assert.equal(7, getIEVersion("Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)")); + Assert.equal(7, getIEVersion("Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; en-US)")); + Assert.equal(7, getIEVersion("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; Trident/4.0;)")); + Assert.equal(8, getIEVersion("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)")); + Assert.equal(8, getIEVersion("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)")); + Assert.equal(8, getIEVersion("Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)")); + Assert.equal(8, getIEVersion("Mozilla/4.0 (Compatible; MSIE 8.0; Windows NT 5.2; Trident/6.0)")); + Assert.equal(9, getIEVersion("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.0)")); + Assert.equal(9, getIEVersion("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1)")); + Assert.equal(10, getIEVersion("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)")); + Assert.equal(10, getIEVersion("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)")); + Assert.equal(11, getIEVersion("Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko")); + Assert.equal(11, getIEVersion("Mozilla/5.0 (Windows NT 6.2; Trident/7.0; rv:11.0) like Gecko")); + Assert.equal(11, getIEVersion("Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko")); + Assert.equal(11, getIEVersion("Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0) like Gecko")); + Assert.equal(11, getIEVersion("Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko")); const origDocMode = document['documentMode']; document['documentMode'] = 11; - Assert.equal(11, Util.getIEVersion("Mozilla/4.0 (Compatible; MSIE 8.0; Windows NT 5.2; Trident/6.0)")); - Assert.equal(11, Util.getIEVersion("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; Win64; x64; Trident/7.0; .NET4.0C; .NET4.0E)")); + Assert.equal(11, getIEVersion("Mozilla/4.0 (Compatible; MSIE 8.0; Windows NT 5.2; Trident/6.0)")); + Assert.equal(11, getIEVersion("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; Win64; x64; Trident/7.0; .NET4.0C; .NET4.0E)")); // restore documentMode document['documentMode'] = origDocMode; diff --git a/shared/AppInsightsCommon/package.json b/shared/AppInsightsCommon/package.json index 9b9e2675..84b93cfa 100644 --- a/shared/AppInsightsCommon/package.json +++ b/shared/AppInsightsCommon/package.json @@ -28,7 +28,7 @@ "devDependencies": { "@microsoft/ai-test-framework": "0.0.1", "@microsoft/applicationinsights-rollup-plugin-uglify3-js": "1.0.0", - "@microsoft/applicationinsights-rollup-es3": "1.1.3", + "@microsoft/applicationinsights-rollup-es5": "1.0.0", "@microsoft/api-extractor": "^7.18.1", "grunt": "^1.5.3", "grunt-cli": "^1.4.3", @@ -51,7 +51,8 @@ "dependencies": { "@microsoft/applicationinsights-shims": "2.0.1", "@microsoft/applicationinsights-core-js": "2.8.6", - "@microsoft/dynamicproto-js": "^1.1.6" + "@microsoft/dynamicproto-js": "^1.1.6", + "@nevware21/ts-utils": "^0.4.1" }, "license": "MIT" } diff --git a/shared/AppInsightsCommon/rollup.config.js b/shared/AppInsightsCommon/rollup.config.js index 409e7f98..6065a62a 100644 --- a/shared/AppInsightsCommon/rollup.config.js +++ b/shared/AppInsightsCommon/rollup.config.js @@ -2,7 +2,7 @@ import nodeResolve from "@rollup/plugin-node-resolve"; import { uglify } from "@microsoft/applicationinsights-rollup-plugin-uglify3-js"; import replace from "@rollup/plugin-replace"; import cleanup from "rollup-plugin-cleanup"; -import { es3Poly, es3Check, importCheck } from "@microsoft/applicationinsights-rollup-es3"; +import { es5Poly, es5Check, importCheck } from "@microsoft/applicationinsights-rollup-es5"; import dynamicRemove from "@microsoft/dynamicproto-js/tools/rollup/node/removedynamic"; import { updateDistEsmFiles } from "../../tools/updateDistEsm/updateDistEsm"; @@ -61,8 +61,8 @@ const browserRollupConfigFactory = isProduction => { preferBuiltins: false }), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; @@ -118,8 +118,8 @@ const nodeUmdRollupConfigFactory = (isProduction) => { importCheck({ exclude: [ "applicationinsights-common-js" ] }), nodeResolve(), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; diff --git a/shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.ts b/shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.ts index 26d645d7..91b6a09f 100644 --- a/shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.ts +++ b/shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.ts @@ -83,9 +83,9 @@ export function dataSanitizeString(logger: IDiagnosticLogger, value: any, maxLen let valueTrunc : String; if (value) { maxLength = maxLength ? maxLength : DataSanitizerValues.MAX_STRING_LENGTH; // in case default parameters dont work - value = strTrim(value); - if (value.toString().length > maxLength) { - valueTrunc = value.toString().substring(0, maxLength); + value = strTrim(value.toString()); + if (value.length > maxLength) { + valueTrunc = value.substring(0, maxLength); _throwInternal(logger, eLoggingSeverity.WARNING, _eInternalMessageId.StringValueTooLong, @@ -176,7 +176,7 @@ export function dataSanitizeId(logger: IDiagnosticLogger, id: string): string { export function dataSanitizeInput(logger: IDiagnosticLogger, input: any, maxLength: number, _msgId: _eInternalMessageId) { let inputTrunc : String; if (input) { - input = strTrim(input); + input = strTrim(input.toString()); if (input.length > maxLength) { inputTrunc = input.substring(0, maxLength); _throwInternal(logger, @@ -195,93 +195,3 @@ export function dsPadNumber(num: number) { const s = "00" + num; return s.substr(s.length - 3); } - -export interface IDataSanitizer { - /** - * Max length allowed for custom names. - */ - MAX_NAME_LENGTH: number; - - /** - * Max length allowed for Id field in page views. - */ - MAX_ID_LENGTH: number; - - /** - * Max length allowed for custom values. - */ - MAX_PROPERTY_LENGTH: number; - - /** - * Max length allowed for names - */ - MAX_STRING_LENGTH: number; - - /** - * Max length allowed for url. - */ - MAX_URL_LENGTH: number; - - /** - * Max length allowed for messages. - */ - MAX_MESSAGE_LENGTH: number; - - /** - * Max length allowed for exceptions. - */ - MAX_EXCEPTION_LENGTH: number; - - sanitizeKeyAndAddUniqueness: (logger: IDiagnosticLogger, key: any, map: any) => string; - - sanitizeKey: (logger: IDiagnosticLogger, name: any) => string; - - sanitizeString: (logger: IDiagnosticLogger, value: any, maxLength?: number) => string; - - sanitizeUrl: (logger: IDiagnosticLogger, url: any) => string; - - sanitizeMessage: (logger: IDiagnosticLogger, message: any) => string; - - sanitizeException: (logger: IDiagnosticLogger, exception: any) => string; - - sanitizeProperties: (logger: IDiagnosticLogger, properties: any) => any; - - sanitizeMeasurements: (logger: IDiagnosticLogger, measurements: any) => any; - - sanitizeId: (logger: IDiagnosticLogger, id: string) => string; - - sanitizeInput: (logger: IDiagnosticLogger, input: any, maxLength: number, _msgId: _eInternalMessageId) => any; - - padNumber: (num: number) => string; - - /** - * helper method to trim strings (IE8 does not implement String.prototype.trim) - */ - trim: (str: any) => string; -} - -/** - * Provides the DataSanitizer functions within the previous namespace. - */ -export const DataSanitizer: IDataSanitizer = { - MAX_NAME_LENGTH: DataSanitizerValues.MAX_NAME_LENGTH, - MAX_ID_LENGTH: DataSanitizerValues.MAX_ID_LENGTH, - MAX_PROPERTY_LENGTH: DataSanitizerValues.MAX_PROPERTY_LENGTH, - MAX_STRING_LENGTH: DataSanitizerValues.MAX_STRING_LENGTH, - MAX_URL_LENGTH: DataSanitizerValues.MAX_URL_LENGTH, - MAX_MESSAGE_LENGTH: DataSanitizerValues.MAX_MESSAGE_LENGTH, - MAX_EXCEPTION_LENGTH: DataSanitizerValues.MAX_EXCEPTION_LENGTH, - - sanitizeKeyAndAddUniqueness: dataSanitizeKeyAndAddUniqueness, - sanitizeKey: dataSanitizeKey, - sanitizeString: dataSanitizeString, - sanitizeUrl: dataSanitizeUrl, - sanitizeMessage: dataSanitizeMessage, - sanitizeException: dataSanitizeException, - sanitizeProperties: dataSanitizeProperties, - sanitizeMeasurements: dataSanitizeMeasurements, - sanitizeId: dataSanitizeId, - sanitizeInput: dataSanitizeInput, - padNumber: dsPadNumber, - trim: strTrim -}; diff --git a/shared/AppInsightsCommon/src/Util.ts b/shared/AppInsightsCommon/src/Util.ts index 9c613d02..fe4e0a59 100644 --- a/shared/AppInsightsCommon/src/Util.ts +++ b/shared/AppInsightsCommon/src/Util.ts @@ -2,23 +2,15 @@ // Licensed under the MIT License. import { - IDiagnosticLogger, IDistributedTraceContext, IPlugin, arrForEach, arrIndexOf, attachEvent, canUseCookies as coreCanUseCookies, dateNow, - deleteCookie as coreDeleteCookie, disableCookies as coreDisableCookies, dumpObj, generateW3CId, getCookie as coreGetCookie, - getExceptionName as coreGetExceptionName, getIEVersion, getPerformance, isArray, isBeaconsSupported, isDate, isError, isNullOrUndefined, - isValidSpanId, isValidTraceId, newId, random32, setCookie as coreSetCookie, strTrim, toISOString, uaDisallowsSameSiteNone + IDiagnosticLogger, IDistributedTraceContext, arrForEach, arrIndexOf, dateNow, getPerformance, isNullOrUndefined, isValidSpanId, + isValidTraceId } from "@microsoft/applicationinsights-core-js"; -import { DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, strNotSpecified } from "./Constants"; -import { createDomEvent } from "./DomHelperFuncs"; -import { getExtensionByName, isCrossOriginError, msToTimeSpan, stringToBoolOrDefault } from "./HelperFuncs"; +import { DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH } from "./Constants"; import { ITelemetryTrace } from "./Interfaces/Context/ITelemetryTrace"; import { ICorrelationConfig } from "./Interfaces/ICorrelationConfig"; import { RequestHeaders, eRequestHeaders } from "./RequestResponseHeaders"; -import { - utlCanUseLocalStorage, utlCanUseSessionStorage, utlDisableStorage, utlGetLocalStorage, utlGetSessionStorage, utlGetSessionStorageKeys, - utlRemoveSessionStorage, utlRemoveStorage, utlSetLocalStorage, utlSetSessionStorage -} from "./StorageHelperFuncs"; import { dataSanitizeString } from "./Telemetry/Common/DataSanitizer"; -import { urlGetAbsoluteUrl, urlGetCompleteUrl, urlGetPathName, urlParseFullHost, urlParseHost, urlParseUrl } from "./UrlHelperFuncs"; +import { urlParseFullHost, urlParseUrl } from "./UrlHelperFuncs"; // listing only non-geo specific locations const _internalEndpoints: string[] = [ @@ -27,394 +19,107 @@ const _internalEndpoints: string[] = [ "https://dc-int.services.visualstudio.com" + DEFAULT_BREEZE_PATH ]; +let _correlationIdPrefix: string = "cid-v1:"; + export function isInternalApplicationInsightsEndpoint(endpointUrl: string): boolean { return arrIndexOf(_internalEndpoints, endpointUrl.toLowerCase()) !== -1; } -export interface IUtil { - NotSpecified: string, - - createDomEvent: (eventName: string) => Event, - - /* - * Force the SDK not to use local and session storage - */ - disableStorage: () => void, - - /** - * Checks if endpoint URL is application insights internal injestion service URL. - * - * @param endpointUrl Endpoint URL to check. - * @returns {boolean} True if if endpoint URL is application insights internal injestion service URL. - */ - isInternalApplicationInsightsEndpoint: (endpointUrl: string) => boolean, - - /** - * Check if the browser supports local storage. - * - * @returns {boolean} True if local storage is supported. - */ - canUseLocalStorage: () => boolean, - - /** - * Get an object from the browser's local storage - * - * @param {string} name - the name of the object to get from storage - * @returns {string} The contents of the storage object with the given name. Null if storage is not supported. - */ - getStorage: (logger: IDiagnosticLogger, name: string) => string, - - /** - * Set the contents of an object in the browser's local storage - * - * @param {string} name - the name of the object to set in storage - * @param {string} data - the contents of the object to set in storage - * @returns {boolean} True if the storage object could be written. - */ - setStorage: (logger: IDiagnosticLogger, name: string, data: string) => boolean, - - /** - * Remove an object from the browser's local storage - * - * @param {string} name - the name of the object to remove from storage - * @returns {boolean} True if the storage object could be removed. - */ - removeStorage: (logger: IDiagnosticLogger, name: string) => boolean, - - /** - * Check if the browser supports session storage. - * - * @returns {boolean} True if session storage is supported. - */ - canUseSessionStorage: () => boolean, - - /** - * Gets the list of session storage keys - * - * @returns {string[]} List of session storage keys - */ - getSessionStorageKeys: () => string[], - - /** - * Get an object from the browser's session storage - * - * @param {string} name - the name of the object to get from storage - * @returns {string} The contents of the storage object with the given name. Null if storage is not supported. - */ - getSessionStorage: (logger: IDiagnosticLogger, name: string) => string, - - /** - * Set the contents of an object in the browser's session storage - * - * @param {string} name - the name of the object to set in storage - * @param {string} data - the contents of the object to set in storage - * @returns {boolean} True if the storage object could be written. - */ - setSessionStorage: (logger: IDiagnosticLogger, name: string, data: string) => boolean, - - /** - * Remove an object from the browser's session storage - * - * @param {string} name - the name of the object to remove from storage - * @returns {boolean} True if the storage object could be removed. - */ - removeSessionStorage: (logger: IDiagnosticLogger, name: string) => boolean, - - /** - * @deprecated - Use the core.getCookieMgr().disable() - * Force the SDK not to store and read any data from cookies. - */ - disableCookies: () => void, - - /** - * @deprecated - Use the core.getCookieMgr().isEnabled() - * Helper method to tell if document.cookie object is available and whether it can be used. - */ - canUseCookies: (logger: IDiagnosticLogger) => any, - - disallowsSameSiteNone: (userAgent: string) => boolean, - - /** - * @deprecated - Use the core.getCookieMgr().set() - * helper method to set userId and sessionId cookie - */ - setCookie: (logger: IDiagnosticLogger, name: string, value: string, domain?: string) => void, - - stringToBoolOrDefault: (str: any, defaultValue?: boolean) => boolean, - - /** - * @deprecated - Use the core.getCookieMgr().get() - * helper method to access userId and sessionId cookie - */ - getCookie: (logger: IDiagnosticLogger, name: string) => string, - - /** - * @deprecated - Use the core.getCookieMgr().del() - * Deletes a cookie by setting it's expiration time in the past. - * @param name - The name of the cookie to delete. - */ - deleteCookie: (logger: IDiagnosticLogger, name: string) => void, - - /** - * helper method to trim strings (IE8 does not implement String.prototype.trim) - */ - trim: (str: any) => string, - - /** - * generate random id string - */ - newId: () => string, - - /** - * generate a random 32bit number (-0x80000000..0x7FFFFFFF). - */ - random32: () => number, - - /** - * generate W3C trace id - */ - generateW3CId: () => string, - - /** - * Check if an object is of type Array - */ - isArray: (obj: any) => boolean, - - /** - * Check if an object is of type Error - */ - isError: (obj: any) => obj is Error, - - /** - * Check if an object is of type Date - */ - isDate: (obj: any) => obj is Date, - - // Keeping this name for backward compatibility (for now) - toISOStringForIE8: (date: Date) => string, - - /** - * Gets IE version returning the document emulation mode if we are running on IE, or null otherwise - */ - getIEVersion: (userAgentStr?: string) => number, - - /** - * Convert ms to c# time span format - */ - msToTimeSpan: (totalms: number) => string, - - /** - * Checks if error has no meaningful data inside. Ususally such errors are received by window.onerror when error - * happens in a script from other domain (cross origin, CORS). - */ - isCrossOriginError: (message: string|Event, url: string, lineNumber: number, columnNumber: number, error: Error) => boolean, - - /** - * Returns string representation of an object suitable for diagnostics logging. - */ - dump: (object: any) => string, - - /** - * Returns the name of object if it's an Error. Otherwise, returns empty string. - */ - getExceptionName: (object: any) => string, - - /** - * Adds an event handler for the specified event to the window - * @param eventName {string} - The name of the event - * @param callback {any} - The callback function that needs to be executed for the given event - * @return {boolean} - true if the handler was successfully added - */ - addEventHandler: (obj: any, eventNameWithoutOn: string, handlerRef: any, useCapture: boolean) => boolean, - - /** - * Tells if a browser supports a Beacon API - */ - IsBeaconApiSupported: () => boolean, - - getExtension: (extensions: IPlugin[], identifier: string) => IPlugin | null +export function correlationIdSetPrefix(prefix: string) { + _correlationIdPrefix = prefix; } -export const Util: IUtil = { - NotSpecified: strNotSpecified, - createDomEvent, - disableStorage: utlDisableStorage, - isInternalApplicationInsightsEndpoint, - canUseLocalStorage: utlCanUseLocalStorage, - getStorage: utlGetLocalStorage, - setStorage: utlSetLocalStorage, - removeStorage: utlRemoveStorage, - canUseSessionStorage: utlCanUseSessionStorage, - getSessionStorageKeys: utlGetSessionStorageKeys, - getSessionStorage: utlGetSessionStorage, - setSessionStorage: utlSetSessionStorage, - removeSessionStorage: utlRemoveSessionStorage, - disableCookies: coreDisableCookies, - canUseCookies: coreCanUseCookies, - disallowsSameSiteNone: uaDisallowsSameSiteNone, - setCookie: coreSetCookie, - stringToBoolOrDefault, - getCookie: coreGetCookie, - deleteCookie: coreDeleteCookie, - trim: strTrim, - newId, - random32() { - return random32(true); - }, - generateW3CId, - isArray, - isError, - isDate, - toISOStringForIE8: toISOString, - getIEVersion, - msToTimeSpan, - isCrossOriginError, - dump: dumpObj, - getExceptionName: coreGetExceptionName, - addEventHandler: attachEvent, - IsBeaconApiSupported: isBeaconsSupported, - getExtension: getExtensionByName -}; - -export interface IUrlHelper { - - parseUrl: (url: string) => HTMLAnchorElement, - getAbsoluteUrl: (url: string) => string, - getPathName: (url: string) => string, - getCompleteUrl: (method: string, absoluteUrl: string) => string, - - // Fallback method to grab host from url if document.createElement method is not available - parseHost: (url: string, inclPort?: boolean) => string, - - /** - * Get the full host from the url, optionally including the port - */ - parseFullHost: (url: string, inclPort?: boolean) => string +export function correlationIdGetPrefix() { + return _correlationIdPrefix; } -export const UrlHelper: IUrlHelper = { - parseUrl: urlParseUrl, - getAbsoluteUrl: urlGetAbsoluteUrl, - getPathName: urlGetPathName, - getCompleteUrl: urlGetCompleteUrl, - parseHost: urlParseHost, - parseFullHost: urlParseFullHost -}; +/** + * Checks if a request url is not on a excluded domain list and if it is safe to add correlation headers. + * Headers are always included if the current domain matches the request domain. If they do not match (CORS), + * they are regex-ed across correlationHeaderDomains and correlationHeaderExcludedDomains to determine if headers are included. + * Some environments don't give information on currentHost via window.location.host (e.g. Cordova). In these cases, the user must + * manually supply domains to include correlation headers on. Else, no headers will be included at all. + */ +export function correlationIdCanIncludeCorrelationHeader(config: ICorrelationConfig, requestUrl: string, currentHost?: string) { + if (!requestUrl || (config && config.disableCorrelationHeaders)) { + return false; + } -export interface ICorrelationIdHelper { - correlationIdPrefix: string; - - /** - * Checks if a request url is not on a excluded domain list and if it is safe to add correlation headers. - * Headers are always included if the current domain matches the request domain. If they do not match (CORS), - * they are regex-ed across correlationHeaderDomains and correlationHeaderExcludedDomains to determine if headers are included. - * Some environments don't give information on currentHost via window.location.host (e.g. Cordova). In these cases, the user must - * manually supply domains to include correlation headers on. Else, no headers will be included at all. - */ - canIncludeCorrelationHeader(config: ICorrelationConfig, requestUrl: string, currentHost?: string): boolean; - - /** - * Combines target appId and target role name from response header. - */ - getCorrelationContext(responseHeader: string): string | undefined; - - /** - * Gets key from correlation response header - */ - getCorrelationContextValue(responseHeader: string, key: string): string | undefined; -} - -export const CorrelationIdHelper: ICorrelationIdHelper = { - correlationIdPrefix: "cid-v1:", - - /** - * Checks if a request url is not on a excluded domain list and if it is safe to add correlation headers. - * Headers are always included if the current domain matches the request domain. If they do not match (CORS), - * they are regex-ed across correlationHeaderDomains and correlationHeaderExcludedDomains to determine if headers are included. - * Some environments don't give information on currentHost via window.location.host (e.g. Cordova). In these cases, the user must - * manually supply domains to include correlation headers on. Else, no headers will be included at all. - */ - canIncludeCorrelationHeader(config: ICorrelationConfig, requestUrl: string, currentHost?: string) { - if (!requestUrl || (config && config.disableCorrelationHeaders)) { - return false; - } - - if (config && config.correlationHeaderExcludePatterns) { - for (let i = 0; i < config.correlationHeaderExcludePatterns.length; i++) { - if (config.correlationHeaderExcludePatterns[i].test(requestUrl)) { - return false; - } - } - } - - let requestHost = urlParseUrl(requestUrl).host.toLowerCase(); - if (requestHost && (requestHost.indexOf(":443") !== -1 || requestHost.indexOf(":80") !== -1)) { - // [Bug #1260] IE can include the port even for http and https URLs so if present - // try and parse it to remove if it matches the default protocol port - requestHost = (urlParseFullHost(requestUrl, true) || "").toLowerCase(); - } - - if ((!config || !config.enableCorsCorrelation) && (requestHost && requestHost !== currentHost)) { - return false; - } - - const includedDomains = config && config.correlationHeaderDomains; - if (includedDomains) { - let matchExists: boolean; - arrForEach(includedDomains, (domain) => { - const regex = new RegExp(domain.toLowerCase().replace(/\\/g, "\\\\").replace(/\./g, "\\.").replace(/\*/g, ".*")); - matchExists = matchExists || regex.test(requestHost); - }); - - if (!matchExists) { + if (config && config.correlationHeaderExcludePatterns) { + for (let i = 0; i < config.correlationHeaderExcludePatterns.length; i++) { + if (config.correlationHeaderExcludePatterns[i].test(requestUrl)) { return false; } } - - const excludedDomains = config && config.correlationHeaderExcludedDomains; - if (!excludedDomains || excludedDomains.length === 0) { - return true; - } - - for (let i = 0; i < excludedDomains.length; i++) { - const regex = new RegExp(excludedDomains[i].toLowerCase().replace(/\\/g, "\\\\").replace(/\./g, "\\.").replace(/\*/g, ".*")); - if (regex.test(requestHost)) { - return false; - } - } - - // if we don't know anything about the requestHost, require the user to use included/excludedDomains. - // Previously we always returned false for a falsy requestHost - return requestHost && requestHost.length > 0; - }, - - /** - * Combines target appId and target role name from response header. - */ - getCorrelationContext(responseHeader: string) { - if (responseHeader) { - const correlationId = CorrelationIdHelper.getCorrelationContextValue(responseHeader, RequestHeaders[eRequestHeaders.requestContextTargetKey]); - if (correlationId && correlationId !== CorrelationIdHelper.correlationIdPrefix) { - return correlationId; - } - } - }, - - /** - * Gets key from correlation response header - */ - getCorrelationContextValue(responseHeader: string, key: string) { - if (responseHeader) { - const keyValues = responseHeader.split(","); - for (let i = 0; i < keyValues.length; ++i) { - const keyValue = keyValues[i].split("="); - if (keyValue.length === 2 && keyValue[0] === key) { - return keyValue[1]; - } - } - } } -}; + + let requestHost = urlParseUrl(requestUrl).host.toLowerCase(); + if (requestHost && (requestHost.indexOf(":443") !== -1 || requestHost.indexOf(":80") !== -1)) { + // [Bug #1260] IE can include the port even for http and https URLs so if present + // try and parse it to remove if it matches the default protocol port + requestHost = (urlParseFullHost(requestUrl, true) || "").toLowerCase(); + } + + if ((!config || !config.enableCorsCorrelation) && (requestHost && requestHost !== currentHost)) { + return false; + } + + const includedDomains = config && config.correlationHeaderDomains; + if (includedDomains) { + let matchExists: boolean; + arrForEach(includedDomains, (domain) => { + const regex = new RegExp(domain.toLowerCase().replace(/\\/g, "\\\\").replace(/\./g, "\\.").replace(/\*/g, ".*")); + matchExists = matchExists || regex.test(requestHost); + }); + + if (!matchExists) { + return false; + } + } + + const excludedDomains = config && config.correlationHeaderExcludedDomains; + if (!excludedDomains || excludedDomains.length === 0) { + return true; + } + + for (let i = 0; i < excludedDomains.length; i++) { + const regex = new RegExp(excludedDomains[i].toLowerCase().replace(/\\/g, "\\\\").replace(/\./g, "\\.").replace(/\*/g, ".*")); + if (regex.test(requestHost)) { + return false; + } + } + + // if we don't know anything about the requestHost, require the user to use included/excludedDomains. + // Previously we always returned false for a falsy requestHost + return requestHost && requestHost.length > 0; +} + +/** + * Combines target appId and target role name from response header. + */ +export function correlationIdGetCorrelationContext(responseHeader: string) { + if (responseHeader) { + const correlationId = correlationIdGetCorrelationContextValue(responseHeader, RequestHeaders[eRequestHeaders.requestContextTargetKey]); + if (correlationId && correlationId !== _correlationIdPrefix) { + return correlationId; + } + } +} + +/** + * Gets key from correlation response header + */ +export function correlationIdGetCorrelationContextValue(responseHeader: string, key: string) { + if (responseHeader) { + const keyValues = responseHeader.split(","); + for (let i = 0; i < keyValues.length; ++i) { + const keyValue = keyValues[i].split("="); + if (keyValue.length === 2 && keyValue[0] === key) { + return keyValue[1]; + } + } + } +} export function AjaxHelperParseDependencyPath(logger: IDiagnosticLogger, absoluteUrl: string, method: string, commandName: string) { let target, name = commandName, data = commandName; @@ -469,27 +174,6 @@ export function dateTimeUtilsDuration(start: number, end: number): number { return result; } -export interface IDateTimeUtils { - /** - * Get the number of milliseconds since 1970/01/01 in local timezone - */ - Now: () => number; - - /** - * Gets duration between two timestamps - */ - GetDuration: (start: number, end: number) => number; -} - -/** - * A utility class that helps getting time related parameters - */ -export const DateTimeUtils: IDateTimeUtils = { - Now: dateTimeUtilsNow, - GetDuration: dateTimeUtilsDuration -}; - - /** * Creates a IDistributedTraceContext from an optional telemetryTrace * @param telemetryTrace - The telemetryTrace instance that is being wrapped diff --git a/shared/AppInsightsCommon/src/applicationinsights-common.ts b/shared/AppInsightsCommon/src/applicationinsights-common.ts index 684bbebd..f6045ea7 100644 --- a/shared/AppInsightsCommon/src/applicationinsights-common.ts +++ b/shared/AppInsightsCommon/src/applicationinsights-common.ts @@ -1,9 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the export { - IUtil, Util, ICorrelationIdHelper, CorrelationIdHelper, - IDateTimeUtils, DateTimeUtils, dateTimeUtilsNow, dateTimeUtilsDuration, - IUrlHelper, UrlHelper, isInternalApplicationInsightsEndpoint, + correlationIdSetPrefix, correlationIdGetPrefix, correlationIdCanIncludeCorrelationHeader, correlationIdGetCorrelationContext, + correlationIdGetCorrelationContextValue, dateTimeUtilsNow, dateTimeUtilsDuration, isInternalApplicationInsightsEndpoint, createDistributedTraceContextFromTrace } from "./Util"; export { parseConnectionString, ConnectionStringParser } from "./ConnectionStringParser"; @@ -36,7 +35,7 @@ export { IConfig, ConfigurationManager } from "./Interfaces/IConfig"; export { IChannelControlsAI } from "./Interfaces/IChannelControlsAI"; export { IContextTagKeys, ContextTagKeys } from "./Interfaces/Contracts/ContextTagKeys"; export { - DataSanitizerValues, IDataSanitizer, DataSanitizer, + DataSanitizerValues, dataSanitizeKeyAndAddUniqueness, dataSanitizeKey, dataSanitizeString, dataSanitizeUrl, dataSanitizeMessage, dataSanitizeException, dataSanitizeProperties, dataSanitizeMeasurements, dataSanitizeId, dataSanitizeInput, dsPadNumber diff --git a/shared/AppInsightsCommon/tsconfig.json b/shared/AppInsightsCommon/tsconfig.json index 0d4631d7..ddb6f30a 100644 --- a/shared/AppInsightsCommon/tsconfig.json +++ b/shared/AppInsightsCommon/tsconfig.json @@ -5,7 +5,7 @@ "noImplicitAny": true, "module": "es6", "moduleResolution": "Node", - "target": "es3", + "target": "es5", "alwaysStrict": true, "suppressImplicitAnyIndexErrors": true, "allowSyntheticDefaultImports": true, diff --git a/shared/AppInsightsCore/README.md b/shared/AppInsightsCore/README.md index 5ac7e7bf..7ee58df2 100644 --- a/shared/AppInsightsCore/README.md +++ b/shared/AppInsightsCore/README.md @@ -6,6 +6,13 @@ Core SDK layer for next version of application insights javascript SDK. +## Beta Release Breaking changes + +- Removed ES3 / IE8 Support +- Removed V1 API Backward Compatibility (Upgrading V1 -> V3) + +See [Breaking Changes](./BETA_BREAKING_CHANGES.md) + ## Build & Test: - Install: `$ npm install` - Build: `$ npm run build` diff --git a/shared/AppInsightsCore/Tests/Unit/src/ApplicationInsightsCore.Tests.ts b/shared/AppInsightsCore/Tests/Unit/src/ApplicationInsightsCore.Tests.ts index 7ab934d1..c3846b76 100644 --- a/shared/AppInsightsCore/Tests/Unit/src/ApplicationInsightsCore.Tests.ts +++ b/shared/AppInsightsCore/Tests/Unit/src/ApplicationInsightsCore.Tests.ts @@ -1,5 +1,5 @@ import { Assert, AITestClass } from "@microsoft/ai-test-framework"; -import { IConfiguration, ITelemetryPlugin, ITelemetryItem, IPlugin, CoreUtils, IAppInsightsCore, normalizeJsName, random32, mwcRandomSeed } from "../../../src/applicationinsights-core-js" +import { IConfiguration, ITelemetryPlugin, ITelemetryItem, IPlugin, IAppInsightsCore, normalizeJsName, random32, mwcRandomSeed, newId, randomValue, mwcRandom32, isNullOrUndefined } from "../../../src/applicationinsights-core-js" import { AppInsightsCore } from "../../../src/JavaScriptSDK/AppInsightsCore"; import { IChannelControls } from "../../../src/JavaScriptSDK.Interfaces/IChannelControls"; import { _InternalMessageId, LoggingSeverity } from "../../../src/JavaScriptSDK.Enums/LoggingEnums"; @@ -521,7 +521,7 @@ export class ApplicationInsightsCoreTests extends AITestClass { []); Assert.ok(channelPlugin1._nextPlugin === channelPlugin2); - Assert.ok(CoreUtils.isNullOrUndefined(channelPlugin3._nextPlugin)); + Assert.ok(isNullOrUndefined(channelPlugin3._nextPlugin)); const channelControls = appInsightsCore.getTransmissionControls(); Assert.ok(channelControls.length === 2); Assert.ok(channelControls[0].length === 2); @@ -554,7 +554,7 @@ export class ApplicationInsightsCoreTests extends AITestClass { Assert.ok(channelPlugin1._nextPlugin === channelPlugin2); Assert.ok(channelPlugin2._nextPlugin === channelPlugin3); - Assert.ok(CoreUtils.isNullOrUndefined(channelPlugin3._nextPlugin)); + Assert.ok(isNullOrUndefined(channelPlugin3._nextPlugin)); const channelControls = appInsightsCore.getTransmissionControls(); Assert.ok(channelControls.length === 1); Assert.ok(channelControls[0].length === 3); @@ -654,16 +654,16 @@ export class ApplicationInsightsCoreTests extends AITestClass { this.testCase({ name: 'newId tests length', test: () => { - _checkNewId(5, CoreUtils.newId(5), "Test the previous length"); - _checkNewId(10, CoreUtils.newId(10), "Test the double the previous length"); - _checkNewId(22, CoreUtils.newId(), "Test new default length"); - _checkNewId(99, CoreUtils.newId(99), "Test 99 character == 74.25 bytes"); - _checkNewId(200, CoreUtils.newId(200), "Test 200 character == 150 bytes"); + _checkNewId(5, newId(5), "Test the previous length"); + _checkNewId(10, newId(10), "Test the double the previous length"); + _checkNewId(22, newId(), "Test new default length"); + _checkNewId(99, newId(99), "Test 99 character == 74.25 bytes"); + _checkNewId(200, newId(200), "Test 200 character == 150 bytes"); // Check the id is not zero filled ("A") based on the an int32 === 5 base64 bytes (plus 2 bits) - let newId = CoreUtils.newId(); - Assert.notEqual("AAAAAAAAAAAAAAAA", newId.substring(0, 16), "Make sure that [" + newId + "] value is not zero filled (generally -- it is randomly possible)") - Assert.notEqual("AAAAAAAAAAAAAAAA", newId.substring(5), "Make sure that [" + newId + "] value is not zero filled (generally -- it is randomly possible)") + let theNewId = newId(); + Assert.notEqual("AAAAAAAAAAAAAAAA", theNewId.substring(0, 16), "Make sure that [" + theNewId + "] value is not zero filled (generally -- it is randomly possible)") + Assert.notEqual("AAAAAAAAAAAAAAAA", theNewId.substring(5), "Make sure that [" + theNewId + "] value is not zero filled (generally -- it is randomly possible)") } }); @@ -682,12 +682,12 @@ export class ApplicationInsightsCoreTests extends AITestClass { mwcRandomSeed(); for (let lp = 0; lp < 10000; lp ++) { - let newId = CoreUtils.newId(); - if (map[newId]) { - Assert.ok(false, "[" + newId + "] was duplicated...") + let theNewId = newId(); + if (map[theNewId]) { + Assert.ok(false, "[" + theNewId + "] was duplicated...") } - map[newId] = true; + map[theNewId] = true; } mwcRandomSeed(1); @@ -715,12 +715,12 @@ export class ApplicationInsightsCoreTests extends AITestClass { Assert.notEqual(722346555, random32(), "Make sure that the mwcRandom was being called - step 3"); for (let lp = 0; lp < 10000; lp ++) { - let newId = CoreUtils.newId(); - if (map[newId]) { - Assert.ok(false, "[" + newId + "] was duplicated...") + let theNewId = newId(); + if (map[theNewId]) { + Assert.ok(false, "[" + theNewId + "] was duplicated...") } - map[newId] = true; + map[theNewId] = true; } // Reset the seed and re-check the expected result @@ -738,7 +738,7 @@ export class ApplicationInsightsCoreTests extends AITestClass { let runs = 1000000; for (let lp = 0; lp < runs; lp++) { - const bucket = CoreUtils.randomValue(numBuckets-1); + const bucket = randomValue(numBuckets-1); buckets[bucket] ++; } @@ -780,7 +780,7 @@ export class ApplicationInsightsCoreTests extends AITestClass { for (let lp = 0; lp < runs; lp++) { // Need to use floor otherwise the bucket is defined as a float as the index - const bucket = Math.floor((CoreUtils.random32() / MaxInt32) * numBuckets); + const bucket = Math.floor((random32() / MaxInt32) * numBuckets); buckets[bucket] ++; } @@ -822,7 +822,7 @@ export class ApplicationInsightsCoreTests extends AITestClass { for (let lp = 0; lp < runs; lp++) { // Need to use floor otherwise the bucket is defined as a float as the index - const bucket = Math.floor((CoreUtils.mwcRandom32() / MaxInt32) * numBuckets); + const bucket = Math.floor((mwcRandom32() / MaxInt32) * numBuckets); buckets[bucket] ++; } diff --git a/shared/AppInsightsCore/Tests/Unit/src/CookieManager.Tests.ts b/shared/AppInsightsCore/Tests/Unit/src/CookieManager.Tests.ts index edd249d9..e2936935 100644 --- a/shared/AppInsightsCore/Tests/Unit/src/CookieManager.Tests.ts +++ b/shared/AppInsightsCore/Tests/Unit/src/CookieManager.Tests.ts @@ -1,5 +1,5 @@ import { Assert, AITestClass } from "@microsoft/ai-test-framework"; -import { AppInsightsCore, CoreUtils, createCookieMgr, IAppInsightsCore, IConfiguration, ICookieMgrConfig, IPlugin, ITelemetryItem, newId, _legacyCookieMgr } from "../../../src/applicationinsights-core-js" +import { AppInsightsCore, createCookieMgr, IAppInsightsCore, IConfiguration, ICookieMgrConfig, IPlugin, ITelemetryItem, newId } from "../../../src/applicationinsights-core-js" import { _InternalMessageId, LoggingSeverity } from "../../../src/JavaScriptSDK.Enums/LoggingEnums"; import { _InternalLogMessage, DiagnosticLogger } from "../../../src/JavaScriptSDK/DiagnosticLogger"; @@ -10,8 +10,8 @@ export class CookieManagerTests extends AITestClass { }; private _testCookies = {}; - constructor(emulateEs3: boolean) { - super("CookieManagerTests", emulateEs3); + constructor(emulateIe: boolean) { + super("CookieManagerTests", emulateIe); } public testInitialize() { @@ -185,7 +185,7 @@ export class CookieManagerTests extends AITestClass { let maxAge = 42 * 24 * 60 * 60; manager.set(newKey, newValue, maxAge); Assert.equal(newValue, manager.get(newKey)); - if (this.isEmulatingEs3) { + if (this.isEmulatingIe) { Assert.equal(newValue + "; expires=Thu, 12 Feb 1970 00:00:00 GMT; path=/", this._testCookies[newKey]); } else { Assert.equal(newValue + "; expires=Thu, 12 Feb 1970 00:00:00 GMT; max-age=" + maxAge + "; path=/", this._testCookies[newKey]); @@ -198,7 +198,7 @@ export class CookieManagerTests extends AITestClass { manager.set(newKey, newValue + "; expires=Thu, 12 Feb 2170 00:00:00 GMT", maxAge); Assert.equal(newValue, manager.get(newKey)); - if (this.isEmulatingEs3) { + if (this.isEmulatingIe) { Assert.equal(newValue + "; expires=Thu, 12 Feb 2170 00:00:00 GMT; path=/", this._testCookies[newKey]); } else { Assert.equal(newValue + "; expires=Thu, 12 Feb 2170 00:00:00 GMT; max-age=" + maxAge + "; path=/", this._testCookies[newKey]); @@ -395,38 +395,6 @@ export class CookieManagerTests extends AITestClass { Assert.equal(undefined, this._testCookies[newKey]); } }); - - - this.testCase({ - name: "CookieManager: validate setting _canUseCookies correctly enables or blocks cookie usage", - test: () => { - CoreUtils._canUseCookies = undefined; - // initialize the global cookie manager - let globalMgr = _legacyCookieMgr(); - Assert.equal(true, globalMgr.isEnabled()); - Assert.equal(true, globalMgr.isEnabled()); - CoreUtils._canUseCookies = false; - Assert.equal(false, globalMgr.isEnabled()); - CoreUtils._canUseCookies = true; - Assert.equal(true, globalMgr.isEnabled()); - - let core = new AppInsightsCore(); - let manager = core.getCookieMgr(); - manager.setEnabled(true); - Assert.equal(true, manager.isEnabled()); - CoreUtils._canUseCookies = false; - Assert.equal(false, manager.isEnabled()); - - manager.setEnabled(false); - CoreUtils._canUseCookies = true; - Assert.equal(true, globalMgr.isEnabled()); - Assert.equal(false, manager.isEnabled()); - - manager.setEnabled(true); - Assert.equal(true, globalMgr.isEnabled()); - Assert.equal(true, manager.isEnabled()); - } - }); } } diff --git a/shared/AppInsightsCore/Tests/Unit/src/HelperFunc.Tests.ts b/shared/AppInsightsCore/Tests/Unit/src/HelperFunc.Tests.ts index e41117fa..ac687221 100644 --- a/shared/AppInsightsCore/Tests/Unit/src/HelperFunc.Tests.ts +++ b/shared/AppInsightsCore/Tests/Unit/src/HelperFunc.Tests.ts @@ -1,9 +1,21 @@ import { Assert, AITestClass } from "@microsoft/ai-test-framework"; import { _InternalMessageId } from "../../../src/JavaScriptSDK.Enums/LoggingEnums"; import { _InternalLogMessage } from "../../../src/JavaScriptSDK/DiagnosticLogger"; -import { normalizeJsName, objExtend, strEndsWith, _strEndsWithPoly, strStartsWith, _strStartsWithPoly, isObject, objKeys, _getObjProto, isPlainObject, dateNow, isArray } from "../../../src/JavaScriptSDK/HelperFuncs"; +import { normalizeJsName, objExtend, _getObjProto, isPlainObject, dateNow } from "../../../src/JavaScriptSDK/HelperFuncs"; import { BaseCore } from "../../../src/JavaScriptSDK/BaseCore"; import { AppInsightsCore } from "../../../src/JavaScriptSDK/AppInsightsCore"; +import { isArray, isObject, objKeys, strEndsWith, strStartsWith } from "@nevware21/ts-utils"; +import { dumpObj } from "../../../src/applicationinsights-core-js"; + + +function _expectException(cb: () => void) { + try { + cb(); + Assert.ok(false, "Expected and exception to be thrown"); + } catch(e) { + Assert.ok(true, "Expected an exception - " + dumpObj(e)); + } +} export class HelperFuncTests extends AITestClass { @@ -20,13 +32,17 @@ export class HelperFuncTests extends AITestClass { this.testCase({ name: "strEndsWith", test: () => { - Assert.ok(!strEndsWith(null, null)); + _expectException(() => { + Assert.ok(!strEndsWith(null, null)); + }); Assert.ok(!strEndsWith("", null)); - Assert.ok(!strEndsWith(null, "")); - Assert.ok(!strEndsWith("", "")); + _expectException(() => { + Assert.ok(!strEndsWith(null, "")); + }); + Assert.ok(strEndsWith("", "")); Assert.ok(!strEndsWith("", "a")); Assert.ok(!strEndsWith("a", "b")); - Assert.ok(!strEndsWith("a", "")); + Assert.ok(strEndsWith("a", "")); Assert.ok(!strEndsWith("a", "ab")); Assert.ok(strEndsWith("a", "a")); Assert.ok(strEndsWith("ba", "a")); @@ -37,35 +53,19 @@ export class HelperFuncTests extends AITestClass { } }); - this.testCase({ - name: "_strEndsWithPoly", - test: () => { - Assert.ok(!_strEndsWithPoly(null, null)); - Assert.ok(!_strEndsWithPoly("", null)); - Assert.ok(!_strEndsWithPoly(null, "")); - Assert.ok(!_strEndsWithPoly("", "")); - Assert.ok(!_strEndsWithPoly("", "a")); - Assert.ok(!_strEndsWithPoly("a", "b")); - Assert.ok(!_strEndsWithPoly("a", "")); - Assert.ok(!_strEndsWithPoly("a", "ab")); - Assert.ok(_strEndsWithPoly("a", "a")); - Assert.ok(_strEndsWithPoly("ba", "a")); - Assert.ok(_strEndsWithPoly("zyxyvutsrqponmlkjihgfedcba", "cba")); - Assert.ok(!_strEndsWithPoly("a", "ba")); - Assert.ok(!_strEndsWithPoly("abba", "cba")); - Assert.ok(!_strEndsWithPoly("abba", "bb")); - } - }); - this.testCase({ name: "strStartsWith", test: () => { - Assert.ok(!strStartsWith(null, null)); - Assert.ok(!strStartsWith("", null)); - Assert.ok(!strStartsWith(null, "")); - Assert.ok(!strStartsWith("", "")); + _expectException(() => { + Assert.ok(!strStartsWith(null as any, null as any)); + }); + Assert.ok(!strStartsWith("", null as any)); + _expectException(() => { + Assert.ok(!strStartsWith(null as any, "")); + }); + Assert.ok(strStartsWith("", "")); Assert.ok(!strStartsWith("", "a")); - Assert.ok(!strStartsWith("a", "")); + Assert.ok(strStartsWith("a", "")); Assert.ok(!strStartsWith("a", "b")); Assert.ok(!strStartsWith("a", "ba")); Assert.ok(strStartsWith("ab", "a")); @@ -77,26 +77,6 @@ export class HelperFuncTests extends AITestClass { } }); - this.testCase({ - name: "_strStartsWithPoly", - test: () => { - Assert.ok(!_strStartsWithPoly(null, null)); - Assert.ok(!_strStartsWithPoly("", null)); - Assert.ok(!_strStartsWithPoly(null, "")); - Assert.ok(!_strStartsWithPoly("", "")); - Assert.ok(!_strStartsWithPoly("", "a")); - Assert.ok(!_strStartsWithPoly("a", "")); - Assert.ok(!_strStartsWithPoly("a", "b")); - Assert.ok(!_strStartsWithPoly("a", "ba")); - Assert.ok(_strStartsWithPoly("ab", "a")); - Assert.ok(!_strStartsWithPoly("zyxyvutsrqponmlkjihgfedcba", "a")); - Assert.ok(_strStartsWithPoly("zyxwvutsrqponmlkjihgfedcba", "zyxw")); - Assert.ok(!_strStartsWithPoly("a", "ab")); - Assert.ok(!_strStartsWithPoly("abba", "abc")); - Assert.ok(!_strStartsWithPoly("abba", "bb")); - } - }); - this.testCase({ name: 'default objExtend (shallow)', test: () => { @@ -342,8 +322,12 @@ export class HelperFuncTests extends AITestClass { this.testCase({ name: "_getObjProto", test: () => { - Assert.equal(null, _getObjProto(null)); - Assert.equal(null, _getObjProto(undefined)); + _expectException(() => { + Assert.equal(null, _getObjProto(null)); + }); + _expectException(() => { + Assert.equal(null, _getObjProto(undefined)); + }); Assert.equal(Object.prototype, _getObjProto({})); Assert.equal(Date.prototype, _getObjProto(new Date())); Assert.equal(Number.prototype, _getObjProto(dateNow())); diff --git a/shared/AppInsightsCore/Tests/Unit/src/LoggingEnum.Tests.ts b/shared/AppInsightsCore/Tests/Unit/src/LoggingEnum.Tests.ts index fe4f49c5..b337b617 100644 --- a/shared/AppInsightsCore/Tests/Unit/src/LoggingEnum.Tests.ts +++ b/shared/AppInsightsCore/Tests/Unit/src/LoggingEnum.Tests.ts @@ -1,7 +1,7 @@ import { Assert, AITestClass } from "@microsoft/ai-test-framework"; +import { isString, objForEachKey } from "@nevware21/ts-utils"; import { _InternalMessageId, LoggingSeverity, eLoggingSeverity, _eInternalMessageId } from "../../../src/JavaScriptSDK.Enums/LoggingEnums"; import { _InternalLogMessage } from "../../../src/JavaScriptSDK/DiagnosticLogger"; -import { isString, objForEachKey, objKeys } from "../../../src/JavaScriptSDK/HelperFuncs"; type NoRepeats = { [M in keyof T]: { [N in keyof T]: N extends M ? never : T[M] extends T[N] ? unknown : never diff --git a/shared/AppInsightsCore/package.json b/shared/AppInsightsCore/package.json index 04c38fc0..63aa5701 100644 --- a/shared/AppInsightsCore/package.json +++ b/shared/AppInsightsCore/package.json @@ -40,7 +40,7 @@ "devDependencies": { "@microsoft/ai-test-framework": "0.0.1", "@microsoft/applicationinsights-rollup-plugin-uglify3-js": "1.0.0", - "@microsoft/applicationinsights-rollup-es3": "1.1.3", + "@microsoft/applicationinsights-rollup-es5": "1.0.0", "@microsoft/api-extractor": "^7.18.1", "grunt": "^1.5.3", "grunt-cli": "^1.4.3", @@ -65,6 +65,7 @@ }, "dependencies": { "@microsoft/applicationinsights-shims": "2.0.1", - "@microsoft/dynamicproto-js": "^1.1.6" + "@microsoft/dynamicproto-js": "^1.1.6", + "@nevware21/ts-utils": "^0.4.1" } } diff --git a/shared/AppInsightsCore/rollup.config.js b/shared/AppInsightsCore/rollup.config.js index b458cd8f..5ec7444a 100644 --- a/shared/AppInsightsCore/rollup.config.js +++ b/shared/AppInsightsCore/rollup.config.js @@ -3,7 +3,7 @@ import { uglify } from "@microsoft/applicationinsights-rollup-plugin-uglify3-js" import replace from "@rollup/plugin-replace"; import cleanup from "rollup-plugin-cleanup"; import dynamicRemove from "@microsoft/dynamicproto-js/tools/rollup/node/removedynamic"; -import { es3Poly, es3Check, importCheck } from "@microsoft/applicationinsights-rollup-es3"; +import { es5Poly, es5Check, importCheck } from "@microsoft/applicationinsights-rollup-es5"; import { updateDistEsmFiles } from "../../tools/updateDistEsm/updateDistEsm"; const version = require("./package.json").version; @@ -62,8 +62,8 @@ const browserRollupConfigFactory = isProduction => { preferBuiltins: false }), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; @@ -118,8 +118,8 @@ const nodeUmdRollupConfigFactory = (isProduction) => { importCheck({ exclude: [ "applicationinsights-core-js" ] }), nodeResolve(), doCleanup(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; diff --git a/shared/AppInsightsCore/src/JavaScriptSDK.Enums/EnumHelperFuncs.ts b/shared/AppInsightsCore/src/JavaScriptSDK.Enums/EnumHelperFuncs.ts index 24141f8c..4a80b0aa 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK.Enums/EnumHelperFuncs.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK.Enums/EnumHelperFuncs.ts @@ -1,40 +1,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -import { objForEachKey, deepFreeze } from "../JavaScriptSDK/HelperFuncs"; +import { EnumCls, createEnum, createTypeMap } from "@nevware21/ts-utils"; -export declare type EnumValue = { readonly [key in keyof E]: E[key] }; -export declare type EnumMap = { readonly [key in keyof E extends string ? keyof E : never]: key extends string ? key : keyof E } & I; +export declare type EnumValue = EnumCls; +// export declare type EnumMap = EnumNameMap; /** * Create an enum style object which has both the key => value and value => key mappings * @param values - The values to populate on the new object * @returns */ -export function createEnumStyle(values: { [key in keyof E]: E[keyof E] }): EnumValue { - let enumClass: any = {}; - objForEachKey(values, (field, value) => { - enumClass[field] = value; - enumClass[value] = field; - }); - - return deepFreeze(enumClass); -} - -/** - * Create a 2 index map that maps an enum's key as both the key and value, X["key"] => "key" and X[0] => "keyof 0". - * @param values - The values to populate on the new object - * @returns - */ -export function createEnumMap(values: { [key in keyof E]: E[keyof E] }): EnumMap { - let mapClass: any = {}; - objForEachKey(values, (field, value) => { - mapClass[field] = field; - mapClass[value] = field; - }); - - return deepFreeze(mapClass); -} +export const createEnumStyle: (values: { [key in keyof E]: E[keyof E] }) => EnumValue = createEnum; /** * Create a 2 index map that maps an enum's key and value to the defined map value, X["key"] => mapValue and X[0] => mapValue. @@ -45,12 +22,4 @@ export function createEnumMap(values: { [key in keyof E]: E[keyo * @param values - The values to populate on the new object * @returns */ -export function createValueMap(values: { [key in keyof E]: [ E[keyof E], V[keyof V] ] }): V { - let mapClass: any = {}; - objForEachKey(values, (field, value) => { - mapClass[field] = value[1]; - mapClass[value[0]] = value[1]; - }); - - return deepFreeze(mapClass); -} +export const createValueMap: (values: { [key in keyof E]: [ E[keyof E], V[keyof V] ] }) => V = createTypeMap; diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/AppInsightsCore.ts b/shared/AppInsightsCore/src/JavaScriptSDK/AppInsightsCore.ts index 25e6321c..0b627584 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/AppInsightsCore.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/AppInsightsCore.ts @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import dynamicProto from "@microsoft/dynamicproto-js"; +import { isNullOrUndefined, throwError } from "@nevware21/ts-utils"; import { eEventsDiscardedReason } from "../JavaScriptSDK.Enums/EventsDiscardedReason"; import { IAppInsightsCore } from "../JavaScriptSDK.Interfaces/IAppInsightsCore"; import { IConfiguration } from "../JavaScriptSDK.Interfaces/IConfiguration"; @@ -10,7 +11,6 @@ import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem"; import { IPlugin } from "../JavaScriptSDK.Interfaces/ITelemetryPlugin"; import { BaseCore } from "./BaseCore"; import { DiagnosticLogger } from "./DiagnosticLogger"; -import { isNullOrUndefined, throwError } from "./HelperFuncs"; import { NotificationManager } from "./NotificationManager"; import { doPerf } from "./PerfManager"; diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/BaseCore.ts b/shared/AppInsightsCore/src/JavaScriptSDK/BaseCore.ts index fd427e58..ac5a4ace 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/BaseCore.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/BaseCore.ts @@ -4,6 +4,7 @@ import dynamicProto from "@microsoft/dynamicproto-js"; import { objCreateFn } from "@microsoft/applicationinsights-shims"; +import { arrForEach, arrIndexOf, isFunction, isNullOrUndefined, objFreeze, throwError } from "@nevware21/ts-utils"; import { _eInternalMessageId, eLoggingSeverity } from "../JavaScriptSDK.Enums/LoggingEnums"; import { SendRequestReason } from "../JavaScriptSDK.Enums/SendRequestReason"; import { TelemetryUnloadReason } from "../JavaScriptSDK.Enums/TelemetryUnloadReason"; @@ -32,10 +33,7 @@ import { createCookieMgr } from "./CookieMgr"; import { createUniqueNamespace } from "./DataCacheHelper"; import { getDebugListener } from "./DbgExtensionUtils"; import { DiagnosticLogger, _InternalLogMessage, _throwInternal, _warnToConsole } from "./DiagnosticLogger"; -import { - arrForEach, arrIndexOf, getCfgValue, getSetValue, isFunction, isNullOrUndefined, objExtend, objFreeze, proxyFunctionAs, proxyFunctions, - throwError, toISOString -} from "./HelperFuncs"; +import { getCfgValue, getSetValue, objExtend, proxyFunctionAs, proxyFunctions, toISOString } from "./HelperFuncs"; import { STR_CHANNELS, STR_CREATE_PERF_MGR, STR_DISABLED, STR_EXTENSIONS, STR_EXTENSION_CONFIG } from "./InternalConstants"; import { PerfManager, getGblPerfMgr } from "./PerfManager"; import { diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/BaseTelemetryPlugin.ts b/shared/AppInsightsCore/src/JavaScriptSDK/BaseTelemetryPlugin.ts index 2d8c8611..0627c324 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/BaseTelemetryPlugin.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/BaseTelemetryPlugin.ts @@ -3,6 +3,7 @@ "use strict"; import dynamicProto from "@microsoft/dynamicproto-js"; +import { arrForEach, isArray, isFunction, isNullOrUndefined } from "@nevware21/ts-utils"; import { TelemetryUnloadReason } from "../JavaScriptSDK.Enums/TelemetryUnloadReason"; import { TelemetryUpdateReason } from "../JavaScriptSDK.Enums/TelemetryUpdateReason"; import { IAppInsightsCore } from "../JavaScriptSDK.Interfaces/IAppInsightsCore"; @@ -17,7 +18,7 @@ import { IPlugin, ITelemetryPlugin } from "../JavaScriptSDK.Interfaces/ITelemetr import { ITelemetryPluginChain } from "../JavaScriptSDK.Interfaces/ITelemetryPluginChain"; import { ITelemetryUnloadState } from "../JavaScriptSDK.Interfaces/ITelemetryUnloadState"; import { ITelemetryUpdateState } from "../JavaScriptSDK.Interfaces/ITelemetryUpdateState"; -import { arrForEach, isArray, isFunction, isNullOrUndefined, proxyFunctionAs, setValue } from "./HelperFuncs"; +import { proxyFunctionAs, setValue } from "./HelperFuncs"; import { STR_EXTENSION_CONFIG } from "./InternalConstants"; import { createProcessTelemetryContext, createProcessTelemetryUnloadContext, createProcessTelemetryUpdateContext diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/ChannelController.ts b/shared/AppInsightsCore/src/JavaScriptSDK/ChannelController.ts index c8a36249..d6c1becb 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/ChannelController.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/ChannelController.ts @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. +import { arrForEach, isArray, objFreeze, throwError } from "@nevware21/ts-utils"; import { SendRequestReason } from "../JavaScriptSDK.Enums/SendRequestReason"; import { TelemetryUnloadReason } from "../JavaScriptSDK.Enums/TelemetryUnloadReason"; import { TelemetryUpdateReason } from "../JavaScriptSDK.Enums/TelemetryUpdateReason"; @@ -15,7 +16,6 @@ import { IPlugin } from "../JavaScriptSDK.Interfaces/ITelemetryPlugin"; import { ITelemetryPluginChain } from "../JavaScriptSDK.Interfaces/ITelemetryPluginChain"; import { ITelemetryUnloadState } from "../JavaScriptSDK.Interfaces/ITelemetryUnloadState"; import { ITelemetryUpdateState } from "../JavaScriptSDK.Interfaces/ITelemetryUpdateState"; -import { arrForEach, isArray, objFreeze, throwError } from "./HelperFuncs"; import { createProcessTelemetryContext, createTelemetryProxyChain } from "./ProcessTelemetryContext"; import { initializePlugins } from "./TelemetryHelpers"; diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/CookieMgr.ts b/shared/AppInsightsCore/src/JavaScriptSDK/CookieMgr.ts index 27c12a82..32cf3c73 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/CookieMgr.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/CookieMgr.ts @@ -1,16 +1,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +import { + arrForEach, dumpObj, getDocument, getNavigator, isFunction, isNullOrUndefined, isString, isTruthy, isUndefined, objForEachKey, + strEndsWith, strTrim +} from "@nevware21/ts-utils"; import { _eInternalMessageId, eLoggingSeverity } from "../JavaScriptSDK.Enums/LoggingEnums"; import { IAppInsightsCore } from "../JavaScriptSDK.Interfaces/IAppInsightsCore"; import { IConfiguration } from "../JavaScriptSDK.Interfaces/IConfiguration"; import { ICookieMgr, ICookieMgrConfig } from "../JavaScriptSDK.Interfaces/ICookieMgr"; import { IDiagnosticLogger } from "../JavaScriptSDK.Interfaces/IDiagnosticLogger"; import { _throwInternal } from "./DiagnosticLogger"; -import { dumpObj, getDocument, getLocation, getNavigator, isIE } from "./EnvUtils"; -import { - arrForEach, dateNow, getExceptionName, isFunction, isNotNullOrUndefined, isNullOrUndefined, isString, isTruthy, isUndefined, - objForEachKey, setValue, strContains, strEndsWith, strTrim -} from "./HelperFuncs"; +import { getLocation, isIE } from "./EnvUtils"; +import { dateNow, getExceptionName, isNotNullOrUndefined, setValue, strContains } from "./HelperFuncs"; import { STR_EMPTY } from "./InternalConstants"; const strToGMTString = "toGMTString"; diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/CoreUtils.ts b/shared/AppInsightsCore/src/JavaScriptSDK/CoreUtils.ts index 9be5115e..6531b30c 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/CoreUtils.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/CoreUtils.ts @@ -1,22 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. "use strict"; -import { objCreateFn, strShimUndefined } from "@microsoft/applicationinsights-shims"; -import { IConfiguration } from "../JavaScriptSDK.Interfaces/IConfiguration"; -import { ICookieMgr } from "../JavaScriptSDK.Interfaces/ICookieMgr"; -import { IDiagnosticLogger } from "../JavaScriptSDK.Interfaces/IDiagnosticLogger"; -import { _gblCookieMgr } from "./CookieMgr"; -import { getPerformance, isIE } from "./EnvUtils"; -import { addEventHandler, attachEvent, detachEvent } from "./EventHelpers"; -import { - arrForEach, arrIndexOf, arrMap, arrReduce, dateNow, hasOwnProperty, isArray, isBoolean, isDate, isError, isFunction, isNullOrUndefined, - isNumber, isObject, isString, isTypeof, isUndefined, objDefineAccessors, objKeys, strTrim, toISOString -} from "./HelperFuncs"; +import { strShimUndefined } from "@microsoft/applicationinsights-shims"; +import { getPerformance } from "./EnvUtils"; +import { dateNow } from "./HelperFuncs"; import { STR_EMPTY } from "./InternalConstants"; -import { mwcRandom32, mwcRandomSeed, newId, random32, randomValue } from "./RandomHelper"; - -let _cookieMgrs: ICookieMgr[] = null; -let _canUseCookies: boolean; // legacy supported config +import { random32 } from "./RandomHelper"; // Added to help with minfication export const Undefined = strShimUndefined; @@ -81,404 +70,3 @@ export function generateW3CId(): string { const clockSequenceHi = hexValues[8 + (random32() & 0x03) | 0]; return oct.substr(0, 8) + oct.substr(9, 4) + "4" + oct.substr(13, 3) + clockSequenceHi + oct.substr(16, 3) + oct.substr(19, 12); } - -/** - * Provides a collection of utility functions, included for backward compatibility with previous releases. - * @deprecated Marking this interface and instance as deprecated in favor of direct usage of the helper functions - * as direct usage provides better tree-shaking and minification by avoiding the inclusion of the unused items - * in your resulting code. - */ -export interface ICoreUtils { - /** - * Internal - Do not use directly. - * @deprecated Direct usage of this property is not recommend - */ - _canUseCookies: boolean; - - isTypeof: (value: any, theType: string) => boolean; - - isUndefined: (value: any) => boolean; - - isNullOrUndefined: (value: any) => boolean; - - hasOwnProperty: (obj: any, prop: string) => boolean; - - /** - * Checks if the passed of value is a function. - * @param {any} value - Value to be checked. - * @return {boolean} True if the value is a boolean, false otherwise. - */ - isFunction: (value: any) => value is Function; - - /** - * Checks if the passed of value is a function. - * @param {any} value - Value to be checked. - * @return {boolean} True if the value is a boolean, false otherwise. - */ - isObject: (value: any) => boolean; - - /** - * Check if an object is of type Date - */ - isDate: (obj: any) => obj is Date; - - /** - * Check if an object is of type Array - */ - isArray: (obj: any) => boolean; - - /** - * Check if an object is of type Error - */ - isError: (obj: any) => obj is Error; - - /** - * Checks if the type of value is a string. - * @param {any} value - Value to be checked. - * @return {boolean} True if the value is a string, false otherwise. - */ - isString: (value: any) => value is string; - - /** - * Checks if the type of value is a number. - * @param {any} value - Value to be checked. - * @return {boolean} True if the value is a number, false otherwise. - */ - isNumber: (value: any) => value is number; - - /** - * Checks if the type of value is a boolean. - * @param {any} value - Value to be checked. - * @return {boolean} True if the value is a boolean, false otherwise. - */ - isBoolean: (value: any) => value is boolean; - - /** - * Convert a date to I.S.O. format in IE8 - */ - toISOString: (date: Date) => string; - - /** - * Performs the specified action for each element in an array. This helper exists to avoid adding a polyfil for older browsers - * that do not define Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page checks for presence/absence of the prototype - * implementation. Note: For consistency this will not use the Array.prototype.xxxx implementation if it exists as this would - * cause a testing requirement to test with and without the implementations - * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. It can return -1 to break out of the loop - * @param thisArg [Optional] An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - arrForEach: (arr: T[], callbackfn: (value: T, index?: number, array?: T[]) => void|number, thisArg?: any) => void; - - /** - * Returns the index of the first occurrence of a value in an array. This helper exists to avoid adding a polyfil for older browsers - * that do not define Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page checks for presence/absence of the prototype - * implementation. Note: For consistency this will not use the Array.prototype.xxxx implementation if it exists as this would - * cause a testing requirement to test with and without the implementations - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. - */ - arrIndexOf: (arr: T[], searchElement: T, fromIndex?: number) => number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. This helper exists - * to avoid adding a polyfil for older browsers that do not define Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page - * checks for presence/absence of the prototype implementation. Note: For consistency this will not use the Array.prototype.xxxx - * implementation if it exists as this would cause a testing requirement to test with and without the implementations - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - arrMap: (arr: T[], callbackfn: (value: T, index?: number, array?: T[]) => R, thisArg?: any) => R[]; - - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is - * provided as an argument in the next call to the callback function. This helper exists to avoid adding a polyfil for older browsers that do not define - * Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page checks for presence/absence of the prototype implementation. Note: For consistency - * this will not use the Array.prototype.xxxx implementation if it exists as this would cause a testing requirement to test with and without the implementations - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - arrReduce: (arr: T[], callbackfn: (previousValue: T | R, currentValue?: T, currentIndex?: number, array?: T[]) => R, initialValue?: R) => R; - - /** - * helper method to trim strings (IE8 does not implement String.prototype.trim) - */ - strTrim: (str: any) => string; - - /** - * Creates an object that has the specified prototype, and that optionally contains specified properties. This helper exists to avoid adding a polyfil - * for older browsers that do not define Object.create eg. ES3 only, IE8 just in case any page checks for presence/absence of the prototype implementation. - * Note: For consistency this will not use the Object.create implementation if it exists as this would cause a testing requirement to test with and without the implementations - * @param obj Object to use as a prototype. May be null - */ - // tslint:disable-next-line: member-ordering - objCreate:(obj: object) => any; - - /** - * Returns the names of the enumerable string properties and methods of an object. This helper exists to avoid adding a polyfil for older browsers - * that do not define Object.keys eg. ES3 only, IE8 just in case any page checks for presence/absence of the prototype implementation. - * Note: For consistency this will not use the Object.keys implementation if it exists as this would cause a testing requirement to test with and without the implementations - * @param obj Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. - */ - objKeys: (obj: {}) => string[]; - - /** - * Try to define get/set object property accessors for the target object/prototype, this will provide compatibility with - * existing API definition when run within an ES5+ container that supports accessors but still enable the code to be loaded - * and executed in an ES3 container, providing basic IE8 compatibility. - * @param target The object on which to define the property. - * @param prop The name of the property to be defined or modified. - * @param getProp The getter function to wire against the getter. - * @param setProp The setter function to wire against the setter. - * @returns True if it was able to create the accessors otherwise false - */ - objDefineAccessors: (target: any, prop: string, getProp?: () => T, setProp?: (v: T) => void) => boolean; - - /** - * Trys to add an event handler for the specified event to the window, body and document - * @param eventName {string} - The name of the event - * @param callback {any} - The callback function that needs to be executed for the given event - * @return {boolean} - true if the handler was successfully added - */ - addEventHandler: (eventName: string, callback: any, evtNamespace?: string | string[]) => boolean; - - /** - * Return the current time via the Date now() function (if available) and falls back to (new Date()).getTime() if now() is unavailable (IE8 or less) - * https://caniuse.com/#search=Date.now - */ - dateNow: () => number; - - /** - * Identifies whether the current environment appears to be IE - */ - isIE: () => boolean; - - /** - * @deprecated - Use the core.getCookieMgr().disable() - * Force the SDK not to store and read any data from cookies. - */ - disableCookies: () => void; - - newGuid: () => string; - - /** - * Return the current value of the Performance Api now() function (if available) and fallback to dateNow() if it is unavailable (IE9 or less) - * https://caniuse.com/#search=performance.now - */ - perfNow: () => number; - - /** - * Generate random base64 id string. - * The default length is 22 which is 132-bits so almost the same as a GUID but as base64 (the previous default was 5) - * @param maxLength - Optional value to specify the length of the id to be generated, defaults to 22 - */ - newId: (maxLength?: number) => string; - - /** - * Generate a random value between 0 and maxValue, max value should be limited to a 32-bit maximum. - * So maxValue(16) will produce a number from 0..16 (range of 17) - * @param maxValue - */ - randomValue: (maxValue: number) => number; - - /** - * generate a random 32-bit number (0x000000..0xFFFFFFFF) or (-0x80000000..0x7FFFFFFF), defaults un-unsigned. - * @param signed - True to return a signed 32-bit number (-0x80000000..0x7FFFFFFF) otherwise an unsigned one (0x000000..0xFFFFFFFF) - */ - random32: (signed?: boolean) => number; - - /** - * Seed the MWC random number generator with the specified seed or a random value - * @param value - optional the number to used as the seed, if undefined, null or zero a random value will be chosen - */ - mwcRandomSeed: (value?: number) => void; - - /** - * Generate a random 32-bit number between (0x000000..0xFFFFFFFF) or (-0x80000000..0x7FFFFFFF), using MWC (Multiply with carry) - * instead of Math.random() defaults to un-signed. - * Used as a replacement random generator for IE to avoid issues with older IE instances. - * @param signed - True to return a signed 32-bit number (-0x80000000..0x7FFFFFFF) otherwise an unsigned one (0x000000..0xFFFFFFFF) - */ - mwcRandom32: (signed?: boolean) => number; - - /** - * generate W3C trace id - */ - generateW3CId: () => string; -} - -/** - * Provides a collection of utility functions, included for backward compatibility with previous releases. - * @deprecated Marking this instance as deprecated in favor of direct usage of the helper functions - * as direct usage provides better tree-shaking and minification by avoiding the inclusion of the unused items - * in your resulting code. - */ -export const CoreUtils: ICoreUtils = { - _canUseCookies: undefined, - isTypeof: isTypeof, - isUndefined: isUndefined, - isNullOrUndefined: isNullOrUndefined, - hasOwnProperty: hasOwnProperty, - isFunction: isFunction, - isObject: isObject, - isDate: isDate, - isArray: isArray, - isError: isError, - isString: isString, - isNumber: isNumber, - isBoolean: isBoolean, - toISOString: toISOString, - arrForEach: arrForEach, - arrIndexOf: arrIndexOf, - arrMap: arrMap, - arrReduce: arrReduce, - strTrim: strTrim, - objCreate: objCreateFn, - objKeys: objKeys, - objDefineAccessors: objDefineAccessors, - addEventHandler: addEventHandler, - dateNow: dateNow, - isIE: isIE, - disableCookies: disableCookies, - newGuid: newGuid, - perfNow: perfNow, - newId: newId, - randomValue: randomValue, - random32: random32, - mwcRandomSeed: mwcRandomSeed, - mwcRandom32: mwcRandom32, - generateW3CId: generateW3CId -}; - -const GuidRegex = /[xy]/g; - -export interface IEventHelper { - /** - * Binds the specified function to an event, so that the function gets called whenever the event fires on the object - * @param obj Object to add the event too. - * @param eventNameWithoutOn String that specifies any of the standard DHTML Events without "on" prefix - * @param handlerRef Pointer that specifies the function to call when event fires - * @returns True if the function was bound successfully to the event, otherwise false - */ - Attach: (obj: any, eventNameWithoutOn: string, handlerRef: any) => boolean; - - /** - * Binds the specified function to an event, so that the function gets called whenever the event fires on the object - * @deprecated Use {@link EventHelper#Attach} as we are already in a class call EventHelper the extra "Event" just causes a larger result - * @param obj Object to add the event too. - * @param eventNameWithoutOn String that specifies any of the standard DHTML Events without "on" prefix - * @param handlerRef Pointer that specifies the function to call when event fires - * @returns True if the function was bound successfully to the event, otherwise false - */ - AttachEvent: (obj: any, eventNameWithoutOn: string, handlerRef: any) => boolean; - - /** - * Removes an event handler for the specified event - * @param eventName {string} - The name of the event - * @param callback {any} - The callback function that needs to be executed for the given event - * @return {boolean} - true if the handler was successfully added - */ - Detach: (obj: any, eventNameWithoutOn: string, handlerRef: any) => void; - - /** - * Removes an event handler for the specified event - * @deprecated Use {@link EventHelper#Detach} as we are already in a class call EventHelper the extra "Event" just causes a larger result - * @param eventName {string} - The name of the event - * @param callback {any} - The callback function that needs to be executed for the given event - * @return {boolean} - true if the handler was successfully added - */ - DetachEvent: (obj: any, eventNameWithoutOn: string, handlerRef: any) => void; -} - -export const EventHelper: IEventHelper = { - Attach: attachEvent, - AttachEvent: attachEvent, - Detach: detachEvent, - DetachEvent: detachEvent -}; - -/** - * Helper to support backward compatibility for users that use the legacy cookie handling functions and the use the internal - * CoreUtils._canUseCookies global flag to enable/disable cookies usage. - * Note: This has the following deliberate side-effects - * - Creates the global (legacy) cookie manager if it does not already exist - * - Attempts to add "listeners" to the CoreUtils._canUseCookies property to support the legacy usage - * @param config - * @param logger - * @returns - */ -export function _legacyCookieMgr(config?: IConfiguration, logger?: IDiagnosticLogger): ICookieMgr { - let cookieMgr = _gblCookieMgr(config, logger); - let legacyCanUseCookies = (CoreUtils as any)._canUseCookies; - - if (_cookieMgrs === null) { - _cookieMgrs = []; - _canUseCookies = legacyCanUseCookies; - - // Dynamically create get/set property accessors for backward compatibility for enabling / disabling cookies - // this WILL NOT work for ES3 browsers (< IE8) - objDefineAccessors(CoreUtils, "_canUseCookies", - () => { - return _canUseCookies; - }, - (value) => { - _canUseCookies = value; - arrForEach(_cookieMgrs, (mgr) => { - mgr.setEnabled(value); - }); - }); - } - - if (arrIndexOf(_cookieMgrs, cookieMgr) === -1) { - _cookieMgrs.push(cookieMgr); - } - - if (isBoolean(legacyCanUseCookies)) { - cookieMgr.setEnabled(legacyCanUseCookies); - } - - if (isBoolean(_canUseCookies)) { - cookieMgr.setEnabled(_canUseCookies); - } - - return cookieMgr; -} - -/** - * @deprecated - Use the core.getCookieMgr().disable() - * Force the SDK not to store and read any data from cookies. - */ -export function disableCookies() { - _legacyCookieMgr().setEnabled(false); -} - -/** - * @deprecated - Use the core.getCookieMgr().isEnabled() - * Helper method to tell if document.cookie object is available and whether it can be used. - */ -export function canUseCookies(logger: IDiagnosticLogger): any { - return _legacyCookieMgr(null, logger).isEnabled(); -} - -/** - * @deprecated - Use the core.getCookieMgr().get() - * helper method to access userId and sessionId cookie - */ -export function getCookie(logger: IDiagnosticLogger, name: string) { - return _legacyCookieMgr(null, logger).get(name); -} - -/** - * @deprecated - Use the core.getCookieMgr().set() - * helper method to set userId and sessionId cookie - */ -export function setCookie(logger: IDiagnosticLogger, name: string, value: string, domain?: string) { - _legacyCookieMgr(null, logger).set(name, value, null, domain); -} - -/** - * @deprecated - Use the core.getCookieMgr().del() - * Deletes a cookie by setting it's expiration time in the past. - * @param name - The name of the cookie to delete. - */ -export function deleteCookie(logger: IDiagnosticLogger, name: string) { - return _legacyCookieMgr(null, logger).del(name); -} diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/DbgExtensionUtils.ts b/shared/AppInsightsCore/src/JavaScriptSDK/DbgExtensionUtils.ts index a5577754..b750cb41 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/DbgExtensionUtils.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/DbgExtensionUtils.ts @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +import { getInst } from "@nevware21/ts-utils"; import { IConfiguration } from "../JavaScriptSDK.Interfaces/IConfiguration"; import { IDbgExtension } from "../JavaScriptSDK.Interfaces/IDbgExtension"; import { INotificationListener } from "../JavaScriptSDK.Interfaces/INotificationListener"; -import { getGlobalInst } from "./EnvUtils"; const listenerFuncs = [ "eventsSent", "eventsDiscarded", "eventsSendRequest", "perfEvent" ]; @@ -26,7 +26,7 @@ function _listenerProxyFunc(name: string, config: IConfiguration) { function _getExtensionNamespace() { // Cache the lookup of the global namespace object - let target = getGlobalInst("Microsoft"); + let target = getInst("Microsoft"); if (target) { _aiNamespace = target["ApplicationInsights"]; } diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/DiagnosticLogger.ts b/shared/AppInsightsCore/src/JavaScriptSDK/DiagnosticLogger.ts index 6b2ceeb7..81e33fb7 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/DiagnosticLogger.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/DiagnosticLogger.ts @@ -2,13 +2,14 @@ // Licensed under the MIT License. "use strict" import dynamicProto from "@microsoft/dynamicproto-js"; +import { dumpObj, isFunction, isUndefined } from "@nevware21/ts-utils"; import { LoggingSeverity, _InternalMessageId, _eInternalMessageId, eLoggingSeverity } from "../JavaScriptSDK.Enums/LoggingEnums"; import { IAppInsightsCore } from "../JavaScriptSDK.Interfaces/IAppInsightsCore"; import { IConfiguration } from "../JavaScriptSDK.Interfaces/IConfiguration"; import { IDiagnosticLogger } from "../JavaScriptSDK.Interfaces/IDiagnosticLogger"; import { getDebugExt } from "./DbgExtensionUtils"; -import { dumpObj, getConsole, getJSON, hasJSON } from "./EnvUtils"; -import { getCfgValue, isFunction, isUndefined } from "./HelperFuncs"; +import { getConsole, getJSON, hasJSON } from "./EnvUtils"; +import { getCfgValue } from "./HelperFuncs"; import { STR_EMPTY, STR_ERROR_TO_CONSOLE, STR_WARN_TO_CONSOLE } from "./InternalConstants"; /** diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/EnvUtils.ts b/shared/AppInsightsCore/src/JavaScriptSDK/EnvUtils.ts index 854840e1..c35b974b 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/EnvUtils.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/EnvUtils.ts @@ -2,8 +2,9 @@ // Licensed under the MIT License. "use strict"; -import { getGlobal, strShimObject, strShimPrototype, strShimUndefined } from "@microsoft/applicationinsights-shims"; -import { isString, isUndefined, strContains } from "./HelperFuncs"; +import { strShimObject, strShimPrototype, strShimUndefined } from "@microsoft/applicationinsights-shims"; +import { getDocument, getInst, getNavigator, hasNavigator, isString, isUndefined } from "@nevware21/ts-utils"; +import { strContains } from "./HelperFuncs"; import { STR_EMPTY } from "./InternalConstants"; // TypeScript removed this interface so we need to declare the global so we can check for it's existence. @@ -16,11 +17,7 @@ declare var XDomainRequest: any; * functions/properties only need to include those that are used within their own modules. */ -const strWindow = "window"; -const strDocument = "document"; const strDocumentMode = "documentMode"; -const strNavigator = "navigator"; -const strHistory = "history"; const strLocation = "location"; const strConsole = "console"; const strPerformance = "performance"; @@ -75,122 +72,122 @@ export function setEnableEnvMocks(enabled: boolean) { _enableMocks = enabled; } -/** - * Return the named global object if available, will return null if the object is not available. - * @param name The globally named object - */ -export function getGlobalInst(name:string): T { - let gbl = getGlobal(); - if (gbl && gbl[name]) { - return gbl[name] as T; - } +// /** +// * Return the named global object if available, will return null if the object is not available. +// * @param name The globally named object +// */ +// export function getinst(name:string): T { +// let gbl = getGlobal(); +// if (gbl && gbl[name]) { +// return gbl[name] as T; +// } - // Test workaround, for environments where .window (when global == window) doesn't return the base window - if (name === strWindow && hasWindow()) { - // tslint:disable-next-line: no-angle-bracket-type-assertion - return window as T; - } +// // Test workaround, for environments where .window (when global == window) doesn't return the base window +// if (name === strWindow && hasWindow()) { +// // tslint:disable-next-line: no-angle-bracket-type-assertion +// return window as T; +// } - return null; -} +// return null; +// } -/** - * Checks if window object is available, this is required as we support the API running without a - * window /document (eg. Node server, electron webworkers) and if we attempt to assign a window - * object to a local variable or pass as an argument an "Uncaught ReferenceError: window is not defined" - * exception will be thrown. - * Defined as a function to support lazy / late binding environments. - */ -export function hasWindow(): boolean { - return Boolean(typeof window === strShimObject && window); -} +// /** +// * Checks if window object is available, this is required as we support the API running without a +// * window /document (eg. Node server, electron webworkers) and if we attempt to assign a window +// * object to a local variable or pass as an argument an "Uncaught ReferenceError: window is not defined" +// * exception will be thrown. +// * Defined as a function to support lazy / late binding environments. +// */ +// export const hasWindow = () => boolean = hasWindow; +// return Boolean(typeof window === strShimObject && window); +// } -/** - * Returns the global window object if it is present otherwise null. - * This helper is used to access the window object without causing an exception - * "Uncaught ReferenceError: window is not defined" - */ -export function getWindow(): Window | null { - if (hasWindow()) { - return window; - } +// /** +// * Returns the global window object if it is present otherwise null. +// * This helper is used to access the window object without causing an exception +// * "Uncaught ReferenceError: window is not defined" +// */ +// export function getWindow(): Window | null { +// if (hasWindow()) { +// return window; +// } - // Return the global instance or null - return getGlobalInst(strWindow); -} +// // Return the global instance or null +// return getInst(strWindow); +// } -/** - * Checks if document object is available, this is required as we support the API running without a - * window /document (eg. Node server, electron webworkers) and if we attempt to assign a document - * object to a local variable or pass as an argument an "Uncaught ReferenceError: document is not defined" - * exception will be thrown. - * Defined as a function to support lazy / late binding environments. - */ -export function hasDocument(): boolean { - return Boolean(typeof document === strShimObject && document); -} +// /** +// * Checks if document object is available, this is required as we support the API running without a +// * window /document (eg. Node server, electron webworkers) and if we attempt to assign a document +// * object to a local variable or pass as an argument an "Uncaught ReferenceError: document is not defined" +// * exception will be thrown. +// * Defined as a function to support lazy / late binding environments. +// */ +// export function hasDocument(): boolean { +// return Boolean(typeof document === strShimObject && document); +// } -/** - * Returns the global document object if it is present otherwise null. - * This helper is used to access the document object without causing an exception - * "Uncaught ReferenceError: document is not defined" - */ -export function getDocument(): Document | null { - if (hasDocument()) { - return document; - } +// /** +// * Returns the global document object if it is present otherwise null. +// * This helper is used to access the document object without causing an exception +// * "Uncaught ReferenceError: document is not defined" +// */ +// export function getDocument(): Document | null { +// if (hasDocument()) { +// return document; +// } - return getGlobalInst(strDocument); -} +// return getInst(strDocument); +// } -/** - * Checks if navigator object is available, this is required as we support the API running without a - * window /document (eg. Node server, electron webworkers) and if we attempt to assign a navigator - * object to a local variable or pass as an argument an "Uncaught ReferenceError: navigator is not defined" - * exception will be thrown. - * Defined as a function to support lazy / late binding environments. - */ -export function hasNavigator(): boolean { - return Boolean(typeof navigator === strShimObject && navigator); -} +// /** +// * Checks if navigator object is available, this is required as we support the API running without a +// * window /document (eg. Node server, electron webworkers) and if we attempt to assign a navigator +// * object to a local variable or pass as an argument an "Uncaught ReferenceError: navigator is not defined" +// * exception will be thrown. +// * Defined as a function to support lazy / late binding environments. +// */ +// export function hasNavigator(): boolean { +// return Boolean(typeof navigator === strShimObject && navigator); +// } -/** - * Returns the global navigator object if it is present otherwise null. - * This helper is used to access the navigator object without causing an exception - * "Uncaught ReferenceError: navigator is not defined" - */ -export function getNavigator(): Navigator | null { - if (hasNavigator()) { - return navigator; - } +// /** +// * Returns the global navigator object if it is present otherwise null. +// * This helper is used to access the navigator object without causing an exception +// * "Uncaught ReferenceError: navigator is not defined" +// */ +// export function getNavigator(): Navigator | null { +// if (hasNavigator()) { +// return navigator; +// } - return getGlobalInst(strNavigator); -} +// return getInst(strNavigator); +// } -/** - * Checks if history object is available, this is required as we support the API running without a - * window /document (eg. Node server, electron webworkers) and if we attempt to assign a history - * object to a local variable or pass as an argument an "Uncaught ReferenceError: history is not defined" - * exception will be thrown. - * Defined as a function to support lazy / late binding environments. - */ -export function hasHistory(): boolean { - return Boolean(typeof history === strShimObject && history); -} +// /** +// * Checks if history object is available, this is required as we support the API running without a +// * window /document (eg. Node server, electron webworkers) and if we attempt to assign a history +// * object to a local variable or pass as an argument an "Uncaught ReferenceError: history is not defined" +// * exception will be thrown. +// * Defined as a function to support lazy / late binding environments. +// */ +// export function hasHistory(): boolean { +// return Boolean(typeof history === strShimObject && history); +// } -/** - * Returns the global history object if it is present otherwise null. - * This helper is used to access the history object without causing an exception - * "Uncaught ReferenceError: history is not defined" - */ -export function getHistory(): History | null { - if (hasHistory()) { - return history; - } +// /** +// * Returns the global history object if it is present otherwise null. +// * This helper is used to access the history object without causing an exception +// * "Uncaught ReferenceError: history is not defined" +// */ +// export function getHistory(): History | null { +// if (hasHistory()) { +// return history; +// } - return getGlobalInst(strHistory); -} +// return getInst(strHistory); +// } /** * Returns the global location object if it is present otherwise null. @@ -199,7 +196,7 @@ export function getHistory(): History | null { */ export function getLocation(checkForMock?: boolean): Location | null { if (checkForMock && _enableMocks) { - let mockLocation = getGlobalInst("__mockLocation") as Location; + let mockLocation = getInst("__mockLocation") as Location; if (mockLocation) { return mockLocation; } @@ -209,7 +206,7 @@ export function getLocation(checkForMock?: boolean): Location | null { return location; } - return getGlobalInst(strLocation); + return getInst(strLocation); } /** @@ -220,7 +217,7 @@ export function getConsole(): Console | null { return console; } - return getGlobalInst(strConsole); + return getInst(strConsole); } /** @@ -229,7 +226,7 @@ export function getConsole(): Console | null { * global instance which could be window or globalThis for a web worker */ export function getPerformance(): Performance | null { - return getGlobalInst(strPerformance); + return getInst(strPerformance); } /** @@ -240,7 +237,7 @@ export function getPerformance(): Performance | null { * Defined as a function to support lazy / late binding environments. */ export function hasJSON(): boolean { - return Boolean((typeof JSON === strShimObject && JSON) || getGlobalInst(strJSON) !== null); + return Boolean((typeof JSON === strShimObject && JSON) || getInst(strJSON) !== null); } /** @@ -250,7 +247,7 @@ export function hasJSON(): boolean { */ export function getJSON(): JSON | null { if (hasJSON()) { - return JSON || getGlobalInst(strJSON); + return JSON || getInst(strJSON); } return null; @@ -262,7 +259,7 @@ export function getJSON(): JSON | null { * global instance which could be window or globalThis for a web worker */ export function getCrypto(): Crypto | null { - return getGlobalInst(strCrypto); + return getInst(strCrypto); } /** @@ -271,7 +268,7 @@ export function getCrypto(): Crypto | null { * global instance which could be window or globalThis for a web worker */ export function getMsCrypto(): Crypto | null { - return getGlobalInst(strMsCrypto); + return getInst(strMsCrypto); } /** @@ -326,20 +323,20 @@ export function getIEVersion(userAgentStr: string = null): number { return null; } -/** - * Returns string representation of an object suitable for diagnostics logging. - */ -export function dumpObj(object: any): string { - const objectTypeDump: string = Object[strShimPrototype].toString.call(object); - let propertyValueDump: string = STR_EMPTY; - if (objectTypeDump === "[object Error]") { - propertyValueDump = "{ stack: '" + object.stack + "', message: '" + object.message + "', name: '" + object.name + "'"; - } else if (hasJSON()) { - propertyValueDump = getJSON().stringify(object); - } +// /** +// * Returns string representation of an object suitable for diagnostics logging. +// */ +// export function dumpObj(object: any): string { +// const objectTypeDump: string = Object[strShimPrototype].toString.call(object); +// let propertyValueDump: string = STR_EMPTY; +// if (objectTypeDump === "[object Error]") { +// propertyValueDump = "{ stack: '" + object.stack + "', message: '" + object.message + "', name: '" + object.name + "'"; +// } else if (hasJSON()) { +// propertyValueDump = getJSON().stringify(object); +// } - return objectTypeDump + propertyValueDump; -} +// return objectTypeDump + propertyValueDump; +// } export function isSafari(userAgentStr ?: string) { if (!userAgentStr || !isString(userAgentStr)) { @@ -371,8 +368,8 @@ export function isBeaconsSupported(): boolean { export function isFetchSupported(withKeepAlive?: boolean): boolean { let isSupported = false; try { - isSupported = !!getGlobalInst("fetch"); - const request = getGlobalInst("Request"); + isSupported = !!getInst("fetch"); + const request = getInst("Request"); if (isSupported && withKeepAlive && request) { isSupported = _hasProperty(request, "keepalive"); } @@ -387,7 +384,7 @@ export function useXDomainRequest(): boolean | undefined { if (_useXDomainRequest === null) { _useXDomainRequest = (typeof XDomainRequest !== strShimUndefined); if (_useXDomainRequest && isXhrSupported()) { - _useXDomainRequest = _useXDomainRequest && !_hasProperty(getGlobalInst(strXMLHttpRequest), "withCredentials"); + _useXDomainRequest = _useXDomainRequest && !_hasProperty(getInst(strXMLHttpRequest), "withCredentials"); } } @@ -401,7 +398,7 @@ export function useXDomainRequest(): boolean | undefined { export function isXhrSupported(): boolean { let isSupported = false; try { - const xmlHttpRequest = getGlobalInst(strXMLHttpRequest); + const xmlHttpRequest = getInst(strXMLHttpRequest); isSupported = !!xmlHttpRequest; } catch (e) { // Just Swallow any failure during availability checks diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/EventHelpers.ts b/shared/AppInsightsCore/src/JavaScriptSDK/EventHelpers.ts index 1ec49c40..04d98f45 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/EventHelpers.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/EventHelpers.ts @@ -1,8 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +import { arrForEach, arrIndexOf, getDocument, getWindow, isArray, objForEachKey, objKeys } from "@nevware21/ts-utils"; import { createElmNodeData, createUniqueNamespace } from "./DataCacheHelper"; -import { getDocument, getWindow } from "./EnvUtils"; -import { arrForEach, arrIndexOf, isArray, objForEachKey, objKeys } from "./HelperFuncs"; import { STR_EMPTY } from "./InternalConstants"; // Added to help with minfication diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/HelperFuncs.ts b/shared/AppInsightsCore/src/JavaScriptSDK/HelperFuncs.ts index 5a2882b5..46aabe60 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/HelperFuncs.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/HelperFuncs.ts @@ -1,51 +1,33 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +import { ObjAssign, ObjClass, ObjHasOwnProperty, ObjProto, strShimFunction, strShimPrototype } from "@microsoft/applicationinsights-shims"; import { - ObjAssign, ObjClass, ObjDefineProperty, ObjHasOwnProperty, ObjProto, strShimFunction, strShimObject, strShimPrototype, strShimUndefined, - throwTypeError -} from "@microsoft/applicationinsights-shims"; + arrForEach, isArray, isBoolean, isError, isFunction, isNullOrUndefined, isObject, isString, isUndefined, objDeepFreeze, + objDefineAccessors, objForEachKey, objHasOwnProperty, strIndexOf, throwUnsupported +} from "@nevware21/ts-utils"; import { STR_EMPTY } from "./InternalConstants"; // RESTRICT and AVOID circular dependencies you should not import other contained modules or export the contents of this file directly -// Added to help with minfication +// Added to help with minification +const cString = "String"; +const cObject = "Object"; const strToISOString = "toISOString"; -const cStrEndsWith = "endsWith"; -const cStrStartsWith = "startsWith"; -const strIndexOf = "indexOf"; const strMap = "map"; -const strReduce = "reduce"; -const cStrTrim = "trim"; const strToString = "toString"; - -/** - * Constant string defined to support minimization - * @ignore - */ -const str__Proto = "__proto__"; +const strGetPrototypeOf = "getPrototypeOf"; /** * Constant string defined to support minimization * @ignore */ const strConstructor = "constructor"; - -const _objDefineProperty = ObjDefineProperty; -const _objFreeze = ObjClass.freeze; -const _objSeal = ObjClass.seal; -const _objKeys = ObjClass.keys; - -const StringProto = String[strShimPrototype]; -const _strTrim = StringProto[cStrTrim]; -const _strEndsWith = StringProto[cStrEndsWith]; -const _strStartsWith = StringProto[cStrStartsWith]; const DateProto = Date[strShimPrototype]; -const _dataToISOString = DateProto[strToISOString]; -const _isArray = Array.isArray; -const _objToString = ObjProto[strToString]; +const _dateToISOString = DateProto[strToISOString] || _polyfillRequired("Date", strToISOString); +const _objToString = ObjProto[strToString] || _polyfillRequired(cObject, strToString); -const _fnToString = ObjHasOwnProperty[strToString]; +const _fnToString = ObjHasOwnProperty[strToString] || _polyfillRequired(cString, strToString); // Cache what this browser reports as the object function constructor (as a string) const _objFunctionString = _fnToString.call(ObjClass); @@ -53,76 +35,26 @@ const rCamelCase = /-([a-z])/g; const rNormalizeInvalid = /([^\w\d_$])/g; const rLeadingNumeric = /^(\d+[\w\d_$])/; - -/** - * Pre-lookup to check if we are running on a modern browser (i.e. not IE8) - * @ignore - */ -let _objGetPrototypeOf = Object["getPrototypeOf"]; - -/** - * Helper used to get the prototype of the target object as getPrototypeOf is not available in an ES3 environment. - * @ignore - */ -export function _getObjProto(target:any) { - if (target) { - // This method doesn't existing in older browsers (e.g. IE8) - if (_objGetPrototypeOf) { - return _objGetPrototypeOf(target); - } - - // target[Constructor] May break if the constructor has been changed or removed - let newProto = target[str__Proto] || target[strShimPrototype] || target[strConstructor]; - if(newProto) { - return newProto; - } +function _polyfillRequired(object:string, name: string): any { + return function() { + throwUnsupported("Polyfill required for [" + name + "]"); } - - return null; } +export let _getObjProto = Object[strGetPrototypeOf] || _polyfillRequired(cObject, strGetPrototypeOf); + export function objToString(obj: any) { return _objToString.call(obj); } -export function isTypeof(value: any, theType: string): boolean { - return typeof value === theType; -} - -export function isUndefined(value: any): value is undefined { - return value === undefined || typeof value === strShimUndefined; -} - export function isNotUndefined(value: T): value is T { return !isUndefined(value); } -export function isNullOrUndefined(value: any): value is null | undefined { - return (value === null || isUndefined(value)); -} - export function isNotNullOrUndefined(value: T): value is T { return !isNullOrUndefined(value); } -export function hasOwnProperty(obj: any, prop: string): boolean { - return !!(obj && ObjHasOwnProperty.call(obj, prop)); -} - -export function isObject(value: T): value is T { - // Changing to inline for performance - return !!(value && typeof value === strShimObject); -} - -export function isFunction(value: any): value is Function { - // Changing to inline for performance - return !!(value && typeof value === strShimFunction); -} - -export function isPromiseLike(value: any): value is PromiseLike { - return value && isFunction(value.then); -} - /** * Validates that the string name conforms to the JS IdentifierName specification and if not * normalizes the name so that it would. This method does not identify or change any keywords @@ -148,178 +80,19 @@ export function normalizeJsName(name: string): string { return value; } -/** - * This is a helper function for the equivalent of arForEach(objKeys(target), callbackFn), this is a - * performance optimization to avoid the creation of a new array for large objects - * @param target The target object to find and process the keys - * @param callbackfn The function to call with the details - */ -export function objForEachKey(target: T, callbackfn: (name: string, value: T[keyof T]) => void) { - if (target) { - for (let prop in target) { - if (ObjHasOwnProperty.call(target, prop)) { - callbackfn.call(target, prop, target[prop]); - } - } - } -} - -/** - * The strEndsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate. - * @param value - The value to check whether it ends with the search value. - * @param search - The characters to be searched for at the end of the value. - * @returns true if the given search value is found at the end of the string, otherwise false. - */ -export function strEndsWith(value: string, search: string) { - let result = false; - if (value && search && !(result = value === search)) { - // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification - result = _strEndsWith ? value[cStrEndsWith](search) : _strEndsWithPoly(value, search); - } - - return result; -} - -/** - * The _strEndsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate. - * @param value - The value to check whether it ends with the search value. - * @param search - The characters to be searched for at the end of the value. - * @returns true if the given search value is found at the end of the string, otherwise false. - */ -export function _strEndsWithPoly(value: string, search: string) { - let result = false; - let searchLen = search ? search.length : 0; - let valLen = value ? value.length : 0; - if (searchLen && valLen && valLen >= searchLen && !(result = value === search)) { - let pos = valLen - 1; - for (let lp = searchLen - 1; lp >= 0; lp--) { - if (value[pos] != search[lp]) { - return false; - } - pos--; - } - - result = true; - } - - return result; -} - -/** - * The strStartsWith() method determines whether a string starts with the characters of the specified string, returning true or false as appropriate. - * @param value - The value to check whether it ends with the search value. - * @param checkValue - The characters to be searched for at the start of the value. - * @returns true if the given search value is found at the start of the string, otherwise false. - */ -export function strStartsWith(value: string, checkValue: string) { - let result = false; - if (value && checkValue && !(result = value === checkValue)) { - // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification - result = _strStartsWith ? value[cStrStartsWith](checkValue) : _strStartsWithPoly(value, checkValue); - } - - return result; -} - -/** - * The strStartsWith() method determines whether a string starts with the characters of the specified string, returning true or false as appropriate. - * @param value - The value to check whether it ends with the search value. - * @param checkValue - The characters to be searched for at the start of the value. - * @returns true if the given search value is found at the start of the string, otherwise false. - */ -export function _strStartsWithPoly(value: string, checkValue: string) { - // Using helper for performance and because string startsWith() is not available on IE - let result = false; - let chkLen = checkValue ? checkValue.length : 0; - if (value && chkLen && value.length >= chkLen && !(result = value === checkValue)) { - for (let lp = 0; lp < chkLen; lp++) { - if (value[lp] !== checkValue[lp]) { - return false; - } - } - - result = true; - } - - return result; -} - /** * A simple wrapper (for minification support) to check if the value contains the search string. * @param value - The string value to check for the existence of the search value * @param search - The value search within the value */ -export function strContains(value: string, search: string) { +export function strContains(value: string, search: string): boolean { if (value && search) { - return value.indexOf(search) !== -1; + return strIndexOf(value, search) !== -1; } return false; } -/** - * Check if an object is of type Date - */ -export function isDate(obj: any): obj is Date { - return !!(obj && _objToString.call(obj) === "[object Date]"); -} - -/** - * Check if an object is of type Array with optional generic T, the generic type is not validated - * and exists to help with TypeScript validation only. - */ -export let isArray: (obj: any) => obj is Array = _isArray || _isArrayPoly; -function _isArrayPoly(obj: any): obj is Array { - return !!(obj && _objToString.call(obj) === "[object Array]"); -} - -/** - * Check if an object is of type Error - */ -export function isError(obj: any): obj is Error { - return !!(obj && _objToString.call(obj) === "[object Error]"); -} - -/** - * Checks if the type of value is a string. - * @param {any} value - Value to be checked. - * @return {boolean} True if the value is a string, false otherwise. - */ -export function isString(value: any): value is string { - // Changing to inline for performance - return typeof value === "string"; -} - -/** - * Checks if the type of value is a number. - * @param {any} value - Value to be checked. - * @return {boolean} True if the value is a number, false otherwise. - */ -export function isNumber(value: any): value is number { - // Changing to inline for performance - return typeof value === "number"; -} - -/** - * Checks if the type of value is a boolean. - * @param {any} value - Value to be checked. - * @return {boolean} True if the value is a boolean, false otherwise. - */ -export function isBoolean(value: any): value is boolean { - // Changing to inline for performance - return typeof value === "boolean"; -} - -/** - * Checks if the type of value is a Symbol. - * This only returns a boolean as returning value is Symbol will cause issues for older TypeScript consumers - * @param {any} value - Value to be checked. - * @return {boolean} True if the value is a Symbol, false otherwise. - */ -export function isSymbol(value: any): boolean { - return typeof value === "symbol"; -} - /** * Checks if the type of the value is a normal plain object (not a null or data) * @param value @@ -329,7 +102,7 @@ export function isPlainObject(value: any): boolean { if (value && typeof value === "object") { // Inlining _objGetPrototypeOf for performance to avoid an additional function call - let proto = _objGetPrototypeOf ? _objGetPrototypeOf(value) : _getObjProto(value); + let proto = _getObjProto(value); if (!proto) { // No prototype found so this is a plain Object eg. 'Object.create(null)' result = true; @@ -350,285 +123,10 @@ export function isPlainObject(value: any): boolean { * Convert a date to I.S.O. format in IE8 */ export function toISOString(date: Date) { - if (date) { - // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification - return _dataToISOString ? date[strToISOString]() : _toISOStringPoly(date); - } + return _dateToISOString.call(date); } -/** - * Convert a date to I.S.O. format in IE8 - */ -export function _toISOStringPoly(date: Date) { - if (date && date.getUTCFullYear) { - const pad = (num: number) => { - let r = String(num); - if (r.length === 1) { - r = "0" + r; - } - - return r; - } - - return date.getUTCFullYear() - + "-" + pad(date.getUTCMonth() + 1) - + "-" + pad(date.getUTCDate()) - + "T" + pad(date.getUTCHours()) - + ":" + pad(date.getUTCMinutes()) - + ":" + pad(date.getUTCSeconds()) - + "." + String((date.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5) - + "Z"; - } -} - -/** - * Performs the specified action for each element in an array. This helper exists to avoid adding a polyfil for older browsers - * that do not define Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page checks for presence/absence of the prototype - * implementation. Note: For consistency this will not use the Array.prototype.xxxx implementation if it exists as this would - * cause a testing requirement to test with and without the implementations - * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. It can return -1 to break out of the loop - * @param thisArg [Optional] An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ -export function arrForEach(arr: T[], callbackfn: (value: T, index?: number, array?: T[]) => undefined | void | number, thisArg?: any): void { - let len = arr.length; - try { - for (let idx = 0; idx < len; idx++) { - if (idx in arr) { - if (callbackfn.call(thisArg || arr, arr[idx], idx, arr) === -1) { - break; - } - } - } - } catch (e) { - // This can happen with some native browser objects, but should not happen for the type we are checking for - } -} - -/** - * Returns the index of the first occurrence of a value in an array. This helper exists to avoid adding a polyfil for older browsers - * that do not define Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page checks for presence/absence of the prototype - * implementation. Note: For consistency this will not use the Array.prototype.xxxx implementation if it exists as this would - * cause a testing requirement to test with and without the implementations - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. - */ -export function arrIndexOf(arr: T[], searchElement: T, fromIndex?: number): number { - if (arr) { - // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification - if (arr[strIndexOf]) { - return arr[strIndexOf](searchElement, fromIndex); - } - - let len = arr.length; - let from = fromIndex || 0; - try { - for (let lp = Math.max(from >= 0 ? from : len - Math.abs(from), 0); lp < len; lp++) { - if (lp in arr && arr[lp] === searchElement) { - return lp; - } - } - } catch (e) { - // This can happen with some native browser objects, but should not happen for the type we are checking for - } - } - - return -1; -} - -/** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. This helper exists - * to avoid adding a polyfil for older browsers that do not define Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page - * checks for presence/absence of the prototype implementation. Note: For consistency this will not use the Array.prototype.xxxx - * implementation if it exists as this would cause a testing requirement to test with and without the implementations - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ -export function arrMap(arr: T[], callbackfn: (value: T, index?: number, array?: T[]) => R, thisArg?: any): R[] { - let results: R[]; - - if (arr) { - // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification - if (arr[strMap]) { - return arr[strMap](callbackfn, thisArg); - } - - let len = arr.length; - let _this = thisArg || arr; - results = new Array(len); - - try { - for (let lp = 0; lp < len; lp++) { - if (lp in arr) { - results[lp] = callbackfn.call(_this, arr[lp], arr); - } - } - } catch (e) { - // This can happen with some native browser objects, but should not happen for the type we are checking for - } - - } - - return results; -} - -/** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is - * provided as an argument in the next call to the callback function. This helper exists to avoid adding a polyfil for older browsers that do not define - * Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page checks for presence/absence of the prototype implementation. Note: For consistency - * this will not use the Array.prototype.xxxx implementation if it exists as this would cause a testing requirement to test with and without the implementations - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ -export function arrReduce(arr: T[], callbackfn: (previousValue: T | R, currentValue?: T, currentIndex?: number, array?: T[]) => R, initialValue?: R): R { - let value; - - if (arr) { - // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification - if (arr[strReduce]) { - return arr[strReduce](callbackfn, initialValue); - } - - let len = arr.length; - let lp = 0; - - // Specifically checking the number of passed arguments as the value could be anything - if (arguments.length >= 3) { - value = arguments[2]; - } else { - while (lp < len && !(lp in arr)) { - lp++; - } - - value = arr[lp++]; - } - - while (lp < len) { - if (lp in arr) { - value = callbackfn(value, arr[lp], lp, arr); - } - lp++; - } - } - - return value; -} - -/** - * helper method to trim strings (IE8 does not implement String.prototype.trim) - */ -export function strTrim(str: any): string { - if (str) { - // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification - str = (_strTrim && str[cStrTrim]) ? str[cStrTrim]() : (str.replace ? str.replace(/^\s+|\s+$/g, STR_EMPTY) : str); - } - - return str; -} - -let _objKeysHasDontEnumBug = !({ toString: null }).propertyIsEnumerable("toString"); -let _objKeysDontEnums = [ - "toString", - "toLocaleString", - "valueOf", - "hasOwnProperty", - "isPrototypeOf", - "propertyIsEnumerable", - "constructor" -]; - -/** - * Returns the names of the enumerable string properties and methods of an object. This helper exists to avoid adding a polyfil for older browsers - * that do not define Object.keys eg. ES3 only, IE8 just in case any page checks for presence/absence of the prototype implementation. - * Note: For consistency this will not use the Object.keys implementation if it exists as this would cause a testing requirement to test with and without the implementations - * @param obj Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. - */ -export function objKeys(obj: {}): string[] { - var objType = typeof obj; - - if (objType !== strShimFunction && (objType !== strShimObject || obj === null)) { - throwTypeError("objKeys called on non-object"); - } - - // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification - if (!_objKeysHasDontEnumBug && _objKeys) { - return _objKeys(obj); - } - - let result: string[] = []; - - for (let prop in obj) { - if (obj && ObjHasOwnProperty.call(obj, prop)) { - result.push(prop); - } - } - - if (_objKeysHasDontEnumBug) { - let dontEnumsLength = _objKeysDontEnums.length; - - for (let lp = 0; lp < dontEnumsLength; lp++) { - if (obj && ObjHasOwnProperty.call(obj, _objKeysDontEnums[lp])) { - result.push(_objKeysDontEnums[lp]); - } - } - } - - return result; -} - -/** - * Try to define get/set object property accessors for the target object/prototype, this will provide compatibility with - * existing API definition when run within an ES5+ container that supports accessors but still enable the code to be loaded - * and executed in an ES3 container, providing basic IE8 compatibility. - * @param target The object on which to define the property. - * @param prop The name of the property to be defined or modified. - * @param getProp The getter function to wire against the getter. - * @param setProp The setter function to wire against the setter. - * @returns True if it was able to create the accessors otherwise false - */ -export function objDefineAccessors(target: any, prop: string, getProp?: () => T, setProp?: (v: T) => void): boolean { - if (_objDefineProperty) { - try { - let descriptor: PropertyDescriptor = { - enumerable: true, - configurable: true - } - - if (getProp) { - descriptor.get = getProp; - } - if (setProp) { - descriptor.set = setProp; - } - - _objDefineProperty(target, prop, descriptor); - return true; - } catch (e) { - // IE8 Defines a defineProperty on Object but it's only supported for DOM elements so it will throw - // We will just ignore this here. - } - } - - return false; -} - -function _doNothing(value: T): T { - return value; -} - -export function deepFreeze(obj: T): T { - if (_objFreeze) { - objForEachKey(obj, (name, value) => { - if (isArray(value) || isObject(value)) { - _objFreeze(value); - } - }); - } - - return objFreeze(obj); -} - -export const objFreeze: (value: T) => T = _objFreeze || _doNothing; -export const objSeal: (value: T) => T = _objSeal || _doNothing; +export const deepFreeze: (obj: T) => T = objDeepFreeze; /** * Return the current time via the Date now() function (if available) and falls back to (new Date()).getTime() if now() is unavailable (IE8 or less) @@ -706,18 +204,6 @@ export function getCfgValue(theValue: V, defaultValue?: V): V { return !isNullOrUndefined(theValue) ? theValue : defaultValue; } -export function isNotTruthy(value: any) { - return !value; -} - -export function isTruthy(value: any) { - return !!value; -} - -export function throwError(message: string): never { - throw new Error(message); -} - function _createProxyFunction(source: S | (() => S), funcName: (keyof S)) { let srcFunc: () => S = null; let src: S = null; @@ -767,7 +253,7 @@ export function proxyAssign(target: T, source: S, chkSet?: (name: string, target[field as string] = _createProxyFunction(source, field); } } else if (!chkSet || chkSet(field, false, source, target)) { - if (hasOwnProperty(target, field)) { + if (objHasOwnProperty(target, field)) { // Remove any previous instance property delete (target as any)[field]; } diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/InstrumentHooks.ts b/shared/AppInsightsCore/src/JavaScriptSDK/InstrumentHooks.ts index 533f2aac..5e50d55a 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/InstrumentHooks.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/InstrumentHooks.ts @@ -2,11 +2,11 @@ // Licensed under the MIT License. import { strShimFunction, strShimPrototype } from "@microsoft/applicationinsights-shims"; +import { getInst, objHasOwnProperty } from "@nevware21/ts-utils"; import { IInstrumentCallDetails, IInstrumentHook, IInstrumentHooks, IInstrumentHooksCallbacks, InstrumentorHooksCallback } from "../JavaScriptSDK.Interfaces/IInstrumentHooks"; -import { getGlobalInst } from "./EnvUtils"; -import { _getObjProto, hasOwnProperty } from "./HelperFuncs"; +import { _getObjProto } from "./HelperFuncs"; const aiInstrumentHooks = "_aiHooks"; @@ -88,7 +88,7 @@ function _createFunctionHook(aiHook:IInstrumentHooks) { let hookCtx: any[] = []; let cbArgs = _createArgs([funcArgs], orgArgs); - funcArgs.evt = getGlobalInst("event"); + funcArgs.evt = getInst("event"); function _createArgs(target:any[], theArgs:any[]): any[] { _arrLoop((theArgs as any), (arg) => { @@ -134,7 +134,7 @@ function _createFunctionHook(aiHook:IInstrumentHooks) { function _getOwner(target:any, name:string, checkPrototype: boolean): any { let owner = null; if (target) { - if (hasOwnProperty(target, name)) { + if (objHasOwnProperty(target, name)) { owner = target; } else if (checkPrototype) { owner = _getOwner(_getObjProto(target), name, false); diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/InternalConstants.ts b/shared/AppInsightsCore/src/JavaScriptSDK/InternalConstants.ts index 6aaa9ac5..494c3d27 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/InternalConstants.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/InternalConstants.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!! -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +// ################################################################################################################################################### +// Note: DON'T Export these const from the package as we are still targeting IE/ES5 this will export a mutable variables that someone could change ### +// ################################################################################################################################################### export const STR_EMPTY = ""; export const STR_CHANNELS = "channels"; diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/NotificationManager.ts b/shared/AppInsightsCore/src/JavaScriptSDK/NotificationManager.ts index 8ad42669..15ac1a1e 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/NotificationManager.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/NotificationManager.ts @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import dynamicProto from "@microsoft/dynamicproto-js"; +import { arrForEach, arrIndexOf } from "@nevware21/ts-utils"; import { IConfiguration } from "../JavaScriptSDK.Interfaces/IConfiguration"; import { INotificationListener } from "../JavaScriptSDK.Interfaces/INotificationListener"; import { INotificationManager } from "../JavaScriptSDK.Interfaces/INotificationManager"; import { IPerfEvent } from "../JavaScriptSDK.Interfaces/IPerfEvent"; import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem"; -import { arrForEach, arrIndexOf } from "./HelperFuncs"; import { STR_EVENTS_DISCARDED, STR_EVENTS_SEND_REQUEST, STR_EVENTS_SENT, STR_PERF_EVENT } from "./InternalConstants"; function _runListeners(listeners: INotificationListener[], name: string, isAsync: boolean, callback: (listener: INotificationListener) => void) { diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/PerfManager.ts b/shared/AppInsightsCore/src/JavaScriptSDK/PerfManager.ts index 14918c55..eda53ea2 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/PerfManager.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/PerfManager.ts @@ -1,10 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import dynamicProto from "@microsoft/dynamicproto-js"; +import { isArray, isFunction, objDefineAccessors } from "@nevware21/ts-utils"; import { INotificationManager } from "../JavaScriptSDK.Interfaces/INotificationManager"; import { IPerfEvent } from "../JavaScriptSDK.Interfaces/IPerfEvent"; import { IPerfManager, IPerfManagerProvider } from "../JavaScriptSDK.Interfaces/IPerfManager"; -import { dateNow, isArray, isFunction, objDefineAccessors } from "./HelperFuncs"; +import { dateNow } from "./HelperFuncs"; import { STR_GET_PERF_MGR } from "./InternalConstants"; const strExecutionContextKey = "ctx"; @@ -63,7 +64,6 @@ export class PerfEvent implements IPerfEvent { constructor(name: string, payloadDetails: () => any, isAsync: boolean) { let _self = this; - let accessorDefined = false; _self.start = dateNow(); _self.name = name; _self.isAsync = isAsync; @@ -72,7 +72,7 @@ export class PerfEvent implements IPerfEvent { if (isFunction(payloadDetails)) { // Create an accessor to minimize the potential performance impact of executing the payloadDetails callback let theDetails:any; - accessorDefined = objDefineAccessors(_self, "payload", () => { + objDefineAccessors(_self, "payload", () => { // Delay the execution of the payloadDetails until needed if (!theDetails && isFunction(payloadDetails)) { theDetails = payloadDetails(); @@ -130,10 +130,6 @@ export class PerfEvent implements IPerfEvent { _self.time = dateNow() - _self.start; _self.exTime = _self.time - childTime; _self.complete = () => {}; - if (!accessorDefined && isFunction(payloadDetails)) { - // If we couldn't define the property set during complete -- to minimize the perf impact until after the time - _self.payload = payloadDetails(); - } }; } } diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/ProcessTelemetryContext.ts b/shared/AppInsightsCore/src/JavaScriptSDK/ProcessTelemetryContext.ts index 4cce60ec..4085bd23 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/ProcessTelemetryContext.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/ProcessTelemetryContext.ts @@ -2,6 +2,9 @@ // Licensed under the MIT License. "use strict"; +import { + arrForEach, dumpObj, isArray, isFunction, isNullOrUndefined, isObject, isUndefined, objForEachKey, objFreeze, objKeys +} from "@nevware21/ts-utils"; import { _eInternalMessageId, eLoggingSeverity } from "../JavaScriptSDK.Enums/LoggingEnums"; import { IAppInsightsCore } from "../JavaScriptSDK.Interfaces/IAppInsightsCore"; import { IConfiguration } from "../JavaScriptSDK.Interfaces/IConfiguration"; @@ -15,10 +18,7 @@ import { ITelemetryPluginChain } from "../JavaScriptSDK.Interfaces/ITelemetryPlu import { ITelemetryUnloadState } from "../JavaScriptSDK.Interfaces/ITelemetryUnloadState"; import { ITelemetryUpdateState } from "../JavaScriptSDK.Interfaces/ITelemetryUpdateState"; import { _throwInternal, safeGetLogger } from "./DiagnosticLogger"; -import { dumpObj } from "./EnvUtils"; -import { - arrForEach, isArray, isFunction, isNullOrUndefined, isObject, isUndefined, objExtend, objForEachKey, objFreeze, objKeys, proxyFunctions -} from "./HelperFuncs"; +import { objExtend, proxyFunctions } from "./HelperFuncs"; import { STR_CORE, STR_DISABLED, STR_EMPTY } from "./InternalConstants"; import { doPerf } from "./PerfManager"; import { _getPluginState } from "./TelemetryHelpers"; diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/TelemetryHelpers.ts b/shared/AppInsightsCore/src/JavaScriptSDK/TelemetryHelpers.ts index abf43f2f..5f756339 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/TelemetryHelpers.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/TelemetryHelpers.ts @@ -2,6 +2,7 @@ // Licensed under the MIT License. "use strict"; +import { arrForEach, isFunction } from "@nevware21/ts-utils"; import { IAppInsightsCore } from "../JavaScriptSDK.Interfaces/IAppInsightsCore"; import { IDistributedTraceContext } from "../JavaScriptSDK.Interfaces/IDistributedTraceContext"; import { IProcessTelemetryContext, IProcessTelemetryUnloadContext } from "../JavaScriptSDK.Interfaces/IProcessTelemetryContext"; @@ -11,7 +12,6 @@ import { ITelemetryUnloadState } from "../JavaScriptSDK.Interfaces/ITelemetryUnl import { ITraceParent } from "../JavaScriptSDK.Interfaces/ITraceParent"; import { IUnloadableComponent } from "../JavaScriptSDK.Interfaces/IUnloadableComponent"; import { createElmNodeData } from "./DataCacheHelper"; -import { arrForEach, isFunction } from "./HelperFuncs"; import { STR_CORE, STR_PRIORITY, STR_PROCESS_TELEMETRY } from "./InternalConstants"; import { isValidSpanId, isValidTraceId } from "./W3cTraceParent"; diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/TelemetryInitializerPlugin.ts b/shared/AppInsightsCore/src/JavaScriptSDK/TelemetryInitializerPlugin.ts index c7b20c24..c0aeefaf 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/TelemetryInitializerPlugin.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/TelemetryInitializerPlugin.ts @@ -2,6 +2,7 @@ // // Licensed under the MIT License. import dynamicProto from "@microsoft/dynamicproto-js"; +import { arrForEach, dumpObj } from "@nevware21/ts-utils"; import { _eInternalMessageId, eLoggingSeverity } from "../JavaScriptSDK.Enums/LoggingEnums"; import { IProcessTelemetryContext } from "../JavaScriptSDK.Interfaces/IProcessTelemetryContext"; import { @@ -10,8 +11,7 @@ import { import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem"; import { BaseTelemetryPlugin } from "./BaseTelemetryPlugin"; import { _throwInternal } from "./DiagnosticLogger"; -import { dumpObj } from "./EnvUtils"; -import { arrForEach, getExceptionName } from "./HelperFuncs"; +import { getExceptionName } from "./HelperFuncs"; interface _IInternalTelemetryInitializerHandler { id: number; diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/UnloadHandlerContainer.ts b/shared/AppInsightsCore/src/JavaScriptSDK/UnloadHandlerContainer.ts index 0f3b7a96..3f917e5c 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/UnloadHandlerContainer.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/UnloadHandlerContainer.ts @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +import { arrForEach, dumpObj } from "@nevware21/ts-utils"; import { _eInternalMessageId, eLoggingSeverity } from "../JavaScriptSDK.Enums/LoggingEnums"; import { IProcessTelemetryUnloadContext } from "../JavaScriptSDK.Interfaces/IProcessTelemetryContext"; import { ITelemetryUnloadState } from "../JavaScriptSDK.Interfaces/ITelemetryUnloadState"; import { _throwInternal } from "./DiagnosticLogger"; -import { dumpObj } from "./EnvUtils"; -import { arrForEach } from "./HelperFuncs"; export type UnloadHandler = (itemCtx: IProcessTelemetryUnloadContext, unloadState: ITelemetryUnloadState) => void; diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/W3cTraceParent.ts b/shared/AppInsightsCore/src/JavaScriptSDK/W3cTraceParent.ts index c32f0f0f..247925f1 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/W3cTraceParent.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/W3cTraceParent.ts @@ -1,7 +1,7 @@ +import { isArray, isString, strTrim } from "@nevware21/ts-utils"; import { ITraceParent } from "../JavaScriptSDK.Interfaces/ITraceParent"; import { generateW3CId } from "./CoreUtils"; import { findMetaTag, findNamedServerTiming } from "./EnvUtils"; -import { isArray, isString, strTrim } from "./HelperFuncs"; // using {0,16} for leading and trailing whitespace just to constrain the possible runtime of a random string const TRACE_PARENT_REGEX = /^([\da-f]{2})-([\da-f]{32})-([\da-f]{16})-([\da-f]{2})(-[^\s]*)?$/; diff --git a/shared/AppInsightsCore/src/applicationinsights-core-js.ts b/shared/AppInsightsCore/src/applicationinsights-core-js.ts index 9cdf5992..e355d807 100644 --- a/shared/AppInsightsCore/src/applicationinsights-core-js.ts +++ b/shared/AppInsightsCore/src/applicationinsights-core-js.ts @@ -20,17 +20,23 @@ export { BaseCore } from "./JavaScriptSDK/BaseCore"; export { BaseTelemetryPlugin } from "./JavaScriptSDK/BaseTelemetryPlugin"; export { randomValue, random32, mwcRandomSeed, mwcRandom32, newId } from "./JavaScriptSDK/RandomHelper"; export { - CoreUtils, ICoreUtils, EventHelper, IEventHelper, Undefined, newGuid, perfNow, generateW3CId, - disableCookies, canUseCookies, getCookie, setCookie, deleteCookie, _legacyCookieMgr + Undefined, newGuid, perfNow, generateW3CId } from "./JavaScriptSDK/CoreUtils"; export { - isTypeof, isUndefined, isNullOrUndefined, hasOwnProperty, isObject, isFunction, normalizeJsName, - objForEachKey, strEndsWith, strStartsWith, isDate, isArray, isError, isString, isNumber, isBoolean, toISOString, arrForEach, arrIndexOf, - arrMap, arrReduce, strTrim, objKeys, objDefineAccessors, dateNow, getExceptionName, throwError, strContains, isSymbol, - setValue, getSetValue, isNotTruthy, isTruthy, proxyAssign, proxyFunctions, proxyFunctionAs, createClassFromInterface, optimizeObject, - isNotUndefined, isNotNullOrUndefined, objFreeze, objSeal, objExtend, objToString, deepFreeze + normalizeJsName, toISOString, dateNow, getExceptionName, strContains, setValue, getSetValue, + proxyAssign, proxyFunctions, proxyFunctionAs, createClassFromInterface, optimizeObject, + isNotUndefined, isNotNullOrUndefined, objExtend } from "./JavaScriptSDK/HelperFuncs"; -export { EnumValue, createEnumStyle, EnumMap, createEnumMap, createValueMap } from "./JavaScriptSDK.Enums/EnumHelperFuncs"; + +export { + isArray, isTypeof, isUndefined, isNullOrUndefined, objHasOwnProperty as hasOwnProperty, isObject, isFunction, + objForEachKey, strEndsWith, strStartsWith, isDate, isError, isString, isNumber, isBoolean, arrForEach, arrIndexOf, + arrReduce, arrMap, strTrim, objKeys, objDefineAccessors, throwError, isSymbol, + isNotTruthy, isTruthy, objFreeze, objSeal, objToString, objDeepFreeze as deepFreeze, + getInst as getGlobalInst, hasWindow, getWindow, hasDocument, getDocument, hasNavigator, getNavigator, hasHistory, + getHistory, dumpObj +} from "@nevware21/ts-utils"; +export { EnumValue, createEnumStyle, createValueMap } from "./JavaScriptSDK.Enums/EnumHelperFuncs"; export { attachEvent, detachEvent, addEventHandler, addEventListeners, addPageUnloadEventListener, addPageHideEventListener, addPageShowEventListener, removeEventHandler, removeEventListeners, removePageUnloadEventListener, removePageHideEventListener, removePageShowEventListener, eventOn, eventOff, @@ -38,9 +44,8 @@ export { } from "./JavaScriptSDK/EventHelpers"; export { - getGlobalInst, hasWindow, getWindow, hasDocument, getDocument, getCrypto, getMsCrypto, - hasNavigator, getNavigator, hasHistory, getHistory, getLocation, getPerformance, hasJSON, getJSON, - isReactNative, getConsole, dumpObj, isIE, getIEVersion, isSafari, + getCrypto, getMsCrypto, getLocation, getPerformance, hasJSON, getJSON, + isReactNative, getConsole, isIE, getIEVersion, isSafari, setEnableEnvMocks, isBeaconsSupported, isFetchSupported, useXDomainRequest, isXhrSupported, findMetaTag, findNamedServerTiming } from "./JavaScriptSDK/EnvUtils"; diff --git a/shared/AppInsightsCore/tsconfig.json b/shared/AppInsightsCore/tsconfig.json index f307d23b..598edf97 100644 --- a/shared/AppInsightsCore/tsconfig.json +++ b/shared/AppInsightsCore/tsconfig.json @@ -5,7 +5,7 @@ "noImplicitAny": true, "module": "es6", "moduleResolution": "node", - "target": "es3", + "target": "es5", "forceConsistentCasingInFileNames": true, "importHelpers": true, "noEmitHelpers": true, diff --git a/tools/applicationinsights-web-snippet/package.json b/tools/applicationinsights-web-snippet/package.json index 4f5a65ba..b3e78cc6 100644 --- a/tools/applicationinsights-web-snippet/package.json +++ b/tools/applicationinsights-web-snippet/package.json @@ -22,7 +22,7 @@ "license": "MIT", "devDependencies": { "@microsoft/applicationinsights-rollup-plugin-uglify3-js": "1.0.0", - "@microsoft/applicationinsights-rollup-es3": "1.1.3", + "@microsoft/applicationinsights-rollup-es5": "1.0.0", "typescript": "^4.3.4", "tslib": "^2.0.0", "magic-string": "^0.25.7", diff --git a/tools/applicationinsights-web-snippet/tsconfig.json b/tools/applicationinsights-web-snippet/tsconfig.json index b56c88f3..74f5003b 100644 --- a/tools/applicationinsights-web-snippet/tsconfig.json +++ b/tools/applicationinsights-web-snippet/tsconfig.json @@ -4,7 +4,7 @@ "noImplicitAny": true, "module": "es6", "moduleResolution": "Node", - "target": "es3", + "target": "es5", "alwaysStrict": true, "suppressImplicitAnyIndexErrors": true, "allowSyntheticDefaultImports": true, diff --git a/tools/chrome-debug-extension/package.json b/tools/chrome-debug-extension/package.json index f6e70ecd..5e84195d 100644 --- a/tools/chrome-debug-extension/package.json +++ b/tools/chrome-debug-extension/package.json @@ -46,6 +46,7 @@ "@microsoft/applicationinsights-common": "2.8.6", "@microsoft/applicationinsights-shims": "2.0.1", "@microsoft/dynamicproto-js": "^1.1.6", + "@nevware21/ts-utils": "^0.4.1", "file-saver": "^2.0.0", "react": "^17.0.2", "react-dom": "^17.0.2", diff --git a/tools/chrome-debug-extension/src/LogEntry.ts b/tools/chrome-debug-extension/src/LogEntry.ts index b46423de..3f063085 100644 --- a/tools/chrome-debug-extension/src/LogEntry.ts +++ b/tools/chrome-debug-extension/src/LogEntry.ts @@ -1,8 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -import { Util } from "@microsoft/applicationinsights-common"; -import { isBoolean, isNumber, isObject, isString, objToString } from "@microsoft/applicationinsights-core-js"; +import { isArray, isBoolean, isError, isNumber, isObject, isString, objToString } from "@microsoft/applicationinsights-core-js"; import { MAX_DEPTH, formatLogElements, getTargetKeys, getTargetName, makeRegex, toggleClassName, traverseAndReplace } from "./helpers"; export class LogEntry { @@ -32,13 +31,13 @@ export class LogEntry { function _testObj(rg: RegExp, value: any, excludedKeys: string[], includeFunctions: boolean): boolean { if (value !== null && value !== undefined && value !== "") { - if (Util.isArray(value)) { + if (isArray(value)) { for (let lp = 0; lp < value.length; lp++) { if (_testObj(rg, value[lp], excludedKeys, includeFunctions)) { return true; } } - } else if (isObject(value) || Util.isError(value)) { + } else if (isObject(value) || isError(value)) { let keys = getTargetKeys(value, excludedKeys, includeFunctions); for (let lp = 0; lp < keys.length; lp++) { let key = keys[lp]; diff --git a/tools/chrome-debug-extension/src/helpers.ts b/tools/chrome-debug-extension/src/helpers.ts index 381ea05f..04d1a540 100644 --- a/tools/chrome-debug-extension/src/helpers.ts +++ b/tools/chrome-debug-extension/src/helpers.ts @@ -1,10 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -import { Util } from "@microsoft/applicationinsights-common"; -import { - arrForEach, arrIndexOf, hasOwnProperty, isFunction, isObject, isString, isSymbol, objKeys -} from "@microsoft/applicationinsights-core-js"; +import { arrForEach, arrIndexOf, getIEVersion, hasOwnProperty, isArray, isError, isFunction, isObject, isString, isSymbol, objKeys } from "@microsoft/applicationinsights-core-js"; import { strShimPrototype } from "@microsoft/applicationinsights-shims"; const strConstructor = "constructor"; @@ -234,7 +231,7 @@ function _toString(value: any) { export function getTargetKeys(target: any, excludedKeys: string[], includeFunctions: boolean) { let keys: string[] = objKeys(target); - if (!Util.isArray(target)) { + if (!isArray(target)) { try { if (Object[strGetOwnPropertyNames]) { // We need to use this for built in objects such as Error which don't return their values via objKeys because they are not enumerable for example @@ -280,8 +277,8 @@ export function formatLogElements(target: Object, tmLabel: string, key: string, thingsReferenced = []; } - let isObj = isObject(target) || Util.isError(target); - let isErr = target && target["baseType"] && target["baseType"] === "ExceptionData" || Util.isError(target); + let isObj = isObject(target) || isError(target); + let isErr = target && target["baseType"] && target["baseType"] === "ExceptionData" || isError(target); const children: HTMLElement[] = []; @@ -340,7 +337,7 @@ export function formatLogElements(target: Object, tmLabel: string, key: string, builder.className = "empty"; builder.innerText = ``; children.push(builder); - } else if (targetValue !== null && (isObject(targetValue) || Util.isError(targetValue))) { + } else if (targetValue !== null && (isObject(targetValue) || isError(targetValue))) { thingsReferenced.push(target); let formatted = formatLogElements(targetValue, "", key, level + 1, textFilter, excludeKeys, thingsReferenced, includeFunctions); thingsReferenced.pop(); @@ -404,7 +401,7 @@ export function formatLogElements(target: Object, tmLabel: string, key: string, let currentLine = document.createElement("span"); if (isObj || children.length) { innerText = `${key ? key : "obj"}: `; - if (Util.isArray(target)) { + if (isArray(target)) { innerText += `[${getTargetKeys(target, excludeKeys, includeFunctions as boolean).length}]`; } else { let targetName = getTargetName(target); @@ -448,7 +445,7 @@ export function formatLogElements(target: Object, tmLabel: string, key: string, } const openHandler = (evt: Event, forceState?: boolean) => { evt.stopPropagation(); - if (Util.getIEVersion()) { + if (getIEVersion()) { focusHandler(evt, target, level, excludeKeys, includeFunctions as boolean); } if (forceState !== undefined && openState === forceState) { diff --git a/tools/grunt-tasks/minifyNames.js b/tools/grunt-tasks/minifyNames.js index 57b8654d..c79fc565 100644 --- a/tools/grunt-tasks/minifyNames.js +++ b/tools/grunt-tasks/minifyNames.js @@ -12,9 +12,9 @@ var AutoGeneratedConstFile = "// ##############################################################\n" + "// AUTO GENERATED FILE: This file is Auto Generated during build.\n" + "// ##############################################################\n\n" + - "// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" + - "// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\n" + - "// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n"; + "// ###########################################################################################################################################\n" + + "// Note: DON'T Export these const from the package as we are still targeting IE this will export a mutable variables that someone could change\n" + + "// ###########################################################################################################################################\n\n"; const encodeValues = ".();[]:"; const defaultGeneratedConstantFile = "./src/__DynamicConstants.ts"; diff --git a/tools/rollup-es3/Tests/Unit/src/Es3Rollup.Tests.ts b/tools/rollup-es3/Tests/Unit/src/Es3Rollup.Tests.ts deleted file mode 100644 index 3dbe107c..00000000 --- a/tools/rollup-es3/Tests/Unit/src/Es3Rollup.Tests.ts +++ /dev/null @@ -1,698 +0,0 @@ -import { AITestClass } from "@microsoft/ai-test-framework"; -import { es3Check, es3Poly, importCheck } from "../../../src/applicationinsights-rollup-es3"; - -export class Es3RollupTests extends AITestClass { - - public testInitialize() { - } - - private visibleNewlines(value) { - if (value) { - return value.replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/\t/g, "\\t"); - } - - return value; - } - - private convertNewlines(value, newline) { - if (value) { - return value.replace(/\n/g, newline); - } - - return value; - } - - private testPolyNoChange(options:any, input:string, id:string = null) { - let plugin = es3Poly(options); - - QUnit.assert.equal(plugin.name, "ai-rollup-es3poly"); - QUnit.assert.equal(plugin.renderChunk(input, { filename: id ? id : "test.js" }), null); - QUnit.assert.equal(plugin.transform(input, id ? id : "testId"), null); - } - - private testCheckNoMatch(options:any, input:string) { - let plugin = es3Check(options); - - QUnit.assert.equal(plugin.name, "ai-rollup-es3check"); - QUnit.assert.equal(plugin.renderChunk(input, { filename: "test.js" }), null); - QUnit.assert.equal(plugin.transform(input, "testId"), null); - } - - public testImportCheck(options:any, input:string) { - let plugin = importCheck(options); - - QUnit.assert.equal(plugin.name, "ai-rollup-importcheck"); - QUnit.assert.equal(plugin.renderChunk(input, { filename: "test.js" }), null); - QUnit.assert.equal(plugin.transform(input, "testId"), null); - } - - public testImportCheckFail(options:any, input:string, renderExpected:string, transformExpected:string = null) { - let plugin = importCheck(options); - - QUnit.assert.equal(plugin.name, "ai-rollup-importcheck"); - - this.testError(plugin, input, input, renderExpected, transformExpected); - } - - private doTest(plugin:any, input:string, expected:string) { - this.testExpected(plugin, input, expected); - this.testExpected(plugin, this.convertNewlines(input, "\r"), this.convertNewlines(expected, "\r")); - this.testExpected(plugin, this.convertNewlines(input, "\r\n"), this.convertNewlines(expected, "\r\n")); - this.testExpected(plugin, this.convertNewlines(input, "\n\r"), this.convertNewlines(expected, "\n\r")); - } - - private testExpected(plugin:any, input:string, expected:string) { - QUnit.assert.equal(plugin.name, "ai-rollup-es3poly"); - let result = plugin.renderChunk(input, { filename: "test.js" }); - QUnit.assert.equal(result != null ? result.code : null, expected, this.visibleNewlines(result != null ? result.code : null)); - - result = plugin.transform(input, "testId"); - QUnit.assert.equal(result != null ? result.code : null, expected, this.visibleNewlines(result != null ? result.code : null)); - } - - private testError(plugin:any, message:string, input:string, renderExpected:string, transformExpected:string = null) { - QUnit.assert.throws(() => { - plugin.renderChunk(input, { filename: "test.js" }); - }, new Error(renderExpected), "renderChunk:" + (message || input)); - - QUnit.assert.throws(() => { - plugin.transform(input, "test.js"); - }, new Error(transformExpected || renderExpected.replace(/during renderChunk/g, "during transform")), "transform:" + (message || input)); - } - - public registerTests() { - this.testCase({ - name: "No matching values for Es3Poly", - test: () => { - this.testPolyNoChange(null, "Nothing removed"); - this.testPolyNoChange(null, "ClassName.prototype.anotherMethod = function () {\n};\n"); - - this.testPolyNoChange(null, - "ClassName.prototype.methodName = function () {\n" + - " // This is a comment for a dynamic proto stub\n" + - "};\n"); - - this.testPolyNoChange(null, - "ClassName.prototype.methodName = function () {\n" + - " // This is a comment for a dynamic proto stub\n" + - "};\n"); - - this.testPolyNoChange(null, - "// @Stub -- Type 1 comment\n" + - "function methodName() {\n" + - " // This is a comment for a dynamic proto stub\n" + - "};\n"); - - this.testPolyNoChange(null, - "function methodName() {\n" + - " // @Stub -- Type 2 single line comment\n" + - "};\n"); - - this.testPolyNoChange(null, - "function methodName() {\n" + - " /* @Stub -- Type 2 multiline comment */\n" + - "};\n"); - - this.testPolyNoChange(null, - "function methodName() {\n" + - " /* @Stub -- Type 2 multiline comment\n" + - " * Continuation of a multi-line comment/\n" + - " */\n" + - "};\n"); - } - }); - - this.testCase({ - name: "No matching values for Es3Check", - test: () => { - this.testCheckNoMatch(null, "Nothing removed"); - this.testCheckNoMatch(null, "ClassName.prototype.anotherMethod = function () {\n};\n"); - this.testCheckNoMatch(null, "telemertyItem.time = CoreUtils.toISOString(new Date());"); - this.testCheckNoMatch(null, "var responseHeaders = {};\nresponse.headers.forEach(function (value, name) {\n"); - } - }); - - this.testCase({ - name: "Test Es3Polyfil implementations", - test: () => { - this.testPolyNoChange(null, - "Object[\"defineProperty\"](exports, '__esModule', { value: true });"); - - this.testExpected( - es3Poly(), - "Object.defineProperty(exports, '__esModule', { value: true });", - "(function(obj, prop, descriptor) { /* ai_es3_polyfil defineProperty */ var func = Object[\"defineProperty\"]; if (func) { try { return func(obj, prop, descriptor); } catch(e) { /* IE8 defines defineProperty, but will throw */ } } if (descriptor && typeof descriptor.value !== undefined) { obj[prop] = descriptor.value; } return obj; })(exports, '__esModule', { value: true });"); - - this.testExpected( - es3Poly(), - "return r && Object.defineProperty(exports, '__esModule', { value: true }), b;", - "return r && (function(obj, prop, descriptor) { /* ai_es3_polyfil defineProperty */ var func = Object[\"defineProperty\"]; if (func) { try { return func(obj, prop, descriptor); } catch(e) { /* IE8 defines defineProperty, but will throw */ } } if (descriptor && typeof descriptor.value !== undefined) { obj[prop] = descriptor.value; } return obj; })(exports, '__esModule', { value: true }), b;"); - - this.testExpected( - es3Poly(), - "d = Object.getOwnPropertyDescriptor(obj, 'foo'), a=b;", - "d = (function(obj, prop) { /* ai_es3_polyfil getOwnPropertyDescriptor */var func = Object[\"getOwnPropertyDescriptor\"]; if (func) { return func(obj, prop); } return undefined; })(obj, 'foo'), a=b;"); - - this.testExpected( - es3Poly(), - "d = Object.getOwnPropertyDescriptor(obj, 'foo');", - "d = (function(obj, prop) { /* ai_es3_polyfil getOwnPropertyDescriptor */var func = Object[\"getOwnPropertyDescriptor\"]; if (func) { return func(obj, prop); } return undefined; })(obj, 'foo');"); - - this.testExpected( - es3Poly(), - "Rectangle.prototype = Object.create(Shape.prototype);", - "Rectangle.prototype = (function(obj) { /* ai_es3_polyfil create */ var func = Object[\"create\"]; if (func) { return func(obj); } if (obj == null) { return {}; }; var type = typeof obj; if (type !== 'object' && type !== 'function') { throw new TypeError('Object prototype may only be an Object:' + obj); } function tmpFunc() {}; tmpFunc.prototype = obj; return new tmpFunc(); })(Shape.prototype);"); - - // We don't support a polyfil with a 2nd argument - this.testError( - es3Poly(), - null, - "Rectangle.prototype = Object.create(Shape.prototype, propsObj);", - "Invalid ES3 function [Object.create(] found on line [1], column [23], position [22] during renderChunk - test.js\n" + - "[Object.create] is not supported in an ES3 environment, use the helper function objCreate() or add an explicit existence check\n" + - "\n" + - "--------------------=([Object.create(])=--------------------\n" - ); - - this.testExpected( - es3Poly(), - "a = Object.freeze(obj);", - "a = (function(obj) { /* ai_es3_polyfil freeze */ var func = Object[\"freeze\"]; if (func) { return func(obj); } return obj; })(obj);"); - - this.testExpected( - es3Poly(), - "a = Object.seal(obj);", - "a = (function(obj) { /* ai_es3_polyfil seal */ var func = Object[\"seal\"]; if (func) { return func(obj); } return obj; })(obj);"); - - } - }); - - this.testCase({ - name: "Test recursive replacements", - test: () => { - this.testExpected( - es3Poly(), - " var PropertiesPluginIdentifier = \"AppInsightsPropertiesPlugin\";\n"+ - " var BreezeChannelIdentifier = \"AppInsightsChannelPlugin\";\n"+ - " var Common = /*#__PURE__*/Object.freeze({\n"+ - " PropertiesPluginIdentifier: PropertiesPluginIdentifier,\n"+ - " BreezeChannelIdentifier: BreezeChannelIdentifier,\n"+ - " Util: Util,\n"+ - " CorrelationIdHelper: CorrelationIdHelper,\n"+ - " UrlHelper: UrlHelper,\n"+ - " DateTimeUtils: DateTimeUtils,\n"+ - " ConnectionStringParser: ConnectionStringParser,\n"+ - " get FieldType () { return FieldType; },\n"+ - " RequestHeaders: RequestHeaders,\n"+ - " DisabledPropertyName: DisabledPropertyName,\n"+ - " ProcessLegacy: ProcessLegacy,\n"+ - " SampleRate: SampleRate,\n"+ - " HttpMethod: HttpMethod,\n"+ - " DEFAULT_BREEZE_ENDPOINT: DEFAULT_BREEZE_ENDPOINT,\n"+ - " AIData: Data,\n"+ - " AIBase: Base,\n"+ - " Envelope: Envelope$1,\n"+ - " Event: Event$1,\n"+ - " Exception: Exception,\n"+ - " Metric: Metric,\n"+ - " PageView: PageView,\n"+ - " get SeverityLevel () { return exports.SeverityLevel; },\n"+ - " ConfigurationManager: ConfigurationManager,\n"+ - " ContextTagKeys: ContextTagKeys,\n"+ - " DataSanitizer: DataSanitizer,\n"+ - " TelemetryItemCreator: TelemetryItemCreator,\n"+ - " CtxTagKeys: CtxTagKeys,\n"+ - " Extensions: Extensions,\n"+ - " get DistributedTracingModes () { return exports.DistributedTracingModes; }\n"+ - "});", - " var PropertiesPluginIdentifier = \"AppInsightsPropertiesPlugin\";\n"+ - " var BreezeChannelIdentifier = \"AppInsightsChannelPlugin\";\n"+ - " var Common = /*#__PURE__*/(function(obj) { /* ai_es3_polyfil freeze */ var func = Object[\"freeze\"]; if (func) { return func(obj); } return obj; })({\n"+ - " PropertiesPluginIdentifier: PropertiesPluginIdentifier,\n"+ - " BreezeChannelIdentifier: BreezeChannelIdentifier,\n"+ - " Util: Util,\n"+ - " CorrelationIdHelper: CorrelationIdHelper,\n"+ - " UrlHelper: UrlHelper,\n"+ - " DateTimeUtils: DateTimeUtils,\n"+ - " ConnectionStringParser: ConnectionStringParser,\n"+ - " FieldType: (function(obj) { /* ai_es3polyfil get FieldType */ if (obj == null || typeof obj !== \"object\") { return obj; } var cpy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) { cpy[attr] = obj[attr]; } } return cpy; })(FieldType),\n"+ - " RequestHeaders: RequestHeaders,\n"+ - " DisabledPropertyName: DisabledPropertyName,\n"+ - " ProcessLegacy: ProcessLegacy,\n"+ - " SampleRate: SampleRate,\n"+ - " HttpMethod: HttpMethod,\n"+ - " DEFAULT_BREEZE_ENDPOINT: DEFAULT_BREEZE_ENDPOINT,\n"+ - " AIData: Data,\n"+ - " AIBase: Base,\n"+ - " Envelope: Envelope$1,\n"+ - " Event: Event$1,\n"+ - " Exception: Exception,\n"+ - " Metric: Metric,\n"+ - " PageView: PageView,\n"+ - " SeverityLevel: (function(obj) { /* ai_es3polyfil get SeverityLevel */ if (obj == null || typeof obj !== \"object\") { return obj; } var cpy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) { cpy[attr] = obj[attr]; } } return cpy; })(exports.SeverityLevel),\n"+ - " ConfigurationManager: ConfigurationManager,\n"+ - " ContextTagKeys: ContextTagKeys,\n"+ - " DataSanitizer: DataSanitizer,\n"+ - " TelemetryItemCreator: TelemetryItemCreator,\n"+ - " CtxTagKeys: CtxTagKeys,\n"+ - " Extensions: Extensions,\n"+ - " DistributedTracingModes: (function(obj) { /* ai_es3polyfil get DistributedTracingModes */ if (obj == null || typeof obj !== \"object\") { return obj; } var cpy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) { cpy[attr] = obj[attr]; } } return cpy; })(exports.DistributedTracingModes)\n"+ - "});"); - } - }); - - this.testCase({ - name: "Test Errors Es3Check", - test: () => { - this.testError( - es3Check(), - null, - "var dt = new Date();\n" + - "\n" + - "dt.toISOString ();\n" + - "Can.toISOString();\n", - "Invalid ES3 function [dt.toISOString (] found on line [3], column [1], position [22] during renderChunk - test.js\n" + - "[dt.toISOString (] is not supported in an ES3 environment, use getISOString()\n" + - "1 :var dt = new Date();\n" + - "2 :\n" + - "3 :dt.toISOString ();\n" + - " ^^^^^^^^^^^^^^^^\n" + - "4 :Can.toISOString();\n" + - "\n" + - "--------------------=([dt.toISOString (])=--------------------\n" + - "Invalid ES3 function [Can.toISOString(] found on line [4], column [1], position [41] during renderChunk - test.js\n" + - "[Can.toISOString(] is not supported in an ES3 environment, use getISOString()\n" + - "1 :var dt = new Date();\n" + - "2 :\n" + - "3 :dt.toISOString ();\n" + - "4 :Can.toISOString();\n" + - " ^^^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Can.toISOString(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = [];\n" + - "\n" + - "arr.forEach(function (value, name) { });\n", - "Invalid ES3 function [arr.forEach(] found on line [3], column [1], position [15] during renderChunk - test.js\n" + - "[arr.forEach(] is not a supported array method in an ES3 environment, use arrForEach().\n" + - "1 :var arr = [];\n" + - "2 :\n" + - "3 :arr.forEach(function (value, name) { });\n" + - " ^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([arr.forEach(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.defineProperty(a);\n", - "Invalid ES3 function [Object.defineProperty(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.defineProperty(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.defineProperty(a);\n" + - " ^^^^^^^^^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.defineProperty(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.create(a);\n", - "Invalid ES3 function [Object.create(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.create(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.create(a);\n" + - " ^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.create(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.defineProperties(a);\n", - "Invalid ES3 function [Object.defineProperties(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.defineProperties(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.defineProperties(a);\n" + - " ^^^^^^^^^^^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.defineProperties(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.getOwnPropertyNames(a);\n", - "Invalid ES3 function [Object.getOwnPropertyNames(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.getOwnPropertyNames(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.getOwnPropertyNames(a);\n" + - " ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.getOwnPropertyNames(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.getPrototypeOf(a);\n", - "Invalid ES3 function [Object.getPrototypeOf(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.getPrototypeOf(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.getPrototypeOf(a);\n" + - " ^^^^^^^^^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.getPrototypeOf(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.getOwnPropertyDescriptor(a);\n", - "Invalid ES3 function [Object.getOwnPropertyDescriptor(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.getOwnPropertyDescriptor(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.getOwnPropertyDescriptor(a);\n" + - " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.getOwnPropertyDescriptor(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.preventExtensions(a);\n", - "Invalid ES3 function [Object.preventExtensions(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.preventExtensions(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.preventExtensions(a);\n" + - " ^^^^^^^^^^^^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.preventExtensions(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.is(a);\n", - "Invalid ES3 function [Object.is(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.is(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.is(a);\n" + - " ^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.is(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.isExtensible(a);\n", - "Invalid ES3 function [Object.isExtensible(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.isExtensible(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.isExtensible(a);\n" + - " ^^^^^^^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.isExtensible(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.seal(a);\n", - "Invalid ES3 function [Object.seal(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.seal(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.seal(a);\n" + - " ^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.seal(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.isSealed(a);\n", - "Invalid ES3 function [Object.isSealed(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.isSealed(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.isSealed(a);\n" + - " ^^^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.isSealed(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.freeze(a);\n", - "Invalid ES3 function [Object.freeze(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.freeze(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.freeze(a);\n" + - " ^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.freeze(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.isFrozen(a);\n", - "Invalid ES3 function [Object.isFrozen(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.isFrozen(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.isFrozen(a);\n" + - " ^^^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.isFrozen(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.fromEntries(a);\n", - "Invalid ES3 function [Object.fromEntries(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.fromEntries(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.fromEntries(a);\n" + - " ^^^^^^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.fromEntries(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.entries(a);\n", - "Invalid ES3 function [Object.entries(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.entries(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.entries(a);\n" + - " ^^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.entries(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var arr = Object.assign(a);\n", - "Invalid ES3 function [Object.assign(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + - "[Object.assign(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var arr = Object.assign(a);\n" + - " ^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.assign(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var a = Object.isPrototypeOf(a);\n", - "Invalid ES3 function [Object.isPrototypeOf(] found on line [1], column [9], position [8] during renderChunk - test.js\n" + - "[Object.isPrototypeOf(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var a = Object.isPrototypeOf(a);\n" + - " ^^^^^^^^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.isPrototypeOf(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var x = Object.setPrototypeOf(a);\n", - "Invalid ES3 function [Object.setPrototypeOf(] found on line [1], column [9], position [8] during renderChunk - test.js\n" + - "[Object.setPrototypeOf(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var x = Object.setPrototypeOf(a);\n" + - " ^^^^^^^^^^^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.setPrototypeOf(])=--------------------\n" - ); - - this.testError( - es3Check(), - null, - "var x = Object.keys(a);\n", - "Invalid ES3 function [Object.keys(] found on line [1], column [9], position [8] during renderChunk - test.js\n" + - "[Object.keys(] is not supported in an ES3 environment, use a helper function or add explicit check for existence\n" + - "1 :var x = Object.keys(a);\n" + - " ^^^^^^^^^^^^\n" + - "\n" + - "--------------------=([Object.keys(])=--------------------\n" - ); - - } - }); - - this.testCase({ - name: "Test Import Check", - test: () => { - let plugin = importCheck({}); - - this.testImportCheck({}, ""); - this.testImportCheck({ exclude: ["index"]}, "import {\nSomeClass\n} from './MyCode'"); - this.testImportCheck({ exclude: ["index"]}, "import {\nSomeClass\n} from \"./MyCode\""); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import { A, B, C } from './Index';", - "Invalid Import detected [import { A, B, C } from './Index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from './Index']\n" + - "\n" + - "--------------------=([import { A, B, C } from './Index'])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import { A, B, C } from \"./Index\";", - "Invalid Import detected [import { A, B, C } from \"./Index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from \"./Index\"]\n" + - "\n" + - "--------------------=([import { A, B, C } from \"./Index\"])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import { A, B, C } from './Index'", - "Invalid Import detected [import { A, B, C } from './Index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from './Index']\n" + - "\n" + - "--------------------=([import { A, B, C } from './Index'])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import { A, B, C } from \"./Index\"", - "Invalid Import detected [import { A, B, C } from \"./Index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from \"./Index\"]\n" + - "\n" + - "--------------------=([import { A, B, C } from \"./Index\"])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import { A, B, C } from './index';", - "Invalid Import detected [import { A, B, C } from './index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from './index']\n" + - "\n" + - "--------------------=([import { A, B, C } from './index'])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import { A, B, C } from \"./index\";", - "Invalid Import detected [import { A, B, C } from \"./index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from \"./index\"]\n" + - "\n" + - "--------------------=([import { A, B, C } from \"./index\"])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import { A, B, C } from './index'", - "Invalid Import detected [import { A, B, C } from './index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from './index']\n" + - "\n" + - "--------------------=([import { A, B, C } from './index'])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import { A, B, C } from \"./index\"", - "Invalid Import detected [import { A, B, C } from \"./index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from \"./index\"]\n" + - "\n" + - "--------------------=([import { A, B, C } from \"./index\"])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import { A, B, C } from './folder/index';", - "Invalid Import detected [import { A, B, C } from './folder/index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from './folder/index']\n" + - "\n" + - "--------------------=([import { A, B, C } from './folder/index'])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import { A, B, C } from \"./folder/index\";", - "Invalid Import detected [import { A, B, C } from \"./folder/index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from \"./folder/index\"]\n" + - "\n" + - "--------------------=([import { A, B, C } from \"./folder/index\"])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import { A, B, C } from './folder/index'", - "Invalid Import detected [import { A, B, C } from './folder/index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from './folder/index']\n" + - "\n" + - "--------------------=([import { A, B, C } from './folder/index'])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import { A, B, C } from \"./folder/index\"", - "Invalid Import detected [import { A, B, C } from \"./folder/index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from \"./folder/index\"]\n" + - "\n" + - "--------------------=([import { A, B, C } from \"./folder/index\"])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import * from './Index';", - "Invalid Import detected [import * from './Index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import * from './Index']\n" + - "\n" + - "--------------------=([import * from './Index'])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import * from \"./Index\";", - "Invalid Import detected [import * from \"./Index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import * from \"./Index\"]\n" + - "\n" + - "--------------------=([import * from \"./Index\"])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import * from './Index'", - "Invalid Import detected [import * from './Index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import * from './Index']\n" + - "\n" + - "--------------------=([import * from './Index'])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import * from \"./Index\"", - "Invalid Import detected [import * from \"./Index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import * from \"./Index\"]\n" + - "\n" + - "--------------------=([import * from \"./Index\"])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import * from './folder/Index';", - "Invalid Import detected [import * from './folder/Index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import * from './folder/Index']\n" + - "\n" + - "--------------------=([import * from './folder/Index'])=--------------------\n"); - - this.testImportCheckFail( - { exclude: [ "index" ]}, - "import * from \"./folder/Index\";", - "Invalid Import detected [import * from \"./folder/Index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + - "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import * from \"./folder/Index\"]\n" + - "\n" + - "--------------------=([import * from \"./folder/Index\"])=--------------------\n"); - - } - }); - } -} - diff --git a/tools/rollup-es3/Tests/Unit/src/Es3RollupTests.ts b/tools/rollup-es3/Tests/Unit/src/Es3RollupTests.ts deleted file mode 100644 index 27462496..00000000 --- a/tools/rollup-es3/Tests/Unit/src/Es3RollupTests.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { Es3RollupTests } from './Es3Rollup.Tests'; - -export function runTests() { - new Es3RollupTests().registerTests(); -} diff --git a/tools/rollup-es3/src/applicationinsights-rollup-es3.ts b/tools/rollup-es3/src/applicationinsights-rollup-es3.ts deleted file mode 100644 index 4804f667..00000000 --- a/tools/rollup-es3/src/applicationinsights-rollup-es3.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -import { INamedGroups, IEs3CheckKeyword, IEs3Keyword, IEs3RollupOptions, IImportCheckRollupOptions } from "./es3/Interfaces"; -import { es3Poly } from "./es3/Es3Poly"; -import { es3Check } from "./es3/Es3Check"; -import { importCheck } from "./ImportCheck"; - -export { es3Poly, es3Check, importCheck, INamedGroups, IEs3CheckKeyword, IEs3Keyword, IEs3RollupOptions, IImportCheckRollupOptions }; diff --git a/tools/rollup-es3/src/es3/Es3Tokens.ts b/tools/rollup-es3/src/es3/Es3Tokens.ts deleted file mode 100644 index c2d8a06d..00000000 --- a/tools/rollup-es3/src/es3/Es3Tokens.ts +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -import { IEs3CheckKeyword, IEs3Keyword } from "./Interfaces"; - -export const defaultEs3Tokens:IEs3Keyword[] = [ - { - funcNames: [ /Object\.(defineProperty)[\s]*\(/g ], - errorMsg: "[Object.defineProperty] is not supported in an ES3 environment, use a helper function or add an explicit existence check", - extract: /(Object)\.(defineProperty)[\s]*\(([^)]*)\)([;]?)/g, - checkGroups: [ 2 ], // Identifies that this group MUST contain a value for this to token to be replaced - namedGroups: [ // Used to simulate named RegEx groups and provide replacement token names - { name: "src", idx: 0 }, - { name: "class", idx: 1 }, - { name: "function", idx: 2 }, - { name: "semi", idx: 4}, - { name: "args", idx: 3} - ], - replace:"(function(obj, prop, descriptor) { " + - "/* ai_es3_polyfil %function% */ " + - "var func = %class%[\"%function%\"]; " + - "if (func) { try { return func(obj, prop, descriptor); } catch(e) { /* IE8 defines defineProperty, but will throw */ } } " + - "if (descriptor && typeof descriptor.value !== undefined) { obj[prop] = descriptor.value; } " + - "return obj; " + - "})(%args%)%semi%" - }, - { - funcNames: [/Object\.getOwnPropertyDescriptor[\s]*\(/g ], - errorMsg: "[Object.getOwnPropertyDescriptor] is not supported in an ES3 environment, use a helper function or add an explicit existence check", - extract: /(Object)\.(getOwnPropertyDescriptor)[\s]*\(([^)]*)\)([;]?)/g, - checkGroups: [ 2 ], - namedGroups: [ - { name: "src", idx: 0 }, - { name: "class", idx: 1 }, - { name: "function", idx: 2 }, - { name: "semi", idx: 4}, - { name: "args", idx: 3} - ], - replace:"(function(obj, prop) { " + - "/* ai_es3_polyfil %function% */" + - "var func = %class%[\"%function%\"]; " + - "if (func) { return func(obj, prop); } " + - "return undefined; " + - "})(%args%)%semi%" - }, - { - funcNames: [/Object\.create[\s]*\(/g ], - errorMsg: "[Object.create] is not supported in an ES3 environment, use the helper function objCreate() or add an explicit existence check", - // We are only supporting the version that takes a single argument - extract: /(Object)\.(create)[\s]*\(([^,)]*)\)([;]?)/g, - checkGroups: [ 2 ], - namedGroups: [ - { name: "src", idx: 0 }, - { name: "class", idx: 1 }, - { name: "function", idx: 2 }, - { name: "semi", idx: 4}, - { name: "args", idx: 3} - ], - replace:"(function(obj) { " + - "/* ai_es3_polyfil %function% */ " + - "var func = %class%[\"%function%\"]; " + - // Use build in Object.create - "if (func) { return func(obj); } " + - "if (obj == null) { return {}; }; " + - "var type = typeof obj; " + - "if (type !== 'object' && type !== 'function') { throw new TypeError('Object prototype may only be an Object:' + obj); } " + - "function tmpFunc() {}; tmpFunc.prototype = obj; return new tmpFunc(); " + - "})(%args%)%semi%" - }, - { - funcNames: [/Object\.(freeze|seal)[\s]*\(/g ], - errorMsg: "[Object.freeze] is not supported in an ES3 environment, use a helper or add an explicit existence check", - extract: /(Object)\.(freeze|seal)[\s]*\(([^)]*)\)([;]?)/g, - checkGroups: [ 2 ], - namedGroups: [ - { name: "src", idx: 0 }, - { name: "class", idx: 1 }, - { name: "function", idx: 2 }, - { name: "semi", idx: 4}, - { name: "args", idx: 3} - ], - replace:"(function(obj) { " + - "/* ai_es3_polyfil %function% */ " + - "var func = %class%[\"%function%\"]; " + - // Use existing function if available - "if (func) { return func(obj); } " + - "return obj; " + - "})(%args%)%semi%" - }, - { - funcNames: [ /[\s(,]get[\s]+([\w]+)[\s]*\(\)[\s]*\{/g ], - errorMsg: "[%funcName%] is not supported in an ES3 environment.", - extract: /([\s(,])get[\s]+([\w]+)[\s]*\(\)[\s]*\{[\s]*return[\s]*([^;]*);[\s]*\}/g, - checkGroups: [2, 3], - namedGroups: [ - { name: "src", idx: 0 }, - { name: "prefix", idx: 1 }, - { name: "name", idx: 2 }, - { name: "value", idx: 3 } - ], - replace:"%prefix%%name%: (function(obj) { " + - "/* ai_es3polyfil get %name% */ " + - "if (obj == null || typeof obj !== \"object\") { return obj; } " + - "var cpy = obj.constructor(); " + - "for (var attr in obj) { " + - "if (obj.hasOwnProperty(attr)) { cpy[attr] = obj[attr]; } " + - "} " + - "return cpy; "+ - "})(%value%)" - } -]; - -export const defaultEs3CheckTokens:IEs3CheckKeyword[] = [ - { - funcNames: [ /Object\.(defineProperty|create|getPrototypeOf|getOwnPropertyDescriptor|preventExtensions|is|isExtensible|seal|isSealed|freeze|isFrozen|fromEntries|entries|isPrototypeOf|setPrototypeOf)\(/g ], - errorMsg: "[%funcName%] is not supported in an ES3 environment, use a helper function or add explicit check for existence" - }, - { - funcNames: [ /Object\.(defineProperties)\(/g ], - errorMsg: "[%funcName%] is not supported in an ES3 environment, use a helper function or add explicit check for existence", - ignoreIds: [ - "applicationinsights-react-js", // Don't break build if these exist in the final react extension - "react.production.min.js", // Don't break build if these exist in the react prod source code - "react.development.js" // Don't break build if these exist in the react dev source code - ] - }, - { - funcNames: [ /Object\.(assign|getOwnPropertyNames)\(/g ], - errorMsg: "[%funcName%] is not supported in an ES3 environment, use a helper function or add explicit check for existence", - ignoreIds: [ - "applicationinsights-react-js", // Don't break build if these exist in the final react extension - "object-assign\\index.js", // object-assign node module contains a pre existence check before usage - "object-assign/index.js" // object-assign node module contains a pre existence check before usage - ] - }, - { - funcNames: [ /Object\.(keys)\(/g ], - errorMsg: "[%funcName%] is not supported in an ES3 environment, use a helper function or add explicit check for existence", - ignoreIds: [ - "react.production.min.js", // Don't break build if these exist in the react prod source code - "react.development.js", // Don't break build if these exist in the react dev source code - "applicationinsights-react-js", // Don't break build if these exist in the final react extension - "object-assign\\index.js", // object-assign node module contains a pre existence check before usage - "object-assign/index.js" // object-assign node module contains a pre existence check before usage - ] - }, - { - funcNames: [ /Object\.(getOwnPropertySymbols)\(/g ], - errorMsg: "[%funcName%] is not supported in an ES3 environment, use a helper function or add explicit check for existence", - ignoreIds: [ - "tslib.es6", // tslib.es6 library has a pre existence check before usage - "object-assign\\index.js", // object-assign node module contains a pre existence check before usage - "object-assign/index.js" // object-assign node module contains a pre existence check before usage - ] - }, - { - funcNames: [ /([\w0-9$]*)\.toISOString[\s]*\(/g ], - errorMsg: "[%funcName%] is not supported in an ES3 environment, use getISOString()", - ignoreFuncMatch: [ - // eslint-disable-next-line security/detect-unsafe-regex - /CoreUtils(\$[\d]{0,5})?\.isISOString/, // Make sure this isn't a reference to CoreUtils.isISOString(); CoreUtils$1.isISOString(); - "Utils.toISOString" // or if it's a reference to Utils.isISOString() - ] - }, - { - funcNames: [ /\.(every|some|filter|reduce|reduceRight)[\s]*\(/g ], - errorMsg: "[%funcName%] is not a supported array method in an ES3 environment." - }, - { - funcNames: [ /\.(map)[\s]*\(/g ], - errorMsg: "[%funcName%] is not a supported array method in an ES3 environment.", - ignoreIds: [ - "react.production.min.js", // Don't break build if these exist in the react prod source code - "react.development.js", // Don't break build if these exist in the react dev source code - "applicationinsights-react-js", // Don't break build if these exist in the final react extension - "object-assign\\index.js", // object-assign node module usage is only after checking for existence of Object.assign - "object-assign/index.js" // object-assign node module usage is only after checking for existence of Object.assign - ] - }, - { - funcNames: [ /([\w0-9]*)\.(forEach)[\s]*\(/g ], - errorMsg: "[%funcName%] is not a supported array method in an ES3 environment, use arrForEach().", - ignoreFuncMatch: [ - "headers.forEach" // Ignore patterns that look like the response headers processing - ], - ignoreIds: [ - "applicationinsights-react-js", // Don't break build if these exist in the final react extension - "object-assign\\index.js", // object-assign node module usage is only after checking for existence of Object.assign - "object-assign/index.js" // object-assign node module usage is only after checking for existence of Object.assign - ] - }, - { - funcNames: [ /[\s(,][gs]et[\s]+([\w]+)[\s]*\(\)[\s]*\{/g ], - errorMsg: "[%funcName%] is not supported in an ES3 environment." - }, - { - funcNames: [ /([\w0-9]*)\.(trim)[\s]*\(/g ], - errorMsg: "[%funcName%] is not a supported string method in an ES3 environment, use strTrim().", - ignoreFuncMatch: [ - "Util.trim", // Make sure this isn't a reference to Util.trim() - "DataSanitizer.trim" // Make sure this isn't a reference to Util.trim() - ] - }, - { - funcNames: [ /([\w0-9]*)\.(startsWith)[\s]*\(/g ], - errorMsg: "[%funcName%] is not a supported string method in an ES3 environment, use strStartsWith().", - ignoreFuncMatch: [ - ] - }, - { - funcNames: [ /([\w0-9]*)\.(endsWith)[\s]*\(/g ], - errorMsg: "[%funcName%] is not a supported string method in an ES3 environment, use strEndsWith().", - ignoreFuncMatch: [ - ] - }, - { - funcNames: [ /([\w0-9$]*)(\(\))?\.now[\s]*\(\)/g ], - errorMsg: "[%funcName%] is not supported in an ES3 environment, use dateNow() or perfNow()", - ignoreFuncMatch: [ - "perf.now()", // This assume a pre-check that now actually exists - "dt.now()" // This assume a pre-check that now actually exists - ] - } -]; - diff --git a/tools/rollup-es3/.npmignore b/tools/rollup-es5/.npmignore similarity index 100% rename from tools/rollup-es3/.npmignore rename to tools/rollup-es5/.npmignore diff --git a/tools/rollup-es3/LICENSE b/tools/rollup-es5/LICENSE similarity index 100% rename from tools/rollup-es3/LICENSE rename to tools/rollup-es5/LICENSE diff --git a/tools/rollup-es3/README.md b/tools/rollup-es5/README.md similarity index 95% rename from tools/rollup-es3/README.md rename to tools/rollup-es5/README.md index b3534108..55090c47 100644 --- a/tools/rollup-es3/README.md +++ b/tools/rollup-es5/README.md @@ -3,7 +3,7 @@ [![Build Status](https://travis-ci.org/microsoft/ApplicationInsights-JS.svg?branch=master)](https://travis-ci.org/microsoft/ApplicationInsights-JS) [![npm version](https://badge.fury.io/js/%40microsoft%2Fapplicationinsights-analytics-js.svg)](https://badge.fury.io/js/%40microsoft%2Fapplicationinsights-analytics-js) -Rollup ES3 Support Plugin for the Application Insights Javascript SDK +Rollup ES5/IE Support Plugin for the Application Insights Javascript SDK ## Build: ``` diff --git a/tools/rollup-es5/Tests/Unit/src/Es5Rollup.Tests.ts b/tools/rollup-es5/Tests/Unit/src/Es5Rollup.Tests.ts new file mode 100644 index 00000000..ca0968cb --- /dev/null +++ b/tools/rollup-es5/Tests/Unit/src/Es5Rollup.Tests.ts @@ -0,0 +1,410 @@ +import { AITestClass } from "@microsoft/ai-test-framework"; +import { es5Check, es5Poly, importCheck } from "../../../src/applicationinsights-rollup-es5"; + +export class Es5RollupTests extends AITestClass { + + public testInitialize() { + } + + private visibleNewlines(value) { + if (value) { + return value.replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/\t/g, "\\t"); + } + + return value; + } + + private convertNewlines(value, newline) { + if (value) { + return value.replace(/\n/g, newline); + } + + return value; + } + + private testPolyNoChange(options:any, input:string, id:string = null) { + let plugin = es5Poly(options); + + QUnit.assert.equal(plugin.name, "ai-rollup-es5poly"); + QUnit.assert.equal(plugin.renderChunk(input, { filename: id ? id : "test.js" }), null); + QUnit.assert.equal(plugin.transform(input, id ? id : "testId"), null); + } + + private testCheckNoMatch(options:any, input:string) { + let plugin = es5Check(options); + + QUnit.assert.equal(plugin.name, "ai-rollup-es5check"); + QUnit.assert.equal(plugin.renderChunk(input, { filename: "test.js" }), null); + QUnit.assert.equal(plugin.transform(input, "testId"), null); + } + + public testImportCheck(options:any, input:string) { + let plugin = importCheck(options); + + QUnit.assert.equal(plugin.name, "ai-rollup-importcheck"); + QUnit.assert.equal(plugin.renderChunk(input, { filename: "test.js" }), null); + QUnit.assert.equal(plugin.transform(input, "testId"), null); + } + + public testImportCheckFail(options:any, input:string, renderExpected:string, transformExpected:string = null) { + let plugin = importCheck(options); + + QUnit.assert.equal(plugin.name, "ai-rollup-importcheck"); + + this.testError(plugin, input, input, renderExpected, transformExpected); + } + + private doTest(plugin:any, input:string, expected:string) { + this.testExpected(plugin, input, expected); + this.testExpected(plugin, this.convertNewlines(input, "\r"), this.convertNewlines(expected, "\r")); + this.testExpected(plugin, this.convertNewlines(input, "\r\n"), this.convertNewlines(expected, "\r\n")); + this.testExpected(plugin, this.convertNewlines(input, "\n\r"), this.convertNewlines(expected, "\n\r")); + } + + private testExpected(plugin:any, input:string, expected:string) { + QUnit.assert.equal(plugin.name, "ai-rollup-es5poly"); + let result = plugin.renderChunk(input, { filename: "test.js" }); + QUnit.assert.equal(result != null ? result.code : null, expected, this.visibleNewlines(result != null ? result.code : null)); + + result = plugin.transform(input, "testId"); + QUnit.assert.equal(result != null ? result.code : null, expected, this.visibleNewlines(result != null ? result.code : null)); + } + + private testError(plugin:any, message:string, input:string, renderExpected:string, transformExpected:string = null) { + QUnit.assert.throws(() => { + plugin.renderChunk(input, { filename: "test.js" }); + }, new Error(renderExpected), "renderChunk:" + (message || input)); + + QUnit.assert.throws(() => { + plugin.transform(input, "test.js"); + }, new Error(transformExpected || renderExpected.replace(/during renderChunk/g, "during transform")), "transform:" + (message || input)); + } + + public registerTests() { + this.testCase({ + name: "No matching values for es5Poly", + test: () => { + this.testPolyNoChange(null, "Nothing removed"); + this.testPolyNoChange(null, "ClassName.prototype.anotherMethod = function () {\n};\n"); + + this.testPolyNoChange(null, + "ClassName.prototype.methodName = function () {\n" + + " // This is a comment for a dynamic proto stub\n" + + "};\n"); + + this.testPolyNoChange(null, + "ClassName.prototype.methodName = function () {\n" + + " // This is a comment for a dynamic proto stub\n" + + "};\n"); + + this.testPolyNoChange(null, + "// @Stub -- Type 1 comment\n" + + "function methodName() {\n" + + " // This is a comment for a dynamic proto stub\n" + + "};\n"); + + this.testPolyNoChange(null, + "function methodName() {\n" + + " // @Stub -- Type 2 single line comment\n" + + "};\n"); + + this.testPolyNoChange(null, + "function methodName() {\n" + + " /* @Stub -- Type 2 multiline comment */\n" + + "};\n"); + + this.testPolyNoChange(null, + "function methodName() {\n" + + " /* @Stub -- Type 2 multiline comment\n" + + " * Continuation of a multi-line comment/\n" + + " */\n" + + "};\n"); + } + }); + + this.testCase({ + name: "No matching values for es5Check", + test: () => { + this.testCheckNoMatch(null, "Nothing removed"); + this.testCheckNoMatch(null, "ClassName.prototype.anotherMethod = function () {\n};\n"); + this.testCheckNoMatch(null, "telemertyItem.time = CoreUtils.toISOString(new Date());"); + this.testCheckNoMatch(null, "var responseHeaders = {};\nresponse.headers.forEach(function (value, name) {\n"); + } + }); + + this.testCase({ + name: "Test es5Polyfil implementations", + test: () => { + this.testPolyNoChange(null, + "Object[\"defineProperty\"](exports, '__esModule', { value: true });"); + + this.testPolyNoChange(null, + "Object.defineProperty(exports, '__esModule', { value: true });"); + + this.testPolyNoChange(null, + "return r && Object.defineProperty(exports, '__esModule', { value: true }), b;"); + + this.testPolyNoChange(null, + "d = Object.getOwnPropertyDescriptor(obj, 'foo'), a=b;"); + + this.testPolyNoChange(null, + "d = Object.getOwnPropertyDescriptor(obj, 'foo');"); + + this.testPolyNoChange(null, + "Rectangle.prototype = Object.create(Shape.prototype);"); + + this.testPolyNoChange(null, + "Rectangle.prototype = Object.create(Shape.prototype, propsObj);"); + + this.testPolyNoChange(null, + "a = Object.freeze(obj);"); + + this.testPolyNoChange(null, + "a = Object.seal(obj);"); + + this.testPolyNoChange(null, + "var dt = new Date();\n" + + "\n" + + "dt.toISOString ();\n" + + "Can.toISOString();\n"); + + } + }); + + this.testCase({ + name: "Test Errors es5Check", + test: () => { + + this.testError( + es5Check(), + null, + "var arr = Object.is(a);\n", + "Invalid IE/ES5 function [Object.is(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + + "[Object.is(] is not supported in an IE/ES5 environment, use a helper function or add explicit check for existence\n" + + "1 :var arr = Object.is(a);\n" + + " ^^^^^^^^^^\n" + + "\n" + + "--------------------=([Object.is(])=--------------------\n" + ); + + this.testError( + es5Check(), + null, + "var arr = Object.fromEntries(a);\n", + "Invalid IE/ES5 function [Object.fromEntries(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + + "[Object.fromEntries(] is not supported in an IE/ES5 environment, use a helper function or add explicit check for existence\n" + + "1 :var arr = Object.fromEntries(a);\n" + + " ^^^^^^^^^^^^^^^^^^^\n" + + "\n" + + "--------------------=([Object.fromEntries(])=--------------------\n" + ); + + this.testError( + es5Check(), + null, + "var arr = Object.entries(a);\n", + "Invalid IE/ES5 function [Object.entries(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + + "[Object.entries(] is not supported in an IE/ES5 environment, use a helper function or add explicit check for existence\n" + + "1 :var arr = Object.entries(a);\n" + + " ^^^^^^^^^^^^^^^\n" + + "\n" + + "--------------------=([Object.entries(])=--------------------\n" + ); + + this.testError( + es5Check(), + null, + "var arr = Object.assign(a);\n", + "Invalid IE/ES5 function [Object.assign(] found on line [1], column [11], position [10] during renderChunk - test.js\n" + + "[Object.assign(] is not supported in an IE/ES5 environment, use a helper function or add explicit check for existence\n" + + "1 :var arr = Object.assign(a);\n" + + " ^^^^^^^^^^^^^^\n" + + "\n" + + "--------------------=([Object.assign(])=--------------------\n" + ); + + this.testError( + es5Check(), + null, + "var x = Object.setPrototypeOf(a);\n", + "Invalid IE/ES5 function [Object.setPrototypeOf(] found on line [1], column [9], position [8] during renderChunk - test.js\n" + + "[Object.setPrototypeOf(] is not supported in an IE/ES5 environment, use a helper function or add explicit check for existence\n" + + "1 :var x = Object.setPrototypeOf(a);\n" + + " ^^^^^^^^^^^^^^^^^^^^^^\n" + + "\n" + + "--------------------=([Object.setPrototypeOf(])=--------------------\n" + ); + + this.testError( + es5Check(), + null, + "var x = Object.keys(a);\n", + "Invalid IE/ES5 function [Object.keys(] found on line [1], column [9], position [8] during renderChunk - test.js\n" + + "[Object.keys(] is not supported in an IE/ES5 environment, use a helper function or add explicit check for existence\n" + + "1 :var x = Object.keys(a);\n" + + " ^^^^^^^^^^^^\n" + + "\n" + + "--------------------=([Object.keys(])=--------------------\n" + ); + + } + }); + + this.testCase({ + name: "Test Import Check", + test: () => { + let plugin = importCheck({}); + + this.testImportCheck({}, ""); + this.testImportCheck({ exclude: ["index"]}, "import {\nSomeClass\n} from './MyCode'"); + this.testImportCheck({ exclude: ["index"]}, "import {\nSomeClass\n} from \"./MyCode\""); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import { A, B, C } from './Index';", + "Invalid Import detected [import { A, B, C } from './Index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from './Index']\n" + + "\n" + + "--------------------=([import { A, B, C } from './Index'])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import { A, B, C } from \"./Index\";", + "Invalid Import detected [import { A, B, C } from \"./Index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from \"./Index\"]\n" + + "\n" + + "--------------------=([import { A, B, C } from \"./Index\"])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import { A, B, C } from './Index'", + "Invalid Import detected [import { A, B, C } from './Index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from './Index']\n" + + "\n" + + "--------------------=([import { A, B, C } from './Index'])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import { A, B, C } from \"./Index\"", + "Invalid Import detected [import { A, B, C } from \"./Index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from \"./Index\"]\n" + + "\n" + + "--------------------=([import { A, B, C } from \"./Index\"])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import { A, B, C } from './index';", + "Invalid Import detected [import { A, B, C } from './index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from './index']\n" + + "\n" + + "--------------------=([import { A, B, C } from './index'])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import { A, B, C } from \"./index\";", + "Invalid Import detected [import { A, B, C } from \"./index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from \"./index\"]\n" + + "\n" + + "--------------------=([import { A, B, C } from \"./index\"])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import { A, B, C } from './index'", + "Invalid Import detected [import { A, B, C } from './index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from './index']\n" + + "\n" + + "--------------------=([import { A, B, C } from './index'])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import { A, B, C } from \"./index\"", + "Invalid Import detected [import { A, B, C } from \"./index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from \"./index\"]\n" + + "\n" + + "--------------------=([import { A, B, C } from \"./index\"])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import { A, B, C } from './folder/index';", + "Invalid Import detected [import { A, B, C } from './folder/index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from './folder/index']\n" + + "\n" + + "--------------------=([import { A, B, C } from './folder/index'])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import { A, B, C } from \"./folder/index\";", + "Invalid Import detected [import { A, B, C } from \"./folder/index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from \"./folder/index\"]\n" + + "\n" + + "--------------------=([import { A, B, C } from \"./folder/index\"])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import { A, B, C } from './folder/index'", + "Invalid Import detected [import { A, B, C } from './folder/index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from './folder/index']\n" + + "\n" + + "--------------------=([import { A, B, C } from './folder/index'])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import { A, B, C } from \"./folder/index\"", + "Invalid Import detected [import { A, B, C } from \"./folder/index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import { A, B, C } from \"./folder/index\"]\n" + + "\n" + + "--------------------=([import { A, B, C } from \"./folder/index\"])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import * from './Index';", + "Invalid Import detected [import * from './Index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import * from './Index']\n" + + "\n" + + "--------------------=([import * from './Index'])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import * from \"./Index\";", + "Invalid Import detected [import * from \"./Index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import * from \"./Index\"]\n" + + "\n" + + "--------------------=([import * from \"./Index\"])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import * from './Index'", + "Invalid Import detected [import * from './Index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import * from './Index']\n" + + "\n" + + "--------------------=([import * from './Index'])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import * from \"./Index\"", + "Invalid Import detected [import * from \"./Index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import * from \"./Index\"]\n" + + "\n" + + "--------------------=([import * from \"./Index\"])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import * from './folder/Index';", + "Invalid Import detected [import * from './folder/Index'] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import * from './folder/Index']\n" + + "\n" + + "--------------------=([import * from './folder/Index'])=--------------------\n"); + + this.testImportCheckFail( + { exclude: [ "index" ]}, + "import * from \"./folder/Index\";", + "Invalid Import detected [import * from \"./folder/Index\"] found on line [0], column [1], position [0] during renderChunk - test.js\n" + + "Importing from this module has been blocked, you should be importing directly from the source file and not the main module index definition - [import * from \"./folder/Index\"]\n" + + "\n" + + "--------------------=([import * from \"./folder/Index\"])=--------------------\n"); + + } + }); + } +} + diff --git a/tools/rollup-es5/Tests/Unit/src/Es5RollupTests.ts b/tools/rollup-es5/Tests/Unit/src/Es5RollupTests.ts new file mode 100644 index 00000000..8530df5c --- /dev/null +++ b/tools/rollup-es5/Tests/Unit/src/Es5RollupTests.ts @@ -0,0 +1,5 @@ +import { Es5RollupTests } from './Es5Rollup.Tests'; + +export function runTests() { + new Es5RollupTests().registerTests(); +} diff --git a/tools/rollup-es3/Tests/UnitTests.html b/tools/rollup-es5/Tests/UnitTests.html similarity index 90% rename from tools/rollup-es3/Tests/UnitTests.html rename to tools/rollup-es5/Tests/UnitTests.html index e5b80d51..71e136fe 100644 --- a/tools/rollup-es3/Tests/UnitTests.html +++ b/tools/rollup-es5/Tests/UnitTests.html @@ -4,7 +4,7 @@ - Tests for Es3 Rollup Plugin + Tests for Es5 Rollup Plugin @@ -27,7 +27,7 @@ // Load and define the app insights test framework module modules.add("@microsoft/ai-test-framework", "./node_modules/@microsoft/ai-test-framework/dist/ai-test-framework"); - var testModule = modules.add("Tests/Unit/src/Es3RollupTests", "./Unit/dist/es3rolluptests.js"); + var testModule = modules.add("Tests/Unit/src/Es5RollupTests", "./Unit/dist/es5rolluptests.js"); testModule.run = function (tests) { console && console.log("Starting tests"); QUnit.start(); diff --git a/tools/rollup-es3/Tests/tsconfig.json b/tools/rollup-es5/Tests/tsconfig.json similarity index 100% rename from tools/rollup-es3/Tests/tsconfig.json rename to tools/rollup-es5/Tests/tsconfig.json diff --git a/tools/rollup-es3/api-extractor.json b/tools/rollup-es5/api-extractor.json similarity index 99% rename from tools/rollup-es3/api-extractor.json rename to tools/rollup-es5/api-extractor.json index 844f060a..90a6ced4 100644 --- a/tools/rollup-es3/api-extractor.json +++ b/tools/rollup-es5/api-extractor.json @@ -45,7 +45,7 @@ * * SUPPORTED TOKENS: , , */ - "mainEntryPointFilePath": "/types/applicationinsights-rollup-es3.d.ts", + "mainEntryPointFilePath": "/types/applicationinsights-rollup-es5.d.ts", /** * A list of NPM package names whose exports should be treated as part of this package. diff --git a/tools/rollup-es3/package.json b/tools/rollup-es5/package.json similarity index 78% rename from tools/rollup-es3/package.json rename to tools/rollup-es5/package.json index 5ed85e6c..dd928786 100644 --- a/tools/rollup-es3/package.json +++ b/tools/rollup-es5/package.json @@ -1,9 +1,9 @@ { - "name": "@microsoft/applicationinsights-rollup-es3", + "name": "@microsoft/applicationinsights-rollup-es5", "author": "Microsoft Application Insights Team", - "version": "1.1.3", - "description": "Microsoft Application Insights JavaScript SDK - Rollup Plugin for ES3 support", - "homepage": "https://github.com/microsoft/ApplicationInsights-JS/tree/master/tools/rollup-es3", + "version": "1.0.0", + "description": "Microsoft Application Insights JavaScript SDK - Rollup Plugin for IE/ES5 support", + "homepage": "https://github.com/microsoft/ApplicationInsights-JS/tree/master/tools/rollup-es5", "keywords": [ "azure", "cloud", @@ -11,18 +11,18 @@ "application insights", "rollup", "rollup-plugin", - "es3" + "es5" ], - "main": "dist/node/applicationinsights-rollup-es3.min.js", - "module": "dist/esm/applicationinsights-rollup-es3.min.js", - "types": "types/applicationinsights-rollup-es3.d.ts", + "main": "dist/node/applicationinsights-rollup-es5.min.js", + "module": "dist/esm/applicationinsights-rollup-es5.min.js", + "types": "types/applicationinsights-rollup-es5.d.ts", "scripts": { "clean": "grunt clean", "build": "npm run build:esm && npm run build:bundle", - "build:esm": "grunt rollupes3", + "build:esm": "grunt rollupes5", "build:bundle": "rollup -c rollup.config.js", "rebuild": "npm run build", - "test": "grunt rollupes3test", + "test": "grunt rollupes5test", "lint": "tslint -p tsconfig.json" }, "repository": { diff --git a/tools/rollup-es3/rollup.config.js b/tools/rollup-es5/rollup.config.js similarity index 93% rename from tools/rollup-es3/rollup.config.js rename to tools/rollup-es5/rollup.config.js index da6ff335..52fe2ba1 100644 --- a/tools/rollup-es3/rollup.config.js +++ b/tools/rollup-es5/rollup.config.js @@ -5,8 +5,8 @@ import minify from 'rollup-plugin-minify-es'; const version = require("./package.json").version; const desc = require("./package.json").description; -const inputName = "./out/applicationinsights-rollup-es3"; -const outputName = "applicationinsights-rollup-es3"; +const inputName = "./out/applicationinsights-rollup-es5"; +const outputName = "applicationinsights-rollup-es5"; const distPath = "./dist/"; const banner = [ "/*!", @@ -22,7 +22,7 @@ const nodeUmdRollupConfigFactory = (isProduction) => { file: `${distPath}node/${outputName}.js`, banner: banner, format: "umd", - name: "Microsoft.ApplicationInsights-Rollup-ES3", + name: "Microsoft.ApplicationInsights-Rollup-ES5", extend: true, freeze: false, sourcemap: false @@ -70,7 +70,7 @@ const moduleRollupConfigFactory = (format, isProduction) => { file: `${distPath}${format}/${outputName}.js`, banner: banner, format: format, - name: "Microsoft.ApplicationInsights-Rollup-ES3", + name: "Microsoft.ApplicationInsights-Rollup-ES5", extend: true, freeze: false, sourcemap: false diff --git a/tools/rollup-es3/src/ImportCheck.ts b/tools/rollup-es5/src/ImportCheck.ts similarity index 89% rename from tools/rollup-es3/src/ImportCheck.ts rename to tools/rollup-es5/src/ImportCheck.ts index 1eb80462..30cc6fec 100644 --- a/tools/rollup-es3/src/ImportCheck.ts +++ b/tools/rollup-es5/src/ImportCheck.ts @@ -1,14 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -import { IImportCheckRollupOptions, IEs3CheckRollupOptions } from "./es3/Interfaces"; -import { es3Check } from "./es3/Es3Check"; +import { IImportCheckRollupOptions, IEs5CheckRollupOptions } from "./es5/Interfaces"; +import { es5Check } from "./es5/Es5Check"; function _escapeRegEx(str:string) { return str.replace(/([.*+?^=!:${}()|[\]/\\])/g, "\\$1"); } export function importCheck(options:IImportCheckRollupOptions = {}) { - let checkOptions:IEs3CheckRollupOptions = { + let checkOptions:IEs5CheckRollupOptions = { ignoreDefault: true, keywords: [] }; @@ -39,7 +39,7 @@ export function importCheck(options:IImportCheckRollupOptions = {}) { } } - let plugin = es3Check(checkOptions); + let plugin = es5Check(checkOptions); plugin.name = "ai-rollup-importcheck"; return plugin diff --git a/tools/rollup-es5/src/applicationinsights-rollup-es5.ts b/tools/rollup-es5/src/applicationinsights-rollup-es5.ts new file mode 100644 index 00000000..1f93bec5 --- /dev/null +++ b/tools/rollup-es5/src/applicationinsights-rollup-es5.ts @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +import { INamedGroups, IEs5CheckKeyword, IEs5Keyword, IEs5RollupOptions, IImportCheckRollupOptions } from "./es5/Interfaces"; +import { es5Poly } from "./es5/Es5Poly"; +import { es5Check } from "./es5/Es5Check"; +import { importCheck } from "./ImportCheck"; + +export { es5Poly, es5Check, importCheck, INamedGroups, IEs5CheckKeyword, IEs5Keyword, IEs5RollupOptions, IImportCheckRollupOptions }; diff --git a/tools/rollup-es3/src/es3/Es3Check.ts b/tools/rollup-es5/src/es5/Es5Check.ts similarity index 88% rename from tools/rollup-es3/src/es3/Es3Check.ts rename to tools/rollup-es5/src/es5/Es5Check.ts index ff0cdc04..e580975b 100644 --- a/tools/rollup-es3/src/es3/Es3Check.ts +++ b/tools/rollup-es5/src/es5/Es5Check.ts @@ -1,8 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import { isNullOrUndefined, isIgnoreFuncMatch, isIgnore } from "./Utils"; -import { IEs3CheckKeyword, IEs3CheckRollupOptions } from "./Interfaces"; -import { defaultEs3CheckTokens } from "./Es3Tokens"; +import { IEs5CheckKeyword, IEs5CheckRollupOptions } from "./Interfaces"; +import { defaultEs5CheckTokens } from "./Es5Tokens"; import { formatError } from "./FormatError"; function visibleNewlines(value:string) { @@ -13,12 +13,12 @@ function visibleNewlines(value:string) { return value; } -export function checkResult(tokens:IEs3CheckKeyword[], result:string, id:string, entry:string, isTransform:boolean) { +export function checkResult(tokens:IEs5CheckKeyword[], result:string, id:string, entry:string, isTransform:boolean) { if (result) { let errorMessage = ""; for (let idx in tokens) { - let keyword:IEs3CheckKeyword = tokens[idx]; + let keyword:IEs5CheckKeyword = tokens[idx]; if (!isIgnore(id, keyword, isTransform)) { for (let funcIdx in keyword.funcNames) { let funcRegEx = keyword.funcNames[funcIdx]; @@ -51,8 +51,8 @@ export function checkResult(tokens:IEs3CheckKeyword[], result:string, id:string, } } -export function es3Check(options:IEs3CheckRollupOptions = {}) { - let tokens:IEs3CheckKeyword[] = defaultEs3CheckTokens.slice(0); +export function es5Check(options:IEs5CheckRollupOptions = {}) { + let tokens:IEs5CheckKeyword[] = defaultEs5CheckTokens.slice(0); if (options) { if (!isNullOrUndefined(options.ignoreDefault) && options.ignoreDefault) { tokens = []; @@ -71,7 +71,7 @@ export function es3Check(options:IEs3CheckRollupOptions = {}) { } return { - name: "ai-rollup-es3check", + name: "ai-rollup-es5check", renderChunk(code:string, chunk:any) { return doCheck(code, chunk.filename || chunk.fileName || chunk.name, "renderChunk", false); }, diff --git a/tools/rollup-es3/src/es3/Es3Poly.ts b/tools/rollup-es5/src/es5/Es5Poly.ts similarity index 91% rename from tools/rollup-es3/src/es3/Es3Poly.ts rename to tools/rollup-es5/src/es5/Es5Poly.ts index f46af74f..c77bb3cf 100644 --- a/tools/rollup-es3/src/es3/Es3Poly.ts +++ b/tools/rollup-es5/src/es5/Es5Poly.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import { isNullOrUndefined, isNullOrWhitespace, isSourceMapEnabled, isIgnore } from "./Utils"; -import { defaultEs3Tokens } from "./Es3Tokens"; -import { INamedGroups, IEs3Keyword, IEs3RollupOptions } from "./Interfaces"; -import { checkResult } from "./Es3Check"; +import { defaultEs5Tokens } from "./Es5Tokens"; +import { INamedGroups, IEs5Keyword, IEs5RollupOptions } from "./Interfaces"; +import { checkResult } from "./Es5Check"; import MagicString from "magic-string"; // Start the temp name from the recent milliseconds -- this is to try and ensure that multiple runs which @@ -19,7 +19,7 @@ function _replaceAll(str:string, value:string, newValue: string) { return str.replace(new RegExp(_escapeRegEx(value), "g"), newValue); } -function _replaceToken(keyword:IEs3Keyword, code:string, theString:MagicString, _entry:string):boolean { +function _replaceToken(keyword:IEs5Keyword, code:string, theString:MagicString, _entry:string):boolean { let result = false; let extract:RegExp = keyword.extract; let replaceValue:string = keyword.replace || ""; @@ -60,7 +60,7 @@ function _replaceToken(keyword:IEs3Keyword, code:string, theString:MagicString, } if (!nameUsed) { - let tempName = "aies3_" + tempIndex; + let tempName = "aies5_" + tempIndex; tempIndex++; newValue = newValue.replace("%tempName%", tempName); } @@ -72,9 +72,9 @@ function _replaceToken(keyword:IEs3Keyword, code:string, theString:MagicString, return result; } -export function es3Poly(options:IEs3RollupOptions = {}) { +export function es5Poly(options:IEs5RollupOptions = {}) { let doReplace = true; - let tokens:IEs3Keyword[] = defaultEs3Tokens.slice(0); + let tokens:IEs5Keyword[] = defaultEs5Tokens.slice(0); if (options) { if (!isNullOrUndefined(options.ignoreDefault) && options.ignoreDefault) { tokens = []; @@ -94,7 +94,7 @@ export function es3Poly(options:IEs3RollupOptions = {}) { if (doReplace && code) { theString = new MagicString(code); for (let idx in tokens) { - let keyword:IEs3Keyword = tokens[idx]; + let keyword:IEs5Keyword = tokens[idx]; if (keyword && !isIgnore(id, keyword, isTransform)) { try { if (_replaceToken(keyword, code, theString, entry)) { @@ -145,7 +145,7 @@ export function es3Poly(options:IEs3RollupOptions = {}) { } return { - name: "ai-rollup-es3poly", + name: "ai-rollup-es5poly", renderChunk(code:string, chunk:any) { return doTransformAndCheck(code, chunk.filename, "renderChunk", false); }, diff --git a/tools/rollup-es5/src/es5/Es5Tokens.ts b/tools/rollup-es5/src/es5/Es5Tokens.ts new file mode 100644 index 00000000..5bce5496 --- /dev/null +++ b/tools/rollup-es5/src/es5/Es5Tokens.ts @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +import { IEs5CheckKeyword, IEs5Keyword } from "./Interfaces"; + +export const defaultEs5Tokens:IEs5Keyword[] = [ +]; + +export const defaultEs5CheckTokens:IEs5CheckKeyword[] = [ + { + funcNames: [ /Object\.(is|fromEntries|entries|setPrototypeOf)\(/g ], + errorMsg: "[%funcName%] is not supported in an IE/ES5 environment, use a helper function or add explicit check for existence" + }, + { + funcNames: [ /Object\.(assign)\(/g ], + errorMsg: "[%funcName%] is not supported in an IE/ES5 environment, use a helper function or add explicit check for existence", + ignoreIds: [ + "applicationinsights-react-js", // Don't break build if these exist in the final react extension + "object-assign\\index.js", // object-assign node module contains a pre existence check before usage + "object-assign/index.js" // object-assign node module contains a pre existence check before usage + ] + }, + { + funcNames: [ /Object\.(keys)\(/g ], + errorMsg: "[%funcName%] is not supported in an IE/ES5 environment, use a helper function or add explicit check for existence", + ignoreIds: [ + "react.production.min.js", // Don't break build if these exist in the react prod source code + "react.development.js", // Don't break build if these exist in the react dev source code + "applicationinsights-react-js", // Don't break build if these exist in the final react extension + "object-assign\\index.js", // object-assign node module contains a pre existence check before usage + "object-assign/index.js" // object-assign node module contains a pre existence check before usage + ] + }, + { + funcNames: [ /Object\.(getOwnPropertySymbols)\(/g ], + errorMsg: "[%funcName%] is not supported in an IE/ES5 environment, use a helper function or add explicit check for existence", + ignoreIds: [ + "tslib.es6", // tslib.es6 library has a pre existence check before usage + "object-assign\\index.js", // object-assign node module contains a pre existence check before usage + "object-assign/index.js" // object-assign node module contains a pre existence check before usage + ] + }, + { + funcNames: [ /([\w0-9]*)\.(trim)[\s]*\(/g ], + errorMsg: "[%funcName%] is not a supported string method in an IE/ES5 environment, use strTrim().", + ignoreFuncMatch: [ + "Util.trim", // Make sure this isn't a reference to Util.trim() + "DataSanitizer.trim" // Make sure this isn't a reference to Util.trim() + ] + }, + { + funcNames: [ /([\w0-9]*)\.(startsWith)[\s]*\(/g ], + errorMsg: "[%funcName%] is not a supported string method in an IE/ES5 environment, use strStartsWith().", + ignoreFuncMatch: [ + ] + }, + { + funcNames: [ /([\w0-9]*)\.(endsWith)[\s]*\(/g ], + errorMsg: "[%funcName%] is not a supported string method in an IE/ES5 environment, use strEndsWith().", + ignoreFuncMatch: [ + ] + } +]; + diff --git a/tools/rollup-es3/src/es3/FormatError.ts b/tools/rollup-es5/src/es5/FormatError.ts similarity index 81% rename from tools/rollup-es3/src/es3/FormatError.ts rename to tools/rollup-es5/src/es5/FormatError.ts index 80f76fe6..4992df51 100644 --- a/tools/rollup-es3/src/es3/FormatError.ts +++ b/tools/rollup-es5/src/es5/FormatError.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import { padEnd, isNullOrWhitespace } from "./Utils"; -import { IEs3CheckKeyword, IEs3Keyword } from "./Interfaces"; +import { IEs5CheckKeyword, IEs5Keyword } from "./Interfaces"; -export function formatError(keyword:IEs3CheckKeyword|IEs3Keyword, funcName:string, errorMsg:string, code:string, pos:number, id:string, entry:string) { +export function formatError(keyword:IEs5CheckKeyword|IEs5Keyword, funcName:string, errorMsg:string, code:string, pos:number, id:string, entry:string) { let lines = code.split(/(?:\r\n|\n\r|\r|\n)/); let lineNumber = 0; let count = pos; @@ -15,7 +15,7 @@ export function formatError(keyword:IEs3CheckKeyword|IEs3Keyword, funcName:strin let lineStart = code.lastIndexOf("\n", pos); let column = lineStart !== -1 ? (pos - lineStart) : pos + 1; - var message = (keyword.errorTitle || "Invalid ES3 function") + " [" + funcName + "] found on line [" + lineNumber + "], column [" + column + "], position [" + pos + "] during " + (entry||"") + " - " + (id||"") + "\n"; + var message = (keyword.errorTitle || "Invalid IE/ES5 function") + " [" + funcName + "] found on line [" + lineNumber + "], column [" + column + "], position [" + pos + "] during " + (entry||"") + " - " + (id||"") + "\n"; if (errorMsg) { message += errorMsg.replace("%funcName%", funcName) + "\n"; } @@ -44,12 +44,12 @@ export function formatError(keyword:IEs3CheckKeyword|IEs3Keyword, funcName:strin message += " ...\n"; } - if ((keyword as IEs3Keyword).extract && !isNullOrWhitespace(funcName)) { + if ((keyword as IEs5Keyword).extract && !isNullOrWhitespace(funcName)) { let match; let matchCount = 0; /* tslint:disable:no-conditional-assignment */ - while ((match = (keyword as IEs3Keyword).extract.exec(code))) { + while ((match = (keyword as IEs5Keyword).extract.exec(code))) { if (matchCount === 0) { message += "\nMatch checks\n"; } diff --git a/tools/rollup-es3/src/es3/Interfaces.ts b/tools/rollup-es5/src/es5/Interfaces.ts similarity index 84% rename from tools/rollup-es3/src/es3/Interfaces.ts rename to tools/rollup-es5/src/es5/Interfaces.ts index 79ec3a00..3a128150 100644 --- a/tools/rollup-es3/src/es3/Interfaces.ts +++ b/tools/rollup-es5/src/es5/Interfaces.ts @@ -10,12 +10,12 @@ export interface INamedGroups { } /** - * Identifies the checks to apply as part of the es3Check() rollup plugin + * Identifies the checks to apply as part of the es5Check() rollup plugin */ -export interface IEs3CheckKeyword { +export interface IEs5CheckKeyword { /** - * These RegEx's are used to identify the presence of keywords (code) that should not exist (for es3Check()) or - * should be attempted to be replaced (es3Poly()). + * These RegEx's are used to identify the presence of keywords (code) that should not exist (for es5Check()) or + * should be attempted to be replaced (es5Poly()). */ funcNames: RegExp[], @@ -38,15 +38,15 @@ export interface IEs3CheckKeyword { ignoreFuncMatch?:Array, /** - * The prefix added to any reported error, defaults to "Invalid ES3 function" + * The prefix added to any reported error, defaults to "Invalid IE/ES5 function" */ errorTitle?:string } /** - * Identifies the checks and replacement values to apply as part of the es3Poly() rollup plugin + * Identifies the checks and replacement values to apply as part of the es5Poly() rollup plugin */ -export interface IEs3Keyword extends IEs3CheckKeyword { +export interface IEs5Keyword extends IEs5CheckKeyword { /** * The RegEx used to match and extract the function details, don't use named groups (?<name>....); the "s" flag or * positive or negative lookbehind (?<=....); (? { values: replaceValues }), nodeResolve(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; @@ -84,8 +84,8 @@ const moduleRollupConfigFactory = (format, isProduction) => { values: replaceValues }), nodeResolve(), - es3Poly(), - es3Check() + es5Poly(), + es5Check() ] }; diff --git a/tools/shims/src/Helpers.ts b/tools/shims/src/Helpers.ts index 5fc7496f..3bd69cc1 100644 --- a/tools/shims/src/Helpers.ts +++ b/tools/shims/src/Helpers.ts @@ -49,7 +49,7 @@ export function throwTypeError(message: string): never { /** * Creates an object that has the specified prototype, and that optionally contains specified properties. This helper exists to avoid adding a polyfil - * for older browsers that do not define Object.create eg. ES3 only, IE8 just in case any page checks for presence/absence of the prototype implementation. + * for older browsers that do not define Object.create eg. ES5 only, IE8 just in case any page checks for presence/absence of the prototype implementation. * Note: For consistency this will not use the Object.create implementation if it exists as this would cause a testing requirement to test with and without the implementations * @param obj Object to use as a prototype. May be null */ diff --git a/tools/shims/src/TsLibShims.ts b/tools/shims/src/TsLibShims.ts index 48703d94..4674bf45 100644 --- a/tools/shims/src/TsLibShims.ts +++ b/tools/shims/src/TsLibShims.ts @@ -8,7 +8,7 @@ import { import { getGlobal, objCreateFn, throwTypeError } from "./Helpers"; // Most of these functions have been directly shamelessly "lifted" from the https://github.com/@microsoft/tslib and -// modified to be ES3 compatible and applying several minification and tree-shaking techniques so that Application Insights +// modified to be ES5 compatible and applying several minification and tree-shaking techniques so that Application Insights // can successfully use TypeScript "importHelpers" which imports tslib during compilation but it will use these at runtime // Which is also why all of the functions have not been included as Application Insights currently doesn't use or require // them. diff --git a/tools/shims/tsconfig.json b/tools/shims/tsconfig.json index dfd5d6f6..8121d1f6 100644 --- a/tools/shims/tsconfig.json +++ b/tools/shims/tsconfig.json @@ -5,7 +5,7 @@ "noImplicitAny": true, "module": "es6", "moduleResolution": "node", - "target": "es3", + "target": "es5", "forceConsistentCasingInFileNames": true, "importHelpers": false, "noEmitHelpers": true, diff --git a/tsconfig.json b/tsconfig.json index 0178c329..b9b4540e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,7 +4,7 @@ "inlineSources": true, "noImplicitAny": false, "module": "amd", - "target": "es3", + "target": "es5", "alwaysStrict": true, "declaration": true },