Skip to content

Commit

Permalink
Add eslint validation (#905)
Browse files Browse the repository at this point in the history
* Add eslint validation

* Fix

* Update dependencies

* Run only on node 14

* WIP
  • Loading branch information
hectorhdzg authored Feb 8, 2022
1 parent 6a10cd5 commit 2763731
Show file tree
Hide file tree
Showing 63 changed files with 6,073 additions and 254 deletions.
3 changes: 3 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
**/*.js
/out
/Tests
41 changes: 41 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:security/recommended"
],
"plugins": [
"security"
],
"rules": {
"quotes": ["warn", "double"], // Enabled for auto fixing
"prefer-const": "off",
"prefer-spread": "off",
"no-var": "off",
"no-extra-boolean-cast": "off",
"prefer-rest-params": "off",
"no-case-declarations": "off",
"no-prototype-builtins": "off",
"no-useless-escape": "off", // Suppressing Error -- need to Review Later
"no-trailing-spaces": [ "warn", { "skipBlankLines": true }],// Enabled for auto fixing
"no-const-assign": "error",
"comma-dangle": [ "error", "never" ], // Enabled for auto fixing
"security/detect-object-injection": "off", // Suppress Warning -- need to Review Later
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/no-unused-vars": [ "warn", { "vars": "all", "args": "none", "argsIgnorePattern": "^_", "ignoreRestSiblings": true } ],
"@typescript-eslint/triple-slash-reference": "off",
"@typescript-eslint/no-inferrable-types": "off",
"@typescript-eslint/no-this-alias": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-empty-interface": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-extra-semi": "error", // Enabled for auto fixing
"@typescript-eslint/no-non-null-assertion": "error"
}
}
1 change: 1 addition & 0 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@ jobs:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm run build --if-present
- run: if [[ ${{ matrix.node-version }} == 14 ]]; then npm run lint; fi;
- run: npm test
4 changes: 2 additions & 2 deletions AutoCollection/AsyncHooksScopeManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,11 @@ export class OpenTelemetryScopeManagerWrapper {
...span.spanContext(),
traceFlags: span.spanContext().traceFlags
};
let parentId = parentSpanId ? `|${spanContext.traceId}.${parentSpanId}.` : spanContext.traceId;
let parentId = parentSpanId ? `|${spanContext.traceId}.${parentSpanId}.` : spanContext.traceId;
const aiContext = CorrelationContextManager.getCurrentContext();
if (aiContext) {
context.traceId = aiContext.operation.id;
// If parent is no available use current context
// If parent is no available use current context
if (!parentSpanId) {
parentId = aiContext.operation.parentId;
}
Expand Down
1 change: 0 additions & 1 deletion AutoCollection/Console.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import TelemetryClient = require("../Library/TelemetryClient");
import Logging = require("../Library/Logging");

import * as DiagChannel from "./diagnostic-channel/initialization";

Expand Down
10 changes: 5 additions & 5 deletions AutoCollection/CorrelationContextManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,9 @@ export class CorrelationContextManager {

if (typeof this.cls === "undefined") {
if ((CorrelationContextManager.forceClsHooked === true) || (CorrelationContextManager.forceClsHooked === undefined && CorrelationContextManager.shouldUseClsHooked())) {
this.cls = require('cls-hooked');
this.cls = require("cls-hooked");
} else {
this.cls = require('continuation-local-storage');
this.cls = require("continuation-local-storage");
}
}

Expand Down Expand Up @@ -228,7 +228,7 @@ export class CorrelationContextManager {
: parser.getOperationName({}),
parser && parser.getCorrelationContextHeader() || undefined,
traceparent,
tracestate,
tracestate
);

return correlationContext;
Expand All @@ -245,7 +245,7 @@ export class CorrelationContextManager {
parser.getOperationName({}),
parser.getCorrelationContextHeader(),
traceparent,
tracestate,
tracestate
);

return correlationContext;
Expand All @@ -268,7 +268,7 @@ export class CorrelationContextManager {
public static reset() {
if (CorrelationContextManager.hasEverEnabled) {
CorrelationContextManager.session = null;
CorrelationContextManager.session = this.cls.createNamespace('AI-CLS-Session');
CorrelationContextManager.session = this.cls.createNamespace("AI-CLS-Session");
}
}

Expand Down
1 change: 0 additions & 1 deletion AutoCollection/Exceptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ class AutoCollectExceptions {
public enable(isEnabled: boolean) {
if (isEnabled) {
this._isInitialized = true;
var self = this;
if (!this._exceptionListenerHandle) {
// For scenarios like Promise.reject(), an error won't be passed to the handle. Create a placeholder
// error for these scenarios.
Expand Down
14 changes: 7 additions & 7 deletions AutoCollection/HttpDependencies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ import Traceparent = require("../Library/Traceparent");
import * as DiagChannel from "./diagnostic-channel/initialization";

class AutoCollectHttpDependencies {
public static disableCollectionRequestOption = 'disableAppInsightsAutoCollection';
public static disableCollectionRequestOption = "disableAppInsightsAutoCollection";

public static INSTANCE: AutoCollectHttpDependencies;

private static requestNumber = 1;
private static alreadyAutoCollectedFlag = '_appInsightsAutoCollected';
private static alreadyAutoCollectedFlag = "_appInsightsAutoCollected";

private _client: TelemetryClient;
private _isEnabled: boolean;
Expand Down Expand Up @@ -64,7 +64,7 @@ class AutoCollectHttpDependencies {
!(<any>request)[AutoCollectHttpDependencies.alreadyAutoCollectedFlag];

// If someone else patched traceparent headers onto this request
if ((<any>options).headers && (<any>options).headers['user-agent'] && (<any>options).headers['user-agent'].toString().indexOf('azsdk-js') !== -1) {
if ((<any>options).headers && (<any>options).headers["user-agent"] && (<any>options).headers["user-agent"].toString().indexOf("azsdk-js") !== -1) {
shouldCollect = false;
}

Expand Down Expand Up @@ -151,7 +151,7 @@ class AutoCollectHttpDependencies {
uniqueTraceparent = traceparent.toString();
uniqueRequestId = traceparent.getBackCompatRequestId();
} else {
uniqueRequestId = currentContext && currentContext.operation && (currentContext.operation.parentId + AutoCollectHttpDependencies.requestNumber++ + '.');
uniqueRequestId = currentContext && currentContext.operation && (currentContext.operation.parentId + AutoCollectHttpDependencies.requestNumber++ + ".");
}

// Add the source correlationId to the request headers, if a value was not already provided.
Expand Down Expand Up @@ -205,7 +205,7 @@ class AutoCollectHttpDependencies {

// Collect dependency telemetry about the request when it finishes.
if (telemetry.request.on) {
telemetry.request.on('response', (response: http.ClientResponse) => {
telemetry.request.on("response", (response: http.ClientResponse) => {
requestParser.onResponse(response);

var dependencyTelemetry = requestParser.getDependencyTelemetry(telemetry, uniqueRequestId);
Expand All @@ -217,7 +217,7 @@ class AutoCollectHttpDependencies {

client.trackDependency(dependencyTelemetry);
});
telemetry.request.on('error', (error: Error) => {
telemetry.request.on("error", (error: Error) => {
requestParser.onError(error);

var dependencyTelemetry = requestParser.getDependencyTelemetry(telemetry, uniqueRequestId);
Expand All @@ -229,7 +229,7 @@ class AutoCollectHttpDependencies {

client.trackDependency(dependencyTelemetry);
});
telemetry.request.on('abort', () => {
telemetry.request.on("abort", () => {
requestParser.onError(new Error());

var dependencyTelemetry = requestParser.getDependencyTelemetry(telemetry, uniqueRequestId);
Expand Down
31 changes: 21 additions & 10 deletions AutoCollection/HttpDependencyParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ class HttpDependencyParser extends RequestParser {

}
catch (ex) { // Invalid URL
// Ignore error
}
if (this.correlationId) {
remoteDependencyType = Contracts.RemoteDependencyDataConstants.TYPE_AI;
Expand Down Expand Up @@ -112,13 +113,15 @@ class HttpDependencyParser extends RequestParser {
* necessary because a ClientRequest object does not expose a url property.
*/
private static _getUrlFromRequestOptions(options: any, request: http.ClientRequest) {
if (typeof options === 'string') {
if (typeof options === "string") {
if (options.indexOf("http://") === 0 || options.indexOf("https://") === 0) {
// protocol exists, parse normally
try {
options = new url.URL(options);
}
catch (ex) { }
catch (ex) {
// Ignore error
}
} else {
// protocol not found, insert http/https where appropriate
try {
Expand All @@ -129,9 +132,11 @@ class HttpDependencyParser extends RequestParser {
options = new url.URL("http://" + options);
}
}
catch (ex) { }
catch (ex) {
// Ignore error
}
}
} else if (options && typeof url.URL === 'function' && options instanceof url.URL) {
} else if (options && typeof url.URL === "function" && options instanceof url.URL) {
return url.format(options);
} else {
// Avoid modifying the original options object.
Expand All @@ -149,23 +154,27 @@ class HttpDependencyParser extends RequestParser {
if (options.path && options.host) {
// need to force a protocol to make parameter valid - base url is required when input is a relative url
try {
const parsedQuery = new url.URL(options.path, 'http://' + options.host + options.path);
const parsedQuery = new url.URL(options.path, "http://" + options.host + options.path);
options.pathname = parsedQuery.pathname;
options.search = parsedQuery.search;
}
catch (ex) { }
catch (ex) {
// Ignore error
}
}

// Sometimes the hostname is provided but not the host
// Add in the path when this occurs
if (options.path && options.hostname && !options.host) {
// need to force a protocol to make parameter valid - base url is required when input is a relative url
try {
const parsedQuery = new url.URL(options.path, 'http://' + options.hostname + options.path);
const parsedQuery = new url.URL(options.path, "http://" + options.hostname + options.path);
options.pathname = parsedQuery.pathname;
options.search = parsedQuery.search;
}
catch (ex) { }
catch (ex) {
// Ignore error
}
}

// Similarly, url.format ignores hostname and port if host is specified,
Expand All @@ -183,12 +192,14 @@ class HttpDependencyParser extends RequestParser {
delete options.host;
}
}
catch (ex) { }
catch (ex) {
// Ignore error
}
}

// Mix in default values used by http.request and others
options.protocol = options.protocol || ((<any>request).agent && (<any>request).agent.protocol) || ((<any>request).protocol) || undefined;
options.hostname = options.hostname || 'localhost';
options.hostname = options.hostname || "localhost";

return url.format(options);
}
Expand Down
10 changes: 7 additions & 3 deletions AutoCollection/HttpRequestParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ class HttpRequestParser extends RequestParser {
name += " " + new url.URL(this.url).pathname;
}
catch (ex) { // Invalid URL
// Ignore error
}

var requestTelemetry: Contracts.RequestTelemetry & Contracts.Identified = {
Expand Down Expand Up @@ -152,6 +153,7 @@ class HttpRequestParser extends RequestParser {
pathName = new url.URL(this.url).pathname;
}
catch (ex) { // Invalid URL
// Ignore error
}
let operationName = this.method;
if (pathName) {
Expand Down Expand Up @@ -189,7 +191,7 @@ class HttpRequestParser extends RequestParser {

var protocol = (encrypted || request.headers["x-forwarded-proto"] == "https") ? "https" : "http";

var baseUrl = protocol + '://' + request.headers.host + '/';
var baseUrl = protocol + "://" + request.headers.host + "/";

var pathName = "";
var search = "";
Expand All @@ -198,7 +200,9 @@ class HttpRequestParser extends RequestParser {
pathName = requestUrl.pathname;
search = requestUrl.search;
}
catch (ex) { }
catch (ex) {
// Ignore errors
}
var absoluteUrl = url.format({
protocol: protocol,
host: request.headers.host,
Expand Down Expand Up @@ -241,7 +245,7 @@ class HttpRequestParser extends RequestParser {

private _getId(name: string) {
var cookie = (this.rawHeaders && this.rawHeaders["cookie"] &&
typeof this.rawHeaders["cookie"] === 'string' && this.rawHeaders["cookie"]) || "";
typeof this.rawHeaders["cookie"] === "string" && this.rawHeaders["cookie"]) || "";
var value = HttpRequestParser.parseId(Util.getCookie(name, cookie));
return value;
}
Expand Down
12 changes: 6 additions & 6 deletions AutoCollection/HttpRequests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class AutoCollectHttpRequests {

public static INSTANCE: AutoCollectHttpRequests;

private static alreadyAutoCollectedFlag = '_appInsightsAutoCollected';
private static alreadyAutoCollectedFlag = "_appInsightsAutoCollected";

private _client: TelemetryClient;
private _isEnabled: boolean;
Expand Down Expand Up @@ -82,8 +82,8 @@ class AutoCollectHttpRequests {
if (!onRequest) {
return undefined;
}
if (typeof onRequest !== 'function') {
throw new Error('onRequest handler must be a function');
if (typeof onRequest !== "function") {
throw new Error("onRequest handler must be a function");
}
return (request: http.ServerRequest, response: http.ServerResponse) => {
CorrelationContextManager.wrapEmitter(request);
Expand Down Expand Up @@ -135,8 +135,8 @@ class AutoCollectHttpRequests {
const originalAddListener = server.addListener.bind(server);
server.addListener = (eventType: string, eventHandler: Function) => {
switch (eventType) {
case 'request':
case 'checkContinue':
case "request":
case "checkContinue":
return originalAddListener(eventType, wrapOnRequestHandler(eventHandler));
default:
return originalAddListener(eventType, eventHandler);
Expand All @@ -153,7 +153,7 @@ class AutoCollectHttpRequests {
// function createServer(options: ServerOptions, requestListener?: RequestListener): Server;
http.createServer = (param1?: Object, param2?: Function) => {
// todo: get a pointer to the server so the IP address can be read from server.address
if (param2 && typeof param2 === 'function') {
if (param2 && typeof param2 === "function") {
const server: http.Server = originalHttpServer(param1, wrapOnRequestHandler(param2));
wrapServerEventHandler(server);
return server;
Expand Down
8 changes: 4 additions & 4 deletions AutoCollection/NativePerformance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ export class AutoCollectNativePerformance {
return;
}

const name = `Event Loop CPU Time`;
const name = "Event Loop CPU Time";
const stdDev = Math.sqrt(metrics.sumSquares / metrics.count - Math.pow(metrics.total / metrics.count, 2)) || 0;
this._client.trackMetric({
name: name,
Expand Down Expand Up @@ -251,23 +251,23 @@ export class AutoCollectNativePerformance {
const { heapUsed, heapTotal, rss } = memoryUsage;

this._client.trackMetric({
name: `Memory Usage (Heap)`,
name: "Memory Usage (Heap)",
value: heapUsed,
count: 1,
tagOverrides: {
[this._client.context.keys.internalSdkVersion]: "node-nativeperf:" + Context.sdkVersion
}
});
this._client.trackMetric({
name: `Memory Total (Heap)`,
name: "Memory Total (Heap)",
value: heapTotal,
count: 1,
tagOverrides: {
[this._client.context.keys.internalSdkVersion]: "node-nativeperf:" + Context.sdkVersion
}
});
this._client.trackMetric({
name: `Memory Usage (Non-Heap)`,
name: "Memory Usage (Non-Heap)",
value: rss - heapTotal,
count: 1,
tagOverrides: {
Expand Down
Loading

0 comments on commit 2763731

Please sign in to comment.