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 @@ -101,6 +101,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
- [Saved Objects Management] Add new or remove extra tags and styles ([#4069](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/4069))
- [Console] Migrate `/lib/mappings/` module to TypeScript ([#4008](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/4008))
- [Console] Migrate `/lib/autocomplete/` module to TypeScript ([#4148](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/4148))
- [Console] Migrate `/lib/!autocomplete/` module to TypeScript ([#4150](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/4150))
- [Dashboard] Restructure the `Dashboard` plugin folder to be more cohesive with the project ([#4575](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/4575))

### 🔩 Tests
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import {

import { populateContext } from '../../autocomplete/engine';
import { PartialAutoCompleteContext } from '../components/autocomplete_component';
import { ComponentFactory, ParametrizedComponentFactories } from '../../osd';
import { ComponentFactory, ParametrizedComponentFactories } from '../types';

describe('Url autocomplete', () => {
function patternsTest(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import {
ConditionalProxy,
GlobalOnlyComponent,
} from './components';
import { ParametrizedComponentFactories } from '../osd/osd';
import { ParametrizedComponentFactories } from './types';
import { AutoCompleteContext, Template, Term } from './types';
import { CoreEditor, Token } from '../../types';
import { MatchResult } from './components/autocomplete_component';
Expand Down Expand Up @@ -265,7 +265,7 @@ function compileParametrizedValue(
if (!componentFactory) {
throw new Error("no factory found for '" + value + "'");
}
let component = componentFactory(value, null, template);
let component = componentFactory(value, null, !!template);
if (!_.isUndefined(template)) {
component = wrapComponentWithDefaults(component, { template });
}
Expand Down Expand Up @@ -345,7 +345,7 @@ export function globalsOnlyAutocompleteComponents() {
export function compileBodyDescription(
endpointId: string,
description: Description,
parametrizedComponentFactories: ParametrizedComponentFactories
parametrizedComponentFactories?: ParametrizedComponentFactories
) {
return compileDescription(
description,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import {

import { FullRequestComponent } from './full_request_component';
import { Endpoint, UrlComponent, UrlObjectComponent } from '../types';
import { ComponentFactory, ParametrizedComponentFactories } from '../../osd/osd';
import { ComponentFactory, ParametrizedComponentFactories } from '../types';

interface MethodData {
rootComponent: SharedComponent;
Expand Down
44 changes: 44 additions & 0 deletions src/plugins/console/public/lib/autocomplete/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@

import { Token, Position, Range } from '../../types';
import { Description } from './body_completer';
import {
FieldAutocompleteComponent,
IdAutocompleteComponent,
IndexAutocompleteComponent,
ListComponent,
TemplateAutocompleteComponent,
TypeAutocompleteComponent,
UsernameAutocompleteComponent,
} from './components';
import { SharedComponent } from './components/shared_component';

export interface UrlObjectComponent {
Expand Down Expand Up @@ -75,3 +84,38 @@ export interface TermObject {
}

export type Term = string | TermObject;

export type IdAutocompleteComponentFactory = (
name: string,
parent: SharedComponent,
multiValued?: boolean
) => IdAutocompleteComponent;

export type ComponentFactory = (
name: string,
parent: SharedComponent | null,
multiValued?: boolean
) => SharedComponent;

export interface ParametrizedComponentFactories {
getComponent: (
name: string,
parent?: SharedComponent | boolean,
provideDefault?: boolean
) => ComponentFactory | undefined;
index?: (name: string, parent: ListComponent) => IndexAutocompleteComponent | undefined;
indices?: (name: string, parent: ListComponent) => IndexAutocompleteComponent | undefined;
type?: (name: string, parent: ListComponent) => TypeAutocompleteComponent;
types?: (name: string, parent: ListComponent) => TypeAutocompleteComponent;
id?: (name: string, parent: SharedComponent) => IdAutocompleteComponent;
transform_id?: (name: string, parent: SharedComponent) => IdAutocompleteComponent;
username?: (name: string, parent: ListComponent) => UsernameAutocompleteComponent;
user?: (name: string, parent: ListComponent) => UsernameAutocompleteComponent;
template?: (name: string, parent: ListComponent) => TemplateAutocompleteComponent;
task_id?: (name: string, parent: SharedComponent) => IdAutocompleteComponent;
ids?: (name: string, parent: SharedComponent) => IdAutocompleteComponent;
fields?: (name: string, parent: ListComponent) => FieldAutocompleteComponent;
field?: (name: string, parent: ListComponent) => FieldAutocompleteComponent;
nodes?: (name: string, parent: SharedComponent) => ListComponent;
node?: (name: string, parent: SharedComponent) => ListComponent;
}
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';
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,37 +69,41 @@ 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,
null,
expectedContext.autoCompleteSet,
!!expectedContext.autoCompleteSet,
osd.getTopLevelUrlCompleteComponents('GET')
);

// 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
Loading