Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Console] Convert all non-autocomplete lib files to typescript #4150

Merged
merged 8 commits into from
Jul 26, 2023
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
- [Console] Remove unused ul element and its custom styling ([#3993](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/3993))
- Fix EUI/OUI type errors ([#3798](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/3798))
- Remove unused Sass in `tile_map` plugin ([#4110](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/4110))
- [Console] Convert all non-autocomplete lib files to TypeScript ([#4150](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/4150))

### 🔩 Tests

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,10 @@ describe('CURL', () => {
if (fixture.trim() === '') {
return;
}
fixture = fixture.split(/^-+$/m);
const name = fixture[0].trim();
const curlText = fixture[1];
const response = fixture[2].trim();
const fixtureParts = fixture.split(/^-+$/m);
const name = fixtureParts[0].trim();
const curlText = fixtureParts[1];
const response = fixtureParts[2].trim();

test('cURL Detection - ' + name, function () {
expect(detectCURL(curlText)).toBe(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@
* under the License.
*/

function detectCURLinLine(line) {
function detectCURLinLine(line: string) {
// returns true if text matches a curl request
return line.match(/^\s*?curl\s+(-X[A-Z]+)?\s*['"]?.*?['"]?(\s*$|\s+?-d\s*?['"])/);
}

export function detectCURL(text) {
export function detectCURL(text: string) {
// returns true if text matches a curl request
if (!text) return false;
for (const line of text.split('\n')) {
Expand All @@ -44,10 +44,10 @@ export function detectCURL(text) {
return false;
}

export function parseCURL(text) {
export function parseCURL(text: string) {
let state = 'NONE';
const out = [];
let body = [];
const out: string[] = [];
let body: string[] = [];
let line = '';
const lines = text.trim().split('\n');
let matches;
Expand Down Expand Up @@ -79,12 +79,12 @@ export function parseCURL(text) {
if (lines.length === 0) {
return false;
}
line = lines.shift().replace(/[\r\n]+/g, '\n') + '\n';
line = lines.shift()?.replace(/[\r\n]+/g, '\n') + '\n';
joshuarrrr marked this conversation as resolved.
Show resolved Hide resolved
return true;
}

function unescapeLastBodyEl() {
const str = body.pop().replace(/\\([\\"'])/g, '$1');
const str = (body.pop() as string).replace(/\\([\\"'])/g, '$1');
body.push(str);
}

Expand Down Expand Up @@ -115,11 +115,11 @@ export function parseCURL(text) {
// If the pattern matches, then the state is about to change,
// so add the capture to the body and detect the next state
// Otherwise add the whole line
function consumeMatching(pattern) {
const matches = line.match(pattern);
if (matches) {
body.push(matches[1]);
line = line.substr(matches[0].length);
function consumeMatching(pattern: RegExp) {
const patternMatches = line.match(pattern);
if (patternMatches) {
body.push(patternMatches[1]);
line = line.substr(patternMatches[0].length);
detectQuote();
} else {
body.push(line);
Expand All @@ -130,9 +130,9 @@ export function parseCURL(text) {
function parseCurlLine() {
let verb = 'GET';
let request = '';
let matches;
if ((matches = line.match(CurlVerb))) {
verb = matches[1];
let curlMatches: RegExpMatchArray | null;
if ((curlMatches = line.match(CurlVerb))) {
verb = curlMatches[1];
}

// JS regexen don't support possessive quantifiers, so
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,10 @@ import _ from 'lodash';
import { populateContext } from '../../autocomplete/engine';

import '../../../application/models/sense_editor/sense_editor.test.mocks';
import * as osd from '../../osd';
import * as osd from '../osd';
import * as mappings from '../../mappings/mappings';
import { PartialAutoCompleteContext } from '../../autocomplete/components/autocomplete_component';
import { Term } from '../../autocomplete/types';

describe('Knowledge base', () => {
beforeEach(() => {
Expand Down Expand Up @@ -67,17 +69,21 @@ describe('Knowledge base', () => {
},
};

function testUrlContext(tokenPath, otherTokenValues, expectedContext) {
function testUrlContext(
tokenPath: Array<string | string[]>,
otherTokenValues: string[],
expectedContext: PartialAutoCompleteContext
) {
if (expectedContext.autoCompleteSet) {
expectedContext.autoCompleteSet = _.map(expectedContext.autoCompleteSet, function (t) {
if (_.isString(t)) {
t = { name: t };
expectedContext.autoCompleteSet = _.map(expectedContext.autoCompleteSet, function (term) {
if (_.isString(term)) {
term = { name: term };
}
return t;
return term;
});
}

const context = { otherTokenValues: otherTokenValues };
const context: PartialAutoCompleteContext = { otherTokenValues };
populateContext(
tokenPath,
context,
Expand All @@ -88,16 +94,16 @@ describe('Knowledge base', () => {

// override context to just check on id
if (context.endpoint) {
context.endpoint = context.endpoint.id;
context.endpoint = (context as any).endpoint.id;
}

delete context.otherTokenValues;

function norm(t) {
if (_.isString(t)) {
return { name: t };
function norm(term: Term) {
if (_.isString(term)) {
return { name: term };
}
return t;
return term;
}

if (context.autoCompleteSet) {
Expand All @@ -113,34 +119,35 @@ describe('Knowledge base', () => {
expect(context).toEqual(expectedContext);
}

function t(term) {
function t(term: string) {
return { name: term, meta: 'type' };
}

function i(term) {
function i(term: string) {
return { name: term, meta: 'index' };
}

function indexTest(name, tokenPath, otherTokenValues, expectedContext) {
function indexTest(
name: string,
tokenPath: Array<string | string[]>,
otherTokenValues: string[],
expectedContext: PartialAutoCompleteContext
) {
test(name, function () {
// eslint-disable-next-line new-cap
const testApi = new osd._test.loadApisFromJson(
{
indexTest: {
endpoints: {
_multi_indices: {
patterns: ['{indices}/_multi_indices'],
},
_single_index: { patterns: ['{index}/_single_index'] },
_no_index: {
// testing default patters
// patterns: ["_no_index"]
},
const testApi = osd._test.loadApisFromJson({
indexTest: {
endpoints: {
_multi_indices: {
patterns: ['{indices}/_multi_indices'],
},
_single_index: { patterns: ['{index}/_single_index'] },
_no_index: {
// testing default patters
// patterns: ["_no_index"]
},
},
},
osd._test.globalUrlComponentFactories
);
});

osd.setActiveApi(testApi);

Expand Down Expand Up @@ -171,20 +178,22 @@ describe('Knowledge base', () => {
autoCompleteSet: ['_multi_indices'],
});

function typeTest(name, tokenPath, otherTokenValues, expectedContext) {
function typeTest(
name: string,
tokenPath: Array<string | string[]>,
otherTokenValues: string[],
expectedContext: PartialAutoCompleteContext
) {
test(name, function () {
const testApi = osd._test.loadApisFromJson(
{
typeTest: {
endpoints: {
_multi_types: { patterns: ['{indices}/{types}/_multi_types'] },
_single_type: { patterns: ['{indices}/{type}/_single_type'] },
_no_types: { patterns: ['{indices}/_no_types'] },
},
const testApi = osd._test.loadApisFromJson({
typeTest: {
endpoints: {
_multi_types: { patterns: ['{indices}/{types}/_multi_types'] },
_single_type: { patterns: ['{indices}/{type}/_single_type'] },
_no_types: { patterns: ['{indices}/_no_types'] },
},
},
osd._test.globalUrlComponentFactories
);
});
osd.setActiveApi(testApi);

mappings.loadMappings(MAPPING);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,14 @@
*/

import _ from 'lodash';
joshuarrrr marked this conversation as resolved.
Show resolved Hide resolved
import { UrlPatternMatcher } from '../autocomplete/components';
import { SharedComponent, UrlPatternMatcher } from '../autocomplete/components';
import { UrlParams } from '../autocomplete/url_params';
import {
globalsOnlyAutocompleteComponents,
compileBodyDescription,
} from '../autocomplete/body_completer';
import { Endpoint } from '../autocomplete/types';
joshuarrrr marked this conversation as resolved.
Show resolved Hide resolved
import { ParametrizedComponentFactories } from './osd';
joshuarrrr marked this conversation as resolved.
Show resolved Hide resolved

/**
*
Expand All @@ -44,41 +46,50 @@ import {
* @constructor
* @param bodyParametrizedComponentFactories same as urlParametrizedComponentFactories but used for body compilation
*/
function Api(urlParametrizedComponentFactories, bodyParametrizedComponentFactories) {
this.globalRules = Object.create(null);
this.endpoints = Object.create(null);
this.urlPatternMatcher = new UrlPatternMatcher(urlParametrizedComponentFactories);
this.globalBodyComponentFactories = bodyParametrizedComponentFactories;
this.name = '';
}
export class Api {
globalRules: Record<string, any>;
endpoints: Record<string, Endpoint>;
urlPatternMatcher: UrlPatternMatcher;
globalBodyComponentFactories: ParametrizedComponentFactories | undefined;
name: string;

constructor(
urlParametrizedComponentFactories?: ParametrizedComponentFactories,
bodyParametrizedComponentFactories?: ParametrizedComponentFactories
) {
this.globalRules = Object.create(null);
this.endpoints = Object.create(null);
this.urlPatternMatcher = new UrlPatternMatcher(urlParametrizedComponentFactories);
this.globalBodyComponentFactories = bodyParametrizedComponentFactories;
this.name = '';
}

(function (cls) {
cls.addGlobalAutocompleteRules = function (parentNode, rules) {
addGlobalAutocompleteRules(parentNode: string, rules: Record<string, any>): void {
this.globalRules[parentNode] = compileBodyDescription(
'GLOBAL.' + parentNode,
rules,
this.globalBodyComponentFactories
);
};
}

cls.getGlobalAutocompleteComponents = function (term, throwOnMissing) {
const result = this.globalRules[term];
getGlobalAutocompleteComponents(term: string, throwOnMissing?: boolean) {
joshuarrrr marked this conversation as resolved.
Show resolved Hide resolved
const result: SharedComponent[] = this.globalRules[term];
joshuarrrr marked this conversation as resolved.
Show resolved Hide resolved
if (_.isUndefined(result) && (throwOnMissing || _.isUndefined(throwOnMissing))) {
throw new Error("failed to resolve global components for ['" + term + "']");
}
return result;
};
}

cls.addEndpointDescription = function (endpoint, description) {
const copiedDescription = {};
addEndpointDescription(endpoint: string, description?: Record<string, any>) {
joshuarrrr marked this conversation as resolved.
Show resolved Hide resolved
const copiedDescription: Record<string, any> = {};
_.assign(copiedDescription, description || {});
_.defaults(copiedDescription, {
id: endpoint,
patterns: [endpoint],
methods: ['GET'],
});
_.each(copiedDescription.patterns, (p) => {
this.urlPatternMatcher.addEndpoint(p, copiedDescription);
this.urlPatternMatcher.addEndpoint(p, copiedDescription as Endpoint);
});

copiedDescription.paramsAutocomplete = new UrlParams(copiedDescription.url_params);
Expand All @@ -88,25 +99,23 @@ function Api(urlParametrizedComponentFactories, bodyParametrizedComponentFactori
this.globalBodyComponentFactories
);

this.endpoints[endpoint] = copiedDescription;
};
this.endpoints[endpoint] = copiedDescription as Endpoint;
}

cls.getEndpointDescriptionByEndpoint = function (endpoint) {
getEndpointDescriptionByEndpoint(endpoint: string) {
return this.endpoints[endpoint];
};
}

cls.getTopLevelUrlCompleteComponents = function (method) {
getTopLevelUrlCompleteComponents(method: string) {
return this.urlPatternMatcher.getTopLevelComponents(method);
};
}

cls.getUnmatchedEndpointComponents = function () {
getUnmatchedEndpointComponents() {
return globalsOnlyAutocompleteComponents();
};
}

cls.clear = function () {
clear(): void {
this.endpoints = {};
this.globalRules = {};
};
})(Api.prototype);

export default Api;
}
}
Loading