# API Connect Explorer

## Contents

- [Getting Started](#gettingstarted)
- [Configuration](#configuration)
- [Usage in React](#useageinreact)
- [Usage outside of React](#UsageoutsideofReact)
- [Changing Configuration](#ChangingConfiguration)
- [Running Unit Tests](#RunningUnitTests)
- [Running E2E Tests](RunningE2ETests)
  - [Accessibility](#Accessibility)

## Getting Started

To get up and running:

```shell
npm install
npm start
```

This will install, build, and then run the API Explorer.

## Configuration

API Connect Explorer can be configured either via passing props (if the consuming application is React), or by a global variable `apiConnectExplorer`:

Regardless of how the Explorer is attached, the following options may be set.

### Required

```js
apis: [<array_of_OpenAPI_files_as_json>] // required
```

### Optional

```js
encodedApis: [<array_of__base64_encoded_OpenAPI_files_as_json>] 
apps: [{
  name: string,
  description,
  redirectUri: string,
  credentials: [{
    id: string,
    description: string
  }]
}]
```

```js
options: {
  fixedCredentials: {
    clientId: string,
    clientSecret: string
  }, // optional
  menuView: 'tags' | 'operations', // defaults to operations
  nestedTags: boolean, // defaults to false
  groupByTags: boolean, // defaults to false
  tryIt: boolean, //defaults to true
  languages: string[], // defaults to curl, ruby, python, php, java, node, go and swift
  defaultLanguage: string, // defaults to the first in the language array
  apiMaxDepth: integer // defaults to 9
  showSwaggerDownload : boolean // defaults to true 
  showAsyncApiDownload : boolean // defaults to true
  showSoapCodeSnippets: boolean, // defaults to true
  showSoapSwaggerDownload: boolean, // defaults to true
  showApiVersion: boolean, // defaults to true
  showCorsWarnings: boolean, // defaults to true
  showMTLSHeader: boolean, //defaults to true
  optimiseOauthUX: boolean, // defaults to false
  apiImageUrl: string, // optional
  loginLink: string, // optional
  loggedIn: boolean, // optional
  deferBootstrap: boolean, // optional
  proxyUrl: string, // optional
  infoSectionEntries: InfoSectionEntry[][], // optional
  renderSchemaView: boolean, // defaults to false
  onReady: func | string, // optional
  enableToggleInteract: boolean, // defaults to false
  showInteract: boolean, // defaults to true,
  locale: string, // locale code to override localization
  validateSwagger: boolean, // defaults to true
  headerActive: boolean, //defaults to false
  certificateStripPrefix: boolean, // defaults to false
  certificateStripNewlines: boolean, // defaults to false,
  apiTypeDocs: {apitype: '<link to doc>'} // defaults to {}. current api types are "mq", "kafka", and "asyncapi" 
}

```

`encodedApis` : an array of base64 encoded openAPI files as json.  If provided, these override the apis included in `apis` 

`apps`: an array of applications defining credentials and redirect URIs. If provided, they will be represented as a selectable option to the user to save entering details in each operation.

`fixedCredentials`: provide a `clientId` and / or a `clientSecret` up-front, and prevent the relevant inputs being rendered

`menuView`: a choice of `'tags'` or `'operations'` - the left hand menu will either group operations by tag, or render them as a simple list in the order in which they are defined in the OpenAPI document.

`nestedTags`: if `menuView` is set to `'tags'`, setting this option to true will cause the array of operation tags to be treated as a nested heirarchy. An operation tagged with `['one', 'two', 'three']` will be rendered `one -> two -> three`. Set to false, the operation would appear in each tag category `one`, `two`, and `three`.

`groupByTags`: when set to true, if an API has tags the operations will be shown by default grouped according to tag.  default is false.

`tryIt`: controls whether or not to show the inline test tool

`languages`: an array of languages for which to generate code samples. Supported languages are `curl`, `ruby`, `python`, `php`, `java`, `node`, `go`, `swift`, `c`, and `csharp`.

`defaultLanguage`: default code language to display

`apiMaxDepth` : configurable max depth limit for definition examples, defaults to 9, min value 2, max value 25

`showSwaggerDownload` : show swagger/OAI download for any type of API

`showAsyncApiDownload` : show download for AsyncAPIs

`showSoapCodeSnippets`: show code snippets for SOAP APIs

`showSoapSwaggerDownload`: show swagger download for SOAP APIs

`showApiVersion`: shows the version number for an API

`showCorsWarnings`: shows warnings when CORS errors are suspected

`showMTLSHeader`: shows application certificate in header

`optimiseOauthUX`: removes specific redirect fields of an api secured by Implicit or Authorization Code oAuth API

`apiImageUrl`: URL for an image that represents the API

`loginLink`: if users are required to log in to your system in order to access their client credentials, specify the login link here. it will then be displayed prominently above the credentials section if the user is not logged in.

`loggedIn`: set this to true if the user is logged in and any provided login link should be suppressed.

`deferBootstrap`: prevent automatic bootstrapping by angular. Bootstrapping will need to be carried out by the application.

`proxyUrl`: set this to the relative URL of a proxy service. The test tool will invoke the service with a body which follows this structure:

`validateSwagger`: true by default. Set to false to disable validation of swagger documents against the swagger specification.

`headerActive`: false by default. Set to true to view a simple header above your apis

`certificateStripPrefix`: false by default.  Strip whitespace from the certificates before use in the "try it" tool.

`certificateStripNewlines`: false by default. Remove the prefix and suffix (`-----BEGIN CERTIFICATE-----` and `-----END CERTIFICATE-----`) from the certificates before use in the "try it" tool.

## Usage in React

When integrating into a React-based application, render the API Explorer in your React component like this:

```js
import React from 'react';
import ApiExplorer from 'apiconnect-explorer';

class MyComponent extends React.Component {
  render() {
    return <ApiExplorer apis={apis} apps={apps} options={options} />
  }
}
```

**Important note**: Internally, `apiconnect-explorer` consists mainly of JavaScript modules. However, it also `import`s/`require`s CSS and SCSS stylesheets and SVG images.

```js
import '../css/main.scss';
```

These imports are intentionally left unaltered, to provide flexibility for downstream consumers. It is assumed that `apiconnect-explorer` is being consumed as part of a larger application with an overall webpack build or similar. To consume `apiconnect-explorer`, ensure suitable loaders like `sass-loader` and `file-loader` are part of your webpack configuration.

## Usage outside of React

The API Explorer can be instantiated within any page by loading the pre-compiled JS bundles via `<script>` tags.

Currently, only one JS file must be included, as follows:

```html
<script src="dist/static/js/main.<hash>.js"></script>
```

*Further work will be done to make this a bit more consumable (e.g. standardizing the bundle name, etc). Also, the bundle **is**
fully PWA-enabled (and includes a service worker to enable offline-usage and faster startup on second load); however, none of these
aspects are required for "normal" operation. In the future, a second service worker may be extracted for better load times across
the board.*

Next, simply populate the global `apiConnectExplorer` object using the options identified above. An `attachPoint` property may also be set to control where the Explorer is injected.

This is how the `apiConnectExplorer` object would be formatted:

```js
window.apiConnectExplorer = {
  attachPoint: string | DOMNode, // defaults to 'apiconnect-explorer',instantiating outside of React.
  apis, // required
  apps, // optional
  options, // optional
  docs //optional
}
```

## Detailed description of options

`fixedCredentials`: provide a `clientId` and / or a `clientSecret` up-front, and prevent the relevant inputs being rendered

`authentication`: provide a default `username` and / or `password` up-front.

`apps`: an array of applications defining credentials and redirect URIs. If provided, they will be represented as a selectable option to the user to save entering details in each operation.

`menuView`: a choice of `'tags'` or `'operations'` - the left hand menu will either group operations by tag, or render them as a simple list in the order in which they are defined in the OpenAPI document.

`nestedTags`: if `menuView` is set to `'tags'`, setting this option to true will cause the array of operation tags to be treated as a nested heirarchy. An operation tagged with `['one', 'two', 'three']` will be rendered `one -> two -> three`. Set to false, the operation would appear in each tag category `one`, `two`, and `three`.

`tryIt`: controls whether or not to show the inline test tool

`languages`: an array of languages for which to generate code samples. Supported languages are `curl`, `ruby`, `python`, `php`, `java`, `node`, `go`, `swift`, `c`, and `csharp`.

`defaultLanguage`: default code language to display

`showSwaggerDownload` : show swagger/OAI download for any type of API

`showAsyncApiDownload` : show download for AsyncAPIs

`showSoapCodeSnippets`: show code snippets for SOAP APIs

`showSoapSwaggerDownload`: show swagger download for SOAP APIs

`showApiVersion`: shows the version number for an API

`showCorsWarnings`: shows warnings when CORS errors are suspected

`apiImageUrl`: URL for an image that represents the API

`loginLink`: if users are required to log in to your system in order to access their client credentials, specify the login link here. it will then be displayed prominently above the credentials section if the user is not logged in.

`loggedIn`: set this to true if the user is logged in and any provided login link should be suppressed.

`deferBootstrap`: prevent automatic bootstrapping by angular. Bootstrapping will need to be carried out by the application.

`proxyUrl`: set this to the relative URL of a reverse proxy service. The test tool will invoke the service with a body which follows this structure:

```js
{
  method: 'PUT',
  url: 'https://somewhere?query=true',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: '{"foo":"bar"}'
}
```

The `body` property is not required if the request does not have a body.

The proxy should just pass any response (success or error) straight through, unmodified. To avoid a cross origin request the proxyUrl should be a relative URL to where a proxy service is running.

`infoSectionEntries`: set this if you want optional sections in the information area of the APIs. Set this to an array with the same length as
apis. Each entry is an array of objects of type InfoSectionEntry, to render for the API which is in the apis array at the same index, or null if no info sections are needed for the API.

The InfoSectionEntry is a simple object with 3 properties: class (string) - the class to put on the section div, html (string) - the HTML to put into the section div, location (string either "DOCUMENTATION" or "INTERACTION", default to "DOCUMENTATION") - which side to put the section in. The HTML will be placed as provided into the page. The documentation section is the first section where the API name and description is, the section will be added below the other information. The interaction section is the second section where the test tool lives, the section will be added at the top of this section.

`renderSchemaView`: set this to true to render an interactive view of the definitions section. Set this to false to render the JSON of the definitions with color highlights. The default is false which is the old behavior.

`onReady`: provide a function to call when the explorer has rendered itself into the DOM. Alternatively accepts a string representing the name of a global function attached to window object.

`documentationEntries`: set this if you want optional documentation links in the operations navigator for the APIs. Clicking the link will open a modal dialog which loads the content of the URL and shows it, assuming the contents of the URL is a HTML document. Set this to an array with the same length as
apis. Each entry is an array of objects of type DocumentationEntry, to render for the API which is in the apis array at the same index, or null if no documentation entries are needed for the API.

The DocumentationEntry is a simple object with 3 properties: url (string) - the url to load into the dialog (should be relative), title (string) - the title to put into the operations navigator and at the top of the dialog, extractPortalContent - boolean whether to attempt to extract the element with class "apicMainContent", or just extract the contents of the body, for the loaded content.

`interactExpanded`: set this to false to hide the interact section by default. By default the section is shown. This flag sets the initial visibility of the interact section, the user can use the control to toggle the interact section. The interact section contains the Examples and Try It sections.

`locale` : set this to override the interface language. If not set, the language used will be based on the Accept-language header as specified by the browser. If the locale code selected doesn't match with one of the available localizations, the UI will display in English.

`routerType` : set this to change the router type. If not set, the router type will default to using a MemoryRouter. Available options are 'hash' and 'memory'.

## Changing Configuration

Configuration can be modified at any time.

If the API Explorer is instantiated using React, simply changing the passed props will cause an update to occur.

If instantiation is handled outside of React and the configuration is specified using the `apiConnectExplorer` global, a manual event trigger is required to notify the Explorer that it should re-read the config object and trigger an update.

```js
dispatchEvent(new Event('apiConnectExplorerUpdate'));
```

## Running Unit Tests

`npm run test` will run all unit tests for this project using a jest runner.

## Running E2E Tests

`npm run cypress` will run all e2e tests for this project using a cypress runner. You will manually need to run the app at the same time.

`npm run cypress:open` will run cypress in open mode so you can watch the browser. This is helpful for writing and debugging e2e tests. You will manually need to run the app at the same time.

`npm run test:e2e` will start up a server that hosts `dist/app` and then runs `cypress`. This is designed for use on CI where it has just built the app.

### Accessibility

E2E tests should call `cy.customA11y()` when viewing a new page (or when changes are made to a page). If these tests fail, it will print out a formatted table in the terminal with all the errors. For help with debugging these errors. You can run `npm run cypress:open -- --env CY_A11Y_DEBUG=true` and a red border will be added to any element that has a violation.
