diff --git a/AISKU/Tests/TelemetryValidation/ExceptionValidator.ts b/AISKU/Tests/TelemetryValidation/ExceptionValidator.ts index 1b8d6d5d..bb11a558 100644 --- a/AISKU/Tests/TelemetryValidation/ExceptionValidator.ts +++ b/AISKU/Tests/TelemetryValidation/ExceptionValidator.ts @@ -9,9 +9,9 @@ export class ExceptionValidator implements ITypeValidator { // verify exceptions has typeName, message, hasFullStack, stack, parsedStack fields if (!exceptions[0].typeName || !exceptions[0].message || - !exceptions[0].hasFullStack || + !("hasFullStack" in exceptions[0]) || !exceptions[0].stack || - !exceptions[0].parsedStack) { + !("parsedStack" in exceptions[0])) { return false; } diff --git a/AISKU/Tests/TestFramework/PollingAssert.ts b/AISKU/Tests/TestFramework/PollingAssert.ts index 173a1363..d9767748 100644 --- a/AISKU/Tests/TestFramework/PollingAssert.ts +++ b/AISKU/Tests/TestFramework/PollingAssert.ts @@ -23,14 +23,14 @@ export class PollingAssert { Assert.ok(false, "assert didn't succeed for " + timeout + " seconds: " + assertDescription + "[" + (TestClass.currentTestInfo ? TestClass.currentTestInfo.name : "") + "]"); nextTestStep(); } else { - setTimeout(polling, pollIntervalMs); + TestClass.orgSetTimeout(polling, pollIntervalMs); } } catch (e) { Assert.ok(true, "Polling exception - " + e); - setTimeout(polling, pollIntervalMs); + TestClass.orgSetTimeout(polling, pollIntervalMs); } } - setTimeout(polling, pollIntervalMs); + TestClass.orgSetTimeout(polling, pollIntervalMs); } pollingAssert[TestClass.isPollingStepFlag] = true; diff --git a/AISKU/Tests/TestFramework/TestClass.ts b/AISKU/Tests/TestFramework/TestClass.ts index 55b4b387..af67ede9 100644 --- a/AISKU/Tests/TestFramework/TestClass.ts +++ b/AISKU/Tests/TestFramework/TestClass.ts @@ -21,12 +21,12 @@ export class TestClass { /** The instance of the currently running suite. */ public static currentTestClass: TestClass; public static currentTestInfo: TestCase|TestCaseAsync; + public static orgSetTimeout: (handler: Function, timeout?: number) => number; + public static orgClearTimeout: (handle?: number) => void; /** Turns on/off sinon's fake implementation of XMLHttpRequest. On by default. */ public sandboxConfig: any = {}; - public static orgSetTimeout: (handler: Function, timeout?: number) => number; - public static orgClearTimeout: (handle?: number) => void; public static orgObjectDefineProperty = Object.defineProperty; protected _xhrRequests: FakeXMLHttpRequest[] = []; @@ -96,6 +96,9 @@ export class TestClass { if (!testInfo.steps) { throw new Error("Must specify 'steps' to take asynchronously"); } + if (testInfo.autoComplete === undefined) { + testInfo.autoComplete = true; + } if (testInfo.autoComplete === undefined) { testInfo.autoComplete = true; @@ -219,9 +222,10 @@ export class TestClass { } catch (e) { console.error("Failed: Unexpected Exception: " + e); Assert.ok(false, e.toString()); - + this._testCompleted(true); // done is QUnit callback indicating the end of the test - testDone(); + done(); + return; } } else if (!testComplete) { @@ -267,7 +271,6 @@ export class TestClass { // Save off the instance of the currently running suite. TestClass.currentTestClass = this; TestClass.currentTestInfo = testInfo; - function _testFinished(failed?: boolean) { TestClass.currentTestClass._testCompleted(failed); done(); @@ -302,6 +305,16 @@ export class TestClass { this._emulateEs3(); } + let failed = false; + + TestClass.orgSetTimeout = (handler:Function, timeout?:number) => { + return orgSetTimeout(handler, timeout); + } + + TestClass.orgClearTimeout = (handler:number) => { + orgClearTimeout(handler); + } + // Run the test. try { this._testStarting(); @@ -320,8 +333,7 @@ export class TestClass { result.then(() => { promiseTimeout && clearTimeout(promiseTimeout); _testFinished(); - }, - (reason) => { + }).catch((reason) => { promiseTimeout && clearTimeout(promiseTimeout); QUnit.assert.ok(false, "Returned Promise rejected: " + reason); _testFinished(true); @@ -329,8 +341,7 @@ export class TestClass { } else { _testFinished(); } - } - catch (ex) { + } catch (ex) { console.error("Failed: Unexpected Exception: " + ex); Assert.ok(false, "Unexpected Exception: " + ex); _testFinished(true); @@ -375,6 +386,7 @@ export class TestClass { if (_self.isEmulatingEs3) { // As we removed Object.define we need to temporarily restore this for each sandbox call + // tslint:disable-next-line:forin for (var field in _self.sandbox) { var value = _self.sandbox[field]; if (CoreUtils.isFunction(value)) { @@ -397,7 +409,6 @@ export class TestClass { // Restore the Object properties/functions _self._restoreObject(saveObjectProps); - return result; } })(value); diff --git a/AISKU/Tests/applicationinsights.e2e.tests.ts b/AISKU/Tests/applicationinsights.e2e.tests.ts index 729a780a..dd2044d4 100644 --- a/AISKU/Tests/applicationinsights.e2e.tests.ts +++ b/AISKU/Tests/applicationinsights.e2e.tests.ts @@ -2,10 +2,9 @@ import { TestClass } from './TestFramework/TestClass'; 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 } from '@microsoft/applicationinsights-common'; +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 { TelemetryContext } from '@microsoft/applicationinsights-properties-js'; -import { AjaxPlugin } from '@microsoft/applicationinsights-dependencies-js'; import { EventValidator } from './TelemetryValidation/EventValidator'; import { TraceValidator } from './TelemetryValidation/TraceValidator'; import { ExceptionValidator } from './TelemetryValidation/ExceptionValidator'; @@ -180,22 +179,6 @@ export class ApplicationInsightsTests extends TestClass { }) }); - this.testCaseAsync({ - name: 'E2E.GenericTests: 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._ai.trackException({ exception }); - } - Assert.ok(exception); - }].concat(this.asserts(1)) - }); - this.testCaseAsync({ name: 'E2E.GenericTests: legacy trackException sends to backend', stepDelay: 1, @@ -212,6 +195,135 @@ export class ApplicationInsightsTests extends TestClass { }].concat(this.asserts(1)) }); + this.testCaseAsync({ + name: 'E2E.GenericTests: trackException with auto telemetry sends to backend', + stepDelay: 1, + steps: [() => { + let exception: Error = null; + try { + window['a']['b'](); + Assert.ok(false, 'trackException test not run'); + } catch (e) { + // Simulating window.onerror option + let autoTelemetry = { + message: e.message, + url: "https://dummy.auto.example.com", + lineNumber: 42, + columnNumber: 53, + error: e, + evt: null + } as IAutoExceptionTelemetry; + + exception = e; + this._ai.trackException({ exception: autoTelemetry }); + } + Assert.ok(exception); + }].concat(this.asserts(1)) + }); + + this.testCaseAsync({ + name: 'E2E.GenericTests: trackException with message only sends to backend', + stepDelay: 1, + steps: [() => { + let exception: Error = null; + try { + window['a']['b'](); + Assert.ok(false, 'trackException test not run'); + } catch (e) { + // Simulating window.onerror option + let autoTelemetry = { + message: e.toString(), + url: "https://dummy.message.example.com", + lineNumber: 42, + columnNumber: 53, + error: e.toString(), + evt: null + } as IAutoExceptionTelemetry; + + exception = e; + this._ai.trackException({ exception: autoTelemetry }); + } + Assert.ok(exception); + }].concat(this.asserts(1)) + }); + + this.testCaseAsync({ + name: 'E2E.GenericTests: trackException with message holding error sends to backend', + stepDelay: 1, + steps: [() => { + let exception: Error = null; + try { + window['a']['b'](); + Assert.ok(false, 'trackException test not run'); + } catch (e) { + // Simulating window.onerror option + let autoTelemetry = { + message: e, + url: "https://dummy.error.example.com", + lineNumber: 42, + columnNumber: 53, + error: undefined, + evt: null + } as IAutoExceptionTelemetry; + + try { + exception = e; + this._ai.trackException({ exception: autoTelemetry }); + } catch (e) { + console.log(e); + console.log(e.stack); + Assert.ok(false, e.stack); + } + } + Assert.ok(exception); + }].concat(this.asserts(1)) + }); + + this.testCaseAsync({ + name: 'E2E.GenericTests: trackException with no Error sends to backend', + stepDelay: 1, + steps: [() => { + let autoTelemetry = { + message: "Test Message", + url: "https://dummy.no.error.example.com", + lineNumber: 42, + columnNumber: 53, + error: this, + evt: null + } as IAutoExceptionTelemetry; + this._ai.trackException({ exception: autoTelemetry }); + Assert.ok(autoTelemetry); + }].concat(this.asserts(1)) + }); + + this.testCaseAsync({ + name: 'E2E.GenericTests: trackException with CustomError sends to backend', + stepDelay: 1, + steps: [() => { + this._ai.trackException({ exception: new CustomTestError("Test Custom Error!") }); + }].concat(this.asserts(1)).concat(() => { + const payloadStr: string[] = this.getPayloadMessages(this.successSpy); + if (payloadStr.length > 0) { + const payload = JSON.parse(payloadStr[0]); + const data = payload.data; + Assert.ok(data, "Has Data"); + if (data) { + Assert.ok(data.baseData, "Has BaseData"); + let baseData = data.baseData; + if (baseData) { + const ex = baseData.exceptions[0]; + Assert.ok(ex.message.indexOf("Test Custom Error!") !== -1, "Make sure the error message is present [" + ex.message + "]"); + Assert.ok(ex.message.indexOf("CustomTestError") !== -1, "Make sure the error type is present [" + ex.message + "]"); + Assert.equal("CustomTestError", ex.typeName, "Got the correct typename"); + Assert.ok(ex.stack.length > 0, "Has stack"); + Assert.ok(ex.parsedStack, "Stack was parsed"); + Assert.ok(ex.hasFullStack, "Stack has been decoded"); + } + } + } + }) + }); + this.testCaseAsync({ name: "TelemetryContext: track metric", stepDelay: 1, @@ -766,3 +878,11 @@ export class ApplicationInsightsTests extends TestClass { }, "sender succeeded", 60, 1000)) ]; } + +class CustomTestError extends Error { + constructor(message = "", ...args) { + super(message, ...args); + this.name = "CustomTestError"; + this.message = message + " -- test error."; + } +} \ No newline at end of file diff --git a/AISKU/snippet/snippet.js b/AISKU/snippet/snippet.js index 2c581bb3..be4cf8d4 100644 --- a/AISKU/snippet/snippet.js +++ b/AISKU/snippet/snippet.js @@ -285,7 +285,8 @@ url: url, lineNumber: lineNumber, columnNumber: columnNumber, - error: error + error: error, + evt: win.event }); } diff --git a/AISKU/src/Initialization.ts b/AISKU/src/Initialization.ts index 3b625504..23d37c59 100644 --- a/AISKU/src/Initialization.ts +++ b/AISKU/src/Initialization.ts @@ -16,7 +16,7 @@ import { Envelope, Event, Exception, Metric, PageView, PageViewData, RemoteDependencyData, IEventTelemetry, ITraceTelemetry, IMetricTelemetry, IDependencyTelemetry, IExceptionTelemetry, IAutoExceptionTelemetry, IPageViewTelemetry, IPageViewPerformanceTelemetry, Trace, PageViewPerformance, Data, SeverityLevel, - IConfig, ConfigurationManager, ContextTagKeys, DataSanitizer, TelemetryItemCreator, IAppInsights, CtxTagKeys, Extensions, + IConfig, ConfigurationManager, ContextTagKeys, IDataSanitizer, DataSanitizer, TelemetryItemCreator, IAppInsights, CtxTagKeys, Extensions, IPropertiesPlugin, DistributedTracingModes, PropertiesPluginIdentifier, BreezeChannelIdentifier, AnalyticsPluginIdentifier, ITelemetryContext as Common_ITelemetryContext, parseConnectionString } from "@microsoft/applicationinsights-common" @@ -57,6 +57,13 @@ export interface IApplicationInsights extends IAppInsights, IDependenciesPlugin, // 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 */ @@ -70,7 +77,7 @@ export const Telemetry = { UrlHelper, DateTimeUtils, ConnectionStringParser, - FieldType, + FieldType : fieldType, RequestHeaders, DisabledPropertyName, ProcessLegacy, @@ -92,7 +99,7 @@ export const Telemetry = { SeverityLevel, ConfigurationManager, ContextTagKeys, - DataSanitizer, + DataSanitizer: DataSanitizer as IDataSanitizer, TelemetryItemCreator, CtxTagKeys, Extensions, diff --git a/common/Tests/External/qunit-1.23.1.css b/common/Tests/External/qunit-1.23.1.css new file mode 100644 index 00000000..ae68fc41 --- /dev/null +++ b/common/Tests/External/qunit-1.23.1.css @@ -0,0 +1,305 @@ +/*! + * QUnit 1.23.1 + * https://qunitjs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * https://jquery.org/license + * + * Date: 2016-04-12T17:29Z + */ + +/** Font Family and Sizes */ + +#qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-filteredTest, #qunit-userAgent, #qunit-testresult { + font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif; +} + +#qunit-testrunner-toolbar, #qunit-filteredTest, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; } +#qunit-tests { font-size: smaller; } + + +/** Resets */ + +#qunit-tests, #qunit-header, #qunit-banner, #qunit-filteredTest, #qunit-userAgent, #qunit-testresult, #qunit-modulefilter { + margin: 0; + padding: 0; +} + + +/** Header */ + +#qunit-header { + padding: 0.5em 0 0.5em 1em; + + color: #8699A4; + background-color: #0D3349; + + font-size: 1.5em; + line-height: 1em; + font-weight: 400; + + border-radius: 5px 5px 0 0; +} + +#qunit-header a { + text-decoration: none; + color: #C2CCD1; +} + +#qunit-header a:hover, +#qunit-header a:focus { + color: #FFF; +} + +#qunit-testrunner-toolbar label { + display: inline-block; + padding: 0 0.5em 0 0.1em; +} + +#qunit-banner { + height: 5px; +} + +#qunit-testrunner-toolbar { + padding: 0.5em 1em 0.5em 1em; + color: #5E740B; + background-color: #EEE; + overflow: hidden; +} + +#qunit-filteredTest { + padding: 0.5em 1em 0.5em 1em; + background-color: #F4FF77; + color: #366097; +} + +#qunit-userAgent { + padding: 0.5em 1em 0.5em 1em; + background-color: #2B81AF; + color: #FFF; + text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px; +} + +#qunit-modulefilter-container { + float: right; + padding: 0.2em; +} + +.qunit-url-config { + display: inline-block; + padding: 0.1em; +} + +.qunit-filter { + display: block; + float: right; + margin-left: 1em; +} + +/** Tests: Pass/Fail */ + +#qunit-tests { + list-style-position: inside; +} + +#qunit-tests li { + padding: 0.4em 1em 0.4em 1em; + border-bottom: 1px solid #FFF; + list-style-position: inside; +} + +#qunit-tests > li { + display: none; +} + +#qunit-tests li.running, +#qunit-tests li.pass, +#qunit-tests li.fail, +#qunit-tests li.skipped { + display: list-item; +} + +#qunit-tests.hidepass { + position: relative; +} + +#qunit-tests.hidepass li.running, +#qunit-tests.hidepass li.pass { + visibility: hidden; + position: absolute; + width: 0; + height: 0; + padding: 0; + border: 0; + margin: 0; +} + +#qunit-tests li strong { + cursor: pointer; +} + +#qunit-tests li.skipped strong { + cursor: default; +} + +#qunit-tests li a { + padding: 0.5em; + color: #C2CCD1; + text-decoration: none; +} + +#qunit-tests li p a { + padding: 0.25em; + color: #6B6464; +} +#qunit-tests li a:hover, +#qunit-tests li a:focus { + color: #000; +} + +#qunit-tests li .runtime { + float: right; + font-size: smaller; +} + +.qunit-assert-list { + margin-top: 0.5em; + padding: 0.5em; + + background-color: #FFF; + + border-radius: 5px; +} + +.qunit-source { + margin: 0.6em 0 0.3em; +} + +.qunit-collapsed { + display: none; +} + +#qunit-tests table { + border-collapse: collapse; + margin-top: 0.2em; +} + +#qunit-tests th { + text-align: right; + vertical-align: top; + padding: 0 0.5em 0 0; +} + +#qunit-tests td { + vertical-align: top; +} + +#qunit-tests pre { + margin: 0; + white-space: pre-wrap; + word-wrap: break-word; +} + +#qunit-tests del { + background-color: #E0F2BE; + color: #374E0C; + text-decoration: none; +} + +#qunit-tests ins { + background-color: #FFCACA; + color: #500; + text-decoration: none; +} + +/*** Test Counts */ + +#qunit-tests b.counts { color: #000; } +#qunit-tests b.passed { color: #5E740B; } +#qunit-tests b.failed { color: #710909; } + +#qunit-tests li li { + padding: 5px; + background-color: #FFF; + border-bottom: none; + list-style-position: inside; +} + +/*** Passing Styles */ + +#qunit-tests li li.pass { + color: #3C510C; + background-color: #FFF; + border-left: 10px solid #C6E746; +} + +#qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; } +#qunit-tests .pass .test-name { color: #366097; } + +#qunit-tests .pass .test-actual, +#qunit-tests .pass .test-expected { color: #999; } + +#qunit-banner.qunit-pass { background-color: #C6E746; } + +/*** Failing Styles */ + +#qunit-tests li li.fail { + color: #710909; + background-color: #FFF; + border-left: 10px solid #EE5757; + white-space: pre; +} + +#qunit-tests > li:last-child { + border-radius: 0 0 5px 5px; +} + +#qunit-tests .fail { color: #000; background-color: #EE5757; } +#qunit-tests .fail .test-name, +#qunit-tests .fail .module-name { color: #000; } + +#qunit-tests .fail .test-actual { color: #EE5757; } +#qunit-tests .fail .test-expected { color: #008000; } + +#qunit-banner.qunit-fail { background-color: #EE5757; } + +/*** Skipped tests */ + +#qunit-tests .skipped { + background-color: #EBECE9; +} + +#qunit-tests .qunit-skipped-label { + background-color: #F4FF77; + display: inline-block; + font-style: normal; + color: #366097; + line-height: 1.8em; + padding: 0 0.5em; + margin: -0.4em 0.4em -0.4em 0; +} + +/** Result */ + +#qunit-testresult { + padding: 0.5em 1em 0.5em 1em; + + color: #2B81AF; + background-color: #D2E0E6; + + border-bottom: 1px solid #FFF; +} +#qunit-testresult .module-name { + font-weight: 700; +} + +/** Fixture */ + +#qunit-fixture { + position: absolute; + top: -10000px; + left: -10000px; + width: 1000px; + height: 1000px; +} diff --git a/common/Tests/External/require-2.2.0.js b/common/Tests/External/require-2.2.0.js new file mode 100644 index 00000000..23ddb4ee --- /dev/null +++ b/common/Tests/External/require-2.2.0.js @@ -0,0 +1,2142 @@ +/** vim: et:ts=4:sw=4:sts=4 + * @license RequireJS 2.2.0 Copyright jQuery Foundation and other contributors. + * Released under MIT license, http://github.com/requirejs/requirejs/LICENSE + */ +//Not using strict: uneven strict support in browsers, #392, and causes +//problems with requirejs.exec()/transpiler plugins that may not be strict. +/*jslint regexp: true, nomen: true, sloppy: true */ +/*global window, navigator, document, importScripts, setTimeout, opera */ + +var requirejs, require, define; +(function (global) { + var req, s, head, baseElement, dataMain, src, + interactiveScript, currentlyAddingScript, mainScript, subPath, + version = '2.2.0', + commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, + cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, + jsSuffixRegExp = /\.js$/, + currDirRegExp = /^\.\//, + op = Object.prototype, + ostring = op.toString, + hasOwn = op.hasOwnProperty, + isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document), + isWebWorker = !isBrowser && typeof importScripts !== 'undefined', + //PS3 indicates loaded and complete, but need to wait for complete + //specifically. Sequence is 'loading', 'loaded', execution, + // then 'complete'. The UA check is unfortunate, but not sure how + //to feature test w/o causing perf issues. + readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? + /^complete$/ : /^(complete|loaded)$/, + defContextName = '_', + //Oh the tragedy, detecting opera. See the usage of isOpera for reason. + isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', + contexts = {}, + cfg = {}, + globalDefQueue = [], + useInteractive = false; + + //Could match something like ')//comment', do not lose the prefix to comment. + function commentReplace(match, multi, multiText, singlePrefix) { + return singlePrefix || ''; + } + + function isFunction(it) { + return ostring.call(it) === '[object Function]'; + } + + function isArray(it) { + return ostring.call(it) === '[object Array]'; + } + + /** + * Helper function for iterating over an array. If the func returns + * a true value, it will break out of the loop. + */ + function each(ary, func) { + if (ary) { + var i; + for (i = 0; i < ary.length; i += 1) { + if (ary[i] && func(ary[i], i, ary)) { + break; + } + } + } + } + + /** + * Helper function for iterating over an array backwards. If the func + * returns a true value, it will break out of the loop. + */ + function eachReverse(ary, func) { + if (ary) { + var i; + for (i = ary.length - 1; i > -1; i -= 1) { + if (ary[i] && func(ary[i], i, ary)) { + break; + } + } + } + } + + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } + + function getOwn(obj, prop) { + return hasProp(obj, prop) && obj[prop]; + } + + /** + * Cycles over properties in an object and calls a function for each + * property value. If the function returns a truthy value, then the + * iteration is stopped. + */ + function eachProp(obj, func) { + var prop; + for (prop in obj) { + if (hasProp(obj, prop)) { + if (func(obj[prop], prop)) { + break; + } + } + } + } + + /** + * Simple function to mix in properties from source into target, + * but only if target does not already have a property of the same name. + */ + function mixin(target, source, force, deepStringMixin) { + if (source) { + eachProp(source, function (value, prop) { + if (force || !hasProp(target, prop)) { + if (deepStringMixin && typeof value === 'object' && value && + !isArray(value) && !isFunction(value) && + !(value instanceof RegExp)) { + + if (!target[prop]) { + target[prop] = {}; + } + mixin(target[prop], value, force, deepStringMixin); + } else { + target[prop] = value; + } + } + }); + } + return target; + } + + //Similar to Function.prototype.bind, but the 'this' object is specified + //first, since it is easier to read/figure out what 'this' will be. + function bind(obj, fn) { + return function () { + return fn.apply(obj, arguments); + }; + } + + function scripts() { + return document.getElementsByTagName('script'); + } + + function defaultOnError(err) { + throw err; + } + + //Allow getting a global that is expressed in + //dot notation, like 'a.b.c'. + function getGlobal(value) { + if (!value) { + return value; + } + var g = global; + each(value.split('.'), function (part) { + g = g[part]; + }); + return g; + } + + /** + * Constructs an error with a pointer to an URL with more information. + * @param {String} id the error ID that maps to an ID on a web page. + * @param {String} message human readable error. + * @param {Error} [err] the original error, if there is one. + * + * @returns {Error} + */ + function makeError(id, msg, err, requireModules) { + var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); + e.requireType = id; + e.requireModules = requireModules; + if (err) { + e.originalError = err; + } + return e; + } + + if (typeof define !== 'undefined') { + //If a define is already in play via another AMD loader, + //do not overwrite. + return; + } + + if (typeof requirejs !== 'undefined') { + if (isFunction(requirejs)) { + //Do not overwrite an existing requirejs instance. + return; + } + cfg = requirejs; + requirejs = undefined; + } + + //Allow for a require config object + if (typeof require !== 'undefined' && !isFunction(require)) { + //assume it is a config object. + cfg = require; + require = undefined; + } + + function newContext(contextName) { + var inCheckLoaded, Module, context, handlers, + checkLoadedTimeoutId, + config = { + //Defaults. Do not set a default for map + //config to speed up normalize(), which + //will run faster if there is no default. + waitSeconds: 7, + baseUrl: './', + paths: {}, + bundles: {}, + pkgs: {}, + shim: {}, + config: {} + }, + registry = {}, + //registry of just enabled modules, to speed + //cycle breaking code when lots of modules + //are registered, but not activated. + enabledRegistry = {}, + undefEvents = {}, + defQueue = [], + defined = {}, + urlFetched = {}, + bundlesMap = {}, + requireCounter = 1, + unnormalizedCounter = 1; + + /** + * Trims the . and .. from an array of path segments. + * It will keep a leading path segment if a .. will become + * the first path segment, to help with module name lookups, + * which act like paths, but can be remapped. But the end result, + * all paths that use this function should look normalized. + * NOTE: this method MODIFIES the input array. + * @param {Array} ary the array of path segments. + */ + function trimDots(ary) { + var i, part; + for (i = 0; i < ary.length; i++) { + part = ary[i]; + if (part === '.') { + ary.splice(i, 1); + i -= 1; + } else if (part === '..') { + // If at the start, or previous value is still .., + // keep them so that when converted to a path it may + // still work when converted to a path, even though + // as an ID it is less than ideal. In larger point + // releases, may be better to just kick out an error. + if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') { + continue; + } else if (i > 0) { + ary.splice(i - 1, 2); + i -= 2; + } + } + } + } + + /** + * Given a relative module name, like ./something, normalize it to + * a real name that can be mapped to a path. + * @param {String} name the relative name + * @param {String} baseName a real name that the name arg is relative + * to. + * @param {Boolean} applyMap apply the map config to the value. Should + * only be done if this normalization is for a dependency ID. + * @returns {String} normalized name + */ + function normalize(name, baseName, applyMap) { + var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex, + foundMap, foundI, foundStarMap, starI, normalizedBaseParts, + baseParts = (baseName && baseName.split('/')), + map = config.map, + starMap = map && map['*']; + + //Adjust any relative paths. + if (name) { + name = name.split('/'); + lastIndex = name.length - 1; + + // If wanting node ID compatibility, strip .js from end + // of IDs. Have to do this here, and not in nameToUrl + // because node allows either .js or non .js to map + // to same file. + if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { + name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); + } + + // Starts with a '.' so need the baseName + if (name[0].charAt(0) === '.' && baseParts) { + //Convert baseName to array, and lop off the last part, + //so that . matches that 'directory' and not name of the baseName's + //module. For instance, baseName of 'one/two/three', maps to + //'one/two/three.js', but we want the directory, 'one/two' for + //this normalization. + normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); + name = normalizedBaseParts.concat(name); + } + + trimDots(name); + name = name.join('/'); + } + + //Apply map config if available. + if (applyMap && map && (baseParts || starMap)) { + nameParts = name.split('/'); + + outerLoop: for (i = nameParts.length; i > 0; i -= 1) { + nameSegment = nameParts.slice(0, i).join('/'); + + if (baseParts) { + //Find the longest baseName segment match in the config. + //So, do joins on the biggest to smallest lengths of baseParts. + for (j = baseParts.length; j > 0; j -= 1) { + mapValue = getOwn(map, baseParts.slice(0, j).join('/')); + + //baseName segment has config, find if it has one for + //this name. + if (mapValue) { + mapValue = getOwn(mapValue, nameSegment); + if (mapValue) { + //Match, update name to the new value. + foundMap = mapValue; + foundI = i; + break outerLoop; + } + } + } + } + + //Check for a star map match, but just hold on to it, + //if there is a shorter segment match later in a matching + //config, then favor over this star map. + if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { + foundStarMap = getOwn(starMap, nameSegment); + starI = i; + } + } + + if (!foundMap && foundStarMap) { + foundMap = foundStarMap; + foundI = starI; + } + + if (foundMap) { + nameParts.splice(0, foundI, foundMap); + name = nameParts.join('/'); + } + } + + // If the name points to a package's name, use + // the package main instead. + pkgMain = getOwn(config.pkgs, name); + + return pkgMain ? pkgMain : name; + } + + function removeScript(name) { + if (isBrowser) { + each(scripts(), function (scriptNode) { + if (scriptNode.getAttribute('data-requiremodule') === name && + scriptNode.getAttribute('data-requirecontext') === context.contextName) { + scriptNode.parentNode.removeChild(scriptNode); + return true; + } + }); + } + } + + function hasPathFallback(id) { + var pathConfig = getOwn(config.paths, id); + if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { + //Pop off the first array value, since it failed, and + //retry + pathConfig.shift(); + context.require.undef(id); + + //Custom require that does not do map translation, since + //ID is "absolute", already mapped/resolved. + context.makeRequire(null, { + skipMap: true + })([id]); + + return true; + } + } + + //Turns a plugin!resource to [plugin, resource] + //with the plugin being undefined if the name + //did not have a plugin prefix. + function splitPrefix(name) { + var prefix, + index = name ? name.indexOf('!') : -1; + if (index > -1) { + prefix = name.substring(0, index); + name = name.substring(index + 1, name.length); + } + return [prefix, name]; + } + + /** + * Creates a module mapping that includes plugin prefix, module + * name, and path. If parentModuleMap is provided it will + * also normalize the name via require.normalize() + * + * @param {String} name the module name + * @param {String} [parentModuleMap] parent module map + * for the module name, used to resolve relative names. + * @param {Boolean} isNormalized: is the ID already normalized. + * This is true if this call is done for a define() module ID. + * @param {Boolean} applyMap: apply the map config to the ID. + * Should only be true if this map is for a dependency. + * + * @returns {Object} + */ + function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { + var url, pluginModule, suffix, nameParts, + prefix = null, + parentName = parentModuleMap ? parentModuleMap.name : null, + originalName = name, + isDefine = true, + normalizedName = ''; + + //If no name, then it means it is a require call, generate an + //internal name. + if (!name) { + isDefine = false; + name = '_@r' + (requireCounter += 1); + } + + nameParts = splitPrefix(name); + prefix = nameParts[0]; + name = nameParts[1]; + + if (prefix) { + prefix = normalize(prefix, parentName, applyMap); + pluginModule = getOwn(defined, prefix); + } + + //Account for relative paths if there is a base name. + if (name) { + if (prefix) { + if (pluginModule && pluginModule.normalize) { + //Plugin is loaded, use its normalize method. + normalizedName = pluginModule.normalize(name, function (name) { + return normalize(name, parentName, applyMap); + }); + } else { + // If nested plugin references, then do not try to + // normalize, as it will not normalize correctly. This + // places a restriction on resourceIds, and the longer + // term solution is not to normalize until plugins are + // loaded and all normalizations to allow for async + // loading of a loader plugin. But for now, fixes the + // common uses. Details in #1131 + normalizedName = name.indexOf('!') === -1 ? + normalize(name, parentName, applyMap) : + name; + } + } else { + //A regular module. + normalizedName = normalize(name, parentName, applyMap); + + //Normalized name may be a plugin ID due to map config + //application in normalize. The map config values must + //already be normalized, so do not need to redo that part. + nameParts = splitPrefix(normalizedName); + prefix = nameParts[0]; + normalizedName = nameParts[1]; + isNormalized = true; + + url = context.nameToUrl(normalizedName); + } + } + + //If the id is a plugin id that cannot be determined if it needs + //normalization, stamp it with a unique ID so two matching relative + //ids that may conflict can be separate. + suffix = prefix && !pluginModule && !isNormalized ? + '_unnormalized' + (unnormalizedCounter += 1) : + ''; + + return { + prefix: prefix, + name: normalizedName, + parentMap: parentModuleMap, + unnormalized: !!suffix, + url: url, + originalName: originalName, + isDefine: isDefine, + id: (prefix ? + prefix + '!' + normalizedName : + normalizedName) + suffix + }; + } + + function getModule(depMap) { + var id = depMap.id, + mod = getOwn(registry, id); + + if (!mod) { + mod = registry[id] = new context.Module(depMap); + } + + return mod; + } + + function on(depMap, name, fn) { + var id = depMap.id, + mod = getOwn(registry, id); + + if (hasProp(defined, id) && + (!mod || mod.defineEmitComplete)) { + if (name === 'defined') { + fn(defined[id]); + } + } else { + mod = getModule(depMap); + if (mod.error && name === 'error') { + fn(mod.error); + } else { + mod.on(name, fn); + } + } + } + + function onError(err, errback) { + var ids = err.requireModules, + notified = false; + + if (errback) { + errback(err); + } else { + each(ids, function (id) { + var mod = getOwn(registry, id); + if (mod) { + //Set error on module, so it skips timeout checks. + mod.error = err; + if (mod.events.error) { + notified = true; + mod.emit('error', err); + } + } + }); + + if (!notified) { + req.onError(err); + } + } + } + + /** + * Internal method to transfer globalQueue items to this context's + * defQueue. + */ + function takeGlobalQueue() { + //Push all the globalDefQueue items into the context's defQueue + if (globalDefQueue.length) { + each(globalDefQueue, function(queueItem) { + var id = queueItem[0]; + if (typeof id === 'string') { + context.defQueueMap[id] = true; + } + defQueue.push(queueItem); + }); + globalDefQueue = []; + } + } + + handlers = { + 'require': function (mod) { + if (mod.require) { + return mod.require; + } else { + return (mod.require = context.makeRequire(mod.map)); + } + }, + 'exports': function (mod) { + mod.usingExports = true; + if (mod.map.isDefine) { + if (mod.exports) { + return (defined[mod.map.id] = mod.exports); + } else { + return (mod.exports = defined[mod.map.id] = {}); + } + } + }, + 'module': function (mod) { + if (mod.module) { + return mod.module; + } else { + return (mod.module = { + id: mod.map.id, + uri: mod.map.url, + config: function () { + return getOwn(config.config, mod.map.id) || {}; + }, + exports: mod.exports || (mod.exports = {}) + }); + } + } + }; + + function cleanRegistry(id) { + //Clean up machinery used for waiting modules. + delete registry[id]; + delete enabledRegistry[id]; + } + + function breakCycle(mod, traced, processed) { + var id = mod.map.id; + + if (mod.error) { + mod.emit('error', mod.error); + } else { + traced[id] = true; + each(mod.depMaps, function (depMap, i) { + var depId = depMap.id, + dep = getOwn(registry, depId); + + //Only force things that have not completed + //being defined, so still in the registry, + //and only if it has not been matched up + //in the module already. + if (dep && !mod.depMatched[i] && !processed[depId]) { + if (getOwn(traced, depId)) { + mod.defineDep(i, defined[depId]); + mod.check(); //pass false? + } else { + breakCycle(dep, traced, processed); + } + } + }); + processed[id] = true; + } + } + + function checkLoaded() { + var err, usingPathFallback, + waitInterval = config.waitSeconds * 1000, + //It is possible to disable the wait interval by using waitSeconds of 0. + expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), + noLoads = [], + reqCalls = [], + stillLoading = false, + needCycleCheck = true; + + //Do not bother if this call was a result of a cycle break. + if (inCheckLoaded) { + return; + } + + inCheckLoaded = true; + + //Figure out the state of all the modules. + eachProp(enabledRegistry, function (mod) { + var map = mod.map, + modId = map.id; + + //Skip things that are not enabled or in error state. + if (!mod.enabled) { + return; + } + + if (!map.isDefine) { + reqCalls.push(mod); + } + + if (!mod.error) { + //If the module should be executed, and it has not + //been inited and time is up, remember it. + if (!mod.inited && expired) { + if (hasPathFallback(modId)) { + usingPathFallback = true; + stillLoading = true; + } else { + noLoads.push(modId); + removeScript(modId); + } + } else if (!mod.inited && mod.fetched && map.isDefine) { + stillLoading = true; + if (!map.prefix) { + //No reason to keep looking for unfinished + //loading. If the only stillLoading is a + //plugin resource though, keep going, + //because it may be that a plugin resource + //is waiting on a non-plugin cycle. + return (needCycleCheck = false); + } + } + } + }); + + if (expired && noLoads.length) { + //If wait time expired, throw error of unloaded modules. + err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); + err.contextName = context.contextName; + return onError(err); + } + + //Not expired, check for a cycle. + if (needCycleCheck) { + each(reqCalls, function (mod) { + breakCycle(mod, {}, {}); + }); + } + + //If still waiting on loads, and the waiting load is something + //other than a plugin resource, or there are still outstanding + //scripts, then just try back later. + if ((!expired || usingPathFallback) && stillLoading) { + //Something is still waiting to load. Wait for it, but only + //if a timeout is not already in effect. + if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { + checkLoadedTimeoutId = setTimeout(function () { + checkLoadedTimeoutId = 0; + checkLoaded(); + }, 50); + } + } + + inCheckLoaded = false; + } + + Module = function (map) { + this.events = getOwn(undefEvents, map.id) || {}; + this.map = map; + this.shim = getOwn(config.shim, map.id); + this.depExports = []; + this.depMaps = []; + this.depMatched = []; + this.pluginMaps = {}; + this.depCount = 0; + + /* this.exports this.factory + this.depMaps = [], + this.enabled, this.fetched + */ + }; + + Module.prototype = { + init: function (depMaps, factory, errback, options) { + options = options || {}; + + //Do not do more inits if already done. Can happen if there + //are multiple define calls for the same module. That is not + //a normal, common case, but it is also not unexpected. + if (this.inited) { + return; + } + + this.factory = factory; + + if (errback) { + //Register for errors on this module. + this.on('error', errback); + } else if (this.events.error) { + //If no errback already, but there are error listeners + //on this module, set up an errback to pass to the deps. + errback = bind(this, function (err) { + this.emit('error', err); + }); + } + + //Do a copy of the dependency array, so that + //source inputs are not modified. For example + //"shim" deps are passed in here directly, and + //doing a direct modification of the depMaps array + //would affect that config. + this.depMaps = depMaps && depMaps.slice(0); + + this.errback = errback; + + //Indicate this module has be initialized + this.inited = true; + + this.ignore = options.ignore; + + //Could have option to init this module in enabled mode, + //or could have been previously marked as enabled. However, + //the dependencies are not known until init is called. So + //if enabled previously, now trigger dependencies as enabled. + if (options.enabled || this.enabled) { + //Enable this module and dependencies. + //Will call this.check() + this.enable(); + } else { + this.check(); + } + }, + + defineDep: function (i, depExports) { + //Because of cycles, defined callback for a given + //export can be called more than once. + if (!this.depMatched[i]) { + this.depMatched[i] = true; + this.depCount -= 1; + this.depExports[i] = depExports; + } + }, + + fetch: function () { + if (this.fetched) { + return; + } + this.fetched = true; + + context.startTime = (new Date()).getTime(); + + var map = this.map; + + //If the manager is for a plugin managed resource, + //ask the plugin to load it now. + if (this.shim) { + context.makeRequire(this.map, { + enableBuildCallback: true + })(this.shim.deps || [], bind(this, function () { + return map.prefix ? this.callPlugin() : this.load(); + })); + } else { + //Regular dependency. + return map.prefix ? this.callPlugin() : this.load(); + } + }, + + load: function () { + var url = this.map.url; + + //Regular dependency. + if (!urlFetched[url]) { + urlFetched[url] = true; + context.load(this.map.id, url); + } + }, + + /** + * Checks if the module is ready to define itself, and if so, + * define it. + */ + check: function () { + if (!this.enabled || this.enabling) { + return; + } + + var err, cjsModule, + id = this.map.id, + depExports = this.depExports, + exports = this.exports, + factory = this.factory; + + if (!this.inited) { + // Only fetch if not already in the defQueue. + if (!hasProp(context.defQueueMap, id)) { + this.fetch(); + } + } else if (this.error) { + this.emit('error', this.error); + } else if (!this.defining) { + //The factory could trigger another require call + //that would result in checking this module to + //define itself again. If already in the process + //of doing that, skip this work. + this.defining = true; + + if (this.depCount < 1 && !this.defined) { + if (isFunction(factory)) { + //If there is an error listener, favor passing + //to that instead of throwing an error. However, + //only do it for define()'d modules. require + //errbacks should not be called for failures in + //their callbacks (#699). However if a global + //onError is set, use that. + if ((this.events.error && this.map.isDefine) || + req.onError !== defaultOnError) { + try { + exports = context.execCb(id, factory, depExports, exports); + } catch (e) { + err = e; + } + } else { + exports = context.execCb(id, factory, depExports, exports); + } + + // Favor return value over exports. If node/cjs in play, + // then will not have a return value anyway. Favor + // module.exports assignment over exports object. + if (this.map.isDefine && exports === undefined) { + cjsModule = this.module; + if (cjsModule) { + exports = cjsModule.exports; + } else if (this.usingExports) { + //exports already set the defined value. + exports = this.exports; + } + } + + if (err) { + err.requireMap = this.map; + err.requireModules = this.map.isDefine ? [this.map.id] : null; + err.requireType = this.map.isDefine ? 'define' : 'require'; + return onError((this.error = err)); + } + + } else { + //Just a literal value + exports = factory; + } + + this.exports = exports; + + if (this.map.isDefine && !this.ignore) { + defined[id] = exports; + + if (req.onResourceLoad) { + var resLoadMaps = []; + each(this.depMaps, function (depMap) { + resLoadMaps.push(depMap.normalizedMap || depMap); + }); + req.onResourceLoad(context, this.map, resLoadMaps); + } + } + + //Clean up + cleanRegistry(id); + + this.defined = true; + } + + //Finished the define stage. Allow calling check again + //to allow define notifications below in the case of a + //cycle. + this.defining = false; + + if (this.defined && !this.defineEmitted) { + this.defineEmitted = true; + this.emit('defined', this.exports); + this.defineEmitComplete = true; + } + + } + }, + + callPlugin: function () { + var map = this.map, + id = map.id, + //Map already normalized the prefix. + pluginMap = makeModuleMap(map.prefix); + + //Mark this as a dependency for this plugin, so it + //can be traced for cycles. + this.depMaps.push(pluginMap); + + on(pluginMap, 'defined', bind(this, function (plugin) { + var load, normalizedMap, normalizedMod, + bundleId = getOwn(bundlesMap, this.map.id), + name = this.map.name, + parentName = this.map.parentMap ? this.map.parentMap.name : null, + localRequire = context.makeRequire(map.parentMap, { + enableBuildCallback: true + }); + + //If current map is not normalized, wait for that + //normalized name to load instead of continuing. + if (this.map.unnormalized) { + //Normalize the ID if the plugin allows it. + if (plugin.normalize) { + name = plugin.normalize(name, function (name) { + return normalize(name, parentName, true); + }) || ''; + } + + //prefix and name should already be normalized, no need + //for applying map config again either. + normalizedMap = makeModuleMap(map.prefix + '!' + name, + this.map.parentMap); + on(normalizedMap, + 'defined', bind(this, function (value) { + this.map.normalizedMap = normalizedMap; + this.init([], function () { return value; }, null, { + enabled: true, + ignore: true + }); + })); + + normalizedMod = getOwn(registry, normalizedMap.id); + if (normalizedMod) { + //Mark this as a dependency for this plugin, so it + //can be traced for cycles. + this.depMaps.push(normalizedMap); + + if (this.events.error) { + normalizedMod.on('error', bind(this, function (err) { + this.emit('error', err); + })); + } + normalizedMod.enable(); + } + + return; + } + + //If a paths config, then just load that file instead to + //resolve the plugin, as it is built into that paths layer. + if (bundleId) { + this.map.url = context.nameToUrl(bundleId); + this.load(); + return; + } + + load = bind(this, function (value) { + this.init([], function () { return value; }, null, { + enabled: true + }); + }); + + load.error = bind(this, function (err) { + this.inited = true; + this.error = err; + err.requireModules = [id]; + + //Remove temp unnormalized modules for this module, + //since they will never be resolved otherwise now. + eachProp(registry, function (mod) { + if (mod.map.id.indexOf(id + '_unnormalized') === 0) { + cleanRegistry(mod.map.id); + } + }); + + onError(err); + }); + + //Allow plugins to load other code without having to know the + //context or how to 'complete' the load. + load.fromText = bind(this, function (text, textAlt) { + /*jslint evil: true */ + var moduleName = map.name, + moduleMap = makeModuleMap(moduleName), + hasInteractive = useInteractive; + + //As of 2.1.0, support just passing the text, to reinforce + //fromText only being called once per resource. Still + //support old style of passing moduleName but discard + //that moduleName in favor of the internal ref. + if (textAlt) { + text = textAlt; + } + + //Turn off interactive script matching for IE for any define + //calls in the text, then turn it back on at the end. + if (hasInteractive) { + useInteractive = false; + } + + //Prime the system by creating a module instance for + //it. + getModule(moduleMap); + + //Transfer any config to this other module. + if (hasProp(config.config, id)) { + config.config[moduleName] = config.config[id]; + } + + try { + req.exec(text); + } catch (e) { + return onError(makeError('fromtexteval', + 'fromText eval for ' + id + + ' failed: ' + e, + e, + [id])); + } + + if (hasInteractive) { + useInteractive = true; + } + + //Mark this as a dependency for the plugin + //resource + this.depMaps.push(moduleMap); + + //Support anonymous modules. + context.completeLoad(moduleName); + + //Bind the value of that module to the value for this + //resource ID. + localRequire([moduleName], load); + }); + + //Use parentName here since the plugin's name is not reliable, + //could be some weird string with no path that actually wants to + //reference the parentName's path. + plugin.load(map.name, localRequire, load, config); + })); + + context.enable(pluginMap, this); + this.pluginMaps[pluginMap.id] = pluginMap; + }, + + enable: function () { + enabledRegistry[this.map.id] = this; + this.enabled = true; + + //Set flag mentioning that the module is enabling, + //so that immediate calls to the defined callbacks + //for dependencies do not trigger inadvertent load + //with the depCount still being zero. + this.enabling = true; + + //Enable each dependency + each(this.depMaps, bind(this, function (depMap, i) { + var id, mod, handler; + + if (typeof depMap === 'string') { + //Dependency needs to be converted to a depMap + //and wired up to this module. + depMap = makeModuleMap(depMap, + (this.map.isDefine ? this.map : this.map.parentMap), + false, + !this.skipMap); + this.depMaps[i] = depMap; + + handler = getOwn(handlers, depMap.id); + + if (handler) { + this.depExports[i] = handler(this); + return; + } + + this.depCount += 1; + + on(depMap, 'defined', bind(this, function (depExports) { + if (this.undefed) { + return; + } + this.defineDep(i, depExports); + this.check(); + })); + + if (this.errback) { + on(depMap, 'error', bind(this, this.errback)); + } else if (this.events.error) { + // No direct errback on this module, but something + // else is listening for errors, so be sure to + // propagate the error correctly. + on(depMap, 'error', bind(this, function(err) { + this.emit('error', err); + })); + } + } + + id = depMap.id; + mod = registry[id]; + + //Skip special modules like 'require', 'exports', 'module' + //Also, don't call enable if it is already enabled, + //important in circular dependency cases. + if (!hasProp(handlers, id) && mod && !mod.enabled) { + context.enable(depMap, this); + } + })); + + //Enable each plugin that is used in + //a dependency + eachProp(this.pluginMaps, bind(this, function (pluginMap) { + var mod = getOwn(registry, pluginMap.id); + if (mod && !mod.enabled) { + context.enable(pluginMap, this); + } + })); + + this.enabling = false; + + this.check(); + }, + + on: function (name, cb) { + var cbs = this.events[name]; + if (!cbs) { + cbs = this.events[name] = []; + } + cbs.push(cb); + }, + + emit: function (name, evt) { + each(this.events[name], function (cb) { + cb(evt); + }); + if (name === 'error') { + //Now that the error handler was triggered, remove + //the listeners, since this broken Module instance + //can stay around for a while in the registry. + delete this.events[name]; + } + } + }; + + function callGetModule(args) { + //Skip modules already defined. + if (!hasProp(defined, args[0])) { + getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); + } + } + + function removeListener(node, func, name, ieName) { + //Favor detachEvent because of IE9 + //issue, see attachEvent/addEventListener comment elsewhere + //in this file. + if (node.detachEvent && !isOpera) { + //Probably IE. If not it will throw an error, which will be + //useful to know. + if (ieName) { + node.detachEvent(ieName, func); + } + } else { + node.removeEventListener(name, func, false); + } + } + + /** + * Given an event from a script node, get the requirejs info from it, + * and then removes the event listeners on the node. + * @param {Event} evt + * @returns {Object} + */ + function getScriptData(evt) { + //Using currentTarget instead of target for Firefox 2.0's sake. Not + //all old browsers will be supported, but this one was easy enough + //to support and still makes sense. + var node = evt.currentTarget || evt.srcElement; + + //Remove the listeners once here. + removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); + removeListener(node, context.onScriptError, 'error'); + + return { + node: node, + id: node && node.getAttribute('data-requiremodule') + }; + } + + function intakeDefines() { + var args; + + //Any defined modules in the global queue, intake them now. + takeGlobalQueue(); + + //Make sure any remaining defQueue items get properly processed. + while (defQueue.length) { + args = defQueue.shift(); + if (args[0] === null) { + return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + + args[args.length - 1])); + } else { + //args are id, deps, factory. Should be normalized by the + //define() function. + callGetModule(args); + } + } + context.defQueueMap = {}; + } + + context = { + config: config, + contextName: contextName, + registry: registry, + defined: defined, + urlFetched: urlFetched, + defQueue: defQueue, + defQueueMap: {}, + Module: Module, + makeModuleMap: makeModuleMap, + nextTick: req.nextTick, + onError: onError, + + /** + * Set a configuration for the context. + * @param {Object} cfg config object to integrate. + */ + configure: function (cfg) { + //Make sure the baseUrl ends in a slash. + if (cfg.baseUrl) { + if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { + cfg.baseUrl += '/'; + } + } + + // Convert old style urlArgs string to a function. + if (typeof cfg.urlArgs === 'string') { + var urlArgs = cfg.urlArgs; + cfg.urlArgs = function(id, url) { + return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs; + }; + } + + //Save off the paths since they require special processing, + //they are additive. + var shim = config.shim, + objs = { + paths: true, + bundles: true, + config: true, + map: true + }; + + eachProp(cfg, function (value, prop) { + if (objs[prop]) { + if (!config[prop]) { + config[prop] = {}; + } + mixin(config[prop], value, true, true); + } else { + config[prop] = value; + } + }); + + //Reverse map the bundles + if (cfg.bundles) { + eachProp(cfg.bundles, function (value, prop) { + each(value, function (v) { + if (v !== prop) { + bundlesMap[v] = prop; + } + }); + }); + } + + //Merge shim + if (cfg.shim) { + eachProp(cfg.shim, function (value, id) { + //Normalize the structure + if (isArray(value)) { + value = { + deps: value + }; + } + if ((value.exports || value.init) && !value.exportsFn) { + value.exportsFn = context.makeShimExports(value); + } + shim[id] = value; + }); + config.shim = shim; + } + + //Adjust packages if necessary. + if (cfg.packages) { + each(cfg.packages, function (pkgObj) { + var location, name; + + pkgObj = typeof pkgObj === 'string' ? {name: pkgObj} : pkgObj; + + name = pkgObj.name; + location = pkgObj.location; + if (location) { + config.paths[name] = pkgObj.location; + } + + //Save pointer to main module ID for pkg name. + //Remove leading dot in main, so main paths are normalized, + //and remove any trailing .js, since different package + //envs have different conventions: some use a module name, + //some use a file name. + config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main') + .replace(currDirRegExp, '') + .replace(jsSuffixRegExp, ''); + }); + } + + //If there are any "waiting to execute" modules in the registry, + //update the maps for them, since their info, like URLs to load, + //may have changed. + eachProp(registry, function (mod, id) { + //If module already has init called, since it is too + //late to modify them, and ignore unnormalized ones + //since they are transient. + if (!mod.inited && !mod.map.unnormalized) { + mod.map = makeModuleMap(id, null, true); + } + }); + + //If a deps array or a config callback is specified, then call + //require with those args. This is useful when require is defined as a + //config object before require.js is loaded. + if (cfg.deps || cfg.callback) { + context.require(cfg.deps || [], cfg.callback); + } + }, + + makeShimExports: function (value) { + function fn() { + var ret; + if (value.init) { + ret = value.init.apply(global, arguments); + } + return ret || (value.exports && getGlobal(value.exports)); + } + return fn; + }, + + makeRequire: function (relMap, options) { + options = options || {}; + + function localRequire(deps, callback, errback) { + var id, map, requireMod; + + if (options.enableBuildCallback && callback && isFunction(callback)) { + callback.__requireJsBuild = true; + } + + if (typeof deps === 'string') { + if (isFunction(callback)) { + //Invalid call + return onError(makeError('requireargs', 'Invalid require call'), errback); + } + + //If require|exports|module are requested, get the + //value for them from the special handlers. Caveat: + //this only works while module is being defined. + if (relMap && hasProp(handlers, deps)) { + return handlers[deps](registry[relMap.id]); + } + + //Synchronous access to one module. If require.get is + //available (as in the Node adapter), prefer that. + if (req.get) { + return req.get(context, deps, relMap, localRequire); + } + + //Normalize module name, if it contains . or .. + map = makeModuleMap(deps, relMap, false, true); + id = map.id; + + if (!hasProp(defined, id)) { + return onError(makeError('notloaded', 'Module name "' + + id + + '" has not been loaded yet for context: ' + + contextName + + (relMap ? '' : '. Use require([])'))); + } + return defined[id]; + } + + //Grab defines waiting in the global queue. + intakeDefines(); + + //Mark all the dependencies as needing to be loaded. + context.nextTick(function () { + //Some defines could have been added since the + //require call, collect them. + intakeDefines(); + + requireMod = getModule(makeModuleMap(null, relMap)); + + //Store if map config should be applied to this require + //call for dependencies. + requireMod.skipMap = options.skipMap; + + requireMod.init(deps, callback, errback, { + enabled: true + }); + + checkLoaded(); + }); + + return localRequire; + } + + mixin(localRequire, { + isBrowser: isBrowser, + + /** + * Converts a module name + .extension into an URL path. + * *Requires* the use of a module name. It does not support using + * plain URLs like nameToUrl. + */ + toUrl: function (moduleNamePlusExt) { + var ext, + index = moduleNamePlusExt.lastIndexOf('.'), + segment = moduleNamePlusExt.split('/')[0], + isRelative = segment === '.' || segment === '..'; + + //Have a file extension alias, and it is not the + //dots from a relative path. + if (index !== -1 && (!isRelative || index > 1)) { + ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); + moduleNamePlusExt = moduleNamePlusExt.substring(0, index); + } + + return context.nameToUrl(normalize(moduleNamePlusExt, + relMap && relMap.id, true), ext, true); + }, + + defined: function (id) { + return hasProp(defined, makeModuleMap(id, relMap, false, true).id); + }, + + specified: function (id) { + id = makeModuleMap(id, relMap, false, true).id; + return hasProp(defined, id) || hasProp(registry, id); + } + }); + + //Only allow undef on top level require calls + if (!relMap) { + localRequire.undef = function (id) { + //Bind any waiting define() calls to this context, + //fix for #408 + takeGlobalQueue(); + + var map = makeModuleMap(id, relMap, true), + mod = getOwn(registry, id); + + mod.undefed = true; + removeScript(id); + + delete defined[id]; + delete urlFetched[map.url]; + delete undefEvents[id]; + + //Clean queued defines too. Go backwards + //in array so that the splices do not + //mess up the iteration. + eachReverse(defQueue, function(args, i) { + if (args[0] === id) { + defQueue.splice(i, 1); + } + }); + delete context.defQueueMap[id]; + + if (mod) { + //Hold on to listeners in case the + //module will be attempted to be reloaded + //using a different config. + if (mod.events.defined) { + undefEvents[id] = mod.events; + } + + cleanRegistry(id); + } + }; + } + + return localRequire; + }, + + /** + * Called to enable a module if it is still in the registry + * awaiting enablement. A second arg, parent, the parent module, + * is passed in for context, when this method is overridden by + * the optimizer. Not shown here to keep code compact. + */ + enable: function (depMap) { + var mod = getOwn(registry, depMap.id); + if (mod) { + getModule(depMap).enable(); + } + }, + + /** + * Internal method used by environment adapters to complete a load event. + * A load event could be a script load or just a load pass from a synchronous + * load call. + * @param {String} moduleName the name of the module to potentially complete. + */ + completeLoad: function (moduleName) { + var found, args, mod, + shim = getOwn(config.shim, moduleName) || {}, + shExports = shim.exports; + + takeGlobalQueue(); + + while (defQueue.length) { + args = defQueue.shift(); + if (args[0] === null) { + args[0] = moduleName; + //If already found an anonymous module and bound it + //to this name, then this is some other anon module + //waiting for its completeLoad to fire. + if (found) { + break; + } + found = true; + } else if (args[0] === moduleName) { + //Found matching define call for this script! + found = true; + } + + callGetModule(args); + } + context.defQueueMap = {}; + + //Do this after the cycle of callGetModule in case the result + //of those calls/init calls changes the registry. + mod = getOwn(registry, moduleName); + + if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { + if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { + if (hasPathFallback(moduleName)) { + return; + } else { + return onError(makeError('nodefine', + 'No define call for ' + moduleName, + null, + [moduleName])); + } + } else { + //A script that does not call define(), so just simulate + //the call for it. + callGetModule([moduleName, (shim.deps || []), shim.exportsFn]); + } + } + + checkLoaded(); + }, + + /** + * Converts a module name to a file path. Supports cases where + * moduleName may actually be just an URL. + * Note that it **does not** call normalize on the moduleName, + * it is assumed to have already been normalized. This is an + * internal API, not a public one. Use toUrl for the public API. + */ + nameToUrl: function (moduleName, ext, skipExt) { + var paths, syms, i, parentModule, url, + parentPath, bundleId, + pkgMain = getOwn(config.pkgs, moduleName); + + if (pkgMain) { + moduleName = pkgMain; + } + + bundleId = getOwn(bundlesMap, moduleName); + + if (bundleId) { + return context.nameToUrl(bundleId, ext, skipExt); + } + + //If a colon is in the URL, it indicates a protocol is used and it is just + //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) + //or ends with .js, then assume the user meant to use an url and not a module id. + //The slash is important for protocol-less URLs as well as full paths. + if (req.jsExtRegExp.test(moduleName)) { + //Just a plain path, not module name lookup, so just return it. + //Add extension if it is included. This is a bit wonky, only non-.js things pass + //an extension, this method probably needs to be reworked. + url = moduleName + (ext || ''); + } else { + //A module that needs to be converted to a path. + paths = config.paths; + + syms = moduleName.split('/'); + //For each module name segment, see if there is a path + //registered for it. Start with most specific name + //and work up from it. + for (i = syms.length; i > 0; i -= 1) { + parentModule = syms.slice(0, i).join('/'); + + parentPath = getOwn(paths, parentModule); + if (parentPath) { + //If an array, it means there are a few choices, + //Choose the one that is desired + if (isArray(parentPath)) { + parentPath = parentPath[0]; + } + syms.splice(0, i, parentPath); + break; + } + } + + //Join the path parts together, then figure out if baseUrl is needed. + url = syms.join('/'); + url += (ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js')); + url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; + } + + return config.urlArgs && !/^blob\:/.test(url) ? + url + config.urlArgs(moduleName, url) : url; + }, + + //Delegates to req.load. Broken out as a separate function to + //allow overriding in the optimizer. + load: function (id, url) { + req.load(context, id, url); + }, + + /** + * Executes a module callback function. Broken out as a separate function + * solely to allow the build system to sequence the files in the built + * layer in the right sequence. + * + * @private + */ + execCb: function (name, callback, args, exports) { + return callback.apply(exports, args); + }, + + /** + * callback for script loads, used to check status of loading. + * + * @param {Event} evt the event from the browser for the script + * that was loaded. + */ + onScriptLoad: function (evt) { + //Using currentTarget instead of target for Firefox 2.0's sake. Not + //all old browsers will be supported, but this one was easy enough + //to support and still makes sense. + if (evt.type === 'load' || + (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { + //Reset interactive script so a script node is not held onto for + //to long. + interactiveScript = null; + + //Pull out the name of the module and the context. + var data = getScriptData(evt); + context.completeLoad(data.id); + } + }, + + /** + * Callback for script errors. + */ + onScriptError: function (evt) { + var data = getScriptData(evt); + if (!hasPathFallback(data.id)) { + var parents = []; + eachProp(registry, function(value, key) { + if (key.indexOf('_@r') !== 0) { + each(value.depMaps, function(depMap) { + if (depMap.id === data.id) { + parents.push(key); + return true; + } + }); + } + }); + return onError(makeError('scripterror', 'Script error for "' + data.id + + (parents.length ? + '", needed by: ' + parents.join(', ') : + '"'), evt, [data.id])); + } + } + }; + + context.require = context.makeRequire(); + return context; + } + + /** + * Main entry point. + * + * If the only argument to require is a string, then the module that + * is represented by that string is fetched for the appropriate context. + * + * If the first argument is an array, then it will be treated as an array + * of dependency string names to fetch. An optional function callback can + * be specified to execute when all of those dependencies are available. + * + * Make a local req variable to help Caja compliance (it assumes things + * on a require that are not standardized), and to give a short + * name for minification/local scope use. + */ + req = requirejs = function (deps, callback, errback, optional) { + + //Find the right context, use default + var context, config, + contextName = defContextName; + + // Determine if have config object in the call. + if (!isArray(deps) && typeof deps !== 'string') { + // deps is a config object + config = deps; + if (isArray(callback)) { + // Adjust args if there are dependencies + deps = callback; + callback = errback; + errback = optional; + } else { + deps = []; + } + } + + if (config && config.context) { + contextName = config.context; + } + + context = getOwn(contexts, contextName); + if (!context) { + context = contexts[contextName] = req.s.newContext(contextName); + } + + if (config) { + context.configure(config); + } + + return context.require(deps, callback, errback); + }; + + /** + * Support require.config() to make it easier to cooperate with other + * AMD loaders on globally agreed names. + */ + req.config = function (config) { + return req(config); + }; + + /** + * Execute something after the current tick + * of the event loop. Override for other envs + * that have a better solution than setTimeout. + * @param {Function} fn function to execute later. + */ + req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { + setTimeout(fn, 4); + } : function (fn) { fn(); }; + + /** + * Export require as a global, but only if it does not already exist. + */ + if (!require) { + require = req; + } + + req.version = version; + + //Used to filter out dependencies that are already paths. + req.jsExtRegExp = /^\/|:|\?|\.js$/; + req.isBrowser = isBrowser; + s = req.s = { + contexts: contexts, + newContext: newContext + }; + + //Create default context. + req({}); + + //Exports some context-sensitive methods on global require. + each([ + 'toUrl', + 'undef', + 'defined', + 'specified' + ], function (prop) { + //Reference from contexts instead of early binding to default context, + //so that during builds, the latest instance of the default context + //with its config gets used. + req[prop] = function () { + var ctx = contexts[defContextName]; + return ctx.require[prop].apply(ctx, arguments); + }; + }); + + if (isBrowser) { + head = s.head = document.getElementsByTagName('head')[0]; + //If BASE tag is in play, using appendChild is a problem for IE6. + //When that browser dies, this can be removed. Details in this jQuery bug: + //http://dev.jquery.com/ticket/2709 + baseElement = document.getElementsByTagName('base')[0]; + if (baseElement) { + head = s.head = baseElement.parentNode; + } + } + + /** + * Any errors that require explicitly generates will be passed to this + * function. Intercept/override it if you want custom error handling. + * @param {Error} err the error object. + */ + req.onError = defaultOnError; + + /** + * Creates the node for the load command. Only used in browser envs. + */ + req.createNode = function (config, moduleName, url) { + var node = config.xhtml ? + document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') : + document.createElement('script'); + node.type = config.scriptType || 'text/javascript'; + node.charset = 'utf-8'; + node.async = true; + return node; + }; + + /** + * Does the request to load a module for the browser case. + * Make this a separate function to allow other environments + * to override it. + * + * @param {Object} context the require context to find state. + * @param {String} moduleName the name of the module. + * @param {Object} url the URL to the module. + */ + req.load = function (context, moduleName, url) { + var config = (context && context.config) || {}, + node; + if (isBrowser) { + //In the browser so use a script tag + node = req.createNode(config, moduleName, url); + + node.setAttribute('data-requirecontext', context.contextName); + node.setAttribute('data-requiremodule', moduleName); + + //Set up load listener. Test attachEvent first because IE9 has + //a subtle issue in its addEventListener and script onload firings + //that do not match the behavior of all other browsers with + //addEventListener support, which fire the onload event for a + //script right after the script execution. See: + //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution + //UNFORTUNATELY Opera implements attachEvent but does not follow the script + //script execution mode. + if (node.attachEvent && + //Check if node.attachEvent is artificially added by custom script or + //natively supported by browser + //read https://github.com/requirejs/requirejs/issues/187 + //if we can NOT find [native code] then it must NOT natively supported. + //in IE8, node.attachEvent does not have toString() + //Note the test for "[native code" with no closing brace, see: + //https://github.com/requirejs/requirejs/issues/273 + !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && + !isOpera) { + //Probably IE. IE (at least 6-8) do not fire + //script onload right after executing the script, so + //we cannot tie the anonymous define call to a name. + //However, IE reports the script as being in 'interactive' + //readyState at the time of the define call. + useInteractive = true; + + node.attachEvent('onreadystatechange', context.onScriptLoad); + //It would be great to add an error handler here to catch + //404s in IE9+. However, onreadystatechange will fire before + //the error handler, so that does not help. If addEventListener + //is used, then IE will fire error before load, but we cannot + //use that pathway given the connect.microsoft.com issue + //mentioned above about not doing the 'script execute, + //then fire the script load event listener before execute + //next script' that other browsers do. + //Best hope: IE10 fixes the issues, + //and then destroys all installs of IE 6-9. + //node.attachEvent('onerror', context.onScriptError); + } else { + node.addEventListener('load', context.onScriptLoad, false); + node.addEventListener('error', context.onScriptError, false); + } + node.src = url; + + //Calling onNodeCreated after all properties on the node have been + //set, but before it is placed in the DOM. + if (config.onNodeCreated) { + config.onNodeCreated(node, config, moduleName, url); + } + + //For some cache cases in IE 6-8, the script executes before the end + //of the appendChild execution, so to tie an anonymous define + //call to the module name (which is stored on the node), hold on + //to a reference to this node, but clear after the DOM insertion. + currentlyAddingScript = node; + if (baseElement) { + head.insertBefore(node, baseElement); + } else { + head.appendChild(node); + } + currentlyAddingScript = null; + + return node; + } else if (isWebWorker) { + try { + //In a web worker, use importScripts. This is not a very + //efficient use of importScripts, importScripts will block until + //its script is downloaded and evaluated. However, if web workers + //are in play, the expectation is that a build has been done so + //that only one script needs to be loaded anyway. This may need + //to be reevaluated if other use cases become common. + + // Post a task to the event loop to work around a bug in WebKit + // where the worker gets garbage-collected after calling + // importScripts(): https://webkit.org/b/153317 + setTimeout(function() {}, 0); + importScripts(url); + + //Account for anonymous modules + context.completeLoad(moduleName); + } catch (e) { + context.onError(makeError('importscripts', + 'importScripts failed for ' + + moduleName + ' at ' + url, + e, + [moduleName])); + } + } + }; + + function getInteractiveScript() { + if (interactiveScript && interactiveScript.readyState === 'interactive') { + return interactiveScript; + } + + eachReverse(scripts(), function (script) { + if (script.readyState === 'interactive') { + return (interactiveScript = script); + } + }); + return interactiveScript; + } + + //Look for a data-main script attribute, which could also adjust the baseUrl. + if (isBrowser && !cfg.skipDataMain) { + //Figure out baseUrl. Get it from the script tag with require.js in it. + eachReverse(scripts(), function (script) { + //Set the 'head' where we can append children by + //using the script's parent. + if (!head) { + head = script.parentNode; + } + + //Look for a data-main attribute to set main script for the page + //to load. If it is there, the path to data main becomes the + //baseUrl, if it is not already set. + dataMain = script.getAttribute('data-main'); + if (dataMain) { + //Preserve dataMain in case it is a path (i.e. contains '?') + mainScript = dataMain; + + //Set final baseUrl if there is not already an explicit one, + //but only do so if the data-main value is not a loader plugin + //module ID. + if (!cfg.baseUrl && mainScript.indexOf('!') === -1) { + //Pull off the directory of data-main for use as the + //baseUrl. + src = mainScript.split('/'); + mainScript = src.pop(); + subPath = src.length ? src.join('/') + '/' : './'; + + cfg.baseUrl = subPath; + } + + //Strip off any trailing .js since mainScript is now + //like a module name. + mainScript = mainScript.replace(jsSuffixRegExp, ''); + + //If mainScript is still a path, fall back to dataMain + if (req.jsExtRegExp.test(mainScript)) { + mainScript = dataMain; + } + + //Put the data-main script in the files to load. + cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; + + return true; + } + }); + } + + /** + * The function that handles definitions of modules. Differs from + * require() in that a string for the module should be the first argument, + * and the function to execute after dependencies are loaded should + * return a value to define the module corresponding to the first argument's + * name. + */ + define = function (name, deps, callback) { + var node, context; + + //Allow for anonymous modules + if (typeof name !== 'string') { + //Adjust args appropriately + callback = deps; + deps = name; + name = null; + } + + //This module may not have dependencies + if (!isArray(deps)) { + callback = deps; + deps = null; + } + + //If no name, and callback is a function, then figure out if it a + //CommonJS thing with dependencies. + if (!deps && isFunction(callback)) { + deps = []; + //Remove comments from the callback string, + //look for require calls, and pull them into the dependencies, + //but only if there are function args. + if (callback.length) { + callback + .toString() + .replace(commentRegExp, commentReplace) + .replace(cjsRequireRegExp, function (match, dep) { + deps.push(dep); + }); + + //May be a CommonJS thing even without require calls, but still + //could use exports, and module. Avoid doing exports and module + //work though if it just needs require. + //REQUIRES the function to expect the CommonJS variables in the + //order listed below. + deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); + } + } + + //If in IE 6-8 and hit an anonymous define() call, do the interactive + //work. + if (useInteractive) { + node = currentlyAddingScript || getInteractiveScript(); + if (node) { + if (!name) { + name = node.getAttribute('data-requiremodule'); + } + context = contexts[node.getAttribute('data-requirecontext')]; + } + } + + //Always save off evaluating the def call until the script onload handler. + //This allows multiple modules to be in a file without prematurely + //tracing dependencies, and allows for anonymous module support, + //where the module name is not known until the script onload event + //occurs. If no context, use the global queue, and get it processed + //in the onscript load callback. + if (context) { + context.defQueue.push([name, deps, callback]); + context.defQueueMap[name] = true; + } else { + globalDefQueue.push([name, deps, callback]); + } + }; + + define.amd = { + jQuery: true + }; + + /** + * Executes the text. Normally just uses eval, but can be modified + * to use a better, environment-specific call. Only used for transpiling + * loader plugins, not for plain JS modules. + * @param {String} text the text to execute/evaluate. + */ + req.exec = function (text) { + /*jslint evil: true */ + return eval(text); + }; + + //Set up with config info. + req(cfg); +}(this)); diff --git a/common/Tests/Framework/src/AITestClass.ts b/common/Tests/Framework/src/AITestClass.ts index 6ea88410..5790bd90 100644 --- a/common/Tests/Framework/src/AITestClass.ts +++ b/common/Tests/Framework/src/AITestClass.ts @@ -400,9 +400,11 @@ export class AITestClass { if (spy.called && spy.args && spy.args.length > 0) { spy.args.forEach(call => { call[0].forEach((message: string) => { - // Ignore the internal SendBrowserInfoOnUserInit message (Only occurs when running tests in a browser) - if (includeInit || message.indexOf("AI (Internal): 72 ") === -1) { - resultPayload.push(message); + if (message) { + // Ignore the internal SendBrowserInfoOnUserInit message (Only occurs when running tests in a browser) + if (includeInit || message.indexOf("AI (Internal): 72 ") === -1) { + resultPayload.push(message); + } } }) }); @@ -590,9 +592,11 @@ export class AITestClass { for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i]; - var eqPos = cookie.indexOf("="); - var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie; - document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; + if (cookie) { + var eqPos = cookie.indexOf("="); + var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie; + document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; + } } } diff --git a/common/Tests/Framework/src/PollingAssert.ts b/common/Tests/Framework/src/PollingAssert.ts index e59c77b6..bce979dd 100644 --- a/common/Tests/Framework/src/PollingAssert.ts +++ b/common/Tests/Framework/src/PollingAssert.ts @@ -22,14 +22,14 @@ export class PollingAssert { Assert.ok(false, "assert didn't succeed for " + timeout + " seconds: " + assertDescription + "[" + (AITestClass.currentTestInfo ? AITestClass.currentTestInfo.name : "") + "]"); nextTestStep(); } else { - setTimeout(polling, pollIntervalMs); + AITestClass.orgSetTimeout(polling, pollIntervalMs); } } catch (e) { Assert.ok(true, "Polling exception - " + e); - setTimeout(polling, pollIntervalMs); + AITestClass.orgSetTimeout(polling, pollIntervalMs); } } - setTimeout(polling, pollIntervalMs); + AITestClass.orgSetTimeout(polling, pollIntervalMs); } pollingAssert[AITestClass.isPollingStepFlag] = true; diff --git a/common/Tests/Framework/src/TelemetryValidation/CommonValidator.ts b/common/Tests/Framework/src/TelemetryValidation/CommonValidator.ts new file mode 100644 index 00000000..65e59fa7 --- /dev/null +++ b/common/Tests/Framework/src/TelemetryValidation/CommonValidator.ts @@ -0,0 +1,24 @@ +import { ITypeValidator } from './ITypeValidator'; + +export class CommonValidator implements ITypeValidator { + + static CommonValidator = new CommonValidator(); + + public Validate(item: any, baseType: string): boolean { + // verify item has data, iKey, name, tags, and time fields + if (!item.data || !item.iKey || !item.name || !item.tags || !item.time) { + return false; + }; + + if (item.data.baseData.ver !== 2) { + return false; + } + + // verify item.data has baseType field + if (!item.data.baseType) { + return false; + } + + return true; + } +} \ No newline at end of file diff --git a/common/Tests/Framework/src/TelemetryValidation/EventValidator.ts b/common/Tests/Framework/src/TelemetryValidation/EventValidator.ts new file mode 100644 index 00000000..f0569ce5 --- /dev/null +++ b/common/Tests/Framework/src/TelemetryValidation/EventValidator.ts @@ -0,0 +1,25 @@ +import { ITypeValidator } from './ITypeValidator'; +import { CommonValidator } from './CommonValidator'; + +export class EventValidator implements ITypeValidator { + + static EventValidator = new EventValidator(); + + public Validate(item: any, baseType: string): boolean { + // verify item passes CommonValidator + if (!CommonValidator.CommonValidator.Validate(item, baseType)) { + return false; + } + + // verify item has ver, name, properties, and measurement fields + if (!item.data.baseData || + !item.data.baseData.ver || + !item.data.baseData.name || + !item.data.baseData.properties || + !item.data.baseData.measurements) { + return false; + } + + return true; + } +} \ No newline at end of file diff --git a/common/Tests/Framework/src/TelemetryValidation/ExceptionValidator.ts b/common/Tests/Framework/src/TelemetryValidation/ExceptionValidator.ts new file mode 100644 index 00000000..a6d4c52a --- /dev/null +++ b/common/Tests/Framework/src/TelemetryValidation/ExceptionValidator.ts @@ -0,0 +1,48 @@ +import { ITypeValidator } from './ITypeValidator'; +import { CommonValidator } from './CommonValidator'; + +export class ExceptionValidator implements ITypeValidator { + static ExceptionValidator = new ExceptionValidator(); + + private static _validateExceptions(exceptions: any[]): boolean { + // verify exceptions has typeName, message, hasFullStack, stack, parsedStack fields + if (!("typeName" in exceptions[0]) || + !("message" in exceptions[0]) || + !("hasFullStack" in exceptions[0]) || + !("stack" in exceptions[0]) || + !("parsedStack" in exceptions[0])) { + return false; + } + + return true; + } + + Validate(item: any, baseType: string): boolean { + // verify item passes CommonValidator + if (!CommonValidator.CommonValidator.Validate(item, baseType)) { + console.log("ExceptionValidator::Validate failed - " + JSON.stringify(item)); + return false; + } + + // verify item has ver and exceptions fields + if (!item.data.baseData || + !item.data.baseData.ver || + !item.data.baseData.exceptions) { + console.log("ExceptionValidator::Validate missing basedata values - " + JSON.stringify(item.data)); + return false; + } + + // Exception.ver should be a number for breeze channel, but a string in CS4.0 + if (item.data.baseData.ver !== 2) { + console.log("ExceptionValidator::Validate not breeze - " + JSON.stringify(item.data.baseData)); + return false; // not a valid breeze exception + } + + if (!ExceptionValidator._validateExceptions(item.data.baseData.exceptions)) { + console.log("ExceptionValidator::_validateExceptions failed - " + JSON.stringify(item.data.baseData.exceptions)); + return false; + } + + return true; + } +} \ No newline at end of file diff --git a/common/Tests/Framework/src/TelemetryValidation/ITypeValidator.ts b/common/Tests/Framework/src/TelemetryValidation/ITypeValidator.ts new file mode 100644 index 00000000..69d6be8f --- /dev/null +++ b/common/Tests/Framework/src/TelemetryValidation/ITypeValidator.ts @@ -0,0 +1,3 @@ +export interface ITypeValidator { + Validate(item: any, baseType?: string): boolean; +} \ No newline at end of file diff --git a/common/Tests/Framework/src/TelemetryValidation/MetricValidator.ts b/common/Tests/Framework/src/TelemetryValidation/MetricValidator.ts new file mode 100644 index 00000000..3c53b96e --- /dev/null +++ b/common/Tests/Framework/src/TelemetryValidation/MetricValidator.ts @@ -0,0 +1,23 @@ +import { ITypeValidator } from './ITypeValidator'; +import { CommonValidator } from './CommonValidator'; + +export class MetricValidator implements ITypeValidator { + static MetricValidator = new MetricValidator(); + + Validate(item: any, baseType: string): boolean { + // verify item passes CommonValidator + if (!CommonValidator.CommonValidator.Validate(item, baseType)) { + return false; + } + + // verify item has ver, metrics, and properties fields + if (!item.data.baseData || + !item.data.baseData.ver || + !item.data.baseData.metrics || + !item.data.baseData.properties) { + return false; + } + + return true; + } +} \ No newline at end of file diff --git a/common/Tests/Framework/src/TelemetryValidation/PageViewPerformanceValidator.ts b/common/Tests/Framework/src/TelemetryValidation/PageViewPerformanceValidator.ts new file mode 100644 index 00000000..780b9843 --- /dev/null +++ b/common/Tests/Framework/src/TelemetryValidation/PageViewPerformanceValidator.ts @@ -0,0 +1,29 @@ +import { ITypeValidator } from './ITypeValidator'; +import { CommonValidator } from './CommonValidator'; + +export class PageViewPerformanceValidator implements ITypeValidator { + static PageViewPerformanceValidator = new PageViewPerformanceValidator(); + + public Validate(item: any, baseType: string): boolean { + // verify item passes CommonValidator + if (!CommonValidator.CommonValidator.Validate(item, baseType)) { + return false; + } + + // verify item has ver, url, perfTotal, name, duration, networkConnect, sentRequest, receivedResponse, and domProcessing fields + if (!item.data.baseData || + !item.data.baseData.ver || + !item.data.baseData.url || + !item.data.baseData.perfTotal || + !item.data.baseData.name || + !item.data.baseData.duration || + !item.data.baseData.networkConnect || + !item.data.baseData.sentRequest || + !item.data.baseData.receivedResponse || + !item.data.baseData.domProcessing) { + return false; + } + + return true; + } +} \ No newline at end of file diff --git a/common/Tests/Framework/src/TelemetryValidation/PageViewValidator.ts b/common/Tests/Framework/src/TelemetryValidation/PageViewValidator.ts new file mode 100644 index 00000000..fa430f0b --- /dev/null +++ b/common/Tests/Framework/src/TelemetryValidation/PageViewValidator.ts @@ -0,0 +1,26 @@ +import { ITypeValidator } from './ITypeValidator'; +import { CommonValidator } from './CommonValidator'; + +export class PageViewValidator implements ITypeValidator { + static PageViewValidator = new PageViewValidator(); + + public Validate(item: any, baseType: string): boolean { + // verify item passes CommonValidator + if (!CommonValidator.CommonValidator.Validate(item, baseType)) { + return false; + } + + // verify item has ver, url, name, duration, id, properties, and measurements fields + if (!item.data.baseData || + !item.data.baseData.ver || + !item.data.baseData.url || + !item.data.baseData.name || + !item.data.baseData.duration || + !item.data.baseData.id || + !item.data.baseData.properties || + !item.data.baseData.measurements) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/common/Tests/Framework/src/TelemetryValidation/RemoteDepdencyValidator.ts b/common/Tests/Framework/src/TelemetryValidation/RemoteDepdencyValidator.ts new file mode 100644 index 00000000..146b65b2 --- /dev/null +++ b/common/Tests/Framework/src/TelemetryValidation/RemoteDepdencyValidator.ts @@ -0,0 +1,30 @@ +import { ITypeValidator } from './ITypeValidator'; +import { CommonValidator } from './CommonValidator'; + +export class RemoteDepdencyValidator implements ITypeValidator { + static RemoteDepdencyValidator = new RemoteDepdencyValidator(); + + public Validate(item: any, baseType: string): boolean { + // verify item passes CommonValidator + if (!CommonValidator.CommonValidator.Validate(item, baseType)) { + return false; + } + + // verify item has ver, name, id, resultCode, duration, data, target, type, properties, and measurement fields + if (!item.data.baseData || + !item.data.baseData.ver || + !item.data.baseData.name || + !item.data.baseData.id || + !item.data.baseData.resultCode || + !item.data.baseData.duration || + !item.data.baseData.data || + !item.data.baseData.target || + !item.data.baseData.type || + !item.data.baseData.properties || + !item.data.baseData.measurements) { + return false; + } + + return true; + } +} \ No newline at end of file diff --git a/common/Tests/Framework/src/TelemetryValidation/TraceValidator.ts b/common/Tests/Framework/src/TelemetryValidation/TraceValidator.ts new file mode 100644 index 00000000..045bdde8 --- /dev/null +++ b/common/Tests/Framework/src/TelemetryValidation/TraceValidator.ts @@ -0,0 +1,22 @@ +import { ITypeValidator } from './ITypeValidator'; +import { CommonValidator } from './CommonValidator'; + +export class TraceValidator implements ITypeValidator { + static TraceValidator = new TraceValidator(); + + public Validate(item: any, baseType: string): boolean { + // verify item passes CommonValidator + if (!CommonValidator.CommonValidator.Validate(item, baseType)) { + return false; + } + + // verify item has ver, message, and properties fields + if (!item.data.baseData || + !item.data.baseData.ver || + !item.data.baseData.message || + !item.data.baseData.properties) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/common/Tests/Framework/src/ai-test-framework.ts b/common/Tests/Framework/src/ai-test-framework.ts index f8535005..71dfd4bd 100644 --- a/common/Tests/Framework/src/ai-test-framework.ts +++ b/common/Tests/Framework/src/ai-test-framework.ts @@ -2,3 +2,13 @@ export { Assert } from "./Assert"; export { PollingAssert } from "./PollingAssert"; export { TestCase, TestCaseAsync } from "./TestCase"; export { AITestClass } from "./AITestClass"; + +export { ITypeValidator } from "./TelemetryValidation/ITypeValidator"; +export { CommonValidator } from "./TelemetryValidation/CommonValidator"; +export { EventValidator } from "./TelemetryValidation/EventValidator"; +export { ExceptionValidator } from "./TelemetryValidation/ExceptionValidator"; +export { MetricValidator } from "./TelemetryValidation/MetricValidator"; +export { PageViewPerformanceValidator } from "./TelemetryValidation/PageViewPerformanceValidator"; +export { PageViewValidator } from "./TelemetryValidation/PageViewValidator"; +export { RemoteDepdencyValidator } from "./TelemetryValidation/RemoteDepdencyValidator"; +export { TraceValidator } from "./TelemetryValidation/TraceValidator"; diff --git a/common/Tests/Selenium/ExceptionHelper.js b/common/Tests/Selenium/ExceptionHelper.js new file mode 100644 index 00000000..2f88a497 --- /dev/null +++ b/common/Tests/Selenium/ExceptionHelper.js @@ -0,0 +1,128 @@ + +function ExceptionHelper(config) { + + let orgError = null; + + function throwCorsException() { + throw "Simulated Cors Exception"; + } + + function throwPageException(value) { + function doThrow() { + throw value; + } + + doThrow(); + } + + function throwStrictException(value) { + "use strict"; + function doThrow() { + throw value; + } + + doThrow(); + } + + function throwRuntimeException(timeoutFunc) { + function doThrow() { + var ug = "Hello"; + // This should throw + ug(); + } + + if (!timeoutFunc) { + timeoutFunc = setTimeout; + } + + timeoutFunc(function() { + doThrow(); + }, 0); + } + + function throwStrictRuntimeException(timeoutFunc) { + "use strict"; + function doThrow() { + var ug = "Hello"; + // This should throw + ug(); + } + + if (!timeoutFunc) { + timeoutFunc = setTimeout; + } + + timeoutFunc(function() { + doThrow(); + }, 0); + } + function saveOnError() { + if (!orgError) { + orgError = { + onerror: window.onerror + }; + } + } + + function restoreOnError() { + if (orgError && orgError.onerror) { + window.onerror = orgError.onerror; + } + } + + function captureStrictPageOnError(appInsights) { + saveOnError(); + + "use strict"; + function doCapture() { + + // Ignoring any previous handler + window.onerror = function (message, url, lineNumber, columnNumber, error) { + appInsights._onerror({ + message, + url, + lineNumber, + columnNumber, + error: error, + evt: window.event + }); + + return true; + } + } + + doCapture(); + } + + function capturePageOnError(appInsights) { + saveOnError(); + + function doCapture() { + // Ignoring any previous handler + window.onerror = function (message, url, lineNumber, columnNumber, error) { + appInsights._onerror({ + message, + url, + lineNumber, + columnNumber, + error: error, + evt: window.event + }); + + return true; + } + } + + doCapture(); + } + + return { + capture: capturePageOnError, + captureStrict: captureStrictPageOnError, + throw: throwPageException, + throwCors: throwCorsException, + throwStrict: throwStrictException, + throwRuntimeException: throwRuntimeException, + throwStrictRuntimeException: throwStrictRuntimeException + } +} \ No newline at end of file diff --git a/common/config/rush/command-line.json b/common/config/rush/command-line.json index 2cdbb604..5330df78 100644 --- a/common/config/rush/command-line.json +++ b/common/config/rush/command-line.json @@ -7,7 +7,7 @@ "summary": "Run all tests for all packages", "description": "Runs tests for all projects", "safeForSimultaneousRushProcesses": false, - "enableParallelism": true, + "enableParallelism": false, "ignoreMissingScript": false }, { diff --git a/common/config/rush/npm-shrinkwrap.json b/common/config/rush/npm-shrinkwrap.json index 279b00b3..ef6ec14b 100644 --- a/common/config/rush/npm-shrinkwrap.json +++ b/common/config/rush/npm-shrinkwrap.json @@ -37,6 +37,7 @@ "grunt-run": "^0.8.1", "grunt-ts": "^6.0.0-beta.22", "grunt-tslint": "^5.0.2", + "http-server": "0.12.3", "magic-string": "^0.25.7", "qunit": "^2.9.1", "rollup": "^2.32.0", @@ -63,16 +64,16 @@ } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.12.11", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.12.11.tgz", - "integrity": "sha512-np/lG3uARFybkoHokJUmf1QfEvRVCPbmQeUQpKow5cQ3xWrV9i3rUHodKDJPQfTVX61qKi+UdYk8kik84n7XOw==" + "version": "7.14.0", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.0.tgz", + "integrity": "sha512-V3ts7zMSu5lfiwWDVWzRDGIN+lnCEUdaXgtVHJgLb1rGaA6jMrtB9EmE7L18foXJIE8Un/A/h6NJfGQp/e1J4A==" }, "node_modules/@babel/highlight": { - "version": "7.13.10", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.13.10.tgz", - "integrity": "sha512-5aPpe5XQPzflQrFwL1/QoeHkP2MsA4JCntcXHRhEsdsfPVkvPi2w7Qix4iV7t5S/oC9OodGrggd8aco1g3SZFg==", + "version": "7.14.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.14.0.tgz", + "integrity": "sha512-YSCOwxvTYEIMSGaBQb5kDDsCopDdiUGsqpatp3fOlI4+2HQSkTmEVWnVuySdAC5EWCqSWWTv0ib63RjR7dTBdg==", "dependencies": { - "@babel/helper-validator-identifier": "^7.12.11", + "@babel/helper-validator-identifier": "^7.14.0", "chalk": "^2.0.0", "js-tokens": "^4.0.0" } @@ -134,14 +135,14 @@ } }, "node_modules/@microsoft/api-extractor": { - "version": "7.14.0", - "resolved": "https://registry.npmjs.org/@microsoft/api-extractor/-/api-extractor-7.14.0.tgz", - "integrity": "sha512-R9B0ic8EIcHhwSFQWYTyQX7QDi7kXONeKdIjJI8R+WzVJMA3r0Je9XxSQxxZ9MZIBUxv3fB7pXC2CPIsSkI/BA==", + "version": "7.15.1", + "resolved": "https://registry.npmjs.org/@microsoft/api-extractor/-/api-extractor-7.15.1.tgz", + "integrity": "sha512-PYbGAvxbM5B6HbafXY7tJ4ObYpeUZrZFt9vlN68tpYG/7aeldMLAZSjTyB30VFXaGlArjeEooKZIcs2ZnVAbNg==", "dependencies": { - "@microsoft/api-extractor-model": "7.13.0", + "@microsoft/api-extractor-model": "7.13.1", "@microsoft/tsdoc": "0.13.2", "@microsoft/tsdoc-config": "~0.15.2", - "@rushstack/node-core-library": "3.36.2", + "@rushstack/node-core-library": "3.37.0", "@rushstack/rig-package": "0.2.12", "@rushstack/ts-command-line": "4.7.10", "colors": "~1.2.1", @@ -149,26 +150,26 @@ "resolve": "~1.17.0", "semver": "~7.3.0", "source-map": "~0.6.1", - "typescript": "~4.1.3" + "typescript": "~4.2.4" }, "bin": { "api-extractor": "bin/api-extractor" } }, "node_modules/@microsoft/api-extractor-model": { - "version": "7.13.0", - "resolved": "https://registry.npmjs.org/@microsoft/api-extractor-model/-/api-extractor-model-7.13.0.tgz", - "integrity": "sha512-HnIbXpNiF/a+tTnGVJFq4aaxWEGI5XN7vpm1YjNLc+CY5C0s/bdT0LV9o9NzWSpQdHVUaYhQEVLviaDpusu6dg==", + "version": "7.13.1", + "resolved": "https://registry.npmjs.org/@microsoft/api-extractor-model/-/api-extractor-model-7.13.1.tgz", + "integrity": "sha512-PKAjDmAJ6X07tvqCHSN1PRaKq8bZQXF9QI6WGEMnCHNFWwXUoITOAcvFW0Ol3TzwHO5rLbuy/CqWebfhv8eOtw==", "dependencies": { "@microsoft/tsdoc": "0.13.2", "@microsoft/tsdoc-config": "~0.15.2", - "@rushstack/node-core-library": "3.36.2" + "@rushstack/node-core-library": "3.37.0" } }, "node_modules/@microsoft/api-extractor/node_modules/typescript": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.1.5.tgz", - "integrity": "sha512-6OSu9PTIzmn9TCDiovULTnET6BgXtDYL4Gg4szY+cGsc3JP1dQL8qvE8kShTRx1NIw4Q9IBHlwODjkjWEtMUyA==", + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.2.4.tgz", + "integrity": "sha512-V+evlYHZnQkaz8TRBuxTA92yZBPotr5H+WhQ7bD3hZUndx5tGOa1fuCgeSjxAzM1RiN5IzvadIXTVefuuwZCRg==", "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -348,7 +349,7 @@ "node_modules/@rush-temp/applicationinsights-analytics-js": { "version": "0.0.0", "resolved": "file:projects/applicationinsights-analytics-js.tgz", - "integrity": "sha512-Y4Kn7QLNC0STOGbfSuU4Nf1Rpt4duAXbdLSiBlbXJ74UO3qA9ONaUNiigpjhmZ+pUPUCPbX4jslHRUO5ME06FQ==", + "integrity": "sha512-2hQXSaKcP3wDCsD3ki0l8myvsjdqSBX7+CCh7Wr5D9KNJmVbIioPt5Q0zXCmua1hxhHWoBNCGoPJDV/eM76xzw==", "dependencies": { "@microsoft/api-extractor": "^7.9.11", "@microsoft/dynamicproto-js": "^1.1.2", @@ -360,6 +361,7 @@ "grunt-contrib-qunit": "^3.1.0", "grunt-run": "^0.8.1", "grunt-ts": "^6.0.0-beta.22", + "http-server": "0.12.3", "magic-string": "^0.25.7", "qunit": "^2.9.1", "rollup": "^2.32.0", @@ -668,9 +670,9 @@ } }, "node_modules/@rushstack/node-core-library": { - "version": "3.36.2", - "resolved": "https://registry.npmjs.org/@rushstack/node-core-library/-/node-core-library-3.36.2.tgz", - "integrity": "sha512-5J8xSY/PuCKR+yfxS497l0PP43kBUeD86S4eS3RzrmMle04J4522MWal8mk1T1EIDpYpgi8qScannU9oVxoStA==", + "version": "3.37.0", + "resolved": "https://registry.npmjs.org/@rushstack/node-core-library/-/node-core-library-3.37.0.tgz", + "integrity": "sha512-b0OGvl20zfepytLBnKsOtemtiadNZAVolXxaSYssV9VjXaLPF97oLvtLfwc58BX05ufIsrKZgXatnRo8YeffNg==", "dependencies": { "@types/node": "10.17.13", "colors": "~1.2.1", @@ -1163,6 +1165,14 @@ "node": ">=0.10.0" } }, + "node_modules/basic-auth": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-1.1.0.tgz", + "integrity": "sha1-RSIe5Cn37h5QNb4/UVM/HN/SmIQ=", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/bcrypt-pbkdf": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", @@ -1457,6 +1467,14 @@ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" }, + "node_modules/corser": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/corser/-/corser-2.0.1.tgz", + "integrity": "sha1-jtolLsqrWEDc2XXOuQ2TcMgZ/4c=", + "engines": { + "node": ">= 0.4.0" + } + }, "node_modules/csproj2ts": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/csproj2ts/-/csproj2ts-1.1.0.tgz", @@ -1674,6 +1692,20 @@ "safer-buffer": "^2.1.0" } }, + "node_modules/ecstatic": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/ecstatic/-/ecstatic-3.3.2.tgz", + "integrity": "sha512-fLf9l1hnwrHI2xn9mEDT7KIi22UDqA2jaCwyCbSUJh9a1V+LEUSL/JO/6TIz/QyuBURWUHrFL5Kg2TtO1bkkog==", + "dependencies": { + "he": "^1.1.1", + "mime": "^1.6.0", + "minimist": "^1.1.0", + "url-join": "^2.0.5" + }, + "bin": { + "ecstatic": "lib/ecstatic.js" + } + }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -1756,6 +1788,11 @@ "resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-0.4.14.tgz", "integrity": "sha1-j2G3XN4BKy6esoTUVFWDtWQ7Yas=" }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==" + }, "node_modules/exit": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", @@ -2018,6 +2055,25 @@ "node": ">= 0.10" } }, + "node_modules/follow-redirects": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.0.tgz", + "integrity": "sha512-0vRwd7RKQBTt+mgu87mtYeofLFZpTas2S9zY+jIeuLJMNvudIgF52nr19q40HOwH5RrhWIPuj9puybzSJiRrVg==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, "node_modules/for-in": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", @@ -2143,9 +2199,9 @@ } }, "node_modules/glob": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", - "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "version": "7.1.7", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz", + "integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==", "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -2585,6 +2641,14 @@ "node": ">=0.10.0" } }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "bin": { + "he": "bin/he" + } + }, "node_modules/homedir-polyfill": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz", @@ -2619,6 +2683,51 @@ "node": ">= 0.6" } }, + "node_modules/http-proxy": { + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz", + "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==", + "dependencies": { + "eventemitter3": "^4.0.0", + "follow-redirects": "^1.0.0", + "requires-port": "^1.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/http-server": { + "version": "0.12.3", + "resolved": "https://registry.npmjs.org/http-server/-/http-server-0.12.3.tgz", + "integrity": "sha512-be0dKG6pni92bRjq0kvExtj/NrrAd28/8fCXkaI/4piTwQMSDSLMhWyW0NI1V+DBI3aa1HMlQu46/HjVLfmugA==", + "dependencies": { + "basic-auth": "^1.0.3", + "colors": "^1.4.0", + "corser": "^2.0.1", + "ecstatic": "^3.3.2", + "http-proxy": "^1.18.0", + "minimist": "^1.2.5", + "opener": "^1.5.1", + "portfinder": "^1.0.25", + "secure-compare": "3.0.1", + "union": "~0.5.0" + }, + "bin": { + "hs": "bin/http-server", + "http-server": "bin/http-server" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/http-server/node_modules/colors": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", + "engines": { + "node": ">=0.1.90" + } + }, "node_modules/http-signature": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", @@ -2757,9 +2866,9 @@ "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==" }, "node_modules/is-core-module": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.2.0.tgz", - "integrity": "sha512-XRAfAdyyY5F5cOXn7hYQDqh2Xmii+DEfIcQGxK/uNwMHhIkPWO0g8msXcbzLe+MpGoR951MlqM/2iIlU4vKDdQ==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.3.0.tgz", + "integrity": "sha512-xSphU2KG9867tsYdLD4RWQ1VqdFl4HTO9Thf3I/3dLEfr0dbPTWKsuCKrgqMljg4nPE+Gq0VCnzT3gr0CyBmsw==", "dependencies": { "has": "^1.0.3" }, @@ -3282,14 +3391,14 @@ } }, "node_modules/mime": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/mime/-/mime-2.5.2.tgz", - "integrity": "sha512-tqkh47FzKeCPD2PUiPB6pkbMzsCasjxAfC62/Wap5qrUWcb+sFasXUC5I3gYM5iBM8v/Qpn4UK0x+j0iHyFPDg==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", "bin": { "mime": "cli.js" }, "engines": { - "node": ">=4.0.0" + "node": ">=4" } }, "node_modules/mime-db": { @@ -3625,6 +3734,14 @@ "wrappy": "1" } }, + "node_modules/opener": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/opener/-/opener-1.5.2.tgz", + "integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==", + "bin": { + "opener": "bin/opener-bin.js" + } + }, "node_modules/os-homedir": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", @@ -3833,6 +3950,40 @@ "node": ">=0.10.0" } }, + "node_modules/portfinder": { + "version": "1.0.28", + "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.28.tgz", + "integrity": "sha512-Se+2isanIcEqf2XMHjyUKskczxbPH7dQnlMjXX6+dybayyHvAf/TCgyMRlzf/B6QDhAEFOGes0pzRo3by4AbMA==", + "dependencies": { + "async": "^2.6.2", + "debug": "^3.1.1", + "mkdirp": "^0.5.5" + }, + "engines": { + "node": ">= 0.12.0" + } + }, + "node_modules/portfinder/node_modules/async": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.3.tgz", + "integrity": "sha512-zflvls11DCy+dQWzTW2dzuilv8Z5X/pjfmZOWba6TNIVDm+2UDaJmXSOXlasHKfNBs8oo3M0aT50fDEWfKZjXg==", + "dependencies": { + "lodash": "^4.17.14" + } + }, + "node_modules/portfinder/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/portfinder/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, "node_modules/posix-character-classes": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", @@ -3907,6 +4058,17 @@ } } }, + "node_modules/puppeteer/node_modules/mime": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.5.2.tgz", + "integrity": "sha512-tqkh47FzKeCPD2PUiPB6pkbMzsCasjxAfC62/Wap5qrUWcb+sFasXUC5I3gYM5iBM8v/Qpn4UK0x+j0iHyFPDg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4.0.0" + } + }, "node_modules/puppeteer/node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", @@ -4201,6 +4363,11 @@ "node": ">= 6" } }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=" + }, "node_modules/resolve": { "version": "1.17.0", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz", @@ -4259,9 +4426,9 @@ } }, "node_modules/rollup": { - "version": "2.45.2", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.45.2.tgz", - "integrity": "sha512-kRRU7wXzFHUzBIv0GfoFFIN3m9oteY4uAsKllIpQDId5cfnkWF2J130l+27dzDju0E6MScKiV0ZM5Bw8m4blYQ==", + "version": "2.47.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.47.0.tgz", + "integrity": "sha512-rqBjgq9hQfW0vRmz+0S062ORRNJXvwRpzxhFXORvar/maZqY6za3rgQ/p1Glg+j1hnc1GtYyQCPiAei95uTElg==", "bin": { "rollup": "dist/bin/rollup" }, @@ -4366,6 +4533,11 @@ "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" }, + "node_modules/secure-compare": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/secure-compare/-/secure-compare-3.0.1.tgz", + "integrity": "sha1-8aAymzCLIh+uN7mXTz1XjQypmeM=" + }, "node_modules/selenium-server-standalone-jar": { "version": "3.141.59", "resolved": "https://registry.npmjs.org/selenium-server-standalone-jar/-/selenium-server-standalone-jar-3.141.59.tgz", @@ -4408,17 +4580,6 @@ "node": ">= 0.8.0" } }, - "node_modules/send/node_modules/mime": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", - "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/send/node_modules/ms": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", @@ -5209,9 +5370,9 @@ "integrity": "sha512-MVuS359B+YzaWqjCL/c+22gfryv+mCBPHAv3zyVI2GN8EY6IRP8VwtasXn8jyyhvvq84R4ImN1OKRtcbIasjYA==" }, "node_modules/uglify-js": { - "version": "3.13.4", - "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.13.4.tgz", - "integrity": "sha512-kv7fCkIXyQIilD5/yQy8O+uagsYIOt5cZvs890W40/e/rvjMSzJw81o9Bg0tkURxzZBROtDQhW2LFjOGoK3RZw==", + "version": "3.13.5", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.13.5.tgz", + "integrity": "sha512-xtB8yEqIkn7zmOyS2zUNBsYCBRhDkvlNxMMY2smuJ/qA8NCHeQvKCF3i9Z4k8FJH4+PJvZRtMrPynfZ75+CSZw==", "bin": { "uglifyjs": "bin/uglifyjs" }, @@ -5239,6 +5400,17 @@ "node": "*" } }, + "node_modules/union": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/union/-/union-0.5.0.tgz", + "integrity": "sha512-N6uOhuW6zO95P3Mel2I2zMsbsanvvtgn6jVqJv4vbVcz/JN0OkL9suomjQGmWtxJQXOCqUJvquc1sMeNz/IwlA==", + "dependencies": { + "qs": "^6.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/union-value": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.1.tgz", @@ -5336,6 +5508,11 @@ "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=", "deprecated": "Please see https://github.com/lydell/urix#deprecated" }, + "node_modules/url-join": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/url-join/-/url-join-2.0.5.tgz", + "integrity": "sha1-WvIvGMBSoACkjXuCxenC4v7tpyg=" + }, "node_modules/use": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", @@ -5483,16 +5660,16 @@ } }, "@babel/helper-validator-identifier": { - "version": "7.12.11", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.12.11.tgz", - "integrity": "sha512-np/lG3uARFybkoHokJUmf1QfEvRVCPbmQeUQpKow5cQ3xWrV9i3rUHodKDJPQfTVX61qKi+UdYk8kik84n7XOw==" + "version": "7.14.0", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.0.tgz", + "integrity": "sha512-V3ts7zMSu5lfiwWDVWzRDGIN+lnCEUdaXgtVHJgLb1rGaA6jMrtB9EmE7L18foXJIE8Un/A/h6NJfGQp/e1J4A==" }, "@babel/highlight": { - "version": "7.13.10", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.13.10.tgz", - "integrity": "sha512-5aPpe5XQPzflQrFwL1/QoeHkP2MsA4JCntcXHRhEsdsfPVkvPi2w7Qix4iV7t5S/oC9OodGrggd8aco1g3SZFg==", + "version": "7.14.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.14.0.tgz", + "integrity": "sha512-YSCOwxvTYEIMSGaBQb5kDDsCopDdiUGsqpatp3fOlI4+2HQSkTmEVWnVuySdAC5EWCqSWWTv0ib63RjR7dTBdg==", "requires": { - "@babel/helper-validator-identifier": "^7.12.11", + "@babel/helper-validator-identifier": "^7.14.0", "chalk": "^2.0.0", "js-tokens": "^4.0.0" }, @@ -5544,14 +5721,14 @@ } }, "@microsoft/api-extractor": { - "version": "7.14.0", - "resolved": "https://registry.npmjs.org/@microsoft/api-extractor/-/api-extractor-7.14.0.tgz", - "integrity": "sha512-R9B0ic8EIcHhwSFQWYTyQX7QDi7kXONeKdIjJI8R+WzVJMA3r0Je9XxSQxxZ9MZIBUxv3fB7pXC2CPIsSkI/BA==", + "version": "7.15.1", + "resolved": "https://registry.npmjs.org/@microsoft/api-extractor/-/api-extractor-7.15.1.tgz", + "integrity": "sha512-PYbGAvxbM5B6HbafXY7tJ4ObYpeUZrZFt9vlN68tpYG/7aeldMLAZSjTyB30VFXaGlArjeEooKZIcs2ZnVAbNg==", "requires": { - "@microsoft/api-extractor-model": "7.13.0", + "@microsoft/api-extractor-model": "7.13.1", "@microsoft/tsdoc": "0.13.2", "@microsoft/tsdoc-config": "~0.15.2", - "@rushstack/node-core-library": "3.36.2", + "@rushstack/node-core-library": "3.37.0", "@rushstack/rig-package": "0.2.12", "@rushstack/ts-command-line": "4.7.10", "colors": "~1.2.1", @@ -5559,24 +5736,24 @@ "resolve": "~1.17.0", "semver": "~7.3.0", "source-map": "~0.6.1", - "typescript": "~4.1.3" + "typescript": "~4.2.4" }, "dependencies": { "typescript": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.1.5.tgz", - "integrity": "sha512-6OSu9PTIzmn9TCDiovULTnET6BgXtDYL4Gg4szY+cGsc3JP1dQL8qvE8kShTRx1NIw4Q9IBHlwODjkjWEtMUyA==" + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.2.4.tgz", + "integrity": "sha512-V+evlYHZnQkaz8TRBuxTA92yZBPotr5H+WhQ7bD3hZUndx5tGOa1fuCgeSjxAzM1RiN5IzvadIXTVefuuwZCRg==" } } }, "@microsoft/api-extractor-model": { - "version": "7.13.0", - "resolved": "https://registry.npmjs.org/@microsoft/api-extractor-model/-/api-extractor-model-7.13.0.tgz", - "integrity": "sha512-HnIbXpNiF/a+tTnGVJFq4aaxWEGI5XN7vpm1YjNLc+CY5C0s/bdT0LV9o9NzWSpQdHVUaYhQEVLviaDpusu6dg==", + "version": "7.13.1", + "resolved": "https://registry.npmjs.org/@microsoft/api-extractor-model/-/api-extractor-model-7.13.1.tgz", + "integrity": "sha512-PKAjDmAJ6X07tvqCHSN1PRaKq8bZQXF9QI6WGEMnCHNFWwXUoITOAcvFW0Ol3TzwHO5rLbuy/CqWebfhv8eOtw==", "requires": { "@microsoft/tsdoc": "0.13.2", "@microsoft/tsdoc-config": "~0.15.2", - "@rushstack/node-core-library": "3.36.2" + "@rushstack/node-core-library": "3.37.0" } }, "@microsoft/dynamicproto-js": { @@ -5719,7 +5896,7 @@ }, "@rush-temp/applicationinsights-analytics-js": { "version": "file:projects\\applicationinsights-analytics-js.tgz", - "integrity": "sha512-Y4Kn7QLNC0STOGbfSuU4Nf1Rpt4duAXbdLSiBlbXJ74UO3qA9ONaUNiigpjhmZ+pUPUCPbX4jslHRUO5ME06FQ==", + "integrity": "sha512-2hQXSaKcP3wDCsD3ki0l8myvsjdqSBX7+CCh7Wr5D9KNJmVbIioPt5Q0zXCmua1hxhHWoBNCGoPJDV/eM76xzw==", "requires": { "@microsoft/api-extractor": "^7.9.11", "@microsoft/dynamicproto-js": "^1.1.2", @@ -5731,6 +5908,7 @@ "grunt-contrib-qunit": "^3.1.0", "grunt-run": "^0.8.1", "grunt-ts": "^6.0.0-beta.22", + "http-server": "0.12.3", "magic-string": "^0.25.7", "qunit": "^2.9.1", "rollup": "^2.32.0", @@ -6027,9 +6205,9 @@ } }, "@rushstack/node-core-library": { - "version": "3.36.2", - "resolved": "https://registry.npmjs.org/@rushstack/node-core-library/-/node-core-library-3.36.2.tgz", - "integrity": "sha512-5J8xSY/PuCKR+yfxS497l0PP43kBUeD86S4eS3RzrmMle04J4522MWal8mk1T1EIDpYpgi8qScannU9oVxoStA==", + "version": "3.37.0", + "resolved": "https://registry.npmjs.org/@rushstack/node-core-library/-/node-core-library-3.37.0.tgz", + "integrity": "sha512-b0OGvl20zfepytLBnKsOtemtiadNZAVolXxaSYssV9VjXaLPF97oLvtLfwc58BX05ufIsrKZgXatnRo8YeffNg==", "requires": { "@types/node": "10.17.13", "colors": "~1.2.1", @@ -6426,6 +6604,11 @@ } } }, + "basic-auth": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-1.1.0.tgz", + "integrity": "sha1-RSIe5Cn37h5QNb4/UVM/HN/SmIQ=" + }, "bcrypt-pbkdf": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", @@ -6663,6 +6846,11 @@ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" }, + "corser": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/corser/-/corser-2.0.1.tgz", + "integrity": "sha1-jtolLsqrWEDc2XXOuQ2TcMgZ/4c=" + }, "csproj2ts": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/csproj2ts/-/csproj2ts-1.1.0.tgz", @@ -6832,6 +7020,17 @@ "safer-buffer": "^2.1.0" } }, + "ecstatic": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/ecstatic/-/ecstatic-3.3.2.tgz", + "integrity": "sha512-fLf9l1hnwrHI2xn9mEDT7KIi22UDqA2jaCwyCbSUJh9a1V+LEUSL/JO/6TIz/QyuBURWUHrFL5Kg2TtO1bkkog==", + "requires": { + "he": "^1.1.1", + "mime": "^1.6.0", + "minimist": "^1.1.0", + "url-join": "^2.0.5" + } + }, "ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -6897,6 +7096,11 @@ "resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-0.4.14.tgz", "integrity": "sha1-j2G3XN4BKy6esoTUVFWDtWQ7Yas=" }, + "eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==" + }, "exit": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", @@ -7107,6 +7311,11 @@ "resolved": "https://registry.npmjs.org/flagged-respawn/-/flagged-respawn-1.0.1.tgz", "integrity": "sha512-lNaHNVymajmk0OJMBn8fVUAU1BtDeKIqKoVhk4xAALB57aALg6b4W0MfJ/cUE0g9YBXy5XhSlPIpYIJ7HaY/3Q==" }, + "follow-redirects": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.0.tgz", + "integrity": "sha512-0vRwd7RKQBTt+mgu87mtYeofLFZpTas2S9zY+jIeuLJMNvudIgF52nr19q40HOwH5RrhWIPuj9puybzSJiRrVg==" + }, "for-in": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", @@ -7197,9 +7406,9 @@ } }, "glob": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", - "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "version": "7.1.7", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz", + "integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==", "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -7530,6 +7739,11 @@ } } }, + "he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==" + }, "homedir-polyfill": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz", @@ -7555,6 +7769,40 @@ "toidentifier": "1.0.0" } }, + "http-proxy": { + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz", + "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==", + "requires": { + "eventemitter3": "^4.0.0", + "follow-redirects": "^1.0.0", + "requires-port": "^1.0.0" + } + }, + "http-server": { + "version": "0.12.3", + "resolved": "https://registry.npmjs.org/http-server/-/http-server-0.12.3.tgz", + "integrity": "sha512-be0dKG6pni92bRjq0kvExtj/NrrAd28/8fCXkaI/4piTwQMSDSLMhWyW0NI1V+DBI3aa1HMlQu46/HjVLfmugA==", + "requires": { + "basic-auth": "^1.0.3", + "colors": "^1.4.0", + "corser": "^2.0.1", + "ecstatic": "^3.3.2", + "http-proxy": "^1.18.0", + "minimist": "^1.2.5", + "opener": "^1.5.1", + "portfinder": "^1.0.25", + "secure-compare": "3.0.1", + "union": "~0.5.0" + }, + "dependencies": { + "colors": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==" + } + } + }, "http-signature": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", @@ -7667,9 +7915,9 @@ "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==" }, "is-core-module": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.2.0.tgz", - "integrity": "sha512-XRAfAdyyY5F5cOXn7hYQDqh2Xmii+DEfIcQGxK/uNwMHhIkPWO0g8msXcbzLe+MpGoR951MlqM/2iIlU4vKDdQ==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.3.0.tgz", + "integrity": "sha512-xSphU2KG9867tsYdLD4RWQ1VqdFl4HTO9Thf3I/3dLEfr0dbPTWKsuCKrgqMljg4nPE+Gq0VCnzT3gr0CyBmsw==", "requires": { "has": "^1.0.3" } @@ -8083,9 +8331,9 @@ } }, "mime": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/mime/-/mime-2.5.2.tgz", - "integrity": "sha512-tqkh47FzKeCPD2PUiPB6pkbMzsCasjxAfC62/Wap5qrUWcb+sFasXUC5I3gYM5iBM8v/Qpn4UK0x+j0iHyFPDg==" + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==" }, "mime-db": { "version": "1.47.0", @@ -8345,6 +8593,11 @@ "wrappy": "1" } }, + "opener": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/opener/-/opener-1.5.2.tgz", + "integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==" + }, "os-homedir": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", @@ -8498,6 +8751,39 @@ "pinkie": "^2.0.0" } }, + "portfinder": { + "version": "1.0.28", + "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.28.tgz", + "integrity": "sha512-Se+2isanIcEqf2XMHjyUKskczxbPH7dQnlMjXX6+dybayyHvAf/TCgyMRlzf/B6QDhAEFOGes0pzRo3by4AbMA==", + "requires": { + "async": "^2.6.2", + "debug": "^3.1.1", + "mkdirp": "^0.5.5" + }, + "dependencies": { + "async": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.3.tgz", + "integrity": "sha512-zflvls11DCy+dQWzTW2dzuilv8Z5X/pjfmZOWba6TNIVDm+2UDaJmXSOXlasHKfNBs8oo3M0aT50fDEWfKZjXg==", + "requires": { + "lodash": "^4.17.14" + } + }, + "debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + } + } + }, "posix-character-classes": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", @@ -8551,6 +8837,11 @@ "ms": "2.1.2" } }, + "mime": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.5.2.tgz", + "integrity": "sha512-tqkh47FzKeCPD2PUiPB6pkbMzsCasjxAfC62/Wap5qrUWcb+sFasXUC5I3gYM5iBM8v/Qpn4UK0x+j0iHyFPDg==" + }, "ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", @@ -8773,6 +9064,11 @@ "uuid": "^3.3.2" } }, + "requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=" + }, "resolve": { "version": "1.17.0", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz", @@ -8814,9 +9110,9 @@ } }, "rollup": { - "version": "2.45.2", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.45.2.tgz", - "integrity": "sha512-kRRU7wXzFHUzBIv0GfoFFIN3m9oteY4uAsKllIpQDId5cfnkWF2J130l+27dzDju0E6MScKiV0ZM5Bw8m4blYQ==", + "version": "2.47.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.47.0.tgz", + "integrity": "sha512-rqBjgq9hQfW0vRmz+0S062ORRNJXvwRpzxhFXORvar/maZqY6za3rgQ/p1Glg+j1hnc1GtYyQCPiAei95uTElg==", "requires": { "fsevents": "~2.3.1" }, @@ -8892,6 +9188,11 @@ "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" }, + "secure-compare": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/secure-compare/-/secure-compare-3.0.1.tgz", + "integrity": "sha1-8aAymzCLIh+uN7mXTz1XjQypmeM=" + }, "selenium-server-standalone-jar": { "version": "3.141.59", "resolved": "https://registry.npmjs.org/selenium-server-standalone-jar/-/selenium-server-standalone-jar-3.141.59.tgz", @@ -8925,11 +9226,6 @@ "statuses": "~1.5.0" }, "dependencies": { - "mime": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", - "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==" - }, "ms": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", @@ -9540,9 +9836,9 @@ } }, "uglify-js": { - "version": "3.13.4", - "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.13.4.tgz", - "integrity": "sha512-kv7fCkIXyQIilD5/yQy8O+uagsYIOt5cZvs890W40/e/rvjMSzJw81o9Bg0tkURxzZBROtDQhW2LFjOGoK3RZw==" + "version": "3.13.5", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.13.5.tgz", + "integrity": "sha512-xtB8yEqIkn7zmOyS2zUNBsYCBRhDkvlNxMMY2smuJ/qA8NCHeQvKCF3i9Z4k8FJH4+PJvZRtMrPynfZ75+CSZw==" }, "unc-path-regex": { "version": "0.1.2", @@ -9558,6 +9854,14 @@ "util-deprecate": "^1.0.2" } }, + "union": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/union/-/union-0.5.0.tgz", + "integrity": "sha512-N6uOhuW6zO95P3Mel2I2zMsbsanvvtgn6jVqJv4vbVcz/JN0OkL9suomjQGmWtxJQXOCqUJvquc1sMeNz/IwlA==", + "requires": { + "qs": "^6.4.0" + } + }, "union-value": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.1.tgz", @@ -9633,6 +9937,11 @@ "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=" }, + "url-join": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/url-join/-/url-join-2.0.5.tgz", + "integrity": "sha1-WvIvGMBSoACkjXuCxenC4v7tpyg=" + }, "use": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", diff --git a/extensions/applicationinsights-analytics-js/Tests/ApplicationInsights.tests.ts b/extensions/applicationinsights-analytics-js/Tests/ApplicationInsights.tests.ts index 1811cdfe..3fbe2abf 100644 --- a/extensions/applicationinsights-analytics-js/Tests/ApplicationInsights.tests.ts +++ b/extensions/applicationinsights-analytics-js/Tests/ApplicationInsights.tests.ts @@ -1,15 +1,37 @@ -import { Assert, AITestClass } from "@microsoft/ai-test-framework"; -import { SinonStub } from 'sinon'; -import { Util, Exception, SeverityLevel, Trace, PageViewPerformance, IConfig, IExceptionInternal, AnalyticsPluginIdentifier } from "@microsoft/applicationinsights-common"; +import { + Assert, AITestClass, PollingAssert, EventValidator, TraceValidator, ExceptionValidator, + MetricValidator, PageViewPerformanceValidator, PageViewValidator, RemoteDepdencyValidator +} from "@microsoft/ai-test-framework"; +import { SinonStub, SinonSpy } from 'sinon'; +import { + Exception, SeverityLevel, Event, Trace, PageViewPerformance, IConfig, IExceptionInternal, + AnalyticsPluginIdentifier, Util, IAppInsights, Metric, PageView, RemoteDependencyData +} from "@microsoft/applicationinsights-common"; import { ITelemetryItem, AppInsightsCore, IPlugin, IConfiguration, IAppInsightsCore, setEnableEnvMocks, getLocation, dumpObj } from "@microsoft/applicationinsights-core-js"; +import { Sender } from "@microsoft/applicationinsights-channel-js" import { PropertiesPlugin } from "@microsoft/applicationinsights-properties-js"; import { ApplicationInsights } from "../src/JavaScriptSDK/ApplicationInsights"; +declare class ExceptionHelper { + capture: (appInsights:IAppInsights) => void; + captureStrict: (appInsights:IAppInsights) => void; + throw: (value:any) => void; + throwCors: () => void; + throwStrict: (value:any) => void; + throwRuntimeException: (timeoutFunc: VoidFunction) => void; + throwStrictRuntimeException: (timeoutFunc: VoidFunction) => void; +}; + export class ApplicationInsightsTests extends AITestClass { + private _onerror:any = null; + private trackSpy:SinonSpy; + private throwInternalSpy:SinonSpy; + private exceptionHelper: any = new ExceptionHelper(); + public testInitialize() { + this._onerror = window.onerror; setEnableEnvMocks(false); super.testInitialize(); - Util.setCookie(undefined, 'ai_session', ""); Util.setCookie(undefined, 'ai_user', ""); if (Util.canUseLocalStorage()) { @@ -24,6 +46,13 @@ export class ApplicationInsightsTests extends AITestClass { if (Util.canUseLocalStorage()) { window.localStorage.clear(); } + window.onerror = this._onerror; + } + + public causeException(cb:Function) { + AITestClass.orgSetTimeout(() => { + cb(); + }, 0); } public registerTests() { @@ -323,7 +352,7 @@ export class ApplicationInsightsTests extends AITestClass { const appInsights = new ApplicationInsights(); appInsights.initialize({instrumentationKey: core.config.instrumentationKey}, core, []); const trackStub = this.sandbox.stub(appInsights.core, "track"); - + let envelope: ITelemetryItem; const test = (action, expectedEnvelopeType, expectedDataType, test?: () => void) => { action(); @@ -497,13 +526,10 @@ export class ApplicationInsightsTests extends AITestClass { appInsights.initialize({ instrumentationKey: "key" }, core, []); const throwInternal = this.sandbox.spy(appInsights.core.logger, "throwInternal"); - const nameStub = this.sandbox.stub(Util, "getExceptionName"); this.sandbox.stub(appInsights, "trackException").throws(new CustomTestError("Simulated Error")); const expectedErrorName: string = "CustomTestError"; - nameStub.returns(expectedErrorName); - appInsights._onerror({message: "some message", url: "some://url", lineNumber: 1234, columnNumber: 5678, error: new Error()}); Assert.ok(throwInternal.calledOnce, "throwInternal called once"); @@ -557,6 +583,350 @@ export class ApplicationInsightsTests extends AITestClass { Assert.equal(document.URL, trackExceptionSpy.args[0][1].url); } }); + + this.testCase({ + name: "OnErrorTests: _onerror logs name of unexpected error thrown by trackException for diagnostics", + test: () => { + // setup + const plugin = new ChannelPlugin(); + const core = new AppInsightsCore(); + core.initialize( + {instrumentationKey: "key"}, + [plugin] + ); + const appInsights = new ApplicationInsights(); + appInsights.initialize({ instrumentationKey: "key" }, core, []); + + const throwInternal = this.sandbox.spy(appInsights.core.logger, "throwInternal"); + + // Internal code does call this anymore! + const expectedErrorName: string = "test error"; + + let theError = new Error(); + theError.name = expectedErrorName; + this.sandbox.stub(appInsights, "trackException").throws(theError); + + + appInsights._onerror({message: "some message", url: "some://url", lineNumber: 1234, columnNumber: 5678, error: "the error message"}); + + Assert.ok(throwInternal.calledOnce, "throwInternal called once"); + const logMessage: string = throwInternal.getCall(0).args[2]; + Assert.notEqual(-1, logMessage.indexOf(expectedErrorName), "logMessage: " + logMessage); + } + }); + + + this.testCaseAsync({ + name: "OnErrorTests: _onerror logs name of unexpected error thrown by trackException for diagnostics", + stepDelay: 1, + useFakeTimers: true, + steps: [() => { + // setup + const sender: Sender = new Sender(); + const core = new AppInsightsCore(); + core.initialize( + { + instrumentationKey: "key", + extensionConfig: { + [sender.identifier]: { + enableSessionStorageBuffer: false, + maxBatchInterval: 1 + } + } + }, + [sender] + ); + const appInsights = new ApplicationInsights(); + appInsights.initialize({ instrumentationKey: "key" }, core, []); + appInsights.addTelemetryInitializer((item: ITelemetryItem) => { + Assert.equal("4.0", item.ver, "Telemetry items inside telemetry initializers should be in CS4.0 format"); + }); + + this.throwInternalSpy = this.sandbox.spy(appInsights.core.logger, "throwInternal"); + sender._sender = (payload:string[], isAsync:boolean) => { + sender._onSuccess(payload, payload.length); + }; + this.sandbox.spy() + this.trackSpy = this.sandbox.spy(sender, "_onSuccess"); + + this.exceptionHelper.capture(appInsights); + + this.causeException(() => { + this.exceptionHelper.throwRuntimeException(AITestClass.orgSetTimeout); + }); + + Assert.ok(!this.trackSpy.calledOnce, "track not called yet"); + Assert.ok(!this.throwInternalSpy.called, "No internal errors"); + }].concat(this.waitForException(1)) + .concat(() => { + + let isLocal = window.location.protocol === "file:"; + let exp = this.trackSpy.args[0]; + const payloadStr: string[] = this.getPayloadMessages(this.trackSpy); + if (payloadStr.length > 0) { + const payload = JSON.parse(payloadStr[0]); + const data = payload.data; + Assert.ok(data, "Has Data"); + if (data) { + Assert.ok(data.baseData, "Has BaseData"); + let baseData = data.baseData; + if (baseData) { + const ex = baseData.exceptions[0]; + if (isLocal) { + Assert.ok(ex.message.indexOf("Script error:") !== -1, "Make sure the error message is present [" + ex.message + "]"); + Assert.equal("String", ex.typeName, "Got the correct typename [" + ex.typeName + "]"); + } else { + Assert.ok(ex.message.indexOf("ug is not a function") !== -1, "Make sure the error message is present [" + ex.message + "]"); + Assert.equal("TypeError", ex.typeName, "Got the correct typename [" + ex.typeName + "]"); + Assert.ok(baseData.properties["columnNumber"], "has column number"); + Assert.ok(baseData.properties["lineNumber"], "has Line number"); + } + + Assert.ok(ex.stack.length > 0, "Has stack"); + Assert.ok(ex.parsedStack, "Stack was parsed"); + Assert.ok(ex.hasFullStack, "Stack has been decoded"); + Assert.ok(baseData.properties["url"], "has Url"); + Assert.ok(baseData.properties["errorSrc"].indexOf("window.onerror@") !== -1, "has source"); + } + } + } + }) + + }); + + this.testCaseAsync({ + name: "OnErrorTests: _onerror logs name of unexpected error thrown by trackException for diagnostics with a text exception", + stepDelay: 1, + useFakeTimers: true, + steps: [() => { + // setup + const sender: Sender = new Sender(); + const core = new AppInsightsCore(); + core.initialize( + { + instrumentationKey: "key", + extensionConfig: { + [sender.identifier]: { + enableSessionStorageBuffer: false, + maxBatchInterval: 1 + } + } + }, + [sender] + ); + const appInsights = new ApplicationInsights(); + appInsights.initialize({ instrumentationKey: "key" }, core, []); + appInsights.addTelemetryInitializer((item: ITelemetryItem) => { + Assert.equal("4.0", item.ver, "Telemetry items inside telemetry initializers should be in CS4.0 format"); + }); + + this.throwInternalSpy = this.sandbox.spy(appInsights.core.logger, "throwInternal"); + sender._sender = (payload:string[], isAsync:boolean) => { + sender._onSuccess(payload, payload.length); + }; + this.sandbox.spy() + this.trackSpy = this.sandbox.spy(sender, "_onSuccess"); + + this.exceptionHelper.capture(appInsights); + this.causeException(() => { + this.exceptionHelper.throw("Test Text Error!"); + }); + + Assert.ok(!this.trackSpy.calledOnce, "track not called yet"); + Assert.ok(!this.throwInternalSpy.called, "No internal errors"); + }].concat(this.waitForException(1)) + .concat(() => { + + let exp = this.trackSpy.args[0]; + const payloadStr: string[] = this.getPayloadMessages(this.trackSpy); + if (payloadStr.length > 0) { + const payload = JSON.parse(payloadStr[0]); + const data = payload.data; + Assert.ok(data, "Has Data"); + if (data) { + Assert.ok(data.baseData, "Has BaseData"); + let baseData = data.baseData; + if (baseData) { + const ex = baseData.exceptions[0]; + Assert.ok(ex.message.indexOf("Test Text Error!") !== -1, "Make sure the error message is present [" + ex.message + "]"); + Assert.ok(baseData.properties["columnNumber"], "has column number"); + Assert.ok(baseData.properties["lineNumber"], "has Line number"); + Assert.equal("String", ex.typeName, "Got the correct typename"); + Assert.ok(ex.stack.length > 0, "Has stack"); + Assert.ok(ex.parsedStack, "Stack was parsed"); + Assert.ok(ex.hasFullStack, "Stack has been decoded"); + Assert.ok(baseData.properties["url"], "has Url"); + Assert.ok(baseData.properties["errorSrc"].indexOf("window.onerror@") !== -1, "has source"); + } + } + } + }) + }); + + this.testCaseAsync({ + name: "OnErrorTests: _onerror logs name of unexpected error thrown by trackException for diagnostics with a custom direct exception", + stepDelay: 1, + useFakeTimers: true, + steps: [() => { + // setup + const sender: Sender = new Sender(); + const core = new AppInsightsCore(); + core.initialize( + { + instrumentationKey: "key", + extensionConfig: { + [sender.identifier]: { + enableSessionStorageBuffer: false, + maxBatchInterval: 1 + } + } + }, + [sender] + ); + const appInsights = new ApplicationInsights(); + appInsights.initialize({ instrumentationKey: "key" }, core, []); + appInsights.addTelemetryInitializer((item: ITelemetryItem) => { + Assert.equal("4.0", item.ver, "Telemetry items inside telemetry initializers should be in CS4.0 format"); + }); + + this.throwInternalSpy = this.sandbox.spy(appInsights.core.logger, "throwInternal"); + sender._sender = (payload:string[], isAsync:boolean) => { + sender._onSuccess(payload, payload.length); + }; + this.sandbox.spy() + this.trackSpy = this.sandbox.spy(sender, "_onSuccess"); + + this.exceptionHelper.capture(appInsights); + this.causeException(() => { + this.exceptionHelper.throw(new CustomTestError("Test Text Error!")); + }); + + Assert.ok(!this.trackSpy.calledOnce, "track not called yet"); + Assert.ok(!this.throwInternalSpy.called, "No internal errors"); + }].concat(this.waitForException(1)) + .concat(() => { + + let isLocal = window.location.protocol === "file:"; + let exp = this.trackSpy.args[0]; + const payloadStr: string[] = this.getPayloadMessages(this.trackSpy); + if (payloadStr.length > 0) { + const payload = JSON.parse(payloadStr[0]); + const data = payload.data; + Assert.ok(data, "Has Data"); + if (data) { + Assert.ok(data.baseData, "Has BaseData"); + let baseData = data.baseData; + if (baseData) { + const ex = baseData.exceptions[0]; + if (isLocal) { + Assert.ok(ex.message.indexOf("Script error:") !== -1, "Make sure the error message is present [" + ex.message + "]"); + Assert.equal("String", ex.typeName, "Got the correct typename"); + } else { + Assert.ok(ex.message.indexOf("Test Text Error!") !== -1, "Make sure the error message is present [" + ex.message + "]"); + Assert.ok(ex.message.indexOf("CustomTestError") !== -1, "Make sure the error type is present [" + ex.message + "]"); + Assert.equal("CustomTestError", ex.typeName, "Got the correct typename"); + Assert.ok(baseData.properties["columnNumber"], "has column number"); + Assert.ok(baseData.properties["lineNumber"], "has Line number"); + } + + Assert.ok(ex.stack.length > 0, "Has stack"); + Assert.ok(ex.parsedStack, "Stack was parsed"); + Assert.ok(ex.hasFullStack, "Stack has been decoded"); + Assert.ok(baseData.properties["url"], "has Url"); + Assert.ok(baseData.properties["errorSrc"].indexOf("window.onerror@") !== -1, "has source"); + } + } + } + }) + }); + + this.testCaseAsync({ + name: "OnErrorTests: _onerror logs name of unexpected error thrown by trackException for diagnostics with a strict custom direct exception", + stepDelay: 1, + useFakeTimers: true, + steps: [() => { + // setup + const sender: Sender = new Sender(); + const core = new AppInsightsCore(); + core.initialize( + { + instrumentationKey: "key", + extensionConfig: { + [sender.identifier]: { + enableSessionStorageBuffer: false, + maxBatchInterval: 1 + } + } + }, + [sender] + ); + const appInsights = new ApplicationInsights(); + appInsights.initialize({ instrumentationKey: "key" }, core, []); + appInsights.addTelemetryInitializer((item: ITelemetryItem) => { + Assert.equal("4.0", item.ver, "Telemetry items inside telemetry initializers should be in CS4.0 format"); + }); + + this.throwInternalSpy = this.sandbox.spy(appInsights.core.logger, "throwInternal"); + sender._sender = (payload:string[], isAsync:boolean) => { + sender._onSuccess(payload, payload.length); + }; + this.sandbox.spy() + this.trackSpy = this.sandbox.spy(sender, "_onSuccess"); + + this.exceptionHelper.capture(appInsights); + this.causeException(() => { + this.exceptionHelper.throwStrict(new CustomTestError("Test Text Error!")); + }); + + Assert.ok(!this.trackSpy.calledOnce, "track not called yet"); + Assert.ok(!this.throwInternalSpy.called, "No internal errors"); + }].concat(this.waitForException(1)) + .concat(() => { + + let isLocal = window.location.protocol === "file:"; + let exp = this.trackSpy.args[0]; + const payloadStr: string[] = this.getPayloadMessages(this.trackSpy); + if (payloadStr.length > 0) { + const payload = JSON.parse(payloadStr[0]); + const data = payload.data; + Assert.ok(data, "Has Data"); + if (data) { + Assert.ok(data.baseData, "Has BaseData"); + let baseData = data.baseData; + if (baseData) { + const ex = baseData.exceptions[0]; + if (isLocal) { + Assert.ok(ex.message.indexOf("Script error:") !== -1, "Make sure the error message is present [" + ex.message + "]"); + Assert.equal("String", ex.typeName, "Got the correct typename"); + } else { + Assert.ok(ex.message.indexOf("Test Text Error!") !== -1, "Make sure the error message is present [" + ex.message + "]"); + Assert.ok(ex.message.indexOf("CustomTestError") !== -1, "Make sure the error type is present [" + ex.message + "]"); + Assert.equal("CustomTestError", ex.typeName, "Got the correct typename"); + Assert.ok(baseData.properties["columnNumber"], "has column number"); + Assert.ok(baseData.properties["lineNumber"], "has Line number"); + } + + Assert.ok(ex.stack.length > 0, "Has stack"); + Assert.ok(ex.parsedStack, "Stack was parsed"); + Assert.ok(ex.hasFullStack, "Stack has been decoded"); + Assert.ok(baseData.properties["url"], "has Url"); + Assert.ok(baseData.properties["errorSrc"].indexOf("window.onerror@") !== -1, "has source"); + } + } + } + }) + }); + } + + private throwStrictRuntimeException() { + "use strict"; + function doThrow() { + var ug: any = "Hello"; + // This should throw + ug(); + } + + doThrow(); } private addStartStopTrackPageTests() { @@ -1158,6 +1528,67 @@ export class ApplicationInsightsTests extends AITestClass { Assert.ok(trackStub.args && trackStub.args[index] && trackStub.args[index][0], "track was called for: " + action); return trackStub.args[index][0] as ITelemetryItem; } + + private checkNoInternalErrors() { + if (this.throwInternalSpy) { + Assert.ok(this.throwInternalSpy.notCalled, "Check no internal errors"); + if (this.throwInternalSpy.called) { + Assert.ok(false, JSON.stringify(this.throwInternalSpy.args[0])); + } + } + } + + private waitForException: any = (expectedCount:number, action: string = "", includeInit:boolean = false) => [ + () => { + const message = "polling: " + new Date().toISOString() + " " + action; + Assert.ok(true, message); + console.log(message); + this.checkNoInternalErrors(); + this.clock.tick(500); + }, + (PollingAssert.createPollingAssert(() => { + this.checkNoInternalErrors(); + let argCount = 0; + if (this.trackSpy.called) { + this.trackSpy.args.forEach(call => { + argCount += call.length; + }); + } + + Assert.ok(true, "* [" + argCount + " of " + expectedCount + "] checking spy " + new Date().toISOString()); + + try { + if (argCount >= expectedCount) { + const payload = JSON.parse(this.trackSpy.args[0][0]); + const baseType = payload.data.baseType; + // call the appropriate Validate depending on the baseType + switch (baseType) { + case Event.dataType: + return EventValidator.EventValidator.Validate(payload, baseType); + case Trace.dataType: + return TraceValidator.TraceValidator.Validate(payload, baseType); + case Exception.dataType: + return ExceptionValidator.ExceptionValidator.Validate(payload, baseType); + case Metric.dataType: + return MetricValidator.MetricValidator.Validate(payload, baseType); + case PageView.dataType: + return PageViewValidator.PageViewValidator.Validate(payload, baseType); + case PageViewPerformance.dataType: + return PageViewPerformanceValidator.PageViewPerformanceValidator.Validate(payload, baseType); + case RemoteDependencyData.dataType: + return RemoteDepdencyValidator.RemoteDepdencyValidator.Validate(payload, baseType); + + default: + return EventValidator.EventValidator.Validate(payload, baseType); + } + } + } finally { + this.clock.tick(500); + } + + return false; + }, "sender succeeded", 10, 1000)) + ]; } class ChannelPlugin implements IPlugin { @@ -1213,4 +1644,4 @@ class CustomTestError extends Error { this.name = "CustomTestError"; this.message = message + " -- test error."; } - } \ No newline at end of file +} \ No newline at end of file diff --git a/extensions/applicationinsights-analytics-js/Tests/Selenium/Tests.html b/extensions/applicationinsights-analytics-js/Tests/Selenium/Tests.html index 5777689a..a1ed7a9a 100644 --- a/extensions/applicationinsights-analytics-js/Tests/Selenium/Tests.html +++ b/extensions/applicationinsights-analytics-js/Tests/Selenium/Tests.html @@ -5,9 +5,12 @@ Tests for Application Insights JavaScript Analytics Extension - - - + + + + --> + + @@ -40,6 +43,9 @@ // Load Common modules.add("@microsoft/applicationinsights-common", "./node_modules/@microsoft/applicationinsights-common/browser/applicationinsights-common"); + // Load Channel + modules.add("@microsoft/applicationinsights-channel-js", "./node_modules/@microsoft/applicationinsights-channel-js/browser/applicationinsights-channel-js"); + // Load Properties modules.add("@microsoft/applicationinsights-properties-js", "./node_modules/@microsoft/applicationinsights-properties-js/browser/applicationinsights-properties-js"); diff --git a/extensions/applicationinsights-analytics-js/package.json b/extensions/applicationinsights-analytics-js/package.json index c5dffe89..d4fa8c5c 100644 --- a/extensions/applicationinsights-analytics-js/package.json +++ b/extensions/applicationinsights-analytics-js/package.json @@ -25,6 +25,7 @@ "@microsoft/applicationinsights-rollup-plugin-uglify3-js": "1.0.0", "@microsoft/applicationinsights-rollup-es3" : "1.1.3", "@microsoft/applicationinsights-properties-js": "2.6.2", + "@microsoft/applicationinsights-channel-js": "2.6.2", "@microsoft/api-extractor" : "^7.9.11", "typescript": "2.5.3", "tslib": "^1.13.0", @@ -42,7 +43,8 @@ "tslint": "^5.19.0", "tslint-config-prettier": "^1.18.0", "qunit": "^2.9.1", - "sinon": "^7.3.1" + "sinon": "^7.3.1", + "http-server": "0.12.3" }, "dependencies": { "@microsoft/dynamicproto-js": "^1.1.2", diff --git a/extensions/applicationinsights-analytics-js/src/JavaScriptSDK/ApplicationInsights.ts b/extensions/applicationinsights-analytics-js/src/JavaScriptSDK/ApplicationInsights.ts index 6b6d2225..c5057b91 100644 --- a/extensions/applicationinsights-analytics-js/src/JavaScriptSDK/ApplicationInsights.ts +++ b/extensions/applicationinsights-analytics-js/src/JavaScriptSDK/ApplicationInsights.ts @@ -16,7 +16,7 @@ import { IPlugin, IConfiguration, IAppInsightsCore, BaseTelemetryPlugin, ITelemetryItem, IProcessTelemetryContext, ITelemetryPluginChain, IDiagnosticLogger, LoggingSeverity, _InternalMessageId, ICustomProperties, - getWindow, getDocument, getHistory, getLocation, doPerf, objForEachKey, + getWindow, getDocument, getHistory, getLocation, doPerf, objForEachKey, isString, isFunction, isNullOrUndefined, arrForEach, generateW3CId, dumpObj, getExceptionName, isError, ICookieMgr, safeGetCookieMgr } from "@microsoft/applicationinsights-core-js"; import { PageViewManager, IAppInsightsInternal } from "./Telemetry/PageViewManager"; @@ -31,6 +31,7 @@ import { PropertiesPlugin } from "@microsoft/applicationinsights-properties-js"; "use strict"; const durationProperty: string = "duration"; +const strEvent = "event"; function _dispatchEvent(target:EventTarget, evnt: Event) { if (target && target.dispatchEvent && evnt) { @@ -38,19 +39,6 @@ function _dispatchEvent(target:EventTarget, evnt: Event) { } } -function _formatMessage(message: any) { - if (message && !isString(message)) { - // tslint:disable-next-line: prefer-conditional-expression - if (isFunction(message.toString)) { - message = message.toString(); - } else { - message = JSON.stringify(message); - } - } - - return message; -} - export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsights, IAppInsightsInternal { public static Version = "2.6.2"; // Not currently used anywhere @@ -401,10 +389,11 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi * @param systemProperties */ _self.sendExceptionInternal = (exception: IExceptionTelemetry, customProperties?: { [key: string]: any }, systemProperties?: { [key: string]: any }) => { + const theError = exception.exception || exception.error || new Error(strNotSpecified); const exceptionPartB = new Exception( _self.diagLog(), - exception.exception || new Error(strNotSpecified), - exception.properties, + theError, + exception.properties || customProperties, exception.measurements, exception.severityLevel, exception.id @@ -448,28 +437,46 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi * @memberof ApplicationInsights */ _self._onerror = (exception: IAutoExceptionTelemetry): void => { + let error = exception && exception.error; + let evt = exception && exception.evt; + try { + if (!evt) { + let _window = getWindow(); + if (_window) { + evt = _window[strEvent]; + } + } + const url = (exception && exception.url) || (getDocument() || {} as any).URL; + // If no error source is provided assume the default window.onerror handler + const errorSrc = exception.errorSrc || "window.onerror@" + url + ":" + (exception.lineNumber || 0) + ":" + (exception.columnNumber || 0); const properties = { - url: (exception && exception.url) || (getDocument()||{} as any).URL, - lineNumber: exception.lineNumber, - columnNumber: exception.columnNumber, + errorSrc, + url, + lineNumber: exception.lineNumber || 0, + columnNumber: exception.columnNumber || 0, message: exception.message }; - + if (isCrossOriginError(exception.message, exception.url, exception.lineNumber, exception.columnNumber, exception.error)) { - _sendCORSException(properties.url); + _sendCORSException(Exception.CreateAutoException( + "Script error: The browser's same-origin policy prevents us from getting the details of this exception. Consider using the 'crossorigin' attribute.", + url, + exception.lineNumber || 0, + exception.columnNumber || 0, + error, + evt, + null, + errorSrc + ), properties); } else { - if (!isError(exception.error)) { - const stack = "window.onerror@" + properties.url + ":" + exception.lineNumber + ":" + (exception.columnNumber || 0); - exception.error = new Error(exception.message); - exception.error.stack = stack; + if (!exception.errorSrc) { + exception.errorSrc = errorSrc; } - _self.trackException({ exception: exception.error, severityLevel: SeverityLevel.Error }, properties); + _self.trackException({ exception, severityLevel: SeverityLevel.Error }, properties); } } catch (e) { - const errorString = exception.error ? - (exception.error.name + ", " + exception.error.message) - : "null"; + const errorString = error ? (error.name + ", " + error.message) : "null"; _self.diagLog().throwInternal( LoggingSeverity.CRITICAL, @@ -578,15 +585,17 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi const onerror = "onerror"; const originalOnError = _window[onerror]; _window.onerror = (message, url, lineNumber, columnNumber, error) => { + const evt = _window[strEvent]; const handled = originalOnError && (originalOnError(message, url, lineNumber, columnNumber, error) as any); if (handled !== true) { // handled could be typeof function - instance._onerror({ - message: _formatMessage(message), + instance._onerror(Exception.CreateAutoException( + message, url, lineNumber, columnNumber, - error - }); + error, + evt + )); } return handled; @@ -601,15 +610,17 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi const onunhandledrejection = "onunhandledrejection"; const originalOnUnhandledRejection = _window[onunhandledrejection]; _window[onunhandledrejection] = (error: PromiseRejectionEvent) => { + const evt = _window[strEvent]; const handled = originalOnUnhandledRejection && (originalOnUnhandledRejection.call(_window, error) as any); if (handled !== true) { // handled could be typeof function - instance._onerror({ - message: error.reason.toString(), - error: error.reason instanceof Error ? error.reason : new Error(error.reason.toString()), - url: _location ? _location.href : "", - lineNumber: 0, - columnNumber: 0 - }); + instance._onerror(Exception.CreateAutoException( + error.reason.toString(), + _location ? _location.href : "", + 0, + 0, + error, + evt + )); } return handled; @@ -720,20 +731,13 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi _self._telemetryInitializers.push(telemetryInitializer); } - function _sendCORSException(url: string) { - const exception: IAutoExceptionTelemetry = { - message: "Script error: The browser's same-origin policy prevents us from getting the details of this exception. Consider using the 'crossorigin' attribute.", - url, - lineNumber: 0, - columnNumber: 0, - error: undefined - }; + function _sendCORSException(exception: IAutoExceptionTelemetry, properties?: ICustomProperties) { const telemetryItem: ITelemetryItem = TelemetryItemCreator.create( exception, Exception.dataType, Exception.envelopeType, _self.diagLog(), - { url } + properties ); _self.core.track(telemetryItem); diff --git a/extensions/applicationinsights-dependencies-js/src/ajaxRecord.ts b/extensions/applicationinsights-dependencies-js/src/ajaxRecord.ts index 5dfbf126..fbad1086 100644 --- a/extensions/applicationinsights-dependencies-js/src/ajaxRecord.ts +++ b/extensions/applicationinsights-dependencies-js/src/ajaxRecord.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -import { DataSanitizer, dateTimeUtilsDuration, IDependencyTelemetry, urlGetAbsoluteUrl, urlGetCompleteUrl, msToTimeSpan } from '@microsoft/applicationinsights-common'; +import { dataSanitizeUrl, dateTimeUtilsDuration, IDependencyTelemetry, urlGetAbsoluteUrl, urlGetCompleteUrl, msToTimeSpan } from '@microsoft/applicationinsights-common'; import { IDiagnosticLogger, objKeys, arrForEach, isNumber, isString, normalizeJsName, objForEachKey } from '@microsoft/applicationinsights-core-js'; import dynamicProto from "@microsoft/dynamicproto-js"; @@ -272,7 +272,7 @@ export class ajaxRecord { } self.getPathName = () => { - return self.requestUrl ? DataSanitizer.sanitizeUrl(_logger, urlGetCompleteUrl(self.method, self.requestUrl)) : null; + return self.requestUrl ? dataSanitizeUrl(_logger, urlGetCompleteUrl(self.method, self.requestUrl)) : null; } self.CreateTrackItem = (ajaxType:string, enableRequestHeaderTracking:boolean, getResponse:() => IAjaxRecordResponse):IDependencyTelemetry => { diff --git a/extensions/applicationinsights-properties-js/src/Context/TelemetryTrace.ts b/extensions/applicationinsights-properties-js/src/Context/TelemetryTrace.ts index af8b7a8c..72577042 100644 --- a/extensions/applicationinsights-properties-js/src/Context/TelemetryTrace.ts +++ b/extensions/applicationinsights-properties-js/src/Context/TelemetryTrace.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -import { ITelemetryTrace, ITraceState, DataSanitizer } from '@microsoft/applicationinsights-common'; +import { ITelemetryTrace, ITraceState, dataSanitizeString } from '@microsoft/applicationinsights-common'; import { generateW3CId, getLocation, IDiagnosticLogger } from '@microsoft/applicationinsights-core-js'; export class TelemetryTrace implements ITelemetryTrace { @@ -21,6 +21,6 @@ export class TelemetryTrace implements ITelemetryTrace { _self.name = location.pathname; } - _self.name = DataSanitizer.sanitizeString(logger, _self.name); + _self.name = dataSanitizeString(logger, _self.name); } } \ No newline at end of file diff --git a/gruntfile.js b/gruntfile.js index 9a94085d..5af14c1e 100644 --- a/gruntfile.js +++ b/gruntfile.js @@ -311,7 +311,7 @@ module.exports = function (grunt) { core: { options: { urls: [ - './shared/AppInsightsCore/Tests/Selenium/Tests.html' + 'http://localhost:9001/shared/AppInsightsCore/Tests/Selenium/Tests.html' ], timeout: 300 * 1000, // 5 min console: true, @@ -322,18 +322,18 @@ module.exports = function (grunt) { common: { options: { urls: [ - './shared/AppInsightsCommon/Tests/Selenium/Tests.html' + 'http://localhost:9001/shared/AppInsightsCommon/Tests/Selenium/Tests.html' ], timeout: 300 * 1000, // 5 min - console: false, - summaryOnly: true, + console: true, + summaryOnly: false, '--web-security': 'false' // we need this to allow CORS requests in PhantomJS } }, aitests: { options: { urls: [ - './extensions/applicationinsights-analytics-js/Tests/Selenium/Tests.html' + 'http://localhost:9001/extensions/applicationinsights-analytics-js/Tests/Selenium/Tests.html' ], timeout: 300 * 1000, // 5 min console: true, @@ -344,7 +344,7 @@ module.exports = function (grunt) { deps: { options: { urls: [ - './extensions/applicationinsights-dependencies-js/Tests/Selenium/Tests.html' + 'http://localhost:9001/extensions/applicationinsights-dependencies-js/Tests/Selenium/Tests.html' ], timeout: 300 * 1000, // 5 min console: true, @@ -355,7 +355,7 @@ module.exports = function (grunt) { properties: { options: { urls: [ - './extensions/applicationinsights-properties-js/Tests/Selenium/Tests.html' + 'http://localhost:9001/extensions/applicationinsights-properties-js/Tests/Selenium/Tests.html' ], timeout: 5 * 60 * 1000, // 5 min console: false, @@ -366,7 +366,7 @@ module.exports = function (grunt) { reactnative: { options: { urls: [ - './extensions/applicationinsights-react-native/Tests/Selenium/Tests.html' + 'http://localhost:9001/extensions/applicationinsights-react-native/Tests/Selenium/Tests.html' ], timeout: 5 * 60 * 1000, // 5 min console: true, @@ -377,18 +377,18 @@ module.exports = function (grunt) { aisku: { options: { urls: [ - './AISKU/Tests/Selenium/Tests.html' + 'http://localhost:9001/AISKU/Tests/Selenium/Tests.html' ], timeout: 5 * 60 * 1000, // 5 min - console: false, - summaryOnly: true, + console: true, + summaryOnly: false, '--web-security': 'false' } }, aichannel: { options: { urls: [ - './channels/applicationinsights-channel-js/Tests/Selenium/Tests.html' + 'http://localhost:9001/channels/applicationinsights-channel-js/Tests/Selenium/Tests.html' ], timeout: 300 * 1000, // 5 min console: false, @@ -421,7 +421,7 @@ module.exports = function (grunt) { clickanalytics: { options: { urls: [ - './extensions/applicationinsights-clickanalytics-js/Tests/Selenium/Tests.html' + 'http://localhost:9001/extensions/applicationinsights-clickanalytics-js/Tests/Selenium/Tests.html' ], timeout: 300 * 1000, // 5 min console: true, @@ -429,6 +429,14 @@ module.exports = function (grunt) { '--web-security': 'false' // we need this to allow CORS requests in PhantomJS } }, + }, + connect: { + server: { + options: { + port: 9001, + base: '.' + } + } } }); @@ -440,36 +448,38 @@ module.exports = function (grunt) { grunt.loadNpmTasks('grunt-tslint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-qunit'); + grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-run'); 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("core", ["ts:core"]); grunt.registerTask("common", ["ts:common"]); grunt.registerTask("module", ["ts:module"]); grunt.registerTask("ai", ["ts:appinsights"]); - grunt.registerTask("aitests", ["ts:appinsightstests", "qunit:aitests"]); + grunt.registerTask("aitests", ["connect", "ts:appinsightstests", "qunit:aitests"]); grunt.registerTask("aisku", ["ts:aisku"]); grunt.registerTask("aiskulite", ["ts:aiskulite"]); grunt.registerTask("snippetvnext", ["uglify:snippetvNext"]); - grunt.registerTask("aiskutests", ["ts:aiskutests", "qunit:aisku"]); - grunt.registerTask("test", ["ts:default", "ts:test", "ts:testSchema", "ts:testE2E", "qunit:all"]); + grunt.registerTask("aiskutests", ["connect", "ts:aiskutests", "qunit:aisku"]); + grunt.registerTask("test", ["connect", "ts:default", "ts:test", "ts:testSchema", "ts:testE2E", "qunit:all"]); grunt.registerTask("test1ds", ["coretest", "common", "propertiestests", "depstest", "aitests", "aiskutests", "reactnativetests", "reacttests"]); - grunt.registerTask("coretest", ["ts:coretest", "qunit:core"]); - grunt.registerTask("commontest", ["ts:common", "ts:commontest", "qunit:common"]); + grunt.registerTask("coretest", ["connect", "ts:coretest", "qunit:core"]); + grunt.registerTask("commontest", ["connect", "ts:common", "ts:commontest", "qunit:common"]); grunt.registerTask("properties", ["ts:properties"]); - grunt.registerTask("propertiestests", ["ts:propertiestests", "qunit:properties"]); + grunt.registerTask("propertiestests", ["connect", "ts:propertiestests", "qunit:properties"]); grunt.registerTask("reactnative", ["ts:reactnative"]); - grunt.registerTask("reactnativetests", ["qunit:reactnative"]); + grunt.registerTask("reactnativetests", ["connect", "qunit:reactnative"]); grunt.registerTask("deps", ["ts:deps"]); - grunt.registerTask("depstest", ["ts:depstest", "qunit:deps"]); + grunt.registerTask("depstest", [ "connect", "ts:depstest","qunit:deps"]); grunt.registerTask("debugplugin", ["ts:debugplugin"]); grunt.registerTask("aichannel", ["ts:aichannel"]); - grunt.registerTask("aichanneltest", ["ts:aichanneltest", "qunit:aichannel"]); + grunt.registerTask("aichanneltest", ["connect", "ts:aichanneltest", "qunit:aichannel"]); grunt.registerTask("rollupuglify", ["ts:rollupuglify"]); grunt.registerTask("rollupes3", ["ts:rollupes3", "ts:rollupes3test", "qunit:rollupes3"]); grunt.registerTask("rollupes3test", ["ts:rollupes3test", "qunit:rollupes3"]); grunt.registerTask("shims", ["ts:shims", "ts:shimstest", "qunit:shims"]); grunt.registerTask("shimstest", ["ts:shimstest", "qunit:shims"]); grunt.registerTask("clickanalytics", ["ts:clickanalytics"]); - grunt.registerTask("clickanalyticstests", ["ts:clickanalyticstests", "qunit:clickanalytics"]); + grunt.registerTask("clickanalyticstests", ["connect", "ts:clickanalyticstests", "qunit:clickanalytics"]); grunt.registerTask("tst-framework", ["ts:tst-framework"]); + grunt.registerTask("serve", ["connect:server:keepalive"]); }; diff --git a/package.json b/package.json index 2dd26cfe..7ef6a624 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,8 @@ "test": "node common/scripts/install-run-rush.js test --verbose", "lint": "node common/scripts/install-run-rush.js lint --verbose", "rollupes3": "grunt rollupes3", - "rupdate": "node common/scripts/install-run-rush.js update --recheck --purge --full" + "rupdate": "node common/scripts/install-run-rush.js update --recheck --purge --full", + "serve": "grunt serve" }, "repository": { "type": "git", @@ -29,6 +30,7 @@ "devDependencies": { "grunt": "^1.0.1", "grunt-cli": "^1.3.2", + "grunt-contrib-connect": "^3.0.0", "grunt-contrib-qunit": "^3.1.0", "grunt-contrib-uglify": "^3.1.0", "grunt-run": "^0.8.1", @@ -39,6 +41,7 @@ "tslint-config-prettier": "^1.18.0", "typescript": "2.5.3", "whatwg-fetch": "^3.0.0", - "typedoc": "^0.16.9" + "typedoc": "^0.16.9", + "connect": "^3.7.0" } } diff --git a/shared/AppInsightsCommon/Tests/Exception.tests.ts b/shared/AppInsightsCommon/Tests/Exception.tests.ts index e74c9821..93fb6e12 100644 --- a/shared/AppInsightsCommon/Tests/Exception.tests.ts +++ b/shared/AppInsightsCommon/Tests/Exception.tests.ts @@ -40,20 +40,26 @@ export class ExceptionTests extends TestClass { this.testCase({ name: "ExceptionDetails: ExceptionDetails can be exported to interface format", test: () => { - const exceptionDetails = new _ExceptionDetails(this.logger, new Error("test error")); - Assert.ok(exceptionDetails, "ExceptionDetails instance is created"); - - const exceptionDetailsInterface: IExceptionDetailsInternal = exceptionDetails.toInterface(); - Assert.deepEqual(exceptionDetails.id, exceptionDetailsInterface.id); - Assert.deepEqual(exceptionDetails.outerId, exceptionDetailsInterface.outerId); - Assert.deepEqual(exceptionDetails.typeName, exceptionDetailsInterface.typeName); - Assert.deepEqual(exceptionDetails.message, exceptionDetailsInterface.message); - Assert.deepEqual(exceptionDetails.hasFullStack, exceptionDetailsInterface.hasFullStack); - Assert.deepEqual(exceptionDetails.stack, exceptionDetailsInterface.stack); - Assert.deepEqual(exceptionDetails.parsedStack && exceptionDetails.parsedStack.map((frame: _StackFrame) => frame.toInterface()), exceptionDetailsInterface.parsedStack); - - const exceptionDetailsConverted = _ExceptionDetails.CreateFromInterface(this.logger, exceptionDetailsInterface); - Assert.deepEqual(exceptionDetails, exceptionDetailsConverted); + try { + const exceptionDetails = new _ExceptionDetails(this.logger, new Error("test error")); + Assert.ok(exceptionDetails, "ExceptionDetails instance is created"); + + const exceptionDetailsInterface: IExceptionDetailsInternal = exceptionDetails.toInterface(); + Assert.deepEqual(exceptionDetails.id, exceptionDetailsInterface.id); + Assert.deepEqual(exceptionDetails.outerId, exceptionDetailsInterface.outerId); + Assert.deepEqual(exceptionDetails.typeName, exceptionDetailsInterface.typeName); + Assert.deepEqual(exceptionDetails.message, exceptionDetailsInterface.message); + Assert.deepEqual(exceptionDetails.hasFullStack, exceptionDetailsInterface.hasFullStack); + Assert.deepEqual(exceptionDetails.stack, exceptionDetailsInterface.stack); + Assert.deepEqual(exceptionDetails.parsedStack && exceptionDetails.parsedStack.map((frame: _StackFrame) => frame.toInterface()), exceptionDetailsInterface.parsedStack); + + const exceptionDetailsConverted = _ExceptionDetails.CreateFromInterface(this.logger, exceptionDetailsInterface); + Assert.deepEqual(exceptionDetails, exceptionDetailsConverted); + } catch (e) { + console.log(e.stack); + console.log(e.toString()); + Assert.ok(false, e.toString()); + } } }); diff --git a/shared/AppInsightsCommon/src/Enums.ts b/shared/AppInsightsCommon/src/Enums.ts index 2f350c70..d01bdc72 100644 --- a/shared/AppInsightsCommon/src/Enums.ts +++ b/shared/AppInsightsCommon/src/Enums.ts @@ -13,7 +13,7 @@ export enum StorageType { * Enum is used in aiDataContract to describe how fields are serialized. * For instance: (Fieldtype.Required | FieldType.Array) will mark the field as required and indicate it's an array */ -export enum FieldType { Default = 0, Required = 1, Array = 2, Hidden = 4 }; +export const enum FieldType { Default = 0, Required = 1, Array = 2, Hidden = 4 }; export enum DistributedTracingModes { /** diff --git a/shared/AppInsightsCommon/src/HelperFuncs.ts b/shared/AppInsightsCommon/src/HelperFuncs.ts index 381c4283..34b5d27d 100644 --- a/shared/AppInsightsCommon/src/HelperFuncs.ts +++ b/shared/AppInsightsCommon/src/HelperFuncs.ts @@ -52,6 +52,6 @@ export function getExtensionByName(extensions: IPlugin[], identifier: string): I return extension; } -export function isCrossOriginError(message: string|Event, url: string, lineNumber: number, columnNumber: number, error: Error): boolean { +export function isCrossOriginError(message: string|Event, url: string, lineNumber: number, columnNumber: number, error: Error | Event): boolean { return !error && isString(message) && (message === "Script error." || message === "Script error"); } diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/Generated/ExceptionDetails.ts b/shared/AppInsightsCommon/src/Interfaces/Contracts/Generated/ExceptionDetails.ts index 5cd1984c..51b4f813 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/Generated/ExceptionDetails.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/Generated/ExceptionDetails.ts @@ -23,7 +23,7 @@ export class ExceptionDetails { * Exception type name. */ public typeName: string; - + /** * Exception message. */ diff --git a/shared/AppInsightsCommon/src/Interfaces/IExceptionTelemetry.ts b/shared/AppInsightsCommon/src/Interfaces/IExceptionTelemetry.ts index 18305a57..809686ff 100644 --- a/shared/AppInsightsCommon/src/Interfaces/IExceptionTelemetry.ts +++ b/shared/AppInsightsCommon/src/Interfaces/IExceptionTelemetry.ts @@ -28,7 +28,7 @@ export interface IExceptionTelemetry extends IPartC { * @memberof IExceptionTelemetry * @description Error Object(s) */ - exception?: Error; + exception?: Error | IAutoExceptionTelemetry; /** * @description Specified severity of exception for use with @@ -75,10 +75,38 @@ export interface IAutoExceptionTelemetry { /** * @description Error Object (object) - * @type {Error} + * @type {any} * @memberof IAutoExceptionTelemetry */ - error: Error; + error: any; + + /** + * @description The event at the time of the exception (object) + * @type {Event|string} + * @memberof IAutoExceptionTelemetry + */ + evt?: Event|string; + + /** + * @description The provided stack for the error + * @type {IStackDetails} + * @memberof IAutoExceptionTelemetry + */ + stackDetails?: IStackDetails; + + /** + * @description The calculated type of the error + * @type {string} + * @memberof IAutoExceptionTelemetry + */ + typeName?: string; + + /** + * @description The descriptive source of the error + * @type {string} + * @memberof IAutoExceptionTelemetry + */ + errorSrc?: string; } export interface IExceptionInternal extends IPartC { @@ -108,3 +136,8 @@ export interface IExceptionStackFrameInternal { line: number; pos?: number; } + +export interface IStackDetails { + src: string, + obj: string[], +} diff --git a/shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.ts b/shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.ts index 4ea99b04..d9ba8cff 100644 --- a/shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.ts +++ b/shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.ts @@ -1,202 +1,285 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -import { IDiagnosticLogger, LoggingSeverity, _InternalMessageId, hasJSON, getJSON, objForEachKey, isObject, isString } from '@microsoft/applicationinsights-core-js'; - -export class DataSanitizer { +import { IDiagnosticLogger, LoggingSeverity, _InternalMessageId, hasJSON, getJSON, objForEachKey, isObject, isString, strTrim } from '@microsoft/applicationinsights-core-js'; +export const enum DataSanitizerValues { /** * Max length allowed for custom names. */ - public static MAX_NAME_LENGTH = 150; + MAX_NAME_LENGTH = 150, - /** - * Max length allowed for Id field in page views. - */ - public static MAX_ID_LENGTH = 128; + /** + * Max length allowed for Id field in page views. + */ + MAX_ID_LENGTH = 128, + + /** + * Max length allowed for custom values. + */ + MAX_PROPERTY_LENGTH = 8192, + + /** + * Max length allowed for names + */ + MAX_STRING_LENGTH = 1024, + + /** + * Max length allowed for url. + */ + MAX_URL_LENGTH = 2048, + + /** + * Max length allowed for messages. + */ + MAX_MESSAGE_LENGTH = 32768, + + /** + * Max length allowed for exceptions. + */ + MAX_EXCEPTION_LENGTH = 32768 +}; - /** - * Max length allowed for custom values. - */ - public static MAX_PROPERTY_LENGTH = 8192; +export function dataSanitizeKeyAndAddUniqueness(logger: IDiagnosticLogger, key: any, map: any) { + const origLength = key.length; + let field = dataSanitizeKey(logger, key); - /** - * Max length allowed for names - */ - public static MAX_STRING_LENGTH = 1024; - - /** - * Max length allowed for url. - */ - public static MAX_URL_LENGTH = 2048; - - /** - * Max length allowed for messages. - */ - public static MAX_MESSAGE_LENGTH = 32768; - - /** - * Max length allowed for exceptions. - */ - public static MAX_EXCEPTION_LENGTH = 32768; - - public static sanitizeKeyAndAddUniqueness(logger: IDiagnosticLogger, key: any, map: any) { - const origLength = key.length; - let field = DataSanitizer.sanitizeKey(logger, key); - - // validation truncated the length. We need to add uniqueness - if (field.length !== origLength) { - let i = 0; - let uniqueField = field; - while (map[uniqueField] !== undefined) { - i++; - uniqueField = field.substring(0, DataSanitizer.MAX_NAME_LENGTH - 3) + DataSanitizer.padNumber(i); - } - field = uniqueField; + // validation truncated the length. We need to add uniqueness + if (field.length !== origLength) { + let i = 0; + let uniqueField = field; + while (map[uniqueField] !== undefined) { + i++; + uniqueField = field.substring(0, DataSanitizerValues.MAX_NAME_LENGTH - 3) + dsPadNumber(i); } - return field; + field = uniqueField; } + return field; +} - public static sanitizeKey(logger: IDiagnosticLogger, name: any) { - let nameTrunc: String; - if (name) { - // Remove any leading or trailing whitepace - name = DataSanitizer.trim(name.toString()); +export function dataSanitizeKey(logger: IDiagnosticLogger, name: any) { + let nameTrunc: String; + if (name) { + // Remove any leading or trailing whitepace + name = strTrim(name.toString()); - // truncate the string to 150 chars - if (name.length > DataSanitizer.MAX_NAME_LENGTH) { - nameTrunc = name.substring(0, DataSanitizer.MAX_NAME_LENGTH); - logger.throwInternal( - LoggingSeverity.WARNING, - _InternalMessageId.NameTooLong, - "name is too long. It has been truncated to " + DataSanitizer.MAX_NAME_LENGTH + " characters.", - { name }, true); - } + // truncate the string to 150 chars + if (name.length > DataSanitizerValues.MAX_NAME_LENGTH) { + nameTrunc = name.substring(0, DataSanitizerValues.MAX_NAME_LENGTH); + logger.throwInternal( + LoggingSeverity.WARNING, + _InternalMessageId.NameTooLong, + "name is too long. It has been truncated to " + DataSanitizerValues.MAX_NAME_LENGTH + " characters.", + { name }, true); } - - return nameTrunc || name; } - public static sanitizeString(logger: IDiagnosticLogger, value: any, maxLength: number = DataSanitizer.MAX_STRING_LENGTH) { - let valueTrunc : String; - if (value) { - maxLength = maxLength ? maxLength : DataSanitizer.MAX_STRING_LENGTH; // in case default parameters dont work - value = DataSanitizer.trim(value); - if (value.toString().length > maxLength) { - valueTrunc = value.toString().substring(0, maxLength); - logger.throwInternal( - LoggingSeverity.WARNING, - _InternalMessageId.StringValueTooLong, - "string value is too long. It has been truncated to " + maxLength + " characters.", - { value }, true); - } + return nameTrunc || name; +} + +export function dataSanitizeString(logger: IDiagnosticLogger, value: any, maxLength: number = DataSanitizerValues.MAX_STRING_LENGTH) { + 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); + logger.throwInternal( + LoggingSeverity.WARNING, + _InternalMessageId.StringValueTooLong, + "string value is too long. It has been truncated to " + maxLength + " characters.", + { value }, true); } - - return valueTrunc || value; } - public static sanitizeUrl(logger: IDiagnosticLogger, url: any) { - return DataSanitizer.sanitizeInput(logger, url, DataSanitizer.MAX_URL_LENGTH, _InternalMessageId.UrlTooLong); - } + return valueTrunc || value; +} - public static sanitizeMessage(logger: IDiagnosticLogger, message: any) { - let messageTrunc : String; - if (message) { - if (message.length > DataSanitizer.MAX_MESSAGE_LENGTH) { - messageTrunc = message.substring(0, DataSanitizer.MAX_MESSAGE_LENGTH); - logger.throwInternal( - LoggingSeverity.WARNING, _InternalMessageId.MessageTruncated, - "message is too long, it has been truncated to " + DataSanitizer.MAX_MESSAGE_LENGTH + " characters.", - { message }, - true); - } +export function dataSanitizeUrl(logger: IDiagnosticLogger, url: any) { + return dataSanitizeInput(logger, url, DataSanitizerValues.MAX_URL_LENGTH, _InternalMessageId.UrlTooLong); +} + +export function dataSanitizeMessage(logger: IDiagnosticLogger, message: any) { + let messageTrunc : String; + if (message) { + if (message.length > DataSanitizerValues.MAX_MESSAGE_LENGTH) { + messageTrunc = message.substring(0, DataSanitizerValues.MAX_MESSAGE_LENGTH); + logger.throwInternal( + LoggingSeverity.WARNING, _InternalMessageId.MessageTruncated, + "message is too long, it has been truncated to " + DataSanitizerValues.MAX_MESSAGE_LENGTH + " characters.", + { message }, + true); } - - return messageTrunc || message; } - public static sanitizeException(logger: IDiagnosticLogger, exception: any) { - let exceptionTrunc : String; - if (exception) { - if (exception.length > DataSanitizer.MAX_EXCEPTION_LENGTH) { - exceptionTrunc = exception.substring(0, DataSanitizer.MAX_EXCEPTION_LENGTH); - logger.throwInternal( - LoggingSeverity.WARNING, _InternalMessageId.ExceptionTruncated, "exception is too long, it has been truncated to " + DataSanitizer.MAX_EXCEPTION_LENGTH + " characters.", - { exception }, true); - } + return messageTrunc || message; +} + +export function dataSanitizeException(logger: IDiagnosticLogger, exception: any) { + let exceptionTrunc : String; + if (exception) { + // Make surte its a string + let value:string = "" + exception; + if (value.length > DataSanitizerValues.MAX_EXCEPTION_LENGTH) { + exceptionTrunc = value.substring(0, DataSanitizerValues.MAX_EXCEPTION_LENGTH); + logger.throwInternal( + LoggingSeverity.WARNING, _InternalMessageId.ExceptionTruncated, "exception is too long, it has been truncated to " + DataSanitizerValues.MAX_EXCEPTION_LENGTH + " characters.", + { exception }, true); } - - return exceptionTrunc || exception; } - public static sanitizeProperties(logger: IDiagnosticLogger, properties: any) { - if (properties) { - const tempProps = {}; - objForEachKey(properties, (prop, value) => { - if (isObject(value) && hasJSON()) { - // Stringify any part C properties - try { - value = getJSON().stringify(value); - } catch (e) { - logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.CannotSerializeObjectNonSerializable, "custom property is not valid", { exception: e}, true); - } + return exceptionTrunc || exception; +} + +export function dataSanitizeProperties(logger: IDiagnosticLogger, properties: any) { + if (properties) { + const tempProps = {}; + objForEachKey(properties, (prop, value) => { + if (isObject(value) && hasJSON()) { + // Stringify any part C properties + try { + value = getJSON().stringify(value); + } catch (e) { + logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.CannotSerializeObjectNonSerializable, "custom property is not valid", { exception: e}, true); } - value = DataSanitizer.sanitizeString(logger, value, DataSanitizer.MAX_PROPERTY_LENGTH); - prop = DataSanitizer.sanitizeKeyAndAddUniqueness(logger, prop, tempProps); - tempProps[prop] = value; - }); - properties = tempProps; - } - - return properties; - } - - public static sanitizeMeasurements(logger: IDiagnosticLogger, measurements: any) { - if (measurements) { - const tempMeasurements = {}; - objForEachKey(measurements, (measure, value) => { - measure = DataSanitizer.sanitizeKeyAndAddUniqueness(logger, measure, tempMeasurements); - tempMeasurements[measure] = value; - }); - - measurements = tempMeasurements; - } - - return measurements; - } - - public static sanitizeId(logger: IDiagnosticLogger, id: string): string { - return id ? DataSanitizer.sanitizeInput(logger, id, DataSanitizer.MAX_ID_LENGTH, _InternalMessageId.IdTooLong).toString() : id; - } - - public static sanitizeInput(logger: IDiagnosticLogger, input: any, maxLength: number, _msgId: _InternalMessageId) { - let inputTrunc : String; - if (input) { - input = DataSanitizer.trim(input); - if (input.length > maxLength) { - inputTrunc = input.substring(0, maxLength); - logger.throwInternal( - LoggingSeverity.WARNING, - _msgId, - "input is too long, it has been truncated to " + maxLength + " characters.", - { data: input }, - true); } + value = dataSanitizeString(logger, value, DataSanitizerValues.MAX_PROPERTY_LENGTH); + prop = dataSanitizeKeyAndAddUniqueness(logger, prop, tempProps); + tempProps[prop] = value; + }); + properties = tempProps; + } + + return properties; +} + +export function dataSanitizeMeasurements(logger: IDiagnosticLogger, measurements: any) { + if (measurements) { + const tempMeasurements = {}; + objForEachKey(measurements, (measure, value) => { + measure = dataSanitizeKeyAndAddUniqueness(logger, measure, tempMeasurements); + tempMeasurements[measure] = value; + }); + + measurements = tempMeasurements; + } + + return measurements; +} + +export function dataSanitizeId(logger: IDiagnosticLogger, id: string): string { + return id ? dataSanitizeInput(logger, id, DataSanitizerValues.MAX_ID_LENGTH, _InternalMessageId.IdTooLong).toString() : id; +} + +export function dataSanitizeInput(logger: IDiagnosticLogger, input: any, maxLength: number, _msgId: _InternalMessageId) { + let inputTrunc : String; + if (input) { + input = strTrim(input); + if (input.length > maxLength) { + inputTrunc = input.substring(0, maxLength); + logger.throwInternal( + LoggingSeverity.WARNING, + _msgId, + "input is too long, it has been truncated to " + maxLength + " characters.", + { data: input }, + true); } - - return inputTrunc || input; } - public static padNumber(num: number) { - const s = "00" + num; - return s.substr(s.length - 3); - } + return inputTrunc || input; +} +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: _InternalMessageId) => any; + + padNumber: (num: number) => string; + /** * helper method to trim strings (IE8 does not implement String.prototype.trim) */ - public static trim(str: any): string { - if (!isString(str)) { return str; } - return str.replace(/^\s+|\s+$/g, ""); - } -} \ No newline at end of file + 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 +}; \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Telemetry/Common/Envelope.ts b/shared/AppInsightsCommon/src/Telemetry/Common/Envelope.ts index 6ef11235..4915b4a3 100644 --- a/shared/AppInsightsCommon/src/Telemetry/Common/Envelope.ts +++ b/shared/AppInsightsCommon/src/Telemetry/Common/Envelope.ts @@ -4,7 +4,7 @@ import { Envelope as AIEnvelope } from '../../Interfaces/Contracts/Generated/Envelope'; import { Base } from '../../Interfaces/Contracts/Generated/Base'; import { IEnvelope } from '../../Interfaces/Telemetry/IEnvelope'; -import { DataSanitizer } from './DataSanitizer'; +import { dataSanitizeString } from './DataSanitizer'; import { FieldType } from '../../Enums'; import { IDiagnosticLogger, toISOString } from '@microsoft/applicationinsights-core-js'; import { strNotSpecified } from '../../Constants'; @@ -22,7 +22,7 @@ export class Envelope extends AIEnvelope implements IEnvelope { constructor(logger: IDiagnosticLogger, data: Base, name: string) { super(); - this.name = DataSanitizer.sanitizeString(logger, name) || strNotSpecified; + this.name = dataSanitizeString(logger, name) || strNotSpecified; this.data = data; this.time = toISOString(new Date()); diff --git a/shared/AppInsightsCommon/src/Telemetry/Event.ts b/shared/AppInsightsCommon/src/Telemetry/Event.ts index 49116ecc..8010ed96 100644 --- a/shared/AppInsightsCommon/src/Telemetry/Event.ts +++ b/shared/AppInsightsCommon/src/Telemetry/Event.ts @@ -4,7 +4,7 @@ import { IDiagnosticLogger } from '@microsoft/applicationinsights-core-js'; import { EventData } from '../Interfaces/Contracts/Generated/EventData'; import { ISerializable } from '../Interfaces/Telemetry/ISerializable'; -import { DataSanitizer } from './Common/DataSanitizer'; +import { dataSanitizeString, dataSanitizeProperties, dataSanitizeMeasurements } from './Common/DataSanitizer'; import { FieldType } from '../Enums'; import { strNotSpecified } from '../Constants'; @@ -27,8 +27,8 @@ export class Event extends EventData implements ISerializable { super(); - this.name = DataSanitizer.sanitizeString(logger, name) || strNotSpecified; - this.properties = DataSanitizer.sanitizeProperties(logger, properties); - this.measurements = DataSanitizer.sanitizeMeasurements(logger, measurements); + this.name = dataSanitizeString(logger, name) || strNotSpecified; + this.properties = dataSanitizeProperties(logger, properties); + this.measurements = dataSanitizeMeasurements(logger, measurements); } } diff --git a/shared/AppInsightsCommon/src/Telemetry/Exception.ts b/shared/AppInsightsCommon/src/Telemetry/Exception.ts index 81f8a7c7..4dc5e1b1 100644 --- a/shared/AppInsightsCommon/src/Telemetry/Exception.ts +++ b/shared/AppInsightsCommon/src/Telemetry/Exception.ts @@ -5,21 +5,244 @@ import { StackFrame } from '../Interfaces/Contracts/Generated/StackFrame'; import { ExceptionData } from '../Interfaces/Contracts/Generated/ExceptionData'; import { ExceptionDetails } from '../Interfaces/Contracts/Generated/ExceptionDetails'; import { ISerializable } from '../Interfaces/Telemetry/ISerializable'; -import { DataSanitizer } from './Common/DataSanitizer'; +import { dataSanitizeException, dataSanitizeMeasurements, dataSanitizeMessage, dataSanitizeProperties, dataSanitizeString } from './Common/DataSanitizer'; import { FieldType } from '../Enums'; import { SeverityLevel } from '../Interfaces/Contracts/Generated/SeverityLevel'; -import { IDiagnosticLogger, isNullOrUndefined, arrMap, isString, strTrim, isArray, isError } from '@microsoft/applicationinsights-core-js'; -import { IExceptionInternal, IExceptionDetailsInternal, IExceptionStackFrameInternal } from '../Interfaces/IExceptionTelemetry'; +import { IDiagnosticLogger, isNullOrUndefined, arrMap, isString, strTrim, isArray, isError, arrForEach, isObject, isFunction, getSetValue } from '@microsoft/applicationinsights-core-js'; +import { + IExceptionInternal, IExceptionDetailsInternal, IExceptionStackFrameInternal, IAutoExceptionTelemetry, IStackDetails +} from '../Interfaces/IExceptionTelemetry'; import { strNotSpecified } from '../Constants'; +const NoMethod = ""; const strError = "error"; +const strStack = "stack"; +const strStackDetails = "stackDetails"; +const strErrorSrc = "errorSrc"; +const strMessage = "message"; +const strDescription = "description"; + +function _stringify(value: any, convertToString: boolean) { + let result = value; + if (result && !isString(result)) { + if (JSON && JSON.stringify) { + result = JSON.stringify(value); + if (convertToString && (!result || result === "{}")) { + if (isFunction(value.toString)) { + result = value.toString(); + } else { + result = "" + value; + } + } + } else { + result = "" + value + " - (Missing JSON.stringify)"; + } + } + + return result || ""; +} + +function _formatMessage(theEvent: any, errorType: string) { + let evtMessage = theEvent; + if (theEvent) { + evtMessage = theEvent[strMessage] || theEvent[strDescription] || ""; + // Make sure the message is a string + if (evtMessage && !isString(evtMessage)) { + // tslint:disable-next-line: prefer-conditional-expression + evtMessage = _stringify(evtMessage, true); + } + + if (theEvent["filename"]) { + // Looks like an event object with filename + evtMessage = evtMessage + " @" + (theEvent["filename"] || "") + ":" + (theEvent["lineno"] || "?") + ":" + (theEvent["colno"] || "?"); + } + } + + // Automatically add the error type to the message if it does already appear to be present + if (errorType && errorType !== "String" && errorType !== "Object" && errorType !== "Error" && (evtMessage || "").indexOf(errorType) === -1) { + evtMessage = errorType + ": " + evtMessage; + } + + return evtMessage || ""; +} function _isExceptionDetailsInternal(value:any): value is IExceptionDetailsInternal { - return "hasFullStack" in value && "typeName" in value; + if (isObject(value)) { + return "hasFullStack" in value && "typeName" in value; + } + + return false; } function _isExceptionInternal(value:any): value is IExceptionInternal { - return ("ver" in value && "exceptions" in value && "properties" in value); + if (isObject(value)) { + return ("ver" in value && "exceptions" in value && "properties" in value); + } + + return false; +} + +function _isStackDetails(details:any): details is IStackDetails { + return details && details.src && isString(details.src) && details.obj && isArray(details.obj); +} + +function _convertStackObj(errorStack:string): IStackDetails { + let src = errorStack || ""; + if (!isString(src)) { + if (isString(src[strStack])) { + src = src[strStack]; + } else { + src = "" + src; + } + } + + let items = src.split("\n"); + return { + src, + obj: items + }; +} + +function _getOperaStack(errorMessage:string): IStackDetails { + var stack: string[] = []; + var lines = errorMessage.split("\n"); + for (var lp = 0; lp < lines.length; lp++) { + var entry = lines[lp]; + if (lines[lp + 1]) { + entry += "@" + lines[lp + 1]; + lp++; + } + + stack.push(entry); + } + + return { + src: errorMessage, + obj: stack + }; +} + +function _getStackFromErrorObj(errorObj:any): IStackDetails { + let details = null; + if (errorObj) { + try { + /* Using bracket notation is support older browsers (IE 7/8 -- dont remember the version) that throw when using dot + notation for undefined objects and we don't want to loose the error from being reported */ + if (errorObj[strStack]) { + // Chrome/Firefox + details = _convertStackObj(errorObj[strStack]); + } else if (errorObj[strError] && errorObj[strError][strStack]) { + // Edge error event provides the stack and error object + details = _convertStackObj(errorObj[strError][strStack]); + } else if (errorObj['exception'] && errorObj.exception[strStack]) { + details = _convertStackObj(errorObj.exception[strStack]); + } else if (_isStackDetails(errorObj)) { + details = errorObj; + } else if (_isStackDetails(errorObj[strStackDetails])) { + details = errorObj[strStackDetails]; + } else if (window['opera'] && errorObj[strMessage]) { + // Opera + details = _getOperaStack(errorObj.message); + } else if (isString(errorObj)) { + details = _convertStackObj(errorObj); + } else { + let evtMessage = errorObj[strMessage] || errorObj[strDescription] || ""; + + if (isString(errorObj[strErrorSrc])) { + if (evtMessage) { + evtMessage += "\n"; + } + + evtMessage += " from " + errorObj[strErrorSrc]; + } + + if (evtMessage) { + details = _convertStackObj(evtMessage); + } + } + } catch (e) { + // something unexpected happened so to avoid failing to report any error lets swallow the exception + // and fallback to the callee/caller method + details = _convertStackObj(e); + } + } + + return details || { + src: "", + obj: null + }; +} + +function _formatStackTrace(stackDetails: IStackDetails) { + let stack = ""; + + if (stackDetails) { + if (stackDetails.obj) { + arrForEach(stackDetails.obj, (entry) => { + stack += entry + "\n"; + }); + } else { + stack = stackDetails.src || ""; + } + + } + + return stack; +} + +function _parseStack(stack:IStackDetails): _StackFrame[] { + let parsedStack: _StackFrame[]; + let frames = stack.obj; + if (frames && frames.length > 0) { + parsedStack = []; + let level = 0; + + let totalSizeInBytes = 0; + + arrForEach(frames, (frame) => { + let theFrame = frame.toString(); + if (_StackFrame.regex.test(theFrame)) { + const parsedFrame = new _StackFrame(theFrame, level++); + totalSizeInBytes += parsedFrame.sizeInBytes; + parsedStack.push(parsedFrame); + } + }); + + // DP Constraint - exception parsed stack must be < 32KB + // remove frames from the middle to meet the threshold + const exceptionParsedStackThreshold = 32 * 1024; + if (totalSizeInBytes > exceptionParsedStackThreshold) { + let left = 0; + let right = parsedStack.length - 1; + let size = 0; + let acceptedLeft = left; + let acceptedRight = right; + + while (left < right) { + // check size + const lSize = parsedStack[left].sizeInBytes; + const rSize = parsedStack[right].sizeInBytes; + size += lSize + rSize; + + if (size > exceptionParsedStackThreshold) { + + // remove extra frames from the middle + const howMany = acceptedRight - acceptedLeft + 1; + parsedStack.splice(acceptedLeft, howMany); + break; + } + + // update pointers + acceptedLeft = left; + acceptedRight = right; + + left++; + right--; + } + } + } + + return parsedStack; } function _getErrorType(errorType: any) { @@ -41,6 +264,40 @@ function _getErrorType(errorType: any) { return typeName; } +/** + * Formats the provided errorObj for display and reporting, it may be a String, Object, integer or undefined depending on the browser. + * @param errorObj The supplied errorObj + */ +export function _formatErrorCode(errorObj:any) { + if (errorObj) { + try { + if (!isString(errorObj)) { + var errorType = _getErrorType(errorObj); + var result = _stringify(errorObj, false); + if (!result || result === "{}") { + if (errorObj[strError]) { + // Looks like an MS Error Event + errorObj = errorObj[strError]; + errorType = _getErrorType(errorObj); + } + + result = _stringify(errorObj, true); + } + + if (result.indexOf(errorType) !== 0 && errorType !== "String") { + return errorType + ":" + result; + } + + return result; + } + } catch (e) { + } + } + + // Fallback to just letting the object format itself into a string + return "" + (errorObj || ""); +} + export class Exception extends ExceptionData implements ISerializable { public static envelopeType = "Microsoft.ApplicationInsights.{0}.Exception"; @@ -61,13 +318,17 @@ export class Exception extends ExceptionData implements ISerializable { /** * Constructs a new instance of the ExceptionTelemetry object */ - constructor(logger: IDiagnosticLogger, exception: Error | IExceptionInternal, properties?: {[key: string]: any}, measurements?: {[key: string]: number}, severityLevel?: SeverityLevel, id?: string) { + constructor(logger: IDiagnosticLogger, exception: Error | IExceptionInternal | IAutoExceptionTelemetry, properties?: {[key: string]: any}, measurements?: {[key: string]: number}, severityLevel?: SeverityLevel, id?: string) { super(); if (!_isExceptionInternal(exception)) { - this.exceptions = [new _ExceptionDetails(logger, exception)]; - this.properties = DataSanitizer.sanitizeProperties(logger, properties) || {}; - this.measurements = DataSanitizer.sanitizeMeasurements(logger, measurements); + if (!properties) { + properties = { }; + } + + this.exceptions = [new _ExceptionDetails(logger, exception, properties)]; + this.properties = dataSanitizeProperties(logger, properties); + this.measurements = dataSanitizeMeasurements(logger, measurements); if (severityLevel) { this.severityLevel = severityLevel; } if (id) { this.id = id; } } else { @@ -84,6 +345,32 @@ export class Exception extends ExceptionData implements ISerializable { } } + public static CreateAutoException( + message: string | Event, + url: string, + lineNumber: number, + columnNumber: number, + error: any, + evt?: Event|string, + stack?: string, + errorSrc?: string + ): IAutoExceptionTelemetry { + + let errorType = _getErrorType(error || evt || message); + + return { + message: _formatMessage(message, errorType), + url, + lineNumber, + columnNumber, + error: _formatErrorCode(error || evt || message), + evt: _formatErrorCode(evt || message), + typeName: errorType, + stackDetails: _getStackFromErrorObj(stack || error || evt), + errorSrc + } + } + public static CreateFromInterface(logger: IDiagnosticLogger, exception: IExceptionInternal, properties?: any, measurements?: { [key: string]: number }): Exception { const exceptions: _ExceptionDetails[] = exception.exceptions && arrMap(exception.exceptions, (ex: IExceptionDetailsInternal) => _ExceptionDetails.CreateFromInterface(logger, ex)); @@ -122,11 +409,13 @@ export class Exception extends ExceptionData implements ISerializable { hasFullStack: true, message, stack: details, - typeName + typeName, } as ExceptionDetails ] } as Exception; } + + public static formatError = _formatErrorCode; } export class _ExceptionDetails extends ExceptionDetails implements ISerializable { @@ -141,25 +430,30 @@ export class _ExceptionDetails extends ExceptionDetails implements ISerializable parsedStack: FieldType.Array }; - constructor(logger: IDiagnosticLogger, exception: Error | IExceptionDetailsInternal) { + constructor(logger: IDiagnosticLogger, exception: Error | IExceptionDetailsInternal | IAutoExceptionTelemetry, properties?: {[key: string]: any}) { super(); if (!_isExceptionDetailsInternal(exception)) { let error = exception as any; + let evt = error && error.evt; if (!isError(error)) { - error = error[strError] || error.evt || error; + error = error[strError] || evt || error; } - this.typeName = DataSanitizer.sanitizeString(logger, _getErrorType(error)) || strNotSpecified; - this.message = DataSanitizer.sanitizeMessage(logger, exception.message) || strNotSpecified; - const stack = exception.stack; - this.parsedStack = _ExceptionDetails.parseStack(stack); - this.stack = DataSanitizer.sanitizeException(logger, stack); + this.typeName = dataSanitizeString(logger, _getErrorType(error)) || strNotSpecified; + this.message = dataSanitizeMessage(logger, _formatMessage(exception || error, this.typeName)) || strNotSpecified; + const stack = exception[strStackDetails] || _getStackFromErrorObj(exception); + this.parsedStack = _parseStack(stack); + this[strStack] = dataSanitizeException(logger, _formatStackTrace(stack)); this.hasFullStack = isArray(this.parsedStack) && this.parsedStack.length > 0; + + if (properties) { + properties.typeName = properties.typeName || this.typeName; + } } else { this.typeName = exception.typeName; this.message = exception.message; - this.stack = exception.stack; + this[strStack] = exception[strStack]; this.parsedStack = exception.parsedStack this.hasFullStack = exception.hasFullStack } @@ -175,7 +469,7 @@ export class _ExceptionDetails extends ExceptionDetails implements ISerializable typeName: this.typeName, message: this.message, hasFullStack: this.hasFullStack, - stack: this.stack, + stack: this[strStack], parsedStack: parsedStack || undefined }; @@ -191,67 +485,13 @@ export class _ExceptionDetails extends ExceptionDetails implements ISerializable return exceptionDetails; } - - private static parseStack(stack?:string): _StackFrame[] { - let parsedStack: _StackFrame[]; - if (isString(stack)) { - const frames = stack.split('\n'); - parsedStack = []; - let level = 0; - - let totalSizeInBytes = 0; - for (let i = 0; i <= frames.length; i++) { - const frame = frames[i]; - if (_StackFrame.regex.test(frame)) { - const parsedFrame = new _StackFrame(frames[i], level++); - totalSizeInBytes += parsedFrame.sizeInBytes; - parsedStack.push(parsedFrame); - } - } - - // DP Constraint - exception parsed stack must be < 32KB - // remove frames from the middle to meet the threshold - const exceptionParsedStackThreshold = 32 * 1024; - if (totalSizeInBytes > exceptionParsedStackThreshold) { - let left = 0; - let right = parsedStack.length - 1; - let size = 0; - let acceptedLeft = left; - let acceptedRight = right; - - while (left < right) { - // check size - const lSize = parsedStack[left].sizeInBytes; - const rSize = parsedStack[right].sizeInBytes; - size += lSize + rSize; - - if (size > exceptionParsedStackThreshold) { - - // remove extra frames from the middle - const howMany = acceptedRight - acceptedLeft + 1; - parsedStack.splice(acceptedLeft, howMany); - break; - } - - // update pointers - acceptedLeft = left; - acceptedRight = right; - - left++; - right--; - } - } - } - - return parsedStack; - } } export class _StackFrame extends StackFrame implements ISerializable { // regex to match stack frames from ie/chrome/ff // methodName=$2, fileName=$4, lineNo=$5, column=$6 - public static regex = /^([\s]+at)?(.*?)(\@|\s\(|\s)([^\(\@\n]+):([0-9]+):([0-9]+)(\)?)$/; + public static regex = /^([\s]+at)?[\s]*([^\@\()]+?)[\s]*(\@|\()([^\(\n]+):([0-9]+):([0-9]+)(\)?)$/; public static baseSize = 58; // '{"method":"","level":,"assembly":"","fileName":"","line":}'.length public sizeInBytes = 0; @@ -271,7 +511,7 @@ export class _StackFrame extends StackFrame implements ISerializable { if (typeof sourceFrame === "string") { const frame: string = sourceFrame; this.level = level; - this.method = ""; + this.method = NoMethod; this.assembly = strTrim(frame); this.fileName = ""; this.line = 0; diff --git a/shared/AppInsightsCommon/src/Telemetry/Metric.ts b/shared/AppInsightsCommon/src/Telemetry/Metric.ts index ae586e7a..8b923261 100644 --- a/shared/AppInsightsCommon/src/Telemetry/Metric.ts +++ b/shared/AppInsightsCommon/src/Telemetry/Metric.ts @@ -3,7 +3,7 @@ import { MetricData } from '../Interfaces/Contracts/Generated/MetricData'; import { ISerializable } from '../Interfaces/Telemetry/ISerializable'; -import { DataSanitizer } from './Common/DataSanitizer'; +import { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString } from './Common/DataSanitizer'; import { FieldType } from '../Enums'; import { DataPoint } from './Common/DataPoint'; import { IDiagnosticLogger } from '@microsoft/applicationinsights-core-js'; @@ -30,11 +30,11 @@ export class Metric extends MetricData implements ISerializable { dataPoint.count = count > 0 ? count : undefined; dataPoint.max = isNaN(max) || max === null ? undefined : max; dataPoint.min = isNaN(min) || min === null ? undefined : min; - dataPoint.name = DataSanitizer.sanitizeString(logger, name) || strNotSpecified; + dataPoint.name = dataSanitizeString(logger, name) || strNotSpecified; dataPoint.value = value; this.metrics = [dataPoint]; - this.properties = DataSanitizer.sanitizeProperties(logger, properties); - this.measurements = DataSanitizer.sanitizeMeasurements(logger, measurements); + this.properties = dataSanitizeProperties(logger, properties); + this.measurements = dataSanitizeMeasurements(logger, measurements); } } diff --git a/shared/AppInsightsCommon/src/Telemetry/PageView.ts b/shared/AppInsightsCommon/src/Telemetry/PageView.ts index 60ebd5c4..8842295c 100644 --- a/shared/AppInsightsCommon/src/Telemetry/PageView.ts +++ b/shared/AppInsightsCommon/src/Telemetry/PageView.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { PageViewData } from '../Interfaces/Contracts/Generated/PageViewData'; -import { DataSanitizer } from './Common/DataSanitizer'; +import { dataSanitizeId, dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from './Common/DataSanitizer'; import { ISerializable } from '../Interfaces/Telemetry/ISerializable'; import { FieldType } from '../Enums'; import { IDiagnosticLogger } from '@microsoft/applicationinsights-core-js'; @@ -30,13 +30,13 @@ export class PageView extends PageViewData implements ISerializable { constructor(logger: IDiagnosticLogger, name?: string, url?: string, durationMs?: number, properties?: {[key: string]: string}, measurements?: {[key: string]: number}, id?: string) { super(); - this.id = DataSanitizer.sanitizeId(logger, id); - this.url = DataSanitizer.sanitizeUrl(logger, url); - this.name = DataSanitizer.sanitizeString(logger, name) || strNotSpecified; + this.id = dataSanitizeId(logger, id); + this.url = dataSanitizeUrl(logger, url); + this.name = dataSanitizeString(logger, name) || strNotSpecified; if (!isNaN(durationMs)) { this.duration = msToTimeSpan(durationMs); } - this.properties = DataSanitizer.sanitizeProperties(logger, properties); - this.measurements = DataSanitizer.sanitizeMeasurements(logger, measurements); + this.properties = dataSanitizeProperties(logger, properties); + this.measurements = dataSanitizeMeasurements(logger, measurements); } } diff --git a/shared/AppInsightsCommon/src/Telemetry/PageViewPerformance.ts b/shared/AppInsightsCommon/src/Telemetry/PageViewPerformance.ts index 958d034b..e576c2e1 100644 --- a/shared/AppInsightsCommon/src/Telemetry/PageViewPerformance.ts +++ b/shared/AppInsightsCommon/src/Telemetry/PageViewPerformance.ts @@ -4,7 +4,7 @@ import { PageViewPerfData } from '../Interfaces/Contracts/Generated/PageViewPerfData'; import { FieldType } from '../Enums'; import { ISerializable } from '../Interfaces/Telemetry/ISerializable'; -import { DataSanitizer } from './Common/DataSanitizer'; +import { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from './Common/DataSanitizer'; import { IDiagnosticLogger, _InternalMessageId, LoggingSeverity } from '@microsoft/applicationinsights-core-js'; import { IPageViewPerformanceTelemetry } from '../Interfaces/IPageViewPerformanceTelemetry'; import { strNotSpecified } from '../Constants'; @@ -34,11 +34,11 @@ export class PageViewPerformance extends PageViewPerfData implements ISerializab */ constructor(logger: IDiagnosticLogger, name: string, url: string, unused: number, properties?: { [key: string]: string }, measurements?: { [key: string]: number }, cs4BaseData?: IPageViewPerformanceTelemetry) { super(); - this.url = DataSanitizer.sanitizeUrl(logger, url); - this.name = DataSanitizer.sanitizeString(logger, name) || strNotSpecified; + this.url = dataSanitizeUrl(logger, url); + this.name = dataSanitizeString(logger, name) || strNotSpecified; - this.properties = DataSanitizer.sanitizeProperties(logger, properties); - this.measurements = DataSanitizer.sanitizeMeasurements(logger, measurements); + this.properties = dataSanitizeProperties(logger, properties); + this.measurements = dataSanitizeMeasurements(logger, measurements); if (cs4BaseData) { this.domProcessing = cs4BaseData.domProcessing; diff --git a/shared/AppInsightsCommon/src/Telemetry/RemoteDependencyData.ts b/shared/AppInsightsCommon/src/Telemetry/RemoteDependencyData.ts index 63dbdf8d..7eac0e96 100644 --- a/shared/AppInsightsCommon/src/Telemetry/RemoteDependencyData.ts +++ b/shared/AppInsightsCommon/src/Telemetry/RemoteDependencyData.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -import { DataSanitizer } from './Common/DataSanitizer'; +import { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from './Common/DataSanitizer'; import { FieldType } from '../Enums'; import { ISerializable } from '../Interfaces/Telemetry/ISerializable'; import { AjaxHelperParseDependencyPath} from '../Util'; @@ -51,17 +51,17 @@ export class RemoteDependencyData extends GeneratedRemoteDependencyData implemen this.success = success; this.resultCode = resultCode + ""; - this.type = DataSanitizer.sanitizeString(logger, requestAPI); + this.type = dataSanitizeString(logger, requestAPI); const dependencyFields = AjaxHelperParseDependencyPath(logger, absoluteUrl, method, commandName); - this.data = DataSanitizer.sanitizeUrl(logger, commandName) || dependencyFields.data; // get a value from hosturl if commandName not available - this.target = DataSanitizer.sanitizeString(logger, dependencyFields.target); + this.data = dataSanitizeUrl(logger, commandName) || dependencyFields.data; // get a value from hosturl if commandName not available + this.target = dataSanitizeString(logger, dependencyFields.target); if (correlationContext) { this.target = `${this.target} | ${correlationContext}`; } - this.name = DataSanitizer.sanitizeString(logger, dependencyFields.name); + this.name = dataSanitizeString(logger, dependencyFields.name); - this.properties = DataSanitizer.sanitizeProperties(logger, properties); - this.measurements = DataSanitizer.sanitizeMeasurements(logger, measurements); + this.properties = dataSanitizeProperties(logger, properties); + this.measurements = dataSanitizeMeasurements(logger, measurements); } } diff --git a/shared/AppInsightsCommon/src/Telemetry/Trace.ts b/shared/AppInsightsCommon/src/Telemetry/Trace.ts index 2ac12058..a0e2c624 100644 --- a/shared/AppInsightsCommon/src/Telemetry/Trace.ts +++ b/shared/AppInsightsCommon/src/Telemetry/Trace.ts @@ -3,7 +3,7 @@ import { MessageData } from '../Interfaces/Contracts/Generated/MessageData'; import { ISerializable } from '../Interfaces/Telemetry/ISerializable'; -import { DataSanitizer } from './Common/DataSanitizer'; +import { dataSanitizeMessage, dataSanitizeProperties, dataSanitizeMeasurements } from './Common/DataSanitizer'; import { FieldType } from '../Enums'; import { SeverityLevel } from '../Interfaces/Contracts/Generated/SeverityLevel'; import { IDiagnosticLogger } from '@microsoft/applicationinsights-core-js'; @@ -27,9 +27,9 @@ export class Trace extends MessageData implements ISerializable { constructor(logger: IDiagnosticLogger, message: string, severityLevel?: SeverityLevel, properties?: any, measurements?: { [key: string]: number }) { super(); message = message || strNotSpecified; - this.message = DataSanitizer.sanitizeMessage(logger, message); - this.properties = DataSanitizer.sanitizeProperties(logger, properties); - this.measurements = DataSanitizer.sanitizeMeasurements(logger, measurements); + this.message = dataSanitizeMessage(logger, message); + this.properties = dataSanitizeProperties(logger, properties); + this.measurements = dataSanitizeMeasurements(logger, measurements); if (severityLevel) { this.severityLevel = severityLevel; diff --git a/shared/AppInsightsCommon/src/TelemetryItemCreator.ts b/shared/AppInsightsCommon/src/TelemetryItemCreator.ts index c079f028..b2cb3b8f 100644 --- a/shared/AppInsightsCommon/src/TelemetryItemCreator.ts +++ b/shared/AppInsightsCommon/src/TelemetryItemCreator.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -import { DataSanitizer } from "./Telemetry/Common/DataSanitizer"; +import { dataSanitizeString } from "./Telemetry/Common/DataSanitizer"; import { ITelemetryItem, IDiagnosticLogger, objForEachKey, isNullOrUndefined, toISOString } from "@microsoft/applicationinsights-core-js"; import { strNotSpecified } from "./Constants"; @@ -24,7 +24,7 @@ export class TelemetryItemCreator { customProperties?: { [key: string]: any }, systemProperties?: { [key: string]: any }): ITelemetryItem { - envelopeName = DataSanitizer.sanitizeString(logger, envelopeName) || strNotSpecified; + envelopeName = dataSanitizeString(logger, envelopeName) || strNotSpecified; if (isNullOrUndefined(item) || isNullOrUndefined(baseType) || diff --git a/shared/AppInsightsCommon/src/Util.ts b/shared/AppInsightsCommon/src/Util.ts index 06d2bfce..98738a3c 100644 --- a/shared/AppInsightsCommon/src/Util.ts +++ b/shared/AppInsightsCommon/src/Util.ts @@ -13,7 +13,7 @@ import { setCookie as coreSetCookie, deleteCookie as coreDeleteCookie } from "@microsoft/applicationinsights-core-js"; import { RequestHeaders } from "./RequestResponseHeaders"; -import { DataSanitizer } from "./Telemetry/Common/DataSanitizer"; +import { dataSanitizeString } from "./Telemetry/Common/DataSanitizer"; import { ICorrelationConfig } from "./Interfaces/ICorrelationConfig"; import { createDomEvent } from './DomHelperFuncs'; import { stringToBoolOrDefault, msToTimeSpan, isBeaconApiSupported, isCrossOriginError, getExtensionByName } from "./HelperFuncs"; @@ -430,9 +430,9 @@ export function AjaxHelperParseDependencyPath(logger: IDiagnosticLogger, absolut pathName = "/" + pathName; } data = parsedUrl.pathname; - name = DataSanitizer.sanitizeString(logger, method ? method + " " + pathName : pathName); + name = dataSanitizeString(logger, method ? method + " " + pathName : pathName); } else { - name = DataSanitizer.sanitizeString(logger, absoluteUrl); + name = dataSanitizeString(logger, absoluteUrl); } } } else { diff --git a/shared/AppInsightsCommon/src/applicationinsights-common.ts b/shared/AppInsightsCommon/src/applicationinsights-common.ts index 94492ea8..0dd20590 100644 --- a/shared/AppInsightsCommon/src/applicationinsights-common.ts +++ b/shared/AppInsightsCommon/src/applicationinsights-common.ts @@ -35,7 +35,12 @@ export { SeverityLevel } from './Interfaces/Contracts/Generated/SeverityLevel'; export { IConfig, ConfigurationManager } from './Interfaces/IConfig'; export { IChannelControlsAI } from './Interfaces/IChannelControlsAI'; export { IContextTagKeys, ContextTagKeys } from './Interfaces/Contracts/Generated/ContextTagKeys'; -export { DataSanitizer } from './Telemetry/Common/DataSanitizer'; +export { + DataSanitizerValues, IDataSanitizer, DataSanitizer, + dataSanitizeKeyAndAddUniqueness, dataSanitizeKey, dataSanitizeString, dataSanitizeUrl, dataSanitizeMessage, + dataSanitizeException, dataSanitizeProperties, dataSanitizeMeasurements, dataSanitizeId, dataSanitizeInput, + dsPadNumber +} from './Telemetry/Common/DataSanitizer'; export { TelemetryItemCreator } from './TelemetryItemCreator'; export { ICorrelationConfig } from './Interfaces/ICorrelationConfig'; export { IAppInsights } from './Interfaces/IAppInsights'; diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/EnvUtils.ts b/shared/AppInsightsCore/src/JavaScriptSDK/EnvUtils.ts index f97a4cb1..acf00ac3 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/EnvUtils.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/EnvUtils.ts @@ -5,7 +5,7 @@ import { getGlobal, strShimUndefined, strShimObject, strShimPrototype, strShimFunction } from "@microsoft/applicationinsights-shims"; -import { strContains } from "./HelperFuncs"; +import { isString, strContains } from "./HelperFuncs"; /** * This file exists to hold environment utilities that are required to check and @@ -271,15 +271,16 @@ export function isIE() { * Gets IE version returning the document emulation mode if we are running on IE, or null otherwise */ export function getIEVersion(userAgentStr: string = null): number { - let myNav = userAgentStr ? userAgentStr.toLowerCase() : ""; if (!userAgentStr) { let navigator = getNavigator() || ({} as Navigator); - myNav = navigator ? (navigator.userAgent || "").toLowerCase() : ""; + userAgentStr = navigator ? (navigator.userAgent || "").toLowerCase() : ""; } - if (strContains(myNav, strMsie)) { - return parseInt(myNav.split(strMsie)[1]); - } else if (strContains(myNav, strTrident)) { - let tridentVer = parseInt(myNav.split(strTrident)[1]); + + var ua = (userAgentStr || "").toLowerCase(); + if (strContains(ua, strMsie)) { + return parseInt(ua.split(strMsie)[1]); + } else if (strContains(ua, strTrident)) { + let tridentVer = parseInt(ua.split(strTrident)[1]); if (tridentVer) { return tridentVer + 4; } @@ -302,3 +303,13 @@ export function dumpObj(object: any): string { return objectTypeDump + propertyValueDump; } + +export function isSafari(userAgentStr ?: string) { + if (!userAgentStr || !isString(userAgentStr)) { + let navigator = getNavigator() || ({} as Navigator); + userAgentStr = navigator ? (navigator.userAgent || "").toLowerCase() : ""; + } + + var ua = (userAgentStr || "").toLowerCase(); + return (ua.indexOf('safari') >= 0); +} diff --git a/shared/AppInsightsCore/src/JavaScriptSDK/HelperFuncs.ts b/shared/AppInsightsCore/src/JavaScriptSDK/HelperFuncs.ts index 1aeb5650..55ccb432 100644 --- a/shared/AppInsightsCore/src/JavaScriptSDK/HelperFuncs.ts +++ b/shared/AppInsightsCore/src/JavaScriptSDK/HelperFuncs.ts @@ -171,8 +171,8 @@ export function strEndsWith(value: string, search: string) { * 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. -*/ + * @returns true if the given search value is found at the start of the string, otherwise false. + */ export function strStartsWith(value: string, checkValue: string) { // Using helper for performance and because string startsWith() is not available on IE let result = false; diff --git a/shared/AppInsightsCore/src/applicationinsights-core-js.ts b/shared/AppInsightsCore/src/applicationinsights-core-js.ts index 35d7d411..dba06f16 100644 --- a/shared/AppInsightsCore/src/applicationinsights-core-js.ts +++ b/shared/AppInsightsCore/src/applicationinsights-core-js.ts @@ -30,7 +30,7 @@ export { export { getGlobalInst, hasWindow, getWindow, hasDocument, getDocument, getCrypto, getMsCrypto, hasNavigator, getNavigator, hasHistory, getHistory, getLocation, getPerformance, hasJSON, getJSON, - isReactNative, getConsole, dumpObj, isIE, getIEVersion, + isReactNative, getConsole, dumpObj, isIE, getIEVersion, isSafari, setEnableEnvMocks } from "./JavaScriptSDK/EnvUtils"; export {