### Start Dev Server with Example Plugins Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/CLAUDE.md Starts the development server with example plugins loaded. ```bash yarn start --run-examples ``` -------------------------------- ### Run OpenSearch Dashboards with Developer Examples Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/DEVELOPER_GUIDE.md Enable developer examples when starting OpenSearch Dashboards to better understand essential plugins and APIs. This command starts the server with examples turned on. ```bash $ yarn start --run-examples ``` -------------------------------- ### Register a Developer Example Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/examples/developer_examples/README.md Use the `developerExamples.register` function within the `setup` contract to add a new example to the developer examples app. Provide details like `appId`, `title`, `description`, `links`, and an `image`. ```typescript setup(core, { developerExamples }) { developerExamples.register({ appId: 'myFooExampleApp', title: 'Foo services', description: `Foo services let you do bar and zed.`, links: [ { label: 'README', href: 'https://github.com/opensearch-project/OpenSearch-Dashboards/tree/main/src/plugins/foo/README.md', iconType: 'logoGithub', target: '_blank', size: 's', }, ], image: img, }); } ``` -------------------------------- ### Plugin Setup and Start Methods Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/core/server/server.api.md Defines the core interface for a plugin, including `setup`, `start`, and optional `stop` methods. These methods are essential for integrating plugins into the OpenSearch Dashboards core. ```typescript setup(core: CoreSetup, plugins: TPluginsSetup): TSetup | Promise; start(core: CoreStart, plugins: TPluginsStart): TStart | Promise; stop?(): void; ``` -------------------------------- ### Plugin Lifecycle Implementation Source: https://context7.com/opensearch-project/opensearch-dashboards/llms.txt Example of a plugin class implementing the `Plugin` interface with `setup` and `start` lifecycle phases. The `setup` phase is for registration, and `start` is for runtime logic. ```typescript import { CoreSetup, CoreStart, Plugin } from '../../src/core/public'; import { DataPublicPluginSetup, DataPublicPluginStart } from '../data/public'; export interface MyPluginSetup { registerThing(name: string): void; } export interface MyPluginStart { getThing(): string; } export class MyPlugin implements Plugin { private thing = ''; public setup(core: CoreSetup, { data }: { data: DataPublicPluginSetup }): MyPluginSetup { // Register the app so it appears in the navigation core.application.register({ id: 'my-app', title: 'My App', async mount(params) { const { renderApp } = await import('./application/my_app'); const [coreStart, depsStart] = await core.getStartServices(); return renderApp(coreStart, depsStart, params); }, }); return { registerThing: (name: string) => { this.thing = name; }, }; } public start(core: CoreStart): MyPluginStart { return { getThing: () => this.thing }; } public stop() {} } ``` -------------------------------- ### Start OpenSearch Snapshot with Security Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/DEVELOPER_GUIDE.md Initiates the OpenSearch snapshot process with the security plugin installed and configured. This command should be run before starting OpenSearch Dashboards. ```bash yarn opensearch snapshot --security ``` -------------------------------- ### Start Test Server and Run Tests Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/test/examples/README.md Use these commands to start the test server and then initiate a test run during development. Ensure the test server is running before starting a test. ```bash # Start the test server (can continue running) node scripts/functional_tests_server.js --config test/examples/config.js ``` ```bash # Start a test run node scripts/functional_test_runner.js --config test/examples/config.js ``` -------------------------------- ### Sync State with URL using OsdUrlStateStorage Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/opensearch_dashboards_utils/docs/state_sync/README.md This example demonstrates how to use `syncState` with `OsdUrlStateStorage` to synchronize a state container's value with the URL. It shows the setup, starting the sync, updating the state, and stopping the sync. The `stateContainer` change is reflected in the URL. ```typescript import { createStateContainer, syncState, createOsdUrlStateStorage, } from 'src/plugins/opensearch_dashboards_utils/public'; const stateContainer = createStateContainer({ count: 0 }); const stateStorage = createOsdUrlStateStorage(); const { start, stop } = syncState({ storageKey: '_a', stateContainer, stateStorage, }); start(); // state container change is synched to state storage // osdUrlStateStorage updates the URL to "/?_a=(count:2)" stateContainer.set({ count: 2 }); stop(); ``` -------------------------------- ### Start Test Server Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/test/plugin_functional/README.md Use this command to start the test server, which can remain running for continuous testing. ```bash # Start the test server (can continue running) node scripts/functional_tests_server.js --config test/plugin_functional/config.ts ``` -------------------------------- ### Install and Bootstrap OpenSearch Dashboards Source: https://context7.com/opensearch-project/opensearch-dashboards/llms.txt Commands to clone the repository, install dependencies, and bootstrap the project for development. Ensure the correct Node.js version is installed using nvm. ```bash git clone git@github.com:opensearch-project/OpenSearch-Dashboards.git cd OpenSearch-Dashboards nvm install npm i -g corepack && corepack install yarn osd bootstrap ``` -------------------------------- ### Build OpenSearch Dashboards with Multiple Dark Themes Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/packages/osd-optimizer/README.md This example starts OpenSearch Dashboards with both v7dark and v8dark themes by listing them in the OSD_OPTIMIZER_THEMES environment variable. ```sh OSD_OPTIMIZER_THEMES=v7dark,v8dark yarn start ``` -------------------------------- ### Integrate Service into Plugin Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/core/CONVENTIONS.md Shows how to instantiate and integrate `MyService` into the main `Plugin` class. The `setup` and `start` methods of the plugin delegate calls to the corresponding methods of `MyService`. ```typescript // my_plugin/public/plugin.ts import { MyService } from './services'; export class Plugin { private readonly myService = new MyService(); public setup() { return { myService: myService.setup(); } } public start() { return { myService: myService.start(); } } } ``` -------------------------------- ### Start OpenSearch Snapshot for Local Development Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/CLAUDE.md Starts an OpenSearch snapshot for local development purposes. ```bash yarn opensearch snapshot ``` -------------------------------- ### Start OpenSearch Dashboards with Enhancements Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/docs/plugins/discover/getting_started_with_discover.md Start OpenSearch Dashboards with Discover 2.0 features enabled using the yarn start:enhancements command. ```bash yarn start:enhancements ``` -------------------------------- ### Build OpenSearch Dashboards with a Single Theme Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/packages/osd-optimizer/README.md Use the OSD_OPTIMIZER_THEMES environment variable to specify which themes to build. This example starts OpenSearch Dashboards with only the v7light theme. ```sh OSD_OPTIMIZER_THEMES=v7light yarn start ``` -------------------------------- ### Implement Plugin Service with Lifecycle Methods Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/core/CONVENTIONS.md Implements a service (`MyService`) with `setup` and `start` methods that mirror the plugin lifecycle. This service uses a `BehaviorSubject` to manage a list of strings. ```typescript // my_plugin/public/services/my_service.ts export class MyService { private readonly strings$ = new BehaviorSubject(); public setup() { return { registerStrings: (newString: string) => this.strings$.next([...this.strings$.value, newString]); } } public start() { this.strings$.complete(); return { strings: this.strings$.value }; } } ``` -------------------------------- ### Register Share Plugin Context Menu Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/share/README.md Examples for registering the share plugin context menu. For legacy plugins, use `npSetup`. For new plugins, ensure 'share' is in `optionalPlugins` in `opensearch_dashboards.json` and access it via `plugins.share` in `setup`. ```typescript // For legacy plugins import { npSetup } from 'ui/new_platform'; npSetup.plugins.share.register(/* same details here */); // For new plugins: first add 'share' to the list of `optionalPlugins` // in your opensearch_dashboards.json file. Then access the plugin directly in `setup`: class MyPlugin { setup(core, plugins) { if (plugins.share) { plugins.share.register(/* same details here. */); } } } ``` -------------------------------- ### Button Action Example Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/docs/plugins/explore/query-panel-actions.md An example of registering a button action that navigates to the monitor creation page, passing the current query string. ```tsx export class ExamplePlugin { public setup( core: CoreSetup, { explore }: ExamplePluginSetupDependencies ) { explore.queryPanelActionsRegistry.register({ id: 'create-monitor', actionType: 'button', // Specify button action order: 1, getIsEnabled: (deps) => deps.resultStatus.status === QueryExecutionStatus.READY, getLabel: () => 'Create monitor', getIcon: () => 'bell', onClick: (deps) => { // Navigate to monitor page with query application.navigateToApp('monitor', { path: `/create?query=${encodeURIComponent(deps.queryInEditor)}` }); } }); } } ``` -------------------------------- ### Start OpenSearch Dashboards with Plugin Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/packages/osd-plugin-generator/README.md Starts the OpenSearch Dashboards server, including the current plugin. You can pass standard arguments for `bin/opensearch-dashboards` to this command. ```sh yarn start --opensearch.hosts http://localhost:9220 ``` -------------------------------- ### Install Dependencies and Set AWS Credentials Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/packages/osd-agents/README.md Install project dependencies and set the AWS region and profile for authentication. ```bash npm install export AWS_REGION=us-west-2 export AWS_PROFILE=default ``` -------------------------------- ### Start OpenSearch Dashboards Dev Server Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/CLAUDE.md Starts the development server. Requires a running OpenSearch instance on localhost:9200. ```bash yarn start ``` -------------------------------- ### Start OpenSearch Dashboards Development Server Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/DEVELOPER_GUIDE.md Use this command to start the OpenSearch Dashboards development server. Ensure the OpenSearch server is running first. ```bash $ yarn start ``` -------------------------------- ### Example Usage of State Management Hooks and Provider Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/opensearch_dashboards_react/public/state_management/README.md A comprehensive example demonstrating the integration of `PluginStoreProvider`, `useAction`, `useSelector`, and `usePluginKeys` in a React application. ```tsx import { PluginStoreProvider, useAction, useSelector, usePluginKeys } from './state_management'; const Counter = () => { const actions = useAction('counterPlugin'); const count = useSelector('counterPlugin', state => state.count); return (
Count: {count}
); }; const PluginList = () => { const pluginKeys = usePluginKeys(); return
    {pluginKeys.map(key =>
  • {key}
  • )}
; }; // In your app root: ``` -------------------------------- ### Install Lighthouse CI for Performance Tests Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/TESTING.md Installs Lighthouse CI as a development dependency for running performance tests locally. ```bash yarn add --dev @lhci/cli ``` -------------------------------- ### OpenSearch Service Setup Interface Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/core/server/server.api.md Defines the setup interface for the OpenSearch service, including legacy client configurations. ```APIDOC ## OpenSearchServiceSetup Interface ### Description This interface represents the setup phase of the OpenSearch service, providing access to configuration and client creation capabilities, including legacy options. ### Properties - `legacy`: An object containing legacy OpenSearch service configurations and client access. - `config$`: An observable stream of the legacy OpenSearch configuration. - `createClient`: A function to create a legacy custom OpenSearch client. - `client`: The legacy OpenSearch cluster client. ``` -------------------------------- ### Run OpenSearch from Tarball Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/DEVELOPER_GUIDE.md Steps to download, install, and run OpenSearch from a tarball distribution. Ensure Java is installed and JAVA_HOME is set. ```bash tar -xvf opensearch--linux-x64.tar.gz ``` ```bash cd opensearch- ``` ```bash ./bin/opensearch ``` -------------------------------- ### Start OpenSearch Dashboards with Security Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/DEVELOPER_GUIDE.md Starts the OpenSearch Dashboards development server with security enabled. Assumes the security-dashboards-plugin is cloned and built. ```bash yarn start:security ``` -------------------------------- ### Example CLI Help Output Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/packages/osd-dev-utils/src/run/README.md This is an example of the help text generated by the `run` function, showing the task description and available options based on the provided configuration. ```sh $ node scripts/my_task # ERROR please provide a single --path flag # # node scripts/my_task.js # # Run my special task # # Options: # --path Required, path to the file to operate on # --verbose, -v Log verbosely # --debug Log debug messages (less than verbose) # --quiet Only log errors # --silent Don't log anything # --help Show this message # ``` -------------------------------- ### Start Test Run Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/test/plugin_functional/README.md Execute this command to initiate a test run using the specified configuration. ```bash # Start a test run node scripts/functional_tests_runner.js --config test/plugin_functional/config.ts ``` -------------------------------- ### Installation APIs Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/core/public/public.api.md APIs related to the installation and setup of OpenSearch Dashboards. ```APIDOC ## Installation APIs ### Description Provides access to various installation-related endpoints. ### Endpoints - `base`: Base path for installation APIs. - `compatibility`: Endpoint for compatibility checks. - `docker`: Endpoint for Docker-related installation. - `dockerSecurity`: Endpoint for Docker security configurations. - `helm`: Endpoint for Helm-based installation. - `tar`: Endpoint for tarball installations. - `ansible`: Endpoint for Ansible-based installations. - `settings`: Endpoint for installation settings. - `plugins`: Endpoint for managing plugins during installation. ``` -------------------------------- ### Define Plugin Interfaces and Class Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/core/CONVENTIONS.md Defines the setup and start interfaces for a plugin, along with its dependencies. The `MyPlugin` class implements the `Plugin` interface, providing `setup`, `start`, and `stop` methods. ```typescript // my_plugin/public/plugin.ts import { CoreSetup, CoreStart, Plugin } from '../../src/core/public'; import { OtherPluginSetup, OtherPluginStart } from '../other_plugin'; import { ThirdPluginSetup, ThirdPluginStart } from '../third_plugin'; export interface MyPluginSetup { registerThing(...); } export interface MyPluginStart { getThing(): Thing; } export interface MyPluginSetupDeps { otherPlugin: OtherPluginSetup; thirdPlugin?: ThirdPluginSetup; // Optional dependency } export interface MyPluginStartDeps { otherPlugin: OtherPluginStart; thirdPlugin?: ThirdPluginStart; // Optional dependency } export class MyPlugin implements Plugin< // All of these types are optional. If your plugin does not expose anything // or depend on other plugins, these can be omitted. MyPluginSetup, MyPluginStart, MyPluginSetupDeps, MyPluginStartDeps, > { public setup(core: CoreSetup, plugins: MyPluginSetupDeps) { // should return a value that matches `MyPluginSetup` } public start(core: CoreStart, plugins: MyPluginStartDeps) { // should return a value that matches `MyPluginStart` } public stop() { ... } } ``` -------------------------------- ### Start Servers and Run Tests Separately Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/scripts/README.md Demonstrates starting servers with one command and then running tests against those servers in a separate terminal, using the same configuration file for both operations. ```sh # Just the servers node scripts/functional_tests_server --config path/to/config ``` ```sh # Just the tests--against the running servers node scripts/functional_test_runner --config path/to/config ``` -------------------------------- ### Get Build Script Help Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/dev/build/README.md Run this command to see all available options for the build script. ```sh node scripts/build --help ``` -------------------------------- ### ApplicationSetup Interface Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/core/public/public.api.md Provides methods for setting up and registering applications during the core initialization phase. ```APIDOC ## ApplicationSetup Interface ### Description Methods available for setting up and registering applications. ### Methods - **register(app: App): void** Registers a new application. - **registerAppUpdater(appUpdater$: Observable): void** Registers an observable for application updates. - **registerMountContext(contextName: T, provider: IContextProvider): void** Registers a mount context provider (deprecated). ``` -------------------------------- ### Message ID Naming Convention Examples Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/packages/osd-i18n/GUIDELINE.md Examples demonstrating the recommended structure for message IDs, starting with a namespace and followed by descriptive segments in camelCase. ```javascript 'osd.management.createIndexPattern.stepTime.options.patternHeader' ``` ```javascript 'common.ui.indexPattern.warningLabel' ``` -------------------------------- ### Example Request for Finding Saved Objects Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/saved_objects/README.md An example of a GET request to the Find Saved Objects API, filtering by type and specifying search fields. ```json GET api/saved_objects/_find?type=index-pattern&search_fields=title ``` -------------------------------- ### IndexPatternsService Class Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/data/server/server.api.md Manages index patterns within OpenSearch Dashboards. Implements Plugin_3 for setup and start phases. The start method provides access to an indexPatternsServiceFactory. ```typescript export class IndexPatternsService implements Plugin_3 { // (undocumented) setup(core: CoreSetup_2): void; // Warning: (ae-forgotten-export) The symbol "IndexPatternsServiceStartDeps" needs to be exported by the entry point index.d.ts // // (undocumented) start(core: CoreStart_2, { fieldFormats, logger }: IndexPatternsServiceStartDeps): { indexPatternsServiceFactory: (opensearchDashboardsRequest: OpenSearchDashboardsRequest_2) => Promise; }; } ``` -------------------------------- ### Running the Optimizer Programmatically Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/packages/osd-optimizer/README.md This example demonstrates how to import and use the `runOptimizer` function and `OptimizerConfig` class to execute the optimizer from your code. It shows how to create a configuration, run the optimizer, and log its state. ```APIDOC ## Running the Optimizer Programmatically To run the optimizer from code, you can import the [`OptimizerConfig`][OptimizerConfig] class and [`runOptimizer`][Optimizer] function. Create an [`OptimizerConfig`][OptimizerConfig] instance by calling it's static `create()` method with some options, then pass it to the [`runOptimizer`][Optimizer] function. `runOptimizer()` returns an observable of update objects, which are summaries of the optimizer state plus an optional `event` property which describes the internal events occurring and may be of use. You can use the [`logOptimizerState()`][LogOptimizerState] helper to write the relevant bits of state to a tooling log or checkout it's implementation to see how the internal events like [`WorkerStdio`][ObserveWorker] and [`WorkerStarted`][ObserveWorker] are used. ### Example Usage ```ts import { runOptimizer, OptimizerConfig, logOptimizerState } from '@osd/optimizer'; import { REPO_ROOT } from '@osd/utils'; import { ToolingLog } from '@osd/dev-utils'; const log = new ToolingLog({ level: 'verbose', writeTo: process.stdout, }) const config = OptimizerConfig.create({ repoRoot: Path.resolve(__dirname, '../../..'), watch: false, dist: true }); await lastValueFrom( runOptimizer(config).pipe(logOptimizerState(log, config)) ); ``` This is essentially what we're doing in [`script/build_opensearch_dashboards_platform_plugins`][Cli] and the new [build system task][BuildTask]. ``` -------------------------------- ### Retrieve Index Pattern Saved Object Example Request Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/saved_objects/README.md Example GET request to retrieve a specific index pattern saved object using its ID. ```http GET api/saved_objects/index-pattern/619cc200-ecd0-11ee-95b1-e7363f9e289d ``` -------------------------------- ### Example Series Configuration Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/packages/osd-ui-shared-deps/flot_charts/API.md Demonstrates how to configure lines and points for data series, including fill options for lines and disabling fill for points. ```javascript var options = { series: { lines: { show: true, fill: true, fillColor: "rgba(255, 255, 255, 0.8)" }, points: { show: true, fill: false } } }; ``` -------------------------------- ### Download Docker Dev Setup Script with Functional Test Flag Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/docs/docker-dev/docker-dev-setup-manual.md Use this command to download and execute the setup script, enabling the functional test environment. ```bash curl -o- https://raw.githubusercontent.com/opensearch-project/OpenSearch-Dashboards/main/dev-tools/install-docker-dev.sh | bash -s -- --ftr ``` -------------------------------- ### Plugin Interface Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/core/server/server.api.md Defines the structure for plugins, including setup, start, and optional stop methods. ```APIDOC ## Plugin Interface ### Description This interface defines the contract for plugins within the Opensearch Dashboards application. Plugins can implement `setup` and `start` methods to integrate with the core application during different lifecycle phases. An optional `stop` method can be provided for cleanup. ### Methods - `setup(core: CoreSetup, plugins: TPluginsSetup): TSetup | Promise`: Called during the setup phase. Receives core services and setup-phase plugins. - `start(core: CoreStart, plugins: TPluginsStart): TStart | Promise`: Called during the start phase. Receives core services and start-phase plugins. - `stop?(): void`: An optional method called when the application is shutting down. ``` -------------------------------- ### Data Server Plugin Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/data/server/server.api.md The main plugin class for the data server, handling setup and start lifecycles. ```APIDOC ## Plugin ### Description Represents the Data Server plugin, managing its setup and start phases. ### Constructor - `constructor(initializerContext: PluginInitializerContext)` - Initializes the plugin with the provided context. ### Setup Method - `setup(core: CoreSetup, { expressions, usageCollection }: DataPluginSetupDependencies): { __enhance: (enhancements: DataEnhancements) => void; search: ISearchSetup; fieldFormats: { register: (customFieldFormat: import("../public").FieldFormatInstanceType) => number; }; }` - Sets up the plugin, providing access to core services and plugin-specific setup functionalities. ### Start Method - `start(core: CoreStart): { fieldFormats: { fieldFormatServiceFactory: (uiSettings: import("../../../core/server").IUiSettingsClient) => Promise; }; indexPatterns: { indexPatternsServiceFactory: (opensearchDashboardsRequest: import("../../../core/server").OpenSearchDashboardsRequest) => Promise; }; search: ISearchStart>; }` - Starts the plugin, making its services available to other plugins. ### Stop Method - `stop(): void` - Cleans up plugin resources when the server stops. ``` -------------------------------- ### ApplicationStart Interface Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/core/public/public.api.md Provides methods for interacting with registered applications after the core has started. ```APIDOC ## ApplicationStart Interface ### Description Methods available for interacting with applications after startup. ### Properties - **applications$**: Observable> - An observable of all registered applications. - **capabilities**: RecursiveReadonly - The capabilities object for the current user. - **currentAppId$**: Observable - An observable of the currently active application ID. ### Methods - **getUrlForApp(appId: string, options?: { path?: string; absolute?: boolean }): string** Generates the URL for a given application. - **navigateToApp(appId: string, options?: NavigateToAppOptions): Promise** Navigates to a specified application. - **navigateToUrl(url: string): Promise** Navigates to a specified URL. - **registerMountContext(contextName: T, provider: IContextProvider): void** Registers a mount context provider (deprecated). ``` -------------------------------- ### Plugin Initializer Export Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/core/CONVENTIONS.md Defines the `plugin` export in `public/index.ts` for initializing a plugin, specifying its setup and start interfaces. ```typescript // my_plugin/public/index.ts import { PluginInitializer } from '../../src/core/public'; import { MyPlugin, MyPluginSetup, MyPluginStart } from './plugin'; export const plugin: PluginInitializer = () => new MyPlugin(); export { MyPluginSetup, MyPluginStart } ``` -------------------------------- ### Clean OpenSearch Dashboards Project Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/DEVELOPER_GUIDE.md Start fresh by cleaning the project before bootstrapping. This removes previously installed dependencies and built artifacts. ```bash $ yarn osd clean ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/docs/plugins/discover/getting_started_with_discover.md Clone the OpenSearch Dashboards repository and change into the directory to begin setup. ```bash git clone https://github.com/opensearch-project/OpenSearch-Dashboards.git cd OpenSearch-Dashboards ``` -------------------------------- ### Data Server Plugin Setup Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/data/server/plugins_data_server.api.md Sets up the Data Server plugin, registering field formats and search strategies. ```APIDOC ## setup ### Description Sets up the Data Server plugin, providing access to field format registration and search capabilities. ### Parameters - **core** (CoreSetup) - The core services provided by OpenSearch Dashboards. - **dependencies** (DataPluginSetupDependencies) - Dependencies for the setup phase, including usage collection. - **usageCollection**: Service for collecting plugin usage data. ### Returns - PluginSetup - An object containing setup interfaces: - **fieldFormats**: Interface for registering custom field formats. - **register**: Function to register a custom field format. - **search**: Interface for search-related operations. - **__LEGACY**: Legacy search interface. - **search**: Function to perform a search using a specified strategy. - **registerSearchStrategyContext**: Function to register a search strategy context. - **registerSearchStrategyProvider**: Function to register a search strategy provider. ``` -------------------------------- ### Commands for APM Topology Package Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/packages/osd-apm-topology/README.md Essential commands for running tests and starting the development server with example applications for the osd-apm-topology package. ```bash # Run tests npx jest --config packages/osd-apm-topology/jest.config.js # Run a single test yarn test:jest packages/osd-apm-topology/src/components/nodes/service_card_node.test.tsx # Start dev server with example app yarn start --run-examples # Then navigate to: http://localhost:5601/app/apmTopologyExample ``` -------------------------------- ### OverlayStart Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/core/public/public.api.md Core service for managing overlays, including modals, flyouts, and banners. ```APIDOC ## OverlayStart Core service for managing overlays. ### Properties - **banners: OverlayBannersStart** - Service for managing overlay banners. ### Methods - **openConfirm(options: ModalConfirmOptions): Promise** - Opens a confirmation modal. - **openFlyout(options: FlyoutOptions): Promise** - Opens a flyout overlay. - **openModal(options: ModalOptions): Promise** - Opens a modal overlay. - **sidecar: OverlaySidecarStart** - Service for managing sidecar overlays. ``` -------------------------------- ### Get Telemetry URL Origin Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/docs/telemetry/telemetry.md Example of how to retrieve the origin of the telemetry URL, which is configured in opensearch_dashboards.yml. It's recommended to call `getTelemetryUrl` before each use. ```javascript const telemetryUrl = await getTelemetryUrl(); > telemetryUrl.origin; // 'https://telemetry.opensearch.org' ``` -------------------------------- ### CapabilitiesSetup Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/core/server/server.api.md Provides methods to set up capabilities, allowing registration of providers and switchers. ```APIDOC ## CapabilitiesSetup ### Description Provides methods to set up capabilities, allowing registration of providers and switchers. ### Methods - `registerProvider(provider: CapabilitiesProvider): void` - Registers a capabilities provider. - `registerSwitcher(switcher: CapabilitiesSwitcher): void` - Registers a capabilities switcher. ``` -------------------------------- ### Install Docker Development Environment Script Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/docs/docker-dev/docker-dev-setup-manual.md Use this command to download and execute the installation script for the Docker development environment. This script creates necessary files like docker-compose.yml and entrypoint.sh. ```bash curl -o- https://raw.githubusercontent.com/opensearch-project/OpenSearch-Dashboards/main/dev-tools/install-docker-dev.sh | bash ``` -------------------------------- ### Boot Functional Test Server with Configuration Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/test/plugin_functional/README.md Boot the functional test server, pointing it to the plugin configuration file to automatically use test environment settings. ```bash node scripts/functional_tests_server --config test/plugin_functional/config.ts ``` -------------------------------- ### Define MyPlugin with Dependencies Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/core/TESTING.md Defines a plugin with required and optional dependencies, exposing an API that utilizes a required dependency. Use this to structure your plugin's setup and start phases. ```typescript // src/plugins/myplugin/public/plugin.ts import { CoreSetup, CoreStart, Plugin } from 'opensearch-dashboards/public'; import { DataPublicPluginSetup, DataPublicPluginStart } from '../../data/public'; import { UsageCollectionSetup } from '../../usage_collection/public'; import { SuggestionsService } from './suggestions'; interface MyPluginSetupDeps { data: DataPublicPluginSetup; usageCollection?: UsageCollectionSetup; } interface MyPluginStartDeps { data: DataPublicPluginStart; } export class MyPlugin implements Plugin { private suggestionsService = new SuggestionsService(); public setup(core: CoreSetup, { data, usageCollection }: MyPluginSetupDeps) { // setup our internal service this.suggestionsService.setup(data); // an example on using an optional dependency that will be tested if (usageCollection) { usageCollection.allowTrackUserAgent(true); } return {}; } public start(core: CoreStart, { data }: MyPluginStartDeps) { const suggestions = this.suggestionsService.start(data); return { getSpecialSuggestions: (query: string) => suggestions.getSuggestions(query), }; } public stop() {} } export type MyPluginSetup = ReturnType; export type MyPluginStart = ReturnType; ``` -------------------------------- ### Setup Node Environment and Load Script Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/packages/osd-dev-utils/src/run/README.md This script sets up the Node.js environment and loads the main task script. It's intended to be executed directly to run the defined task. ```js // scripts/my_task.js require('../src/setup_node_env'); require('../src/dev/my_task/run_my_task'); ``` -------------------------------- ### SearchSource Interface Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/data/public/public.api.md The SearchSource interface provides methods for managing and retrieving search requests, including setting fields, getting request bodies, and handling search start events. ```APIDOC ## Interface: SearchSource ### Description Provides methods for managing and retrieving search requests, including setting fields, getting request bodies, and handling search start events. ### Methods - **getId()**: Returns the ID of the search source. - **getOwnField(field: K)**: Retrieves the value of a specific field from the search source. - **getParent()**: Returns the parent search source, if any. - **getSearchRequestBody()**: Asynchronously retrieves the search request body. - **getSerializedFields()**: Returns the serialized fields of the search source. - **onRequestStart(handler: (searchSource: SearchSource, options?: ISearchOptions) => Promise)**: Registers a handler to be called when a search request starts. - **serialize()**: Serializes the search source into a JSON object. - **setField(field: K, value: SearchSourceFields[K])**: Sets a specific field in the search source. - **setFields(newFields: SearchSourceFields)**: Sets multiple fields in the search source. - **setParent(parent?: ISearchSource, options?: SearchSourceOptions)**: Sets the parent search source. - **setPreferredSearchStrategyId(searchStrategyId: string)**: Sets the preferred search strategy ID. ``` -------------------------------- ### Bulk Get Saved Objects Response Example Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/saved_objects/README.md The response contains a 'saved_objects' array, with each element representing a retrieved saved object, including its attributes, version, and migration information. ```json { "saved_objects": [ { "id": "619cc200-ecd0-11ee-95b1-e7363f9e289d", "type": "index-pattern", "namespaces": [ "default" ], "updated_at": "2024-03-28T06:57:03.008Z", "version": "WzksMl0=", "attributes": { "title": "test*", "fields": "[{\"count\":0,\"name\":\"_id\",\"type\":\"string\",\"scripted\":false,\"searchable\":false,\"aggregatable\":false,\"readFromDocValues\":false},{\"count\":0,\"name\":\"_index\",\"type\":\"string\",\"scripted\":false,\"searchable\":false,\"aggregatable\":false,\"readFromDocValues\":false},{\"count\":0,\"name\":\"_score\",\"type\":\"number\",\"scripted\":false,\"searchable\":false,\"aggregatable\":false,\"readFromDocValues\":false},{\"count\":0,\"name\":\"_source\",\"type\":\"_source\",\"scripted\":false,\"searchable\":false,\"aggregatable\":false,\"readFromDocValues\":false},{\"count\":0,\"name\":\"_type\",\"type\":\"string\",\"scripted\":false,\"searchable\":false,\"aggregatable\":false,\"readFromDocValues\":false}]" }, "references": [ ], "migrationVersion": { "index-pattern": "7.6.0" } }, { "id": "3.0.0", "type": "config", "namespaces": [ "default" ], "updated_at": "2024-03-19T06:11:41.608Z", "version": "WzAsMV0=", "attributes": { "buildNum": 9007199254740991 }, "references": [ ], "migrationVersion": { "config": "7.9.0" } } ] } ``` -------------------------------- ### Search Setup Interface Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/data/server/plugins_data_server.api.md Interface for setting up search capabilities. ```APIDOC ## ISearchSetup ### Description Provides methods for configuring and managing search strategies. ### Properties - **__LEGACY**: { search: (caller: APICaller_2, request: IRequestTypesMap[T], strategyName?: T) => Promise; } - Legacy search interface. - **registerSearchStrategyContext**: (pluginId: symbol, strategyName: TContextName, provider: IContextProvider_2, TContextName>) => void - Registers a context provider for a search strategy. - **registerSearchStrategyProvider**: TRegisterSearchStrategyProvider - Registers a search strategy provider. ``` -------------------------------- ### Accessing and setting dark mode with `useTransitions` Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/opensearch_dashboards_utils/docs/state_containers/react/use_transitions.md Use the `useTransitions` hook to get and set the `isDarkMode` state. This example demonstrates how to read the current dark mode status and provide buttons to toggle it. ```tsx const Demo = () => { const { isDarkMode } = useState(); const { setDarkMode } = useTransitions(); return ( <>
{isDarkMode ? '🌑' : '☀️'}
); }; ``` -------------------------------- ### Render Application Entry Point Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/docs/plugins/explore/explore-plugin-components.md Sets up the React application with necessary providers like context, Redux, and routing. Mounts the application to a specified DOM element. ```typescript export const renderApp = ( { element, history }: AppMountParameters, services: ExploreServices ) => { ReactDOM.render( {/* Routes for different pages */} , element ); }; ``` -------------------------------- ### Implement Saved Object Operations (CRUD) Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/docs/saved_objects/saved_object_repository_factory_design.md Example implementations of core Saved Object operations such as create, get, update, and delete. These methods define the contract for interacting with the chosen storage type. ```typescript async create( type: string, attributes: T, options: SavedObjectsCreateOptions = {} ): Promise> { ... } ``` ```typescript async get( type: string, id: string, options: SavedObjectsBaseOptions = {} ): Promise> { ... } ``` ```typescript async update( type: string, id: string, attributes: Partial, options: SavedObjectsUpdateOptions = {} ): Promise> { ... } ``` ```typescript async deleteFromNamespaces( type: string, id: string, namespaces: string[], options: SavedObjectsDeleteFromNamespacesOptions = {} ): Promise { ... } ``` -------------------------------- ### startServers(configPath: string) Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/packages/osd-test/README.md Starts OpenSearch and OpenSearch Dashboards servers based on a provided configuration file. This method allows users to keep servers running while executing tests separately. ```APIDOC ## startServers ### Description Starts OpenSearch and OpenSearch Dashboards servers based on a provided configuration file. This method allows users to keep servers running while executing tests separately. ### Parameters #### Path Parameters * **configPath** (string) - Required - The absolute path to a configuration file that defines the server setup and test execution. This file should conform to the schema specified [here](https://github.com/opensearch-project/open-search-dashboards/blob/main/src/functional_test_runner/lib/config/schema.js). ### Example ```javascript const test = require('@osd/test'); test.startServers('/path/to/your/config.js'); ``` ``` -------------------------------- ### Bulk Get Saved Objects Request Example Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/saved_objects/README.md Send a POST request with a JSON array of objects, specifying the type and ID of each saved object to retrieve. Optionally, include the 'fields' parameter to specify which attributes to return. ```json POST api/saved_objects/_bulk_get [ { "type": "index-pattern", "id": "619cc200-ecd0-11ee-95b1-e7363f9e289d" }, { "type": "config", "id": "3.0.0" } ] ``` -------------------------------- ### Start OpenSearch Dashboards with Data Sources and Workspaces Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/docs/plugins/discover/getting_started_with_discover.md Start OpenSearch Dashboards with enhancements, data source, and workspace features enabled, along with theme configuration. ```bash yarn start:enhancements \ --data_source.enabled=true \ --workspace.enabled=true \ --home.disableNewThemeModal=false \ --uiSettings.overrides['theme:version']=v9 ``` -------------------------------- ### Retrieve Single Saved Object API Request Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/saved_objects/README.md Example of an HTTP GET request to retrieve a single saved object by its type and ID. Replace placeholders with your OpenSearch host, port, object type, and object ID. ```http GET :/api/saved_objects// ``` -------------------------------- ### Start Dashboards with Security Plugin Source: https://context7.com/opensearch-project/opensearch-dashboards/llms.txt Commands to start OpenSearch Dashboards with the security plugin enabled. This requires starting a local OpenSearch snapshot with security enabled first. ```bash yarn opensearch snapshot --security yarn start:security ``` -------------------------------- ### Start Dashboards with Explore Experience Source: https://context7.com/opensearch-project/opensearch-dashboards/llms.txt Command to start the OpenSearch Dashboards development server with the new Explore experience enabled, which includes multi-datasource, workspaces, and PPL/SQL support. ```bash yarn start:explore ``` -------------------------------- ### Data Plugin Start Interface Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/data/server/server.api.md Defines the structure of the start contract for the Data plugin. ```APIDOC ## PluginStart ### Description Interface representing the start phase of the Data plugin. ### Properties - `fieldFormats` (FieldFormatsStart): Start contract for field formats. - `indexPatterns` (IndexPatternsServiceStart): Start contract for index patterns service. - `search` (ISearchStart): Start contract for search functionalities. ``` -------------------------------- ### Button Action Example Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/docs/plugins/explore/query-panel-actions.md An example demonstrating how to register a button action that navigates to another application page, passing the current query as a URL parameter. ```APIDOC ## Button Action Example ```tsx export class ExamplePlugin { public setup( core: CoreSetup, { explore }: ExamplePluginSetupDependencies ) { explore.queryPanelActionsRegistry.register({ id: 'create-monitor', actionType: 'button', // Specify button action order: 1, getIsEnabled: (deps) => deps.resultStatus.status === QueryExecutionStatus.READY, getLabel: () => 'Create monitor', getIcon: () => 'bell', onClick: (deps) => { // Navigate to monitor page with query application.navigateToApp('monitor', { path: `/create?query=${encodeURIComponent(deps.queryInEditor)}` }); } }); } } ``` ``` -------------------------------- ### Initialize OsdUrlStateStorage Service Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/opensearch_dashboards_utils/docs/global_data_persistence.md Set up the `osdUrlStateStorage` service by calling `createOsdUrlStateStorage`. This service is crucial for initializing the global storage mechanism, indicated by the '_g' flag, and synchronizing state with the URL. ```typescript const services: VisBuilderServices = { ...coreStart, history: params.history, osdUrlStateStorage: createOsdUrlStateStorage({ history: params.history, useHash: coreStart.uiSettings.get('state:storeInSessionStorage'), ...withNotifyOnErrors(coreStart.notifications.toasts), }), ... ``` -------------------------------- ### SQL Query Example Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/plugins/query_enhancements/README.md An example of a SQL query for retrieving and aggregating data from an index. ```sql SELECT category, SUM(price) FROM my_index WHERE count > 100 GROUP BY category ``` -------------------------------- ### CoreSetup Interface Source: https://github.com/opensearch-project/opensearch-dashboards/blob/main/src/core/public/public.api.md Setup interface for the core OpenSearch Dashboards services. ```APIDOC ## CoreSetup Interface ### Description Setup interface for the core OpenSearch Dashboards services, including application, notifications, and UI settings. ### Properties - **application**: ApplicationSetup; - Setup interface for the application service. - **context**: ContextSetup; - Setup interface for context management (deprecated). - **fatalErrors**: FatalErrorsSetup; - Setup interface for fatal error handling. - **getStartServices**: StartServicesAccessor; - Accessor function to get start services from plugins. - **http**: HttpSetup; - Setup interface for the HTTP service. - **injectedMetadata**: { getInjectedVar: (name: string, defaultValue?: any) => unknown; }; - Interface for accessing injected metadata (deprecated). - **notifications**: NotificationsSetup; - Setup interface for the notifications service. - **uiSettings**: IUiSettingsClient; - Client interface for UI settings. ```